Correction to commmit 120863, make sure proper destructor function is called as well...
[asterisk-bristuff.git] / channels / chan_sip.c
blob278528c8049fda8effb2ae797ce8a8adffbe577e
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, TCP and TLS support
29 * Configuration file \link Config_sip sip.conf \endlink
32 * \todo SIP over TCP
33 * \todo SIP over TLS
34 * \todo Better support of forking
35 * \todo VIA branch tag transaction checking
36 * \todo Transaction support
38 * \ingroup channel_drivers
40 * \par Overview of the handling of SIP sessions
41 * The SIP channel handles several types of SIP sessions, or dialogs,
42 * not all of them being "telephone calls".
43 * - Incoming calls that will be sent to the PBX core
44 * - Outgoing calls, generated by the PBX
45 * - SIP subscriptions and notifications of states and voicemail messages
46 * - SIP registrations, both inbound and outbound
47 * - SIP peer management (peerpoke, OPTIONS)
48 * - SIP text messages
50 * In the SIP channel, there's a list of active SIP dialogs, which includes
51 * all of these when they are active. "sip show channels" in the CLI will
52 * show most of these, excluding subscriptions which are shown by
53 * "sip show subscriptions"
55 * \par incoming packets
56 * Incoming packets are received in the monitoring thread, then handled by
57 * sipsock_read(). This function parses the packet and matches an existing
58 * dialog or starts a new SIP dialog.
60 * sipsock_read sends the packet to handle_request(), that parses a bit more.
61 * if it's a response to an outbound request, it's sent to handle_response().
62 * If it is a request, handle_request sends it to one of a list of functions
63 * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
64 * sipsock_read locks the ast_channel if it exists (an active call) and
65 * unlocks it after we have processed the SIP message.
67 * A new INVITE is sent to handle_request_invite(), that will end up
68 * starting a new channel in the PBX, the new channel after that executing
69 * in a separate channel thread. This is an incoming "call".
70 * When the call is answered, either by a bridged channel or the PBX itself
71 * the sip_answer() function is called.
73 * The actual media - Video or Audio - is mostly handled by the RTP subsystem
74 * in rtp.c
76 * \par Outbound calls
77 * Outbound calls are set up by the PBX through the sip_request_call()
78 * function. After that, they are activated by sip_call().
80 * \par Hanging up
81 * The PBX issues a hangup on both incoming and outgoing calls through
82 * the sip_hangup() function
84 * \par Deprecated stuff
85 * This is deprecated and will be removed after the 1.4 release
86 * - the SIPUSERAGENT dialplan variable
87 * - the ALERT_INFO dialplan variable
90 /*** MODULEINFO
91 <depend>res_features</depend>
92 ***/
95 #include "asterisk.h"
97 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
99 #include <stdio.h>
100 #include <ctype.h>
101 #include <string.h>
102 #include <unistd.h>
103 #include <sys/socket.h>
104 #include <sys/ioctl.h>
105 #include <net/if.h>
106 #include <errno.h>
107 #include <stdlib.h>
108 #include <fcntl.h>
109 #include <netdb.h>
110 #include <signal.h>
111 #include <sys/signal.h>
112 #include <netinet/in.h>
113 #include <netinet/in_systm.h>
114 #include <arpa/inet.h>
115 #include <netinet/ip.h>
116 #include <regex.h>
118 #include "asterisk/lock.h"
119 #include "asterisk/channel.h"
120 #include "asterisk/config.h"
121 #include "asterisk/logger.h"
122 #include "asterisk/module.h"
123 #include "asterisk/pbx.h"
124 #include "asterisk/options.h"
125 #include "asterisk/sched.h"
126 #include "asterisk/io.h"
127 #include "asterisk/rtp.h"
128 #include "asterisk/udptl.h"
129 #include "asterisk/acl.h"
130 #include "asterisk/manager.h"
131 #include "asterisk/callerid.h"
132 #include "asterisk/cli.h"
133 #include "asterisk/app.h"
134 #include "asterisk/musiconhold.h"
135 #include "asterisk/dsp.h"
136 #include "asterisk/features.h"
137 #include "asterisk/srv.h"
138 #include "asterisk/astdb.h"
139 #include "asterisk/causes.h"
140 #include "asterisk/utils.h"
141 #include "asterisk/file.h"
142 #include "asterisk/astobj.h"
143 #include "asterisk/devicestate.h"
144 #include "asterisk/linkedlists.h"
145 #include "asterisk/stringfields.h"
146 #include "asterisk/monitor.h"
147 #include "asterisk/localtime.h"
148 #include "asterisk/abstract_jb.h"
149 #include "asterisk/compiler.h"
150 #include "asterisk/threadstorage.h"
151 #include "asterisk/translate.h"
153 #ifndef FALSE
154 #define FALSE 0
155 #endif
157 #ifndef TRUE
158 #define TRUE 1
159 #endif
161 #define SIPBUFSIZE 512
163 #define XMIT_ERROR -2
165 #define VIDEO_CODEC_MASK 0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
166 #ifndef IPTOS_MINCOST
167 #define IPTOS_MINCOST 0x02
168 #endif
170 /* #define VOCAL_DATA_HACK */
172 #define DEFAULT_DEFAULT_EXPIRY 120
173 #define DEFAULT_MIN_EXPIRY 60
174 #define DEFAULT_MAX_EXPIRY 3600
175 #define DEFAULT_REGISTRATION_TIMEOUT 20
176 #define DEFAULT_MAX_FORWARDS "70"
178 /* guard limit must be larger than guard secs */
179 /* guard min must be < 1000, and should be >= 250 */
180 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
181 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
182 EXPIRY_GUARD_SECS */
183 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
184 GUARD_PCT turns out to be lower than this, it
185 will use this time instead.
186 This is in milliseconds. */
187 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
188 below EXPIRY_GUARD_LIMIT */
189 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
191 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
192 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
193 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
194 static int expiry = DEFAULT_EXPIRY;
196 #ifndef MAX
197 #define MAX(a,b) ((a) > (b) ? (a) : (b))
198 #endif
200 #define CALLERID_UNKNOWN "Unknown"
202 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
203 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
204 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
206 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
207 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
208 #define SIP_TRANS_TIMEOUT 32000 /*!< SIP request timeout (rfc 3261) 64*T1
209 \todo Use known T1 for timeout (peerpoke)
211 #define DEFAULT_TRANS_TIMEOUT -1 /* Use default SIP transaction timeout */
212 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
214 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
215 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
216 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
218 #define SDP_MAX_RTPMAP_CODECS 32 /*!< Maximum number of codecs allowed in received SDP */
220 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
222 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
223 static struct ast_jb_conf default_jbconf =
225 .flags = 0,
226 .max_size = -1,
227 .resync_threshold = -1,
228 .impl = ""
230 static struct ast_jb_conf global_jbconf;
232 static const char config[] = "sip.conf";
233 static const char notify_config[] = "sip_notify.conf";
235 #define RTP 1
236 #define NO_RTP 0
238 /*! \brief Authorization scheme for call transfers
239 \note Not a bitfield flag, since there are plans for other modes,
240 like "only allow transfers for authenticated devices" */
241 enum transfermodes {
242 TRANSFER_OPENFORALL, /*!< Allow all SIP transfers */
243 TRANSFER_CLOSED, /*!< Allow no SIP transfers */
247 enum sip_result {
248 AST_SUCCESS = 0,
249 AST_FAILURE = -1,
252 /*! \brief States for the INVITE transaction, not the dialog
253 \note this is for the INVITE that sets up the dialog
255 enum invitestates {
256 INV_NONE = 0, /*!< No state at all, maybe not an INVITE dialog */
257 INV_CALLING = 1, /*!< Invite sent, no answer */
258 INV_PROCEEDING = 2, /*!< We got/sent 1xx message */
259 INV_EARLY_MEDIA = 3, /*!< We got 18x message with to-tag back */
260 INV_COMPLETED = 4, /*!< Got final response with error. Wait for ACK, then CONFIRMED */
261 INV_CONFIRMED = 5, /*!< Confirmed response - we've got an ack (Incoming calls only) */
262 INV_TERMINATED = 6, /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done
263 The only way out of this is a BYE from one side */
264 INV_CANCELLED = 7, /*!< Transaction cancelled by client or server in non-terminated state */
267 /* Do _NOT_ make any changes to this enum, or the array following it;
268 if you think you are doing the right thing, you are probably
269 not doing the right thing. If you think there are changes
270 needed, get someone else to review them first _before_
271 submitting a patch. If these two lists do not match properly
272 bad things will happen.
275 enum xmittype {
276 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
277 If it fails, it's critical and will cause a teardown of the session */
278 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
279 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
282 enum parse_register_result {
283 PARSE_REGISTER_FAILED,
284 PARSE_REGISTER_UPDATE,
285 PARSE_REGISTER_QUERY,
288 enum subscriptiontype {
289 NONE = 0,
290 XPIDF_XML,
291 DIALOG_INFO_XML,
292 CPIM_PIDF_XML,
293 PIDF_XML,
294 MWI_NOTIFICATION
297 static const struct cfsubscription_types {
298 enum subscriptiontype type;
299 const char * const event;
300 const char * const mediatype;
301 const char * const text;
302 } subscription_types[] = {
303 { NONE, "-", "unknown", "unknown" },
304 /* RFC 4235: SIP Dialog event package */
305 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
306 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
307 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
308 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
309 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
312 /*! \brief SIP Request methods known by Asterisk */
313 enum sipmethod {
314 SIP_UNKNOWN, /* Unknown response */
315 SIP_RESPONSE, /* Not request, response to outbound request */
316 SIP_REGISTER,
317 SIP_OPTIONS,
318 SIP_NOTIFY,
319 SIP_INVITE,
320 SIP_ACK,
321 SIP_PRACK, /* Not supported at all */
322 SIP_BYE,
323 SIP_REFER,
324 SIP_SUBSCRIBE,
325 SIP_MESSAGE,
326 SIP_UPDATE, /* We can send UPDATE; but not accept it */
327 SIP_INFO,
328 SIP_CANCEL,
329 SIP_PUBLISH, /* Not supported at all */
330 SIP_PING, /* Not supported at all, no standard but still implemented out there */
333 /*! \brief Authentication types - proxy or www authentication
334 \note Endpoints, like Asterisk, should always use WWW authentication to
335 allow multiple authentications in the same call - to the proxy and
336 to the end point.
338 enum sip_auth_type {
339 PROXY_AUTH,
340 WWW_AUTH,
343 /*! \brief Authentication result from check_auth* functions */
344 enum check_auth_result {
345 AUTH_SUCCESSFUL = 0,
346 AUTH_CHALLENGE_SENT = 1,
347 AUTH_SECRET_FAILED = -1,
348 AUTH_USERNAME_MISMATCH = -2,
349 AUTH_NOT_FOUND = -3,
350 AUTH_FAKE_AUTH = -4,
351 AUTH_UNKNOWN_DOMAIN = -5,
352 AUTH_PEER_NOT_DYNAMIC = -6,
353 AUTH_ACL_FAILED = -7,
356 /*! \brief States for outbound registrations (with register= lines in sip.conf */
357 enum sipregistrystate {
358 REG_STATE_UNREGISTERED = 0, /*!< We are not registred */
359 REG_STATE_REGSENT, /*!< Registration request sent */
360 REG_STATE_AUTHSENT, /*!< We have tried to authenticate */
361 REG_STATE_REGISTERED, /*!< Registred and done */
362 REG_STATE_REJECTED, /*!< Registration rejected */
363 REG_STATE_TIMEOUT, /*!< Registration timed out */
364 REG_STATE_NOAUTH, /*!< We have no accepted credentials */
365 REG_STATE_FAILED, /*!< Registration failed after several tries */
368 #define CAN_NOT_CREATE_DIALOG 0
369 #define CAN_CREATE_DIALOG 1
370 #define CAN_CREATE_DIALOG_UNSUPPORTED_METHOD 2
372 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
373 static const struct cfsip_methods {
374 enum sipmethod id;
375 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
376 char * const text;
377 int can_create;
378 } sip_methods[] = {
379 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
380 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
381 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
382 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
383 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
384 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
385 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
386 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
387 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
388 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
389 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
390 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
391 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
392 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
393 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
394 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
395 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
398 /*! Define SIP option tags, used in Require: and Supported: headers
399 We need to be aware of these properties in the phones to use
400 the replace: header. We should not do that without knowing
401 that the other end supports it...
402 This is nothing we can configure, we learn by the dialog
403 Supported: header on the REGISTER (peer) or the INVITE
404 (other devices)
405 We are not using many of these today, but will in the future.
406 This is documented in RFC 3261
408 #define SUPPORTED 1
409 #define NOT_SUPPORTED 0
411 #define SIP_OPT_REPLACES (1 << 0)
412 #define SIP_OPT_100REL (1 << 1)
413 #define SIP_OPT_TIMER (1 << 2)
414 #define SIP_OPT_EARLY_SESSION (1 << 3)
415 #define SIP_OPT_JOIN (1 << 4)
416 #define SIP_OPT_PATH (1 << 5)
417 #define SIP_OPT_PREF (1 << 6)
418 #define SIP_OPT_PRECONDITION (1 << 7)
419 #define SIP_OPT_PRIVACY (1 << 8)
420 #define SIP_OPT_SDP_ANAT (1 << 9)
421 #define SIP_OPT_SEC_AGREE (1 << 10)
422 #define SIP_OPT_EVENTLIST (1 << 11)
423 #define SIP_OPT_GRUU (1 << 12)
424 #define SIP_OPT_TARGET_DIALOG (1 << 13)
425 #define SIP_OPT_NOREFERSUB (1 << 14)
426 #define SIP_OPT_HISTINFO (1 << 15)
427 #define SIP_OPT_RESPRIORITY (1 << 16)
429 /*! \brief List of well-known SIP options. If we get this in a require,
430 we should check the list and answer accordingly. */
431 static const struct cfsip_options {
432 int id; /*!< Bitmap ID */
433 int supported; /*!< Supported by Asterisk ? */
434 char * const text; /*!< Text id, as in standard */
435 } sip_options[] = { /* XXX used in 3 places */
436 /* RFC3891: Replaces: header for transfer */
437 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
438 /* One version of Polycom firmware has the wrong label */
439 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
440 /* RFC3262: PRACK 100% reliability */
441 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
442 /* RFC4028: SIP Session Timers */
443 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
444 /* RFC3959: SIP Early session support */
445 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
446 /* RFC3911: SIP Join header support */
447 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
448 /* RFC3327: Path support */
449 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
450 /* RFC3840: Callee preferences */
451 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
452 /* RFC3312: Precondition support */
453 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
454 /* RFC3323: Privacy with proxies*/
455 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
456 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
457 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
458 /* RFC3329: Security agreement mechanism */
459 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
460 /* SIMPLE events: RFC4662 */
461 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
462 /* GRUU: Globally Routable User Agent URI's */
463 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
464 /* RFC4538: Target-dialog */
465 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
466 /* Disable the REFER subscription, RFC 4488 */
467 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
468 /* ietf-sip-history-info-06.txt */
469 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
470 /* ietf-sip-resource-priority-10.txt */
471 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
475 /*! \brief SIP Methods we support */
476 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
478 /*! \brief SIP Extensions we support */
479 #define SUPPORTED_EXTENSIONS "replaces"
481 /*! \brief Standard SIP port from RFC 3261. DO NOT CHANGE THIS */
482 #define STANDARD_SIP_PORT 5060
483 /* Note: in many SIP headers, absence of a port number implies port 5060,
484 * and this is why we cannot change the above constant.
485 * There is a limited number of places in asterisk where we could,
486 * in principle, use a different "default" port number, but
487 * we do not support this feature at the moment.
490 /* Default values, set and reset in reload_config before reading configuration */
491 /* These are default values in the source. There are other recommended values in the
492 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
493 yet encouraging new behaviour on new installations
495 #define DEFAULT_CONTEXT "default"
496 #define DEFAULT_MOHINTERPRET "default"
497 #define DEFAULT_MOHSUGGEST ""
498 #define DEFAULT_VMEXTEN "asterisk"
499 #define DEFAULT_CALLERID "asterisk"
500 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
501 #define DEFAULT_MWITIME 10
502 #define DEFAULT_ALLOWGUEST TRUE
503 #define DEFAULT_SRVLOOKUP TRUE /*!< Recommended setting is ON */
504 #define DEFAULT_COMPACTHEADERS FALSE
505 #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. */
506 #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. */
507 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
508 #define DEFAULT_ALLOW_EXT_DOM TRUE
509 #define DEFAULT_REALM "asterisk"
510 #define DEFAULT_NOTIFYRINGING TRUE
511 #define DEFAULT_PEDANTIC FALSE
512 #define DEFAULT_AUTOCREATEPEER FALSE
513 #define DEFAULT_QUALIFY FALSE
514 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
515 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
516 #ifndef DEFAULT_USERAGENT
517 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
518 #endif
521 /* Default setttings are used as a channel setting and as a default when
522 configuring devices */
523 static char default_context[AST_MAX_CONTEXT];
524 static char default_subscribecontext[AST_MAX_CONTEXT];
525 static char default_language[MAX_LANGUAGE];
526 static char default_callerid[AST_MAX_EXTENSION];
527 static char default_fromdomain[AST_MAX_EXTENSION];
528 static char default_notifymime[AST_MAX_EXTENSION];
529 static int default_qualify; /*!< Default Qualify= setting */
530 static char default_vmexten[AST_MAX_EXTENSION];
531 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
532 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
533 * a bridged channel on hold */
534 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
535 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
537 /* Global settings only apply to the channel */
538 static int global_directrtpsetup; /*!< Enable support for Direct RTP setup (no re-invites) */
539 static int global_limitonpeers; /*!< Match call limit on peers only */
540 static int global_rtautoclear;
541 static int global_notifyringing; /*!< Send notifications on ringing */
542 static int global_notifyhold; /*!< Send notifications on hold */
543 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
544 static int srvlookup; /*!< SRV Lookup on or off. Default is on */
545 static int pedanticsipchecking; /*!< Extra checking ? Default off */
546 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
547 static int global_relaxdtmf; /*!< Relax DTMF */
548 static int global_rtptimeout; /*!< Time out call if no RTP */
549 static int global_rtpholdtimeout;
550 static int global_rtpkeepalive; /*!< Send RTP keepalives */
551 static int global_reg_timeout;
552 static int global_regattempts_max; /*!< Registration attempts before giving up */
553 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
554 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
555 the global setting is in globals_flags[1] */
556 static int global_mwitime; /*!< Time between MWI checks for peers */
557 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
558 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
559 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
560 static int compactheaders; /*!< send compact sip headers */
561 static int recordhistory; /*!< Record SIP history. Off by default */
562 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
563 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
564 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
565 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
566 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
567 static int global_callevents; /*!< Whether we send manager events or not */
568 static int global_t1min; /*!< T1 roundtrip time minimum */
569 static int global_autoframing; /*!< Turn autoframing on or off. */
570 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
572 static int global_matchexterniplocally; /*!< Match externip/externhost setting against localnet setting */
574 /*! \brief Codecs that we support by default: */
575 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
577 /* Object counters */
578 static int suserobjs = 0; /*!< Static users */
579 static int ruserobjs = 0; /*!< Realtime users */
580 static int speerobjs = 0; /*!< Statis peers */
581 static int rpeerobjs = 0; /*!< Realtime peers */
582 static int apeerobjs = 0; /*!< Autocreated peer objects */
583 static int regobjs = 0; /*!< Registry objects */
585 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
587 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
588 AST_MUTEX_DEFINE_STATIC(iflock);
590 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
591 when it's doing something critical. */
592 AST_MUTEX_DEFINE_STATIC(netlock);
594 AST_MUTEX_DEFINE_STATIC(monlock);
596 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
598 /*! \brief This is the thread for the monitor which checks for input on the channels
599 which are not currently in use. */
600 static pthread_t monitor_thread = AST_PTHREADT_NULL;
602 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
603 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
605 static struct sched_context *sched; /*!< The scheduling context */
606 static struct io_context *io; /*!< The IO context */
607 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
609 #define DEC_CALL_LIMIT 0
610 #define INC_CALL_LIMIT 1
611 #define DEC_CALL_RINGING 2
612 #define INC_CALL_RINGING 3
614 /*! \brief sip_request: The data grabbed from the UDP socket */
615 struct sip_request {
616 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
617 char *rlPart2; /*!< The Request URI or Response Status */
618 int len; /*!< Length */
619 int headers; /*!< # of SIP Headers */
620 int method; /*!< Method of this request */
621 int lines; /*!< Body Content */
622 unsigned int flags; /*!< SIP_PKT Flags for this packet */
623 char *header[SIP_MAX_HEADERS];
624 char *line[SIP_MAX_LINES];
625 char data[SIP_MAX_PACKET];
626 unsigned int sdp_start; /*!< the line number where the SDP begins */
627 unsigned int sdp_end; /*!< the line number where the SDP ends */
631 * A sip packet is stored into the data[] buffer, with the header followed
632 * by an empty line and the body of the message.
633 * On outgoing packets, data is accumulated in data[] with len reflecting
634 * the next available byte, headers and lines count the number of lines
635 * in both parts. There are no '\0' in data[0..len-1].
637 * On received packet, the input read from the socket is copied into data[],
638 * len is set and the string is NUL-terminated. Then a parser fills up
639 * the other fields -header[] and line[] to point to the lines of the
640 * message, rlPart1 and rlPart2 parse the first lnie as below:
642 * Requests have in the first line METHOD URI SIP/2.0
643 * rlPart1 = method; rlPart2 = uri;
644 * Responses have in the first line SIP/2.0 code description
645 * rlPart1 = SIP/2.0; rlPart2 = code + description;
649 /*! \brief structure used in transfers */
650 struct sip_dual {
651 struct ast_channel *chan1; /*!< First channel involved */
652 struct ast_channel *chan2; /*!< Second channel involved */
653 struct sip_request req; /*!< Request that caused the transfer (REFER) */
654 int seqno; /*!< Sequence number */
657 struct sip_pkt;
659 /*! \brief Parameters to the transmit_invite function */
660 struct sip_invite_param {
661 const char *distinctive_ring; /*!< Distinctive ring header */
662 int addsipheaders; /*!< Add extra SIP headers */
663 const char *uri_options; /*!< URI options to add to the URI */
664 const char *vxml_url; /*!< VXML url for Cisco phones */
665 char *auth; /*!< Authentication */
666 char *authheader; /*!< Auth header */
667 enum sip_auth_type auth_type; /*!< Authentication type */
668 const char *replaces; /*!< Replaces header for call transfers */
669 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
672 /*! \brief Structure to save routing information for a SIP session */
673 struct sip_route {
674 struct sip_route *next;
675 char hop[0];
678 /*! \brief Modes for SIP domain handling in the PBX */
679 enum domain_mode {
680 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
681 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
684 /*! \brief Domain data structure.
685 \note In the future, we will connect this to a configuration tree specific
686 for this domain
688 struct domain {
689 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
690 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
691 enum domain_mode mode; /*!< How did we find this domain? */
692 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
695 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
698 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
699 struct sip_history {
700 AST_LIST_ENTRY(sip_history) list;
701 char event[0]; /* actually more, depending on needs */
704 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
706 /*! \brief sip_auth: Credentials for authentication to other SIP services */
707 struct sip_auth {
708 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
709 char username[256]; /*!< Username */
710 char secret[256]; /*!< Secret */
711 char md5secret[256]; /*!< MD5Secret */
712 struct sip_auth *next; /*!< Next auth structure in list */
715 /*--- Various flags for the flags field in the pvt structure */
716 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
717 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed by the monitor thread */
718 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
719 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
720 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
721 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
722 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
723 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
724 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
725 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
726 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
727 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
728 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
729 #define SIP_OUTGOING (1 << 13) /*!< Direction of the last transaction in this dialog */
730 #define SIP_FREE_BIT (1 << 14) /*!< ---- */
731 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 15) /*!< Do not hangup at first ast_hangup */
732 #define SIP_DTMF (3 << 16) /*!< DTMF Support: four settings, uses two bits */
733 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DTMF Support: RTP DTMF - "rfc2833" */
734 #define SIP_DTMF_INBAND (1 << 16) /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
735 #define SIP_DTMF_INFO (2 << 16) /*!< DTMF Support: SIP Info messages - "info" */
736 #define SIP_DTMF_AUTO (3 << 16) /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
737 /* NAT settings */
738 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
739 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
740 #define SIP_NAT_RFC3581 (1 << 18) /*!< NAT RFC3581 */
741 #define SIP_NAT_ROUTE (2 << 18) /*!< NAT Only ROUTE */
742 #define SIP_NAT_ALWAYS (3 << 18) /*!< NAT Both ROUTE and RFC3581 */
743 /* re-INVITE related settings */
744 #define SIP_REINVITE (7 << 20) /*!< three bits used */
745 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
746 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< allow media reinvite when new peer is behind NAT */
747 #define SIP_REINVITE_UPDATE (4 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
748 /* "insecure" settings */
749 #define SIP_INSECURE_PORT (1 << 23) /*!< don't require matching port for incoming requests */
750 #define SIP_INSECURE_INVITE (1 << 24) /*!< don't require authentication for incoming INVITEs */
751 /* Sending PROGRESS in-band settings */
752 #define SIP_PROG_INBAND (3 << 25) /*!< three settings, uses two bits */
753 #define SIP_PROG_INBAND_NEVER (0 << 25)
754 #define SIP_PROG_INBAND_NO (1 << 25)
755 #define SIP_PROG_INBAND_YES (2 << 25)
756 #define SIP_NO_HISTORY (1 << 27) /*!< Suppress recording request/response history */
757 #define SIP_CALL_LIMIT (1 << 28) /*!< Call limit enforced for this call */
758 #define SIP_SENDRPID (1 << 29) /*!< Remote Party-ID Support */
759 #define SIP_INC_COUNT (1 << 30) /*!< Did this connection increment the counter of in-use calls? */
760 #define SIP_G726_NONSTANDARD (1 << 31) /*!< Use non-standard packing for G726-32 data */
762 #define SIP_FLAGS_TO_COPY \
763 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
764 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
765 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
767 /*--- a new page of flags (for flags[1] */
768 /* realtime flags */
769 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
770 #define SIP_PAGE2_RTUPDATE (1 << 1)
771 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
772 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
773 #define SIP_PAGE2_RTSAVE_SYSNAME (1 << 5)
774 /* Space for addition of other realtime flags in the future */
775 #define SIP_PAGE2_STATECHANGEQUEUE (1 << 9) /*!< D: Unsent state pending change exists */
776 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 10)
777 #define SIP_PAGE2_DEBUG (3 << 11)
778 #define SIP_PAGE2_DEBUG_CONFIG (1 << 11)
779 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 12)
780 #define SIP_PAGE2_DYNAMIC (1 << 13) /*!< Dynamic Peers register with Asterisk */
781 #define SIP_PAGE2_SELFDESTRUCT (1 << 14) /*!< Automatic peers need to destruct themselves */
782 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15)
783 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< Allow subscriptions from this peer? */
784 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< Allow overlap dialing ? */
785 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< Only issue MWI notification if subscribed to */
786 #define SIP_PAGE2_INC_RINGING (1 << 19) /*!< Did this connection increment the counter of in-use calls? */
787 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< T38 Fax Passthrough Support */
788 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< 20: T38 Fax Passthrough Support */
789 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< 21: T38 Fax Passthrough Support (not implemented) */
790 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< 22: T38 Fax Passthrough Support (not implemented) */
791 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< Call states */
792 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23) /*!< 23: Active hold */
793 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23) /*!< 23: One directional hold */
794 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23) /*!< 23: Inactive hold */
795 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25) /*!< 25: ???? */
796 #define SIP_PAGE2_BUGGY_MWI (1 << 26) /*!< 26: Buggy CISCO MWI fix */
797 #define SIP_PAGE2_OUTGOING_CALL (1 << 27) /*!< 27: Is this an outgoing call? */
798 #define SIP_PAGE2_UDPTL_DESTINATION (1 << 28) /*!< 28: Use source IP of RTP as destination if NAT is enabled */
800 #define SIP_PAGE2_FLAGS_TO_COPY \
801 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
802 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_UDPTL_DESTINATION)
804 /* SIP packet flags */
805 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
806 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
807 #define SIP_PKT_IGNORE (1 << 2) /*!< This is a re-transmit, ignore it */
808 #define SIP_PKT_IGNORE_RESP (1 << 3) /*!< Resp ignore - ??? */
809 #define SIP_PKT_IGNORE_REQ (1 << 4) /*!< Req ignore - ??? */
811 /* T.38 set of flags */
812 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
813 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
814 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
815 /* Rate management */
816 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
817 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
818 /* UDP Error correction */
819 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
820 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
821 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
822 /* T38 Spec version */
823 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
824 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
825 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
826 /* Maximum Fax Rate */
827 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
828 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
829 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
830 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
831 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
832 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
834 /*!< This is default: NO MMR and JBIG trancoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
835 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
837 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
838 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
839 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
841 /*! \brief T38 States for a call */
842 enum t38state {
843 T38_DISABLED = 0, /*!< Not enabled */
844 T38_LOCAL_DIRECT, /*!< Offered from local */
845 T38_LOCAL_REINVITE, /*!< Offered from local - REINVITE */
846 T38_PEER_DIRECT, /*!< Offered from peer */
847 T38_PEER_REINVITE, /*!< Offered from peer - REINVITE */
848 T38_ENABLED /*!< Negotiated (enabled) */
851 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
852 struct t38properties {
853 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
854 int capability; /*!< Our T38 capability */
855 int peercapability; /*!< Peers T38 capability */
856 int jointcapability; /*!< Supported T38 capability at both ends */
857 enum t38state state; /*!< T.38 state */
860 /*! \brief Parameters to know status of transfer */
861 enum referstatus {
862 REFER_IDLE, /*!< No REFER is in progress */
863 REFER_SENT, /*!< Sent REFER to transferee */
864 REFER_RECEIVED, /*!< Received REFER from transferer */
865 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING */
866 REFER_ACCEPTED, /*!< Accepted by transferee */
867 REFER_RINGING, /*!< Target Ringing */
868 REFER_200OK, /*!< Answered by transfer target */
869 REFER_FAILED, /*!< REFER declined - go on */
870 REFER_NOAUTH /*!< We had no auth for REFER */
873 static const struct c_referstatusstring {
874 enum referstatus status;
875 char *text;
876 } referstatusstrings[] = {
877 { REFER_IDLE, "<none>" },
878 { REFER_SENT, "Request sent" },
879 { REFER_RECEIVED, "Request received" },
880 { REFER_ACCEPTED, "Accepted" },
881 { REFER_RINGING, "Target ringing" },
882 { REFER_200OK, "Done" },
883 { REFER_FAILED, "Failed" },
884 { REFER_NOAUTH, "Failed - auth failure" }
887 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed */
888 /* OEJ: Should be moved to string fields */
889 struct sip_refer {
890 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
891 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
892 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
893 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
894 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
895 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
896 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
897 char replaces_callid[SIPBUFSIZE]; /*!< Replace info: callid */
898 char replaces_callid_totag[SIPBUFSIZE/2]; /*!< Replace info: to-tag */
899 char replaces_callid_fromtag[SIPBUFSIZE/2]; /*!< Replace info: from-tag */
900 struct sip_pvt *refer_call; /*!< Call we are referring */
901 int attendedtransfer; /*!< Attended or blind transfer? */
902 int localtransfer; /*!< Transfer to local domain? */
903 enum referstatus status; /*!< REFER status */
906 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
907 static struct sip_pvt {
908 ast_mutex_t lock; /*!< Dialog private lock */
909 int method; /*!< SIP method that opened this dialog */
910 enum invitestates invitestate; /*!< The state of the INVITE transaction only */
911 AST_DECLARE_STRING_FIELDS(
912 AST_STRING_FIELD(callid); /*!< Global CallID */
913 AST_STRING_FIELD(randdata); /*!< Random data */
914 AST_STRING_FIELD(accountcode); /*!< Account code */
915 AST_STRING_FIELD(realm); /*!< Authorization realm */
916 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
917 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
918 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
919 AST_STRING_FIELD(domain); /*!< Authorization domain */
920 AST_STRING_FIELD(from); /*!< The From: header */
921 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
922 AST_STRING_FIELD(exten); /*!< Extension where to start */
923 AST_STRING_FIELD(context); /*!< Context for this call */
924 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
925 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
926 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
927 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
928 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
929 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
930 AST_STRING_FIELD(language); /*!< Default language for this call */
931 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
932 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
933 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
934 AST_STRING_FIELD(theirtag); /*!< Their tag */
935 AST_STRING_FIELD(username); /*!< [user] name */
936 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
937 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
938 AST_STRING_FIELD(uri); /*!< Original requested URI */
939 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
940 AST_STRING_FIELD(peersecret); /*!< Password */
941 AST_STRING_FIELD(peermd5secret);
942 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
943 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
944 AST_STRING_FIELD(via); /*!< Via: header */
945 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
946 AST_STRING_FIELD(our_contact); /*!< Our contact header */
947 AST_STRING_FIELD(rpid); /*!< Our RPID header */
948 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
950 unsigned int ocseq; /*!< Current outgoing seqno */
951 unsigned int icseq; /*!< Current incoming seqno */
952 ast_group_t callgroup; /*!< Call group */
953 ast_group_t pickupgroup; /*!< Pickup group */
954 int lastinvite; /*!< Last Cseq of invite */
955 int lastnoninvite; /*!< Last Cseq of non-invite */
956 struct ast_flags flags[2]; /*!< SIP_ flags */
957 int timer_t1; /*!< SIP timer T1, ms rtt */
958 unsigned int sipoptions; /*!< Supported SIP options on the other end */
959 struct ast_codec_pref prefs; /*!< codec prefs */
960 int capability; /*!< Special capability (codec) */
961 int jointcapability; /*!< Supported capability at both ends (codecs) */
962 int peercapability; /*!< Supported peer capability */
963 int prefcodec; /*!< Preferred codec (outbound only) */
964 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
965 int jointnoncodeccapability; /*!< Joint Non codec capability */
966 int redircodecs; /*!< Redirect codecs */
967 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
968 struct t38properties t38; /*!< T38 settings */
969 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
970 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
971 int callingpres; /*!< Calling presentation */
972 int authtries; /*!< Times we've tried to authenticate */
973 int expiry; /*!< How long we take to expire */
974 long branch; /*!< The branch identifier of this session */
975 char tag[11]; /*!< Our tag for this session */
976 int sessionid; /*!< SDP Session ID */
977 int sessionversion; /*!< SDP Session Version */
978 struct sockaddr_in sa; /*!< Our peer */
979 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
980 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
981 time_t lastrtprx; /*!< Last RTP received */
982 time_t lastrtptx; /*!< Last RTP sent */
983 int rtptimeout; /*!< RTP timeout time */
984 struct sockaddr_in recv; /*!< Received as */
985 struct in_addr ourip; /*!< Our IP */
986 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
987 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
988 int route_persistant; /*!< Is this the "real" route? */
989 struct sip_auth *peerauth; /*!< Realm authentication */
990 int noncecount; /*!< Nonce-count */
991 char lastmsg[256]; /*!< Last Message sent/received */
992 int amaflags; /*!< AMA Flags */
993 int pendinginvite; /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
994 struct sip_request initreq; /*!< Request that opened the latest transaction
995 within this SIP dialog */
997 int maxtime; /*!< Max time for first response */
998 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
999 int waitid; /*!< Wait ID for scheduler after 491 or other delays */
1000 int autokillid; /*!< Auto-kill ID (scheduler) */
1001 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
1002 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
1003 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
1004 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
1005 int laststate; /*!< SUBSCRIBE: Last known extension state */
1006 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
1008 struct ast_dsp *vad; /*!< Voice Activation Detection dsp */
1010 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
1011 Used in peerpoke, mwi subscriptions */
1012 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
1013 struct ast_rtp *rtp; /*!< RTP Session */
1014 struct ast_rtp *vrtp; /*!< Video RTP session */
1015 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
1016 struct sip_history_head *history; /*!< History of this SIP dialog */
1017 size_t history_entries; /*!< Number of entires in the history */
1018 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1019 struct sip_pvt *next; /*!< Next dialog in chain */
1020 struct sip_invite_param *options; /*!< Options for INVITE */
1021 int autoframing;
1022 } *iflist = NULL;
1024 /*! Max entires in the history list for a sip_pvt */
1025 #define MAX_HISTORY_ENTRIES 50
1027 #define FLAG_RESPONSE (1 << 0)
1028 #define FLAG_FATAL (1 << 1)
1030 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */
1031 struct sip_pkt {
1032 struct sip_pkt *next; /*!< Next packet in linked list */
1033 int retrans; /*!< Retransmission number */
1034 int method; /*!< SIP method for this packet */
1035 int seqno; /*!< Sequence number */
1036 unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */
1037 struct sip_pvt *owner; /*!< Owner AST call */
1038 int retransid; /*!< Retransmission ID */
1039 int timer_a; /*!< SIP timer A, retransmission timer */
1040 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
1041 int packetlen; /*!< Length of packet */
1042 char data[0];
1045 /*! \brief Structure for SIP user data. User's place calls to us */
1046 struct sip_user {
1047 /* Users who can access various contexts */
1048 ASTOBJ_COMPONENTS(struct sip_user);
1049 char secret[80]; /*!< Password */
1050 char md5secret[80]; /*!< Password in md5 */
1051 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1052 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
1053 char cid_num[80]; /*!< Caller ID num */
1054 char cid_name[80]; /*!< Caller ID name */
1055 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
1056 char language[MAX_LANGUAGE]; /*!< Default language for this user */
1057 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1058 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1059 char useragent[256]; /*!< User agent in SIP request */
1060 struct ast_codec_pref prefs; /*!< codec prefs */
1061 ast_group_t callgroup; /*!< Call group */
1062 ast_group_t pickupgroup; /*!< Pickup Group */
1063 unsigned int sipoptions; /*!< Supported SIP options */
1064 struct ast_flags flags[2]; /*!< SIP_ flags */
1065 int amaflags; /*!< AMA flags for billing */
1066 int callingpres; /*!< Calling id presentation */
1067 int capability; /*!< Codec capability */
1068 int inUse; /*!< Number of calls in use */
1069 int call_limit; /*!< Limit of concurrent calls */
1070 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1071 struct ast_ha *ha; /*!< ACL setting */
1072 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1073 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1074 int autoframing;
1077 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1078 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1079 struct sip_peer {
1080 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
1081 /*!< peer->name is the unique name of this object */
1082 char secret[80]; /*!< Password */
1083 char md5secret[80]; /*!< Password in MD5 */
1084 struct sip_auth *auth; /*!< Realm authentication list */
1085 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1086 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1087 char username[80]; /*!< Temporary username until registration */
1088 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1089 int amaflags; /*!< AMA Flags (for billing) */
1090 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1091 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1092 char fromuser[80]; /*!< From: user when calling this peer */
1093 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1094 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1095 char cid_num[80]; /*!< Caller ID num */
1096 char cid_name[80]; /*!< Caller ID name */
1097 int callingpres; /*!< Calling id presentation */
1098 int inUse; /*!< Number of calls in use */
1099 int inRinging; /*!< Number of calls ringing */
1100 int onHold; /*!< Peer has someone on hold */
1101 int call_limit; /*!< Limit of concurrent calls */
1102 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1103 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1104 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
1105 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1106 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1107 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1108 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1109 struct ast_codec_pref prefs; /*!< codec prefs */
1110 int lastmsgssent;
1111 time_t lastmsgcheck; /*!< Last time we checked for MWI */
1112 unsigned int sipoptions; /*!< Supported SIP options */
1113 struct ast_flags flags[2]; /*!< SIP_ flags */
1114 int expire; /*!< When to expire this peer registration */
1115 int capability; /*!< Codec capability */
1116 int rtptimeout; /*!< RTP timeout */
1117 int rtpholdtimeout; /*!< RTP Hold Timeout */
1118 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1119 ast_group_t callgroup; /*!< Call group */
1120 ast_group_t pickupgroup; /*!< Pickup group */
1121 struct sockaddr_in addr; /*!< IP address of peer */
1122 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1124 /* Qualification */
1125 struct sip_pvt *call; /*!< Call pointer */
1126 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1127 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1128 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1129 struct timeval ps; /*!< Ping send time */
1131 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1132 struct ast_ha *ha; /*!< Access control list */
1133 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1134 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1135 int lastmsg;
1136 int autoframing;
1141 /*! \brief Registrations with other SIP proxies */
1142 struct sip_registry {
1143 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1144 AST_DECLARE_STRING_FIELDS(
1145 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1146 AST_STRING_FIELD(realm); /*!< Authorization realm */
1147 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1148 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1149 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1150 AST_STRING_FIELD(domain); /*!< Authorization domain */
1151 AST_STRING_FIELD(username); /*!< Who we are registering as */
1152 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1153 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1154 AST_STRING_FIELD(secret); /*!< Password in clear text */
1155 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1156 AST_STRING_FIELD(contact); /*!< Contact extension */
1157 AST_STRING_FIELD(random);
1159 int portno; /*!< Optional port override */
1160 int expire; /*!< Sched ID of expiration */
1161 int regattempts; /*!< Number of attempts (since the last success) */
1162 int timeout; /*!< sched id of sip_reg_timeout */
1163 int refresh; /*!< How often to refresh */
1164 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1165 enum sipregistrystate regstate; /*!< Registration state (see above) */
1166 time_t regtime; /*!< Last succesful registration time */
1167 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1168 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1169 struct sockaddr_in us; /*!< Who the server thinks we are */
1170 int noncecount; /*!< Nonce-count */
1171 char lastmsg[256]; /*!< Last Message sent/received */
1174 /* --- Linked lists of various objects --------*/
1176 /*! \brief The user list: Users and friends */
1177 static struct ast_user_list {
1178 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1179 } userl;
1181 /*! \brief The peer list: Peers and Friends */
1182 static struct ast_peer_list {
1183 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1184 } peerl;
1186 /*! \brief The register list: Other SIP proxys we register with and place calls to */
1187 static struct ast_register_list {
1188 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1189 int recheck;
1190 } regl;
1192 static void temp_pvt_cleanup(void *);
1194 /*! \brief A per-thread temporary pvt structure */
1195 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1197 static void ts_ast_rtp_destroy(void *);
1199 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, ts_audio_rtp_init, ts_ast_rtp_destroy);
1200 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, ts_video_rtp_init, ts_ast_rtp_destroy);
1202 /*! \todo Move the sip_auth list to AST_LIST */
1203 static struct sip_auth *authl = NULL; /*!< Authentication list for realm authentication */
1206 /* --- Sockets and networking --------------*/
1207 static int sipsock = -1; /*!< Main socket for SIP network communication */
1208 static struct sockaddr_in bindaddr = { 0, }; /*!< The address we bind to */
1209 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1210 static char externhost[MAXHOSTNAMELEN]; /*!< External host name (possibly with dynamic DNS and DHCP */
1211 static time_t externexpire = 0; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1212 static int externrefresh = 10;
1213 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1214 static struct in_addr __ourip;
1215 static struct sockaddr_in outboundproxyip;
1216 static int ourport;
1217 static struct sockaddr_in debugaddr;
1219 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1221 /*---------------------------- Forward declarations of functions in chan_sip.c */
1222 /*! \note This is added to help splitting up chan_sip.c into several files
1223 in coming releases */
1225 /*--- PBX interface functions */
1226 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1227 static int sip_devicestate(void *data);
1228 static int sip_sendtext(struct ast_channel *ast, const char *text);
1229 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1230 static int sip_hangup(struct ast_channel *ast);
1231 static int sip_answer(struct ast_channel *ast);
1232 static struct ast_frame *sip_read(struct ast_channel *ast);
1233 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1234 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1235 static int sip_transfer(struct ast_channel *ast, const char *dest);
1236 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1237 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1238 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1240 /*--- Transmitting responses and requests */
1241 static int sipsock_read(int *id, int fd, short events, void *ignore);
1242 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
1243 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
1244 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1245 static int retrans_pkt(const void *data);
1246 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
1247 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);
1248 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1249 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1250 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1251 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1252 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1253 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);
1254 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1255 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1256 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1257 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1258 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1259 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
1260 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1261 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1262 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1263 static int transmit_refer(struct sip_pvt *p, const char *dest);
1264 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1265 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1266 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1267 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1268 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1269 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1270 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1271 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1272 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1273 static int does_peer_need_mwi(struct sip_peer *peer);
1275 /*--- Dialog management */
1276 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1277 int useglobal_nat, const int intended_method);
1278 static int __sip_autodestruct(const void *data);
1279 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1280 static int sip_cancel_destroy(struct sip_pvt *p);
1281 static void sip_destroy(struct sip_pvt *p);
1282 static int __sip_destroy(struct sip_pvt *p, int lockowner);
1283 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1284 static void __sip_pretend_ack(struct sip_pvt *p);
1285 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1286 static int auto_congest(const void *nothing);
1287 static int update_call_counter(struct sip_pvt *fup, int event);
1288 static int hangup_sip2cause(int cause);
1289 static const char *hangup_cause2sip(int cause);
1290 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1291 static void free_old_route(struct sip_route *route);
1292 static void list_route(struct sip_route *route);
1293 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1294 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1295 struct sip_request *req, char *uri);
1296 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1297 static void check_pendings(struct sip_pvt *p);
1298 static void *sip_park_thread(void *stuff);
1299 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1300 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1302 /*--- Codec handling / SDP */
1303 static void try_suggested_sip_codec(struct sip_pvt *p);
1304 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1305 static const char *get_sdp(struct sip_request *req, const char *name);
1306 static int find_sdp(struct sip_request *req);
1307 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
1308 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1309 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1310 int debug, int *min_packet_size);
1311 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1312 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1313 int debug);
1314 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p);
1315 static void stop_media_flows(struct sip_pvt *p);
1317 /*--- Authentication stuff */
1318 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1319 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1320 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1321 const char *secret, const char *md5secret, int sipmethod,
1322 char *uri, enum xmittype reliable, int ignore);
1323 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1324 int sipmethod, char *uri, enum xmittype reliable,
1325 struct sockaddr_in *sin, struct sip_peer **authpeer);
1326 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1328 /*--- Domain handling */
1329 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1330 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1331 static void clear_sip_domains(void);
1333 /*--- SIP realm authentication */
1334 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
1335 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1336 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1338 /*--- Misc functions */
1339 static int sip_do_reload(enum channelreloadreason reason);
1340 static int reload_config(enum channelreloadreason reason);
1341 static int expire_register(const void *data);
1342 static void *do_monitor(void *data);
1343 static int restart_monitor(void);
1344 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1345 static int sip_addrcmp(char *name, struct sockaddr_in *sin); /* Support for peer matching */
1346 static int sip_refer_allocate(struct sip_pvt *p);
1347 static void ast_quiet_chan(struct ast_channel *chan);
1348 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1350 /*--- Device monitoring and Device/extension state handling */
1351 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1352 static int sip_devicestate(void *data);
1353 static int sip_poke_noanswer(const void *data);
1354 static int sip_poke_peer(struct sip_peer *peer);
1355 static void sip_poke_all_peers(void);
1356 static void sip_peer_hold(struct sip_pvt *p, int hold);
1358 /*--- Applications, functions, CLI and manager command helpers */
1359 static const char *sip_nat_mode(const struct sip_pvt *p);
1360 static int sip_show_inuse(int fd, int argc, char *argv[]);
1361 static char *transfermode2str(enum transfermodes mode) attribute_const;
1362 static char *nat2str(int nat) attribute_const;
1363 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1364 static int sip_show_users(int fd, int argc, char *argv[]);
1365 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1366 static int sip_show_peers(int fd, int argc, char *argv[]);
1367 static int sip_show_objects(int fd, int argc, char *argv[]);
1368 static void print_group(int fd, ast_group_t group, int crlf);
1369 static const char *dtmfmode2str(int mode) attribute_const;
1370 static const char *insecure2str(int port, int invite) attribute_const;
1371 static void cleanup_stale_contexts(char *new, char *old);
1372 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1373 static const char *domain_mode_to_text(const enum domain_mode mode);
1374 static int sip_show_domains(int fd, int argc, char *argv[]);
1375 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1376 static int sip_show_peer(int fd, int argc, char *argv[]);
1377 static int sip_show_user(int fd, int argc, char *argv[]);
1378 static int sip_show_registry(int fd, int argc, char *argv[]);
1379 static int sip_show_settings(int fd, int argc, char *argv[]);
1380 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1381 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1382 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1383 static int sip_show_channels(int fd, int argc, char *argv[]);
1384 static int sip_show_subscriptions(int fd, int argc, char *argv[]);
1385 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1386 static char *complete_sipch(const char *line, const char *word, int pos, int state);
1387 static char *complete_sip_peer(const char *word, int state, int flags2);
1388 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1389 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state);
1390 static char *complete_sip_user(const char *word, int state, int flags2);
1391 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
1392 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1393 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state);
1394 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state);
1395 static int sip_show_channel(int fd, int argc, char *argv[]);
1396 static int sip_show_history(int fd, int argc, char *argv[]);
1397 static int sip_do_debug_ip(int fd, int argc, char *argv[]);
1398 static int sip_do_debug_peer(int fd, int argc, char *argv[]);
1399 static int sip_do_debug(int fd, int argc, char *argv[]);
1400 static int sip_no_debug(int fd, int argc, char *argv[]);
1401 static int sip_notify(int fd, int argc, char *argv[]);
1402 static int sip_do_history(int fd, int argc, char *argv[]);
1403 static int sip_no_history(int fd, int argc, char *argv[]);
1404 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
1405 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1406 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1407 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1408 static int sip_dtmfmode(struct ast_channel *chan, void *data);
1409 static int sip_addheader(struct ast_channel *chan, void *data);
1410 static int sip_do_reload(enum channelreloadreason reason);
1411 static int sip_reload(int fd, int argc, char *argv[]);
1412 static int acf_channel_read(struct ast_channel *chan, char *funcname, char *preparse, char *buf, size_t buflen);
1414 /*--- Debugging
1415 Functions for enabling debug per IP or fully, or enabling history logging for
1416 a SIP dialog
1418 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1419 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1420 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1421 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1422 static void sip_dump_history(struct sip_pvt *dialog);
1424 /*--- Device object handling */
1425 static struct sip_peer *temp_peer(const char *name);
1426 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1427 static struct sip_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1428 static int update_call_counter(struct sip_pvt *fup, int event);
1429 static void sip_destroy_peer(struct sip_peer *peer);
1430 static void sip_destroy_user(struct sip_user *user);
1431 static int sip_poke_peer(struct sip_peer *peer);
1432 static int sip_poke_peer_s(const void *data);
1433 static void set_peer_defaults(struct sip_peer *peer);
1434 static struct sip_peer *temp_peer(const char *name);
1435 static void register_peer_exten(struct sip_peer *peer, int onoff);
1436 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
1437 static struct sip_user *find_user(const char *name, int realtime);
1438 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1439 static int expire_register(const void *data);
1440 static void reg_source_db(struct sip_peer *peer);
1441 static void destroy_association(struct sip_peer *peer);
1442 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1444 /* Realtime device support */
1445 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
1446 static struct sip_user *realtime_user(const char *username);
1447 static void update_peer(struct sip_peer *p, int expiry);
1448 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
1449 static int sip_prune_realtime(int fd, int argc, char *argv[]);
1451 /*--- Internal UA client handling (outbound registrations) */
1452 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
1453 static void sip_registry_destroy(struct sip_registry *reg);
1454 static int sip_register(char *value, int lineno);
1455 static char *regstate2str(enum sipregistrystate regstate) attribute_const;
1456 static int sip_reregister(const void *data);
1457 static int __sip_do_register(struct sip_registry *r);
1458 static int sip_reg_timeout(const void *data);
1459 static void sip_send_all_registers(void);
1461 /*--- Parsing SIP requests and responses */
1462 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1463 static int determine_firstline_parts(struct sip_request *req);
1464 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1465 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1466 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1467 static int find_sip_method(const char *msg);
1468 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1469 static int parse_request(struct sip_request *req);
1470 static const char *get_header(const struct sip_request *req, const char *name);
1471 static char *referstatus2str(enum referstatus rstatus) attribute_pure;
1472 static int method_match(enum sipmethod id, const char *name);
1473 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1474 static char *get_in_brackets(char *tmp);
1475 static const char *find_alias(const char *name, const char *_default);
1476 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1477 static int lws2sws(char *msgbuf, int len);
1478 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1479 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1480 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1481 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1482 static int set_address_from_contact(struct sip_pvt *pvt);
1483 static void check_via(struct sip_pvt *p, const struct sip_request *req);
1484 static char *get_calleridname(const char *input, char *output, size_t outputsize);
1485 static int get_rpid_num(const char *input, char *output, int maxlen);
1486 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
1487 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1488 static int get_msg_text(char *buf, int len, struct sip_request *req);
1489 static void free_old_route(struct sip_route *route);
1490 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1492 /*--- Constructing requests and responses */
1493 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1494 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1495 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1496 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1497 static int init_resp(struct sip_request *resp, const char *msg);
1498 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1499 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1500 static void build_via(struct sip_pvt *p);
1501 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1502 static int create_addr(struct sip_pvt *dialog, const char *opeer);
1503 static char *generate_random_string(char *buf, size_t size);
1504 static void build_callid_pvt(struct sip_pvt *pvt);
1505 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1506 static void make_our_tag(char *tagbuf, size_t len);
1507 static int add_header(struct sip_request *req, const char *var, const char *value);
1508 static int add_header_contentLength(struct sip_request *req, int len);
1509 static int add_line(struct sip_request *req, const char *line);
1510 static int add_text(struct sip_request *req, const char *text);
1511 static int add_digit(struct sip_request *req, char digit, unsigned int duration);
1512 static int add_vidupdate(struct sip_request *req);
1513 static void add_route(struct sip_request *req, struct sip_route *route);
1514 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1515 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1516 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1517 static void set_destination(struct sip_pvt *p, char *uri);
1518 static void append_date(struct sip_request *req);
1519 static void build_contact(struct sip_pvt *p);
1520 static void build_rpid(struct sip_pvt *p);
1522 /*------Request handling functions */
1523 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1524 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);
1525 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock);
1526 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1527 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1528 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1529 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1530 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1531 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1532 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1533 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1534 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1535 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
1537 /*------Response handling functions */
1538 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1539 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1540 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
1541 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
1543 /*----- RTP interface functions */
1544 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
1545 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1546 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1547 static int sip_get_codec(struct ast_channel *chan);
1548 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
1550 /*------ T38 Support --------- */
1551 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite); /*!< T38 negotiation helper function */
1552 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1553 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p);
1554 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1555 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1557 /*! \brief Definition of this channel for PBX channel registration */
1558 static const struct ast_channel_tech sip_tech = {
1559 .type = "SIP",
1560 .description = "Session Initiation Protocol (SIP)",
1561 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1562 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1563 .requester = sip_request_call,
1564 .devicestate = sip_devicestate,
1565 .call = sip_call,
1566 .hangup = sip_hangup,
1567 .answer = sip_answer,
1568 .read = sip_read,
1569 .write = sip_write,
1570 .write_video = sip_write,
1571 .indicate = sip_indicate,
1572 .transfer = sip_transfer,
1573 .fixup = sip_fixup,
1574 .send_digit_begin = sip_senddigit_begin,
1575 .send_digit_end = sip_senddigit_end,
1576 .bridge = ast_rtp_bridge,
1577 .send_text = sip_sendtext,
1578 .func_channel_read = acf_channel_read,
1581 /*! \brief This version of the sip channel tech has no send_digit_begin
1582 * callback. This is for use with channels using SIP INFO DTMF so that
1583 * the core knows that the channel doesn't want DTMF BEGIN frames. */
1584 static const struct ast_channel_tech sip_tech_info = {
1585 .type = "SIP",
1586 .description = "Session Initiation Protocol (SIP)",
1587 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1588 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1589 .requester = sip_request_call,
1590 .devicestate = sip_devicestate,
1591 .call = sip_call,
1592 .hangup = sip_hangup,
1593 .answer = sip_answer,
1594 .read = sip_read,
1595 .write = sip_write,
1596 .write_video = sip_write,
1597 .indicate = sip_indicate,
1598 .transfer = sip_transfer,
1599 .fixup = sip_fixup,
1600 .send_digit_end = sip_senddigit_end,
1601 .bridge = ast_rtp_bridge,
1602 .send_text = sip_sendtext,
1603 .func_channel_read = acf_channel_read,
1606 /**--- some list management macros. **/
1608 #define UNLINK(element, head, prev) do { \
1609 if (prev) \
1610 (prev)->next = (element)->next; \
1611 else \
1612 (head) = (element)->next; \
1613 } while (0)
1615 /*! \brief Interface structure with callbacks used to connect to RTP module */
1616 static struct ast_rtp_protocol sip_rtp = {
1617 type: "SIP",
1618 get_rtp_info: sip_get_rtp_peer,
1619 get_vrtp_info: sip_get_vrtp_peer,
1620 set_rtp_peer: sip_set_rtp_peer,
1621 get_codec: sip_get_codec,
1624 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1625 static struct ast_udptl_protocol sip_udptl = {
1626 type: "SIP",
1627 get_udptl_info: sip_get_udptl_peer,
1628 set_udptl_peer: sip_set_udptl_peer,
1631 /*! \brief Convert transfer status to string */
1632 static char *referstatus2str(enum referstatus rstatus)
1634 int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
1635 int x;
1637 for (x = 0; x < i; x++) {
1638 if (referstatusstrings[x].status == rstatus)
1639 return (char *) referstatusstrings[x].text;
1641 return "";
1644 /*! \brief Initialize the initital request packet in the pvt structure.
1645 This packet is used for creating replies and future requests in
1646 a dialog */
1647 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
1649 if (p->initreq.headers && option_debug) {
1650 ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
1652 /* Use this as the basis */
1653 copy_request(&p->initreq, req);
1654 parse_request(&p->initreq);
1655 if (ast_test_flag(req, SIP_PKT_DEBUG))
1656 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
1659 static void sip_alreadygone(struct sip_pvt *dialog)
1661 if (option_debug > 2)
1662 ast_log(LOG_DEBUG, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
1663 ast_set_flag(&dialog->flags[0], SIP_ALREADYGONE);
1667 /*! \brief returns true if 'name' (with optional trailing whitespace)
1668 * matches the sip method 'id'.
1669 * Strictly speaking, SIP methods are case SENSITIVE, but we do
1670 * a case-insensitive comparison to be more tolerant.
1671 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1673 static int method_match(enum sipmethod id, const char *name)
1675 int len = strlen(sip_methods[id].text);
1676 int l_name = name ? strlen(name) : 0;
1677 /* true if the string is long enough, and ends with whitespace, and matches */
1678 return (l_name >= len && name[len] < 33 &&
1679 !strncasecmp(sip_methods[id].text, name, len));
1682 /*! \brief find_sip_method: Find SIP method from header */
1683 static int find_sip_method(const char *msg)
1685 int i, res = 0;
1687 if (ast_strlen_zero(msg))
1688 return 0;
1689 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
1690 if (method_match(i, msg))
1691 res = sip_methods[i].id;
1693 return res;
1696 /*! \brief Parse supported header in incoming packet */
1697 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
1699 char *next, *sep;
1700 char *temp;
1701 unsigned int profile = 0;
1702 int i, found;
1704 if (ast_strlen_zero(supported) )
1705 return 0;
1706 temp = ast_strdupa(supported);
1708 if (option_debug > 2 && sipdebug)
1709 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1711 for (next = temp; next; next = sep) {
1712 found = FALSE;
1713 if ( (sep = strchr(next, ',')) != NULL)
1714 *sep++ = '\0';
1715 next = ast_skip_blanks(next);
1716 if (option_debug > 2 && sipdebug)
1717 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1718 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
1719 if (!strcasecmp(next, sip_options[i].text)) {
1720 profile |= sip_options[i].id;
1721 found = TRUE;
1722 if (option_debug > 2 && sipdebug)
1723 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1724 break;
1727 if (!found && option_debug > 2 && sipdebug) {
1728 if (!strncasecmp(next, "x-", 2))
1729 ast_log(LOG_DEBUG, "Found private SIP option, not supported: %s\n", next);
1730 else
1731 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1735 if (pvt)
1736 pvt->sipoptions = profile;
1737 return profile;
1740 /*! \brief See if we pass debug IP filter */
1741 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
1743 if (!sipdebug)
1744 return 0;
1745 if (debugaddr.sin_addr.s_addr) {
1746 if (((ntohs(debugaddr.sin_port) != 0)
1747 && (debugaddr.sin_port != addr->sin_port))
1748 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1749 return 0;
1751 return 1;
1754 /*! \brief The real destination address for a write */
1755 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
1757 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
1760 /*! \brief Display SIP nat mode */
1761 static const char *sip_nat_mode(const struct sip_pvt *p)
1763 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
1766 /*! \brief Test PVT for debugging output */
1767 static inline int sip_debug_test_pvt(struct sip_pvt *p)
1769 if (!sipdebug)
1770 return 0;
1771 return sip_debug_test_addr(sip_real_dst(p));
1774 /*! \brief Transmit SIP message */
1775 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1777 int res;
1778 const struct sockaddr_in *dst = sip_real_dst(p);
1779 res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
1781 if (res == -1) {
1782 switch (errno) {
1783 case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
1784 case EHOSTUNREACH: /* Host can't be reached */
1785 case ENETDOWN: /* Inteface down */
1786 case ENETUNREACH: /* Network failure */
1787 case ECONNREFUSED: /* ICMP port unreachable */
1788 res = XMIT_ERROR; /* Don't bother with trying to transmit again */
1791 if (res != len)
1792 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));
1793 return res;
1797 /*! \brief Build a Via header for a request */
1798 static void build_via(struct sip_pvt *p)
1800 /* Work around buggy UNIDEN UIP200 firmware */
1801 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1803 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1804 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1805 ast_inet_ntoa(p->ourip), ourport, p->branch, rport);
1808 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1810 * Using the localaddr structure built up with localnet statements in sip.conf
1811 * apply it to their address to see if we need to substitute our
1812 * externip or can get away with our internal bindaddr
1814 static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1816 struct sockaddr_in theirs, ours;
1818 /* Get our local information */
1819 ast_ouraddrfor(them, us);
1820 theirs.sin_addr = *them;
1821 ours.sin_addr = *us;
1823 if (localaddr && externip.sin_addr.s_addr &&
1824 (ast_apply_ha(localaddr, &theirs)) &&
1825 (!global_matchexterniplocally || !ast_apply_ha(localaddr, &ours))) {
1826 if (externexpire && time(NULL) >= externexpire) {
1827 struct ast_hostent ahp;
1828 struct hostent *hp;
1830 externexpire = time(NULL) + externrefresh;
1831 if ((hp = ast_gethostbyname(externhost, &ahp))) {
1832 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1833 } else
1834 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1836 *us = externip.sin_addr;
1837 if (option_debug) {
1838 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n",
1839 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
1841 } else if (bindaddr.sin_addr.s_addr)
1842 *us = bindaddr.sin_addr;
1843 return AST_SUCCESS;
1846 /*! \brief Append to SIP dialog history
1847 \return Always returns 0 */
1848 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1850 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1851 __attribute__ ((format (printf, 2, 3)));
1853 /*! \brief Append to SIP dialog history with arg list */
1854 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1856 char buf[80], *c = buf; /* max history length */
1857 struct sip_history *hist;
1858 int l;
1860 vsnprintf(buf, sizeof(buf), fmt, ap);
1861 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1862 l = strlen(buf) + 1;
1863 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1864 return;
1865 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1866 free(hist);
1867 return;
1869 memcpy(hist->event, buf, l);
1870 if (p->history_entries == MAX_HISTORY_ENTRIES) {
1871 struct sip_history *oldest;
1872 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
1873 p->history_entries--;
1874 free(oldest);
1876 AST_LIST_INSERT_TAIL(p->history, hist, list);
1877 p->history_entries++;
1880 /*! \brief Append to SIP dialog history with arg list */
1881 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1883 va_list ap;
1885 if (!p)
1886 return;
1888 if (ast_test_flag(&p->flags[0], SIP_NO_HISTORY)
1889 && !recordhistory && !dumphistory) {
1890 return;
1893 va_start(ap, fmt);
1894 append_history_va(p, fmt, ap);
1895 va_end(ap);
1897 return;
1900 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
1901 static int retrans_pkt(const void *data)
1903 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
1904 int reschedule = DEFAULT_RETRANS;
1905 int xmitres = 0;
1907 /* Lock channel PVT */
1908 ast_mutex_lock(&pkt->owner->lock);
1910 if (pkt->retrans < MAX_RETRANS) {
1911 pkt->retrans++;
1912 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
1913 if (sipdebug && option_debug > 3)
1914 ast_log(LOG_DEBUG, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
1915 } else {
1916 int siptimer_a;
1918 if (sipdebug && option_debug > 3)
1919 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1920 if (!pkt->timer_a)
1921 pkt->timer_a = 2 ;
1922 else
1923 pkt->timer_a = 2 * pkt->timer_a;
1925 /* For non-invites, a maximum of 4 secs */
1926 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
1927 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1928 siptimer_a = 4000;
1930 /* Reschedule re-transmit */
1931 reschedule = siptimer_a;
1932 if (option_debug > 3)
1933 ast_log(LOG_DEBUG, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n", pkt->retrans +1, siptimer_a, pkt->timer_t1, pkt->retransid);
1936 if (sip_debug_test_pvt(pkt->owner)) {
1937 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
1938 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
1939 pkt->retrans, sip_nat_mode(pkt->owner),
1940 ast_inet_ntoa(dst->sin_addr),
1941 ntohs(dst->sin_port), pkt->data);
1944 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1945 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1946 ast_mutex_unlock(&pkt->owner->lock);
1947 if (xmitres == XMIT_ERROR)
1948 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
1949 else
1950 return reschedule;
1952 /* Too many retries */
1953 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
1954 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1955 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (ast_test_flag(pkt, FLAG_FATAL)) ? "Critical" : "Non-critical", (ast_test_flag(pkt, FLAG_RESPONSE)) ? "Response" : "Request");
1956 } else if ((pkt->method == SIP_OPTIONS) && sipdebug) {
1957 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1959 if (xmitres == XMIT_ERROR) {
1960 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission of transaction in call id %s \n", pkt->owner->callid);
1961 append_history(pkt->owner, "XmitErr", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1962 } else
1963 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1965 pkt->retransid = -1;
1967 if (ast_test_flag(pkt, FLAG_FATAL)) {
1968 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
1969 DEADLOCK_AVOIDANCE(&pkt->owner->lock); /* SIP_PVT, not channel */
1972 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
1973 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
1975 if (pkt->owner->owner) {
1976 sip_alreadygone(pkt->owner);
1977 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1978 ast_queue_hangup(pkt->owner->owner);
1979 ast_channel_unlock(pkt->owner->owner);
1980 } else {
1981 /* If no channel owner, destroy now */
1983 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
1984 if (pkt->method != SIP_OPTIONS) {
1985 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
1986 sip_alreadygone(pkt->owner);
1987 if (option_debug)
1988 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
1993 if (pkt->method == SIP_BYE) {
1994 /* We're not getting answers on SIP BYE's. Tear down the call anyway. */
1995 if (pkt->owner->owner)
1996 ast_channel_unlock(pkt->owner->owner);
1997 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
1998 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
2001 /* In any case, go ahead and remove the packet */
2002 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
2003 if (cur == pkt)
2004 break;
2006 if (cur) {
2007 if (prev)
2008 prev->next = cur->next;
2009 else
2010 pkt->owner->packets = cur->next;
2011 ast_mutex_unlock(&pkt->owner->lock);
2012 free(cur);
2013 pkt = NULL;
2014 } else
2015 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
2016 if (pkt)
2017 ast_mutex_unlock(&pkt->owner->lock);
2018 return 0;
2021 /*! \brief Transmit packet with retransmits
2022 \return 0 on success, -1 on failure to allocate packet
2024 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
2026 struct sip_pkt *pkt;
2027 int siptimer_a = DEFAULT_RETRANS;
2028 int xmitres = 0;
2030 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
2031 return AST_FAILURE;
2032 memcpy(pkt->data, data, len);
2033 pkt->method = sipmethod;
2034 pkt->packetlen = len;
2035 pkt->next = p->packets;
2036 pkt->owner = p;
2037 pkt->seqno = seqno;
2038 if (resp)
2039 ast_set_flag(pkt, FLAG_RESPONSE);
2040 pkt->data[len] = '\0';
2041 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
2042 pkt->retransid = -1;
2043 if (fatal)
2044 ast_set_flag(pkt, FLAG_FATAL);
2045 if (pkt->timer_t1)
2046 siptimer_a = pkt->timer_t1 * 2;
2048 if (option_debug > 3 && sipdebug)
2049 ast_log(LOG_DEBUG, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
2050 pkt->retransid = -1;
2051 pkt->next = p->packets;
2052 p->packets = pkt;
2053 if (sipmethod == SIP_INVITE) {
2054 /* Note this is a pending invite */
2055 p->pendinginvite = seqno;
2058 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
2060 if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
2061 append_history(pkt->owner, "XmitErr", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
2062 return AST_FAILURE;
2063 } else {
2064 /* Schedule retransmission */
2065 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
2066 return AST_SUCCESS;
2070 /*! \brief Kill a SIP dialog (called by scheduler) */
2071 static int __sip_autodestruct(const void *data)
2073 struct sip_pvt *p = (struct sip_pvt *)data;
2075 /* If this is a subscription, tell the phone that we got a timeout */
2076 if (p->subscribed) {
2077 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */
2078 p->subscribed = NONE;
2079 append_history(p, "Subscribestatus", "timeout");
2080 if (option_debug > 2)
2081 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
2082 return 10000; /* Reschedule this destruction so that we know that it's gone */
2085 /* If there are packets still waiting for delivery, delay the destruction */
2086 if (p->packets) {
2087 if (option_debug > 2)
2088 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
2089 append_history(p, "ReliableXmit", "timeout");
2090 return 10000;
2093 /* If we're destroying a subscription, dereference peer object too */
2094 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
2095 ASTOBJ_UNREF(p->relatedpeer,sip_destroy_peer);
2097 /* Reset schedule ID */
2098 p->autokillid = -1;
2100 if (option_debug)
2101 ast_log(LOG_DEBUG, "Auto destroying SIP dialog '%s'\n", p->callid);
2102 append_history(p, "AutoDestroy", "%s", p->callid);
2103 if (p->owner) {
2104 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
2105 ast_queue_hangup(p->owner);
2106 } else if (p->refer) {
2107 if (option_debug > 2)
2108 ast_log(LOG_DEBUG, "Finally hanging up channel after transfer: %s\n", p->callid);
2109 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2110 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
2111 } else
2112 sip_destroy(p);
2113 return 0;
2116 /*! \brief Schedule destruction of SIP dialog */
2117 static void sip_scheddestroy(struct sip_pvt *p, int ms)
2119 if (ms < 0) {
2120 if (p->timer_t1 == 0)
2121 p->timer_t1 = 500; /* Set timer T1 if not set (RFC 3261) */
2122 ms = p->timer_t1 * 64;
2124 if (sip_debug_test_pvt(p))
2125 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
2126 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
2127 append_history(p, "SchedDestroy", "%d ms", ms);
2129 AST_SCHED_DEL(sched, p->autokillid);
2130 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
2133 /*! \brief Cancel destruction of SIP dialog */
2134 static int sip_cancel_destroy(struct sip_pvt *p)
2136 int res = 0;
2137 if (p->autokillid > -1) {
2138 if (!(res = ast_sched_del(sched, p->autokillid))) {
2139 append_history(p, "CancelDestroy", "");
2140 p->autokillid = -1;
2143 return res;
2146 /*! \brief Acknowledges receipt of a packet and stops retransmission
2147 * called with p locked*/
2148 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2150 struct sip_pkt *cur, *prev = NULL;
2152 /* Just in case... */
2153 char *msg;
2154 int res = FALSE;
2156 msg = sip_methods[sipmethod].text;
2158 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
2159 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
2160 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
2161 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
2162 if (!resp && (seqno == p->pendinginvite)) {
2163 if (option_debug)
2164 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
2165 p->pendinginvite = 0;
2167 /* this is our baby */
2168 res = TRUE;
2169 UNLINK(cur, p->packets, prev);
2170 if (cur->retransid > -1) {
2171 if (sipdebug && option_debug > 3)
2172 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
2174 /* This odd section is designed to thwart a
2175 * race condition in the packet scheduler. There are
2176 * two conditions under which deleting the packet from the
2177 * scheduler can fail.
2179 * 1. The packet has been removed from the scheduler because retransmission
2180 * is being attempted. The problem is that if the packet is currently attempting
2181 * retransmission and we are at this point in the code, then that MUST mean
2182 * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
2183 * lock temporarily to allow retransmission.
2185 * 2. The packet has reached its maximum number of retransmissions and has
2186 * been permanently removed from the packet scheduler. If this is the case, then
2187 * the packet's retransid will be set to -1. The atomicity of the setting and checking
2188 * of the retransid to -1 is ensured since in both cases p's lock is held.
2190 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
2191 DEADLOCK_AVOIDANCE(&p->lock);
2193 free(cur);
2194 break;
2197 if (option_debug)
2198 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res == FALSE ? "Not Found" : "Found");
2201 /*! \brief Pretend to ack all packets
2202 * called with p locked */
2203 static void __sip_pretend_ack(struct sip_pvt *p)
2205 struct sip_pkt *cur = NULL;
2207 while (p->packets) {
2208 int method;
2209 if (cur == p->packets) {
2210 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
2211 return;
2213 cur = p->packets;
2214 method = (cur->method) ? cur->method : find_sip_method(cur->data);
2215 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method);
2219 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2220 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2222 struct sip_pkt *cur;
2223 int res = -1;
2225 for (cur = p->packets; cur; cur = cur->next) {
2226 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
2227 (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
2228 /* this is our baby */
2229 if (cur->retransid > -1) {
2230 if (option_debug > 3 && sipdebug)
2231 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
2233 AST_SCHED_DEL(sched, cur->retransid);
2234 res = 0;
2235 break;
2238 if (option_debug)
2239 ast_log(LOG_DEBUG, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
2240 return res;
2244 /*! \brief Copy SIP request, parse it */
2245 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2247 memset(dst, 0, sizeof(*dst));
2248 memcpy(dst->data, src->data, sizeof(dst->data));
2249 dst->len = src->len;
2250 parse_request(dst);
2253 /*! \brief add a blank line if no body */
2254 static void add_blank(struct sip_request *req)
2256 if (!req->lines) {
2257 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2258 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2259 req->len += strlen(req->data + req->len);
2263 /*! \brief Transmit response on SIP request*/
2264 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2266 int res;
2268 add_blank(req);
2269 if (sip_debug_test_pvt(p)) {
2270 const struct sockaddr_in *dst = sip_real_dst(p);
2272 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
2273 reliable ? "Reliably " : "", sip_nat_mode(p),
2274 ast_inet_ntoa(dst->sin_addr),
2275 ntohs(dst->sin_port), req->data);
2277 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2278 struct sip_request tmp;
2279 parse_copy(&tmp, req);
2280 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
2281 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
2283 res = (reliable) ?
2284 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2285 __sip_xmit(p, req->data, req->len);
2286 if (res > 0)
2287 return 0;
2288 return res;
2291 /*! \brief Send SIP Request to the other part of the dialogue */
2292 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2294 int res;
2296 add_blank(req);
2297 if (sip_debug_test_pvt(p)) {
2298 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
2299 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);
2300 else
2301 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);
2303 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2304 struct sip_request tmp;
2305 parse_copy(&tmp, req);
2306 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
2308 res = (reliable) ?
2309 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2310 __sip_xmit(p, req->data, req->len);
2311 return res;
2314 /*! \brief Locate closing quote in a string, skipping escaped quotes.
2315 * optionally with a limit on the search.
2316 * start must be past the first quote.
2318 static const char *find_closing_quote(const char *start, const char *lim)
2320 char last_char = '\0';
2321 const char *s;
2322 for (s = start; *s && s != lim; last_char = *s++) {
2323 if (*s == '"' && last_char != '\\')
2324 break;
2326 return s;
2329 /*! \brief Pick out text in brackets from character string
2330 \return pointer to terminated stripped string
2331 \param tmp input string that will be modified
2332 Examples:
2334 "foo" <bar> valid input, returns bar
2335 foo returns the whole string
2336 < "foo ... > returns the string between brackets
2337 < "foo... bogus (missing closing bracket), returns the whole string
2338 XXX maybe should still skip the opening bracket
2340 static char *get_in_brackets(char *tmp)
2342 const char *parse = tmp;
2343 char *first_bracket;
2346 * Skip any quoted text until we find the part in brackets.
2347 * On any error give up and return the full string.
2349 while ( (first_bracket = strchr(parse, '<')) ) {
2350 char *first_quote = strchr(parse, '"');
2352 if (!first_quote || first_quote > first_bracket)
2353 break; /* no need to look at quoted part */
2354 /* the bracket is within quotes, so ignore it */
2355 parse = find_closing_quote(first_quote + 1, NULL);
2356 if (!*parse) { /* not found, return full string ? */
2357 /* XXX or be robust and return in-bracket part ? */
2358 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
2359 break;
2361 parse++;
2363 if (first_bracket) {
2364 char *second_bracket = strchr(first_bracket + 1, '>');
2365 if (second_bracket) {
2366 *second_bracket = '\0';
2367 tmp = first_bracket + 1;
2368 } else {
2369 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
2372 return tmp;
2375 /*! \brief Send SIP MESSAGE text within a call
2376 Called from PBX core sendtext() application */
2377 static int sip_sendtext(struct ast_channel *ast, const char *text)
2379 struct sip_pvt *p = ast->tech_pvt;
2380 int debug = sip_debug_test_pvt(p);
2382 if (debug)
2383 ast_verbose("Sending text %s on %s\n", text, ast->name);
2384 if (!p)
2385 return -1;
2386 if (ast_strlen_zero(text))
2387 return 0;
2388 if (debug)
2389 ast_verbose("Really sending text %s on %s\n", text, ast->name);
2390 transmit_message_with_text(p, text);
2391 return 0;
2394 /*! \brief Update peer object in realtime storage
2395 If the Asterisk system name is set in asterisk.conf, we will use
2396 that name and store that in the "regserver" field in the sippeers
2397 table to facilitate multi-server setups.
2399 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
2401 char port[10];
2402 char ipaddr[INET_ADDRSTRLEN];
2403 char regseconds[20];
2405 char *sysname = ast_config_AST_SYSTEM_NAME;
2406 char *syslabel = NULL;
2408 time_t nowtime = time(NULL) + expirey;
2409 const char *fc = fullcontact ? "fullcontact" : NULL;
2411 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
2412 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2413 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2415 if (ast_strlen_zero(sysname)) /* No system name, disable this */
2416 sysname = NULL;
2417 else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME))
2418 syslabel = "regserver";
2420 if (fc)
2421 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2422 "port", port, "regseconds", regseconds,
2423 "username", username, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
2424 else
2425 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2426 "port", port, "regseconds", regseconds,
2427 "username", username, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
2430 /*! \brief Automatically add peer extension to dial plan */
2431 static void register_peer_exten(struct sip_peer *peer, int onoff)
2433 char multi[256];
2434 char *stringp, *ext, *context;
2436 /* XXX note that global_regcontext is both a global 'enable' flag and
2437 * the name of the global regexten context, if not specified
2438 * individually.
2440 if (ast_strlen_zero(global_regcontext))
2441 return;
2443 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
2444 stringp = multi;
2445 while ((ext = strsep(&stringp, "&"))) {
2446 if ((context = strchr(ext, '@'))) {
2447 *context++ = '\0'; /* split ext@context */
2448 if (!ast_context_find(context)) {
2449 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
2450 continue;
2452 } else {
2453 context = global_regcontext;
2455 if (onoff)
2456 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2457 ast_strdup(peer->name), ast_free, "SIP");
2458 else
2459 ast_context_remove_extension(context, ext, 1, NULL);
2463 /*! \brief Destroy peer object from memory */
2464 static void sip_destroy_peer(struct sip_peer *peer)
2466 if (option_debug > 2)
2467 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
2469 /* Delete it, it needs to disappear */
2470 if (peer->call)
2471 sip_destroy(peer->call);
2473 if (peer->mwipvt) /* We have an active subscription, delete it */
2474 sip_destroy(peer->mwipvt);
2476 if (peer->chanvars) {
2477 ast_variables_destroy(peer->chanvars);
2478 peer->chanvars = NULL;
2481 register_peer_exten(peer, FALSE);
2482 ast_free_ha(peer->ha);
2483 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
2484 apeerobjs--;
2485 else if (ast_test_flag(&peer->flags[0], SIP_REALTIME))
2486 rpeerobjs--;
2487 else
2488 speerobjs--;
2489 clear_realm_authentication(peer->auth);
2490 peer->auth = NULL;
2491 free(peer);
2494 /*! \brief Update peer data in database (if used) */
2495 static void update_peer(struct sip_peer *p, int expiry)
2497 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2498 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
2499 (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
2500 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
2505 /*! \brief realtime_peer: Get peer from realtime storage
2506 * Checks the "sippeers" realtime family from extconfig.conf
2507 * \todo Consider adding check of port address when matching here to follow the same
2508 * algorithm as for static peers. Will we break anything by adding that?
2510 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
2512 struct sip_peer *peer=NULL;
2513 struct ast_variable *var = NULL;
2514 struct ast_config *peerlist = NULL;
2515 struct ast_variable *tmp;
2516 struct ast_flags flags = {0};
2517 const char *iabuf = NULL;
2518 char portstring[6]; /*up to five digits plus null terminator*/
2519 const char *insecure;
2520 char *cat = NULL;
2521 unsigned short portnum;
2523 /* First check on peer name */
2524 if (newpeername) {
2525 var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", NULL);
2526 if (!var && sin)
2527 var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), NULL);
2528 if (!var) {
2529 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
2530 /*!\note
2531 * If this one loaded something, then we need to ensure that the host
2532 * field matched. The only reason why we can't have this as a criteria
2533 * is because we only have the IP address and the host field might be
2534 * set as a name (and the reverse PTR might not match).
2536 if (var && sin) {
2537 for (tmp = var; tmp; tmp = tmp->next) {
2538 if (!strcasecmp(tmp->name, "host")) {
2539 struct hostent *hp;
2540 struct ast_hostent ahp;
2541 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
2542 /* No match */
2543 ast_variables_destroy(var);
2544 var = NULL;
2546 break;
2553 if (!var && sin) { /* Then check on IP address */
2554 iabuf = ast_inet_ntoa(sin->sin_addr);
2555 portnum = ntohs(sin->sin_port);
2556 sprintf(portstring, "%d", portnum);
2557 var = ast_load_realtime("sippeers", "host", iabuf, "port", portstring, NULL); /* First check for fixed IP hosts */
2558 if (!var)
2559 var = ast_load_realtime("sippeers", "ipaddr", iabuf, "port", portstring, NULL); /* Then check for registered hosts */
2560 if (!var) {
2561 peerlist = ast_load_realtime_multientry("sippeers", "host", iabuf, NULL); /*No exact match, see if port is insecure, try host match first*/
2562 if(peerlist){
2563 while((cat = ast_category_browse(peerlist, cat)))
2565 insecure = ast_variable_retrieve(peerlist, cat, "insecure");
2566 set_insecure_flags(&flags, insecure, -1);
2567 if(ast_test_flag(&flags, SIP_INSECURE_PORT)) {
2568 var = ast_category_root(peerlist, cat);
2569 break;
2573 if(!var) {
2574 ast_config_destroy(peerlist);
2575 peerlist = NULL; /*for safety's sake*/
2576 cat = NULL;
2577 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", iabuf, NULL); /*No exact match, see if port is insecure, now try ip address match*/
2578 if(peerlist) {
2579 while((cat = ast_category_browse(peerlist, cat)))
2581 insecure = ast_variable_retrieve(peerlist, cat, "insecure");
2582 set_insecure_flags(&flags, insecure, -1);
2583 if(ast_test_flag(&flags, SIP_INSECURE_PORT)) {
2584 var = ast_category_root(peerlist, cat);
2585 break;
2593 if (!var) {
2594 if(peerlist)
2595 ast_config_destroy(peerlist);
2596 return NULL;
2599 for (tmp = var; tmp; tmp = tmp->next) {
2600 /* If this is type=user, then skip this object. */
2601 if (!strcasecmp(tmp->name, "type") &&
2602 !strcasecmp(tmp->value, "user")) {
2603 ast_variables_destroy(var);
2604 return NULL;
2605 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
2606 newpeername = tmp->value;
2610 if (!newpeername) { /* Did not find peer in realtime */
2611 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
2612 if(peerlist)
2613 ast_config_destroy(peerlist);
2614 else
2615 ast_variables_destroy(var);
2616 return NULL;
2619 /* Peer found in realtime, now build it in memory */
2620 peer = build_peer(newpeername, var, NULL, 1);
2621 if (!peer) {
2622 if(peerlist)
2623 ast_config_destroy(peerlist);
2624 else
2625 ast_variables_destroy(var);
2626 return NULL;
2629 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2630 /* Cache peer */
2631 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
2632 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
2633 if (!AST_SCHED_DEL(sched, peer->expire)) {
2634 struct sip_peer *peer_ptr = peer;
2635 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
2637 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, ASTOBJ_REF(peer));
2638 if (peer->expire == -1) {
2639 struct sip_peer *peer_ptr = peer;
2640 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
2643 ASTOBJ_CONTAINER_LINK(&peerl,peer);
2644 } else {
2645 ast_set_flag(&peer->flags[0], SIP_REALTIME);
2647 if(peerlist)
2648 ast_config_destroy(peerlist);
2649 else
2650 ast_variables_destroy(var);
2651 return peer;
2654 /*! \brief Support routine for find_peer */
2655 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
2657 /* We know name is the first field, so we can cast */
2658 struct sip_peer *p = (struct sip_peer *) name;
2659 return !(!inaddrcmp(&p->addr, sin) ||
2660 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
2661 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
2664 /*! \brief Locate peer by name or ip address
2665 * This is used on incoming SIP message to find matching peer on ip
2666 or outgoing message to find matching peer on name */
2667 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
2669 struct sip_peer *p = NULL;
2671 if (peer)
2672 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
2673 else
2674 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
2676 if (!p && realtime)
2677 p = realtime_peer(peer, sin);
2679 return p;
2682 /*! \brief Remove user object from in-memory storage */
2683 static void sip_destroy_user(struct sip_user *user)
2685 if (option_debug > 2)
2686 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
2687 ast_free_ha(user->ha);
2688 if (user->chanvars) {
2689 ast_variables_destroy(user->chanvars);
2690 user->chanvars = NULL;
2692 if (ast_test_flag(&user->flags[0], SIP_REALTIME))
2693 ruserobjs--;
2694 else
2695 suserobjs--;
2696 free(user);
2699 /*! \brief Load user from realtime storage
2700 * Loads user from "sipusers" category in realtime (extconfig.conf)
2701 * Users are matched on From: user name (the domain in skipped) */
2702 static struct sip_user *realtime_user(const char *username)
2704 struct ast_variable *var;
2705 struct ast_variable *tmp;
2706 struct sip_user *user = NULL;
2708 var = ast_load_realtime("sipusers", "name", username, NULL);
2710 if (!var)
2711 return NULL;
2713 for (tmp = var; tmp; tmp = tmp->next) {
2714 if (!strcasecmp(tmp->name, "type") &&
2715 !strcasecmp(tmp->value, "peer")) {
2716 ast_variables_destroy(var);
2717 return NULL;
2721 user = build_user(username, var, NULL, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2723 if (!user) { /* No user found */
2724 ast_variables_destroy(var);
2725 return NULL;
2728 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2729 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2730 suserobjs++;
2731 ASTOBJ_CONTAINER_LINK(&userl,user);
2732 } else {
2733 /* Move counter from s to r... */
2734 suserobjs--;
2735 ruserobjs++;
2736 ast_set_flag(&user->flags[0], SIP_REALTIME);
2738 ast_variables_destroy(var);
2739 return user;
2742 /*! \brief Locate user by name
2743 * Locates user by name (From: sip uri user name part) first
2744 * from in-memory list (static configuration) then from
2745 * realtime storage (defined in extconfig.conf) */
2746 static struct sip_user *find_user(const char *name, int realtime)
2748 struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
2749 if (!u && realtime)
2750 u = realtime_user(name);
2751 return u;
2754 /*! \brief Set nat mode on the various data sockets */
2755 static void do_setnat(struct sip_pvt *p, int natflags)
2757 const char *mode = natflags ? "On" : "Off";
2759 if (p->rtp) {
2760 if (option_debug)
2761 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", mode);
2762 ast_rtp_setnat(p->rtp, natflags);
2764 if (p->vrtp) {
2765 if (option_debug)
2766 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", mode);
2767 ast_rtp_setnat(p->vrtp, natflags);
2769 if (p->udptl) {
2770 if (option_debug)
2771 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", mode);
2772 ast_udptl_setnat(p->udptl, natflags);
2776 /*! \brief Create address structure from peer reference.
2777 * return -1 on error, 0 on success.
2779 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
2781 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
2782 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
2783 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
2784 dialog->recv = dialog->sa;
2785 } else
2786 return -1;
2788 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
2789 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
2790 dialog->capability = peer->capability;
2791 if ((!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(dialog->capability & AST_FORMAT_VIDEO_MASK)) && dialog->vrtp) {
2792 ast_rtp_destroy(dialog->vrtp);
2793 dialog->vrtp = NULL;
2795 dialog->prefs = peer->prefs;
2796 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
2797 dialog->t38.capability = global_t38_capability;
2798 if (dialog->udptl) {
2799 if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_FEC )
2800 dialog->t38.capability |= T38FAX_UDP_EC_FEC;
2801 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
2802 dialog->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
2803 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_NONE )
2804 dialog->t38.capability |= T38FAX_UDP_EC_NONE;
2805 dialog->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
2806 if (option_debug > 1)
2807 ast_log(LOG_DEBUG,"Our T38 capability (%d)\n", dialog->t38.capability);
2809 dialog->t38.jointcapability = dialog->t38.capability;
2810 } else if (dialog->udptl) {
2811 ast_udptl_destroy(dialog->udptl);
2812 dialog->udptl = NULL;
2814 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE );
2816 if (dialog->rtp) {
2817 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
2818 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
2819 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
2820 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
2821 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
2822 /* Set Frame packetization */
2823 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
2824 dialog->autoframing = peer->autoframing;
2826 if (dialog->vrtp) {
2827 ast_rtp_setdtmf(dialog->vrtp, 0);
2828 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
2829 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
2830 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
2831 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
2834 ast_string_field_set(dialog, peername, peer->name);
2835 ast_string_field_set(dialog, authname, peer->username);
2836 ast_string_field_set(dialog, username, peer->username);
2837 ast_string_field_set(dialog, peersecret, peer->secret);
2838 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
2839 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
2840 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
2841 ast_string_field_set(dialog, tohost, peer->tohost);
2842 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
2843 if (!dialog->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
2844 char *tmpcall;
2845 char *c;
2846 tmpcall = ast_strdupa(dialog->callid);
2847 c = strchr(tmpcall, '@');
2848 if (c) {
2849 *c = '\0';
2850 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
2853 if (ast_strlen_zero(dialog->tohost))
2854 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
2855 if (!ast_strlen_zero(peer->fromdomain))
2856 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
2857 if (!ast_strlen_zero(peer->fromuser))
2858 ast_string_field_set(dialog, fromuser, peer->fromuser);
2859 if (!ast_strlen_zero(peer->language))
2860 ast_string_field_set(dialog, language, peer->language);
2861 dialog->maxtime = peer->maxms;
2862 dialog->callgroup = peer->callgroup;
2863 dialog->pickupgroup = peer->pickupgroup;
2864 dialog->allowtransfer = peer->allowtransfer;
2865 /* Set timer T1 to RTT for this peer (if known by qualify=) */
2866 /* Minimum is settable or default to 100 ms */
2867 if (peer->maxms && peer->lastms)
2868 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
2869 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
2870 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
2871 dialog->noncodeccapability |= AST_RTP_DTMF;
2872 else
2873 dialog->noncodeccapability &= ~AST_RTP_DTMF;
2874 dialog->jointnoncodeccapability = dialog->noncodeccapability;
2875 ast_string_field_set(dialog, context, peer->context);
2876 dialog->rtptimeout = peer->rtptimeout;
2877 if (peer->call_limit)
2878 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
2879 dialog->maxcallbitrate = peer->maxcallbitrate;
2881 return 0;
2884 /*! \brief create address structure from peer name
2885 * Or, if peer not found, find it in the global DNS
2886 * returns TRUE (-1) on failure, FALSE on success */
2887 static int create_addr(struct sip_pvt *dialog, const char *opeer)
2889 struct hostent *hp;
2890 struct ast_hostent ahp;
2891 struct sip_peer *p;
2892 char *port;
2893 int portno;
2894 char host[MAXHOSTNAMELEN], *hostn;
2895 char peer[256];
2897 ast_copy_string(peer, opeer, sizeof(peer));
2898 port = strchr(peer, ':');
2899 if (port)
2900 *port++ = '\0';
2901 dialog->sa.sin_family = AF_INET;
2902 dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
2903 p = find_peer(peer, NULL, 1);
2905 if (p) {
2906 int res = create_addr_from_peer(dialog, p);
2907 ASTOBJ_UNREF(p, sip_destroy_peer);
2908 return res;
2910 hostn = peer;
2911 portno = port ? atoi(port) : STANDARD_SIP_PORT;
2912 if (srvlookup) {
2913 char service[MAXHOSTNAMELEN];
2914 int tportno;
2915 int ret;
2917 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
2918 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
2919 if (ret > 0) {
2920 hostn = host;
2921 portno = tportno;
2924 hp = ast_gethostbyname(hostn, &ahp);
2925 if (!hp) {
2926 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2927 return -1;
2929 ast_string_field_set(dialog, tohost, peer);
2930 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
2931 dialog->sa.sin_port = htons(portno);
2932 dialog->recv = dialog->sa;
2933 return 0;
2936 /*! \brief Scheduled congestion on a call */
2937 static int auto_congest(const void *nothing)
2939 struct sip_pvt *p = (struct sip_pvt *)nothing;
2941 ast_mutex_lock(&p->lock);
2942 p->initid = -1;
2943 if (p->owner) {
2944 /* XXX fails on possible deadlock */
2945 if (!ast_channel_trylock(p->owner)) {
2946 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
2947 append_history(p, "Cong", "Auto-congesting (timer)");
2948 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
2949 ast_channel_unlock(p->owner);
2952 ast_mutex_unlock(&p->lock);
2953 return 0;
2957 /*! \brief Initiate SIP call from PBX
2958 * used from the dial() application */
2959 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2961 int res, xmitres = 0;
2962 struct sip_pvt *p;
2963 struct varshead *headp;
2964 struct ast_var_t *current;
2965 const char *referer = NULL; /* SIP refererer */
2967 p = ast->tech_pvt;
2968 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2969 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2970 return -1;
2973 /* Check whether there is vxml_url, distinctive ring variables */
2974 headp=&ast->varshead;
2975 AST_LIST_TRAVERSE(headp,current,entries) {
2976 /* Check whether there is a VXML_URL variable */
2977 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2978 p->options->vxml_url = ast_var_value(current);
2979 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
2980 p->options->uri_options = ast_var_value(current);
2981 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
2982 /* Check whether there is a ALERT_INFO variable */
2983 p->options->distinctive_ring = ast_var_value(current);
2984 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2985 /* Check whether there is a variable with a name starting with SIPADDHEADER */
2986 p->options->addsipheaders = 1;
2987 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
2988 /* This is a transfered call */
2989 p->options->transfer = 1;
2990 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
2991 /* This is the referer */
2992 referer = ast_var_value(current);
2993 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
2994 /* We're replacing a call. */
2995 p->options->replaces = ast_var_value(current);
2996 } else if (!strcasecmp(ast_var_name(current), "T38CALL")) {
2997 p->t38.state = T38_LOCAL_DIRECT;
2998 if (option_debug)
2999 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
3004 res = 0;
3005 ast_set_flag(&p->flags[0], SIP_OUTGOING);
3007 if (p->options->transfer) {
3008 char buf[SIPBUFSIZE/2];
3010 if (referer) {
3011 if (sipdebug && option_debug > 2)
3012 ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->username, referer);
3013 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
3014 } else
3015 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
3016 ast_string_field_set(p, cid_name, buf);
3018 if (option_debug)
3019 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
3021 res = update_call_counter(p, INC_CALL_RINGING);
3022 if ( res != -1 ) {
3023 p->callingpres = ast->cid.cid_pres;
3024 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
3025 p->jointnoncodeccapability = p->noncodeccapability;
3027 /* If there are no audio formats left to offer, punt */
3028 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
3029 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
3030 res = -1;
3031 } else {
3032 p->t38.jointcapability = p->t38.capability;
3033 if (option_debug > 1)
3034 ast_log(LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
3035 xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
3036 if (xmitres == XMIT_ERROR)
3037 return -1; /* Transmission error */
3039 p->invitestate = INV_CALLING;
3041 /* Initialize auto-congest time */
3042 AST_SCHED_DEL(sched, p->initid);
3043 p->initid = ast_sched_add(sched, p->maxtime ? (p->maxtime * 4) : SIP_TRANS_TIMEOUT, auto_congest, p);
3046 return res;
3049 /*! \brief Destroy registry object
3050 Objects created with the register= statement in static configuration */
3051 static void sip_registry_destroy(struct sip_registry *reg)
3053 /* Really delete */
3054 if (option_debug > 2)
3055 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
3057 if (reg->call) {
3058 /* Clear registry before destroying to ensure
3059 we don't get reentered trying to grab the registry lock */
3060 reg->call->registry = NULL;
3061 if (option_debug > 2)
3062 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
3063 sip_destroy(reg->call);
3065 AST_SCHED_DEL(sched, reg->expire);
3066 AST_SCHED_DEL(sched, reg->timeout);
3067 ast_string_field_free_memory(reg);
3068 regobjs--;
3069 free(reg);
3073 /*! \brief Execute destruction of SIP dialog structure, release memory */
3074 static int __sip_destroy(struct sip_pvt *p, int lockowner)
3076 struct sip_pvt *cur, *prev = NULL;
3077 struct sip_pkt *cp;
3079 /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
3080 if (p->rtp && ast_rtp_get_bridged(p->rtp)) {
3081 ast_verbose("Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
3082 return -1;
3085 if (p->vrtp && ast_rtp_get_bridged(p->vrtp)) {
3086 ast_verbose("Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
3087 return -1;
3090 if (sip_debug_test_pvt(p) || option_debug > 2)
3091 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
3093 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
3094 update_call_counter(p, DEC_CALL_LIMIT);
3095 if (option_debug > 1)
3096 ast_log(LOG_DEBUG, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
3099 /* Unlink us from the owner if we have one */
3100 if (p->owner) {
3101 if (lockowner)
3102 ast_channel_lock(p->owner);
3103 if (option_debug)
3104 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
3105 p->owner->tech_pvt = NULL;
3106 /* Make sure that the channel knows its backend is going away */
3107 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
3108 if (lockowner)
3109 ast_channel_unlock(p->owner);
3110 /* Give the channel a chance to react before deallocation */
3111 usleep(1);
3114 /* Remove link from peer to subscription of MWI */
3115 if (p->relatedpeer) {
3116 p->relatedpeer->mwipvt = NULL;
3117 ASTOBJ_UNREF(p->relatedpeer, sip_destroy_peer);
3120 if (dumphistory)
3121 sip_dump_history(p);
3123 if (p->options)
3124 free(p->options);
3126 if (p->stateid > -1)
3127 ast_extension_state_del(p->stateid, NULL);
3128 AST_SCHED_DEL(sched, p->initid);
3129 AST_SCHED_DEL(sched, p->waitid);
3130 AST_SCHED_DEL(sched, p->autokillid);
3132 if (p->rtp) {
3133 ast_rtp_destroy(p->rtp);
3135 if (p->vrtp) {
3136 ast_rtp_destroy(p->vrtp);
3138 if (p->udptl)
3139 ast_udptl_destroy(p->udptl);
3140 if (p->refer)
3141 free(p->refer);
3142 if (p->route) {
3143 free_old_route(p->route);
3144 p->route = NULL;
3146 if (p->registry) {
3147 if (p->registry->call == p)
3148 p->registry->call = NULL;
3149 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
3152 /* Clear history */
3153 if (p->history) {
3154 struct sip_history *hist;
3155 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
3156 free(hist);
3157 p->history_entries--;
3159 free(p->history);
3160 p->history = NULL;
3163 for (prev = NULL, cur = iflist; cur; prev = cur, cur = cur->next) {
3164 if (cur == p) {
3165 UNLINK(cur, iflist, prev);
3166 break;
3169 if (!cur) {
3170 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
3171 return 0;
3174 /* remove all current packets in this dialog */
3175 while((cp = p->packets)) {
3176 p->packets = p->packets->next;
3177 AST_SCHED_DEL(sched, cp->retransid);
3178 free(cp);
3180 if (p->chanvars) {
3181 ast_variables_destroy(p->chanvars);
3182 p->chanvars = NULL;
3184 ast_mutex_destroy(&p->lock);
3186 ast_string_field_free_memory(p);
3188 free(p);
3189 return 0;
3192 /*! \brief update_call_counter: Handle call_limit for SIP users
3193 * Setting a call-limit will cause calls above the limit not to be accepted.
3195 * Remember that for a type=friend, there's one limit for the user and
3196 * another for the peer, not a combined call limit.
3197 * This will cause unexpected behaviour in subscriptions, since a "friend"
3198 * is *two* devices in Asterisk, not one.
3200 * Thought: For realtime, we should propably update storage with inuse counter...
3202 * \return 0 if call is ok (no call limit, below treshold)
3203 * -1 on rejection of call
3206 static int update_call_counter(struct sip_pvt *fup, int event)
3208 char name[256];
3209 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
3210 int outgoing = ast_test_flag(&fup->flags[1], SIP_PAGE2_OUTGOING_CALL);
3211 struct sip_user *u = NULL;
3212 struct sip_peer *p = NULL;
3214 if (option_debug > 2)
3215 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
3217 /* Test if we need to check call limits, in order to avoid
3218 realtime lookups if we do not need it */
3219 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
3220 return 0;
3222 ast_copy_string(name, fup->username, sizeof(name));
3224 /* Check the list of users only for incoming calls */
3225 if (global_limitonpeers == FALSE && !outgoing && (u = find_user(name, 1))) {
3226 inuse = &u->inUse;
3227 call_limit = &u->call_limit;
3228 inringing = NULL;
3229 } else if ( (p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, 1) ) ) { /* Try to find peer */
3230 inuse = &p->inUse;
3231 call_limit = &p->call_limit;
3232 inringing = &p->inRinging;
3233 ast_copy_string(name, fup->peername, sizeof(name));
3235 if (!p && !u) {
3236 if (option_debug > 1)
3237 ast_log(LOG_DEBUG, "%s is not a local device, no call limit\n", name);
3238 return 0;
3241 switch(event) {
3242 /* incoming and outgoing affects the inUse counter */
3243 case DEC_CALL_LIMIT:
3244 if ( *inuse > 0 ) {
3245 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
3246 (*inuse)--;
3247 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
3249 } else {
3250 *inuse = 0;
3252 if (inringing) {
3253 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3254 if (*inringing > 0)
3255 (*inringing)--;
3256 else if (!ast_test_flag(&p->flags[0], SIP_REALTIME) || ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS))
3257 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", fup->peername);
3258 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3261 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && global_notifyhold) {
3262 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
3263 sip_peer_hold(fup, 0);
3265 if (option_debug > 1 || sipdebug) {
3266 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
3268 break;
3270 case INC_CALL_RINGING:
3271 case INC_CALL_LIMIT:
3272 if (*call_limit > 0 ) {
3273 if (*inuse >= *call_limit) {
3274 ast_log(LOG_ERROR, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
3275 if (u)
3276 ASTOBJ_UNREF(u, sip_destroy_user);
3277 else
3278 ASTOBJ_UNREF(p, sip_destroy_peer);
3279 return -1;
3282 if (inringing && (event == INC_CALL_RINGING)) {
3283 if (!ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3284 (*inringing)++;
3285 ast_set_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3288 /* Continue */
3289 (*inuse)++;
3290 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
3291 if (option_debug > 1 || sipdebug) {
3292 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
3294 break;
3296 case DEC_CALL_RINGING:
3297 if (inringing) {
3298 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3299 if (*inringing > 0)
3300 (*inringing)--;
3301 else if (!ast_test_flag(&p->flags[0], SIP_REALTIME) || ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS))
3302 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", p->name);
3303 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3306 break;
3308 default:
3309 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
3311 if (p) {
3312 ast_device_state_changed("SIP/%s", p->name);
3313 ASTOBJ_UNREF(p, sip_destroy_peer);
3314 } else /* u must be set */
3315 ASTOBJ_UNREF(u, sip_destroy_user);
3316 return 0;
3319 /*! \brief Destroy SIP call structure */
3320 static void sip_destroy(struct sip_pvt *p)
3322 ast_mutex_lock(&iflock);
3323 if (option_debug > 2)
3324 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
3325 __sip_destroy(p, 1);
3326 ast_mutex_unlock(&iflock);
3329 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
3330 static int hangup_sip2cause(int cause)
3332 /* Possible values taken from causes.h */
3334 switch(cause) {
3335 case 401: /* Unauthorized */
3336 return AST_CAUSE_CALL_REJECTED;
3337 case 403: /* Not found */
3338 return AST_CAUSE_CALL_REJECTED;
3339 case 404: /* Not found */
3340 return AST_CAUSE_UNALLOCATED;
3341 case 405: /* Method not allowed */
3342 return AST_CAUSE_INTERWORKING;
3343 case 407: /* Proxy authentication required */
3344 return AST_CAUSE_CALL_REJECTED;
3345 case 408: /* No reaction */
3346 return AST_CAUSE_NO_USER_RESPONSE;
3347 case 409: /* Conflict */
3348 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
3349 case 410: /* Gone */
3350 return AST_CAUSE_UNALLOCATED;
3351 case 411: /* Length required */
3352 return AST_CAUSE_INTERWORKING;
3353 case 413: /* Request entity too large */
3354 return AST_CAUSE_INTERWORKING;
3355 case 414: /* Request URI too large */
3356 return AST_CAUSE_INTERWORKING;
3357 case 415: /* Unsupported media type */
3358 return AST_CAUSE_INTERWORKING;
3359 case 420: /* Bad extension */
3360 return AST_CAUSE_NO_ROUTE_DESTINATION;
3361 case 480: /* No answer */
3362 return AST_CAUSE_NO_ANSWER;
3363 case 481: /* No answer */
3364 return AST_CAUSE_INTERWORKING;
3365 case 482: /* Loop detected */
3366 return AST_CAUSE_INTERWORKING;
3367 case 483: /* Too many hops */
3368 return AST_CAUSE_NO_ANSWER;
3369 case 484: /* Address incomplete */
3370 return AST_CAUSE_INVALID_NUMBER_FORMAT;
3371 case 485: /* Ambigous */
3372 return AST_CAUSE_UNALLOCATED;
3373 case 486: /* Busy everywhere */
3374 return AST_CAUSE_BUSY;
3375 case 487: /* Request terminated */
3376 return AST_CAUSE_INTERWORKING;
3377 case 488: /* No codecs approved */
3378 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3379 case 491: /* Request pending */
3380 return AST_CAUSE_INTERWORKING;
3381 case 493: /* Undecipherable */
3382 return AST_CAUSE_INTERWORKING;
3383 case 500: /* Server internal failure */
3384 return AST_CAUSE_FAILURE;
3385 case 501: /* Call rejected */
3386 return AST_CAUSE_FACILITY_REJECTED;
3387 case 502:
3388 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
3389 case 503: /* Service unavailable */
3390 return AST_CAUSE_CONGESTION;
3391 case 504: /* Gateway timeout */
3392 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
3393 case 505: /* SIP version not supported */
3394 return AST_CAUSE_INTERWORKING;
3395 case 600: /* Busy everywhere */
3396 return AST_CAUSE_USER_BUSY;
3397 case 603: /* Decline */
3398 return AST_CAUSE_CALL_REJECTED;
3399 case 604: /* Does not exist anywhere */
3400 return AST_CAUSE_UNALLOCATED;
3401 case 606: /* Not acceptable */
3402 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3403 default:
3404 return AST_CAUSE_NORMAL;
3406 /* Never reached */
3407 return 0;
3410 /*! \brief Convert Asterisk hangup causes to SIP codes
3411 \verbatim
3412 Possible values from causes.h
3413 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
3414 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
3416 In addition to these, a lot of PRI codes is defined in causes.h
3417 ...should we take care of them too ?
3419 Quote RFC 3398
3421 ISUP Cause value SIP response
3422 ---------------- ------------
3423 1 unallocated number 404 Not Found
3424 2 no route to network 404 Not found
3425 3 no route to destination 404 Not found
3426 16 normal call clearing --- (*)
3427 17 user busy 486 Busy here
3428 18 no user responding 408 Request Timeout
3429 19 no answer from the user 480 Temporarily unavailable
3430 20 subscriber absent 480 Temporarily unavailable
3431 21 call rejected 403 Forbidden (+)
3432 22 number changed (w/o diagnostic) 410 Gone
3433 22 number changed (w/ diagnostic) 301 Moved Permanently
3434 23 redirection to new destination 410 Gone
3435 26 non-selected user clearing 404 Not Found (=)
3436 27 destination out of order 502 Bad Gateway
3437 28 address incomplete 484 Address incomplete
3438 29 facility rejected 501 Not implemented
3439 31 normal unspecified 480 Temporarily unavailable
3440 \endverbatim
3442 static const char *hangup_cause2sip(int cause)
3444 switch (cause) {
3445 case AST_CAUSE_UNALLOCATED: /* 1 */
3446 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
3447 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
3448 return "404 Not Found";
3449 case AST_CAUSE_CONGESTION: /* 34 */
3450 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
3451 return "503 Service Unavailable";
3452 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
3453 return "408 Request Timeout";
3454 case AST_CAUSE_NO_ANSWER: /* 19 */
3455 return "480 Temporarily unavailable";
3456 case AST_CAUSE_CALL_REJECTED: /* 21 */
3457 return "403 Forbidden";
3458 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
3459 return "410 Gone";
3460 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
3461 return "480 Temporarily unavailable";
3462 case AST_CAUSE_INVALID_NUMBER_FORMAT:
3463 return "484 Address incomplete";
3464 case AST_CAUSE_USER_BUSY:
3465 return "486 Busy here";
3466 case AST_CAUSE_FAILURE:
3467 return "500 Server internal failure";
3468 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
3469 return "501 Not Implemented";
3470 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
3471 return "503 Service Unavailable";
3472 /* Used in chan_iax2 */
3473 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
3474 return "502 Bad Gateway";
3475 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
3476 return "488 Not Acceptable Here";
3478 case AST_CAUSE_NOTDEFINED:
3479 default:
3480 if (option_debug)
3481 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
3482 return NULL;
3485 /* Never reached */
3486 return 0;
3490 /*! \brief sip_hangup: Hangup SIP call
3491 * Part of PBX interface, called from ast_hangup */
3492 static int sip_hangup(struct ast_channel *ast)
3494 struct sip_pvt *p = ast->tech_pvt;
3495 int needcancel = FALSE;
3496 int needdestroy = 0;
3497 struct ast_channel *oldowner = ast;
3499 if (!p) {
3500 if (option_debug)
3501 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
3502 return 0;
3505 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
3506 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
3507 if (option_debug && sipdebug)
3508 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
3509 update_call_counter(p, DEC_CALL_LIMIT);
3511 if (option_debug >3)
3512 ast_log(LOG_DEBUG, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
3513 if (p->autokillid > -1 && sip_cancel_destroy(p))
3514 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
3515 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3516 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
3517 ast_clear_flag(&p->flags[0], SIP_NEEDDESTROY);
3518 p->owner->tech_pvt = NULL;
3519 p->owner = NULL; /* Owner will be gone after we return, so take it away */
3520 return 0;
3522 if (option_debug) {
3523 if (ast_test_flag(ast, AST_FLAG_ZOMBIE) && p->refer && option_debug)
3524 ast_log(LOG_DEBUG, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
3525 else {
3526 if (option_debug)
3527 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
3530 if (option_debug && ast_test_flag(ast, AST_FLAG_ZOMBIE))
3531 ast_log(LOG_DEBUG, "Hanging up zombie call. Be scared.\n");
3533 ast_mutex_lock(&p->lock);
3534 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
3535 if (option_debug && sipdebug)
3536 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
3537 update_call_counter(p, DEC_CALL_LIMIT);
3540 /* Determine how to disconnect */
3541 if (p->owner != ast) {
3542 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
3543 ast_mutex_unlock(&p->lock);
3544 return 0;
3546 /* If the call is not UP, we need to send CANCEL instead of BYE */
3547 if (ast->_state == AST_STATE_RING || ast->_state == AST_STATE_RINGING || (p->invitestate < INV_COMPLETED && ast->_state != AST_STATE_UP)) {
3548 needcancel = TRUE;
3549 if (option_debug > 3)
3550 ast_log(LOG_DEBUG, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
3553 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
3555 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->owner->hangupcause) : "Unknown");
3557 /* Disconnect */
3558 if (p->vad)
3559 ast_dsp_free(p->vad);
3561 p->owner = NULL;
3562 ast->tech_pvt = NULL;
3564 ast_module_unref(ast_module_info->self);
3566 /* Do not destroy this pvt until we have timeout or
3567 get an answer to the BYE or INVITE/CANCEL
3568 If we get no answer during retransmit period, drop the call anyway.
3569 (Sorry, mother-in-law, you can't deny a hangup by sending
3570 603 declined to BYE...)
3572 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE))
3573 needdestroy = 1; /* Set destroy flag at end of this function */
3574 else if (p->invitestate != INV_CALLING)
3575 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3577 /* Start the process if it's not already started */
3578 if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
3579 if (needcancel) { /* Outgoing call, not up */
3580 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3581 /* stop retransmitting an INVITE that has not received a response */
3582 __sip_pretend_ack(p);
3583 p->invitestate = INV_CANCELLED;
3585 /* if we can't send right now, mark it pending */
3586 if (p->invitestate == INV_CALLING) {
3587 /* We can't send anything in CALLING state */
3588 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3589 /* Do we need a timer here if we don't hear from them at all? Yes we do or else we will get hung dialogs and those are no fun. */
3590 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3591 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
3592 } else {
3593 /* Send a new request: CANCEL */
3594 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
3595 /* Actually don't destroy us yet, wait for the 487 on our original
3596 INVITE, but do set an autodestruct just in case we never get it. */
3597 needdestroy = 0;
3598 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3600 if ( p->initid != -1 ) {
3601 /* channel still up - reverse dec of inUse counter
3602 only if the channel is not auto-congested */
3603 update_call_counter(p, INC_CALL_LIMIT);
3605 } else { /* Incoming call, not up */
3606 const char *res;
3607 if (ast->hangupcause && (res = hangup_cause2sip(ast->hangupcause)))
3608 transmit_response_reliable(p, res, &p->initreq);
3609 else
3610 transmit_response_reliable(p, "603 Declined", &p->initreq);
3611 p->invitestate = INV_TERMINATED;
3613 } else { /* Call is in UP state, send BYE */
3614 if (!p->pendinginvite) {
3615 char *audioqos = "";
3616 char *videoqos = "";
3617 if (p->rtp)
3618 audioqos = ast_rtp_get_quality(p->rtp, NULL);
3619 if (p->vrtp)
3620 videoqos = ast_rtp_get_quality(p->vrtp, NULL);
3621 /* Send a hangup */
3622 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3624 /* Get RTCP quality before end of call */
3625 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
3626 if (p->rtp)
3627 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
3628 if (p->vrtp)
3629 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
3631 if (p->rtp && oldowner)
3632 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
3633 if (p->vrtp && oldowner)
3634 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
3635 } else {
3636 /* Note we will need a BYE when this all settles out
3637 but we can't send one while we have "INVITE" outstanding. */
3638 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3639 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
3640 AST_SCHED_DEL(sched, p->waitid);
3641 if (sip_cancel_destroy(p))
3642 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
3646 if (needdestroy)
3647 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
3648 ast_mutex_unlock(&p->lock);
3649 return 0;
3652 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
3653 static void try_suggested_sip_codec(struct sip_pvt *p)
3655 int fmt;
3656 const char *codec;
3658 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
3659 if (!codec)
3660 return;
3662 fmt = ast_getformatbyname(codec);
3663 if (fmt) {
3664 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
3665 if (p->jointcapability & fmt) {
3666 p->jointcapability &= fmt;
3667 p->capability &= fmt;
3668 } else
3669 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
3670 } else
3671 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
3672 return;
3675 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
3676 * Part of PBX interface */
3677 static int sip_answer(struct ast_channel *ast)
3679 int res = 0;
3680 struct sip_pvt *p = ast->tech_pvt;
3682 ast_mutex_lock(&p->lock);
3683 if (ast->_state != AST_STATE_UP) {
3684 try_suggested_sip_codec(p);
3686 ast_setstate(ast, AST_STATE_UP);
3687 if (option_debug)
3688 ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name);
3689 if (p->t38.state == T38_PEER_DIRECT) {
3690 p->t38.state = T38_ENABLED;
3691 if (option_debug > 1)
3692 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
3693 res = transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
3694 } else {
3695 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
3698 ast_mutex_unlock(&p->lock);
3699 return res;
3702 /*! \brief Send frame to media channel (rtp) */
3703 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
3705 struct sip_pvt *p = ast->tech_pvt;
3706 int res = 0;
3708 switch (frame->frametype) {
3709 case AST_FRAME_VOICE:
3710 if (!(frame->subclass & ast->nativeformats)) {
3711 char s1[512], s2[512], s3[512];
3712 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
3713 frame->subclass,
3714 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
3715 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
3716 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
3717 ast->readformat,
3718 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
3719 ast->writeformat);
3720 return 0;
3722 if (p) {
3723 ast_mutex_lock(&p->lock);
3724 if (p->rtp) {
3725 /* If channel is not up, activate early media session */
3726 if ((ast->_state != AST_STATE_UP) &&
3727 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3728 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3729 ast_rtp_new_source(p->rtp);
3730 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3731 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3733 p->lastrtptx = time(NULL);
3734 res = ast_rtp_write(p->rtp, frame);
3736 ast_mutex_unlock(&p->lock);
3738 break;
3739 case AST_FRAME_VIDEO:
3740 if (p) {
3741 ast_mutex_lock(&p->lock);
3742 if (p->vrtp) {
3743 /* Activate video early media */
3744 if ((ast->_state != AST_STATE_UP) &&
3745 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3746 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3747 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3748 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3750 p->lastrtptx = time(NULL);
3751 res = ast_rtp_write(p->vrtp, frame);
3753 ast_mutex_unlock(&p->lock);
3755 break;
3756 case AST_FRAME_IMAGE:
3757 return 0;
3758 break;
3759 case AST_FRAME_MODEM:
3760 if (p) {
3761 ast_mutex_lock(&p->lock);
3762 /* UDPTL requires two-way communication, so early media is not needed here.
3763 we simply forget the frames if we get modem frames before the bridge is up.
3764 Fax will re-transmit.
3766 if (p->udptl && ast->_state == AST_STATE_UP)
3767 res = ast_udptl_write(p->udptl, frame);
3768 ast_mutex_unlock(&p->lock);
3770 break;
3771 default:
3772 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
3773 return 0;
3776 return res;
3779 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
3780 Basically update any ->owner links */
3781 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
3783 int ret = -1;
3784 struct sip_pvt *p;
3786 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE) && option_debug)
3787 ast_log(LOG_DEBUG, "New channel is zombie\n");
3788 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE) && option_debug)
3789 ast_log(LOG_DEBUG, "Old channel is zombie\n");
3791 if (!newchan || !newchan->tech_pvt) {
3792 if (!newchan)
3793 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
3794 else
3795 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
3796 return -1;
3798 p = newchan->tech_pvt;
3800 if (!p) {
3801 ast_log(LOG_WARNING, "No pvt after masquerade. Strange things may happen\n");
3802 return -1;
3805 ast_mutex_lock(&p->lock);
3806 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
3807 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
3808 if (p->owner != oldchan)
3809 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
3810 else {
3811 p->owner = newchan;
3812 /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
3813 RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
3814 able to do this if the masquerade happens before the bridge breaks (e.g., AMI
3815 redirect of both channels). Note that a channel can not be masqueraded *into*
3816 a native bridge. So there is no danger that this breaks a native bridge that
3817 should stay up. */
3818 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0);
3819 ret = 0;
3821 if (option_debug > 2)
3822 ast_log(LOG_DEBUG, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
3824 ast_mutex_unlock(&p->lock);
3825 return ret;
3828 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
3830 struct sip_pvt *p = ast->tech_pvt;
3831 int res = 0;
3833 ast_mutex_lock(&p->lock);
3834 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
3835 case SIP_DTMF_INBAND:
3836 res = -1; /* Tell Asterisk to generate inband indications */
3837 break;
3838 case SIP_DTMF_RFC2833:
3839 if (p->rtp)
3840 ast_rtp_senddigit_begin(p->rtp, digit);
3841 break;
3842 default:
3843 break;
3845 ast_mutex_unlock(&p->lock);
3847 return res;
3850 /*! \brief Send DTMF character on SIP channel
3851 within one call, we're able to transmit in many methods simultaneously */
3852 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
3854 struct sip_pvt *p = ast->tech_pvt;
3855 int res = 0;
3857 ast_mutex_lock(&p->lock);
3858 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
3859 case SIP_DTMF_INFO:
3860 transmit_info_with_digit(p, digit, duration);
3861 break;
3862 case SIP_DTMF_RFC2833:
3863 if (p->rtp)
3864 ast_rtp_senddigit_end(p->rtp, digit);
3865 break;
3866 case SIP_DTMF_INBAND:
3867 res = -1; /* Tell Asterisk to stop inband indications */
3868 break;
3870 ast_mutex_unlock(&p->lock);
3872 return res;
3875 /*! \brief Transfer SIP call */
3876 static int sip_transfer(struct ast_channel *ast, const char *dest)
3878 struct sip_pvt *p = ast->tech_pvt;
3879 int res;
3881 if (dest == NULL) /* functions below do not take a NULL */
3882 dest = "";
3883 ast_mutex_lock(&p->lock);
3884 if (ast->_state == AST_STATE_RING)
3885 res = sip_sipredirect(p, dest);
3886 else
3887 res = transmit_refer(p, dest);
3888 ast_mutex_unlock(&p->lock);
3889 return res;
3892 /*! \brief Play indication to user
3893 * With SIP a lot of indications is sent as messages, letting the device play
3894 the indication - busy signal, congestion etc
3895 \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
3897 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
3899 struct sip_pvt *p = ast->tech_pvt;
3900 int res = 0;
3902 ast_mutex_lock(&p->lock);
3903 switch(condition) {
3904 case AST_CONTROL_RINGING:
3905 if (ast->_state == AST_STATE_RING) {
3906 p->invitestate = INV_EARLY_MEDIA;
3907 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
3908 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
3909 /* Send 180 ringing if out-of-band seems reasonable */
3910 transmit_response(p, "180 Ringing", &p->initreq);
3911 ast_set_flag(&p->flags[0], SIP_RINGING);
3912 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
3913 break;
3914 } else {
3915 /* Well, if it's not reasonable, just send in-band */
3918 res = -1;
3919 break;
3920 case AST_CONTROL_BUSY:
3921 if (ast->_state != AST_STATE_UP) {
3922 transmit_response(p, "486 Busy Here", &p->initreq);
3923 p->invitestate = INV_COMPLETED;
3924 sip_alreadygone(p);
3925 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
3926 break;
3928 res = -1;
3929 break;
3930 case AST_CONTROL_CONGESTION:
3931 if (ast->_state != AST_STATE_UP) {
3932 transmit_response(p, "503 Service Unavailable", &p->initreq);
3933 p->invitestate = INV_COMPLETED;
3934 sip_alreadygone(p);
3935 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
3936 break;
3938 res = -1;
3939 break;
3940 case AST_CONTROL_PROCEEDING:
3941 if ((ast->_state != AST_STATE_UP) &&
3942 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3943 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3944 transmit_response(p, "100 Trying", &p->initreq);
3945 p->invitestate = INV_PROCEEDING;
3946 break;
3948 res = -1;
3949 break;
3950 case AST_CONTROL_PROGRESS:
3951 if ((ast->_state != AST_STATE_UP) &&
3952 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3953 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3954 p->invitestate = INV_EARLY_MEDIA;
3955 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3956 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3957 break;
3959 res = -1;
3960 break;
3961 case AST_CONTROL_HOLD:
3962 ast_rtp_new_source(p->rtp);
3963 ast_moh_start(ast, data, p->mohinterpret);
3964 break;
3965 case AST_CONTROL_UNHOLD:
3966 ast_rtp_new_source(p->rtp);
3967 ast_moh_stop(ast);
3968 break;
3969 case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
3970 if (p->vrtp && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
3971 transmit_info_with_vidupdate(p);
3972 /* ast_rtcp_send_h261fur(p->vrtp); */
3973 } else
3974 res = -1;
3975 break;
3976 case AST_CONTROL_SRCUPDATE:
3977 ast_rtp_new_source(p->rtp);
3978 break;
3979 case -1:
3980 res = -1;
3981 break;
3982 default:
3983 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
3984 res = -1;
3985 break;
3987 ast_mutex_unlock(&p->lock);
3988 return res;
3992 /*! \brief Initiate a call in the SIP channel
3993 called from sip_request_call (calls from the pbx ) for outbound channels
3994 and from handle_request_invite for inbound channels
3997 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
3999 struct ast_channel *tmp;
4000 struct ast_variable *v = NULL;
4001 int fmt;
4002 int what;
4003 int needvideo = 0, video = 0;
4004 char *decoded_exten;
4006 const char *my_name; /* pick a good name */
4008 if (title)
4009 my_name = title;
4010 else if ( (my_name = strchr(i->fromdomain,':')) )
4011 my_name++; /* skip ':' */
4012 else
4013 my_name = i->fromdomain;
4015 ast_mutex_unlock(&i->lock);
4016 /* Don't hold a sip pvt lock while we allocate a channel */
4017 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);
4020 if (!tmp) {
4021 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
4022 ast_mutex_lock(&i->lock);
4023 return NULL;
4025 ast_mutex_lock(&i->lock);
4027 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO)
4028 tmp->tech = &sip_tech_info;
4029 else
4030 tmp->tech = &sip_tech;
4032 /* Select our native format based on codec preference until we receive
4033 something from another device to the contrary. */
4034 if (i->jointcapability) { /* The joint capabilities of us and peer */
4035 what = i->jointcapability;
4036 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
4037 } else if (i->capability) { /* Our configured capability for this peer */
4038 what = i->capability;
4039 video = i->capability & AST_FORMAT_VIDEO_MASK;
4040 } else {
4041 what = global_capability; /* Global codec support */
4042 video = global_capability & AST_FORMAT_VIDEO_MASK;
4045 /* Set the native formats for audio and merge in video */
4046 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video;
4047 if (option_debug > 2) {
4048 char buf[SIPBUFSIZE];
4049 ast_log(LOG_DEBUG, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
4050 ast_log(LOG_DEBUG, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
4051 ast_log(LOG_DEBUG, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
4052 ast_log(LOG_DEBUG, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
4053 if (i->prefcodec)
4054 ast_log(LOG_DEBUG, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
4057 /* XXX Why are we choosing a codec from the native formats?? */
4058 fmt = ast_best_codec(tmp->nativeformats);
4060 /* If we have a prefcodec setting, we have an inbound channel that set a
4061 preferred format for this call. Otherwise, we check the jointcapability
4062 We also check for vrtp. If it's not there, we are not allowed do any video anyway.
4064 if (i->vrtp) {
4065 if (i->prefcodec)
4066 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK; /* Outbound call */
4067 else
4068 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK; /* Inbound call */
4071 if (option_debug > 2) {
4072 if (needvideo)
4073 ast_log(LOG_DEBUG, "This channel can handle video! HOLLYWOOD next!\n");
4074 else
4075 ast_log(LOG_DEBUG, "This channel will not be able to handle video.\n");
4080 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
4081 i->vad = ast_dsp_new();
4082 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
4083 if (global_relaxdtmf)
4084 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
4086 if (i->rtp) {
4087 tmp->fds[0] = ast_rtp_fd(i->rtp);
4088 tmp->fds[1] = ast_rtcp_fd(i->rtp);
4090 if (needvideo && i->vrtp) {
4091 tmp->fds[2] = ast_rtp_fd(i->vrtp);
4092 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
4094 if (i->udptl) {
4095 tmp->fds[5] = ast_udptl_fd(i->udptl);
4097 if (state == AST_STATE_RING)
4098 tmp->rings = 1;
4099 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
4100 tmp->writeformat = fmt;
4101 tmp->rawwriteformat = fmt;
4102 tmp->readformat = fmt;
4103 tmp->rawreadformat = fmt;
4104 tmp->tech_pvt = i;
4106 tmp->callgroup = i->callgroup;
4107 tmp->pickupgroup = i->pickupgroup;
4108 tmp->cid.cid_pres = i->callingpres;
4109 if (!ast_strlen_zero(i->accountcode))
4110 ast_string_field_set(tmp, accountcode, i->accountcode);
4111 if (i->amaflags)
4112 tmp->amaflags = i->amaflags;
4113 if (!ast_strlen_zero(i->language))
4114 ast_string_field_set(tmp, language, i->language);
4115 i->owner = tmp;
4116 ast_module_ref(ast_module_info->self);
4117 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
4118 /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
4119 * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
4120 * structure so that there aren't issues when forming URI's
4122 decoded_exten = ast_strdupa(i->exten);
4123 ast_uri_decode(decoded_exten);
4124 ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
4126 /* Don't use ast_set_callerid() here because it will
4127 * generate an unnecessary NewCallerID event */
4128 tmp->cid.cid_ani = ast_strdup(i->cid_num);
4129 if (!ast_strlen_zero(i->rdnis))
4130 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
4132 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
4133 tmp->cid.cid_dnid = ast_strdup(i->exten);
4135 tmp->priority = 1;
4136 if (!ast_strlen_zero(i->uri))
4137 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
4138 if (!ast_strlen_zero(i->domain))
4139 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
4140 if (!ast_strlen_zero(i->useragent))
4141 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
4142 if (!ast_strlen_zero(i->callid))
4143 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
4144 if (i->rtp)
4145 ast_jb_configure(tmp, &global_jbconf);
4147 /* If the INVITE contains T.38 SDP information set the proper channel variable so a created outgoing call will also have T.38 */
4148 if (i->udptl && i->t38.state == T38_PEER_DIRECT)
4149 pbx_builtin_setvar_helper(tmp, "_T38CALL", "1");
4151 /* Set channel variables for this call from configuration */
4152 for (v = i->chanvars ; v ; v = v->next)
4153 pbx_builtin_setvar_helper(tmp, v->name, v->value);
4155 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
4156 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
4157 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
4158 ast_hangup(tmp);
4159 tmp = NULL;
4162 if (!ast_test_flag(&i->flags[0], SIP_NO_HISTORY))
4163 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
4165 return tmp;
4168 /*! \brief Reads one line of SIP message body */
4169 static char *get_body_by_line(const char *line, const char *name, int nameLen)
4171 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=')
4172 return ast_skip_blanks(line + nameLen + 1);
4174 return "";
4177 /*! \brief Lookup 'name' in the SDP starting
4178 * at the 'start' line. Returns the matching line, and 'start'
4179 * is updated with the next line number.
4181 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
4183 int len = strlen(name);
4185 while (*start < req->sdp_end) {
4186 const char *r = get_body_by_line(req->line[(*start)++], name, len);
4187 if (r[0] != '\0')
4188 return r;
4191 return "";
4194 /*! \brief Get a line from an SDP message body */
4195 static const char *get_sdp(struct sip_request *req, const char *name)
4197 int dummy = 0;
4199 return get_sdp_iterate(&dummy, req, name);
4202 /*! \brief Get a specific line from the message body */
4203 static char *get_body(struct sip_request *req, char *name)
4205 int x;
4206 int len = strlen(name);
4207 char *r;
4209 for (x = 0; x < req->lines; x++) {
4210 r = get_body_by_line(req->line[x], name, len);
4211 if (r[0] != '\0')
4212 return r;
4215 return "";
4218 /*! \brief Find compressed SIP alias */
4219 static const char *find_alias(const char *name, const char *_default)
4221 /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
4222 static const struct cfalias {
4223 char * const fullname;
4224 char * const shortname;
4225 } aliases[] = {
4226 { "Content-Type", "c" },
4227 { "Content-Encoding", "e" },
4228 { "From", "f" },
4229 { "Call-ID", "i" },
4230 { "Contact", "m" },
4231 { "Content-Length", "l" },
4232 { "Subject", "s" },
4233 { "To", "t" },
4234 { "Supported", "k" },
4235 { "Refer-To", "r" },
4236 { "Referred-By", "b" },
4237 { "Allow-Events", "u" },
4238 { "Event", "o" },
4239 { "Via", "v" },
4240 { "Accept-Contact", "a" },
4241 { "Reject-Contact", "j" },
4242 { "Request-Disposition", "d" },
4243 { "Session-Expires", "x" },
4244 { "Identity", "y" },
4245 { "Identity-Info", "n" },
4247 int x;
4249 for (x=0; x<sizeof(aliases) / sizeof(aliases[0]); x++)
4250 if (!strcasecmp(aliases[x].fullname, name))
4251 return aliases[x].shortname;
4253 return _default;
4256 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
4258 int pass;
4261 * Technically you can place arbitrary whitespace both before and after the ':' in
4262 * a header, although RFC3261 clearly says you shouldn't before, and place just
4263 * one afterwards. If you shouldn't do it, what absolute idiot decided it was
4264 * a good idea to say you can do it, and if you can do it, why in the hell would.
4265 * you say you shouldn't.
4266 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
4267 * and we always allow spaces after that for compatibility.
4269 for (pass = 0; name && pass < 2;pass++) {
4270 int x, len = strlen(name);
4271 for (x=*start; x<req->headers; x++) {
4272 if (!strncasecmp(req->header[x], name, len)) {
4273 char *r = req->header[x] + len; /* skip name */
4274 if (pedanticsipchecking)
4275 r = ast_skip_blanks(r);
4277 if (*r == ':') {
4278 *start = x+1;
4279 return ast_skip_blanks(r+1);
4283 if (pass == 0) /* Try aliases */
4284 name = find_alias(name, NULL);
4287 /* Don't return NULL, so get_header is always a valid pointer */
4288 return "";
4291 /*! \brief Get header from SIP request */
4292 static const char *get_header(const struct sip_request *req, const char *name)
4294 int start = 0;
4295 return __get_header(req, name, &start);
4298 /*! \brief Read RTP from network */
4299 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
4301 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
4302 struct ast_frame *f;
4304 if (!p->rtp) {
4305 /* We have no RTP allocated for this channel */
4306 return &ast_null_frame;
4309 switch(ast->fdno) {
4310 case 0:
4311 f = ast_rtp_read(p->rtp); /* RTP Audio */
4312 break;
4313 case 1:
4314 f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
4315 break;
4316 case 2:
4317 f = ast_rtp_read(p->vrtp); /* RTP Video */
4318 break;
4319 case 3:
4320 f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
4321 break;
4322 case 5:
4323 f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
4324 break;
4325 default:
4326 f = &ast_null_frame;
4328 /* Don't forward RFC2833 if we're not supposed to */
4329 if (f && (f->frametype == AST_FRAME_DTMF) &&
4330 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833))
4331 return &ast_null_frame;
4333 /* We already hold the channel lock */
4334 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
4335 return f;
4337 if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
4338 if (!(f->subclass & p->jointcapability)) {
4339 if (option_debug) {
4340 ast_log(LOG_DEBUG, "Bogus frame of format '%s' received from '%s'!\n",
4341 ast_getformatname(f->subclass), p->owner->name);
4343 return &ast_null_frame;
4345 if (option_debug)
4346 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
4347 p->owner->nativeformats = (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
4348 ast_set_read_format(p->owner, p->owner->readformat);
4349 ast_set_write_format(p->owner, p->owner->writeformat);
4352 if (f && (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
4353 f = ast_dsp_process(p->owner, p->vad, f);
4354 if (f && f->frametype == AST_FRAME_DTMF) {
4355 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && f->subclass == 'f') {
4356 if (option_debug)
4357 ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
4358 *faxdetect = 1;
4359 } else if (option_debug) {
4360 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
4365 return f;
4368 /*! \brief Read SIP RTP from channel */
4369 static struct ast_frame *sip_read(struct ast_channel *ast)
4371 struct ast_frame *fr;
4372 struct sip_pvt *p = ast->tech_pvt;
4373 int faxdetected = FALSE;
4375 ast_mutex_lock(&p->lock);
4376 fr = sip_rtp_read(ast, p, &faxdetected);
4377 p->lastrtprx = time(NULL);
4379 /* If we are NOT bridged to another channel, and we have detected fax tone we issue T38 re-invite to a peer */
4380 /* 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 */
4381 if (faxdetected && ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && (p->t38.state == T38_DISABLED) && !(ast_bridged_channel(ast))) {
4382 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
4383 if (!p->pendinginvite) {
4384 if (option_debug > 2)
4385 ast_log(LOG_DEBUG, "Sending reinvite on SIP (%s) for T.38 negotiation.\n",ast->name);
4386 p->t38.state = T38_LOCAL_REINVITE;
4387 transmit_reinvite_with_t38_sdp(p);
4388 if (option_debug > 1)
4389 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, ast->name);
4391 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
4392 if (option_debug > 2)
4393 ast_log(LOG_DEBUG, "Deferring reinvite on SIP (%s) - it will be re-negotiated for T.38\n", ast->name);
4394 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
4398 /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
4399 if (fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
4400 fr = &ast_null_frame;
4403 ast_mutex_unlock(&p->lock);
4404 return fr;
4408 /*! \brief Generate 32 byte random string for callid's etc */
4409 static char *generate_random_string(char *buf, size_t size)
4411 long val[4];
4412 int x;
4414 for (x=0; x<4; x++)
4415 val[x] = ast_random();
4416 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
4418 return buf;
4421 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
4422 static void build_callid_pvt(struct sip_pvt *pvt)
4424 char buf[33];
4426 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip));
4428 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
4432 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
4433 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
4435 char buf[33];
4437 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
4439 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
4442 /*! \brief Make our SIP dialog tag */
4443 static void make_our_tag(char *tagbuf, size_t len)
4445 snprintf(tagbuf, len, "as%08lx", ast_random());
4448 /*! \brief Allocate SIP_PVT structure and set defaults */
4449 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
4450 int useglobal_nat, const int intended_method)
4452 struct sip_pvt *p;
4454 if (!(p = ast_calloc(1, sizeof(*p))))
4455 return NULL;
4457 if (ast_string_field_init(p, 512)) {
4458 free(p);
4459 return NULL;
4462 ast_mutex_init(&p->lock);
4464 p->method = intended_method;
4465 p->initid = -1;
4466 p->waitid = -1;
4467 p->autokillid = -1;
4468 p->subscribed = NONE;
4469 p->stateid = -1;
4470 p->prefs = default_prefs; /* Set default codecs for this call */
4472 if (intended_method != SIP_OPTIONS) /* Peerpoke has it's own system */
4473 p->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
4475 if (sin) {
4476 p->sa = *sin;
4477 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
4478 p->ourip = __ourip;
4479 } else
4480 p->ourip = __ourip;
4482 /* Copy global flags to this PVT at setup. */
4483 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
4484 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
4486 ast_set2_flag(&p->flags[0], !recordhistory, SIP_NO_HISTORY);
4488 p->branch = ast_random();
4489 make_our_tag(p->tag, sizeof(p->tag));
4490 p->ocseq = INITIAL_CSEQ;
4492 if (sip_methods[intended_method].need_rtp) {
4493 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
4494 /* If the global videosupport flag is on, we always create a RTP interface for video */
4495 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
4496 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
4497 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
4498 p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
4499 if (!p->rtp || (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)) {
4500 ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n",
4501 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video" : "", strerror(errno));
4502 ast_mutex_destroy(&p->lock);
4503 if (p->chanvars) {
4504 ast_variables_destroy(p->chanvars);
4505 p->chanvars = NULL;
4507 free(p);
4508 return NULL;
4510 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
4511 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
4512 ast_rtp_settos(p->rtp, global_tos_audio);
4513 ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
4514 ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
4515 ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
4516 if (p->vrtp) {
4517 ast_rtp_settos(p->vrtp, global_tos_video);
4518 ast_rtp_setdtmf(p->vrtp, 0);
4519 ast_rtp_setdtmfcompensate(p->vrtp, 0);
4520 ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
4521 ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
4522 ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
4524 if (p->udptl)
4525 ast_udptl_settos(p->udptl, global_tos_audio);
4526 p->maxcallbitrate = default_maxcallbitrate;
4527 p->autoframing = global_autoframing;
4528 ast_rtp_codec_setpref(p->rtp, &p->prefs);
4531 if (useglobal_nat && sin) {
4532 /* Setup NAT structure according to global settings if we have an address */
4533 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
4534 p->recv = *sin;
4535 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
4538 if (p->method != SIP_REGISTER)
4539 ast_string_field_set(p, fromdomain, default_fromdomain);
4540 build_via(p);
4541 if (!callid)
4542 build_callid_pvt(p);
4543 else
4544 ast_string_field_set(p, callid, callid);
4545 /* Assign default music on hold class */
4546 ast_string_field_set(p, mohinterpret, default_mohinterpret);
4547 ast_string_field_set(p, mohsuggest, default_mohsuggest);
4548 p->capability = global_capability;
4549 p->allowtransfer = global_allowtransfer;
4550 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
4551 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
4552 p->noncodeccapability |= AST_RTP_DTMF;
4553 if (p->udptl) {
4554 p->t38.capability = global_t38_capability;
4555 if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY)
4556 p->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
4557 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_FEC)
4558 p->t38.capability |= T38FAX_UDP_EC_FEC;
4559 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_NONE)
4560 p->t38.capability |= T38FAX_UDP_EC_NONE;
4561 p->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
4562 p->t38.jointcapability = p->t38.capability;
4564 ast_string_field_set(p, context, default_context);
4566 /* Add to active dialog list */
4567 ast_mutex_lock(&iflock);
4568 p->next = iflist;
4569 iflist = p;
4570 ast_mutex_unlock(&iflock);
4571 if (option_debug)
4572 ast_log(LOG_DEBUG, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : "(No Call-ID)", sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
4573 return p;
4576 /*! \brief Connect incoming SIP message to current dialog or create new dialog structure
4577 Called by handle_request, sipsock_read */
4578 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
4580 struct sip_pvt *p = NULL;
4581 char *tag = ""; /* note, tag is never NULL */
4582 char totag[128];
4583 char fromtag[128];
4584 const char *callid = get_header(req, "Call-ID");
4585 const char *from = get_header(req, "From");
4586 const char *to = get_header(req, "To");
4587 const char *cseq = get_header(req, "Cseq");
4589 /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
4590 /* get_header always returns non-NULL so we must use ast_strlen_zero() */
4591 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
4592 ast_strlen_zero(from) || ast_strlen_zero(cseq))
4593 return NULL; /* Invalid packet */
4595 if (pedanticsipchecking) {
4596 /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
4597 we need more to identify a branch - so we have to check branch, from
4598 and to tags to identify a call leg.
4599 For Asterisk to behave correctly, you need to turn on pedanticsipchecking
4600 in sip.conf
4602 if (gettag(req, "To", totag, sizeof(totag)))
4603 ast_set_flag(req, SIP_PKT_WITH_TOTAG); /* Used in handle_request/response */
4604 gettag(req, "From", fromtag, sizeof(fromtag));
4606 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
4608 if (option_debug > 4 )
4609 ast_log(LOG_DEBUG, "= Looking for Call ID: %s (Checking %s) --From tag %s --To-tag %s \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag);
4612 ast_mutex_lock(&iflock);
4613 for (p = iflist; p; p = p->next) {
4614 /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
4615 int found = FALSE;
4616 if (ast_strlen_zero(p->callid))
4617 continue;
4618 if (req->method == SIP_REGISTER)
4619 found = (!strcmp(p->callid, callid));
4620 else
4621 found = (!strcmp(p->callid, callid) &&
4622 (!pedanticsipchecking || ast_strlen_zero(tag) || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ;
4624 if (option_debug > 4)
4625 ast_log(LOG_DEBUG, "= %s Their Call ID: %s Their Tag %s Our tag: %s\n", found ? "Found" : "No match", p->callid, p->theirtag, p->tag);
4627 /* If we get a new request within an existing to-tag - check the to tag as well */
4628 if (pedanticsipchecking && found && req->method != SIP_RESPONSE) { /* SIP Request */
4629 if (p->tag[0] == '\0' && totag[0]) {
4630 /* We have no to tag, but they have. Wrong dialog */
4631 found = FALSE;
4632 } else if (totag[0]) { /* Both have tags, compare them */
4633 if (strcmp(totag, p->tag)) {
4634 found = FALSE; /* This is not our packet */
4637 if (!found && option_debug > 4)
4638 ast_log(LOG_DEBUG, "= Being pedantic: This is not our match on request: Call ID: %s Ourtag <null> Totag %s Method %s\n", p->callid, totag, sip_methods[req->method].text);
4642 if (found) {
4643 /* Found the call */
4644 ast_mutex_lock(&p->lock);
4645 ast_mutex_unlock(&iflock);
4646 return p;
4649 ast_mutex_unlock(&iflock);
4651 /* See if the method is capable of creating a dialog */
4652 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
4653 if (intended_method == SIP_REFER) {
4654 /* We do support REFER, but not outside of a dialog yet */
4655 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
4656 } else if (intended_method == SIP_NOTIFY) {
4657 /* We do not support out-of-dialog NOTIFY either,
4658 like voicemail notification, so cancel that early */
4659 transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
4660 } else {
4661 /* Ok, time to create a new SIP dialog object, a pvt */
4662 if ((p = sip_alloc(callid, sin, 1, intended_method))) {
4663 /* Ok, we've created a dialog, let's go and process it */
4664 ast_mutex_lock(&p->lock);
4665 } else {
4666 /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
4667 getting a dialog from sip_alloc.
4669 Without a dialog we can't retransmit and handle ACKs and all that, but at least
4670 send an error message.
4672 Sorry, we apologize for the inconvienience
4674 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
4675 if (option_debug > 3)
4676 ast_log(LOG_DEBUG, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
4679 return p;
4680 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
4681 /* A method we do not support, let's take it on the volley */
4682 transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
4683 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
4684 /* This is a request outside of a dialog that we don't know about
4685 ...never reply to an ACK!
4687 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
4689 /* We do not respond to responses for dialogs that we don't know about, we just drop
4690 the session quickly */
4692 return p;
4695 /*! \brief Parse register=> line in sip.conf and add to registry */
4696 static int sip_register(char *value, int lineno)
4698 struct sip_registry *reg;
4699 int portnum = 0;
4700 char username[256] = "";
4701 char *hostname=NULL, *secret=NULL, *authuser=NULL;
4702 char *porta=NULL;
4703 char *contact=NULL;
4705 if (!value)
4706 return -1;
4707 ast_copy_string(username, value, sizeof(username));
4708 /* First split around the last '@' then parse the two components. */
4709 hostname = strrchr(username, '@'); /* allow @ in the first part */
4710 if (hostname)
4711 *hostname++ = '\0';
4712 if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
4713 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
4714 return -1;
4716 /* split user[:secret[:authuser]] */
4717 secret = strchr(username, ':');
4718 if (secret) {
4719 *secret++ = '\0';
4720 authuser = strchr(secret, ':');
4721 if (authuser)
4722 *authuser++ = '\0';
4724 /* split host[:port][/contact] */
4725 contact = strchr(hostname, '/');
4726 if (contact)
4727 *contact++ = '\0';
4728 if (ast_strlen_zero(contact))
4729 contact = "s";
4730 porta = strchr(hostname, ':');
4731 if (porta) {
4732 *porta++ = '\0';
4733 portnum = atoi(porta);
4734 if (portnum == 0) {
4735 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
4736 return -1;
4739 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
4740 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
4741 return -1;
4744 if (ast_string_field_init(reg, 256)) {
4745 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
4746 free(reg);
4747 return -1;
4750 regobjs++;
4751 ASTOBJ_INIT(reg);
4752 ast_string_field_set(reg, contact, contact);
4753 if (!ast_strlen_zero(username))
4754 ast_string_field_set(reg, username, username);
4755 if (hostname)
4756 ast_string_field_set(reg, hostname, hostname);
4757 if (authuser)
4758 ast_string_field_set(reg, authuser, authuser);
4759 if (secret)
4760 ast_string_field_set(reg, secret, secret);
4761 reg->expire = -1;
4762 reg->timeout = -1;
4763 reg->refresh = default_expiry;
4764 reg->portno = portnum;
4765 reg->callid_valid = FALSE;
4766 reg->ocseq = INITIAL_CSEQ;
4767 ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
4768 ASTOBJ_UNREF(reg,sip_registry_destroy);
4769 return 0;
4772 /*! \brief Parse multiline SIP headers into one header
4773 This is enabled if pedanticsipchecking is enabled */
4774 static int lws2sws(char *msgbuf, int len)
4776 int h = 0, t = 0;
4777 int lws = 0;
4779 for (; h < len;) {
4780 /* Eliminate all CRs */
4781 if (msgbuf[h] == '\r') {
4782 h++;
4783 continue;
4785 /* Check for end-of-line */
4786 if (msgbuf[h] == '\n') {
4787 /* Check for end-of-message */
4788 if (h + 1 == len)
4789 break;
4790 /* Check for a continuation line */
4791 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
4792 /* Merge continuation line */
4793 h++;
4794 continue;
4796 /* Propagate LF and start new line */
4797 msgbuf[t++] = msgbuf[h++];
4798 lws = 0;
4799 continue;
4801 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
4802 if (lws) {
4803 h++;
4804 continue;
4806 msgbuf[t++] = msgbuf[h++];
4807 lws = 1;
4808 continue;
4810 msgbuf[t++] = msgbuf[h++];
4811 if (lws)
4812 lws = 0;
4814 msgbuf[t] = '\0';
4815 return t;
4818 /*! \brief Parse a SIP message
4819 \note this function is used both on incoming and outgoing packets
4821 static int parse_request(struct sip_request *req)
4823 /* Divide fields by NULL's */
4824 char *c;
4825 int f = 0;
4827 c = req->data;
4829 /* First header starts immediately */
4830 req->header[f] = c;
4831 while(*c) {
4832 if (*c == '\n') {
4833 /* We've got a new header */
4834 *c = 0;
4836 if (sipdebug && option_debug > 3)
4837 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
4838 if (ast_strlen_zero(req->header[f])) {
4839 /* Line by itself means we're now in content */
4840 c++;
4841 break;
4843 if (f >= SIP_MAX_HEADERS - 1) {
4844 ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n");
4845 } else
4846 f++;
4847 req->header[f] = c + 1;
4848 } else if (*c == '\r') {
4849 /* Ignore but eliminate \r's */
4850 *c = 0;
4852 c++;
4854 /* Check for last header */
4855 if (!ast_strlen_zero(req->header[f])) {
4856 if (sipdebug && option_debug > 3)
4857 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
4858 f++;
4860 req->headers = f;
4861 /* Now we process any mime content */
4862 f = 0;
4863 req->line[f] = c;
4864 while(*c) {
4865 if (*c == '\n') {
4866 /* We've got a new line */
4867 *c = 0;
4868 if (sipdebug && option_debug > 3)
4869 ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
4870 if (f >= SIP_MAX_LINES - 1) {
4871 ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n");
4872 } else
4873 f++;
4874 req->line[f] = c + 1;
4875 } else if (*c == '\r') {
4876 /* Ignore and eliminate \r's */
4877 *c = 0;
4879 c++;
4881 /* Check for last line */
4882 if (!ast_strlen_zero(req->line[f]))
4883 f++;
4884 req->lines = f;
4885 if (*c)
4886 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
4887 /* Split up the first line parts */
4888 return determine_firstline_parts(req);
4892 \brief Determine whether a SIP message contains an SDP in its body
4893 \param req the SIP request to process
4894 \return 1 if SDP found, 0 if not found
4896 Also updates req->sdp_start and req->sdp_end to indicate where the SDP
4897 lives in the message body.
4899 static int find_sdp(struct sip_request *req)
4901 const char *content_type;
4902 const char *content_length;
4903 const char *search;
4904 char *boundary;
4905 unsigned int x;
4906 int boundaryisquoted = FALSE;
4907 int found_application_sdp = FALSE;
4908 int found_end_of_headers = FALSE;
4910 content_length = get_header(req, "Content-Length");
4912 if (!ast_strlen_zero(content_length)) {
4913 if (sscanf(content_length, "%ud", &x) != 1) {
4914 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
4915 return 0;
4918 /* Content-Length of zero means there can't possibly be an
4919 SDP here, even if the Content-Type says there is */
4920 if (x == 0)
4921 return 0;
4924 content_type = get_header(req, "Content-Type");
4926 /* if the body contains only SDP, this is easy */
4927 if (!strcasecmp(content_type, "application/sdp")) {
4928 req->sdp_start = 0;
4929 req->sdp_end = req->lines;
4930 return req->lines ? 1 : 0;
4933 /* if it's not multipart/mixed, there cannot be an SDP */
4934 if (strncasecmp(content_type, "multipart/mixed", 15))
4935 return 0;
4937 /* if there is no boundary marker, it's invalid */
4938 if ((search = strcasestr(content_type, ";boundary=")))
4939 search += 10;
4940 else if ((search = strcasestr(content_type, "; boundary=")))
4941 search += 11;
4942 else
4943 return 0;
4945 if (ast_strlen_zero(search))
4946 return 0;
4948 /* If the boundary is quoted with ", remove quote */
4949 if (*search == '\"') {
4950 search++;
4951 boundaryisquoted = TRUE;
4954 /* make a duplicate of the string, with two extra characters
4955 at the beginning */
4956 boundary = ast_strdupa(search - 2);
4957 boundary[0] = boundary[1] = '-';
4958 /* Remove final quote */
4959 if (boundaryisquoted)
4960 boundary[strlen(boundary) - 1] = '\0';
4962 /* search for the boundary marker, the empty line delimiting headers from
4963 sdp part and the end boundry if it exists */
4965 for (x = 0; x < (req->lines ); x++) {
4966 if(!strncasecmp(req->line[x], boundary, strlen(boundary))){
4967 if(found_application_sdp && found_end_of_headers){
4968 req->sdp_end = x-1;
4969 return 1;
4971 found_application_sdp = FALSE;
4973 if(!strcasecmp(req->line[x], "Content-Type: application/sdp"))
4974 found_application_sdp = TRUE;
4976 if(strlen(req->line[x]) == 0 ){
4977 if(found_application_sdp && !found_end_of_headers){
4978 req->sdp_start = x;
4979 found_end_of_headers = TRUE;
4983 if(found_application_sdp && found_end_of_headers) {
4984 req->sdp_end = x;
4985 return TRUE;
4987 return FALSE;
4990 /*! \brief Change hold state for a call */
4991 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
4993 if (global_notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
4994 sip_peer_hold(dialog, holdstate);
4995 if (global_callevents)
4996 manager_event(EVENT_FLAG_CALL, holdstate ? "Hold" : "Unhold",
4997 "Channel: %s\r\n"
4998 "Uniqueid: %s\r\n",
4999 dialog->owner->name,
5000 dialog->owner->uniqueid);
5001 append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data);
5002 if (!holdstate) { /* Put off remote hold */
5003 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
5004 return;
5006 /* No address for RTP, we're on hold */
5008 if (sendonly == 1) /* One directional hold (sendonly/recvonly) */
5009 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
5010 else if (sendonly == 2) /* Inactive stream */
5011 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
5012 else
5013 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
5014 return;
5017 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
5018 If offer is rejected, we will not change any properties of the call
5019 Return 0 on success, a negative value on errors.
5020 Must be called after find_sdp().
5022 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
5024 const char *m; /* SDP media offer */
5025 const char *c;
5026 const char *a;
5027 char host[258];
5028 int len = -1;
5029 int portno = -1; /*!< RTP Audio port number */
5030 int vportno = -1; /*!< RTP Video port number */
5031 int udptlportno = -1;
5032 int peert38capability = 0;
5033 char s[256];
5034 int old = 0;
5036 /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
5037 int peercapability = 0, peernoncodeccapability = 0;
5038 int vpeercapability = 0, vpeernoncodeccapability = 0;
5039 struct sockaddr_in sin; /*!< media socket address */
5040 struct sockaddr_in vsin; /*!< Video socket address */
5042 const char *codecs;
5043 struct hostent *hp; /*!< RTP Audio host IP */
5044 struct hostent *vhp = NULL; /*!< RTP video host IP */
5045 struct ast_hostent audiohp;
5046 struct ast_hostent videohp;
5047 int codec;
5048 int destiterator = 0;
5049 int iterator;
5050 int sendonly = -1;
5051 int numberofports;
5052 struct ast_rtp *newaudiortp, *newvideortp; /* Buffers for codec handling */
5053 int newjointcapability; /* Negotiated capability */
5054 int newpeercapability;
5055 int newnoncodeccapability;
5056 int numberofmediastreams = 0;
5057 int debug = sip_debug_test_pvt(p);
5059 int found_rtpmap_codecs[SDP_MAX_RTPMAP_CODECS];
5060 int last_rtpmap_codec=0;
5062 if (!p->rtp) {
5063 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
5064 return -1;
5067 /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
5068 #ifdef LOW_MEMORY
5069 newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
5070 #else
5071 newaudiortp = alloca(ast_rtp_alloc_size());
5072 #endif
5073 memset(newaudiortp, 0, ast_rtp_alloc_size());
5074 ast_rtp_new_init(newaudiortp);
5075 ast_rtp_pt_clear(newaudiortp);
5077 #ifdef LOW_MEMORY
5078 newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
5079 #else
5080 newvideortp = alloca(ast_rtp_alloc_size());
5081 #endif
5082 memset(newvideortp, 0, ast_rtp_alloc_size());
5083 ast_rtp_new_init(newvideortp);
5084 ast_rtp_pt_clear(newvideortp);
5086 /* Update our last rtprx when we receive an SDP, too */
5087 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
5090 /* Try to find first media stream */
5091 m = get_sdp(req, "m");
5092 destiterator = req->sdp_start;
5093 c = get_sdp_iterate(&destiterator, req, "c");
5094 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
5095 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
5096 return -1;
5099 /* Check for IPv4 address (not IPv6 yet) */
5100 if (sscanf(c, "IN IP4 %256s", host) != 1) {
5101 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
5102 return -1;
5105 /* XXX This could block for a long time, and block the main thread! XXX */
5106 hp = ast_gethostbyname(host, &audiohp);
5107 if (!hp) {
5108 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
5109 return -1;
5111 vhp = hp; /* Copy to video address as default too */
5113 iterator = req->sdp_start;
5114 ast_set_flag(&p->flags[0], SIP_NOVIDEO);
5117 /* Find media streams in this SDP offer */
5118 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
5119 int x;
5120 int audio = FALSE;
5122 numberofports = 1;
5123 if ((sscanf(m, "audio %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
5124 (sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
5125 audio = TRUE;
5126 numberofmediastreams++;
5127 /* Found audio stream in this media definition */
5128 portno = x;
5129 /* Scan through the RTP payload types specified in a "m=" line: */
5130 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
5131 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
5132 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
5133 return -1;
5135 if (debug)
5136 ast_verbose("Found RTP audio format %d\n", codec);
5137 ast_rtp_set_m_type(newaudiortp, codec);
5139 } else if ((sscanf(m, "video %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
5140 (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
5141 /* If it is not audio - is it video ? */
5142 ast_clear_flag(&p->flags[0], SIP_NOVIDEO);
5143 numberofmediastreams++;
5144 vportno = x;
5145 /* Scan through the RTP payload types specified in a "m=" line: */
5146 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
5147 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
5148 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
5149 return -1;
5151 if (debug)
5152 ast_verbose("Found RTP video format %d\n", codec);
5153 ast_rtp_set_m_type(newvideortp, codec);
5155 } else if (p->udptl && ( (sscanf(m, "image %d udptl t38%n", &x, &len) == 1) ||
5156 (sscanf(m, "image %d UDPTL t38%n", &x, &len) == 1) )) {
5157 if (debug)
5158 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
5159 udptlportno = x;
5160 numberofmediastreams++;
5162 if (p->owner && p->lastinvite) {
5163 p->t38.state = T38_PEER_REINVITE; /* T38 Offered in re-invite from remote party */
5164 if (option_debug > 1)
5165 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>" );
5166 } else {
5167 p->t38.state = T38_PEER_DIRECT; /* T38 Offered directly from peer in first invite */
5168 if (option_debug > 1)
5169 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
5171 } else
5172 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
5173 if (numberofports > 1)
5174 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
5177 /* Check for Media-description-level-address for audio */
5178 c = get_sdp_iterate(&destiterator, req, "c");
5179 if (!ast_strlen_zero(c)) {
5180 if (sscanf(c, "IN IP4 %256s", host) != 1) {
5181 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
5182 } else {
5183 /* XXX This could block for a long time, and block the main thread! XXX */
5184 if (audio) {
5185 if ( !(hp = ast_gethostbyname(host, &audiohp))) {
5186 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in secondary c= line, '%s'\n", c);
5187 return -2;
5189 } else if (!(vhp = ast_gethostbyname(host, &videohp))) {
5190 ast_log(LOG_WARNING, "Unable to lookup RTP video host in secondary c= line, '%s'\n", c);
5191 return -2;
5197 if (portno == -1 && vportno == -1 && udptlportno == -1)
5198 /* No acceptable offer found in SDP - we have no ports */
5199 /* Do not change RTP or VRTP if this is a re-invite */
5200 return -2;
5202 if (numberofmediastreams > 2)
5203 /* We have too many fax, audio and/or video media streams, fail this offer */
5204 return -3;
5206 /* RTP addresses and ports for audio and video */
5207 sin.sin_family = AF_INET;
5208 vsin.sin_family = AF_INET;
5209 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
5210 if (vhp)
5211 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
5213 /* Setup UDPTL port number */
5214 if (p->udptl) {
5215 if (udptlportno > 0) {
5216 sin.sin_port = htons(udptlportno);
5217 if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
5218 struct sockaddr_in peer;
5219 ast_rtp_get_peer(p->rtp, &peer);
5220 if (peer.sin_addr.s_addr) {
5221 memcpy(&sin.sin_addr, &peer.sin_addr, sizeof(&sin.sin_addr));
5222 if (debug) {
5223 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));
5227 ast_udptl_set_peer(p->udptl, &sin);
5228 if (debug)
5229 ast_log(LOG_DEBUG,"Peer T.38 UDPTL is at port %s:%d\n",ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
5230 } else {
5231 ast_udptl_stop(p->udptl);
5232 if (debug)
5233 ast_log(LOG_DEBUG, "Peer doesn't provide T.38 UDPTL\n");
5238 if (p->rtp) {
5239 if (portno > 0) {
5240 sin.sin_port = htons(portno);
5241 ast_rtp_set_peer(p->rtp, &sin);
5242 if (debug)
5243 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
5244 } else {
5245 if (udptlportno > 0) {
5246 if (debug)
5247 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session. Callid %s\n", p->callid);
5248 } else {
5249 ast_rtp_stop(p->rtp);
5250 if (debug)
5251 ast_verbose("Peer doesn't provide audio. Callid %s\n", p->callid);
5255 /* Setup video port number */
5256 if (vportno != -1)
5257 vsin.sin_port = htons(vportno);
5259 /* Next, scan through each "a=rtpmap:" line, noting each
5260 * specified RTP payload type (with corresponding MIME subtype):
5262 /* XXX This needs to be done per media stream, since it's media stream specific */
5263 iterator = req->sdp_start;
5264 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
5265 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
5266 if (option_debug > 1) {
5267 int breakout = FALSE;
5269 /* If we're debugging, check for unsupported sdp options */
5270 if (!strncasecmp(a, "rtcp:", (size_t) 5)) {
5271 if (debug)
5272 ast_verbose("Got unsupported a:rtcp in SDP offer \n");
5273 breakout = TRUE;
5274 } else if (!strncasecmp(a, "fmtp:", (size_t) 5)) {
5275 /* Format parameters: Not supported */
5276 /* Note: This is used for codec parameters, like bitrate for
5277 G722 and video formats for H263 and H264
5278 See RFC2327 for an example */
5279 if (debug)
5280 ast_verbose("Got unsupported a:fmtp in SDP offer \n");
5281 breakout = TRUE;
5282 } else if (!strncasecmp(a, "framerate:", (size_t) 10)) {
5283 /* Video stuff: Not supported */
5284 if (debug)
5285 ast_verbose("Got unsupported a:framerate in SDP offer \n");
5286 breakout = TRUE;
5287 } else if (!strncasecmp(a, "maxprate:", (size_t) 9)) {
5288 /* Video stuff: Not supported */
5289 if (debug)
5290 ast_verbose("Got unsupported a:maxprate in SDP offer \n");
5291 breakout = TRUE;
5292 } else if (!strncasecmp(a, "crypto:", (size_t) 7)) {
5293 /* SRTP stuff, not yet supported */
5294 if (debug)
5295 ast_verbose("Got unsupported a:crypto in SDP offer \n");
5296 breakout = TRUE;
5298 if (breakout) /* We have a match, skip to next header */
5299 continue;
5301 if (!strcasecmp(a, "sendonly")) {
5302 if (sendonly == -1)
5303 sendonly = 1;
5304 continue;
5305 } else if (!strcasecmp(a, "inactive")) {
5306 if (sendonly == -1)
5307 sendonly = 2;
5308 continue;
5309 } else if (!strcasecmp(a, "sendrecv")) {
5310 if (sendonly == -1)
5311 sendonly = 0;
5312 continue;
5313 } else if (strlen(a) > 5 && !strncasecmp(a, "ptime", 5)) {
5314 char *tmp = strrchr(a, ':');
5315 long int framing = 0;
5316 if (tmp) {
5317 tmp++;
5318 framing = strtol(tmp, NULL, 10);
5319 if (framing == LONG_MIN || framing == LONG_MAX) {
5320 framing = 0;
5321 if (option_debug)
5322 ast_log(LOG_DEBUG, "Can't read framing from SDP: %s\n", a);
5325 if (framing && p->autoframing) {
5326 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
5327 int codec_n;
5328 int format = 0;
5329 for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
5330 format = ast_rtp_codec_getformat(codec_n);
5331 if (!format) /* non-codec or not found */
5332 continue;
5333 if (option_debug)
5334 ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
5335 ast_codec_pref_setsize(pref, format, framing);
5337 ast_rtp_codec_setpref(p->rtp, pref);
5339 continue;
5340 } else if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) == 2) {
5341 /* We have a rtpmap to handle */
5342 int found = FALSE;
5343 /* We should propably check if this is an audio or video codec
5344 so we know where to look */
5346 if (last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
5347 /* Note: should really look at the 'freq' and '#chans' params too */
5348 if(ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
5349 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0) != -1) {
5350 if (debug)
5351 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
5352 found_rtpmap_codecs[last_rtpmap_codec] = codec;
5353 last_rtpmap_codec++;
5354 found = TRUE;
5356 } else if (p->vrtp) {
5357 if(ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0) != -1) {
5358 if (debug)
5359 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
5360 found_rtpmap_codecs[last_rtpmap_codec] = codec;
5361 last_rtpmap_codec++;
5362 found = TRUE;
5365 } else {
5366 if (debug)
5367 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
5370 if (!found) {
5371 /* Remove this codec since it's an unknown media type for us */
5372 /* XXX This is buggy since the media line for audio and video can have the
5373 same numbers. We need to check as described above, but for testing this works... */
5374 ast_rtp_unset_m_type(newaudiortp, codec);
5375 ast_rtp_unset_m_type(newvideortp, codec);
5376 if (debug)
5377 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
5382 if (udptlportno != -1) {
5383 int found = 0, x;
5385 old = 0;
5387 /* Scan trough the a= lines for T38 attributes and set apropriate fileds */
5388 iterator = req->sdp_start;
5389 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
5390 if ((sscanf(a, "T38FaxMaxBuffer:%d", &x) == 1)) {
5391 found = 1;
5392 if (option_debug > 2)
5393 ast_log(LOG_DEBUG, "MaxBufferSize:%d\n",x);
5394 } else if ((sscanf(a, "T38MaxBitRate:%d", &x) == 1)) {
5395 found = 1;
5396 if (option_debug > 2)
5397 ast_log(LOG_DEBUG,"T38MaxBitRate: %d\n",x);
5398 switch (x) {
5399 case 14400:
5400 peert38capability |= T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5401 break;
5402 case 12000:
5403 peert38capability |= T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5404 break;
5405 case 9600:
5406 peert38capability |= T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5407 break;
5408 case 7200:
5409 peert38capability |= T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5410 break;
5411 case 4800:
5412 peert38capability |= T38FAX_RATE_4800 | T38FAX_RATE_2400;
5413 break;
5414 case 2400:
5415 peert38capability |= T38FAX_RATE_2400;
5416 break;
5418 } else if ((sscanf(a, "T38FaxVersion:%d", &x) == 1)) {
5419 found = 1;
5420 if (option_debug > 2)
5421 ast_log(LOG_DEBUG, "FaxVersion: %d\n",x);
5422 if (x == 0)
5423 peert38capability |= T38FAX_VERSION_0;
5424 else if (x == 1)
5425 peert38capability |= T38FAX_VERSION_1;
5426 } else if ((sscanf(a, "T38FaxMaxDatagram:%d", &x) == 1)) {
5427 found = 1;
5428 if (option_debug > 2)
5429 ast_log(LOG_DEBUG, "FaxMaxDatagram: %d\n",x);
5430 ast_udptl_set_far_max_datagram(p->udptl, x);
5431 ast_udptl_set_local_max_datagram(p->udptl, x);
5432 } else if ((sscanf(a, "T38FaxFillBitRemoval:%d", &x) == 1)) {
5433 found = 1;
5434 if (option_debug > 2)
5435 ast_log(LOG_DEBUG, "FillBitRemoval: %d\n",x);
5436 if (x == 1)
5437 peert38capability |= T38FAX_FILL_BIT_REMOVAL;
5438 } else if ((sscanf(a, "T38FaxTranscodingMMR:%d", &x) == 1)) {
5439 found = 1;
5440 if (option_debug > 2)
5441 ast_log(LOG_DEBUG, "Transcoding MMR: %d\n",x);
5442 if (x == 1)
5443 peert38capability |= T38FAX_TRANSCODING_MMR;
5445 if ((sscanf(a, "T38FaxTranscodingJBIG:%d", &x) == 1)) {
5446 found = 1;
5447 if (option_debug > 2)
5448 ast_log(LOG_DEBUG, "Transcoding JBIG: %d\n",x);
5449 if (x == 1)
5450 peert38capability |= T38FAX_TRANSCODING_JBIG;
5451 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
5452 found = 1;
5453 if (option_debug > 2)
5454 ast_log(LOG_DEBUG, "RateManagement: %s\n", s);
5455 if (!strcasecmp(s, "localTCF"))
5456 peert38capability |= T38FAX_RATE_MANAGEMENT_LOCAL_TCF;
5457 else if (!strcasecmp(s, "transferredTCF"))
5458 peert38capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
5459 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
5460 found = 1;
5461 if (option_debug > 2)
5462 ast_log(LOG_DEBUG, "UDP EC: %s\n", s);
5463 if (!strcasecmp(s, "t38UDPRedundancy")) {
5464 peert38capability |= T38FAX_UDP_EC_REDUNDANCY;
5465 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
5466 } else if (!strcasecmp(s, "t38UDPFEC")) {
5467 peert38capability |= T38FAX_UDP_EC_FEC;
5468 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
5469 } else {
5470 peert38capability |= T38FAX_UDP_EC_NONE;
5471 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
5475 if (found) { /* Some cisco equipment returns nothing beside c= and m= lines in 200 OK T38 SDP */
5476 p->t38.peercapability = peert38capability;
5477 p->t38.jointcapability = (peert38capability & 255); /* Put everything beside supported speeds settings */
5478 peert38capability &= (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400);
5479 p->t38.jointcapability |= (peert38capability & p->t38.capability); /* Put the lower of our's and peer's speed */
5481 if (debug)
5482 ast_log(LOG_DEBUG, "Our T38 capability = (%d), peer T38 capability (%d), joint T38 capability (%d)\n",
5483 p->t38.capability,
5484 p->t38.peercapability,
5485 p->t38.jointcapability);
5486 } else {
5487 p->t38.state = T38_DISABLED;
5488 if (option_debug > 2)
5489 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
5492 /* Now gather all of the codecs that we are asked for: */
5493 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
5494 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
5496 newjointcapability = p->capability & (peercapability | vpeercapability);
5497 newpeercapability = (peercapability | vpeercapability);
5498 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
5501 if (debug) {
5502 /* shame on whoever coded this.... */
5503 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE];
5505 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
5506 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
5507 ast_getformatname_multiple(s2, SIPBUFSIZE, newpeercapability),
5508 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
5509 ast_getformatname_multiple(s4, SIPBUFSIZE, newjointcapability));
5511 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
5512 ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
5513 ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
5514 ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
5516 if (!newjointcapability) {
5517 /* If T.38 was not negotiated either, totally bail out... */
5518 if (!p->t38.jointcapability || !udptlportno) {
5519 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
5520 /* Do NOT Change current setting */
5521 return -1;
5522 } else {
5523 if (option_debug > 2)
5524 ast_log(LOG_DEBUG, "Have T.38 but no audio codecs, accepting offer anyway\n");
5525 return 0;
5529 /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
5530 they are acceptable */
5531 p->jointcapability = newjointcapability; /* Our joint codec profile for this call */
5532 p->peercapability = newpeercapability; /* The other sides capability in latest offer */
5533 p->jointnoncodeccapability = newnoncodeccapability; /* DTMF capabilities */
5535 ast_rtp_pt_copy(p->rtp, newaudiortp);
5536 if (p->vrtp)
5537 ast_rtp_pt_copy(p->vrtp, newvideortp);
5539 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
5540 ast_clear_flag(&p->flags[0], SIP_DTMF);
5541 if (newnoncodeccapability & AST_RTP_DTMF) {
5542 /* XXX Would it be reasonable to drop the DSP at this point? XXX */
5543 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
5544 /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
5545 ast_rtp_setdtmf(p->rtp, 1);
5546 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
5547 } else {
5548 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
5552 /* Setup audio port number */
5553 if (p->rtp && sin.sin_port) {
5554 ast_rtp_set_peer(p->rtp, &sin);
5555 if (debug)
5556 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
5559 /* Setup video port number */
5560 if (p->vrtp && vsin.sin_port) {
5561 ast_rtp_set_peer(p->vrtp, &vsin);
5562 if (debug)
5563 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
5566 /* Ok, we're going with this offer */
5567 if (option_debug > 1) {
5568 char buf[SIPBUFSIZE];
5569 ast_log(LOG_DEBUG, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
5572 if (!p->owner) /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
5573 return 0;
5575 if (option_debug > 3)
5576 ast_log(LOG_DEBUG, "We have an owner, now see if we need to change this call\n");
5578 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
5579 if (debug) {
5580 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
5581 ast_log(LOG_DEBUG, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
5582 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
5583 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
5585 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability);
5586 ast_set_read_format(p->owner, p->owner->readformat);
5587 ast_set_write_format(p->owner, p->owner->writeformat);
5590 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
5591 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
5592 /* Activate a re-invite */
5593 ast_queue_frame(p->owner, &ast_null_frame);
5594 } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
5595 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
5596 S_OR(p->mohsuggest, NULL),
5597 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
5598 if (sendonly)
5599 ast_rtp_stop(p->rtp);
5600 /* RTCP needs to go ahead, even if we're on hold!!! */
5601 /* Activate a re-invite */
5602 ast_queue_frame(p->owner, &ast_null_frame);
5605 /* Manager Hold and Unhold events must be generated, if necessary */
5606 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1))
5607 change_hold_state(p, req, FALSE, sendonly);
5608 else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1))
5609 change_hold_state(p, req, TRUE, sendonly);
5610 return 0;
5613 static void ts_ast_rtp_destroy(void *data)
5615 struct ast_rtp *tmp = data;
5616 ast_rtp_destroy(tmp);
5619 /*! \brief Add header to SIP message */
5620 static int add_header(struct sip_request *req, const char *var, const char *value)
5622 int maxlen = sizeof(req->data) - 4 - req->len; /* 4 bytes are for two \r\n ? */
5624 if (req->headers == SIP_MAX_HEADERS) {
5625 ast_log(LOG_WARNING, "Out of SIP header space\n");
5626 return -1;
5629 if (req->lines) {
5630 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
5631 return -1;
5634 if (maxlen <= 0) {
5635 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
5636 return -1;
5639 req->header[req->headers] = req->data + req->len;
5641 if (compactheaders)
5642 var = find_alias(var, var);
5644 snprintf(req->header[req->headers], maxlen, "%s: %s\r\n", var, value);
5645 req->len += strlen(req->header[req->headers]);
5646 req->headers++;
5648 return 0;
5651 /*! \brief Add 'Content-Length' header to SIP message */
5652 static int add_header_contentLength(struct sip_request *req, int len)
5654 char clen[10];
5656 snprintf(clen, sizeof(clen), "%d", len);
5657 return add_header(req, "Content-Length", clen);
5660 /*! \brief Add content (not header) to SIP message */
5661 static int add_line(struct sip_request *req, const char *line)
5663 if (req->lines == SIP_MAX_LINES) {
5664 ast_log(LOG_WARNING, "Out of SIP line space\n");
5665 return -1;
5667 if (!req->lines) {
5668 /* Add extra empty return */
5669 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
5670 req->len += strlen(req->data + req->len);
5672 if (req->len >= sizeof(req->data) - 4) {
5673 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
5674 return -1;
5676 req->line[req->lines] = req->data + req->len;
5677 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
5678 req->len += strlen(req->line[req->lines]);
5679 req->lines++;
5680 return 0;
5683 /*! \brief Copy one header field from one request to another */
5684 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
5686 const char *tmp = get_header(orig, field);
5688 if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
5689 return add_header(req, field, tmp);
5690 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
5691 return -1;
5694 /*! \brief Copy all headers from one request to another */
5695 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
5697 int start = 0;
5698 int copied = 0;
5699 for (;;) {
5700 const char *tmp = __get_header(orig, field, &start);
5702 if (ast_strlen_zero(tmp))
5703 break;
5704 /* Add what we're responding to */
5705 add_header(req, field, tmp);
5706 copied++;
5708 return copied ? 0 : -1;
5711 /*! \brief Copy SIP VIA Headers from the request to the response
5712 \note If the client indicates that it wishes to know the port we received from,
5713 it adds ;rport without an argument to the topmost via header. We need to
5714 add the port number (from our point of view) to that parameter.
5715 We always add ;received=<ip address> to the topmost via header.
5716 Received: RFC 3261, rport RFC 3581 */
5717 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
5719 int copied = 0;
5720 int start = 0;
5722 for (;;) {
5723 char new[512];
5724 const char *oh = __get_header(orig, field, &start);
5726 if (ast_strlen_zero(oh))
5727 break;
5729 if (!copied) { /* Only check for empty rport in topmost via header */
5730 char leftmost[512], *others, *rport;
5732 /* Only work on leftmost value */
5733 ast_copy_string(leftmost, oh, sizeof(leftmost));
5734 others = strchr(leftmost, ',');
5735 if (others)
5736 *others++ = '\0';
5738 /* Find ;rport; (empty request) */
5739 rport = strstr(leftmost, ";rport");
5740 if (rport && *(rport+6) == '=')
5741 rport = NULL; /* We already have a parameter to rport */
5743 /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting) */
5744 if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
5745 /* We need to add received port - rport */
5746 char *end;
5748 rport = strstr(leftmost, ";rport");
5750 if (rport) {
5751 end = strchr(rport + 1, ';');
5752 if (end)
5753 memmove(rport, end, strlen(end) + 1);
5754 else
5755 *rport = '\0';
5758 /* Add rport to first VIA header if requested */
5759 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
5760 leftmost, ast_inet_ntoa(p->recv.sin_addr),
5761 ntohs(p->recv.sin_port),
5762 others ? "," : "", others ? others : "");
5763 } else {
5764 /* We should *always* add a received to the topmost via */
5765 snprintf(new, sizeof(new), "%s;received=%s%s%s",
5766 leftmost, ast_inet_ntoa(p->recv.sin_addr),
5767 others ? "," : "", others ? others : "");
5769 oh = new; /* the header to copy */
5770 } /* else add the following via headers untouched */
5771 add_header(req, field, oh);
5772 copied++;
5774 if (!copied) {
5775 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
5776 return -1;
5778 return 0;
5781 /*! \brief Add route header into request per learned route */
5782 static void add_route(struct sip_request *req, struct sip_route *route)
5784 char r[SIPBUFSIZE*2], *p;
5785 int n, rem = sizeof(r);
5787 if (!route)
5788 return;
5790 p = r;
5791 for (;route ; route = route->next) {
5792 n = strlen(route->hop);
5793 if (rem < n+3) /* we need room for ",<route>" */
5794 break;
5795 if (p != r) { /* add a separator after fist route */
5796 *p++ = ',';
5797 --rem;
5799 *p++ = '<';
5800 ast_copy_string(p, route->hop, rem); /* cannot fail */
5801 p += n;
5802 *p++ = '>';
5803 rem -= (n+2);
5805 *p = '\0';
5806 add_header(req, "Route", r);
5809 /*! \brief Set destination from SIP URI */
5810 static void set_destination(struct sip_pvt *p, char *uri)
5812 char *h, *maddr, hostname[256];
5813 int port, hn;
5814 struct hostent *hp;
5815 struct ast_hostent ahp;
5816 int debug=sip_debug_test_pvt(p);
5818 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
5819 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
5821 if (debug)
5822 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
5824 /* Find and parse hostname */
5825 h = strchr(uri, '@');
5826 if (h)
5827 ++h;
5828 else {
5829 h = uri;
5830 if (strncasecmp(h, "sip:", 4) == 0)
5831 h += 4;
5832 else if (strncasecmp(h, "sips:", 5) == 0)
5833 h += 5;
5835 hn = strcspn(h, ":;>") + 1;
5836 if (hn > sizeof(hostname))
5837 hn = sizeof(hostname);
5838 ast_copy_string(hostname, h, hn);
5839 /* XXX bug here if string has been trimmed to sizeof(hostname) */
5840 h += hn - 1;
5842 /* Is "port" present? if not default to STANDARD_SIP_PORT */
5843 if (*h == ':') {
5844 /* Parse port */
5845 ++h;
5846 port = strtol(h, &h, 10);
5848 else
5849 port = STANDARD_SIP_PORT;
5851 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
5852 maddr = strstr(h, "maddr=");
5853 if (maddr) {
5854 maddr += 6;
5855 hn = strspn(maddr, "0123456789.") + 1;
5856 if (hn > sizeof(hostname))
5857 hn = sizeof(hostname);
5858 ast_copy_string(hostname, maddr, hn);
5861 hp = ast_gethostbyname(hostname, &ahp);
5862 if (hp == NULL) {
5863 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
5864 return;
5866 p->sa.sin_family = AF_INET;
5867 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
5868 p->sa.sin_port = htons(port);
5869 if (debug)
5870 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
5873 /*! \brief Initialize SIP response, based on SIP request */
5874 static int init_resp(struct sip_request *resp, const char *msg)
5876 /* Initialize a response */
5877 memset(resp, 0, sizeof(*resp));
5878 resp->method = SIP_RESPONSE;
5879 resp->header[0] = resp->data;
5880 snprintf(resp->header[0], sizeof(resp->data), "SIP/2.0 %s\r\n", msg);
5881 resp->len = strlen(resp->header[0]);
5882 resp->headers++;
5883 return 0;
5886 /*! \brief Initialize SIP request */
5887 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
5889 /* Initialize a request */
5890 memset(req, 0, sizeof(*req));
5891 req->method = sipmethod;
5892 req->header[0] = req->data;
5893 snprintf(req->header[0], sizeof(req->data), "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
5894 req->len = strlen(req->header[0]);
5895 req->headers++;
5896 return 0;
5900 /*! \brief Prepare SIP response packet */
5901 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
5903 char newto[256];
5904 const char *ot;
5906 init_resp(resp, msg);
5907 copy_via_headers(p, resp, req, "Via");
5908 if (msg[0] == '1' || msg[0] == '2')
5909 copy_all_header(resp, req, "Record-Route");
5910 copy_header(resp, req, "From");
5911 ot = get_header(req, "To");
5912 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
5913 /* Add the proper tag if we don't have it already. If they have specified
5914 their tag, use it. Otherwise, use our own tag */
5915 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
5916 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
5917 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
5918 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
5919 else
5920 ast_copy_string(newto, ot, sizeof(newto));
5921 ot = newto;
5923 add_header(resp, "To", ot);
5924 copy_header(resp, req, "Call-ID");
5925 copy_header(resp, req, "CSeq");
5926 if (!ast_strlen_zero(global_useragent))
5927 add_header(resp, "User-Agent", global_useragent);
5928 add_header(resp, "Allow", ALLOWED_METHODS);
5929 add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
5930 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
5931 /* For registration responses, we also need expiry and
5932 contact info */
5933 char tmp[256];
5935 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
5936 add_header(resp, "Expires", tmp);
5937 if (p->expiry) { /* Only add contact if we have an expiry time */
5938 char contact[SIPBUFSIZE];
5939 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
5940 add_header(resp, "Contact", contact); /* Not when we unregister */
5942 } else if (msg[0] != '4' && !ast_strlen_zero(p->our_contact)) {
5943 add_header(resp, "Contact", p->our_contact);
5945 return 0;
5948 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
5949 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
5951 struct sip_request *orig = &p->initreq;
5952 char stripped[80];
5953 char tmp[80];
5954 char newto[256];
5955 const char *c;
5956 const char *ot, *of;
5957 int is_strict = FALSE; /*!< Strict routing flag */
5959 memset(req, 0, sizeof(struct sip_request));
5961 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
5963 if (!seqno) {
5964 p->ocseq++;
5965 seqno = p->ocseq;
5968 if (newbranch) {
5969 p->branch ^= ast_random();
5970 build_via(p);
5973 /* Check for strict or loose router */
5974 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop,";lr") == NULL) {
5975 is_strict = TRUE;
5976 if (sipdebug)
5977 ast_log(LOG_DEBUG, "Strict routing enforced for session %s\n", p->callid);
5980 if (sipmethod == SIP_CANCEL)
5981 c = p->initreq.rlPart2; /* Use original URI */
5982 else if (sipmethod == SIP_ACK) {
5983 /* Use URI from Contact: in 200 OK (if INVITE)
5984 (we only have the contacturi on INVITEs) */
5985 if (!ast_strlen_zero(p->okcontacturi))
5986 c = is_strict ? p->route->hop : p->okcontacturi;
5987 else
5988 c = p->initreq.rlPart2;
5989 } else if (!ast_strlen_zero(p->okcontacturi))
5990 c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
5991 else if (!ast_strlen_zero(p->uri))
5992 c = p->uri;
5993 else {
5994 char *n;
5995 /* We have no URI, use To: or From: header as URI (depending on direction) */
5996 ast_copy_string(stripped, get_header(orig, (ast_test_flag(&p->flags[0], SIP_OUTGOING)) ? "To" : "From"),
5997 sizeof(stripped));
5998 n = get_in_brackets(stripped);
5999 c = strsep(&n, ";"); /* trim ; and beyond */
6001 init_req(req, sipmethod, c);
6003 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
6005 add_header(req, "Via", p->via);
6006 if (p->route) {
6007 set_destination(p, p->route->hop);
6008 add_route(req, is_strict ? p->route->next : p->route);
6011 ot = get_header(orig, "To");
6012 of = get_header(orig, "From");
6014 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
6015 as our original request, including tag (or presumably lack thereof) */
6016 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
6017 /* Add the proper tag if we don't have it already. If they have specified
6018 their tag, use it. Otherwise, use our own tag */
6019 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_strlen_zero(p->theirtag))
6020 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
6021 else if (!ast_test_flag(&p->flags[0], SIP_OUTGOING))
6022 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
6023 else
6024 snprintf(newto, sizeof(newto), "%s", ot);
6025 ot = newto;
6028 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
6029 add_header(req, "From", of);
6030 add_header(req, "To", ot);
6031 } else {
6032 add_header(req, "From", ot);
6033 add_header(req, "To", of);
6035 /* Do not add Contact for MESSAGE, BYE and Cancel requests */
6036 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
6037 add_header(req, "Contact", p->our_contact);
6039 copy_header(req, orig, "Call-ID");
6040 add_header(req, "CSeq", tmp);
6042 if (!ast_strlen_zero(global_useragent))
6043 add_header(req, "User-Agent", global_useragent);
6044 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
6046 if (!ast_strlen_zero(p->rpid))
6047 add_header(req, "Remote-Party-ID", p->rpid);
6049 return 0;
6052 /*! \brief Base transmit response function */
6053 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
6055 struct sip_request resp;
6056 int seqno = 0;
6058 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
6059 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
6060 return -1;
6062 respprep(&resp, p, msg, req);
6063 add_header_contentLength(&resp, 0);
6064 /* If we are cancelling an incoming invite for some reason, add information
6065 about the reason why we are doing this in clear text */
6066 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
6067 char buf[10];
6069 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
6070 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
6071 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
6073 return send_response(p, &resp, reliable, seqno);
6076 static void temp_pvt_cleanup(void *data)
6078 struct sip_pvt *p = data;
6080 ast_string_field_free_memory(p);
6082 free(data);
6085 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
6086 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)
6088 struct sip_pvt *p = NULL;
6090 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
6091 ast_log(LOG_NOTICE, "Failed to get temporary pvt\n");
6092 return -1;
6095 /* if the structure was just allocated, initialize it */
6096 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
6097 ast_set_flag(&p->flags[0], SIP_NO_HISTORY);
6098 if (ast_string_field_init(p, 512))
6099 return -1;
6102 /* Initialize the bare minimum */
6103 p->method = intended_method;
6105 if (sin) {
6106 p->sa = *sin;
6107 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
6108 p->ourip = __ourip;
6109 } else
6110 p->ourip = __ourip;
6112 p->branch = ast_random();
6113 make_our_tag(p->tag, sizeof(p->tag));
6114 p->ocseq = INITIAL_CSEQ;
6116 if (useglobal_nat && sin) {
6117 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
6118 p->recv = *sin;
6119 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
6121 check_via(p, req);
6123 ast_string_field_set(p, fromdomain, default_fromdomain);
6124 build_via(p);
6125 ast_string_field_set(p, callid, callid);
6127 /* Use this temporary pvt structure to send the message */
6128 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
6130 /* Free the string fields, but not the pool space */
6131 ast_string_field_reset_all(p);
6133 return 0;
6136 /*! \brief Transmit response, no retransmits */
6137 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
6139 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
6142 /*! \brief Transmit response, no retransmits */
6143 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
6145 struct sip_request resp;
6146 respprep(&resp, p, msg, req);
6147 append_date(&resp);
6148 add_header(&resp, "Unsupported", unsupported);
6149 add_header_contentLength(&resp, 0);
6150 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
6153 /*! \brief Transmit response, Make sure you get an ACK
6154 This is only used for responses to INVITEs, where we need to make sure we get an ACK
6156 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
6158 return __transmit_response(p, msg, req, XMIT_CRITICAL);
6161 /*! \brief Append date to SIP message */
6162 static void append_date(struct sip_request *req)
6164 char tmpdat[256];
6165 struct tm tm;
6166 time_t t = time(NULL);
6168 gmtime_r(&t, &tm);
6169 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
6170 add_header(req, "Date", tmpdat);
6173 /*! \brief Append date and content length before transmitting response */
6174 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
6176 struct sip_request resp;
6177 respprep(&resp, p, msg, req);
6178 append_date(&resp);
6179 add_header_contentLength(&resp, 0);
6180 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
6183 /*! \brief Append Accept header, content length before transmitting response */
6184 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
6186 struct sip_request resp;
6187 respprep(&resp, p, msg, req);
6188 add_header(&resp, "Accept", "application/sdp");
6189 add_header_contentLength(&resp, 0);
6190 return send_response(p, &resp, reliable, 0);
6193 /*! \brief Respond with authorization request */
6194 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)
6196 struct sip_request resp;
6197 char tmp[512];
6198 int seqno = 0;
6200 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
6201 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
6202 return -1;
6204 /* Stale means that they sent us correct authentication, but
6205 based it on an old challenge (nonce) */
6206 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
6207 respprep(&resp, p, msg, req);
6208 add_header(&resp, header, tmp);
6209 add_header_contentLength(&resp, 0);
6210 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
6211 return send_response(p, &resp, reliable, seqno);
6214 /*! \brief Add text body to SIP message */
6215 static int add_text(struct sip_request *req, const char *text)
6217 /* XXX Convert \n's to \r\n's XXX */
6218 add_header(req, "Content-Type", "text/plain");
6219 add_header_contentLength(req, strlen(text));
6220 add_line(req, text);
6221 return 0;
6224 /*! \brief Add DTMF INFO tone to sip message */
6225 /* Always adds default duration 250 ms, regardless of what came in over the line */
6226 static int add_digit(struct sip_request *req, char digit, unsigned int duration)
6228 char tmp[256];
6230 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
6231 add_header(req, "Content-Type", "application/dtmf-relay");
6232 add_header_contentLength(req, strlen(tmp));
6233 add_line(req, tmp);
6234 return 0;
6237 /*! \brief add XML encoded media control with update
6238 \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
6239 static int add_vidupdate(struct sip_request *req)
6241 const char *xml_is_a_huge_waste_of_space =
6242 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
6243 " <media_control>\r\n"
6244 " <vc_primitive>\r\n"
6245 " <to_encoder>\r\n"
6246 " <picture_fast_update>\r\n"
6247 " </picture_fast_update>\r\n"
6248 " </to_encoder>\r\n"
6249 " </vc_primitive>\r\n"
6250 " </media_control>\r\n";
6251 add_header(req, "Content-Type", "application/media_control+xml");
6252 add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
6253 add_line(req, xml_is_a_huge_waste_of_space);
6254 return 0;
6257 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
6258 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
6259 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
6260 int debug, int *min_packet_size)
6262 int rtp_code;
6263 struct ast_format_list fmt;
6266 if (debug)
6267 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
6268 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
6269 return;
6271 if (p->rtp) {
6272 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
6273 fmt = ast_codec_pref_getsize(pref, codec);
6274 } 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 */
6275 return;
6276 ast_build_string(m_buf, m_size, " %d", rtp_code);
6277 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
6278 ast_rtp_lookup_mime_subtype(1, codec,
6279 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
6280 sample_rate);
6281 if (codec == AST_FORMAT_G729A) {
6282 /* Indicate that we don't support VAD (G.729 annex B) */
6283 ast_build_string(a_buf, a_size, "a=fmtp:%d annexb=no\r\n", rtp_code);
6284 } else if (codec == AST_FORMAT_G723_1) {
6285 /* Indicate that we don't support VAD (G.723.1 annex A) */
6286 ast_build_string(a_buf, a_size, "a=fmtp:%d annexa=no\r\n", rtp_code);
6287 } else if (codec == AST_FORMAT_ILBC) {
6288 /* Add information about us using only 20/30 ms packetization */
6289 ast_build_string(a_buf, a_size, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
6292 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
6293 *min_packet_size = fmt.cur_ms;
6295 /* Our first codec packetization processed cannot be less than zero */
6296 if ((*min_packet_size) == 0 && fmt.cur_ms)
6297 *min_packet_size = fmt.cur_ms;
6300 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
6301 static int t38_get_rate(int t38cap)
6303 int maxrate = (t38cap & (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400));
6305 if (maxrate & T38FAX_RATE_14400) {
6306 if (option_debug > 1)
6307 ast_log(LOG_DEBUG, "T38MaxFaxRate 14400 found\n");
6308 return 14400;
6309 } else if (maxrate & T38FAX_RATE_12000) {
6310 if (option_debug > 1)
6311 ast_log(LOG_DEBUG, "T38MaxFaxRate 12000 found\n");
6312 return 12000;
6313 } else if (maxrate & T38FAX_RATE_9600) {
6314 if (option_debug > 1)
6315 ast_log(LOG_DEBUG, "T38MaxFaxRate 9600 found\n");
6316 return 9600;
6317 } else if (maxrate & T38FAX_RATE_7200) {
6318 if (option_debug > 1)
6319 ast_log(LOG_DEBUG, "T38MaxFaxRate 7200 found\n");
6320 return 7200;
6321 } else if (maxrate & T38FAX_RATE_4800) {
6322 if (option_debug > 1)
6323 ast_log(LOG_DEBUG, "T38MaxFaxRate 4800 found\n");
6324 return 4800;
6325 } else if (maxrate & T38FAX_RATE_2400) {
6326 if (option_debug > 1)
6327 ast_log(LOG_DEBUG, "T38MaxFaxRate 2400 found\n");
6328 return 2400;
6329 } else {
6330 if (option_debug > 1)
6331 ast_log(LOG_DEBUG, "Strange, T38MaxFaxRate NOT found in peers T38 SDP.\n");
6332 return 0;
6336 /*! \brief Add T.38 Session Description Protocol message */
6337 static int add_t38_sdp(struct sip_request *resp, struct sip_pvt *p)
6339 int len = 0;
6340 int x = 0;
6341 struct sockaddr_in udptlsin;
6342 char v[256] = "";
6343 char s[256] = "";
6344 char o[256] = "";
6345 char c[256] = "";
6346 char t[256] = "";
6347 char m_modem[256];
6348 char a_modem[1024];
6349 char *m_modem_next = m_modem;
6350 size_t m_modem_left = sizeof(m_modem);
6351 char *a_modem_next = a_modem;
6352 size_t a_modem_left = sizeof(a_modem);
6353 struct sockaddr_in udptldest = { 0, };
6354 int debug;
6356 debug = sip_debug_test_pvt(p);
6357 len = 0;
6358 if (!p->udptl) {
6359 ast_log(LOG_WARNING, "No way to add SDP without an UDPTL structure\n");
6360 return -1;
6363 if (!p->sessionid) {
6364 p->sessionid = getpid();
6365 p->sessionversion = p->sessionid;
6366 } else
6367 p->sessionversion++;
6369 /* Our T.38 end is */
6370 ast_udptl_get_us(p->udptl, &udptlsin);
6372 /* Determine T.38 UDPTL destination */
6373 if (p->udptlredirip.sin_addr.s_addr) {
6374 udptldest.sin_port = p->udptlredirip.sin_port;
6375 udptldest.sin_addr = p->udptlredirip.sin_addr;
6376 } else {
6377 udptldest.sin_addr = p->ourip;
6378 udptldest.sin_port = udptlsin.sin_port;
6381 if (debug)
6382 ast_log(LOG_DEBUG, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(udptlsin.sin_port));
6384 /* We break with the "recommendation" and send our IP, in order that our
6385 peer doesn't have to ast_gethostbyname() us */
6387 if (debug) {
6388 ast_log(LOG_DEBUG, "Our T38 capability (%d), peer T38 capability (%d), joint capability (%d)\n",
6389 p->t38.capability,
6390 p->t38.peercapability,
6391 p->t38.jointcapability);
6393 snprintf(v, sizeof(v), "v=0\r\n");
6394 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(udptldest.sin_addr));
6395 snprintf(s, sizeof(s), "s=session\r\n");
6396 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(udptldest.sin_addr));
6397 snprintf(t, sizeof(t), "t=0 0\r\n");
6398 ast_build_string(&m_modem_next, &m_modem_left, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
6400 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_0)
6401 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:0\r\n");
6402 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_1)
6403 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:1\r\n");
6404 if ((x = t38_get_rate(p->t38.jointcapability)))
6405 ast_build_string(&a_modem_next, &a_modem_left, "a=T38MaxBitRate:%d\r\n",x);
6406 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxFillBitRemoval:%d\r\n", (p->t38.jointcapability & T38FAX_FILL_BIT_REMOVAL) ? 1 : 0);
6407 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingMMR:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_MMR) ? 1 : 0);
6408 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingJBIG:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_JBIG) ? 1 : 0);
6409 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxRateManagement:%s\r\n", (p->t38.jointcapability & T38FAX_RATE_MANAGEMENT_LOCAL_TCF) ? "localTCF" : "transferredTCF");
6410 x = ast_udptl_get_local_max_datagram(p->udptl);
6411 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxBuffer:%d\r\n",x);
6412 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxDatagram:%d\r\n",x);
6413 if (p->t38.jointcapability != T38FAX_UDP_EC_NONE)
6414 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxUdpEC:%s\r\n", (p->t38.jointcapability & T38FAX_UDP_EC_REDUNDANCY) ? "t38UDPRedundancy" : "t38UDPFEC");
6415 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m_modem) + strlen(a_modem);
6416 add_header(resp, "Content-Type", "application/sdp");
6417 add_header_contentLength(resp, len);
6418 add_line(resp, v);
6419 add_line(resp, o);
6420 add_line(resp, s);
6421 add_line(resp, c);
6422 add_line(resp, t);
6423 add_line(resp, m_modem);
6424 add_line(resp, a_modem);
6426 /* Update lastrtprx when we send our SDP */
6427 p->lastrtprx = p->lastrtptx = time(NULL);
6429 return 0;
6433 /*! \brief Add RFC 2833 DTMF offer to SDP */
6434 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
6435 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
6436 int debug)
6438 int rtp_code;
6440 if (debug)
6441 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
6442 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
6443 return;
6445 ast_build_string(m_buf, m_size, " %d", rtp_code);
6446 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
6447 ast_rtp_lookup_mime_subtype(0, format, 0),
6448 sample_rate);
6449 if (format == AST_RTP_DTMF)
6450 /* Indicate we support DTMF and FLASH... */
6451 ast_build_string(a_buf, a_size, "a=fmtp:%d 0-16\r\n", rtp_code);
6455 * \note G.722 actually is supposed to specified as 8 kHz, even though it is
6456 * really 16 kHz. Update this macro for other formats as they are added in
6457 * the future.
6459 #define SDP_SAMPLE_RATE(x) 8000
6461 /*! \brief Add Session Description Protocol message */
6462 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p)
6464 int len = 0;
6465 int alreadysent = 0;
6467 struct sockaddr_in sin;
6468 struct sockaddr_in vsin;
6469 struct sockaddr_in dest;
6470 struct sockaddr_in vdest = { 0, };
6472 /* SDP fields */
6473 char *version = "v=0\r\n"; /* Protocol version */
6474 char *subject = "s=session\r\n"; /* Subject of the session */
6475 char owner[256]; /* Session owner/creator */
6476 char connection[256]; /* Connection data */
6477 char *stime = "t=0 0\r\n"; /* Time the session is active */
6478 char bandwidth[256] = ""; /* Max bitrate */
6479 char *hold;
6480 char m_audio[256]; /* Media declaration line for audio */
6481 char m_video[256]; /* Media declaration line for video */
6482 char a_audio[1024]; /* Attributes for audio */
6483 char a_video[1024]; /* Attributes for video */
6484 char *m_audio_next = m_audio;
6485 char *m_video_next = m_video;
6486 size_t m_audio_left = sizeof(m_audio);
6487 size_t m_video_left = sizeof(m_video);
6488 char *a_audio_next = a_audio;
6489 char *a_video_next = a_video;
6490 size_t a_audio_left = sizeof(a_audio);
6491 size_t a_video_left = sizeof(a_video);
6493 int x;
6494 int capability;
6495 int needvideo = FALSE;
6496 int debug = sip_debug_test_pvt(p);
6497 int min_audio_packet_size = 0;
6498 int min_video_packet_size = 0;
6500 m_video[0] = '\0'; /* Reset the video media string if it's not needed */
6502 if (!p->rtp) {
6503 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
6504 return AST_FAILURE;
6507 /* Set RTP Session ID and version */
6508 if (!p->sessionid) {
6509 p->sessionid = getpid();
6510 p->sessionversion = p->sessionid;
6511 } else
6512 p->sessionversion++;
6514 /* Get our addresses */
6515 ast_rtp_get_us(p->rtp, &sin);
6516 if (p->vrtp)
6517 ast_rtp_get_us(p->vrtp, &vsin);
6519 /* Is this a re-invite to move the media out, then use the original offer from caller */
6520 if (p->redirip.sin_addr.s_addr) {
6521 dest.sin_port = p->redirip.sin_port;
6522 dest.sin_addr = p->redirip.sin_addr;
6523 } else {
6524 dest.sin_addr = p->ourip;
6525 dest.sin_port = sin.sin_port;
6528 capability = p->jointcapability;
6531 if (option_debug > 1) {
6532 char codecbuf[SIPBUFSIZE];
6533 ast_log(LOG_DEBUG, "** Our capability: %s Video flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability), ast_test_flag(&p->flags[0], SIP_NOVIDEO) ? "True" : "False");
6534 ast_log(LOG_DEBUG, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
6537 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
6538 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_RTP)) {
6539 ast_build_string(&m_audio_next, &m_audio_left, " %d", 191);
6540 ast_build_string(&a_audio_next, &a_audio_left, "a=rtpmap:%d %s/%d\r\n", 191, "t38", 8000);
6542 #endif
6544 /* Check if we need video in this call */
6545 if ((capability & AST_FORMAT_VIDEO_MASK) && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
6546 if (p->vrtp) {
6547 needvideo = TRUE;
6548 if (option_debug > 1)
6549 ast_log(LOG_DEBUG, "This call needs video offers!\n");
6550 } else if (option_debug > 1)
6551 ast_log(LOG_DEBUG, "This call needs video offers, but there's no video support enabled!\n");
6555 /* Ok, we need video. Let's add what we need for video and set codecs.
6556 Video is handled differently than audio since we can not transcode. */
6557 if (needvideo) {
6558 /* Determine video destination */
6559 if (p->vredirip.sin_addr.s_addr) {
6560 vdest.sin_addr = p->vredirip.sin_addr;
6561 vdest.sin_port = p->vredirip.sin_port;
6562 } else {
6563 vdest.sin_addr = p->ourip;
6564 vdest.sin_port = vsin.sin_port;
6566 ast_build_string(&m_video_next, &m_video_left, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
6568 /* Build max bitrate string */
6569 if (p->maxcallbitrate)
6570 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
6571 if (debug)
6572 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(vsin.sin_port));
6575 if (debug)
6576 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(sin.sin_port));
6578 /* Start building generic SDP headers */
6580 /* We break with the "recommendation" and send our IP, in order that our
6581 peer doesn't have to ast_gethostbyname() us */
6583 snprintf(owner, sizeof(owner), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
6584 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
6585 ast_build_string(&m_audio_next, &m_audio_left, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
6587 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
6588 hold = "a=recvonly\r\n";
6589 else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
6590 hold = "a=inactive\r\n";
6591 else
6592 hold = "a=sendrecv\r\n";
6594 /* Now, start adding audio codecs. These are added in this order:
6595 - First what was requested by the calling channel
6596 - Then preferences in order from sip.conf device config for this peer/user
6597 - Then other codecs in capabilities, including video
6600 /* Prefer the audio codec we were requested to use, first, no matter what
6601 Note that p->prefcodec can include video codecs, so mask them out
6603 if (capability & p->prefcodec) {
6604 int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
6606 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
6607 &m_audio_next, &m_audio_left,
6608 &a_audio_next, &a_audio_left,
6609 debug, &min_audio_packet_size);
6610 alreadysent |= codec;
6613 /* Start by sending our preferred audio codecs */
6614 for (x = 0; x < 32; x++) {
6615 int codec;
6617 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
6618 break;
6620 if (!(capability & codec))
6621 continue;
6623 if (alreadysent & codec)
6624 continue;
6626 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
6627 &m_audio_next, &m_audio_left,
6628 &a_audio_next, &a_audio_left,
6629 debug, &min_audio_packet_size);
6630 alreadysent |= codec;
6633 /* Now send any other common audio and video codecs, and non-codec formats: */
6634 for (x = 1; x <= (needvideo ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
6635 if (!(capability & x)) /* Codec not requested */
6636 continue;
6638 if (alreadysent & x) /* Already added to SDP */
6639 continue;
6641 if (x <= AST_FORMAT_MAX_AUDIO)
6642 add_codec_to_sdp(p, x, SDP_SAMPLE_RATE(x),
6643 &m_audio_next, &m_audio_left,
6644 &a_audio_next, &a_audio_left,
6645 debug, &min_audio_packet_size);
6646 else
6647 add_codec_to_sdp(p, x, 90000,
6648 &m_video_next, &m_video_left,
6649 &a_video_next, &a_video_left,
6650 debug, &min_video_packet_size);
6653 /* Now add DTMF RFC2833 telephony-event as a codec */
6654 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
6655 if (!(p->jointnoncodeccapability & x))
6656 continue;
6658 add_noncodec_to_sdp(p, x, 8000,
6659 &m_audio_next, &m_audio_left,
6660 &a_audio_next, &a_audio_left,
6661 debug);
6664 if (option_debug > 2)
6665 ast_log(LOG_DEBUG, "-- Done with adding codecs to SDP\n");
6667 if (!p->owner || !ast_internal_timing_enabled(p->owner))
6668 ast_build_string(&a_audio_next, &a_audio_left, "a=silenceSupp:off - - - -\r\n");
6670 if (min_audio_packet_size)
6671 ast_build_string(&a_audio_next, &a_audio_left, "a=ptime:%d\r\n", min_audio_packet_size);
6673 if (min_video_packet_size)
6674 ast_build_string(&a_video_next, &a_video_left, "a=ptime:%d\r\n", min_video_packet_size);
6676 if ((m_audio_left < 2) || (m_video_left < 2) || (a_audio_left == 0) || (a_video_left == 0))
6677 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
6679 ast_build_string(&m_audio_next, &m_audio_left, "\r\n");
6680 if (needvideo)
6681 ast_build_string(&m_video_next, &m_video_left, "\r\n");
6683 len = strlen(version) + strlen(subject) + strlen(owner) + strlen(connection) + strlen(stime) + strlen(m_audio) + strlen(a_audio) + strlen(hold);
6684 if (needvideo) /* only if video response is appropriate */
6685 len += strlen(m_video) + strlen(a_video) + strlen(bandwidth) + strlen(hold);
6687 add_header(resp, "Content-Type", "application/sdp");
6688 add_header_contentLength(resp, len);
6689 add_line(resp, version);
6690 add_line(resp, owner);
6691 add_line(resp, subject);
6692 add_line(resp, connection);
6693 if (needvideo) /* only if video response is appropriate */
6694 add_line(resp, bandwidth);
6695 add_line(resp, stime);
6696 add_line(resp, m_audio);
6697 add_line(resp, a_audio);
6698 add_line(resp, hold);
6699 if (needvideo) { /* only if video response is appropriate */
6700 add_line(resp, m_video);
6701 add_line(resp, a_video);
6702 add_line(resp, hold); /* Repeat hold for the video stream */
6705 /* Update lastrtprx when we send our SDP */
6706 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
6708 if (option_debug > 2) {
6709 char buf[SIPBUFSIZE];
6710 ast_log(LOG_DEBUG, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
6713 return AST_SUCCESS;
6716 /*! \brief Used for 200 OK and 183 early media */
6717 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
6719 struct sip_request resp;
6720 int seqno;
6722 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
6723 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
6724 return -1;
6726 respprep(&resp, p, msg, req);
6727 if (p->udptl) {
6728 ast_udptl_offered_from_local(p->udptl, 0);
6729 add_t38_sdp(&resp, p);
6730 } else
6731 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
6732 if (retrans && !p->pendinginvite)
6733 p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
6734 return send_response(p, &resp, retrans, seqno);
6737 /*! \brief copy SIP request (mostly used to save request for responses) */
6738 static void copy_request(struct sip_request *dst, const struct sip_request *src)
6740 long offset;
6741 int x;
6742 offset = ((void *)dst) - ((void *)src);
6743 /* First copy stuff */
6744 memcpy(dst, src, sizeof(*dst));
6745 /* Now fix pointer arithmetic */
6746 for (x=0; x < src->headers; x++)
6747 dst->header[x] += offset;
6748 for (x=0; x < src->lines; x++)
6749 dst->line[x] += offset;
6750 dst->rlPart1 += offset;
6751 dst->rlPart2 += offset;
6754 /*! \brief Used for 200 OK and 183 early media
6755 \return Will return XMIT_ERROR for network errors.
6757 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
6759 struct sip_request resp;
6760 int seqno;
6761 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
6762 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
6763 return -1;
6765 respprep(&resp, p, msg, req);
6766 if (p->rtp) {
6767 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
6768 if (option_debug)
6769 ast_log(LOG_DEBUG, "Setting framing from config on incoming call\n");
6770 ast_rtp_codec_setpref(p->rtp, &p->prefs);
6772 try_suggested_sip_codec(p);
6773 add_sdp(&resp, p);
6774 } else
6775 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
6776 if (reliable && !p->pendinginvite)
6777 p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
6778 return send_response(p, &resp, reliable, seqno);
6781 /*! \brief Parse first line of incoming SIP request */
6782 static int determine_firstline_parts(struct sip_request *req)
6784 char *e = ast_skip_blanks(req->header[0]); /* there shouldn't be any */
6786 if (!*e)
6787 return -1;
6788 req->rlPart1 = e; /* method or protocol */
6789 e = ast_skip_nonblanks(e);
6790 if (*e)
6791 *e++ = '\0';
6792 /* Get URI or status code */
6793 e = ast_skip_blanks(e);
6794 if ( !*e )
6795 return -1;
6796 ast_trim_blanks(e);
6798 if (!strcasecmp(req->rlPart1, "SIP/2.0") ) { /* We have a response */
6799 if (strlen(e) < 3) /* status code is 3 digits */
6800 return -1;
6801 req->rlPart2 = e;
6802 } else { /* We have a request */
6803 if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
6804 ast_log(LOG_WARNING, "bogus uri in <> %s\n", e);
6805 e++;
6806 if (!*e)
6807 return -1;
6809 req->rlPart2 = e; /* URI */
6810 e = ast_skip_nonblanks(e);
6811 if (*e)
6812 *e++ = '\0';
6813 e = ast_skip_blanks(e);
6814 if (strcasecmp(e, "SIP/2.0") ) {
6815 ast_log(LOG_WARNING, "Bad request protocol %s\n", e);
6816 return -1;
6819 return 1;
6822 /*! \brief Transmit reinvite with SDP
6823 \note A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
6824 INVITE that opened the SIP dialogue
6825 We reinvite so that the audio stream (RTP) go directly between
6826 the SIP UAs. SIP Signalling stays with * in the path.
6828 static int transmit_reinvite_with_sdp(struct sip_pvt *p)
6830 struct sip_request req;
6832 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
6834 add_header(&req, "Allow", ALLOWED_METHODS);
6835 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6836 if (sipdebug)
6837 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
6838 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
6839 append_history(p, "ReInv", "Re-invite sent");
6840 add_sdp(&req, p);
6841 /* Use this as the basis */
6842 initialize_initreq(p, &req);
6843 p->lastinvite = p->ocseq;
6844 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Change direction of this dialog */
6845 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
6848 /*! \brief Transmit reinvite with T38 SDP
6849 We reinvite so that the T38 processing can take place.
6850 SIP Signalling stays with * in the path.
6852 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p)
6854 struct sip_request req;
6856 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
6858 add_header(&req, "Allow", ALLOWED_METHODS);
6859 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6860 if (sipdebug)
6861 add_header(&req, "X-asterisk-info", "SIP re-invite (T38 switchover)");
6862 ast_udptl_offered_from_local(p->udptl, 1);
6863 add_t38_sdp(&req, p);
6864 /* Use this as the basis */
6865 initialize_initreq(p, &req);
6866 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Change direction of this dialog */
6867 p->lastinvite = p->ocseq;
6868 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
6871 /*! \brief Check Contact: URI of SIP message */
6872 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
6874 char stripped[SIPBUFSIZE];
6875 char *c;
6877 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
6878 c = get_in_brackets(stripped);
6879 c = strsep(&c, ";"); /* trim ; and beyond */
6880 if (!ast_strlen_zero(c))
6881 ast_string_field_set(p, uri, c);
6884 /*! \brief Build contact header - the contact header we send out */
6885 static void build_contact(struct sip_pvt *p)
6887 /* Construct Contact: header */
6888 if (ourport != STANDARD_SIP_PORT)
6889 ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip), ourport);
6890 else
6891 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip));
6894 /*! \brief Build the Remote Party-ID & From using callingpres options */
6895 static void build_rpid(struct sip_pvt *p)
6897 int send_pres_tags = TRUE;
6898 const char *privacy=NULL;
6899 const char *screen=NULL;
6900 char buf[256];
6901 const char *clid = default_callerid;
6902 const char *clin = NULL;
6903 const char *fromdomain;
6905 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
6906 return;
6908 if (p->owner && p->owner->cid.cid_num)
6909 clid = p->owner->cid.cid_num;
6910 if (p->owner && p->owner->cid.cid_name)
6911 clin = p->owner->cid.cid_name;
6912 if (ast_strlen_zero(clin))
6913 clin = clid;
6915 switch (p->callingpres) {
6916 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
6917 privacy = "off";
6918 screen = "no";
6919 break;
6920 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
6921 privacy = "off";
6922 screen = "yes";
6923 break;
6924 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
6925 privacy = "off";
6926 screen = "no";
6927 break;
6928 case AST_PRES_ALLOWED_NETWORK_NUMBER:
6929 privacy = "off";
6930 screen = "yes";
6931 break;
6932 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
6933 privacy = "full";
6934 screen = "no";
6935 break;
6936 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
6937 privacy = "full";
6938 screen = "yes";
6939 break;
6940 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
6941 privacy = "full";
6942 screen = "no";
6943 break;
6944 case AST_PRES_PROHIB_NETWORK_NUMBER:
6945 privacy = "full";
6946 screen = "yes";
6947 break;
6948 case AST_PRES_NUMBER_NOT_AVAILABLE:
6949 send_pres_tags = FALSE;
6950 break;
6951 default:
6952 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
6953 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
6954 privacy = "full";
6955 else
6956 privacy = "off";
6957 screen = "no";
6958 break;
6961 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip));
6963 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
6964 if (send_pres_tags)
6965 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
6966 ast_string_field_set(p, rpid, buf);
6968 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
6969 S_OR(p->fromuser, clid),
6970 fromdomain, p->tag);
6973 /*! \brief Initiate new SIP request to peer/user */
6974 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
6976 char invite_buf[256] = "";
6977 char *invite = invite_buf;
6978 size_t invite_max = sizeof(invite_buf);
6979 char from[256];
6980 char to[256];
6981 char tmp[SIPBUFSIZE/2];
6982 char tmp2[SIPBUFSIZE/2];
6983 const char *l = NULL, *n = NULL;
6984 const char *urioptions = "";
6986 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
6987 const char *s = p->username; /* being a string field, cannot be NULL */
6989 /* Test p->username against allowed characters in AST_DIGIT_ANY
6990 If it matches the allowed characters list, then sipuser = ";user=phone"
6991 If not, then sipuser = ""
6993 /* + is allowed in first position in a tel: uri */
6994 if (*s == '+')
6995 s++;
6996 for (; *s; s++) {
6997 if (!strchr(AST_DIGIT_ANYNUM, *s) )
6998 break;
7000 /* If we have only digits, add ;user=phone to the uri */
7001 if (*s)
7002 urioptions = ";user=phone";
7006 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
7008 if (p->owner) {
7009 l = p->owner->cid.cid_num;
7010 n = p->owner->cid.cid_name;
7012 /* if we are not sending RPID and user wants his callerid restricted */
7013 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
7014 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
7015 l = CALLERID_UNKNOWN;
7016 n = l;
7018 if (ast_strlen_zero(l))
7019 l = default_callerid;
7020 if (ast_strlen_zero(n))
7021 n = l;
7022 /* Allow user to be overridden */
7023 if (!ast_strlen_zero(p->fromuser))
7024 l = p->fromuser;
7025 else /* Save for any further attempts */
7026 ast_string_field_set(p, fromuser, l);
7028 /* Allow user to be overridden */
7029 if (!ast_strlen_zero(p->fromname))
7030 n = p->fromname;
7031 else /* Save for any further attempts */
7032 ast_string_field_set(p, fromname, n);
7034 if (pedanticsipchecking) {
7035 ast_uri_encode(n, tmp, sizeof(tmp), 0);
7036 n = tmp;
7037 ast_uri_encode(l, tmp2, sizeof(tmp2), 0);
7038 l = tmp2;
7041 if (ourport != STANDARD_SIP_PORT && ast_strlen_zero(p->fromdomain))
7042 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)), ourport, p->tag);
7043 else
7044 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)), p->tag);
7046 /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
7047 if (!ast_strlen_zero(p->fullcontact)) {
7048 /* If we have full contact, trust it */
7049 ast_build_string(&invite, &invite_max, "%s", p->fullcontact);
7050 } else {
7051 /* Otherwise, use the username while waiting for registration */
7052 ast_build_string(&invite, &invite_max, "sip:");
7053 if (!ast_strlen_zero(p->username)) {
7054 n = p->username;
7055 if (pedanticsipchecking) {
7056 ast_uri_encode(n, tmp, sizeof(tmp), 0);
7057 n = tmp;
7059 ast_build_string(&invite, &invite_max, "%s@", n);
7061 ast_build_string(&invite, &invite_max, "%s", p->tohost);
7062 if (ntohs(p->sa.sin_port) != STANDARD_SIP_PORT)
7063 ast_build_string(&invite, &invite_max, ":%d", ntohs(p->sa.sin_port));
7064 ast_build_string(&invite, &invite_max, "%s", urioptions);
7067 /* If custom URI options have been provided, append them */
7068 if (p->options && !ast_strlen_zero(p->options->uri_options))
7069 ast_build_string(&invite, &invite_max, ";%s", p->options->uri_options);
7071 ast_string_field_set(p, uri, invite_buf);
7073 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
7074 /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
7075 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "" : "sip:"), p->uri, p->theirtag);
7076 } else if (p->options && p->options->vxml_url) {
7077 /* If there is a VXML URL append it to the SIP URL */
7078 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
7079 } else
7080 snprintf(to, sizeof(to), "<%s>", p->uri);
7082 init_req(req, sipmethod, p->uri);
7083 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
7085 add_header(req, "Via", p->via);
7086 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
7087 * OTOH, then we won't have anything in p->route anyway */
7088 /* Build Remote Party-ID and From */
7089 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
7090 build_rpid(p);
7091 add_header(req, "From", p->rpid_from);
7092 } else
7093 add_header(req, "From", from);
7094 add_header(req, "To", to);
7095 ast_string_field_set(p, exten, l);
7096 build_contact(p);
7097 add_header(req, "Contact", p->our_contact);
7098 add_header(req, "Call-ID", p->callid);
7099 add_header(req, "CSeq", tmp);
7100 if (!ast_strlen_zero(global_useragent))
7101 add_header(req, "User-Agent", global_useragent);
7102 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
7103 if (!ast_strlen_zero(p->rpid))
7104 add_header(req, "Remote-Party-ID", p->rpid);
7107 /*! \brief Build REFER/INVITE/OPTIONS message and transmit it */
7108 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
7110 struct sip_request req;
7112 req.method = sipmethod;
7113 if (init) { /* Seems like init always is 2 */
7114 /* Bump branch even on initial requests */
7115 p->branch ^= ast_random();
7116 build_via(p);
7117 if (init > 1)
7118 initreqprep(&req, p, sipmethod);
7119 else
7120 reqprep(&req, p, sipmethod, 0, 1);
7121 } else
7122 reqprep(&req, p, sipmethod, 0, 1);
7124 if (p->options && p->options->auth)
7125 add_header(&req, p->options->authheader, p->options->auth);
7126 append_date(&req);
7127 if (sipmethod == SIP_REFER) { /* Call transfer */
7128 if (p->refer) {
7129 char buf[SIPBUFSIZE];
7130 if (!ast_strlen_zero(p->refer->refer_to))
7131 add_header(&req, "Refer-To", p->refer->refer_to);
7132 if (!ast_strlen_zero(p->refer->referred_by)) {
7133 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
7134 add_header(&req, "Referred-By", buf);
7138 /* This new INVITE is part of an attended transfer. Make sure that the
7139 other end knows and replace the current call with this new call */
7140 if (p->options && p->options->replaces && !ast_strlen_zero(p->options->replaces)) {
7141 add_header(&req, "Replaces", p->options->replaces);
7142 add_header(&req, "Require", "replaces");
7145 add_header(&req, "Allow", ALLOWED_METHODS);
7146 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7147 if (p->options && p->options->addsipheaders && p->owner) {
7148 struct ast_channel *chan = p->owner; /* The owner channel */
7149 struct varshead *headp;
7151 ast_channel_lock(chan);
7153 headp = &chan->varshead;
7155 if (!headp)
7156 ast_log(LOG_WARNING,"No Headp for the channel...ooops!\n");
7157 else {
7158 const struct ast_var_t *current;
7159 AST_LIST_TRAVERSE(headp, current, entries) {
7160 /* SIPADDHEADER: Add SIP header to outgoing call */
7161 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
7162 char *content, *end;
7163 const char *header = ast_var_value(current);
7164 char *headdup = ast_strdupa(header);
7166 /* Strip of the starting " (if it's there) */
7167 if (*headdup == '"')
7168 headdup++;
7169 if ((content = strchr(headdup, ':'))) {
7170 *content++ = '\0';
7171 content = ast_skip_blanks(content); /* Skip white space */
7172 /* Strip the ending " (if it's there) */
7173 end = content + strlen(content) -1;
7174 if (*end == '"')
7175 *end = '\0';
7177 add_header(&req, headdup, content);
7178 if (sipdebug)
7179 ast_log(LOG_DEBUG, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
7185 ast_channel_unlock(chan);
7187 if (sdp) {
7188 if (p->udptl && (p->t38.state == T38_LOCAL_DIRECT || p->t38.state == T38_LOCAL_REINVITE)) {
7189 ast_udptl_offered_from_local(p->udptl, 1);
7190 if (option_debug)
7191 ast_log(LOG_DEBUG, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
7192 add_t38_sdp(&req, p);
7193 } else if (p->rtp)
7194 add_sdp(&req, p);
7195 } else {
7196 add_header_contentLength(&req, 0);
7199 if (!p->initreq.headers)
7200 initialize_initreq(p, &req);
7201 p->lastinvite = p->ocseq;
7202 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
7205 /*! \brief Used in the SUBSCRIBE notification subsystem */
7206 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
7208 char tmp[4000], from[256], to[256];
7209 char *t = tmp, *c, *mfrom, *mto;
7210 size_t maxbytes = sizeof(tmp);
7211 struct sip_request req;
7212 char hint[AST_MAX_EXTENSION];
7213 char *statestring = "terminated";
7214 const struct cfsubscription_types *subscriptiontype;
7215 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
7216 char *pidfstate = "--";
7217 char *pidfnote= "Ready";
7219 memset(from, 0, sizeof(from));
7220 memset(to, 0, sizeof(to));
7221 memset(tmp, 0, sizeof(tmp));
7223 switch (state) {
7224 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
7225 statestring = (global_notifyringing) ? "early" : "confirmed";
7226 local_state = NOTIFY_INUSE;
7227 pidfstate = "busy";
7228 pidfnote = "Ringing";
7229 break;
7230 case AST_EXTENSION_RINGING:
7231 statestring = "early";
7232 local_state = NOTIFY_INUSE;
7233 pidfstate = "busy";
7234 pidfnote = "Ringing";
7235 break;
7236 case AST_EXTENSION_INUSE:
7237 statestring = "confirmed";
7238 local_state = NOTIFY_INUSE;
7239 pidfstate = "busy";
7240 pidfnote = "On the phone";
7241 break;
7242 case AST_EXTENSION_BUSY:
7243 statestring = "confirmed";
7244 local_state = NOTIFY_CLOSED;
7245 pidfstate = "busy";
7246 pidfnote = "On the phone";
7247 break;
7248 case AST_EXTENSION_UNAVAILABLE:
7249 statestring = "terminated";
7250 local_state = NOTIFY_CLOSED;
7251 pidfstate = "away";
7252 pidfnote = "Unavailable";
7253 break;
7254 case AST_EXTENSION_ONHOLD:
7255 statestring = "confirmed";
7256 local_state = NOTIFY_CLOSED;
7257 pidfstate = "busy";
7258 pidfnote = "On Hold";
7259 break;
7260 case AST_EXTENSION_NOT_INUSE:
7261 default:
7262 /* Default setting */
7263 break;
7266 subscriptiontype = find_subscription_type(p->subscribed);
7268 /* Check which device/devices we are watching and if they are registered */
7269 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
7270 char *hint2 = hint, *individual_hint = NULL;
7271 int hint_count = 0, unavailable_count = 0;
7273 while ((individual_hint = strsep(&hint2, "&"))) {
7274 hint_count++;
7276 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
7277 unavailable_count++;
7280 /* If none of the hinted devices are registered, we will
7281 * override notification and show no availability.
7283 if (hint_count > 0 && hint_count == unavailable_count) {
7284 local_state = NOTIFY_CLOSED;
7285 pidfstate = "away";
7286 pidfnote = "Not online";
7290 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
7291 c = get_in_brackets(from);
7292 if (strncasecmp(c, "sip:", 4)) {
7293 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
7294 return -1;
7296 mfrom = strsep(&c, ";"); /* trim ; and beyond */
7298 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
7299 c = get_in_brackets(to);
7300 if (strncasecmp(c, "sip:", 4)) {
7301 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
7302 return -1;
7304 mto = strsep(&c, ";"); /* trim ; and beyond */
7306 reqprep(&req, p, SIP_NOTIFY, 0, 1);
7309 add_header(&req, "Event", subscriptiontype->event);
7310 add_header(&req, "Content-Type", subscriptiontype->mediatype);
7311 switch(state) {
7312 case AST_EXTENSION_DEACTIVATED:
7313 if (timeout)
7314 add_header(&req, "Subscription-State", "terminated;reason=timeout");
7315 else {
7316 add_header(&req, "Subscription-State", "terminated;reason=probation");
7317 add_header(&req, "Retry-After", "60");
7319 break;
7320 case AST_EXTENSION_REMOVED:
7321 add_header(&req, "Subscription-State", "terminated;reason=noresource");
7322 break;
7323 default:
7324 if (p->expiry)
7325 add_header(&req, "Subscription-State", "active");
7326 else /* Expired */
7327 add_header(&req, "Subscription-State", "terminated;reason=timeout");
7329 switch (p->subscribed) {
7330 case XPIDF_XML:
7331 case CPIM_PIDF_XML:
7332 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
7333 ast_build_string(&t, &maxbytes, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
7334 ast_build_string(&t, &maxbytes, "<presence>\n");
7335 ast_build_string(&t, &maxbytes, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
7336 ast_build_string(&t, &maxbytes, "<atom id=\"%s\">\n", p->exten);
7337 ast_build_string(&t, &maxbytes, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
7338 ast_build_string(&t, &maxbytes, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
7339 ast_build_string(&t, &maxbytes, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
7340 ast_build_string(&t, &maxbytes, "</address>\n</atom>\n</presence>\n");
7341 break;
7342 case PIDF_XML: /* Eyebeam supports this format */
7343 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
7344 ast_build_string(&t, &maxbytes, "<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);
7345 ast_build_string(&t, &maxbytes, "<pp:person><status>\n");
7346 if (pidfstate[0] != '-')
7347 ast_build_string(&t, &maxbytes, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
7348 ast_build_string(&t, &maxbytes, "</status></pp:person>\n");
7349 ast_build_string(&t, &maxbytes, "<note>%s</note>\n", pidfnote); /* Note */
7350 ast_build_string(&t, &maxbytes, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
7351 ast_build_string(&t, &maxbytes, "<contact priority=\"1\">%s</contact>\n", mto);
7352 if (pidfstate[0] == 'b') /* Busy? Still open ... */
7353 ast_build_string(&t, &maxbytes, "<status><basic>open</basic></status>\n");
7354 else
7355 ast_build_string(&t, &maxbytes, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
7356 ast_build_string(&t, &maxbytes, "</tuple>\n</presence>\n");
7357 break;
7358 case DIALOG_INFO_XML: /* SNOM subscribes in this format */
7359 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
7360 ast_build_string(&t, &maxbytes, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p->dialogver++, full ? "full":"partial", mto);
7361 if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
7362 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
7363 else
7364 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\">\n", p->exten);
7365 ast_build_string(&t, &maxbytes, "<state>%s</state>\n", statestring);
7366 if (state == AST_EXTENSION_ONHOLD) {
7367 ast_build_string(&t, &maxbytes, "<local>\n<target uri=\"%s\">\n"
7368 "<param pname=\"+sip.rendering\" pvalue=\"no\">\n"
7369 "</target>\n</local>\n", mto);
7371 ast_build_string(&t, &maxbytes, "</dialog>\n</dialog-info>\n");
7372 break;
7373 case NONE:
7374 default:
7375 break;
7378 if (t > tmp + sizeof(tmp))
7379 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
7381 add_header_contentLength(&req, strlen(tmp));
7382 add_line(&req, tmp);
7383 p->pendinginvite = p->ocseq; /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
7385 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7388 /*! \brief Notify user of messages waiting in voicemail
7389 \note - Notification only works for registered peers with mailbox= definitions
7390 in sip.conf
7391 - We use the SIP Event package message-summary
7392 MIME type defaults to "application/simple-message-summary";
7394 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
7396 struct sip_request req;
7397 char tmp[500];
7398 char *t = tmp;
7399 size_t maxbytes = sizeof(tmp);
7401 initreqprep(&req, p, SIP_NOTIFY);
7402 add_header(&req, "Event", "message-summary");
7403 add_header(&req, "Content-Type", default_notifymime);
7405 ast_build_string(&t, &maxbytes, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
7406 ast_build_string(&t, &maxbytes, "Message-Account: sip:%s@%s\r\n",
7407 S_OR(vmexten, default_vmexten), S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)));
7408 /* Cisco has a bug in the SIP stack where it can't accept the
7409 (0/0) notification. This can temporarily be disabled in
7410 sip.conf with the "buggymwi" option */
7411 ast_build_string(&t, &maxbytes, "Voice-Message: %d/%d%s\r\n", newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
7413 if (p->subscribed) {
7414 if (p->expiry)
7415 add_header(&req, "Subscription-State", "active");
7416 else /* Expired */
7417 add_header(&req, "Subscription-State", "terminated;reason=timeout");
7420 if (t > tmp + sizeof(tmp))
7421 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
7423 add_header_contentLength(&req, strlen(tmp));
7424 add_line(&req, tmp);
7426 if (!p->initreq.headers)
7427 initialize_initreq(p, &req);
7428 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7431 /*! \brief Transmit SIP request unreliably (only used in sip_notify subsystem) */
7432 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req)
7434 if (!p->initreq.headers) /* Initialize first request before sending */
7435 initialize_initreq(p, req);
7436 return send_request(p, req, XMIT_UNRELIABLE, p->ocseq);
7439 /*! \brief Notify a transferring party of the status of transfer */
7440 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
7442 struct sip_request req;
7443 char tmp[SIPBUFSIZE/2];
7445 reqprep(&req, p, SIP_NOTIFY, 0, 1);
7446 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
7447 add_header(&req, "Event", tmp);
7448 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
7449 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
7450 add_header(&req, "Allow", ALLOWED_METHODS);
7451 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7453 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
7454 add_header_contentLength(&req, strlen(tmp));
7455 add_line(&req, tmp);
7457 if (!p->initreq.headers)
7458 initialize_initreq(p, &req);
7460 p->lastnoninvite = p->ocseq;
7462 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7465 /*! \brief Convert registration state status to string */
7466 static char *regstate2str(enum sipregistrystate regstate)
7468 switch(regstate) {
7469 case REG_STATE_FAILED:
7470 return "Failed";
7471 case REG_STATE_UNREGISTERED:
7472 return "Unregistered";
7473 case REG_STATE_REGSENT:
7474 return "Request Sent";
7475 case REG_STATE_AUTHSENT:
7476 return "Auth. Sent";
7477 case REG_STATE_REGISTERED:
7478 return "Registered";
7479 case REG_STATE_REJECTED:
7480 return "Rejected";
7481 case REG_STATE_TIMEOUT:
7482 return "Timeout";
7483 case REG_STATE_NOAUTH:
7484 return "No Authentication";
7485 default:
7486 return "Unknown";
7490 /*! \brief Update registration with SIP Proxy */
7491 static int sip_reregister(const void *data)
7493 /* if we are here, we know that we need to reregister. */
7494 struct sip_registry *r= ASTOBJ_REF((struct sip_registry *) data);
7496 /* if we couldn't get a reference to the registry object, punt */
7497 if (!r)
7498 return 0;
7500 if (r->call && !ast_test_flag(&r->call->flags[0], SIP_NO_HISTORY))
7501 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
7502 /* Since registry's are only added/removed by the the monitor thread, this
7503 may be overkill to reference/dereference at all here */
7504 if (sipdebug)
7505 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
7507 r->expire = -1;
7508 __sip_do_register(r);
7509 ASTOBJ_UNREF(r, sip_registry_destroy);
7510 return 0;
7513 /*! \brief Register with SIP proxy */
7514 static int __sip_do_register(struct sip_registry *r)
7516 int res;
7518 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
7519 return res;
7522 /*! \brief Registration timeout, register again */
7523 static int sip_reg_timeout(const void *data)
7526 /* if we are here, our registration timed out, so we'll just do it over */
7527 struct sip_registry *r = ASTOBJ_REF((struct sip_registry *) data);
7528 struct sip_pvt *p;
7529 int res;
7531 /* if we couldn't get a reference to the registry object, punt */
7532 if (!r)
7533 return 0;
7535 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
7536 if (r->call) {
7537 /* Unlink us, destroy old call. Locking is not relevant here because all this happens
7538 in the single SIP manager thread. */
7539 p = r->call;
7540 ast_mutex_lock(&p->lock);
7541 if (p->registry)
7542 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
7543 r->call = NULL;
7544 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
7545 /* Pretend to ACK anything just in case */
7546 __sip_pretend_ack(p);
7547 ast_mutex_unlock(&p->lock);
7549 /* If we have a limit, stop registration and give up */
7550 if (global_regattempts_max && (r->regattempts > global_regattempts_max)) {
7551 /* Ok, enough is enough. Don't try any more */
7552 /* We could add an external notification here...
7553 steal it from app_voicemail :-) */
7554 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
7555 r->regstate = REG_STATE_FAILED;
7556 } else {
7557 r->regstate = REG_STATE_UNREGISTERED;
7558 r->timeout = -1;
7559 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
7561 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
7562 ASTOBJ_UNREF(r, sip_registry_destroy);
7563 return 0;
7566 /*! \brief Transmit register to SIP proxy or UA */
7567 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
7569 struct sip_request req;
7570 char from[256];
7571 char to[256];
7572 char tmp[80];
7573 char addr[80];
7574 struct sip_pvt *p;
7576 /* exit if we are already in process with this registrar ?*/
7577 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
7578 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
7579 return 0;
7582 if (r->call) { /* We have a registration */
7583 if (!auth) {
7584 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
7585 return 0;
7586 } else {
7587 p = r->call;
7588 make_our_tag(p->tag, sizeof(p->tag)); /* create a new local tag for every register attempt */
7589 ast_string_field_free(p, theirtag); /* forget their old tag, so we don't match tags when getting response */
7591 } else {
7592 /* Build callid for registration if we haven't registered before */
7593 if (!r->callid_valid) {
7594 build_callid_registry(r, __ourip, default_fromdomain);
7595 r->callid_valid = TRUE;
7597 /* Allocate SIP packet for registration */
7598 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER))) {
7599 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
7600 return 0;
7602 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
7603 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
7604 /* Find address to hostname */
7605 if (create_addr(p, r->hostname)) {
7606 /* we have what we hope is a temporary network error,
7607 * probably DNS. We need to reschedule a registration try */
7608 sip_destroy(p);
7610 if (r->timeout > -1)
7611 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
7612 else
7613 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);
7615 AST_SCHED_DEL(sched, r->timeout);
7616 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
7617 r->regattempts++;
7618 return 0;
7620 /* Copy back Call-ID in case create_addr changed it */
7621 ast_string_field_set(r, callid, p->callid);
7622 if (r->portno) {
7623 p->sa.sin_port = htons(r->portno);
7624 p->recv.sin_port = htons(r->portno);
7625 } else /* Set registry port to the port set from the peer definition/srv or default */
7626 r->portno = ntohs(p->sa.sin_port);
7627 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
7628 r->call=p; /* Save pointer to SIP packet */
7629 p->registry = ASTOBJ_REF(r); /* Add pointer to registry in packet */
7630 if (!ast_strlen_zero(r->secret)) /* Secret (password) */
7631 ast_string_field_set(p, peersecret, r->secret);
7632 if (!ast_strlen_zero(r->md5secret))
7633 ast_string_field_set(p, peermd5secret, r->md5secret);
7634 /* User name in this realm
7635 - if authuser is set, use that, otherwise use username */
7636 if (!ast_strlen_zero(r->authuser)) {
7637 ast_string_field_set(p, peername, r->authuser);
7638 ast_string_field_set(p, authname, r->authuser);
7639 } else if (!ast_strlen_zero(r->username)) {
7640 ast_string_field_set(p, peername, r->username);
7641 ast_string_field_set(p, authname, r->username);
7642 ast_string_field_set(p, fromuser, r->username);
7644 if (!ast_strlen_zero(r->username))
7645 ast_string_field_set(p, username, r->username);
7646 /* Save extension in packet */
7647 ast_string_field_set(p, exten, r->contact);
7650 check which address we should use in our contact header
7651 based on whether the remote host is on the external or
7652 internal network so we can register through nat
7654 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
7655 p->ourip = bindaddr.sin_addr;
7656 build_contact(p);
7659 /* set up a timeout */
7660 if (auth == NULL) {
7661 if (r->timeout > -1)
7662 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
7663 AST_SCHED_DEL(sched, r->timeout);
7664 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
7665 if (option_debug)
7666 ast_log(LOG_DEBUG, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
7669 if (strchr(r->username, '@')) {
7670 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
7671 if (!ast_strlen_zero(p->theirtag))
7672 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
7673 else
7674 snprintf(to, sizeof(to), "<sip:%s>", r->username);
7675 } else {
7676 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
7677 if (!ast_strlen_zero(p->theirtag))
7678 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
7679 else
7680 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
7683 /* Fromdomain is what we are registering to, regardless of actual
7684 host name from SRV */
7685 if (!ast_strlen_zero(p->fromdomain)) {
7686 if (r->portno && r->portno != STANDARD_SIP_PORT)
7687 snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
7688 else
7689 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
7690 } else {
7691 if (r->portno && r->portno != STANDARD_SIP_PORT)
7692 snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
7693 else
7694 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
7696 ast_string_field_set(p, uri, addr);
7698 p->branch ^= ast_random();
7700 init_req(&req, sipmethod, addr);
7702 /* Add to CSEQ */
7703 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
7704 p->ocseq = r->ocseq;
7706 build_via(p);
7707 add_header(&req, "Via", p->via);
7708 add_header(&req, "From", from);
7709 add_header(&req, "To", to);
7710 add_header(&req, "Call-ID", p->callid);
7711 add_header(&req, "CSeq", tmp);
7712 if (!ast_strlen_zero(global_useragent))
7713 add_header(&req, "User-Agent", global_useragent);
7714 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
7717 if (auth) /* Add auth header */
7718 add_header(&req, authheader, auth);
7719 else if (!ast_strlen_zero(r->nonce)) {
7720 char digest[1024];
7722 /* We have auth data to reuse, build a digest header! */
7723 if (sipdebug)
7724 ast_log(LOG_DEBUG, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
7725 ast_string_field_set(p, realm, r->realm);
7726 ast_string_field_set(p, nonce, r->nonce);
7727 ast_string_field_set(p, domain, r->domain);
7728 ast_string_field_set(p, opaque, r->opaque);
7729 ast_string_field_set(p, qop, r->qop);
7730 r->noncecount++;
7731 p->noncecount = r->noncecount;
7733 memset(digest,0,sizeof(digest));
7734 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
7735 add_header(&req, "Authorization", digest);
7736 else
7737 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
7741 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
7742 add_header(&req, "Expires", tmp);
7743 add_header(&req, "Contact", p->our_contact);
7744 add_header(&req, "Event", "registration");
7745 add_header_contentLength(&req, 0);
7747 initialize_initreq(p, &req);
7748 if (sip_debug_test_pvt(p))
7749 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
7750 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
7751 r->regattempts++; /* Another attempt */
7752 if (option_debug > 3)
7753 ast_verbose("REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
7754 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
7757 /*! \brief Transmit text with SIP MESSAGE method */
7758 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
7760 struct sip_request req;
7762 reqprep(&req, p, SIP_MESSAGE, 0, 1);
7763 add_text(&req, text);
7764 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7767 /*! \brief Allocate SIP refer structure */
7768 static int sip_refer_allocate(struct sip_pvt *p)
7770 p->refer = ast_calloc(1, sizeof(struct sip_refer));
7771 return p->refer ? 1 : 0;
7774 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
7775 \note this is currently broken as we have no way of telling the dialplan
7776 engine whether a transfer succeeds or fails.
7777 \todo Fix the transfer() dialplan function so that a transfer may fail
7779 static int transmit_refer(struct sip_pvt *p, const char *dest)
7781 struct sip_request req = {
7782 .headers = 0,
7784 char from[256];
7785 const char *of;
7786 char *c;
7787 char referto[256];
7788 char *ttag, *ftag;
7789 char *theirtag = ast_strdupa(p->theirtag);
7791 if (option_debug || sipdebug)
7792 ast_log(LOG_DEBUG, "SIP transfer of %s to %s\n", p->callid, dest);
7794 /* Are we transfering an inbound or outbound call ? */
7795 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
7796 of = get_header(&p->initreq, "To");
7797 ttag = theirtag;
7798 ftag = p->tag;
7799 } else {
7800 of = get_header(&p->initreq, "From");
7801 ftag = theirtag;
7802 ttag = p->tag;
7805 ast_copy_string(from, of, sizeof(from));
7806 of = get_in_brackets(from);
7807 ast_string_field_set(p, from, of);
7808 if (strncasecmp(of, "sip:", 4))
7809 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
7810 else
7811 of += 4;
7812 /* Get just the username part */
7813 if ((c = strchr(dest, '@')))
7814 c = NULL;
7815 else if ((c = strchr(of, '@')))
7816 *c++ = '\0';
7817 if (c)
7818 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
7819 else
7820 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
7822 /* save in case we get 407 challenge */
7823 sip_refer_allocate(p);
7824 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
7825 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
7826 p->refer->status = REFER_SENT; /* Set refer status */
7828 reqprep(&req, p, SIP_REFER, 0, 1);
7830 add_header(&req, "Refer-To", referto);
7831 add_header(&req, "Allow", ALLOWED_METHODS);
7832 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7833 if (!ast_strlen_zero(p->our_contact))
7834 add_header(&req, "Referred-By", p->our_contact);
7836 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7837 /* We should propably wait for a NOTIFY here until we ack the transfer */
7838 /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
7840 /*! \todo In theory, we should hang around and wait for a reply, before
7841 returning to the dial plan here. Don't know really how that would
7842 affect the transfer() app or the pbx, but, well, to make this
7843 useful we should have a STATUS code on transfer().
7848 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
7849 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
7851 struct sip_request req;
7853 reqprep(&req, p, SIP_INFO, 0, 1);
7854 add_digit(&req, digit, duration);
7855 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7858 /*! \brief Send SIP INFO with video update request */
7859 static int transmit_info_with_vidupdate(struct sip_pvt *p)
7861 struct sip_request req;
7863 reqprep(&req, p, SIP_INFO, 0, 1);
7864 add_vidupdate(&req);
7865 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7868 /*! \brief Transmit generic SIP request
7869 returns XMIT_ERROR if transmit failed with a critical error (don't retry)
7871 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
7873 struct sip_request resp;
7875 if (sipmethod == SIP_ACK)
7876 p->invitestate = INV_CONFIRMED;
7878 reqprep(&resp, p, sipmethod, seqno, newbranch);
7879 add_header_contentLength(&resp, 0);
7880 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
7883 /*! \brief Transmit SIP request, auth added */
7884 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
7886 struct sip_request resp;
7888 reqprep(&resp, p, sipmethod, seqno, newbranch);
7889 if (!ast_strlen_zero(p->realm)) {
7890 char digest[1024];
7892 memset(digest, 0, sizeof(digest));
7893 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
7894 if (p->options && p->options->auth_type == PROXY_AUTH)
7895 add_header(&resp, "Proxy-Authorization", digest);
7896 else if (p->options && p->options->auth_type == WWW_AUTH)
7897 add_header(&resp, "Authorization", digest);
7898 else /* Default, to be backwards compatible (maybe being too careful, but leaving it for now) */
7899 add_header(&resp, "Proxy-Authorization", digest);
7900 } else
7901 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
7903 /* If we are hanging up and know a cause for that, send it in clear text to make
7904 debugging easier. */
7905 if (sipmethod == SIP_BYE && p->owner && p->owner->hangupcause) {
7906 char buf[10];
7908 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
7909 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
7910 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
7913 add_header_contentLength(&resp, 0);
7914 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
7917 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
7918 static void destroy_association(struct sip_peer *peer)
7920 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE)) {
7921 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
7922 ast_update_realtime("sippeers", "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "username", "", "regserver", "", NULL);
7923 else
7924 ast_db_del("SIP/Registry", peer->name);
7928 /*! \brief Expire registration of SIP peer */
7929 static int expire_register(const void *data)
7931 struct sip_peer *peer = (struct sip_peer *)data;
7933 if (!peer) /* Hmmm. We have no peer. Weird. */
7934 return 0;
7936 memset(&peer->addr, 0, sizeof(peer->addr));
7938 destroy_association(peer); /* remove registration data from storage */
7940 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
7941 register_peer_exten(peer, FALSE); /* Remove regexten */
7942 peer->expire = -1;
7943 ast_device_state_changed("SIP/%s", peer->name);
7945 /* Do we need to release this peer from memory?
7946 Only for realtime peers and autocreated peers
7948 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT) ||
7949 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
7950 struct sip_peer *peer_ptr = peer_ptr;
7951 peer_ptr = ASTOBJ_CONTAINER_UNLINK(&peerl, peer);
7952 if (peer_ptr) {
7953 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
7957 ASTOBJ_UNREF(peer, sip_destroy_peer);
7959 return 0;
7962 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
7963 static int sip_poke_peer_s(const void *data)
7965 struct sip_peer *peer = (struct sip_peer *) data;
7967 peer->pokeexpire = -1;
7969 sip_poke_peer(peer);
7971 ASTOBJ_UNREF(peer, sip_destroy_peer);
7973 return 0;
7976 /*! \brief Get registration details from Asterisk DB */
7977 static void reg_source_db(struct sip_peer *peer)
7979 char data[256];
7980 struct in_addr in;
7981 int expiry;
7982 int port;
7983 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
7985 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
7986 return;
7987 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
7988 return;
7990 scan = data;
7991 addr = strsep(&scan, ":");
7992 port_str = strsep(&scan, ":");
7993 expiry_str = strsep(&scan, ":");
7994 username = strsep(&scan, ":");
7995 contact = scan; /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
7997 if (!inet_aton(addr, &in))
7998 return;
8000 if (port_str)
8001 port = atoi(port_str);
8002 else
8003 return;
8005 if (expiry_str)
8006 expiry = atoi(expiry_str);
8007 else
8008 return;
8010 if (username)
8011 ast_copy_string(peer->username, username, sizeof(peer->username));
8012 if (contact)
8013 ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
8015 if (option_debug > 1)
8016 ast_log(LOG_DEBUG, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
8017 peer->name, peer->username, ast_inet_ntoa(in), port, expiry);
8019 memset(&peer->addr, 0, sizeof(peer->addr));
8020 peer->addr.sin_family = AF_INET;
8021 peer->addr.sin_addr = in;
8022 peer->addr.sin_port = htons(port);
8023 if (sipsock < 0) {
8024 /* SIP isn't up yet, so schedule a poke only, pretty soon */
8025 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
8026 struct sip_peer *peer_ptr = peer;
8027 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8029 peer->pokeexpire = ast_sched_add(sched, ast_random() % 5000 + 1, sip_poke_peer_s, ASTOBJ_REF(peer));
8030 if (peer->pokeexpire == -1) {
8031 struct sip_peer *peer_ptr = peer;
8032 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8034 } else
8035 sip_poke_peer(peer);
8036 if (!AST_SCHED_DEL(sched, peer->expire)) {
8037 struct sip_peer *peer_ptr = peer;
8038 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8040 peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, ASTOBJ_REF(peer));
8041 if (peer->expire == -1) {
8042 struct sip_peer *peer_ptr = peer;
8043 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8045 register_peer_exten(peer, TRUE);
8048 /*! \brief Save contact header for 200 OK on INVITE */
8049 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
8051 char contact[SIPBUFSIZE];
8052 char *c;
8054 /* Look for brackets */
8055 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
8056 c = get_in_brackets(contact);
8058 /* Save full contact to call pvt for later bye or re-invite */
8059 ast_string_field_set(pvt, fullcontact, c);
8061 /* Save URI for later ACKs, BYE or RE-invites */
8062 ast_string_field_set(pvt, okcontacturi, c);
8064 /* We should return false for URI:s we can't handle,
8065 like sips:, tel:, mailto:,ldap: etc */
8066 return TRUE;
8069 /*! \brief Change the other partys IP address based on given contact */
8070 static int set_address_from_contact(struct sip_pvt *pvt)
8072 struct hostent *hp;
8073 struct ast_hostent ahp;
8074 int port;
8075 char *c, *host, *pt;
8076 char contact_buf[256];
8077 char *contact;
8079 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
8080 /* NAT: Don't trust the contact field. Just use what they came to us
8081 with. */
8082 pvt->sa = pvt->recv;
8083 return 0;
8086 /* Work on a copy */
8087 ast_copy_string(contact_buf, pvt->fullcontact, sizeof(contact_buf));
8088 contact = contact_buf;
8090 /* Make sure it's a SIP URL */
8091 if (strncasecmp(contact, "sip:", 4)) {
8092 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
8093 } else
8094 contact += 4;
8096 /* Ditch arguments */
8097 /* XXX this code is replicated also shortly below */
8099 /* Grab host */
8100 host = strchr(contact, '@');
8101 if (!host) { /* No username part */
8102 host = contact;
8103 c = NULL;
8104 } else {
8105 *host++ = '\0';
8107 pt = strchr(host, ':');
8108 if (pt) {
8109 *pt++ = '\0';
8110 port = atoi(pt);
8111 } else
8112 port = STANDARD_SIP_PORT;
8114 contact = strsep(&contact, ";"); /* trim ; and beyond in username part */
8115 host = strsep(&host, ";"); /* trim ; and beyond in host/domain part */
8117 /* XXX This could block for a long time XXX */
8118 /* We should only do this if it's a name, not an IP */
8119 hp = ast_gethostbyname(host, &ahp);
8120 if (!hp) {
8121 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
8122 return -1;
8124 pvt->sa.sin_family = AF_INET;
8125 memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
8126 pvt->sa.sin_port = htons(port);
8128 return 0;
8132 /*! \brief Parse contact header and save registration (peer registration) */
8133 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
8135 char contact[SIPBUFSIZE];
8136 char data[SIPBUFSIZE];
8137 const char *expires = get_header(req, "Expires");
8138 int expiry = atoi(expires);
8139 char *curi, *n, *pt;
8140 int port;
8141 const char *useragent;
8142 struct hostent *hp;
8143 struct ast_hostent ahp;
8144 struct sockaddr_in oldsin;
8146 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
8148 if (ast_strlen_zero(expires)) { /* No expires header */
8149 expires = strcasestr(contact, ";expires=");
8150 if (expires) {
8151 /* XXX bug here, we overwrite the string */
8152 expires = strsep((char **) &expires, ";"); /* trim ; and beyond */
8153 if (sscanf(expires + 9, "%d", &expiry) != 1)
8154 expiry = default_expiry;
8155 } else {
8156 /* Nothing has been specified */
8157 expiry = default_expiry;
8161 /* Look for brackets */
8162 curi = contact;
8163 if (strchr(contact, '<') == NULL) /* No <, check for ; and strip it */
8164 strsep(&curi, ";"); /* This is Header options, not URI options */
8165 curi = get_in_brackets(contact);
8167 /* if they did not specify Contact: or Expires:, they are querying
8168 what we currently have stored as their contact address, so return
8171 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
8172 /* If we have an active registration, tell them when the registration is going to expire */
8173 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
8174 pvt->expiry = ast_sched_when(sched, peer->expire);
8175 return PARSE_REGISTER_QUERY;
8176 } else if (!strcasecmp(curi, "*") || !expiry) { /* Unregister this peer */
8177 /* This means remove all registrations and return OK */
8178 memset(&peer->addr, 0, sizeof(peer->addr));
8179 if (!AST_SCHED_DEL(sched, peer->expire)) {
8180 struct sip_peer *peer_ptr = peer;
8181 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8184 destroy_association(peer);
8186 register_peer_exten(peer, 0); /* Add extension from regexten= setting in sip.conf */
8187 peer->fullcontact[0] = '\0';
8188 peer->useragent[0] = '\0';
8189 peer->sipoptions = 0;
8190 peer->lastms = 0;
8192 if (option_verbose > 2)
8193 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", peer->name);
8194 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
8195 return PARSE_REGISTER_UPDATE;
8198 /* Store whatever we got as a contact from the client */
8199 ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));
8201 /* For the 200 OK, we should use the received contact */
8202 ast_string_field_build(pvt, our_contact, "<%s>", curi);
8204 /* Make sure it's a SIP URL */
8205 if (strncasecmp(curi, "sip:", 4)) {
8206 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", curi);
8207 } else
8208 curi += 4;
8209 /* Ditch q */
8210 curi = strsep(&curi, ";");
8211 /* Grab host */
8212 n = strchr(curi, '@');
8213 if (!n) {
8214 n = curi;
8215 curi = NULL;
8216 } else
8217 *n++ = '\0';
8218 pt = strchr(n, ':');
8219 if (pt) {
8220 *pt++ = '\0';
8221 port = atoi(pt);
8222 } else
8223 port = STANDARD_SIP_PORT;
8224 oldsin = peer->addr;
8225 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
8226 /* XXX This could block for a long time XXX */
8227 hp = ast_gethostbyname(n, &ahp);
8228 if (!hp) {
8229 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
8230 return PARSE_REGISTER_FAILED;
8232 peer->addr.sin_family = AF_INET;
8233 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
8234 peer->addr.sin_port = htons(port);
8235 } else {
8236 /* Don't trust the contact field. Just use what they came to us
8237 with */
8238 peer->addr = pvt->recv;
8241 /* Save SIP options profile */
8242 peer->sipoptions = pvt->sipoptions;
8244 if (curi && ast_strlen_zero(peer->username))
8245 ast_copy_string(peer->username, curi, sizeof(peer->username));
8247 if (!AST_SCHED_DEL(sched, peer->expire)) {
8248 struct sip_peer *peer_ptr = peer;
8249 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8251 if (expiry > max_expiry)
8252 expiry = max_expiry;
8253 if (expiry < min_expiry)
8254 expiry = min_expiry;
8255 if (ast_test_flag(&peer->flags[0], SIP_REALTIME)) {
8256 peer->expire = -1;
8257 } else {
8258 peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, ASTOBJ_REF(peer));
8259 if (peer->expire == -1) {
8260 struct sip_peer *peer_ptr = peer;
8261 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8264 pvt->expiry = expiry;
8265 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);
8266 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
8267 ast_db_put("SIP/Registry", peer->name, data);
8268 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
8270 /* Is this a new IP address for us? */
8271 if (inaddrcmp(&peer->addr, &oldsin)) {
8272 sip_poke_peer(peer);
8273 if (option_verbose > 2)
8274 ast_verbose(VERBOSE_PREFIX_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);
8275 register_peer_exten(peer, 1);
8278 /* Save User agent */
8279 useragent = get_header(req, "User-Agent");
8280 if (strcasecmp(useragent, peer->useragent)) { /* XXX copy if they are different ? */
8281 ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
8282 if (option_verbose > 3)
8283 ast_verbose(VERBOSE_PREFIX_3 "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
8285 return PARSE_REGISTER_UPDATE;
8288 /*! \brief Remove route from route list */
8289 static void free_old_route(struct sip_route *route)
8291 struct sip_route *next;
8293 while (route) {
8294 next = route->next;
8295 free(route);
8296 route = next;
8300 /*! \brief List all routes - mostly for debugging */
8301 static void list_route(struct sip_route *route)
8303 if (!route)
8304 ast_verbose("list_route: no route\n");
8305 else {
8306 for (;route; route = route->next)
8307 ast_verbose("list_route: hop: <%s>\n", route->hop);
8311 /*! \brief Build route list from Record-Route header */
8312 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
8314 struct sip_route *thishop, *head, *tail;
8315 int start = 0;
8316 int len;
8317 const char *rr, *contact, *c;
8319 /* Once a persistant route is set, don't fool with it */
8320 if (p->route && p->route_persistant) {
8321 if (option_debug)
8322 ast_log(LOG_DEBUG, "build_route: Retaining previous route: <%s>\n", p->route->hop);
8323 return;
8326 if (p->route) {
8327 free_old_route(p->route);
8328 p->route = NULL;
8331 /* We only want to create the route set the first time this is called */
8332 p->route_persistant = 1;
8334 /* Build a tailq, then assign it to p->route when done.
8335 * If backwards, we add entries from the head so they end up
8336 * in reverse order. However, we do need to maintain a correct
8337 * tail pointer because the contact is always at the end.
8339 head = NULL;
8340 tail = head;
8341 /* 1st we pass through all the hops in any Record-Route headers */
8342 for (;;) {
8343 /* Each Record-Route header */
8344 rr = __get_header(req, "Record-Route", &start);
8345 if (*rr == '\0')
8346 break;
8347 for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
8348 ++rr;
8349 len = strcspn(rr, ">") + 1;
8350 /* Make a struct route */
8351 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
8352 /* ast_calloc is not needed because all fields are initialized in this block */
8353 ast_copy_string(thishop->hop, rr, len);
8354 if (option_debug > 1)
8355 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
8356 /* Link in */
8357 if (backwards) {
8358 /* Link in at head so they end up in reverse order */
8359 thishop->next = head;
8360 head = thishop;
8361 /* If this was the first then it'll be the tail */
8362 if (!tail)
8363 tail = thishop;
8364 } else {
8365 thishop->next = NULL;
8366 /* Link in at the end */
8367 if (tail)
8368 tail->next = thishop;
8369 else
8370 head = thishop;
8371 tail = thishop;
8377 /* Only append the contact if we are dealing with a strict router */
8378 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop,";lr") == NULL) ) {
8379 /* 2nd append the Contact: if there is one */
8380 /* Can be multiple Contact headers, comma separated values - we just take the first */
8381 contact = get_header(req, "Contact");
8382 if (!ast_strlen_zero(contact)) {
8383 if (option_debug > 1)
8384 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
8385 /* Look for <: delimited address */
8386 c = strchr(contact, '<');
8387 if (c) {
8388 /* Take to > */
8389 ++c;
8390 len = strcspn(c, ">") + 1;
8391 } else {
8392 /* No <> - just take the lot */
8393 c = contact;
8394 len = strlen(contact) + 1;
8396 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
8397 /* ast_calloc is not needed because all fields are initialized in this block */
8398 ast_copy_string(thishop->hop, c, len);
8399 thishop->next = NULL;
8400 /* Goes at the end */
8401 if (tail)
8402 tail->next = thishop;
8403 else
8404 head = thishop;
8409 /* Store as new route */
8410 p->route = head;
8412 /* For debugging dump what we ended up with */
8413 if (sip_debug_test_pvt(p))
8414 list_route(p->route);
8417 AST_THREADSTORAGE(check_auth_buf, check_auth_buf_init);
8418 #define CHECK_AUTH_BUF_INITLEN 256
8420 /*! \brief Check user authorization from peer definition
8421 Some actions, like REGISTER and INVITEs from peers require
8422 authentication (if peer have secret set)
8423 \return 0 on success, non-zero on error
8425 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
8426 const char *secret, const char *md5secret, int sipmethod,
8427 char *uri, enum xmittype reliable, int ignore)
8429 const char *response = "407 Proxy Authentication Required";
8430 const char *reqheader = "Proxy-Authorization";
8431 const char *respheader = "Proxy-Authenticate";
8432 const char *authtoken;
8433 char a1_hash[256];
8434 char resp_hash[256]="";
8435 char *c;
8436 int wrongnonce = FALSE;
8437 int good_response;
8438 const char *usednonce = p->randdata;
8439 struct ast_dynamic_str *buf;
8440 int res;
8442 /* table of recognised keywords, and their value in the digest */
8443 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
8444 struct x {
8445 const char *key;
8446 const char *s;
8447 } *i, keys[] = {
8448 [K_RESP] = { "response=", "" },
8449 [K_URI] = { "uri=", "" },
8450 [K_USER] = { "username=", "" },
8451 [K_NONCE] = { "nonce=", "" },
8452 [K_LAST] = { NULL, NULL}
8455 /* Always OK if no secret */
8456 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
8457 return AUTH_SUCCESSFUL;
8458 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
8459 /* On a REGISTER, we have to use 401 and its family of headers instead of 407 and its family
8460 of headers -- GO SIP! Whoo hoo! Two things that do the same thing but are used in
8461 different circumstances! What a surprise. */
8462 response = "401 Unauthorized";
8463 reqheader = "Authorization";
8464 respheader = "WWW-Authenticate";
8466 authtoken = get_header(req, reqheader);
8467 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
8468 /* This is a retransmitted invite/register/etc, don't reconstruct authentication
8469 information */
8470 if (!reliable) {
8471 /* Resend message if this was NOT a reliable delivery. Otherwise the
8472 retransmission should get it */
8473 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
8474 /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
8475 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8477 return AUTH_CHALLENGE_SENT;
8478 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
8479 /* We have no auth, so issue challenge and request authentication */
8480 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
8481 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
8482 /* Schedule auto destroy in 32 seconds */
8483 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8484 return AUTH_CHALLENGE_SENT;
8487 /* --- We have auth, so check it */
8489 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
8490 an example in the spec of just what it is you're doing a hash on. */
8492 if (!(buf = ast_dynamic_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
8493 return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
8495 /* Make a copy of the response and parse it */
8496 res = ast_dynamic_str_thread_set(&buf, 0, &check_auth_buf, "%s", authtoken);
8498 if (res == AST_DYNSTR_BUILD_FAILED)
8499 return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
8501 c = buf->str;
8503 while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
8504 for (i = keys; i->key != NULL; i++) {
8505 const char *separator = ","; /* default */
8507 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
8508 continue;
8509 /* Found. Skip keyword, take text in quotes or up to the separator. */
8510 c += strlen(i->key);
8511 if (*c == '"') { /* in quotes. Skip first and look for last */
8512 c++;
8513 separator = "\"";
8515 i->s = c;
8516 strsep(&c, separator);
8517 break;
8519 if (i->key == NULL) /* not found, jump after space or comma */
8520 strsep(&c, " ,");
8523 /* Verify that digest username matches the username we auth as */
8524 if (strcmp(username, keys[K_USER].s)) {
8525 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
8526 username, keys[K_USER].s);
8527 /* Oops, we're trying something here */
8528 return AUTH_USERNAME_MISMATCH;
8531 /* Verify nonce from request matches our nonce. If not, send 401 with new nonce */
8532 if (strcasecmp(p->randdata, keys[K_NONCE].s)) { /* XXX it was 'n'casecmp ? */
8533 wrongnonce = TRUE;
8534 usednonce = keys[K_NONCE].s;
8537 if (!ast_strlen_zero(md5secret))
8538 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
8539 else {
8540 char a1[256];
8541 snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
8542 ast_md5_hash(a1_hash, a1);
8545 /* compute the expected response to compare with what we received */
8547 char a2[256];
8548 char a2_hash[256];
8549 char resp[256];
8551 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
8552 S_OR(keys[K_URI].s, uri));
8553 ast_md5_hash(a2_hash, a2);
8554 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
8555 ast_md5_hash(resp_hash, resp);
8558 good_response = keys[K_RESP].s &&
8559 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
8560 if (wrongnonce) {
8561 if (good_response) {
8562 if (sipdebug)
8563 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
8564 /* We got working auth token, based on stale nonce . */
8565 ast_string_field_build(p, randdata, "%08lx", ast_random());
8566 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
8567 } else {
8568 /* Everything was wrong, so give the device one more try with a new challenge */
8569 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
8570 if (sipdebug)
8571 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
8572 ast_string_field_build(p, randdata, "%08lx", ast_random());
8573 } else {
8574 if (sipdebug)
8575 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
8577 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
8580 /* Schedule auto destroy in 32 seconds */
8581 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8582 return AUTH_CHALLENGE_SENT;
8584 if (good_response) {
8585 append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
8586 return AUTH_SUCCESSFUL;
8589 /* Ok, we have a bad username/secret pair */
8590 /* Tell the UAS not to re-send this authentication data, because
8591 it will continue to fail
8594 return AUTH_SECRET_FAILED;
8597 /*! \brief Change onhold state of a peer using a pvt structure */
8598 static void sip_peer_hold(struct sip_pvt *p, int hold)
8600 struct sip_peer *peer = find_peer(p->peername, NULL, 1);
8602 if (!peer)
8603 return;
8605 /* If they put someone on hold, increment the value... otherwise decrement it */
8606 if (hold)
8607 peer->onHold++;
8608 else
8609 peer->onHold--;
8611 /* Request device state update */
8612 ast_device_state_changed("SIP/%s", peer->name);
8614 return;
8617 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
8618 \note If you add an "hint" priority to the extension in the dial plan,
8619 you will get notifications on device state changes */
8620 static int cb_extensionstate(char *context, char* exten, int state, void *data)
8622 struct sip_pvt *p = data;
8624 ast_mutex_lock(&p->lock);
8626 switch(state) {
8627 case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
8628 case AST_EXTENSION_REMOVED: /* Extension is gone */
8629 if (p->autokillid > -1 && sip_cancel_destroy(p)) /* Remove subscription expiry for renewals */
8630 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
8631 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); /* Delete subscription in 32 secs */
8632 ast_verbose(VERBOSE_PREFIX_2 "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
8633 p->stateid = -1;
8634 p->subscribed = NONE;
8635 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
8636 break;
8637 default: /* Tell user */
8638 p->laststate = state;
8639 break;
8641 if (p->subscribed != NONE) { /* Only send state NOTIFY if we know the format */
8642 if (!p->pendinginvite) {
8643 transmit_state_notify(p, state, 1, FALSE);
8644 } else {
8645 /* We already have a NOTIFY sent that is not answered. Queue the state up.
8646 if many state changes happen meanwhile, we will only send a notification of the last one */
8647 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
8650 if (option_verbose > 1)
8651 ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
8652 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
8655 ast_mutex_unlock(&p->lock);
8657 return 0;
8660 /*! \brief Send a fake 401 Unauthorized response when the administrator
8661 wants to hide the names of local users/peers from fishers
8663 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable)
8665 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
8666 transmit_response_with_auth(p, "401 Unauthorized", req, p->randdata, reliable, "WWW-Authenticate", 0);
8669 /*! \brief Verify registration of user
8670 - Registration is done in several steps, first a REGISTER without auth
8671 to get a challenge (nonce) then a second one with auth
8672 - Registration requests are only matched with peers that are marked as "dynamic"
8674 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
8675 struct sip_request *req, char *uri)
8677 enum check_auth_result res = AUTH_NOT_FOUND;
8678 struct sip_peer *peer;
8679 char tmp[256];
8680 char *name, *c;
8681 char *t;
8682 char *domain;
8684 /* Terminate URI */
8685 t = uri;
8686 while(*t && (*t > 32) && (*t != ';'))
8687 t++;
8688 *t = '\0';
8690 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
8691 if (pedanticsipchecking)
8692 ast_uri_decode(tmp);
8694 c = get_in_brackets(tmp);
8695 c = strsep(&c, ";"); /* Ditch ;user=phone */
8697 if (!strncasecmp(c, "sip:", 4)) {
8698 name = c + 4;
8699 } else {
8700 name = c;
8701 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
8704 /* Strip off the domain name */
8705 if ((c = strchr(name, '@'))) {
8706 *c++ = '\0';
8707 domain = c;
8708 if ((c = strchr(domain, ':'))) /* Remove :port */
8709 *c = '\0';
8710 if (!AST_LIST_EMPTY(&domain_list)) {
8711 if (!check_sip_domain(domain, NULL, 0)) {
8712 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
8713 return AUTH_UNKNOWN_DOMAIN;
8718 ast_string_field_set(p, exten, name);
8719 build_contact(p);
8720 peer = find_peer(name, NULL, 1);
8721 if (!(peer && ast_apply_ha(peer->ha, sin))) {
8722 /* Peer fails ACL check */
8723 if (peer) {
8724 ASTOBJ_UNREF(peer, sip_destroy_peer);
8725 res = AUTH_ACL_FAILED;
8726 } else
8727 res = AUTH_NOT_FOUND;
8729 if (peer) {
8730 /* Set Frame packetization */
8731 if (p->rtp) {
8732 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
8733 p->autoframing = peer->autoframing;
8735 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
8736 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
8737 res = AUTH_PEER_NOT_DYNAMIC;
8738 } else {
8739 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
8740 transmit_response(p, "100 Trying", req);
8741 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, ast_test_flag(req, SIP_PKT_IGNORE)))) {
8742 if (sip_cancel_destroy(p))
8743 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
8745 /* We have a succesful registration attemp with proper authentication,
8746 now, update the peer */
8747 switch (parse_register_contact(p, peer, req)) {
8748 case PARSE_REGISTER_FAILED:
8749 ast_log(LOG_WARNING, "Failed to parse contact info\n");
8750 transmit_response_with_date(p, "400 Bad Request", req);
8751 peer->lastmsgssent = -1;
8752 res = 0;
8753 break;
8754 case PARSE_REGISTER_QUERY:
8755 transmit_response_with_date(p, "200 OK", req);
8756 peer->lastmsgssent = -1;
8757 res = 0;
8758 break;
8759 case PARSE_REGISTER_UPDATE:
8760 update_peer(peer, p->expiry);
8761 /* Say OK and ask subsystem to retransmit msg counter */
8762 transmit_response_with_date(p, "200 OK", req);
8763 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
8764 peer->lastmsgssent = -1;
8765 res = 0;
8766 break;
8771 if (!peer && autocreatepeer) {
8772 /* Create peer if we have autocreate mode enabled */
8773 peer = temp_peer(name);
8774 if (peer) {
8775 ASTOBJ_CONTAINER_LINK(&peerl, peer);
8776 if (sip_cancel_destroy(p))
8777 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
8778 switch (parse_register_contact(p, peer, req)) {
8779 case PARSE_REGISTER_FAILED:
8780 ast_log(LOG_WARNING, "Failed to parse contact info\n");
8781 transmit_response_with_date(p, "400 Bad Request", req);
8782 peer->lastmsgssent = -1;
8783 res = 0;
8784 break;
8785 case PARSE_REGISTER_QUERY:
8786 transmit_response_with_date(p, "200 OK", req);
8787 peer->lastmsgssent = -1;
8788 res = 0;
8789 break;
8790 case PARSE_REGISTER_UPDATE:
8791 /* Say OK and ask subsystem to retransmit msg counter */
8792 transmit_response_with_date(p, "200 OK", req);
8793 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
8794 peer->lastmsgssent = -1;
8795 res = 0;
8796 break;
8800 if (!res) {
8801 ast_device_state_changed("SIP/%s", peer->name);
8803 if (res < 0) {
8804 switch (res) {
8805 case AUTH_SECRET_FAILED:
8806 /* Wrong password in authentication. Go away, don't try again until you fixed it */
8807 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
8808 break;
8809 case AUTH_USERNAME_MISMATCH:
8810 /* Username and digest username does not match.
8811 Asterisk uses the From: username for authentication. We need the
8812 users to use the same authentication user name until we support
8813 proper authentication by digest auth name */
8814 transmit_response(p, "403 Authentication user name does not match account name", &p->initreq);
8815 break;
8816 case AUTH_NOT_FOUND:
8817 case AUTH_PEER_NOT_DYNAMIC:
8818 case AUTH_ACL_FAILED:
8819 if (global_alwaysauthreject) {
8820 transmit_fake_auth_response(p, &p->initreq, 1);
8821 } else {
8822 /* URI not found */
8823 if (res == AUTH_PEER_NOT_DYNAMIC)
8824 transmit_response(p, "403 Forbidden", &p->initreq);
8825 else
8826 transmit_response(p, "404 Not found", &p->initreq);
8828 break;
8829 default:
8830 break;
8833 if (peer)
8834 ASTOBJ_UNREF(peer, sip_destroy_peer);
8836 return res;
8839 /*! \brief Get referring dnis */
8840 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
8842 char tmp[256], *c, *a;
8843 struct sip_request *req;
8845 req = oreq;
8846 if (!req)
8847 req = &p->initreq;
8848 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
8849 if (ast_strlen_zero(tmp))
8850 return 0;
8851 c = get_in_brackets(tmp);
8852 if (strncasecmp(c, "sip:", 4)) {
8853 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", c);
8854 return -1;
8856 c += 4;
8857 a = c;
8858 strsep(&a, "@;"); /* trim anything after @ or ; */
8859 if (sip_debug_test_pvt(p))
8860 ast_verbose("RDNIS is %s\n", c);
8861 ast_string_field_set(p, rdnis, c);
8863 return 0;
8866 /*! \brief Find out who the call is for
8867 We use the INVITE uri to find out
8869 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
8871 char tmp[256] = "", *uri, *a;
8872 char tmpf[256] = "", *from;
8873 struct sip_request *req;
8874 char *colon;
8876 req = oreq;
8877 if (!req)
8878 req = &p->initreq;
8880 /* Find the request URI */
8881 if (req->rlPart2)
8882 ast_copy_string(tmp, req->rlPart2, sizeof(tmp));
8884 if (pedanticsipchecking)
8885 ast_uri_decode(tmp);
8887 uri = get_in_brackets(tmp);
8889 if (strncasecmp(uri, "sip:", 4)) {
8890 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
8891 return -1;
8893 uri += 4;
8895 /* Now find the From: caller ID and name */
8896 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
8897 if (!ast_strlen_zero(tmpf)) {
8898 if (pedanticsipchecking)
8899 ast_uri_decode(tmpf);
8900 from = get_in_brackets(tmpf);
8901 } else {
8902 from = NULL;
8905 if (!ast_strlen_zero(from)) {
8906 if (strncasecmp(from, "sip:", 4)) {
8907 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
8908 return -1;
8910 from += 4;
8911 if ((a = strchr(from, '@')))
8912 *a++ = '\0';
8913 else
8914 a = from; /* just a domain */
8915 from = strsep(&from, ";"); /* Remove userinfo options */
8916 a = strsep(&a, ";"); /* Remove URI options */
8917 ast_string_field_set(p, fromdomain, a);
8920 /* Skip any options and find the domain */
8922 /* Get the target domain */
8923 if ((a = strchr(uri, '@'))) {
8924 *a++ = '\0';
8925 } else { /* No username part */
8926 a = uri;
8927 uri = "s"; /* Set extension to "s" */
8929 colon = strchr(a, ':'); /* Remove :port */
8930 if (colon)
8931 *colon = '\0';
8933 uri = strsep(&uri, ";"); /* Remove userinfo options */
8934 a = strsep(&a, ";"); /* Remove URI options */
8936 ast_string_field_set(p, domain, a);
8938 if (!AST_LIST_EMPTY(&domain_list)) {
8939 char domain_context[AST_MAX_EXTENSION];
8941 domain_context[0] = '\0';
8942 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
8943 if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
8944 if (option_debug)
8945 ast_log(LOG_DEBUG, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
8946 return -2;
8949 /* If we have a context defined, overwrite the original context */
8950 if (!ast_strlen_zero(domain_context))
8951 ast_string_field_set(p, context, domain_context);
8954 /* If the request coming in is a subscription and subscribecontext has been specified use it */
8955 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
8956 ast_string_field_set(p, context, p->subscribecontext);
8958 if (sip_debug_test_pvt(p))
8959 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
8961 /* If this is a subscription we actually just need to see if a hint exists for the extension */
8962 if (req->method == SIP_SUBSCRIBE) {
8963 char hint[AST_MAX_EXTENSION];
8964 return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
8965 } else {
8966 /* Check the dialplan for the username part of the request URI,
8967 the domain will be stored in the SIPDOMAIN variable
8968 Since extensions.conf can have unescaped characters, try matching a decoded
8969 uri in addition to the non-decoded uri
8970 Return 0 if we have a matching extension */
8971 char *decoded_uri = ast_strdupa(uri);
8972 ast_uri_decode(decoded_uri);
8973 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)) ||
8974 !strcmp(uri, ast_pickup_ext())) {
8975 if (!oreq)
8976 ast_string_field_set(p, exten, uri);
8977 return 0;
8981 /* Return 1 for pickup extension or overlap dialling support (if we support it) */
8982 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
8983 ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) ||
8984 !strncmp(uri, ast_pickup_ext(), strlen(uri))) {
8985 return 1;
8988 return -1;
8991 /*! \brief Lock interface lock and find matching pvt lock
8992 - Their tag is fromtag, our tag is to-tag
8993 - This means that in some transactions, totag needs to be their tag :-)
8994 depending upon the direction
8996 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
8998 struct sip_pvt *sip_pvt_ptr;
9000 ast_mutex_lock(&iflock);
9002 if (option_debug > 3 && totag)
9003 ast_log(LOG_DEBUG, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
9005 /* Search interfaces and find the match */
9006 for (sip_pvt_ptr = iflist; sip_pvt_ptr; sip_pvt_ptr = sip_pvt_ptr->next) {
9007 if (!strcmp(sip_pvt_ptr->callid, callid)) {
9008 int match = 1;
9009 char *ourtag = sip_pvt_ptr->tag;
9011 /* Go ahead and lock it (and its owner) before returning */
9012 ast_mutex_lock(&sip_pvt_ptr->lock);
9014 /* Check if tags match. If not, this is not the call we want
9015 (With a forking SIP proxy, several call legs share the
9016 call id, but have different tags)
9018 if (pedanticsipchecking && (strcmp(fromtag, sip_pvt_ptr->theirtag) || (!ast_strlen_zero(totag) && strcmp(totag, ourtag))))
9019 match = 0;
9021 if (!match) {
9022 ast_mutex_unlock(&sip_pvt_ptr->lock);
9023 continue;
9026 if (option_debug > 3 && totag)
9027 ast_log(LOG_DEBUG, "Matched %s call - their tag is %s Our tag is %s\n",
9028 ast_test_flag(&sip_pvt_ptr->flags[0], SIP_OUTGOING) ? "OUTGOING": "INCOMING",
9029 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
9031 /* deadlock avoidance... */
9032 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
9033 DEADLOCK_AVOIDANCE(&sip_pvt_ptr->lock);
9035 break;
9038 ast_mutex_unlock(&iflock);
9039 if (option_debug > 3 && !sip_pvt_ptr)
9040 ast_log(LOG_DEBUG, "Found no match for callid %s to-tag %s from-tag %s\n", callid, totag, fromtag);
9041 return sip_pvt_ptr;
9044 /*! \brief Call transfer support (the REFER method)
9045 * Extracts Refer headers into pvt dialog structure */
9046 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
9049 const char *p_referred_by = NULL;
9050 char *h_refer_to = NULL;
9051 char *h_referred_by = NULL;
9052 char *refer_to;
9053 const char *p_refer_to;
9054 char *referred_by_uri = NULL;
9055 char *ptr;
9056 struct sip_request *req = NULL;
9057 const char *transfer_context = NULL;
9058 struct sip_refer *referdata;
9061 req = outgoing_req;
9062 referdata = transferer->refer;
9064 if (!req)
9065 req = &transferer->initreq;
9067 p_refer_to = get_header(req, "Refer-To");
9068 if (ast_strlen_zero(p_refer_to)) {
9069 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
9070 return -2; /* Syntax error */
9072 h_refer_to = ast_strdupa(p_refer_to);
9073 refer_to = get_in_brackets(h_refer_to);
9074 if (pedanticsipchecking)
9075 ast_uri_decode(refer_to);
9077 if (strncasecmp(refer_to, "sip:", 4)) {
9078 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
9079 return -3;
9081 refer_to += 4; /* Skip sip: */
9083 /* Get referred by header if it exists */
9084 p_referred_by = get_header(req, "Referred-By");
9085 if (!ast_strlen_zero(p_referred_by)) {
9086 char *lessthan;
9087 h_referred_by = ast_strdupa(p_referred_by);
9088 if (pedanticsipchecking)
9089 ast_uri_decode(h_referred_by);
9091 /* Store referrer's caller ID name */
9092 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
9093 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
9094 *(lessthan - 1) = '\0'; /* Space */
9097 referred_by_uri = get_in_brackets(h_referred_by);
9098 if(strncasecmp(referred_by_uri, "sip:", 4)) {
9099 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
9100 referred_by_uri = (char *) NULL;
9101 } else {
9102 referred_by_uri += 4; /* Skip sip: */
9106 /* Check for arguments in the refer_to header */
9107 if ((ptr = strchr(refer_to, '?'))) { /* Search for arguments */
9108 *ptr++ = '\0';
9109 if (!strncasecmp(ptr, "REPLACES=", 9)) {
9110 char *to = NULL, *from = NULL;
9112 /* This is an attended transfer */
9113 referdata->attendedtransfer = 1;
9114 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
9115 ast_uri_decode(referdata->replaces_callid);
9116 if ((ptr = strchr(referdata->replaces_callid, ';'))) /* Find options */ {
9117 *ptr++ = '\0';
9120 if (ptr) {
9121 /* Find the different tags before we destroy the string */
9122 to = strcasestr(ptr, "to-tag=");
9123 from = strcasestr(ptr, "from-tag=");
9126 /* Grab the to header */
9127 if (to) {
9128 ptr = to + 7;
9129 if ((to = strchr(ptr, '&')))
9130 *to = '\0';
9131 if ((to = strchr(ptr, ';')))
9132 *to = '\0';
9133 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
9136 if (from) {
9137 ptr = from + 9;
9138 if ((to = strchr(ptr, '&')))
9139 *to = '\0';
9140 if ((to = strchr(ptr, ';')))
9141 *to = '\0';
9142 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
9145 if (option_debug > 1) {
9146 if (!pedanticsipchecking)
9147 ast_log(LOG_DEBUG,"Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
9148 else
9149 ast_log(LOG_DEBUG,"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>" );
9154 if ((ptr = strchr(refer_to, '@'))) { /* Separate domain */
9155 char *urioption = NULL, *domain;
9156 *ptr++ = '\0';
9158 if ((urioption = strchr(ptr, ';'))) /* Separate urioptions */
9159 *urioption++ = '\0';
9161 domain = ptr;
9162 if ((ptr = strchr(domain, ':'))) /* Remove :port */
9163 *ptr = '\0';
9165 /* Save the domain for the dial plan */
9166 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
9167 if (urioption)
9168 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
9171 if ((ptr = strchr(refer_to, ';'))) /* Remove options */
9172 *ptr = '\0';
9173 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
9175 if (referred_by_uri) {
9176 if ((ptr = strchr(referred_by_uri, ';'))) /* Remove options */
9177 *ptr = '\0';
9178 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
9179 } else {
9180 referdata->referred_by[0] = '\0';
9183 /* Determine transfer context */
9184 if (transferer->owner) /* Mimic behaviour in res_features.c */
9185 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
9187 /* By default, use the context in the channel sending the REFER */
9188 if (ast_strlen_zero(transfer_context)) {
9189 transfer_context = S_OR(transferer->owner->macrocontext,
9190 S_OR(transferer->context, default_context));
9193 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
9195 /* Either an existing extension or the parking extension */
9196 if (ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
9197 if (sip_debug_test_pvt(transferer)) {
9198 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
9200 /* We are ready to transfer to the extension */
9201 return 0;
9203 if (sip_debug_test_pvt(transferer))
9204 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
9206 /* Failure, we can't find this extension */
9207 return -1;
9211 /*! \brief Call transfer support (old way, deprecated by the IETF)--*/
9212 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
9214 char tmp[256] = "", *c, *a;
9215 struct sip_request *req = oreq ? oreq : &p->initreq;
9216 struct sip_refer *referdata = NULL;
9217 const char *transfer_context = NULL;
9219 if (!p->refer && !sip_refer_allocate(p))
9220 return -1;
9222 referdata = p->refer;
9224 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
9225 c = get_in_brackets(tmp);
9227 if (pedanticsipchecking)
9228 ast_uri_decode(c);
9230 if (strncasecmp(c, "sip:", 4)) {
9231 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
9232 return -1;
9234 c += 4;
9235 if ((a = strchr(c, ';'))) /* Remove arguments */
9236 *a = '\0';
9238 if ((a = strchr(c, '@'))) { /* Separate Domain */
9239 *a++ = '\0';
9240 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
9243 if (sip_debug_test_pvt(p))
9244 ast_verbose("Looking for %s in %s\n", c, p->context);
9246 if (p->owner) /* Mimic behaviour in res_features.c */
9247 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
9249 /* By default, use the context in the channel sending the REFER */
9250 if (ast_strlen_zero(transfer_context)) {
9251 transfer_context = S_OR(p->owner->macrocontext,
9252 S_OR(p->context, default_context));
9254 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
9255 /* This is a blind transfer */
9256 if (option_debug)
9257 ast_log(LOG_DEBUG,"SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
9258 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
9259 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
9260 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
9261 referdata->refer_call = NULL;
9262 /* Set new context */
9263 ast_string_field_set(p, context, transfer_context);
9264 return 0;
9265 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
9266 return 1;
9269 return -1;
9271 /*! \brief check Via: header for hostname, port and rport request/answer */
9272 static void check_via(struct sip_pvt *p, const struct sip_request *req)
9274 char via[512];
9275 char *c, *pt;
9276 struct hostent *hp;
9277 struct ast_hostent ahp;
9279 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
9281 /* Work on the leftmost value of the topmost Via header */
9282 c = strchr(via, ',');
9283 if (c)
9284 *c = '\0';
9286 /* Check for rport */
9287 c = strstr(via, ";rport");
9288 if (c && (c[6] != '=')) /* rport query, not answer */
9289 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
9291 c = strchr(via, ';');
9292 if (c)
9293 *c = '\0';
9295 c = strchr(via, ' ');
9296 if (c) {
9297 *c = '\0';
9298 c = ast_skip_blanks(c+1);
9299 if (strcasecmp(via, "SIP/2.0/UDP")) {
9300 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
9301 return;
9303 pt = strchr(c, ':');
9304 if (pt)
9305 *pt++ = '\0'; /* remember port pointer */
9306 hp = ast_gethostbyname(c, &ahp);
9307 if (!hp) {
9308 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
9309 return;
9311 memset(&p->sa, 0, sizeof(p->sa));
9312 p->sa.sin_family = AF_INET;
9313 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
9314 p->sa.sin_port = htons(pt ? atoi(pt) : STANDARD_SIP_PORT);
9316 if (sip_debug_test_pvt(p)) {
9317 const struct sockaddr_in *dst = sip_real_dst(p);
9318 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
9323 /*! \brief Get caller id name from SIP headers */
9324 static char *get_calleridname(const char *input, char *output, size_t outputsize)
9326 const char *end = strchr(input,'<'); /* first_bracket */
9327 const char *tmp = strchr(input,'"'); /* first quote */
9328 int bytes = 0;
9329 int maxbytes = outputsize - 1;
9331 if (!end || end == input) /* we require a part in brackets */
9332 return NULL;
9334 end--; /* move just before "<" */
9336 if (tmp && tmp <= end) {
9337 /* The quote (tmp) precedes the bracket (end+1).
9338 * Find the matching quote and return the content.
9340 end = strchr(tmp+1, '"');
9341 if (!end)
9342 return NULL;
9343 bytes = (int) (end - tmp);
9344 /* protect the output buffer */
9345 if (bytes > maxbytes)
9346 bytes = maxbytes;
9347 ast_copy_string(output, tmp + 1, bytes);
9348 } else {
9349 /* No quoted string, or it is inside brackets. */
9350 /* clear the empty characters in the begining*/
9351 input = ast_skip_blanks(input);
9352 /* clear the empty characters in the end */
9353 while(*end && *end < 33 && end > input)
9354 end--;
9355 if (end >= input) {
9356 bytes = (int) (end - input) + 2;
9357 /* protect the output buffer */
9358 if (bytes > maxbytes)
9359 bytes = maxbytes;
9360 ast_copy_string(output, input, bytes);
9361 } else
9362 return NULL;
9364 return output;
9367 /*! \brief Get caller id number from Remote-Party-ID header field
9368 * Returns true if number should be restricted (privacy setting found)
9369 * output is set to NULL if no number found
9371 static int get_rpid_num(const char *input, char *output, int maxlen)
9373 char *start;
9374 char *end;
9376 start = strchr(input,':');
9377 if (!start) {
9378 output[0] = '\0';
9379 return 0;
9381 start++;
9383 /* we found "number" */
9384 ast_copy_string(output,start,maxlen);
9385 output[maxlen-1] = '\0';
9387 end = strchr(output,'@');
9388 if (end)
9389 *end = '\0';
9390 else
9391 output[0] = '\0';
9392 if (strstr(input,"privacy=full") || strstr(input,"privacy=uri"))
9393 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
9395 return 0;
9399 /*! \brief Check if matching user or peer is defined
9400 Match user on From: user name and peer on IP/port
9401 This is used on first invite (not re-invites) and subscribe requests
9402 \return 0 on success, non-zero on failure
9404 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
9405 int sipmethod, char *uri, enum xmittype reliable,
9406 struct sockaddr_in *sin, struct sip_peer **authpeer)
9408 struct sip_user *user = NULL;
9409 struct sip_peer *peer;
9410 char from[256], *c;
9411 char *of;
9412 char rpid_num[50];
9413 const char *rpid;
9414 enum check_auth_result res = AUTH_SUCCESSFUL;
9415 char *t;
9416 char calleridname[50];
9417 int debug=sip_debug_test_addr(sin);
9418 struct ast_variable *tmpvar = NULL, *v = NULL;
9419 char *uri2 = ast_strdupa(uri);
9421 /* Terminate URI */
9422 t = uri2;
9423 while (*t && *t > 32 && *t != ';')
9424 t++;
9425 *t = '\0';
9426 ast_copy_string(from, get_header(req, "From"), sizeof(from)); /* XXX bug in original code, overwrote string */
9427 if (pedanticsipchecking)
9428 ast_uri_decode(from);
9429 /* XXX here tries to map the username for invite things */
9430 memset(calleridname, 0, sizeof(calleridname));
9431 get_calleridname(from, calleridname, sizeof(calleridname));
9432 if (calleridname[0])
9433 ast_string_field_set(p, cid_name, calleridname);
9435 rpid = get_header(req, "Remote-Party-ID");
9436 memset(rpid_num, 0, sizeof(rpid_num));
9437 if (!ast_strlen_zero(rpid))
9438 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
9440 of = get_in_brackets(from);
9441 if (ast_strlen_zero(p->exten)) {
9442 t = uri2;
9443 if (!strncasecmp(t, "sip:", 4))
9444 t+= 4;
9445 ast_string_field_set(p, exten, t);
9446 t = strchr(p->exten, '@');
9447 if (t)
9448 *t = '\0';
9449 if (ast_strlen_zero(p->our_contact))
9450 build_contact(p);
9452 /* save the URI part of the From header */
9453 ast_string_field_set(p, from, of);
9454 if (strncasecmp(of, "sip:", 4)) {
9455 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
9456 } else
9457 of += 4;
9458 /* Get just the username part */
9459 if ((c = strchr(of, '@'))) {
9460 char *tmp;
9461 *c = '\0';
9462 if ((c = strchr(of, ':')))
9463 *c = '\0';
9464 tmp = ast_strdupa(of);
9465 /* We need to be able to handle auth-headers looking like
9466 <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
9468 tmp = strsep(&tmp, ";");
9469 if (ast_is_shrinkable_phonenumber(tmp))
9470 ast_shrink_phone_number(tmp);
9471 ast_string_field_set(p, cid_num, tmp);
9474 if (!authpeer) /* If we are looking for a peer, don't check the user objects (or realtime) */
9475 user = find_user(of, 1);
9477 /* Find user based on user name in the from header */
9478 if (user && ast_apply_ha(user->ha, sin)) {
9479 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
9480 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9481 /* copy channel vars */
9482 for (v = user->chanvars ; v ; v = v->next) {
9483 if ((tmpvar = ast_variable_new(v->name, v->value))) {
9484 tmpvar->next = p->chanvars;
9485 p->chanvars = tmpvar;
9488 p->prefs = user->prefs;
9489 /* Set Frame packetization */
9490 if (p->rtp) {
9491 ast_rtp_codec_setpref(p->rtp, &p->prefs);
9492 p->autoframing = user->autoframing;
9494 /* replace callerid if rpid found, and not restricted */
9495 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
9496 char *tmp;
9497 if (*calleridname)
9498 ast_string_field_set(p, cid_name, calleridname);
9499 tmp = ast_strdupa(rpid_num);
9500 if (ast_is_shrinkable_phonenumber(tmp))
9501 ast_shrink_phone_number(tmp);
9502 ast_string_field_set(p, cid_num, tmp);
9505 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE) );
9507 if (!(res = check_auth(p, req, user->name, user->secret, user->md5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
9508 if (sip_cancel_destroy(p))
9509 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
9510 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
9511 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9512 /* Copy SIP extensions profile from INVITE */
9513 if (p->sipoptions)
9514 user->sipoptions = p->sipoptions;
9516 /* If we have a call limit, set flag */
9517 if (user->call_limit)
9518 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
9519 if (!ast_strlen_zero(user->context))
9520 ast_string_field_set(p, context, user->context);
9521 if (!ast_strlen_zero(user->cid_num)) {
9522 char *tmp = ast_strdupa(user->cid_num);
9523 if (ast_is_shrinkable_phonenumber(tmp))
9524 ast_shrink_phone_number(tmp);
9525 ast_string_field_set(p, cid_num, tmp);
9527 if (!ast_strlen_zero(user->cid_name))
9528 ast_string_field_set(p, cid_name, user->cid_name);
9529 ast_string_field_set(p, username, user->name);
9530 ast_string_field_set(p, peername, user->name);
9531 ast_string_field_set(p, peersecret, user->secret);
9532 ast_string_field_set(p, peermd5secret, user->md5secret);
9533 ast_string_field_set(p, subscribecontext, user->subscribecontext);
9534 ast_string_field_set(p, accountcode, user->accountcode);
9535 ast_string_field_set(p, language, user->language);
9536 ast_string_field_set(p, mohsuggest, user->mohsuggest);
9537 ast_string_field_set(p, mohinterpret, user->mohinterpret);
9538 p->allowtransfer = user->allowtransfer;
9539 p->amaflags = user->amaflags;
9540 p->callgroup = user->callgroup;
9541 p->pickupgroup = user->pickupgroup;
9542 if (user->callingpres) /* User callingpres setting will override RPID header */
9543 p->callingpres = user->callingpres;
9545 /* Set default codec settings for this call */
9546 p->capability = user->capability; /* User codec choice */
9547 p->jointcapability = user->capability; /* Our codecs */
9548 if (p->peercapability) /* AND with peer's codecs */
9549 p->jointcapability &= p->peercapability;
9550 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
9551 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
9552 p->noncodeccapability |= AST_RTP_DTMF;
9553 else
9554 p->noncodeccapability &= ~AST_RTP_DTMF;
9555 p->jointnoncodeccapability = p->noncodeccapability;
9556 if (p->t38.peercapability)
9557 p->t38.jointcapability &= p->t38.peercapability;
9558 p->maxcallbitrate = user->maxcallbitrate;
9559 /* If we do not support video, remove video from call structure */
9560 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
9561 ast_rtp_destroy(p->vrtp);
9562 p->vrtp = NULL;
9565 if (user && debug)
9566 ast_verbose("Found user '%s'\n", user->name);
9567 } else {
9568 if (user) {
9569 if (!authpeer && debug)
9570 ast_verbose("Found user '%s', but fails host access\n", user->name);
9571 ASTOBJ_UNREF(user,sip_destroy_user);
9573 user = NULL;
9576 if (!user) {
9577 /* If we didn't find a user match, check for peers */
9578 if (sipmethod == SIP_SUBSCRIBE)
9579 /* For subscribes, match on peer name only */
9580 peer = find_peer(of, NULL, 1);
9581 else
9582 /* Look for peer based on the IP address we received data from */
9583 /* If peer is registered from this IP address or have this as a default
9584 IP address, this call is from the peer
9586 peer = find_peer(NULL, &p->recv, 1);
9588 if (peer) {
9589 /* Set Frame packetization */
9590 if (p->rtp) {
9591 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
9592 p->autoframing = peer->autoframing;
9594 if (debug)
9595 ast_verbose("Found peer '%s'\n", peer->name);
9597 /* Take the peer */
9598 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
9599 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9601 /* Copy SIP extensions profile to peer */
9602 if (p->sipoptions)
9603 peer->sipoptions = p->sipoptions;
9605 /* replace callerid if rpid found, and not restricted */
9606 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
9607 char *tmp = ast_strdupa(rpid_num);
9608 if (*calleridname)
9609 ast_string_field_set(p, cid_name, calleridname);
9610 if (ast_is_shrinkable_phonenumber(tmp))
9611 ast_shrink_phone_number(tmp);
9612 ast_string_field_set(p, cid_num, tmp);
9614 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
9616 ast_string_field_set(p, peersecret, peer->secret);
9617 ast_string_field_set(p, peermd5secret, peer->md5secret);
9618 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
9619 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
9620 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
9621 if (peer->callingpres) /* Peer calling pres setting will override RPID */
9622 p->callingpres = peer->callingpres;
9623 if (peer->maxms && peer->lastms)
9624 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
9625 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
9626 /* Pretend there is no required authentication */
9627 ast_string_field_free(p, peersecret);
9628 ast_string_field_free(p, peermd5secret);
9630 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
9631 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
9632 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9633 /* If we have a call limit, set flag */
9634 if (peer->call_limit)
9635 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
9636 ast_string_field_set(p, peername, peer->name);
9637 ast_string_field_set(p, authname, peer->name);
9639 /* copy channel vars */
9640 for (v = peer->chanvars ; v ; v = v->next) {
9641 if ((tmpvar = ast_variable_new(v->name, v->value))) {
9642 tmpvar->next = p->chanvars;
9643 p->chanvars = tmpvar;
9646 if (authpeer) {
9647 (*authpeer) = ASTOBJ_REF(peer); /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
9650 if (!ast_strlen_zero(peer->username)) {
9651 ast_string_field_set(p, username, peer->username);
9652 /* Use the default username for authentication on outbound calls */
9653 /* XXX this takes the name from the caller... can we override ? */
9654 ast_string_field_set(p, authname, peer->username);
9656 if (!ast_strlen_zero(peer->cid_num)) {
9657 char *tmp = ast_strdupa(peer->cid_num);
9658 if (ast_is_shrinkable_phonenumber(tmp))
9659 ast_shrink_phone_number(tmp);
9660 ast_string_field_set(p, cid_num, tmp);
9662 if (!ast_strlen_zero(peer->cid_name))
9663 ast_string_field_set(p, cid_name, peer->cid_name);
9664 ast_string_field_set(p, fullcontact, peer->fullcontact);
9665 if (!ast_strlen_zero(peer->context))
9666 ast_string_field_set(p, context, peer->context);
9667 ast_string_field_set(p, peersecret, peer->secret);
9668 ast_string_field_set(p, peermd5secret, peer->md5secret);
9669 ast_string_field_set(p, language, peer->language);
9670 ast_string_field_set(p, accountcode, peer->accountcode);
9671 p->amaflags = peer->amaflags;
9672 p->callgroup = peer->callgroup;
9673 p->pickupgroup = peer->pickupgroup;
9674 p->capability = peer->capability;
9675 p->prefs = peer->prefs;
9676 p->jointcapability = peer->capability;
9677 if (p->peercapability)
9678 p->jointcapability &= p->peercapability;
9679 p->maxcallbitrate = peer->maxcallbitrate;
9680 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
9681 ast_rtp_destroy(p->vrtp);
9682 p->vrtp = NULL;
9684 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
9685 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
9686 p->noncodeccapability |= AST_RTP_DTMF;
9687 else
9688 p->noncodeccapability &= ~AST_RTP_DTMF;
9689 p->jointnoncodeccapability = p->noncodeccapability;
9690 if (p->t38.peercapability)
9691 p->t38.jointcapability &= p->t38.peercapability;
9693 ASTOBJ_UNREF(peer, sip_destroy_peer);
9694 } else {
9695 if (debug)
9696 ast_verbose("Found no matching peer or user for '%s:%d'\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
9698 /* do we allow guests? */
9699 if (!global_allowguest) {
9700 if (global_alwaysauthreject)
9701 res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
9702 else
9703 res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
9704 } else if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
9705 char *tmp = ast_strdupa(rpid_num);
9706 if (*calleridname)
9707 ast_string_field_set(p, cid_name, calleridname);
9708 if (ast_is_shrinkable_phonenumber(tmp))
9709 ast_shrink_phone_number(tmp);
9710 ast_string_field_set(p, cid_num, tmp);
9716 if (user)
9717 ASTOBJ_UNREF(user, sip_destroy_user);
9718 return res;
9721 /*! \brief Find user
9722 If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
9724 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
9726 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
9729 /*! \brief Get text out of a SIP MESSAGE packet */
9730 static int get_msg_text(char *buf, int len, struct sip_request *req)
9732 int x;
9733 int y;
9735 buf[0] = '\0';
9736 y = len - strlen(buf) - 5;
9737 if (y < 0)
9738 y = 0;
9739 for (x=0;x<req->lines;x++) {
9740 strncat(buf, req->line[x], y); /* safe */
9741 y -= strlen(req->line[x]) + 1;
9742 if (y < 0)
9743 y = 0;
9744 if (y != 0)
9745 strcat(buf, "\n"); /* safe */
9747 return 0;
9751 /*! \brief Receive SIP MESSAGE method messages
9752 \note We only handle messages within current calls currently
9753 Reference: RFC 3428 */
9754 static void receive_message(struct sip_pvt *p, struct sip_request *req)
9756 char buf[1024];
9757 struct ast_frame f;
9758 const char *content_type = get_header(req, "Content-Type");
9760 if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
9761 transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
9762 if (!p->owner)
9763 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
9764 return;
9767 if (get_msg_text(buf, sizeof(buf), req)) {
9768 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
9769 transmit_response(p, "202 Accepted", req);
9770 if (!p->owner)
9771 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
9772 return;
9775 if (p->owner) {
9776 if (sip_debug_test_pvt(p))
9777 ast_verbose("Message received: '%s'\n", buf);
9778 memset(&f, 0, sizeof(f));
9779 f.frametype = AST_FRAME_TEXT;
9780 f.subclass = 0;
9781 f.offset = 0;
9782 f.data = buf;
9783 f.datalen = strlen(buf);
9784 ast_queue_frame(p->owner, &f);
9785 transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
9786 } else { /* Message outside of a call, we do not support that */
9787 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);
9788 transmit_response(p, "405 Method Not Allowed", req); /* Good enough, or? */
9789 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
9791 return;
9794 /*! \brief CLI Command to show calls within limits set by call_limit */
9795 static int sip_show_inuse(int fd, int argc, char *argv[])
9797 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
9798 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
9799 char ilimits[40];
9800 char iused[40];
9801 int showall = FALSE;
9803 if (argc < 3)
9804 return RESULT_SHOWUSAGE;
9806 if (argc == 4 && !strcmp(argv[3],"all"))
9807 showall = TRUE;
9809 ast_cli(fd, FORMAT, "* User name", "In use", "Limit");
9810 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
9811 ASTOBJ_RDLOCK(iterator);
9812 if (iterator->call_limit)
9813 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
9814 else
9815 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
9816 snprintf(iused, sizeof(iused), "%d", iterator->inUse);
9817 if (showall || iterator->call_limit)
9818 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
9819 ASTOBJ_UNLOCK(iterator);
9820 } while (0) );
9822 ast_cli(fd, FORMAT, "* Peer name", "In use", "Limit");
9824 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
9825 ASTOBJ_RDLOCK(iterator);
9826 if (iterator->call_limit)
9827 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
9828 else
9829 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
9830 snprintf(iused, sizeof(iused), "%d/%d", iterator->inUse, iterator->inRinging);
9831 if (showall || iterator->call_limit)
9832 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
9833 ASTOBJ_UNLOCK(iterator);
9834 } while (0) );
9836 return RESULT_SUCCESS;
9837 #undef FORMAT
9838 #undef FORMAT2
9841 /*! \brief Convert transfer mode to text string */
9842 static char *transfermode2str(enum transfermodes mode)
9844 if (mode == TRANSFER_OPENFORALL)
9845 return "open";
9846 else if (mode == TRANSFER_CLOSED)
9847 return "closed";
9848 return "strict";
9851 /*! \brief Convert NAT setting to text string */
9852 static char *nat2str(int nat)
9854 switch(nat) {
9855 case SIP_NAT_NEVER:
9856 return "No";
9857 case SIP_NAT_ROUTE:
9858 return "Route";
9859 case SIP_NAT_ALWAYS:
9860 return "Always";
9861 case SIP_NAT_RFC3581:
9862 return "RFC3581";
9863 default:
9864 return "Unknown";
9868 /*! \brief Report Peer status in character string
9869 * \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
9871 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
9873 int res = 0;
9874 if (peer->maxms) {
9875 if (peer->lastms < 0) {
9876 ast_copy_string(status, "UNREACHABLE", statuslen);
9877 } else if (peer->lastms > peer->maxms) {
9878 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
9879 res = 1;
9880 } else if (peer->lastms) {
9881 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
9882 res = 1;
9883 } else {
9884 ast_copy_string(status, "UNKNOWN", statuslen);
9886 } else {
9887 ast_copy_string(status, "Unmonitored", statuslen);
9888 /* Checking if port is 0 */
9889 res = -1;
9891 return res;
9894 /*! \brief CLI Command 'SIP Show Users' */
9895 static int sip_show_users(int fd, int argc, char *argv[])
9897 regex_t regexbuf;
9898 int havepattern = FALSE;
9900 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
9902 switch (argc) {
9903 case 5:
9904 if (!strcasecmp(argv[3], "like")) {
9905 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
9906 return RESULT_SHOWUSAGE;
9907 havepattern = TRUE;
9908 } else
9909 return RESULT_SHOWUSAGE;
9910 case 3:
9911 break;
9912 default:
9913 return RESULT_SHOWUSAGE;
9916 ast_cli(fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
9917 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
9918 ASTOBJ_RDLOCK(iterator);
9920 if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
9921 ASTOBJ_UNLOCK(iterator);
9922 continue;
9925 ast_cli(fd, FORMAT, iterator->name,
9926 iterator->secret,
9927 iterator->accountcode,
9928 iterator->context,
9929 iterator->ha ? "Yes" : "No",
9930 nat2str(ast_test_flag(&iterator->flags[0], SIP_NAT)));
9931 ASTOBJ_UNLOCK(iterator);
9932 } while (0)
9935 if (havepattern)
9936 regfree(&regexbuf);
9938 return RESULT_SUCCESS;
9939 #undef FORMAT
9942 static char mandescr_show_peers[] =
9943 "Description: Lists SIP peers in text format with details on current status.\n"
9944 "Variables: \n"
9945 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
9947 /*! \brief Show SIP peers in the manager API */
9948 /* Inspired from chan_iax2 */
9949 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
9951 const char *id = astman_get_header(m,"ActionID");
9952 const char *a[] = {"sip", "show", "peers"};
9953 char idtext[256] = "";
9954 int total = 0;
9956 if (!ast_strlen_zero(id))
9957 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
9959 astman_send_ack(s, m, "Peer status list will follow");
9960 /* List the peers in separate manager events */
9961 _sip_show_peers(-1, &total, s, m, 3, a);
9962 /* Send final confirmation */
9963 astman_append(s,
9964 "Event: PeerlistComplete\r\n"
9965 "ListItems: %d\r\n"
9966 "%s"
9967 "\r\n", total, idtext);
9968 return 0;
9971 /*! \brief CLI Show Peers command */
9972 static int sip_show_peers(int fd, int argc, char *argv[])
9974 return _sip_show_peers(fd, NULL, NULL, NULL, argc, (const char **) argv);
9977 /*! \brief _sip_show_peers: Execute sip show peers command */
9978 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
9980 regex_t regexbuf;
9981 int havepattern = FALSE;
9983 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %-10s\n"
9984 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %-10s\n"
9986 char name[256];
9987 int total_peers = 0;
9988 int peers_mon_online = 0;
9989 int peers_mon_offline = 0;
9990 int peers_unmon_offline = 0;
9991 int peers_unmon_online = 0;
9992 const char *id;
9993 char idtext[256] = "";
9994 int realtimepeers;
9996 realtimepeers = ast_check_realtime("sippeers");
9998 if (s) { /* Manager - get ActionID */
9999 id = astman_get_header(m,"ActionID");
10000 if (!ast_strlen_zero(id))
10001 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
10004 switch (argc) {
10005 case 5:
10006 if (!strcasecmp(argv[3], "like")) {
10007 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
10008 return RESULT_SHOWUSAGE;
10009 havepattern = TRUE;
10010 } else
10011 return RESULT_SHOWUSAGE;
10012 case 3:
10013 break;
10014 default:
10015 return RESULT_SHOWUSAGE;
10018 if (!s) /* Normal list */
10019 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
10021 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
10022 char status[20] = "";
10023 char srch[2000];
10024 char pstatus;
10026 ASTOBJ_RDLOCK(iterator);
10028 if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
10029 ASTOBJ_UNLOCK(iterator);
10030 continue;
10033 if (!ast_strlen_zero(iterator->username) && !s)
10034 snprintf(name, sizeof(name), "%s/%s", iterator->name, iterator->username);
10035 else
10036 ast_copy_string(name, iterator->name, sizeof(name));
10038 pstatus = peer_status(iterator, status, sizeof(status));
10039 if (pstatus == 1)
10040 peers_mon_online++;
10041 else if (pstatus == 0)
10042 peers_mon_offline++;
10043 else {
10044 if (iterator->addr.sin_port == 0)
10045 peers_unmon_offline++;
10046 else
10047 peers_unmon_online++;
10050 snprintf(srch, sizeof(srch), FORMAT, name,
10051 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
10052 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ", /* Dynamic or not? */
10053 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
10054 iterator->ha ? " A " : " ", /* permit/deny */
10055 ntohs(iterator->addr.sin_port), status,
10056 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
10058 if (!s) {/* Normal CLI list */
10059 ast_cli(fd, FORMAT, name,
10060 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
10061 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ", /* Dynamic or not? */
10062 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
10063 iterator->ha ? " A " : " ", /* permit/deny */
10065 ntohs(iterator->addr.sin_port), status,
10066 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
10067 } else { /* Manager format */
10068 /* The names here need to be the same as other channels */
10069 astman_append(s,
10070 "Event: PeerEntry\r\n%s"
10071 "Channeltype: SIP\r\n"
10072 "ObjectName: %s\r\n"
10073 "ChanObjectType: peer\r\n" /* "peer" or "user" */
10074 "IPaddress: %s\r\n"
10075 "IPport: %d\r\n"
10076 "Dynamic: %s\r\n"
10077 "Natsupport: %s\r\n"
10078 "VideoSupport: %s\r\n"
10079 "ACL: %s\r\n"
10080 "Status: %s\r\n"
10081 "RealtimeDevice: %s\r\n\r\n",
10082 idtext,
10083 iterator->name,
10084 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "-none-",
10085 ntohs(iterator->addr.sin_port),
10086 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no", /* Dynamic or not? */
10087 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? "yes" : "no", /* NAT=yes? */
10088 ast_test_flag(&iterator->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no", /* VIDEOSUPPORT=yes? */
10089 iterator->ha ? "yes" : "no", /* permit/deny */
10090 status,
10091 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "yes":"no") : "no");
10094 ASTOBJ_UNLOCK(iterator);
10096 total_peers++;
10097 } while(0) );
10099 if (!s)
10100 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
10101 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
10103 if (havepattern)
10104 regfree(&regexbuf);
10106 if (total)
10107 *total = total_peers;
10110 return RESULT_SUCCESS;
10111 #undef FORMAT
10112 #undef FORMAT2
10115 /*! \brief List all allocated SIP Objects (realtime or static) */
10116 static int sip_show_objects(int fd, int argc, char *argv[])
10118 char tmp[256];
10119 if (argc != 3)
10120 return RESULT_SHOWUSAGE;
10121 ast_cli(fd, "-= User objects: %d static, %d realtime =-\n\n", suserobjs, ruserobjs);
10122 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &userl);
10123 ast_cli(fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
10124 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &peerl);
10125 ast_cli(fd, "-= Registry objects: %d =-\n\n", regobjs);
10126 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &regl);
10127 return RESULT_SUCCESS;
10129 /*! \brief Print call group and pickup group */
10130 static void print_group(int fd, ast_group_t group, int crlf)
10132 char buf[256];
10133 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
10136 /*! \brief Convert DTMF mode to printable string */
10137 static const char *dtmfmode2str(int mode)
10139 switch (mode) {
10140 case SIP_DTMF_RFC2833:
10141 return "rfc2833";
10142 case SIP_DTMF_INFO:
10143 return "info";
10144 case SIP_DTMF_INBAND:
10145 return "inband";
10146 case SIP_DTMF_AUTO:
10147 return "auto";
10149 return "<error>";
10152 /*! \brief Convert Insecure setting to printable string */
10153 static const char *insecure2str(int port, int invite)
10155 if (port && invite)
10156 return "port,invite";
10157 else if (port)
10158 return "port";
10159 else if (invite)
10160 return "invite";
10161 else
10162 return "no";
10165 /*! \brief Destroy disused contexts between reloads
10166 Only used in reload_config so the code for regcontext doesn't get ugly
10168 static void cleanup_stale_contexts(char *new, char *old)
10170 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
10172 while ((oldcontext = strsep(&old, "&"))) {
10173 stalecontext = '\0';
10174 ast_copy_string(newlist, new, sizeof(newlist));
10175 stringp = newlist;
10176 while ((newcontext = strsep(&stringp, "&"))) {
10177 if (strcmp(newcontext, oldcontext) == 0) {
10178 /* This is not the context you're looking for */
10179 stalecontext = '\0';
10180 break;
10181 } else if (strcmp(newcontext, oldcontext)) {
10182 stalecontext = oldcontext;
10186 if (stalecontext)
10187 ast_context_destroy(ast_context_find(stalecontext), "SIP");
10191 /*! \brief Remove temporary realtime objects from memory (CLI) */
10192 static int sip_prune_realtime(int fd, int argc, char *argv[])
10194 struct sip_peer *peer;
10195 struct sip_user *user;
10196 int pruneuser = FALSE;
10197 int prunepeer = FALSE;
10198 int multi = FALSE;
10199 char *name = NULL;
10200 regex_t regexbuf;
10202 switch (argc) {
10203 case 4:
10204 if (!strcasecmp(argv[3], "user"))
10205 return RESULT_SHOWUSAGE;
10206 if (!strcasecmp(argv[3], "peer"))
10207 return RESULT_SHOWUSAGE;
10208 if (!strcasecmp(argv[3], "like"))
10209 return RESULT_SHOWUSAGE;
10210 if (!strcasecmp(argv[3], "all")) {
10211 multi = TRUE;
10212 pruneuser = prunepeer = TRUE;
10213 } else {
10214 pruneuser = prunepeer = TRUE;
10215 name = argv[3];
10217 break;
10218 case 5:
10219 if (!strcasecmp(argv[4], "like"))
10220 return RESULT_SHOWUSAGE;
10221 if (!strcasecmp(argv[3], "all"))
10222 return RESULT_SHOWUSAGE;
10223 if (!strcasecmp(argv[3], "like")) {
10224 multi = TRUE;
10225 name = argv[4];
10226 pruneuser = prunepeer = TRUE;
10227 } else if (!strcasecmp(argv[3], "user")) {
10228 pruneuser = TRUE;
10229 if (!strcasecmp(argv[4], "all"))
10230 multi = TRUE;
10231 else
10232 name = argv[4];
10233 } else if (!strcasecmp(argv[3], "peer")) {
10234 prunepeer = TRUE;
10235 if (!strcasecmp(argv[4], "all"))
10236 multi = TRUE;
10237 else
10238 name = argv[4];
10239 } else
10240 return RESULT_SHOWUSAGE;
10241 break;
10242 case 6:
10243 if (strcasecmp(argv[4], "like"))
10244 return RESULT_SHOWUSAGE;
10245 if (!strcasecmp(argv[3], "user")) {
10246 pruneuser = TRUE;
10247 name = argv[5];
10248 } else if (!strcasecmp(argv[3], "peer")) {
10249 prunepeer = TRUE;
10250 name = argv[5];
10251 } else
10252 return RESULT_SHOWUSAGE;
10253 break;
10254 default:
10255 return RESULT_SHOWUSAGE;
10258 if (multi && name) {
10259 if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
10260 return RESULT_SHOWUSAGE;
10263 if (multi) {
10264 if (prunepeer) {
10265 int pruned = 0;
10267 ASTOBJ_CONTAINER_WRLOCK(&peerl);
10268 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
10269 ASTOBJ_RDLOCK(iterator);
10270 if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
10271 ASTOBJ_UNLOCK(iterator);
10272 continue;
10274 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10275 ASTOBJ_MARK(iterator);
10276 pruned++;
10278 ASTOBJ_UNLOCK(iterator);
10279 } while (0) );
10280 if (pruned) {
10281 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
10282 ast_cli(fd, "%d peers pruned.\n", pruned);
10283 } else
10284 ast_cli(fd, "No peers found to prune.\n");
10285 ASTOBJ_CONTAINER_UNLOCK(&peerl);
10287 if (pruneuser) {
10288 int pruned = 0;
10290 ASTOBJ_CONTAINER_WRLOCK(&userl);
10291 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
10292 ASTOBJ_RDLOCK(iterator);
10293 if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
10294 ASTOBJ_UNLOCK(iterator);
10295 continue;
10297 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10298 ASTOBJ_MARK(iterator);
10299 pruned++;
10301 ASTOBJ_UNLOCK(iterator);
10302 } while (0) );
10303 if (pruned) {
10304 ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, sip_destroy_user);
10305 ast_cli(fd, "%d users pruned.\n", pruned);
10306 } else
10307 ast_cli(fd, "No users found to prune.\n");
10308 ASTOBJ_CONTAINER_UNLOCK(&userl);
10310 } else {
10311 if (prunepeer) {
10312 if ((peer = ASTOBJ_CONTAINER_FIND_UNLINK(&peerl, name))) {
10313 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10314 ast_cli(fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
10315 ASTOBJ_CONTAINER_LINK(&peerl, peer);
10316 } else
10317 ast_cli(fd, "Peer '%s' pruned.\n", name);
10318 ASTOBJ_UNREF(peer, sip_destroy_peer);
10319 } else
10320 ast_cli(fd, "Peer '%s' not found.\n", name);
10322 if (pruneuser) {
10323 if ((user = ASTOBJ_CONTAINER_FIND_UNLINK(&userl, name))) {
10324 if (!ast_test_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10325 ast_cli(fd, "User '%s' is not a Realtime user, cannot be pruned.\n", name);
10326 ASTOBJ_CONTAINER_LINK(&userl, user);
10327 } else
10328 ast_cli(fd, "User '%s' pruned.\n", name);
10329 ASTOBJ_UNREF(user, sip_destroy_user);
10330 } else
10331 ast_cli(fd, "User '%s' not found.\n", name);
10335 return RESULT_SUCCESS;
10338 /*! \brief Print codec list from preference to CLI/manager */
10339 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
10341 int x, codec;
10343 for(x = 0; x < 32 ; x++) {
10344 codec = ast_codec_pref_index(pref, x);
10345 if (!codec)
10346 break;
10347 ast_cli(fd, "%s", ast_getformatname(codec));
10348 ast_cli(fd, ":%d", pref->framing[x]);
10349 if (x < 31 && ast_codec_pref_index(pref, x + 1))
10350 ast_cli(fd, ",");
10352 if (!x)
10353 ast_cli(fd, "none");
10356 /*! \brief Print domain mode to cli */
10357 static const char *domain_mode_to_text(const enum domain_mode mode)
10359 switch (mode) {
10360 case SIP_DOMAIN_AUTO:
10361 return "[Automatic]";
10362 case SIP_DOMAIN_CONFIG:
10363 return "[Configured]";
10366 return "";
10369 /*! \brief CLI command to list local domains */
10370 static int sip_show_domains(int fd, int argc, char *argv[])
10372 struct domain *d;
10373 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
10375 if (AST_LIST_EMPTY(&domain_list)) {
10376 ast_cli(fd, "SIP Domain support not enabled.\n\n");
10377 return RESULT_SUCCESS;
10378 } else {
10379 ast_cli(fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
10380 AST_LIST_LOCK(&domain_list);
10381 AST_LIST_TRAVERSE(&domain_list, d, list)
10382 ast_cli(fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
10383 domain_mode_to_text(d->mode));
10384 AST_LIST_UNLOCK(&domain_list);
10385 ast_cli(fd, "\n");
10386 return RESULT_SUCCESS;
10389 #undef FORMAT
10391 static char mandescr_show_peer[] =
10392 "Description: Show one SIP peer with details on current status.\n"
10393 "Variables: \n"
10394 " Peer: <name> The peer name you want to check.\n"
10395 " ActionID: <id> Optional action ID for this AMI transaction.\n";
10397 /*! \brief Show SIP peers in the manager API */
10398 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
10400 const char *a[4];
10401 const char *peer;
10402 int ret;
10404 peer = astman_get_header(m,"Peer");
10405 if (ast_strlen_zero(peer)) {
10406 astman_send_error(s, m, "Peer: <name> missing.\n");
10407 return 0;
10409 a[0] = "sip";
10410 a[1] = "show";
10411 a[2] = "peer";
10412 a[3] = peer;
10414 ret = _sip_show_peer(1, -1, s, m, 4, a);
10415 astman_append(s, "\r\n\r\n" );
10416 return ret;
10421 /*! \brief Show one peer in detail */
10422 static int sip_show_peer(int fd, int argc, char *argv[])
10424 return _sip_show_peer(0, fd, NULL, NULL, argc, (const char **) argv);
10427 /*! \brief Show one peer in detail (main function) */
10428 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
10430 char status[30] = "";
10431 char cbuf[256];
10432 struct sip_peer *peer;
10433 char codec_buf[512];
10434 struct ast_codec_pref *pref;
10435 struct ast_variable *v;
10436 struct sip_auth *auth;
10437 int x = 0, codec = 0, load_realtime;
10438 int realtimepeers;
10440 realtimepeers = ast_check_realtime("sippeers");
10442 if (argc < 4)
10443 return RESULT_SHOWUSAGE;
10445 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
10446 peer = find_peer(argv[3], NULL, load_realtime);
10447 if (s) { /* Manager */
10448 if (peer) {
10449 const char *id = astman_get_header(m,"ActionID");
10451 astman_append(s, "Response: Success\r\n");
10452 if (!ast_strlen_zero(id))
10453 astman_append(s, "ActionID: %s\r\n",id);
10454 } else {
10455 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.\n", argv[3]);
10456 astman_send_error(s, m, cbuf);
10457 return 0;
10460 if (peer && type==0 ) { /* Normal listing */
10461 ast_cli(fd,"\n\n");
10462 ast_cli(fd, " * Name : %s\n", peer->name);
10463 if (realtimepeers) { /* Realtime is enabled */
10464 ast_cli(fd, " Realtime peer: %s\n", ast_test_flag(&peer->flags[0], SIP_REALTIME) ? "Yes, cached" : "No");
10466 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
10467 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
10468 for (auth = peer->auth; auth; auth = auth->next) {
10469 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
10470 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
10472 ast_cli(fd, " Context : %s\n", peer->context);
10473 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
10474 ast_cli(fd, " Language : %s\n", peer->language);
10475 if (!ast_strlen_zero(peer->accountcode))
10476 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
10477 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
10478 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
10479 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
10480 if (!ast_strlen_zero(peer->fromuser))
10481 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
10482 if (!ast_strlen_zero(peer->fromdomain))
10483 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
10484 ast_cli(fd, " Callgroup : ");
10485 print_group(fd, peer->callgroup, 0);
10486 ast_cli(fd, " Pickupgroup : ");
10487 print_group(fd, peer->pickupgroup, 0);
10488 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
10489 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
10490 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
10491 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
10492 ast_cli(fd, " Dynamic : %s\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Yes":"No"));
10493 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
10494 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
10495 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
10496 ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT), ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)));
10497 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
10498 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
10499 ast_cli(fd, " T38 pt UDPTL : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL)?"Yes":"No");
10500 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10501 ast_cli(fd, " T38 pt RTP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_RTP)?"Yes":"No");
10502 ast_cli(fd, " T38 pt TCP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_TCP)?"Yes":"No");
10503 #endif
10504 ast_cli(fd, " CanReinvite : %s\n", ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Yes":"No");
10505 ast_cli(fd, " PromiscRedir : %s\n", ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Yes":"No");
10506 ast_cli(fd, " User=Phone : %s\n", ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Yes":"No");
10507 ast_cli(fd, " Video Support: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Yes":"No");
10508 ast_cli(fd, " Trust RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_TRUSTRPID) ? "Yes" : "No");
10509 ast_cli(fd, " Send RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_SENDRPID) ? "Yes" : "No");
10510 ast_cli(fd, " Subscriptions: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
10511 ast_cli(fd, " Overlap dial : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
10513 /* - is enumerated */
10514 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
10515 ast_cli(fd, " LastMsg : %d\n", peer->lastmsg);
10516 ast_cli(fd, " ToHost : %s\n", peer->tohost);
10517 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));
10518 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
10519 if (!ast_strlen_zero(global_regcontext))
10520 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
10521 ast_cli(fd, " Def. Username: %s\n", peer->username);
10522 ast_cli(fd, " SIP Options : ");
10523 if (peer->sipoptions) {
10524 int lastoption = -1;
10525 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
10526 if (sip_options[x].id != lastoption) {
10527 if (peer->sipoptions & sip_options[x].id)
10528 ast_cli(fd, "%s ", sip_options[x].text);
10529 lastoption = x;
10532 } else
10533 ast_cli(fd, "(none)");
10535 ast_cli(fd, "\n");
10536 ast_cli(fd, " Codecs : ");
10537 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
10538 ast_cli(fd, "%s\n", codec_buf);
10539 ast_cli(fd, " Codec Order : (");
10540 print_codec_to_cli(fd, &peer->prefs);
10541 ast_cli(fd, ")\n");
10543 ast_cli(fd, " Auto-Framing: %s \n", peer->autoframing ? "Yes" : "No");
10544 ast_cli(fd, " Status : ");
10545 peer_status(peer, status, sizeof(status));
10546 ast_cli(fd, "%s\n",status);
10547 ast_cli(fd, " Useragent : %s\n", peer->useragent);
10548 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
10549 if (peer->chanvars) {
10550 ast_cli(fd, " Variables :\n");
10551 for (v = peer->chanvars ; v ; v = v->next)
10552 ast_cli(fd, " %s = %s\n", v->name, v->value);
10554 ast_cli(fd,"\n");
10555 ASTOBJ_UNREF(peer,sip_destroy_peer);
10556 } else if (peer && type == 1) { /* manager listing */
10557 char buf[256];
10558 astman_append(s, "Channeltype: SIP\r\n");
10559 astman_append(s, "ObjectName: %s\r\n", peer->name);
10560 astman_append(s, "ChanObjectType: peer\r\n");
10561 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
10562 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
10563 astman_append(s, "Context: %s\r\n", peer->context);
10564 astman_append(s, "Language: %s\r\n", peer->language);
10565 if (!ast_strlen_zero(peer->accountcode))
10566 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
10567 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
10568 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
10569 if (!ast_strlen_zero(peer->fromuser))
10570 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
10571 if (!ast_strlen_zero(peer->fromdomain))
10572 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
10573 astman_append(s, "Callgroup: ");
10574 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->callgroup));
10575 astman_append(s, "Pickupgroup: ");
10576 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->pickupgroup));
10577 astman_append(s, "VoiceMailbox: %s\r\n", peer->mailbox);
10578 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
10579 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
10580 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
10581 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
10582 astman_append(s, "Dynamic: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Y":"N"));
10583 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
10584 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched,peer->expire));
10585 astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT), ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)));
10586 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
10587 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
10588 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
10589 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
10590 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
10591 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
10593 /* - is enumerated */
10594 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
10595 astman_append(s, "SIPLastMsg: %d\r\n", peer->lastmsg);
10596 astman_append(s, "ToHost: %s\r\n", peer->tohost);
10597 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));
10598 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));
10599 astman_append(s, "Default-Username: %s\r\n", peer->username);
10600 if (!ast_strlen_zero(global_regcontext))
10601 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
10602 astman_append(s, "Codecs: ");
10603 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
10604 astman_append(s, "%s\r\n", codec_buf);
10605 astman_append(s, "CodecOrder: ");
10606 pref = &peer->prefs;
10607 for(x = 0; x < 32 ; x++) {
10608 codec = ast_codec_pref_index(pref,x);
10609 if (!codec)
10610 break;
10611 astman_append(s, "%s", ast_getformatname(codec));
10612 if (x < 31 && ast_codec_pref_index(pref,x+1))
10613 astman_append(s, ",");
10616 astman_append(s, "\r\n");
10617 astman_append(s, "Status: ");
10618 peer_status(peer, status, sizeof(status));
10619 astman_append(s, "%s\r\n", status);
10620 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
10621 astman_append(s, "Reg-Contact : %s\r\n", peer->fullcontact);
10622 if (peer->chanvars) {
10623 for (v = peer->chanvars ; v ; v = v->next) {
10624 astman_append(s, "ChanVariable:\n");
10625 astman_append(s, " %s,%s\r\n", v->name, v->value);
10629 ASTOBJ_UNREF(peer,sip_destroy_peer);
10631 } else {
10632 ast_cli(fd,"Peer %s not found.\n", argv[3]);
10633 ast_cli(fd,"\n");
10636 return RESULT_SUCCESS;
10639 /*! \brief Show one user in detail */
10640 static int sip_show_user(int fd, int argc, char *argv[])
10642 char cbuf[256];
10643 struct sip_user *user;
10644 struct ast_variable *v;
10645 int load_realtime;
10647 if (argc < 4)
10648 return RESULT_SHOWUSAGE;
10650 /* Load from realtime storage? */
10651 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
10653 user = find_user(argv[3], load_realtime);
10654 if (user) {
10655 ast_cli(fd,"\n\n");
10656 ast_cli(fd, " * Name : %s\n", user->name);
10657 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
10658 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
10659 ast_cli(fd, " Context : %s\n", user->context);
10660 ast_cli(fd, " Language : %s\n", user->language);
10661 if (!ast_strlen_zero(user->accountcode))
10662 ast_cli(fd, " Accountcode : %s\n", user->accountcode);
10663 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
10664 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
10665 ast_cli(fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
10666 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
10667 ast_cli(fd, " Call limit : %d\n", user->call_limit);
10668 ast_cli(fd, " Callgroup : ");
10669 print_group(fd, user->callgroup, 0);
10670 ast_cli(fd, " Pickupgroup : ");
10671 print_group(fd, user->pickupgroup, 0);
10672 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
10673 ast_cli(fd, " ACL : %s\n", (user->ha?"Yes":"No"));
10674 ast_cli(fd, " Codec Order : (");
10675 print_codec_to_cli(fd, &user->prefs);
10676 ast_cli(fd, ")\n");
10678 ast_cli(fd, " Auto-Framing: %s \n", user->autoframing ? "Yes" : "No");
10679 if (user->chanvars) {
10680 ast_cli(fd, " Variables :\n");
10681 for (v = user->chanvars ; v ; v = v->next)
10682 ast_cli(fd, " %s = %s\n", v->name, v->value);
10684 ast_cli(fd,"\n");
10685 ASTOBJ_UNREF(user,sip_destroy_user);
10686 } else {
10687 ast_cli(fd,"User %s not found.\n", argv[3]);
10688 ast_cli(fd,"\n");
10691 return RESULT_SUCCESS;
10694 /*! \brief Show SIP Registry (registrations with other SIP proxies */
10695 static int sip_show_registry(int fd, int argc, char *argv[])
10697 #define FORMAT2 "%-30.30s %-12.12s %8.8s %-20.20s %-25.25s\n"
10698 #define FORMAT "%-30.30s %-12.12s %8d %-20.20s %-25.25s\n"
10699 char host[80];
10700 char tmpdat[256];
10701 struct tm tm;
10704 if (argc != 3)
10705 return RESULT_SHOWUSAGE;
10706 ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State", "Reg.Time");
10707 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
10708 ASTOBJ_RDLOCK(iterator);
10709 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
10710 if (iterator->regtime) {
10711 ast_localtime(&iterator->regtime, &tm, NULL);
10712 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
10713 } else {
10714 tmpdat[0] = 0;
10716 ast_cli(fd, FORMAT, host, iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
10717 ASTOBJ_UNLOCK(iterator);
10718 } while(0));
10719 return RESULT_SUCCESS;
10720 #undef FORMAT
10721 #undef FORMAT2
10724 /*! \brief List global settings for the SIP channel */
10725 static int sip_show_settings(int fd, int argc, char *argv[])
10727 int realtimepeers;
10728 int realtimeusers;
10729 char codec_buf[SIPBUFSIZE];
10731 realtimepeers = ast_check_realtime("sippeers");
10732 realtimeusers = ast_check_realtime("sipusers");
10734 if (argc != 3)
10735 return RESULT_SHOWUSAGE;
10736 ast_cli(fd, "\n\nGlobal Settings:\n");
10737 ast_cli(fd, "----------------\n");
10738 ast_cli(fd, " SIP Port: %d\n", ntohs(bindaddr.sin_port));
10739 ast_cli(fd, " Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
10740 ast_cli(fd, " Videosupport: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "Yes" : "No");
10741 ast_cli(fd, " AutoCreatePeer: %s\n", autocreatepeer ? "Yes" : "No");
10742 ast_cli(fd, " Allow unknown access: %s\n", global_allowguest ? "Yes" : "No");
10743 ast_cli(fd, " Allow subscriptions: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
10744 ast_cli(fd, " Allow overlap dialing: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
10745 ast_cli(fd, " Promsic. redir: %s\n", ast_test_flag(&global_flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
10746 ast_cli(fd, " SIP domain support: %s\n", AST_LIST_EMPTY(&domain_list) ? "No" : "Yes");
10747 ast_cli(fd, " Call to non-local dom.: %s\n", allow_external_domains ? "Yes" : "No");
10748 ast_cli(fd, " URI user is phone no: %s\n", ast_test_flag(&global_flags[0], SIP_USEREQPHONE) ? "Yes" : "No");
10749 ast_cli(fd, " Our auth realm %s\n", global_realm);
10750 ast_cli(fd, " Realm. auth: %s\n", authl ? "Yes": "No");
10751 ast_cli(fd, " Always auth rejects: %s\n", global_alwaysauthreject ? "Yes" : "No");
10752 ast_cli(fd, " Call limit peers only: %s\n", global_limitonpeers ? "Yes" : "No");
10753 ast_cli(fd, " Direct RTP setup: %s\n", global_directrtpsetup ? "Yes" : "No");
10754 ast_cli(fd, " User Agent: %s\n", global_useragent);
10755 ast_cli(fd, " MWI checking interval: %d secs\n", global_mwitime);
10756 ast_cli(fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
10757 ast_cli(fd, " Caller ID: %s\n", default_callerid);
10758 ast_cli(fd, " From: Domain: %s\n", default_fromdomain);
10759 ast_cli(fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
10760 ast_cli(fd, " Call Events: %s\n", global_callevents ? "On" : "Off");
10761 ast_cli(fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
10762 ast_cli(fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
10763 ast_cli(fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
10764 ast_cli(fd, " T38 fax pt UDPTL: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_UDPTL) ? "Yes" : "No");
10765 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10766 ast_cli(fd, " T38 fax pt RTP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_RTP) ? "Yes" : "No");
10767 ast_cli(fd, " T38 fax pt TCP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_TCP) ? "Yes" : "No");
10768 #endif
10769 ast_cli(fd, " RFC2833 Compensation: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE) ? "Yes" : "No");
10770 if (!realtimepeers && !realtimeusers)
10771 ast_cli(fd, " SIP realtime: Disabled\n" );
10772 else
10773 ast_cli(fd, " SIP realtime: Enabled\n" );
10775 ast_cli(fd, "\nGlobal Signalling Settings:\n");
10776 ast_cli(fd, "---------------------------\n");
10777 ast_cli(fd, " Codecs: ");
10778 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
10779 ast_cli(fd, "%s\n", codec_buf);
10780 ast_cli(fd, " Codec Order: ");
10781 print_codec_to_cli(fd, &default_prefs);
10782 ast_cli(fd, "\n");
10783 ast_cli(fd, " T1 minimum: %d\n", global_t1min);
10784 ast_cli(fd, " Relax DTMF: %s\n", global_relaxdtmf ? "Yes" : "No");
10785 ast_cli(fd, " Compact SIP headers: %s\n", compactheaders ? "Yes" : "No");
10786 ast_cli(fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
10787 ast_cli(fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
10788 ast_cli(fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
10789 ast_cli(fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
10790 ast_cli(fd, " DNS SRV lookup: %s\n", srvlookup ? "Yes" : "No");
10791 ast_cli(fd, " Pedantic SIP support: %s\n", pedanticsipchecking ? "Yes" : "No");
10792 ast_cli(fd, " Reg. min duration %d secs\n", min_expiry);
10793 ast_cli(fd, " Reg. max duration: %d secs\n", max_expiry);
10794 ast_cli(fd, " Reg. default duration: %d secs\n", default_expiry);
10795 ast_cli(fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
10796 ast_cli(fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
10797 ast_cli(fd, " Notify ringing state: %s\n", global_notifyringing ? "Yes" : "No");
10798 ast_cli(fd, " Notify hold state: %s\n", global_notifyhold ? "Yes" : "No");
10799 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(global_allowtransfer));
10800 ast_cli(fd, " Max Call Bitrate: %d kbps\r\n", default_maxcallbitrate);
10801 ast_cli(fd, " Auto-Framing: %s \r\n", global_autoframing ? "Yes" : "No");
10802 ast_cli(fd, "\nDefault Settings:\n");
10803 ast_cli(fd, "-----------------\n");
10804 ast_cli(fd, " Context: %s\n", default_context);
10805 ast_cli(fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
10806 ast_cli(fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
10807 ast_cli(fd, " Qualify: %d\n", default_qualify);
10808 ast_cli(fd, " Use ClientCode: %s\n", ast_test_flag(&global_flags[0], SIP_USECLIENTCODE) ? "Yes" : "No");
10809 ast_cli(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" );
10810 ast_cli(fd, " Language: %s\n", S_OR(default_language, "(Defaults to English)"));
10811 ast_cli(fd, " MOH Interpret: %s\n", default_mohinterpret);
10812 ast_cli(fd, " MOH Suggest: %s\n", default_mohsuggest);
10813 ast_cli(fd, " Voice Mail Extension: %s\n", default_vmexten);
10816 if (realtimepeers || realtimeusers) {
10817 ast_cli(fd, "\nRealtime SIP Settings:\n");
10818 ast_cli(fd, "----------------------\n");
10819 ast_cli(fd, " Realtime Peers: %s\n", realtimepeers ? "Yes" : "No");
10820 ast_cli(fd, " Realtime Users: %s\n", realtimeusers ? "Yes" : "No");
10821 ast_cli(fd, " Cache Friends: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? "Yes" : "No");
10822 ast_cli(fd, " Update: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) ? "Yes" : "No");
10823 ast_cli(fd, " Ignore Reg. Expire: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) ? "Yes" : "No");
10824 ast_cli(fd, " Save sys. name: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME) ? "Yes" : "No");
10825 ast_cli(fd, " Auto Clear: %d\n", global_rtautoclear);
10827 ast_cli(fd, "\n----\n");
10828 return RESULT_SUCCESS;
10831 /*! \brief Show subscription type in string format */
10832 static const char *subscription_type2str(enum subscriptiontype subtype)
10834 int i;
10836 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10837 if (subscription_types[i].type == subtype) {
10838 return subscription_types[i].text;
10841 return subscription_types[0].text;
10844 /*! \brief Find subscription type in array */
10845 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
10847 int i;
10849 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10850 if (subscription_types[i].type == subtype) {
10851 return &subscription_types[i];
10854 return &subscription_types[0];
10857 /*! \brief Show active SIP channels */
10858 static int sip_show_channels(int fd, int argc, char *argv[])
10860 return __sip_show_channels(fd, argc, argv, 0);
10863 /*! \brief Show active SIP subscriptions */
10864 static int sip_show_subscriptions(int fd, int argc, char *argv[])
10866 return __sip_show_channels(fd, argc, argv, 1);
10869 /*! \brief SIP show channels CLI (main function) */
10870 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions)
10872 #define FORMAT3 "%-15.15s %-10.10s %-11.11s %-15.15s %-13.13s %-15.15s %-10.10s\n"
10873 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-15.15s %-7.7s %-15.15s\n"
10874 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s\n"
10875 struct sip_pvt *cur;
10876 int numchans = 0;
10877 char *referstatus = NULL;
10879 if (argc != 3)
10880 return RESULT_SHOWUSAGE;
10881 ast_mutex_lock(&iflock);
10882 cur = iflist;
10883 if (!subscriptions)
10884 ast_cli(fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Seq (Tx/Rx)", "Format", "Hold", "Last Message");
10885 else
10886 ast_cli(fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox");
10887 for (; cur; cur = cur->next) {
10888 referstatus = "";
10889 if (cur->refer) { /* SIP transfer in progress */
10890 referstatus = referstatus2str(cur->refer->status);
10892 if (cur->subscribed == NONE && !subscriptions) {
10893 char formatbuf[SIPBUFSIZE/2];
10894 ast_cli(fd, FORMAT, ast_inet_ntoa(cur->sa.sin_addr),
10895 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10896 cur->callid,
10897 cur->ocseq, cur->icseq,
10898 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
10899 ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD) ? "Yes" : "No",
10900 ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY) ? "(d)" : "",
10901 cur->lastmsg ,
10902 referstatus
10904 numchans++;
10906 if (cur->subscribed != NONE && subscriptions) {
10907 ast_cli(fd, FORMAT3, ast_inet_ntoa(cur->sa.sin_addr),
10908 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10909 cur->callid,
10910 /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
10911 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
10912 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
10913 subscription_type2str(cur->subscribed),
10914 cur->subscribed == MWI_NOTIFICATION ? (cur->relatedpeer ? cur->relatedpeer->mailbox : "<none>") : "<none>"
10916 numchans++;
10919 ast_mutex_unlock(&iflock);
10920 if (!subscriptions)
10921 ast_cli(fd, "%d active SIP channel%s\n", numchans, (numchans != 1) ? "s" : "");
10922 else
10923 ast_cli(fd, "%d active SIP subscription%s\n", numchans, (numchans != 1) ? "s" : "");
10924 return RESULT_SUCCESS;
10925 #undef FORMAT
10926 #undef FORMAT2
10927 #undef FORMAT3
10930 /*! \brief Support routine for 'sip show channel' CLI */
10931 static char *complete_sipch(const char *line, const char *word, int pos, int state)
10933 int which=0;
10934 struct sip_pvt *cur;
10935 char *c = NULL;
10936 int wordlen = strlen(word);
10938 if (pos != 3) {
10939 return NULL;
10942 ast_mutex_lock(&iflock);
10943 for (cur = iflist; cur; cur = cur->next) {
10944 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
10945 c = ast_strdup(cur->callid);
10946 break;
10949 ast_mutex_unlock(&iflock);
10950 return c;
10953 /*! \brief Do completion on peer name */
10954 static char *complete_sip_peer(const char *word, int state, int flags2)
10956 char *result = NULL;
10957 int wordlen = strlen(word);
10958 int which = 0;
10960 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !result, do {
10961 /* locking of the object is not required because only the name and flags are being compared */
10962 if (!strncasecmp(word, iterator->name, wordlen) &&
10963 (!flags2 || ast_test_flag(&iterator->flags[1], flags2)) &&
10964 ++which > state)
10965 result = ast_strdup(iterator->name);
10966 } while(0) );
10967 return result;
10970 /*! \brief Support routine for 'sip show peer' CLI */
10971 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
10973 if (pos == 3)
10974 return complete_sip_peer(word, state, 0);
10976 return NULL;
10979 /*! \brief Support routine for 'sip debug peer' CLI */
10980 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state)
10982 if (pos == 3)
10983 return complete_sip_peer(word, state, 0);
10985 return NULL;
10988 /*! \brief Do completion on user name */
10989 static char *complete_sip_user(const char *word, int state, int flags2)
10991 char *result = NULL;
10992 int wordlen = strlen(word);
10993 int which = 0;
10995 ASTOBJ_CONTAINER_TRAVERSE(&userl, !result, do {
10996 /* locking of the object is not required because only the name and flags are being compared */
10997 if (!strncasecmp(word, iterator->name, wordlen)) {
10998 if (flags2 && !ast_test_flag(&iterator->flags[1], flags2))
10999 continue;
11000 if (++which > state) {
11001 result = ast_strdup(iterator->name);
11004 } while(0) );
11005 return result;
11008 /*! \brief Support routine for 'sip show user' CLI */
11009 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
11011 if (pos == 3)
11012 return complete_sip_user(word, state, 0);
11014 return NULL;
11017 /*! \brief Support routine for 'sip notify' CLI */
11018 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
11020 char *c = NULL;
11022 if (pos == 2) {
11023 int which = 0;
11024 char *cat = NULL;
11025 int wordlen = strlen(word);
11027 /* do completion for notify type */
11029 if (!notify_types)
11030 return NULL;
11032 while ( (cat = ast_category_browse(notify_types, cat)) ) {
11033 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
11034 c = ast_strdup(cat);
11035 break;
11038 return c;
11041 if (pos > 2)
11042 return complete_sip_peer(word, state, 0);
11044 return NULL;
11047 /*! \brief Support routine for 'sip prune realtime peer' CLI */
11048 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state)
11050 if (pos == 4)
11051 return complete_sip_peer(word, state, SIP_PAGE2_RTCACHEFRIENDS);
11052 return NULL;
11055 /*! \brief Support routine for 'sip prune realtime user' CLI */
11056 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state)
11058 if (pos == 4)
11059 return complete_sip_user(word, state, SIP_PAGE2_RTCACHEFRIENDS);
11061 return NULL;
11064 /*! \brief Show details of one active dialog */
11065 static int sip_show_channel(int fd, int argc, char *argv[])
11067 struct sip_pvt *cur;
11068 size_t len;
11069 int found = 0;
11071 if (argc != 4)
11072 return RESULT_SHOWUSAGE;
11073 len = strlen(argv[3]);
11074 ast_mutex_lock(&iflock);
11075 for (cur = iflist; cur; cur = cur->next) {
11076 if (!strncasecmp(cur->callid, argv[3], len)) {
11077 char formatbuf[SIPBUFSIZE/2];
11078 ast_cli(fd,"\n");
11079 if (cur->subscribed != NONE)
11080 ast_cli(fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
11081 else
11082 ast_cli(fd, " * SIP Call\n");
11083 ast_cli(fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
11084 ast_cli(fd, " Call-ID: %s\n", cur->callid);
11085 ast_cli(fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
11086 ast_cli(fd, " Our Codec Capability: %d\n", cur->capability);
11087 ast_cli(fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
11088 ast_cli(fd, " Their Codec Capability: %d\n", cur->peercapability);
11089 ast_cli(fd, " Joint Codec Capability: %d\n", cur->jointcapability);
11090 ast_cli(fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
11091 ast_cli(fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
11092 ast_cli(fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
11093 ast_cli(fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
11094 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
11095 ast_cli(fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
11096 ast_cli(fd, " Audio IP: %s %s\n", ast_inet_ntoa(cur->redirip.sin_addr.s_addr ? cur->redirip.sin_addr : cur->ourip), cur->redirip.sin_addr.s_addr ? "(Outside bridge)" : "(local)" );
11097 ast_cli(fd, " Our Tag: %s\n", cur->tag);
11098 ast_cli(fd, " Their Tag: %s\n", cur->theirtag);
11099 ast_cli(fd, " SIP User agent: %s\n", cur->useragent);
11100 if (!ast_strlen_zero(cur->username))
11101 ast_cli(fd, " Username: %s\n", cur->username);
11102 if (!ast_strlen_zero(cur->peername))
11103 ast_cli(fd, " Peername: %s\n", cur->peername);
11104 if (!ast_strlen_zero(cur->uri))
11105 ast_cli(fd, " Original uri: %s\n", cur->uri);
11106 if (!ast_strlen_zero(cur->cid_num))
11107 ast_cli(fd, " Caller-ID: %s\n", cur->cid_num);
11108 ast_cli(fd, " Need Destroy: %d\n", ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY));
11109 ast_cli(fd, " Last Message: %s\n", cur->lastmsg);
11110 ast_cli(fd, " Promiscuous Redir: %s\n", ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
11111 ast_cli(fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
11112 ast_cli(fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
11113 ast_cli(fd, " SIP Options: ");
11114 if (cur->sipoptions) {
11115 int x;
11116 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
11117 if (cur->sipoptions & sip_options[x].id)
11118 ast_cli(fd, "%s ", sip_options[x].text);
11120 } else
11121 ast_cli(fd, "(none)\n");
11122 ast_cli(fd, "\n\n");
11123 found++;
11126 ast_mutex_unlock(&iflock);
11127 if (!found)
11128 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
11129 return RESULT_SUCCESS;
11132 /*! \brief Show history details of one dialog */
11133 static int sip_show_history(int fd, int argc, char *argv[])
11135 struct sip_pvt *cur;
11136 size_t len;
11137 int found = 0;
11139 if (argc != 4)
11140 return RESULT_SHOWUSAGE;
11141 if (!recordhistory)
11142 ast_cli(fd, "\n***Note: History recording is currently DISABLED. Use 'sip history' to ENABLE.\n");
11143 len = strlen(argv[3]);
11144 ast_mutex_lock(&iflock);
11145 for (cur = iflist; cur; cur = cur->next) {
11146 if (!strncasecmp(cur->callid, argv[3], len)) {
11147 struct sip_history *hist;
11148 int x = 0;
11150 ast_cli(fd,"\n");
11151 if (cur->subscribed != NONE)
11152 ast_cli(fd, " * Subscription\n");
11153 else
11154 ast_cli(fd, " * SIP Call\n");
11155 if (cur->history)
11156 AST_LIST_TRAVERSE(cur->history, hist, list)
11157 ast_cli(fd, "%d. %s\n", ++x, hist->event);
11158 if (x == 0)
11159 ast_cli(fd, "Call '%s' has no history\n", cur->callid);
11160 found++;
11163 ast_mutex_unlock(&iflock);
11164 if (!found)
11165 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
11166 return RESULT_SUCCESS;
11169 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
11170 static void sip_dump_history(struct sip_pvt *dialog)
11172 int x = 0;
11173 struct sip_history *hist;
11174 static int errmsg = 0;
11176 if (!dialog)
11177 return;
11179 if (!option_debug && !sipdebug) {
11180 if (!errmsg) {
11181 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
11182 errmsg = 1;
11184 return;
11187 ast_log(LOG_DEBUG, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
11188 if (dialog->subscribed)
11189 ast_log(LOG_DEBUG, " * Subscription\n");
11190 else
11191 ast_log(LOG_DEBUG, " * SIP Call\n");
11192 if (dialog->history)
11193 AST_LIST_TRAVERSE(dialog->history, hist, list)
11194 ast_log(LOG_DEBUG, " %-3.3d. %s\n", ++x, hist->event);
11195 if (!x)
11196 ast_log(LOG_DEBUG, "Call '%s' has no history\n", dialog->callid);
11197 ast_log(LOG_DEBUG, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
11201 /*! \brief Receive SIP INFO Message
11202 \note Doesn't read the duration of the DTMF signal */
11203 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
11205 char buf[1024];
11206 unsigned int event;
11207 const char *c = get_header(req, "Content-Type");
11209 /* Need to check the media/type */
11210 if (!strcasecmp(c, "application/dtmf-relay") ||
11211 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
11212 unsigned int duration = 0;
11214 /* Try getting the "signal=" part */
11215 if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
11216 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
11217 transmit_response(p, "200 OK", req); /* Should return error */
11218 return;
11219 } else {
11220 ast_copy_string(buf, c, sizeof(buf));
11223 if (!ast_strlen_zero((c = get_body(req, "Duration"))))
11224 duration = atoi(c);
11225 if (!duration)
11226 duration = 100; /* 100 ms */
11228 if (!p->owner) { /* not a PBX call */
11229 transmit_response(p, "481 Call leg/transaction does not exist", req);
11230 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11231 return;
11234 if (ast_strlen_zero(buf)) {
11235 transmit_response(p, "200 OK", req);
11236 return;
11239 if (buf[0] == '*')
11240 event = 10;
11241 else if (buf[0] == '#')
11242 event = 11;
11243 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
11244 event = 12 + buf[0] - 'A';
11245 else
11246 event = atoi(buf);
11247 if (event == 16) {
11248 /* send a FLASH event */
11249 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
11250 ast_queue_frame(p->owner, &f);
11251 if (sipdebug)
11252 ast_verbose("* DTMF-relay event received: FLASH\n");
11253 } else {
11254 /* send a DTMF event */
11255 struct ast_frame f = { AST_FRAME_DTMF, };
11256 if (event < 10) {
11257 f.subclass = '0' + event;
11258 } else if (event < 11) {
11259 f.subclass = '*';
11260 } else if (event < 12) {
11261 f.subclass = '#';
11262 } else if (event < 16) {
11263 f.subclass = 'A' + (event - 12);
11265 f.len = duration;
11266 ast_queue_frame(p->owner, &f);
11267 if (sipdebug)
11268 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
11270 transmit_response(p, "200 OK", req);
11271 return;
11272 } else if (!strcasecmp(c, "application/media_control+xml")) {
11273 /* Eh, we'll just assume it's a fast picture update for now */
11274 if (p->owner)
11275 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
11276 transmit_response(p, "200 OK", req);
11277 return;
11278 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
11279 /* Client code (from SNOM phone) */
11280 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
11281 if (p->owner && p->owner->cdr)
11282 ast_cdr_setuserfield(p->owner, c);
11283 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
11284 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
11285 transmit_response(p, "200 OK", req);
11286 } else {
11287 transmit_response(p, "403 Unauthorized", req);
11289 return;
11290 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
11291 /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
11292 transmit_response(p, "200 OK", req);
11293 return;
11296 /* Other type of INFO message, not really understood by Asterisk */
11297 /* if (get_msg_text(buf, sizeof(buf), req)) { */
11299 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
11300 transmit_response(p, "415 Unsupported media type", req);
11301 return;
11304 /*! \brief Enable SIP Debugging in CLI */
11305 static int sip_do_debug_ip(int fd, int argc, char *argv[])
11307 struct hostent *hp;
11308 struct ast_hostent ahp;
11309 int port = 0;
11310 char *p, *arg;
11312 /* sip set debug ip <ip> */
11313 if (argc != 5)
11314 return RESULT_SHOWUSAGE;
11315 p = arg = argv[4];
11316 strsep(&p, ":");
11317 if (p)
11318 port = atoi(p);
11319 hp = ast_gethostbyname(arg, &ahp);
11320 if (hp == NULL)
11321 return RESULT_SHOWUSAGE;
11323 debugaddr.sin_family = AF_INET;
11324 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
11325 debugaddr.sin_port = htons(port);
11326 if (port == 0)
11327 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
11328 else
11329 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
11331 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11333 return RESULT_SUCCESS;
11336 /*! \brief sip_do_debug_peer: Turn on SIP debugging with peer mask */
11337 static int sip_do_debug_peer(int fd, int argc, char *argv[])
11339 struct sip_peer *peer;
11340 if (argc != 5)
11341 return RESULT_SHOWUSAGE;
11342 peer = find_peer(argv[4], NULL, 1);
11343 if (peer) {
11344 if (peer->addr.sin_addr.s_addr) {
11345 debugaddr.sin_family = AF_INET;
11346 debugaddr.sin_addr = peer->addr.sin_addr;
11347 debugaddr.sin_port = peer->addr.sin_port;
11348 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
11349 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11350 } else
11351 ast_cli(fd, "Unable to get IP address of peer '%s'\n", argv[4]);
11352 ASTOBJ_UNREF(peer,sip_destroy_peer);
11353 } else
11354 ast_cli(fd, "No such peer '%s'\n", argv[4]);
11355 return RESULT_SUCCESS;
11358 /*! \brief Turn on SIP debugging (CLI command) */
11359 static int sip_do_debug(int fd, int argc, char *argv[])
11361 int oldsipdebug = sipdebug_console;
11362 if (argc != 3) {
11363 if (argc != 5)
11364 return RESULT_SHOWUSAGE;
11365 else if (strcmp(argv[3], "ip") == 0)
11366 return sip_do_debug_ip(fd, argc, argv);
11367 else if (strcmp(argv[3], "peer") == 0)
11368 return sip_do_debug_peer(fd, argc, argv);
11369 else
11370 return RESULT_SHOWUSAGE;
11372 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11373 memset(&debugaddr, 0, sizeof(debugaddr));
11374 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
11375 return RESULT_SUCCESS;
11378 static int sip_do_debug_deprecated(int fd, int argc, char *argv[])
11380 int oldsipdebug = sipdebug_console;
11381 char *newargv[6] = { "sip", "set", "debug", NULL };
11382 if (argc != 2) {
11383 if (argc != 4)
11384 return RESULT_SHOWUSAGE;
11385 else if (strcmp(argv[2], "ip") == 0) {
11386 newargv[3] = argv[2];
11387 newargv[4] = argv[3];
11388 return sip_do_debug_ip(fd, argc + 1, newargv);
11389 } else if (strcmp(argv[2], "peer") == 0) {
11390 newargv[3] = argv[2];
11391 newargv[4] = argv[3];
11392 return sip_do_debug_peer(fd, argc + 1, newargv);
11393 } else
11394 return RESULT_SHOWUSAGE;
11396 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11397 memset(&debugaddr, 0, sizeof(debugaddr));
11398 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
11399 return RESULT_SUCCESS;
11402 /*! \brief Cli command to send SIP notify to peer */
11403 static int sip_notify(int fd, int argc, char *argv[])
11405 struct ast_variable *varlist;
11406 int i;
11408 if (argc < 4)
11409 return RESULT_SHOWUSAGE;
11411 if (!notify_types) {
11412 ast_cli(fd, "No %s file found, or no types listed there\n", notify_config);
11413 return RESULT_FAILURE;
11416 varlist = ast_variable_browse(notify_types, argv[2]);
11418 if (!varlist) {
11419 ast_cli(fd, "Unable to find notify type '%s'\n", argv[2]);
11420 return RESULT_FAILURE;
11423 for (i = 3; i < argc; i++) {
11424 struct sip_pvt *p;
11425 struct sip_request req;
11426 struct ast_variable *var;
11428 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY))) {
11429 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
11430 return RESULT_FAILURE;
11433 if (create_addr(p, argv[i])) {
11434 /* Maybe they're not registered, etc. */
11435 sip_destroy(p);
11436 ast_cli(fd, "Could not create address for '%s'\n", argv[i]);
11437 continue;
11440 initreqprep(&req, p, SIP_NOTIFY);
11442 for (var = varlist; var; var = var->next)
11443 add_header(&req, var->name, ast_unescape_semicolon(var->value));
11445 /* Recalculate our side, and recalculate Call ID */
11446 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
11447 p->ourip = __ourip;
11448 build_via(p);
11449 build_callid_pvt(p);
11450 ast_cli(fd, "Sending NOTIFY of type '%s' to '%s'\n", argv[2], argv[i]);
11451 transmit_sip_request(p, &req);
11452 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11455 return RESULT_SUCCESS;
11458 /*! \brief Disable SIP Debugging in CLI */
11459 static int sip_no_debug(int fd, int argc, char *argv[])
11461 if (argc != 4)
11462 return RESULT_SHOWUSAGE;
11463 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11464 ast_cli(fd, "SIP Debugging Disabled\n");
11465 return RESULT_SUCCESS;
11468 static int sip_no_debug_deprecated(int fd, int argc, char *argv[])
11470 if (argc != 3)
11471 return RESULT_SHOWUSAGE;
11472 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11473 ast_cli(fd, "SIP Debugging Disabled\n");
11474 return RESULT_SUCCESS;
11477 /*! \brief Enable SIP History logging (CLI) */
11478 static int sip_do_history(int fd, int argc, char *argv[])
11480 if (argc != 2) {
11481 return RESULT_SHOWUSAGE;
11483 recordhistory = TRUE;
11484 ast_cli(fd, "SIP History Recording Enabled (use 'sip show history')\n");
11485 return RESULT_SUCCESS;
11488 /*! \brief Disable SIP History logging (CLI) */
11489 static int sip_no_history(int fd, int argc, char *argv[])
11491 if (argc != 3) {
11492 return RESULT_SHOWUSAGE;
11494 recordhistory = FALSE;
11495 ast_cli(fd, "SIP History Recording Disabled\n");
11496 return RESULT_SUCCESS;
11499 /*! \brief Authenticate for outbound registration */
11500 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader)
11502 char digest[1024];
11503 p->authtries++;
11504 memset(digest,0,sizeof(digest));
11505 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
11506 /* There's nothing to use for authentication */
11507 /* No digest challenge in request */
11508 if (sip_debug_test_pvt(p) && p->registry)
11509 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
11510 /* No old challenge */
11511 return -1;
11513 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
11514 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
11515 if (sip_debug_test_pvt(p) && p->registry)
11516 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
11517 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
11520 /*! \brief Add authentication on outbound SIP packet */
11521 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init)
11523 char digest[1024];
11525 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
11526 return -2;
11528 p->authtries++;
11529 if (option_debug > 1)
11530 ast_log(LOG_DEBUG, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
11531 memset(digest, 0, sizeof(digest));
11532 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
11533 /* No way to authenticate */
11534 return -1;
11536 /* Now we have a reply digest */
11537 p->options->auth = digest;
11538 p->options->authheader = respheader;
11539 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
11542 /*! \brief reply to authentication for outbound registrations
11543 \return Returns -1 if we have no auth
11544 \note This is used for register= servers in sip.conf, SIP proxies we register
11545 with for receiving calls from. */
11546 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
11548 char tmp[512];
11549 char *c;
11550 char oldnonce[256];
11552 /* table of recognised keywords, and places where they should be copied */
11553 const struct x {
11554 const char *key;
11555 int field_index;
11556 } *i, keys[] = {
11557 { "realm=", ast_string_field_index(p, realm) },
11558 { "nonce=", ast_string_field_index(p, nonce) },
11559 { "opaque=", ast_string_field_index(p, opaque) },
11560 { "qop=", ast_string_field_index(p, qop) },
11561 { "domain=", ast_string_field_index(p, domain) },
11562 { NULL, 0 },
11565 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
11566 if (ast_strlen_zero(tmp))
11567 return -1;
11568 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
11569 ast_log(LOG_WARNING, "missing Digest.\n");
11570 return -1;
11572 c = tmp + strlen("Digest ");
11573 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
11574 while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
11575 for (i = keys; i->key != NULL; i++) {
11576 char *src, *separator;
11577 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
11578 continue;
11579 /* Found. Skip keyword, take text in quotes or up to the separator. */
11580 c += strlen(i->key);
11581 if (*c == '"') {
11582 src = ++c;
11583 separator = "\"";
11584 } else {
11585 src = c;
11586 separator = ",";
11588 strsep(&c, separator); /* clear separator and move ptr */
11589 ast_string_field_index_set(p, i->field_index, src);
11590 break;
11592 if (i->key == NULL) /* not found, try ',' */
11593 strsep(&c, ",");
11595 /* Reset nonce count */
11596 if (strcmp(p->nonce, oldnonce))
11597 p->noncecount = 0;
11599 /* Save auth data for following registrations */
11600 if (p->registry) {
11601 struct sip_registry *r = p->registry;
11603 if (strcmp(r->nonce, p->nonce)) {
11604 ast_string_field_set(r, realm, p->realm);
11605 ast_string_field_set(r, nonce, p->nonce);
11606 ast_string_field_set(r, domain, p->domain);
11607 ast_string_field_set(r, opaque, p->opaque);
11608 ast_string_field_set(r, qop, p->qop);
11609 r->noncecount = 0;
11612 return build_reply_digest(p, sipmethod, digest, digest_len);
11615 /*! \brief Build reply digest
11616 \return Returns -1 if we have no auth
11617 \note Build digest challenge for authentication of peers (for registration)
11618 and users (for calls). Also used for authentication of CANCEL and BYE
11620 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
11622 char a1[256];
11623 char a2[256];
11624 char a1_hash[256];
11625 char a2_hash[256];
11626 char resp[256];
11627 char resp_hash[256];
11628 char uri[256];
11629 char opaque[256] = "";
11630 char cnonce[80];
11631 const char *username;
11632 const char *secret;
11633 const char *md5secret;
11634 struct sip_auth *auth = NULL; /* Realm authentication */
11636 if (!ast_strlen_zero(p->domain))
11637 ast_copy_string(uri, p->domain, sizeof(uri));
11638 else if (!ast_strlen_zero(p->uri))
11639 ast_copy_string(uri, p->uri, sizeof(uri));
11640 else
11641 snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, ast_inet_ntoa(p->sa.sin_addr));
11643 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
11645 /* Check if we have separate auth credentials */
11646 if ((auth = find_realm_authentication(authl, p->realm))) {
11647 ast_log(LOG_WARNING, "use realm [%s] from peer [%s][%s]\n",
11648 auth->username, p->peername, p->username);
11649 username = auth->username;
11650 secret = auth->secret;
11651 md5secret = auth->md5secret;
11652 if (sipdebug)
11653 ast_log(LOG_DEBUG,"Using realm %s authentication for call %s\n", p->realm, p->callid);
11654 } else {
11655 /* No authentication, use peer or register= config */
11656 username = p->authname;
11657 secret = p->peersecret;
11658 md5secret = p->peermd5secret;
11660 if (ast_strlen_zero(username)) /* We have no authentication */
11661 return -1;
11663 /* Calculate SIP digest response */
11664 snprintf(a1,sizeof(a1),"%s:%s:%s", username, p->realm, secret);
11665 snprintf(a2,sizeof(a2),"%s:%s", sip_methods[method].text, uri);
11666 if (!ast_strlen_zero(md5secret))
11667 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
11668 else
11669 ast_md5_hash(a1_hash,a1);
11670 ast_md5_hash(a2_hash,a2);
11672 p->noncecount++;
11673 if (!ast_strlen_zero(p->qop))
11674 snprintf(resp,sizeof(resp),"%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
11675 else
11676 snprintf(resp,sizeof(resp),"%s:%s:%s", a1_hash, p->nonce, a2_hash);
11677 ast_md5_hash(resp_hash, resp);
11679 /* only include the opaque string if it's set */
11680 if (!ast_strlen_zero(p->opaque)) {
11681 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
11684 /* XXX We hard code our qop to "auth" for now. XXX */
11685 if (!ast_strlen_zero(p->qop))
11686 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);
11687 else
11688 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);
11690 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
11692 return 0;
11695 static char show_domains_usage[] =
11696 "Usage: sip show domains\n"
11697 " Lists all configured SIP local domains.\n"
11698 " Asterisk only responds to SIP messages to local domains.\n";
11700 static char notify_usage[] =
11701 "Usage: sip notify <type> <peer> [<peer>...]\n"
11702 " Send a NOTIFY message to a SIP peer or peers\n"
11703 " Message types are defined in sip_notify.conf\n";
11705 static char show_users_usage[] =
11706 "Usage: sip show users [like <pattern>]\n"
11707 " Lists all known SIP users.\n"
11708 " Optional regular expression pattern is used to filter the user list.\n";
11710 static char show_user_usage[] =
11711 "Usage: sip show user <name> [load]\n"
11712 " Shows all details on one SIP user and the current status.\n"
11713 " Option \"load\" forces lookup of peer in realtime storage.\n";
11715 static char show_inuse_usage[] =
11716 "Usage: sip show inuse [all]\n"
11717 " List all SIP users and peers usage counters and limits.\n"
11718 " Add option \"all\" to show all devices, not only those with a limit.\n";
11720 static char show_channels_usage[] =
11721 "Usage: sip show channels\n"
11722 " Lists all currently active SIP channels.\n";
11724 static char show_channel_usage[] =
11725 "Usage: sip show channel <channel>\n"
11726 " Provides detailed status on a given SIP channel.\n";
11728 static char show_history_usage[] =
11729 "Usage: sip show history <channel>\n"
11730 " Provides detailed dialog history on a given SIP channel.\n";
11732 static char show_peers_usage[] =
11733 "Usage: sip show peers [like <pattern>]\n"
11734 " Lists all known SIP peers.\n"
11735 " Optional regular expression pattern is used to filter the peer list.\n";
11737 static char show_peer_usage[] =
11738 "Usage: sip show peer <name> [load]\n"
11739 " Shows all details on one SIP peer and the current status.\n"
11740 " Option \"load\" forces lookup of peer in realtime storage.\n";
11742 static char prune_realtime_usage[] =
11743 "Usage: sip prune realtime [peer|user] [<name>|all|like <pattern>]\n"
11744 " Prunes object(s) from the cache.\n"
11745 " Optional regular expression pattern is used to filter the objects.\n";
11747 static char show_reg_usage[] =
11748 "Usage: sip show registry\n"
11749 " Lists all registration requests and status.\n";
11751 static char debug_usage[] =
11752 "Usage: sip set debug\n"
11753 " Enables dumping of SIP packets for debugging purposes\n\n"
11754 " sip set debug ip <host[:PORT]>\n"
11755 " Enables dumping of SIP packets to and from host.\n\n"
11756 " sip set debug peer <peername>\n"
11757 " Enables dumping of SIP packets to and from host.\n"
11758 " Require peer to be registered.\n";
11760 static char no_debug_usage[] =
11761 "Usage: sip set debug off\n"
11762 " Disables dumping of SIP packets for debugging purposes\n";
11764 static char no_history_usage[] =
11765 "Usage: sip history off\n"
11766 " Disables recording of SIP dialog history for debugging purposes\n";
11768 static char history_usage[] =
11769 "Usage: sip history\n"
11770 " Enables recording of SIP dialog history for debugging purposes.\n"
11771 "Use 'sip show history' to view the history of a call number.\n";
11773 static char sip_reload_usage[] =
11774 "Usage: sip reload\n"
11775 " Reloads SIP configuration from sip.conf\n";
11777 static char show_subscriptions_usage[] =
11778 "Usage: sip show subscriptions\n"
11779 " Lists active SIP subscriptions for extension states\n";
11781 static char show_objects_usage[] =
11782 "Usage: sip show objects\n"
11783 " Lists status of known SIP objects\n";
11785 static char show_settings_usage[] =
11786 "Usage: sip show settings\n"
11787 " Provides detailed list of the configuration of the SIP channel.\n";
11789 /*! \brief Read SIP header (dialplan function) */
11790 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len)
11792 struct sip_pvt *p;
11793 const char *content = NULL;
11794 AST_DECLARE_APP_ARGS(args,
11795 AST_APP_ARG(header);
11796 AST_APP_ARG(number);
11798 int i, number, start = 0;
11800 if (ast_strlen_zero(data)) {
11801 ast_log(LOG_WARNING, "This function requires a header name.\n");
11802 return -1;
11805 ast_channel_lock(chan);
11806 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
11807 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
11808 ast_channel_unlock(chan);
11809 return -1;
11812 AST_STANDARD_APP_ARGS(args, data);
11813 if (!args.number) {
11814 number = 1;
11815 } else {
11816 sscanf(args.number, "%d", &number);
11817 if (number < 1)
11818 number = 1;
11821 p = chan->tech_pvt;
11823 /* If there is no private structure, this channel is no longer alive */
11824 if (!p) {
11825 ast_channel_unlock(chan);
11826 return -1;
11829 for (i = 0; i < number; i++)
11830 content = __get_header(&p->initreq, args.header, &start);
11832 if (ast_strlen_zero(content)) {
11833 ast_channel_unlock(chan);
11834 return -1;
11837 ast_copy_string(buf, content, len);
11838 ast_channel_unlock(chan);
11840 return 0;
11843 static struct ast_custom_function sip_header_function = {
11844 .name = "SIP_HEADER",
11845 .synopsis = "Gets the specified SIP header",
11846 .syntax = "SIP_HEADER(<name>[,<number>])",
11847 .desc = "Since there are several headers (such as Via) which can occur multiple\n"
11848 "times, SIP_HEADER takes an optional second argument to specify which header with\n"
11849 "that name to retrieve. Headers start at offset 1.\n",
11850 .read = func_header_read,
11853 /*! \brief Dial plan function to check if domain is local */
11854 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11856 if (ast_strlen_zero(data)) {
11857 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
11858 return -1;
11860 if (check_sip_domain(data, NULL, 0))
11861 ast_copy_string(buf, data, len);
11862 else
11863 buf[0] = '\0';
11864 return 0;
11867 static struct ast_custom_function checksipdomain_function = {
11868 .name = "CHECKSIPDOMAIN",
11869 .synopsis = "Checks if domain is a local domain",
11870 .syntax = "CHECKSIPDOMAIN(<domain|IP>)",
11871 .read = func_check_sipdomain,
11872 .desc = "This function checks if the domain in the argument is configured\n"
11873 "as a local SIP domain that this Asterisk server is configured to handle.\n"
11874 "Returns the domain name if it is locally handled, otherwise an empty string.\n"
11875 "Check the domain= configuration in sip.conf\n",
11878 /*! \brief ${SIPPEER()} Dialplan function - reads peer data */
11879 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11881 struct sip_peer *peer;
11882 char *colname;
11884 if ((colname = strchr(data, ':'))) /*! \todo Will be deprecated after 1.4 */
11885 *colname++ = '\0';
11886 else if ((colname = strchr(data, '|')))
11887 *colname++ = '\0';
11888 else
11889 colname = "ip";
11891 if (!(peer = find_peer(data, NULL, 1)))
11892 return -1;
11894 if (!strcasecmp(colname, "ip")) {
11895 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
11896 } else if (!strcasecmp(colname, "status")) {
11897 peer_status(peer, buf, len);
11898 } else if (!strcasecmp(colname, "language")) {
11899 ast_copy_string(buf, peer->language, len);
11900 } else if (!strcasecmp(colname, "regexten")) {
11901 ast_copy_string(buf, peer->regexten, len);
11902 } else if (!strcasecmp(colname, "limit")) {
11903 snprintf(buf, len, "%d", peer->call_limit);
11904 } else if (!strcasecmp(colname, "curcalls")) {
11905 snprintf(buf, len, "%d", peer->inUse);
11906 } else if (!strcasecmp(colname, "accountcode")) {
11907 ast_copy_string(buf, peer->accountcode, len);
11908 } else if (!strcasecmp(colname, "useragent")) {
11909 ast_copy_string(buf, peer->useragent, len);
11910 } else if (!strcasecmp(colname, "mailbox")) {
11911 ast_copy_string(buf, peer->mailbox, len);
11912 } else if (!strcasecmp(colname, "context")) {
11913 ast_copy_string(buf, peer->context, len);
11914 } else if (!strcasecmp(colname, "expire")) {
11915 snprintf(buf, len, "%d", peer->expire);
11916 } else if (!strcasecmp(colname, "dynamic")) {
11917 ast_copy_string(buf, (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no"), len);
11918 } else if (!strcasecmp(colname, "callerid_name")) {
11919 ast_copy_string(buf, peer->cid_name, len);
11920 } else if (!strcasecmp(colname, "callerid_num")) {
11921 ast_copy_string(buf, peer->cid_num, len);
11922 } else if (!strcasecmp(colname, "codecs")) {
11923 ast_getformatname_multiple(buf, len -1, peer->capability);
11924 } else if (!strncasecmp(colname, "codec[", 6)) {
11925 char *codecnum;
11926 int index = 0, codec = 0;
11928 codecnum = colname + 6; /* move past the '[' */
11929 codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
11930 index = atoi(codecnum);
11931 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
11932 ast_copy_string(buf, ast_getformatname(codec), len);
11936 ASTOBJ_UNREF(peer, sip_destroy_peer);
11938 return 0;
11941 /*! \brief Structure to declare a dialplan function: SIPPEER */
11942 struct ast_custom_function sippeer_function = {
11943 .name = "SIPPEER",
11944 .synopsis = "Gets SIP peer information",
11945 .syntax = "SIPPEER(<peername>[|item])",
11946 .read = function_sippeer,
11947 .desc = "Valid items are:\n"
11948 "- ip (default) The IP address.\n"
11949 "- mailbox The configured mailbox.\n"
11950 "- context The configured context.\n"
11951 "- expire The epoch time of the next expire.\n"
11952 "- dynamic Is it dynamic? (yes/no).\n"
11953 "- callerid_name The configured Caller ID name.\n"
11954 "- callerid_num The configured Caller ID number.\n"
11955 "- codecs The configured codecs.\n"
11956 "- status Status (if qualify=yes).\n"
11957 "- regexten Registration extension\n"
11958 "- limit Call limit (call-limit)\n"
11959 "- curcalls Current amount of calls \n"
11960 " Only available if call-limit is set\n"
11961 "- language Default language for peer\n"
11962 "- accountcode Account code for this peer\n"
11963 "- useragent Current user agent id for peer\n"
11964 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
11965 "\n"
11968 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
11969 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11971 struct sip_pvt *p;
11973 *buf = 0;
11975 if (!data) {
11976 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
11977 return -1;
11980 ast_channel_lock(chan);
11981 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
11982 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
11983 ast_channel_unlock(chan);
11984 return -1;
11987 p = chan->tech_pvt;
11989 /* If there is no private structure, this channel is no longer alive */
11990 if (!p) {
11991 ast_channel_unlock(chan);
11992 return -1;
11995 if (!strcasecmp(data, "peerip")) {
11996 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
11997 } else if (!strcasecmp(data, "recvip")) {
11998 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
11999 } else if (!strcasecmp(data, "from")) {
12000 ast_copy_string(buf, p->from, len);
12001 } else if (!strcasecmp(data, "uri")) {
12002 ast_copy_string(buf, p->uri, len);
12003 } else if (!strcasecmp(data, "useragent")) {
12004 ast_copy_string(buf, p->useragent, len);
12005 } else if (!strcasecmp(data, "peername")) {
12006 ast_copy_string(buf, p->peername, len);
12007 } else if (!strcasecmp(data, "t38passthrough")) {
12008 if (p->t38.state == T38_DISABLED)
12009 ast_copy_string(buf, "0", sizeof("0"));
12010 else /* T38 is offered or enabled in this call */
12011 ast_copy_string(buf, "1", sizeof("1"));
12012 } else {
12013 ast_channel_unlock(chan);
12014 return -1;
12016 ast_channel_unlock(chan);
12018 return 0;
12021 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
12022 static struct ast_custom_function sipchaninfo_function = {
12023 .name = "SIPCHANINFO",
12024 .synopsis = "Gets the specified SIP parameter from the current channel",
12025 .syntax = "SIPCHANINFO(item)",
12026 .read = function_sipchaninfo_read,
12027 .desc = "Valid items are:\n"
12028 "- peerip The IP address of the peer.\n"
12029 "- recvip The source IP address of the peer.\n"
12030 "- from The URI from the From: header.\n"
12031 "- uri The URI from the Contact: header.\n"
12032 "- useragent The useragent.\n"
12033 "- peername The name of the peer.\n"
12034 "- t38passthrough 1 if T38 is offered or enabled in this channel, otherwise 0\n"
12037 /*! \brief Parse 302 Moved temporalily response */
12038 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
12040 char tmp[SIPBUFSIZE];
12041 char *s, *e, *uri, *t;
12042 char *domain;
12044 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
12045 if ((t = strchr(tmp, ',')))
12046 *t = '\0';
12047 s = get_in_brackets(tmp);
12048 uri = ast_strdupa(s);
12049 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
12050 if (!strncasecmp(s, "sip:", 4))
12051 s += 4;
12052 e = strchr(s, ';');
12053 if (e)
12054 *e = '\0';
12055 if (option_debug)
12056 ast_log(LOG_DEBUG, "Found promiscuous redirection to 'SIP/%s'\n", s);
12057 if (p->owner)
12058 ast_string_field_build(p->owner, call_forward, "SIP/%s", s);
12059 } else {
12060 e = strchr(tmp, '@');
12061 if (e) {
12062 *e++ = '\0';
12063 domain = e;
12064 } else {
12065 /* No username part */
12066 domain = tmp;
12068 e = strchr(s, ';'); /* Strip of parameters in the username part */
12069 if (e)
12070 *e = '\0';
12071 e = strchr(domain, ';'); /* Strip of parameters in the domain part */
12072 if (e)
12073 *e = '\0';
12075 if (!strncasecmp(s, "sip:", 4))
12076 s += 4;
12077 if (option_debug > 1)
12078 ast_log(LOG_DEBUG, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
12079 if (p->owner) {
12080 pbx_builtin_setvar_helper(p->owner, "SIPREDIRECTURI", uri);
12081 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
12082 ast_string_field_set(p->owner, call_forward, s);
12087 /*! \brief Check pending actions on SIP call */
12088 static void check_pendings(struct sip_pvt *p)
12090 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
12091 /* if we can't BYE, then this is really a pending CANCEL */
12092 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
12093 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
12094 /* Actually don't destroy us yet, wait for the 487 on our original
12095 INVITE, but do set an autodestruct just in case we never get it. */
12096 else {
12097 /* We have a pending outbound invite, don't send someting
12098 new in-transaction */
12099 if (p->pendinginvite)
12100 return;
12102 /* Perhaps there is an SD change INVITE outstanding */
12103 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
12105 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
12106 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12107 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
12108 /* if we can't REINVITE, hold it for later */
12109 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
12110 if (option_debug)
12111 ast_log(LOG_DEBUG, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
12112 } else {
12113 if (option_debug)
12114 ast_log(LOG_DEBUG, "Sending pending reinvite on '%s'\n", p->callid);
12115 /* Didn't get to reinvite yet, so do it now */
12116 transmit_reinvite_with_sdp(p);
12117 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
12122 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
12123 to avoid race conditions between asterisk servers.
12124 Called from the scheduler.
12126 static int sip_reinvite_retry(const void *data)
12128 struct sip_pvt *p = (struct sip_pvt *) data;
12130 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
12131 p->waitid = -1;
12132 return 0;
12136 /*! \brief Handle SIP response to INVITE dialogue */
12137 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
12139 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
12140 int res = 0;
12141 int xmitres = 0;
12142 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
12143 struct ast_channel *bridgepeer = NULL;
12145 if (option_debug > 3) {
12146 if (reinvite)
12147 ast_log(LOG_DEBUG, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
12148 else
12149 ast_log(LOG_DEBUG, "SIP response %d to standard invite\n", resp);
12152 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) { /* This call is already gone */
12153 if (option_debug)
12154 ast_log(LOG_DEBUG, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
12155 return;
12158 /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
12159 /* Don't auto congest anymore since we've gotten something useful back */
12160 AST_SCHED_DEL(sched, p->initid);
12162 /* RFC3261 says we must treat every 1xx response (but not 100)
12163 that we don't recognize as if it was 183.
12165 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
12166 resp = 183;
12168 /* Any response between 100 and 199 is PROCEEDING */
12169 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
12170 p->invitestate = INV_PROCEEDING;
12172 /* Final response, not 200 ? */
12173 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
12174 p->invitestate = INV_COMPLETED;
12177 switch (resp) {
12178 case 100: /* Trying */
12179 case 101: /* Dialog establishment */
12180 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12181 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12182 check_pendings(p);
12183 break;
12185 case 180: /* 180 Ringing */
12186 case 182: /* 182 Queued */
12187 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12188 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12189 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12190 ast_queue_control(p->owner, AST_CONTROL_RINGING);
12191 if (p->owner->_state != AST_STATE_UP) {
12192 ast_setstate(p->owner, AST_STATE_RINGING);
12195 if (find_sdp(req)) {
12196 if (p->invitestate != INV_CANCELLED)
12197 p->invitestate = INV_EARLY_MEDIA;
12198 res = process_sdp(p, req);
12199 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12200 /* Queue a progress frame only if we have SDP in 180 or 182 */
12201 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
12204 check_pendings(p);
12205 break;
12207 case 183: /* Session progress */
12208 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12209 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12210 /* Ignore 183 Session progress without SDP */
12211 if (find_sdp(req)) {
12212 if (p->invitestate != INV_CANCELLED)
12213 p->invitestate = INV_EARLY_MEDIA;
12214 res = process_sdp(p, req);
12215 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12216 /* Queue a progress frame */
12217 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
12220 check_pendings(p);
12221 break;
12223 case 200: /* 200 OK on invite - someone's answering our call */
12224 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12225 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12226 p->authtries = 0;
12227 if (find_sdp(req)) {
12228 if ((res = process_sdp(p, req)) && !ast_test_flag(req, SIP_PKT_IGNORE))
12229 if (!reinvite)
12230 /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
12231 /* For re-invites, we try to recover */
12232 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12235 /* Parse contact header for continued conversation */
12236 /* When we get 200 OK, we know which device (and IP) to contact for this call */
12237 /* This is important when we have a SIP proxy between us and the phone */
12238 if (outgoing) {
12239 update_call_counter(p, DEC_CALL_RINGING);
12240 parse_ok_contact(p, req);
12241 if(set_address_from_contact(p)) {
12242 /* Bad contact - we don't know how to reach this device */
12243 /* We need to ACK, but then send a bye */
12244 /* OEJ: Possible issue that may need a check:
12245 If we have a proxy route between us and the device,
12246 should we care about resolving the contact
12247 or should we just send it?
12249 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12250 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12253 /* Save Record-Route for any later requests we make on this dialogue */
12254 if (!reinvite)
12255 build_route(p, req, 1);
12258 if (p->owner && (p->owner->_state == AST_STATE_UP) && (bridgepeer = ast_bridged_channel(p->owner))) { /* if this is a re-invite */
12259 struct sip_pvt *bridgepvt = NULL;
12261 if (!bridgepeer->tech) {
12262 ast_log(LOG_WARNING, "Ooooh.. no tech! That's REALLY bad\n");
12263 break;
12265 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
12266 bridgepvt = (struct sip_pvt*)(bridgepeer->tech_pvt);
12267 if (bridgepvt->udptl) {
12268 if (p->t38.state == T38_PEER_REINVITE) {
12269 sip_handle_t38_reinvite(bridgepeer, p, 0);
12270 ast_rtp_set_rtptimers_onhold(p->rtp);
12271 if (p->vrtp)
12272 ast_rtp_set_rtptimers_onhold(p->vrtp); /* Turn off RTP timers while we send fax */
12273 } else if (p->t38.state == T38_DISABLED && bridgepeer && (bridgepvt->t38.state == T38_ENABLED)) {
12274 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
12275 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
12276 /* XXXX Should we really destroy this session here, without any response at all??? */
12277 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12279 } else {
12280 if (option_debug > 1)
12281 ast_log(LOG_DEBUG, "Strange... The other side of the bridge does not have a udptl struct\n");
12282 ast_mutex_lock(&bridgepvt->lock);
12283 bridgepvt->t38.state = T38_DISABLED;
12284 ast_mutex_unlock(&bridgepvt->lock);
12285 if (option_debug)
12286 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->tech->type);
12287 p->t38.state = T38_DISABLED;
12288 if (option_debug > 1)
12289 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12291 } else {
12292 /* Other side is not a SIP channel */
12293 if (option_debug > 1)
12294 ast_log(LOG_DEBUG, "Strange... The other side of the bridge is not a SIP channel\n");
12295 p->t38.state = T38_DISABLED;
12296 if (option_debug > 1)
12297 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12300 if ((p->t38.state == T38_LOCAL_REINVITE) || (p->t38.state == T38_LOCAL_DIRECT)) {
12301 /* If there was T38 reinvite and we are supposed to answer with 200 OK than this should set us to T38 negotiated mode */
12302 p->t38.state = T38_ENABLED;
12303 if (option_debug)
12304 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12307 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12308 if (!reinvite) {
12309 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
12310 } else { /* RE-invite */
12311 ast_queue_frame(p->owner, &ast_null_frame);
12313 } else {
12314 /* It's possible we're getting an 200 OK after we've tried to disconnect
12315 by sending CANCEL */
12316 /* First send ACK, then send bye */
12317 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12318 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12320 /* If I understand this right, the branch is different for a non-200 ACK only */
12321 p->invitestate = INV_TERMINATED;
12322 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
12323 check_pendings(p);
12324 break;
12325 case 407: /* Proxy authentication */
12326 case 401: /* Www auth */
12327 /* First we ACK */
12328 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12329 if (p->options)
12330 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
12332 /* Then we AUTH */
12333 ast_string_field_free(p, theirtag); /* forget their old tag, so we don't match tags when getting response */
12334 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
12335 char *authenticate = (resp == 401 ? "WWW-Authenticate" : "Proxy-Authenticate");
12336 char *authorization = (resp == 401 ? "Authorization" : "Proxy-Authorization");
12337 if (p->authtries < MAX_AUTHTRIES)
12338 p->invitestate = INV_CALLING;
12339 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, authenticate, authorization, SIP_INVITE, 1)) {
12340 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
12341 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12342 sip_alreadygone(p);
12343 if (p->owner)
12344 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12347 break;
12349 case 403: /* Forbidden */
12350 /* First we ACK */
12351 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12352 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
12353 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner)
12354 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12355 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12356 sip_alreadygone(p);
12357 break;
12359 case 404: /* Not found */
12360 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12361 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12362 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12363 sip_alreadygone(p);
12364 break;
12366 case 408: /* Request timeout */
12367 case 481: /* Call leg does not exist */
12368 /* Could be REFER caused INVITE with replaces */
12369 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
12370 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12371 if (p->owner)
12372 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12373 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12374 break;
12375 case 487: /* Cancelled transaction */
12376 /* We have sent CANCEL on an outbound INVITE
12377 This transaction is already scheduled to be killed by sip_hangup().
12379 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12380 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE)) {
12381 ast_queue_hangup(p->owner);
12382 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
12383 } else if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
12384 update_call_counter(p, DEC_CALL_LIMIT);
12385 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
12386 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12387 sip_alreadygone(p);
12389 break;
12390 case 488: /* Not acceptable here */
12391 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12392 if (reinvite && p->udptl) {
12393 /* If this is a T.38 call, we should go back to
12394 audio. If this is an audio call - something went
12395 terribly wrong since we don't renegotiate codecs,
12396 only IP/port .
12398 p->t38.state = T38_DISABLED;
12399 /* Try to reset RTP timers */
12400 ast_rtp_set_rtptimers_onhold(p->rtp);
12401 ast_log(LOG_ERROR, "Got error on T.38 re-invite. Bad configuration. Peer needs to have T.38 disabled.\n");
12403 /*! \bug Is there any way we can go back to the audio call on both
12404 sides here?
12406 /* While figuring that out, hangup the call */
12407 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12408 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12409 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12410 } else if (p->udptl && p->t38.state == T38_LOCAL_DIRECT) {
12411 /* We tried to send T.38 out in an initial INVITE and the remote side rejected it,
12412 right now we can't fall back to audio so totally abort.
12414 p->t38.state = T38_DISABLED;
12415 /* Try to reset RTP timers */
12416 ast_rtp_set_rtptimers_onhold(p->rtp);
12417 ast_log(LOG_ERROR, "Got error on T.38 initial invite. Bailing out.\n");
12419 /* The dialog is now terminated */
12420 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12421 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12422 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12423 sip_alreadygone(p);
12424 } else {
12425 /* We can't set up this call, so give up */
12426 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12427 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12428 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12429 /* If there's no dialog to end, then mark p as already gone */
12430 if (!reinvite)
12431 sip_alreadygone(p);
12433 break;
12434 case 491: /* Pending */
12435 /* we really should have to wait a while, then retransmit
12436 * We should support the retry-after at some point
12437 * At this point, we treat this as a congestion if the call is not in UP state
12439 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12440 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE)) {
12441 if (p->owner->_state != AST_STATE_UP) {
12442 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12443 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12444 } else {
12445 /* This is a re-invite that failed.
12446 * Reset the flag after a while
12448 int wait = 3 + ast_random() % 5;
12449 p->waitid = ast_sched_add(sched, wait, sip_reinvite_retry, p);
12450 if (option_debug > 2)
12451 ast_log(LOG_DEBUG, "Reinvite race. Waiting %d secs before retry\n", wait);
12454 break;
12456 case 501: /* Not implemented */
12457 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12458 if (p->owner)
12459 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12460 break;
12462 if (xmitres == XMIT_ERROR)
12463 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
12466 /* \brief Handle SIP response in REFER transaction
12467 We've sent a REFER, now handle responses to it
12469 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
12471 char *auth = "Proxy-Authenticate";
12472 char *auth2 = "Proxy-Authorization";
12474 /* If no refer structure exists, then do nothing */
12475 if (!p->refer)
12476 return;
12478 switch (resp) {
12479 case 202: /* Transfer accepted */
12480 /* We need to do something here */
12481 /* The transferee is now sending INVITE to target */
12482 p->refer->status = REFER_ACCEPTED;
12483 /* Now wait for next message */
12484 if (option_debug > 2)
12485 ast_log(LOG_DEBUG, "Got 202 accepted on transfer\n");
12486 /* We should hang along, waiting for NOTIFY's here */
12487 break;
12489 case 401: /* Not www-authorized on SIP method */
12490 case 407: /* Proxy auth */
12491 if (ast_strlen_zero(p->authname)) {
12492 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
12493 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12494 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12496 if (resp == 401) {
12497 auth = "WWW-Authenticate";
12498 auth2 = "Authorization";
12500 if ((p->authtries > 1) || do_proxy_auth(p, req, auth, auth2, SIP_REFER, 0)) {
12501 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
12502 p->refer->status = REFER_NOAUTH;
12503 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12505 break;
12506 case 481: /* Call leg does not exist */
12508 /* A transfer with Replaces did not work */
12509 /* OEJ: We should Set flag, cancel the REFER, go back
12510 to original call - but right now we can't */
12511 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
12512 if (p->owner)
12513 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12514 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12515 break;
12517 case 500: /* Server error */
12518 case 501: /* Method not implemented */
12519 /* Return to the current call onhold */
12520 /* Status flag needed to be reset */
12521 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
12522 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12523 p->refer->status = REFER_FAILED;
12524 break;
12525 case 603: /* Transfer declined */
12526 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
12527 p->refer->status = REFER_FAILED;
12528 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12529 break;
12533 /*! \brief Handle responses on REGISTER to services */
12534 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
12536 int expires, expires_ms;
12537 struct sip_registry *r;
12538 r=p->registry;
12540 switch (resp) {
12541 case 401: /* Unauthorized */
12542 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "WWW-Authenticate", "Authorization")) {
12543 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
12544 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12546 break;
12547 case 403: /* Forbidden */
12548 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
12549 if (global_regattempts_max)
12550 p->registry->regattempts = global_regattempts_max+1;
12551 AST_SCHED_DEL(sched, r->timeout);
12552 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12553 break;
12554 case 404: /* Not found */
12555 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username,p->registry->hostname);
12556 if (global_regattempts_max)
12557 p->registry->regattempts = global_regattempts_max+1;
12558 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12559 r->call = NULL;
12560 AST_SCHED_DEL(sched, r->timeout);
12561 break;
12562 case 407: /* Proxy auth */
12563 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization")) {
12564 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
12565 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12567 break;
12568 case 408: /* Request timeout */
12569 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12570 r->call = NULL;
12571 AST_SCHED_DEL(sched, r->timeout);
12572 break;
12573 case 479: /* SER: Not able to process the URI - address is wrong in register*/
12574 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username,p->registry->hostname);
12575 if (global_regattempts_max)
12576 p->registry->regattempts = global_regattempts_max+1;
12577 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12578 r->call = NULL;
12579 AST_SCHED_DEL(sched, r->timeout);
12580 break;
12581 case 200: /* 200 OK */
12582 if (!r) {
12583 ast_log(LOG_WARNING, "Got 200 OK on REGISTER that isn't a register\n");
12584 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12585 return 0;
12588 r->regstate = REG_STATE_REGISTERED;
12589 r->regtime = time(NULL); /* Reset time of last succesful registration */
12590 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
12591 r->regattempts = 0;
12592 if (option_debug)
12593 ast_log(LOG_DEBUG, "Registration successful\n");
12594 if (r->timeout > -1) {
12595 if (option_debug)
12596 ast_log(LOG_DEBUG, "Cancelling timeout %d\n", r->timeout);
12598 AST_SCHED_DEL(sched, r->timeout);
12599 r->call = NULL;
12600 p->registry = NULL;
12601 /* Let this one hang around until we have all the responses */
12602 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12603 /* ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); */
12605 /* set us up for re-registering */
12606 /* figure out how long we got registered for */
12607 AST_SCHED_DEL(sched, r->expire);
12608 /* according to section 6.13 of RFC, contact headers override
12609 expires headers, so check those first */
12610 expires = 0;
12612 /* XXX todo: try to save the extra call */
12613 if (!ast_strlen_zero(get_header(req, "Contact"))) {
12614 const char *contact = NULL;
12615 const char *tmptmp = NULL;
12616 int start = 0;
12617 for(;;) {
12618 contact = __get_header(req, "Contact", &start);
12619 /* this loop ensures we get a contact header about our register request */
12620 if(!ast_strlen_zero(contact)) {
12621 if( (tmptmp=strstr(contact, p->our_contact))) {
12622 contact=tmptmp;
12623 break;
12625 } else
12626 break;
12628 tmptmp = strcasestr(contact, "expires=");
12629 if (tmptmp) {
12630 if (sscanf(tmptmp + 8, "%d;", &expires) != 1)
12631 expires = 0;
12635 if (!expires)
12636 expires=atoi(get_header(req, "expires"));
12637 if (!expires)
12638 expires=default_expiry;
12640 expires_ms = expires * 1000;
12641 if (expires <= EXPIRY_GUARD_LIMIT)
12642 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT),EXPIRY_GUARD_MIN);
12643 else
12644 expires_ms -= EXPIRY_GUARD_SECS * 1000;
12645 if (sipdebug)
12646 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
12648 r->refresh= (int) expires_ms / 1000;
12650 /* Schedule re-registration before we expire */
12651 AST_SCHED_DEL(sched, r->expire);
12652 r->expire = ast_sched_add(sched, expires_ms, sip_reregister, r);
12653 ASTOBJ_UNREF(r, sip_registry_destroy);
12655 return 1;
12658 /*! \brief Handle qualification responses (OPTIONS) */
12659 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
12661 struct sip_peer *peer = p->relatedpeer;
12662 int statechanged, is_reachable, was_reachable;
12663 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
12666 * Compute the response time to a ping (goes in peer->lastms.)
12667 * -1 means did not respond, 0 means unknown,
12668 * 1..maxms is a valid response, >maxms means late response.
12670 if (pingtime < 1) /* zero = unknown, so round up to 1 */
12671 pingtime = 1;
12673 /* Now determine new state and whether it has changed.
12674 * Use some helper variables to simplify the writing
12675 * of the expressions.
12677 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
12678 is_reachable = pingtime <= peer->maxms;
12679 statechanged = peer->lastms == 0 /* yes, unknown before */
12680 || was_reachable != is_reachable;
12682 peer->lastms = pingtime;
12683 peer->call = NULL;
12684 if (statechanged) {
12685 const char *s = is_reachable ? "Reachable" : "Lagged";
12687 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
12688 peer->name, s, pingtime, peer->maxms);
12689 ast_device_state_changed("SIP/%s", peer->name);
12690 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
12691 "Peer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
12692 peer->name, s, pingtime);
12695 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
12696 struct sip_peer *peer_ptr = peer;
12697 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
12700 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12702 /* Try again eventually */
12703 peer->pokeexpire = ast_sched_add(sched,
12704 is_reachable ? DEFAULT_FREQ_OK : DEFAULT_FREQ_NOTOK,
12705 sip_poke_peer_s, ASTOBJ_REF(peer));
12707 if (peer->pokeexpire == -1) {
12708 ASTOBJ_UNREF(peer, sip_destroy_peer);
12712 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
12713 static void stop_media_flows(struct sip_pvt *p)
12715 /* Immediately stop RTP, VRTP and UDPTL as applicable */
12716 if (p->rtp)
12717 ast_rtp_stop(p->rtp);
12718 if (p->vrtp)
12719 ast_rtp_stop(p->vrtp);
12720 if (p->udptl)
12721 ast_udptl_stop(p->udptl);
12724 /*! \brief Handle SIP response in dialogue */
12725 /* XXX only called by handle_request */
12726 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
12728 struct ast_channel *owner;
12729 int sipmethod;
12730 int res = 1;
12731 const char *c = get_header(req, "Cseq");
12732 const char *msg = strchr(c, ' ');
12734 if (!msg)
12735 msg = "";
12736 else
12737 msg++;
12738 sipmethod = find_sip_method(msg);
12740 owner = p->owner;
12741 if (owner)
12742 owner->hangupcause = hangup_sip2cause(resp);
12744 /* Acknowledge whatever it is destined for */
12745 if ((resp >= 100) && (resp <= 199))
12746 __sip_semi_ack(p, seqno, 0, sipmethod);
12747 else
12748 __sip_ack(p, seqno, 0, sipmethod);
12750 /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
12751 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite)
12752 p->pendinginvite = 0;
12754 /* Get their tag if we haven't already */
12755 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
12756 char tag[128];
12758 gettag(req, "To", tag, sizeof(tag));
12759 ast_string_field_set(p, theirtag, tag);
12761 if (p->relatedpeer && p->method == SIP_OPTIONS) {
12762 /* We don't really care what the response is, just that it replied back.
12763 Well, as long as it's not a 100 response... since we might
12764 need to hang around for something more "definitive" */
12765 if (resp != 100)
12766 handle_response_peerpoke(p, resp, req);
12767 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12768 switch(resp) {
12769 case 100: /* 100 Trying */
12770 case 101: /* 101 Dialog establishment */
12771 if (sipmethod == SIP_INVITE)
12772 handle_response_invite(p, resp, rest, req, seqno);
12773 break;
12774 case 183: /* 183 Session Progress */
12775 if (sipmethod == SIP_INVITE)
12776 handle_response_invite(p, resp, rest, req, seqno);
12777 break;
12778 case 180: /* 180 Ringing */
12779 if (sipmethod == SIP_INVITE)
12780 handle_response_invite(p, resp, rest, req, seqno);
12781 break;
12782 case 182: /* 182 Queued */
12783 if (sipmethod == SIP_INVITE)
12784 handle_response_invite(p, resp, rest, req, seqno);
12785 break;
12786 case 200: /* 200 OK */
12787 p->authtries = 0; /* Reset authentication counter */
12788 if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
12789 /* We successfully transmitted a message
12790 or a video update request in INFO */
12791 /* Nothing happens here - the message is inside a dialog */
12792 } else if (sipmethod == SIP_INVITE) {
12793 handle_response_invite(p, resp, rest, req, seqno);
12794 } else if (sipmethod == SIP_NOTIFY) {
12795 /* They got the notify, this is the end */
12796 if (p->owner) {
12797 if (!p->refer) {
12798 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
12799 ast_queue_hangup(p->owner);
12800 } else if (option_debug > 3)
12801 ast_log(LOG_DEBUG, "Got OK on REFER Notify message\n");
12802 } else {
12803 if (p->subscribed == NONE)
12804 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12805 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
12806 /* Ready to send the next state we have on queue */
12807 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
12808 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
12811 } else if (sipmethod == SIP_REGISTER)
12812 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12813 else if (sipmethod == SIP_BYE) /* Ok, we're ready to go */
12814 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12815 break;
12816 case 202: /* Transfer accepted */
12817 if (sipmethod == SIP_REFER)
12818 handle_response_refer(p, resp, rest, req, seqno);
12819 break;
12820 case 401: /* Not www-authorized on SIP method */
12821 if (sipmethod == SIP_INVITE)
12822 handle_response_invite(p, resp, rest, req, seqno);
12823 else if (sipmethod == SIP_REFER)
12824 handle_response_refer(p, resp, rest, req, seqno);
12825 else if (p->registry && sipmethod == SIP_REGISTER)
12826 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12827 else if (sipmethod == SIP_BYE) {
12828 if (ast_strlen_zero(p->authname)) {
12829 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12830 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12831 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12832 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "WWW-Authenticate", "Authorization", sipmethod, 0)) {
12833 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
12834 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12835 /* We fail to auth bye on our own call, but still needs to tear down the call.
12836 Life, they call it. */
12838 } else {
12839 ast_log(LOG_WARNING, "Got authentication request (401) on unknown %s to '%s'\n", sip_methods[sipmethod].text, get_header(req, "To"));
12840 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12842 break;
12843 case 403: /* Forbidden - we failed authentication */
12844 if (sipmethod == SIP_INVITE)
12845 handle_response_invite(p, resp, rest, req, seqno);
12846 else if (p->registry && sipmethod == SIP_REGISTER)
12847 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12848 else {
12849 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
12850 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12852 break;
12853 case 404: /* Not found */
12854 if (p->registry && sipmethod == SIP_REGISTER)
12855 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12856 else if (sipmethod == SIP_INVITE)
12857 handle_response_invite(p, resp, rest, req, seqno);
12858 else if (owner)
12859 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12860 break;
12861 case 407: /* Proxy auth required */
12862 if (sipmethod == SIP_INVITE)
12863 handle_response_invite(p, resp, rest, req, seqno);
12864 else if (sipmethod == SIP_REFER)
12865 handle_response_refer(p, resp, rest, req, seqno);
12866 else if (p->registry && sipmethod == SIP_REGISTER)
12867 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12868 else if (sipmethod == SIP_BYE) {
12869 if (ast_strlen_zero(p->authname)) {
12870 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12871 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12872 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12873 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", sipmethod, 0)) {
12874 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
12875 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12877 } else /* We can't handle this, giving up in a bad way */
12878 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12880 break;
12881 case 408: /* Request timeout - terminate dialog */
12882 if (sipmethod == SIP_INVITE)
12883 handle_response_invite(p, resp, rest, req, seqno);
12884 else if (sipmethod == SIP_REGISTER)
12885 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12886 else if (sipmethod == SIP_BYE) {
12887 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12888 if (option_debug)
12889 ast_log(LOG_DEBUG, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
12890 } else {
12891 if (owner)
12892 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12893 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12895 break;
12896 case 481: /* Call leg does not exist */
12897 if (sipmethod == SIP_INVITE) {
12898 handle_response_invite(p, resp, rest, req, seqno);
12899 } else if (sipmethod == SIP_REFER) {
12900 handle_response_refer(p, resp, rest, req, seqno);
12901 } else if (sipmethod == SIP_BYE) {
12902 /* The other side has no transaction to bye,
12903 just assume it's all right then */
12904 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12905 } else if (sipmethod == SIP_CANCEL) {
12906 /* The other side has no transaction to cancel,
12907 just assume it's all right then */
12908 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12909 } else {
12910 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12911 /* Guessing that this is not an important request */
12913 break;
12914 case 487:
12915 if (sipmethod == SIP_INVITE)
12916 handle_response_invite(p, resp, rest, req, seqno);
12917 break;
12918 case 488: /* Not acceptable here - codec error */
12919 if (sipmethod == SIP_INVITE)
12920 handle_response_invite(p, resp, rest, req, seqno);
12921 break;
12922 case 491: /* Pending */
12923 if (sipmethod == SIP_INVITE)
12924 handle_response_invite(p, resp, rest, req, seqno);
12925 else {
12926 if (option_debug)
12927 ast_log(LOG_DEBUG, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
12928 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12930 break;
12931 case 501: /* Not Implemented */
12932 if (sipmethod == SIP_INVITE)
12933 handle_response_invite(p, resp, rest, req, seqno);
12934 else if (sipmethod == SIP_REFER)
12935 handle_response_refer(p, resp, rest, req, seqno);
12936 else
12937 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
12938 break;
12939 case 603: /* Declined transfer */
12940 if (sipmethod == SIP_REFER) {
12941 handle_response_refer(p, resp, rest, req, seqno);
12942 break;
12944 /* Fallthrough */
12945 default:
12946 if ((resp >= 300) && (resp < 700)) {
12947 /* Fatal response */
12948 if ((option_verbose > 2) && (resp != 487))
12949 ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
12951 if (sipmethod == SIP_INVITE)
12952 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
12954 /* XXX Locking issues?? XXX */
12955 switch(resp) {
12956 case 300: /* Multiple Choices */
12957 case 301: /* Moved permenantly */
12958 case 302: /* Moved temporarily */
12959 case 305: /* Use Proxy */
12960 parse_moved_contact(p, req);
12961 /* Fall through */
12962 case 486: /* Busy here */
12963 case 600: /* Busy everywhere */
12964 case 603: /* Decline */
12965 if (p->owner)
12966 ast_queue_control(p->owner, AST_CONTROL_BUSY);
12967 break;
12968 case 482: /*
12969 \note SIP is incapable of performing a hairpin call, which
12970 is yet another failure of not having a layer 2 (again, YAY
12971 IETF for thinking ahead). So we treat this as a call
12972 forward and hope we end up at the right place... */
12973 if (option_debug)
12974 ast_log(LOG_DEBUG, "Hairpin detected, setting up call forward for what it's worth\n");
12975 if (p->owner)
12976 ast_string_field_build(p->owner, call_forward,
12977 "Local/%s@%s", p->username, p->context);
12978 /* Fall through */
12979 case 480: /* Temporarily Unavailable */
12980 case 404: /* Not Found */
12981 case 410: /* Gone */
12982 case 400: /* Bad Request */
12983 case 500: /* Server error */
12984 if (sipmethod == SIP_REFER) {
12985 handle_response_refer(p, resp, rest, req, seqno);
12986 break;
12988 /* Fall through */
12989 case 502: /* Bad gateway */
12990 case 503: /* Service Unavailable */
12991 case 504: /* Server Timeout */
12992 if (owner)
12993 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12994 break;
12995 default:
12996 /* Send hangup */
12997 if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
12998 ast_queue_hangup(p->owner);
12999 break;
13001 /* ACK on invite */
13002 if (sipmethod == SIP_INVITE)
13003 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
13004 if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
13005 sip_alreadygone(p);
13006 if (!p->owner)
13007 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13008 } else if ((resp >= 100) && (resp < 200)) {
13009 if (sipmethod == SIP_INVITE) {
13010 if (!ast_test_flag(req, SIP_PKT_IGNORE) && sip_cancel_destroy(p))
13011 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13012 if (find_sdp(req))
13013 process_sdp(p, req);
13014 if (p->owner) {
13015 /* Queue a progress frame */
13016 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
13019 } else
13020 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));
13022 } else {
13023 /* Responses to OUTGOING SIP requests on INCOMING calls
13024 get handled here. As well as out-of-call message responses */
13025 if (ast_test_flag(req, SIP_PKT_DEBUG))
13026 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
13028 if (sipmethod == SIP_INVITE && resp == 200) {
13029 /* Tags in early session is replaced by the tag in 200 OK, which is
13030 the final reply to our INVITE */
13031 char tag[128];
13033 gettag(req, "To", tag, sizeof(tag));
13034 ast_string_field_set(p, theirtag, tag);
13037 switch(resp) {
13038 case 200:
13039 if (sipmethod == SIP_INVITE) {
13040 handle_response_invite(p, resp, rest, req, seqno);
13041 } else if (sipmethod == SIP_CANCEL) {
13042 if (option_debug)
13043 ast_log(LOG_DEBUG, "Got 200 OK on CANCEL\n");
13045 /* Wait for 487, then destroy */
13046 } else if (sipmethod == SIP_NOTIFY) {
13047 /* They got the notify, this is the end */
13048 if (p->owner) {
13049 if (p->refer) {
13050 if (option_debug)
13051 ast_log(LOG_DEBUG, "Got 200 OK on NOTIFY for transfer\n");
13052 } else
13053 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
13054 /* ast_queue_hangup(p->owner); Disabled */
13055 } else {
13056 if (!p->subscribed && !p->refer)
13057 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13058 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
13059 /* Ready to send the next state we have on queue */
13060 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
13061 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
13064 } else if (sipmethod == SIP_BYE)
13065 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13066 else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO)
13067 /* We successfully transmitted a message or
13068 a video update request in INFO */
13070 else if (sipmethod == SIP_BYE)
13071 /* Ok, we're ready to go */
13072 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13073 break;
13074 case 202: /* Transfer accepted */
13075 if (sipmethod == SIP_REFER)
13076 handle_response_refer(p, resp, rest, req, seqno);
13077 break;
13078 case 401: /* www-auth */
13079 case 407:
13080 if (sipmethod == SIP_REFER)
13081 handle_response_refer(p, resp, rest, req, seqno);
13082 else if (sipmethod == SIP_INVITE)
13083 handle_response_invite(p, resp, rest, req, seqno);
13084 else if (sipmethod == SIP_BYE) {
13085 char *auth, *auth2;
13087 auth = (resp == 407 ? "Proxy-Authenticate" : "WWW-Authenticate");
13088 auth2 = (resp == 407 ? "Proxy-Authorization" : "Authorization");
13089 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, auth, auth2, sipmethod, 0)) {
13090 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
13091 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13094 break;
13095 case 481: /* Call leg does not exist */
13096 if (sipmethod == SIP_INVITE) {
13097 /* Re-invite failed */
13098 handle_response_invite(p, resp, rest, req, seqno);
13099 } else if (sipmethod == SIP_BYE) {
13100 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13101 } else if (sipdebug) {
13102 ast_log (LOG_DEBUG, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
13104 break;
13105 case 501: /* Not Implemented */
13106 if (sipmethod == SIP_INVITE)
13107 handle_response_invite(p, resp, rest, req, seqno);
13108 else if (sipmethod == SIP_REFER)
13109 handle_response_refer(p, resp, rest, req, seqno);
13110 break;
13111 case 603: /* Declined transfer */
13112 if (sipmethod == SIP_REFER) {
13113 handle_response_refer(p, resp, rest, req, seqno);
13114 break;
13116 /* Fallthrough */
13117 default: /* Errors without handlers */
13118 if ((resp >= 100) && (resp < 200)) {
13119 if (sipmethod == SIP_INVITE) { /* re-invite */
13120 if (!ast_test_flag(req, SIP_PKT_IGNORE) && sip_cancel_destroy(p))
13121 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13124 if ((resp >= 300) && (resp < 700)) {
13125 if ((option_verbose > 2) && (resp != 487))
13126 ast_verbose(VERBOSE_PREFIX_3 "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
13127 switch(resp) {
13128 case 488: /* Not acceptable here - codec error */
13129 case 603: /* Decline */
13130 case 500: /* Server error */
13131 case 502: /* Bad gateway */
13132 case 503: /* Service Unavailable */
13133 case 504: /* Server timeout */
13135 /* re-invite failed */
13136 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
13137 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13138 break;
13141 break;
13147 /*! \brief Park SIP call support function
13148 Starts in a new thread, then parks the call
13149 XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
13150 audio can't be heard before hangup
13152 static void *sip_park_thread(void *stuff)
13154 struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
13155 struct sip_dual *d;
13156 struct sip_request req;
13157 int ext;
13158 int res;
13160 d = stuff;
13161 transferee = d->chan1;
13162 transferer = d->chan2;
13163 copy_request(&req, &d->req);
13164 free(d);
13166 if (!transferee || !transferer) {
13167 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
13168 return NULL;
13170 if (option_debug > 3)
13171 ast_log(LOG_DEBUG, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
13173 ast_channel_lock(transferee);
13174 if (ast_do_masquerade(transferee)) {
13175 ast_log(LOG_WARNING, "Masquerade failed.\n");
13176 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
13177 ast_channel_unlock(transferee);
13178 return NULL;
13180 ast_channel_unlock(transferee);
13182 res = ast_park_call(transferee, transferer, 0, &ext);
13185 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
13186 if (!res) {
13187 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
13188 } else {
13189 /* Then tell the transferer what happened */
13190 sprintf(buf, "Call parked on extension '%d'", ext);
13191 transmit_message_with_text(transferer->tech_pvt, buf);
13193 #endif
13195 /* Any way back to the current call??? */
13196 /* Transmit response to the REFER request */
13197 transmit_response(transferer->tech_pvt, "202 Accepted", &req);
13198 if (!res) {
13199 /* Transfer succeeded */
13200 append_history(transferer->tech_pvt, "SIPpark","Parked call on %d", ext);
13201 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
13202 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
13203 ast_hangup(transferer); /* This will cause a BYE */
13204 if (option_debug)
13205 ast_log(LOG_DEBUG, "SIP Call parked on extension '%d'\n", ext);
13206 } else {
13207 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
13208 append_history(transferer->tech_pvt, "SIPpark","Parking failed\n");
13209 if (option_debug)
13210 ast_log(LOG_DEBUG, "SIP Call parked failed \n");
13211 /* Do not hangup call */
13213 return NULL;
13216 /*! \brief Park a call using the subsystem in res_features.c
13217 This is executed in a separate thread
13219 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
13221 struct sip_dual *d;
13222 struct ast_channel *transferee, *transferer;
13223 /* Chan2m: The transferer, chan1m: The transferee */
13224 pthread_t th;
13226 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
13227 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
13228 if ((!transferer) || (!transferee)) {
13229 if (transferee) {
13230 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13231 ast_hangup(transferee);
13233 if (transferer) {
13234 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13235 ast_hangup(transferer);
13237 return -1;
13240 /* Make formats okay */
13241 transferee->readformat = chan1->readformat;
13242 transferee->writeformat = chan1->writeformat;
13244 /* Prepare for taking over the channel */
13245 ast_channel_masquerade(transferee, chan1);
13247 /* Setup the extensions and such */
13248 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
13249 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
13250 transferee->priority = chan1->priority;
13252 /* We make a clone of the peer channel too, so we can play
13253 back the announcement */
13255 /* Make formats okay */
13256 transferer->readformat = chan2->readformat;
13257 transferer->writeformat = chan2->writeformat;
13259 /* Prepare for taking over the channel. Go ahead and grab this channel
13260 * lock here to avoid a deadlock with callbacks into the channel driver
13261 * that hold the channel lock and want the pvt lock. */
13262 while (ast_channel_trylock(chan2)) {
13263 struct sip_pvt *pvt = chan2->tech_pvt;
13264 DEADLOCK_AVOIDANCE(&pvt->lock);
13266 ast_channel_masquerade(transferer, chan2);
13267 ast_channel_unlock(chan2);
13269 /* Setup the extensions and such */
13270 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
13271 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
13272 transferer->priority = chan2->priority;
13274 ast_channel_lock(transferer);
13275 if (ast_do_masquerade(transferer)) {
13276 ast_log(LOG_WARNING, "Masquerade failed :(\n");
13277 ast_channel_unlock(transferer);
13278 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13279 ast_hangup(transferer);
13280 return -1;
13282 ast_channel_unlock(transferer);
13283 if (!transferer || !transferee) {
13284 if (!transferer) {
13285 if (option_debug)
13286 ast_log(LOG_DEBUG, "No transferer channel, giving up parking\n");
13288 if (!transferee) {
13289 if (option_debug)
13290 ast_log(LOG_DEBUG, "No transferee channel, giving up parking\n");
13292 return -1;
13294 if ((d = ast_calloc(1, sizeof(*d)))) {
13295 pthread_attr_t attr;
13297 pthread_attr_init(&attr);
13298 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
13300 /* Save original request for followup */
13301 copy_request(&d->req, req);
13302 d->chan1 = transferee; /* Transferee */
13303 d->chan2 = transferer; /* Transferer */
13304 d->seqno = seqno;
13305 if (ast_pthread_create_background(&th, &attr, sip_park_thread, d) < 0) {
13306 /* Could not start thread */
13307 free(d); /* We don't need it anymore. If thread is created, d will be free'd
13308 by sip_park_thread() */
13309 pthread_attr_destroy(&attr);
13310 return 0;
13312 pthread_attr_destroy(&attr);
13314 return -1;
13317 /*! \brief Turn off generator data
13318 XXX Does this function belong in the SIP channel?
13320 static void ast_quiet_chan(struct ast_channel *chan)
13322 if (chan && chan->_state == AST_STATE_UP) {
13323 if (ast_test_flag(chan, AST_FLAG_MOH))
13324 ast_moh_stop(chan);
13325 else if (chan->generatordata)
13326 ast_deactivate_generator(chan);
13330 /*! \brief Attempt transfer of SIP call
13331 This fix for attended transfers on a local PBX */
13332 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
13334 int res = 0;
13335 struct ast_channel *peera = NULL,
13336 *peerb = NULL,
13337 *peerc = NULL,
13338 *peerd = NULL;
13341 /* We will try to connect the transferee with the target and hangup
13342 all channels to the transferer */
13343 if (option_debug > 3) {
13344 ast_log(LOG_DEBUG, "Sip transfer:--------------------\n");
13345 if (transferer->chan1)
13346 ast_log(LOG_DEBUG, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
13347 else
13348 ast_log(LOG_DEBUG, "-- No transferer first channel - odd??? \n");
13349 if (target->chan1)
13350 ast_log(LOG_DEBUG, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
13351 else
13352 ast_log(LOG_DEBUG, "-- No target first channel ---\n");
13353 if (transferer->chan2)
13354 ast_log(LOG_DEBUG, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
13355 else
13356 ast_log(LOG_DEBUG, "-- No bridged call to transferee\n");
13357 if (target->chan2)
13358 ast_log(LOG_DEBUG, "-- Bridged call to transfer target: %s State %s\n", target->chan2 ? target->chan2->name : "<none>", target->chan2 ? ast_state2str(target->chan2->_state) : "(none)");
13359 else
13360 ast_log(LOG_DEBUG, "-- No target second channel ---\n");
13361 ast_log(LOG_DEBUG, "-- END Sip transfer:--------------------\n");
13363 if (transferer->chan2) { /* We have a bridge on the transferer's channel */
13364 peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
13365 peerb = target->chan1; /* Transferer - PBX -> target channel - This will get lost in masq */
13366 peerc = transferer->chan2; /* Asterisk to Transferee */
13367 peerd = target->chan2; /* Asterisk to Target */
13368 if (option_debug > 2)
13369 ast_log(LOG_DEBUG, "SIP transfer: Four channels to handle\n");
13370 } else if (target->chan2) { /* Transferer has no bridge (IVR), but transferee */
13371 peera = target->chan1; /* Transferer to PBX -> target channel */
13372 peerb = transferer->chan1; /* Transferer to IVR*/
13373 peerc = target->chan2; /* Asterisk to Target */
13374 peerd = transferer->chan2; /* Nothing */
13375 if (option_debug > 2)
13376 ast_log(LOG_DEBUG, "SIP transfer: Three channels to handle\n");
13379 if (peera && peerb && peerc && (peerb != peerc)) {
13380 ast_quiet_chan(peera); /* Stop generators */
13381 ast_quiet_chan(peerb);
13382 ast_quiet_chan(peerc);
13383 if (peerd)
13384 ast_quiet_chan(peerd);
13386 /* Fix CDRs so they're attached to the remaining channel */
13387 if (peera->cdr && peerb->cdr)
13388 peerb->cdr = ast_cdr_append(peerb->cdr, peera->cdr);
13389 else if (peera->cdr)
13390 peerb->cdr = peera->cdr;
13391 peera->cdr = NULL;
13393 if (peerb->cdr && peerc->cdr)
13394 peerb->cdr = ast_cdr_append(peerb->cdr, peerc->cdr);
13395 else if (peerc->cdr)
13396 peerb->cdr = peerc->cdr;
13397 peerc->cdr = NULL;
13399 if (option_debug > 3)
13400 ast_log(LOG_DEBUG, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
13401 if (ast_channel_masquerade(peerb, peerc)) {
13402 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
13403 res = -1;
13404 } else
13405 ast_log(LOG_DEBUG, "SIP transfer: Succeeded to masquerade channels.\n");
13406 return res;
13407 } else {
13408 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
13409 if (transferer->chan1)
13410 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
13411 if (target->chan1)
13412 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
13413 return -2;
13415 return 0;
13418 /*! \brief Get tag from packet
13420 * \return Returns the pointer to the provided tag buffer,
13421 * or NULL if the tag was not found.
13423 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
13425 const char *thetag;
13427 if (!tagbuf)
13428 return NULL;
13429 tagbuf[0] = '\0'; /* reset the buffer */
13430 thetag = get_header(req, header);
13431 thetag = strcasestr(thetag, ";tag=");
13432 if (thetag) {
13433 thetag += 5;
13434 ast_copy_string(tagbuf, thetag, tagbufsize);
13435 return strsep(&tagbuf, ";");
13437 return NULL;
13440 /*! \brief Handle incoming notifications */
13441 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
13443 /* This is mostly a skeleton for future improvements */
13444 /* Mostly created to return proper answers on notifications on outbound REFER's */
13445 int res = 0;
13446 const char *event = get_header(req, "Event");
13447 char *eventid = NULL;
13448 char *sep;
13450 if( (sep = strchr(event, ';')) ) { /* XXX bug here - overwriting string ? */
13451 *sep++ = '\0';
13452 eventid = sep;
13455 if (option_debug > 1 && sipdebug)
13456 ast_log(LOG_DEBUG, "Got NOTIFY Event: %s\n", event);
13458 if (strcmp(event, "refer")) {
13459 /* We don't understand this event. */
13460 /* Here's room to implement incoming voicemail notifications :-) */
13461 transmit_response(p, "489 Bad event", req);
13462 res = -1;
13463 } else {
13464 /* Save nesting depth for now, since there might be other events we will
13465 support in the future */
13467 /* Handle REFER notifications */
13469 char buf[1024];
13470 char *cmd, *code;
13471 int respcode;
13472 int success = TRUE;
13474 /* EventID for each transfer... EventID is basically the REFER cseq
13476 We are getting notifications on a call that we transfered
13477 We should hangup when we are getting a 200 OK in a sipfrag
13478 Check if we have an owner of this event */
13480 /* Check the content type */
13481 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
13482 /* We need a sipfrag */
13483 transmit_response(p, "400 Bad request", req);
13484 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13485 return -1;
13488 /* Get the text of the attachment */
13489 if (get_msg_text(buf, sizeof(buf), req)) {
13490 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
13491 transmit_response(p, "400 Bad request", req);
13492 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13493 return -1;
13497 From the RFC...
13498 A minimal, but complete, implementation can respond with a single
13499 NOTIFY containing either the body:
13500 SIP/2.0 100 Trying
13502 if the subscription is pending, the body:
13503 SIP/2.0 200 OK
13504 if the reference was successful, the body:
13505 SIP/2.0 503 Service Unavailable
13506 if the reference failed, or the body:
13507 SIP/2.0 603 Declined
13509 if the REFER request was accepted before approval to follow the
13510 reference could be obtained and that approval was subsequently denied
13511 (see Section 2.4.7).
13513 If there are several REFERs in the same dialog, we need to
13514 match the ID of the event header...
13516 if (option_debug > 2)
13517 ast_log(LOG_DEBUG, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
13518 cmd = ast_skip_blanks(buf);
13519 code = cmd;
13520 /* We are at SIP/2.0 */
13521 while(*code && (*code > 32)) { /* Search white space */
13522 code++;
13524 *code++ = '\0';
13525 code = ast_skip_blanks(code);
13526 sep = code;
13527 sep++;
13528 while(*sep && (*sep > 32)) { /* Search white space */
13529 sep++;
13531 *sep++ = '\0'; /* Response string */
13532 respcode = atoi(code);
13533 switch (respcode) {
13534 case 100: /* Trying: */
13535 case 101: /* dialog establishment */
13536 /* Don't do anything yet */
13537 break;
13538 case 183: /* Ringing: */
13539 /* Don't do anything yet */
13540 break;
13541 case 200: /* OK: The new call is up, hangup this call */
13542 /* Hangup the call that we are replacing */
13543 break;
13544 case 301: /* Moved permenantly */
13545 case 302: /* Moved temporarily */
13546 /* Do we get the header in the packet in this case? */
13547 success = FALSE;
13548 break;
13549 case 503: /* Service Unavailable: The new call failed */
13550 /* Cancel transfer, continue the call */
13551 success = FALSE;
13552 break;
13553 case 603: /* Declined: Not accepted */
13554 /* Cancel transfer, continue the current call */
13555 success = FALSE;
13556 break;
13558 if (!success) {
13559 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
13562 /* Confirm that we received this packet */
13563 transmit_response(p, "200 OK", req);
13566 if (!p->lastinvite)
13567 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13569 return res;
13572 /*! \brief Handle incoming OPTIONS request */
13573 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
13575 int res;
13577 res = get_destination(p, req);
13578 build_contact(p);
13580 /* XXX Should we authenticate OPTIONS? XXX */
13582 if (ast_strlen_zero(p->context))
13583 ast_string_field_set(p, context, default_context);
13585 if (ast_shutting_down())
13586 transmit_response_with_allow(p, "503 Unavailable", req, 0);
13587 else if (res < 0)
13588 transmit_response_with_allow(p, "404 Not Found", req, 0);
13589 else
13590 transmit_response_with_allow(p, "200 OK", req, 0);
13592 /* Destroy if this OPTIONS was the opening request, but not if
13593 it's in the middle of a normal call flow. */
13594 if (!p->lastinvite)
13595 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13597 return res;
13600 /*! \brief Handle the transfer part of INVITE with a replaces: header,
13601 meaning a target pickup or an attended transfer */
13602 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin)
13604 struct ast_frame *f;
13605 int earlyreplace = 0;
13606 int oneleggedreplace = 0; /* Call with no bridge, propably IVR or voice message */
13607 struct ast_channel *c = p->owner; /* Our incoming call */
13608 struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
13609 struct ast_channel *targetcall; /* The bridge to the take-over target */
13611 /* Check if we're in ring state */
13612 if (replacecall->_state == AST_STATE_RING)
13613 earlyreplace = 1;
13615 /* Check if we have a bridge */
13616 if (!(targetcall = ast_bridged_channel(replacecall))) {
13617 /* We have no bridge */
13618 if (!earlyreplace) {
13619 if (option_debug > 1)
13620 ast_log(LOG_DEBUG, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
13621 oneleggedreplace = 1;
13624 if (option_debug > 3 && targetcall && targetcall->_state == AST_STATE_RINGING)
13625 ast_log(LOG_DEBUG, "SIP transfer: Target channel is in ringing state\n");
13627 if (option_debug > 3) {
13628 if (targetcall)
13629 ast_log(LOG_DEBUG, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
13630 else
13631 ast_log(LOG_DEBUG, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
13634 if (ignore) {
13635 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
13636 /* We should answer something here. If we are here, the
13637 call we are replacing exists, so an accepted
13638 can't harm */
13639 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
13640 /* Do something more clever here */
13641 ast_channel_unlock(c);
13642 ast_mutex_unlock(&p->refer->refer_call->lock);
13643 return 1;
13645 if (!c) {
13646 /* What to do if no channel ??? */
13647 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
13648 transmit_response_reliable(p, "503 Service Unavailable", req);
13649 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
13650 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13651 ast_mutex_unlock(&p->refer->refer_call->lock);
13652 return 1;
13654 append_history(p, "Xfer", "INVITE/Replace received");
13655 /* We have three channels to play with
13656 channel c: New incoming call
13657 targetcall: Call from PBX to target
13658 p->refer->refer_call: SIP pvt dialog from transferer to pbx.
13659 replacecall: The owner of the previous
13660 We need to masq C into refer_call to connect to
13661 targetcall;
13662 If we are talking to internal audio stream, target call is null.
13665 /* Fake call progress */
13666 transmit_response(p, "100 Trying", req);
13667 ast_setstate(c, AST_STATE_RING);
13669 /* Masquerade the new call into the referred call to connect to target call
13670 Targetcall is not touched by the masq */
13672 /* Answer the incoming call and set channel to UP state */
13673 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
13675 ast_setstate(c, AST_STATE_UP);
13677 /* Stop music on hold and other generators */
13678 ast_quiet_chan(replacecall);
13679 ast_quiet_chan(targetcall);
13680 if (option_debug > 3)
13681 ast_log(LOG_DEBUG, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
13682 /* Unlock clone, but not original (replacecall) */
13683 if (!oneleggedreplace)
13684 ast_channel_unlock(c);
13686 /* Unlock PVT */
13687 ast_mutex_unlock(&p->refer->refer_call->lock);
13689 /* Make sure that the masq does not free our PVT for the old call */
13690 if (! earlyreplace && ! oneleggedreplace )
13691 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
13693 /* Prepare the masquerade - if this does not happen, we will be gone */
13694 if(ast_channel_masquerade(replacecall, c))
13695 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
13696 else if (option_debug > 3)
13697 ast_log(LOG_DEBUG, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
13699 /* The masquerade will happen as soon as someone reads a frame from the channel */
13701 /* C should now be in place of replacecall */
13702 /* ast_read needs to lock channel */
13703 ast_channel_unlock(c);
13705 if (earlyreplace || oneleggedreplace ) {
13706 /* Force the masq to happen */
13707 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
13708 ast_frfree(f);
13709 f = NULL;
13710 if (option_debug > 3)
13711 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from RING channel!\n");
13712 } else {
13713 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from RING channel \n");
13715 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13716 if (!oneleggedreplace)
13717 ast_channel_unlock(replacecall);
13718 } else { /* Bridged call, UP channel */
13719 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
13720 /* Masq ok */
13721 ast_frfree(f);
13722 f = NULL;
13723 if (option_debug > 2)
13724 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from channel! Masq done.\n");
13725 } else {
13726 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from channel. Transfer failed\n");
13728 ast_channel_unlock(replacecall);
13730 ast_mutex_unlock(&p->refer->refer_call->lock);
13732 ast_setstate(c, AST_STATE_DOWN);
13733 if (option_debug > 3) {
13734 struct ast_channel *test;
13735 ast_log(LOG_DEBUG, "After transfer:----------------------------\n");
13736 ast_log(LOG_DEBUG, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
13737 if (replacecall)
13738 ast_log(LOG_DEBUG, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
13739 if (p->owner) {
13740 ast_log(LOG_DEBUG, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
13741 test = ast_bridged_channel(p->owner);
13742 if (test)
13743 ast_log(LOG_DEBUG, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
13744 else
13745 ast_log(LOG_DEBUG, " -- No call bridged to C->owner \n");
13746 } else
13747 ast_log(LOG_DEBUG, " -- No channel yet \n");
13748 ast_log(LOG_DEBUG, "End After transfer:----------------------------\n");
13751 ast_channel_unlock(p->owner); /* Unlock new owner */
13752 if (!oneleggedreplace)
13753 ast_mutex_unlock(&p->lock); /* Unlock SIP structure */
13755 /* The call should be down with no ast_channel, so hang it up */
13756 c->tech_pvt = NULL;
13757 ast_hangup(c);
13758 return 0;
13762 /*! \brief Handle incoming INVITE request
13763 \note If the INVITE has a Replaces header, it is part of an
13764 * attended transfer. If so, we do not go through the dial
13765 * plan but tries to find the active call and masquerade
13766 * into it
13768 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)
13770 int res = 1;
13771 int gotdest;
13772 const char *p_replaces;
13773 char *replace_id = NULL;
13774 const char *required;
13775 unsigned int required_profile = 0;
13776 struct ast_channel *c = NULL; /* New channel */
13777 int reinvite = 0;
13779 /* Find out what they support */
13780 if (!p->sipoptions) {
13781 const char *supported = get_header(req, "Supported");
13782 if (!ast_strlen_zero(supported))
13783 parse_sip_options(p, supported);
13786 /* Find out what they require */
13787 required = get_header(req, "Require");
13788 if (!ast_strlen_zero(required)) {
13789 required_profile = parse_sip_options(NULL, required);
13790 if (required_profile && required_profile != SIP_OPT_REPLACES) {
13791 /* At this point we only support REPLACES */
13792 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
13793 ast_log(LOG_WARNING,"Received SIP INVITE with unsupported required extension: %s\n", required);
13794 p->invitestate = INV_COMPLETED;
13795 if (!p->lastinvite)
13796 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13797 return -1;
13801 /* Check if this is a loop */
13802 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->owner->_state != AST_STATE_UP)) {
13803 /* This is a call to ourself. Send ourselves an error code and stop
13804 processing immediately, as SIP really has no good mechanism for
13805 being able to call yourself */
13806 /* If pedantic is on, we need to check the tags. If they're different, this is
13807 in fact a forked call through a SIP proxy somewhere. */
13808 transmit_response(p, "482 Loop Detected", req);
13809 p->invitestate = INV_COMPLETED;
13810 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13811 return 0;
13814 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->pendinginvite) {
13815 /* We already have a pending invite. Sorry. You are on hold. */
13816 transmit_response(p, "491 Request Pending", req);
13817 if (option_debug)
13818 ast_log(LOG_DEBUG, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
13819 /* Don't destroy dialog here */
13820 return 0;
13823 p_replaces = get_header(req, "Replaces");
13824 if (!ast_strlen_zero(p_replaces)) {
13825 /* We have a replaces header */
13826 char *ptr;
13827 char *fromtag = NULL;
13828 char *totag = NULL;
13829 char *start, *to;
13830 int error = 0;
13832 if (p->owner) {
13833 if (option_debug > 2)
13834 ast_log(LOG_DEBUG, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
13835 transmit_response(p, "400 Bad request", req); /* The best way to not not accept the transfer */
13836 /* Do not destroy existing call */
13837 return -1;
13840 if (sipdebug && option_debug > 2)
13841 ast_log(LOG_DEBUG, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
13842 /* Create a buffer we can manipulate */
13843 replace_id = ast_strdupa(p_replaces);
13844 ast_uri_decode(replace_id);
13846 if (!p->refer && !sip_refer_allocate(p)) {
13847 transmit_response(p, "500 Server Internal Error", req);
13848 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
13849 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13850 p->invitestate = INV_COMPLETED;
13851 return -1;
13854 /* Todo: (When we find phones that support this)
13855 if the replaces header contains ";early-only"
13856 we can only replace the call in early
13857 stage, not after it's up.
13859 If it's not in early mode, 486 Busy.
13862 /* Skip leading whitespace */
13863 replace_id = ast_skip_blanks(replace_id);
13865 start = replace_id;
13866 while ( (ptr = strsep(&start, ";")) ) {
13867 ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
13868 if ( (to = strcasestr(ptr, "to-tag=") ) )
13869 totag = to + 7; /* skip the keyword */
13870 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
13871 fromtag = to + 9; /* skip the keyword */
13872 fromtag = strsep(&fromtag, "&"); /* trim what ? */
13876 if (sipdebug && option_debug > 3)
13877 ast_log(LOG_DEBUG,"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>");
13880 /* Try to find call that we are replacing
13881 If we have a Replaces header, we need to cancel that call if we succeed with this call
13883 if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
13884 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
13885 transmit_response(p, "481 Call Leg Does Not Exist (Replaces)", req);
13886 error = 1;
13889 /* At this point, bot the pvt and the owner of the call to be replaced is locked */
13891 /* The matched call is the call from the transferer to Asterisk .
13892 We want to bridge the bridged part of the call to the
13893 incoming invite, thus taking over the refered call */
13895 if (p->refer->refer_call == p) {
13896 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
13897 p->refer->refer_call = NULL;
13898 transmit_response(p, "400 Bad request", req); /* The best way to not not accept the transfer */
13899 error = 1;
13902 if (!error && !p->refer->refer_call->owner) {
13903 /* Oops, someting wrong anyway, no owner, no call */
13904 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
13905 /* Check for better return code */
13906 transmit_response(p, "481 Call Leg Does Not Exist (Replace)", req);
13907 error = 1;
13910 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 ) {
13911 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
13912 transmit_response(p, "603 Declined (Replaces)", req);
13913 error = 1;
13916 if (error) { /* Give up this dialog */
13917 append_history(p, "Xfer", "INVITE/Replace Failed.");
13918 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13919 ast_mutex_unlock(&p->lock);
13920 if (p->refer->refer_call) {
13921 ast_mutex_unlock(&p->refer->refer_call->lock);
13922 ast_channel_unlock(p->refer->refer_call->owner);
13924 p->invitestate = INV_COMPLETED;
13925 return -1;
13930 /* Check if this is an INVITE that sets up a new dialog or
13931 a re-invite in an existing dialog */
13933 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
13934 int newcall = (p->initreq.headers ? TRUE : FALSE);
13936 if (sip_cancel_destroy(p))
13937 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13938 /* This also counts as a pending invite */
13939 p->pendinginvite = seqno;
13940 check_via(p, req);
13942 copy_request(&p->initreq, req); /* Save this INVITE as the transaction basis */
13943 if (!p->owner) { /* Not a re-invite */
13944 if (debug)
13945 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
13946 if (newcall)
13947 append_history(p, "Invite", "New call: %s", p->callid);
13948 parse_ok_contact(p, req);
13949 } else { /* Re-invite on existing call */
13950 ast_clear_flag(&p->flags[0], SIP_OUTGOING); /* This is now an inbound dialog */
13951 /* Handle SDP here if we already have an owner */
13952 if (find_sdp(req)) {
13953 if (process_sdp(p, req)) {
13954 transmit_response(p, "488 Not acceptable here", req);
13955 if (!p->lastinvite)
13956 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13957 return -1;
13959 } else {
13960 p->jointcapability = p->capability;
13961 if (option_debug > 2)
13962 ast_log(LOG_DEBUG, "Hm.... No sdp for the moment\n");
13963 /* Some devices signal they want to be put off hold by sending a re-invite
13964 *without* an SDP, which is supposed to mean "Go back to your state"
13965 and since they put os on remote hold, we go back to off hold */
13966 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
13967 change_hold_state(p, req, FALSE, 0);
13969 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) /* This is a response, note what it was for */
13970 append_history(p, "ReInv", "Re-invite received");
13972 } else if (debug)
13973 ast_verbose("Ignoring this INVITE request\n");
13976 if (!p->lastinvite && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner) {
13977 /* This is a new invite */
13978 /* Handle authentication if this is our first invite */
13979 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
13980 if (res == AUTH_CHALLENGE_SENT) {
13981 p->invitestate = INV_COMPLETED; /* Needs to restart in another INVITE transaction */
13982 return 0;
13984 if (res < 0) { /* Something failed in authentication */
13985 if (res == AUTH_FAKE_AUTH) {
13986 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
13987 transmit_fake_auth_response(p, req, 1);
13988 } else {
13989 ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
13990 transmit_response_reliable(p, "403 Forbidden", req);
13992 p->invitestate = INV_COMPLETED;
13993 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13994 ast_string_field_free(p, theirtag);
13995 return 0;
13998 /* We have a succesful authentication, process the SDP portion if there is one */
13999 if (find_sdp(req)) {
14000 if (process_sdp(p, req)) {
14001 /* Unacceptable codecs */
14002 transmit_response_reliable(p, "488 Not acceptable here", req);
14003 p->invitestate = INV_COMPLETED;
14004 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14005 if (option_debug)
14006 ast_log(LOG_DEBUG, "No compatible codecs for this SIP call.\n");
14007 return -1;
14009 } else { /* No SDP in invite, call control session */
14010 p->jointcapability = p->capability;
14011 if (option_debug > 1)
14012 ast_log(LOG_DEBUG, "No SDP in Invite, third party call control\n");
14015 /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
14016 /* This seems redundant ... see !p-owner above */
14017 if (p->owner)
14018 ast_queue_frame(p->owner, &ast_null_frame);
14021 /* Initialize the context if it hasn't been already */
14022 if (ast_strlen_zero(p->context))
14023 ast_string_field_set(p, context, default_context);
14026 /* Check number of concurrent calls -vs- incoming limit HERE */
14027 if (option_debug)
14028 ast_log(LOG_DEBUG, "Checking SIP call limits for device %s\n", p->username);
14029 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
14030 if (res < 0) {
14031 ast_log(LOG_NOTICE, "Failed to place call for user %s, too many calls\n", p->username);
14032 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
14033 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14034 p->invitestate = INV_COMPLETED;
14036 return 0;
14038 gotdest = get_destination(p, NULL); /* Get destination right away */
14039 get_rdnis(p, NULL); /* Get redirect information */
14040 extract_uri(p, req); /* Get the Contact URI */
14041 build_contact(p); /* Build our contact header */
14043 if (p->rtp) {
14044 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
14045 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
14048 if (!replace_id && gotdest) { /* No matching extension found */
14049 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
14050 transmit_response_reliable(p, "484 Address Incomplete", req);
14051 else {
14052 transmit_response_reliable(p, "404 Not Found", req);
14053 ast_log(LOG_NOTICE, "Call from '%s' to extension"
14054 " '%s' rejected because extension not found.\n",
14055 S_OR(p->username, p->peername), p->exten);
14057 p->invitestate = INV_COMPLETED;
14058 update_call_counter(p, DEC_CALL_LIMIT);
14059 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14060 return 0;
14061 } else {
14062 /* If no extension was specified, use the s one */
14063 /* Basically for calling to IP/Host name only */
14064 if (ast_strlen_zero(p->exten))
14065 ast_string_field_set(p, exten, "s");
14066 /* Initialize our tag */
14068 make_our_tag(p->tag, sizeof(p->tag));
14069 /* First invitation - create the channel */
14070 c = sip_new(p, AST_STATE_DOWN, S_OR(p->username, NULL));
14071 *recount = 1;
14073 /* Save Record-Route for any later requests we make on this dialogue */
14074 build_route(p, req, 0);
14076 if (c) {
14077 /* Pre-lock the call */
14078 ast_channel_lock(c);
14081 } else {
14082 if (option_debug > 1 && sipdebug) {
14083 if (!ast_test_flag(req, SIP_PKT_IGNORE))
14084 ast_log(LOG_DEBUG, "Got a SIP re-invite for call %s\n", p->callid);
14085 else
14086 ast_log(LOG_DEBUG, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
14088 reinvite = 1;
14089 c = p->owner;
14092 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
14093 p->lastinvite = seqno;
14095 if (replace_id) { /* Attended transfer or call pickup - we're the target */
14096 /* Go and take over the target call */
14097 if (sipdebug && option_debug > 3)
14098 ast_log(LOG_DEBUG, "Sending this call to the invite/replcaes handler %s\n", p->callid);
14099 return handle_invite_replaces(p, req, debug, ast_test_flag(req, SIP_PKT_IGNORE), seqno, sin);
14103 if (c) { /* We have a call -either a new call or an old one (RE-INVITE) */
14104 switch(c->_state) {
14105 case AST_STATE_DOWN:
14106 if (option_debug > 1)
14107 ast_log(LOG_DEBUG, "%s: New call is still down.... Trying... \n", c->name);
14108 transmit_response(p, "100 Trying", req);
14109 p->invitestate = INV_PROCEEDING;
14110 ast_setstate(c, AST_STATE_RING);
14111 if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
14112 enum ast_pbx_result res;
14114 res = ast_pbx_start(c);
14116 switch(res) {
14117 case AST_PBX_FAILED:
14118 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
14119 p->invitestate = INV_COMPLETED;
14120 if (ast_test_flag(req, SIP_PKT_IGNORE))
14121 transmit_response(p, "503 Unavailable", req);
14122 else
14123 transmit_response_reliable(p, "503 Unavailable", req);
14124 break;
14125 case AST_PBX_CALL_LIMIT:
14126 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
14127 p->invitestate = INV_COMPLETED;
14128 if (ast_test_flag(req, SIP_PKT_IGNORE))
14129 transmit_response(p, "480 Temporarily Unavailable", req);
14130 else
14131 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
14132 break;
14133 case AST_PBX_SUCCESS:
14134 /* nothing to do */
14135 break;
14138 if (res) {
14140 /* Unlock locks so ast_hangup can do its magic */
14141 ast_mutex_unlock(&c->lock);
14142 ast_mutex_unlock(&p->lock);
14143 ast_hangup(c);
14144 ast_mutex_lock(&p->lock);
14145 c = NULL;
14147 } else { /* Pickup call in call group */
14148 ast_channel_unlock(c);
14149 *nounlock = 1;
14150 if (ast_pickup_call(c)) {
14151 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
14152 if (ast_test_flag(req, SIP_PKT_IGNORE))
14153 transmit_response(p, "503 Unavailable", req); /* OEJ - Right answer? */
14154 else
14155 transmit_response_reliable(p, "503 Unavailable", req);
14156 sip_alreadygone(p);
14157 /* Unlock locks so ast_hangup can do its magic */
14158 ast_mutex_unlock(&p->lock);
14159 c->hangupcause = AST_CAUSE_CALL_REJECTED;
14160 } else {
14161 ast_mutex_unlock(&p->lock);
14162 ast_setstate(c, AST_STATE_DOWN);
14163 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
14165 p->invitestate = INV_COMPLETED;
14166 ast_hangup(c);
14167 ast_mutex_lock(&p->lock);
14168 c = NULL;
14170 break;
14171 case AST_STATE_RING:
14172 transmit_response(p, "100 Trying", req);
14173 p->invitestate = INV_PROCEEDING;
14174 break;
14175 case AST_STATE_RINGING:
14176 transmit_response(p, "180 Ringing", req);
14177 p->invitestate = INV_PROCEEDING;
14178 break;
14179 case AST_STATE_UP:
14180 if (option_debug > 1)
14181 ast_log(LOG_DEBUG, "%s: This call is UP.... \n", c->name);
14183 transmit_response(p, "100 Trying", req);
14185 if (p->t38.state == T38_PEER_REINVITE) {
14186 struct ast_channel *bridgepeer = NULL;
14187 struct sip_pvt *bridgepvt = NULL;
14189 if ((bridgepeer = ast_bridged_channel(p->owner))) {
14190 /* 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*/
14191 /*! XXX: we should also check here does the other side supports t38 at all !!! XXX */
14192 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
14193 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
14194 if (bridgepvt->t38.state == T38_DISABLED) {
14195 if (bridgepvt->udptl) { /* If everything is OK with other side's udptl struct */
14196 /* Send re-invite to the bridged channel */
14197 sip_handle_t38_reinvite(bridgepeer, p, 1);
14198 } else { /* Something is wrong with peers udptl struct */
14199 ast_log(LOG_WARNING, "Strange... The other side of the bridge don't have udptl struct\n");
14200 ast_mutex_lock(&bridgepvt->lock);
14201 bridgepvt->t38.state = T38_DISABLED;
14202 ast_mutex_unlock(&bridgepvt->lock);
14203 if (option_debug > 1)
14204 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->name);
14205 if (ast_test_flag(req, SIP_PKT_IGNORE))
14206 transmit_response(p, "488 Not acceptable here", req);
14207 else
14208 transmit_response_reliable(p, "488 Not acceptable here", req);
14211 } else {
14212 /* The other side is already setup for T.38 most likely so we need to acknowledge this too */
14213 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
14214 p->t38.state = T38_ENABLED;
14215 if (option_debug)
14216 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14218 } else {
14219 /* Other side is not a SIP channel */
14220 if (ast_test_flag(req, SIP_PKT_IGNORE))
14221 transmit_response(p, "488 Not acceptable here", req);
14222 else
14223 transmit_response_reliable(p, "488 Not acceptable here", req);
14224 p->t38.state = T38_DISABLED;
14225 if (option_debug > 1)
14226 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14228 if (!p->lastinvite) /* Only destroy if this is *not* a re-invite */
14229 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14231 } else {
14232 /* we are not bridged in a call */
14233 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
14234 p->t38.state = T38_ENABLED;
14235 if (option_debug)
14236 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14238 } else if (p->t38.state == T38_DISABLED) { /* Channel doesn't have T38 offered or enabled */
14239 int sendok = TRUE;
14241 /* If we are bridged to a channel that has T38 enabled than this is a case of RTP re-invite after T38 session */
14242 /* so handle it here (re-invite other party to RTP) */
14243 struct ast_channel *bridgepeer = NULL;
14244 struct sip_pvt *bridgepvt = NULL;
14245 if ((bridgepeer = ast_bridged_channel(p->owner))) {
14246 if ((bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) && !ast_check_hangup(bridgepeer)) {
14247 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
14248 /* Does the bridged peer have T38 ? */
14249 if (bridgepvt->t38.state == T38_ENABLED) {
14250 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
14251 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
14252 if (ast_test_flag(req, SIP_PKT_IGNORE))
14253 transmit_response(p, "488 Not Acceptable Here (unsupported)", req);
14254 else
14255 transmit_response_reliable(p, "488 Not Acceptable Here (unsupported)", req);
14256 sendok = FALSE;
14258 /* No bridged peer with T38 enabled*/
14261 /* Respond to normal re-invite */
14262 if (sendok)
14263 /* If this is not a re-invite or something to ignore - it's critical */
14264 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (ast_test_flag(req, SIP_PKT_IGNORE) ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
14266 p->invitestate = INV_TERMINATED;
14267 break;
14268 default:
14269 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
14270 transmit_response(p, "100 Trying", req);
14271 break;
14273 } else {
14274 if (p && (p->autokillid == -1)) {
14275 const char *msg;
14277 if (!p->jointcapability)
14278 msg = "488 Not Acceptable Here (codec error)";
14279 else {
14280 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
14281 msg = "503 Unavailable";
14283 if (ast_test_flag(req, SIP_PKT_IGNORE))
14284 transmit_response(p, msg, req);
14285 else
14286 transmit_response_reliable(p, msg, req);
14287 p->invitestate = INV_COMPLETED;
14288 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14291 return res;
14294 /*! \brief Find all call legs and bridge transferee with target
14295 * called from handle_request_refer */
14296 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
14298 struct sip_dual target; /* Chan 1: Call from tranferer to Asterisk */
14299 /* Chan 2: Call from Asterisk to target */
14300 int res = 0;
14301 struct sip_pvt *targetcall_pvt;
14303 /* Check if the call ID of the replaces header does exist locally */
14304 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
14305 transferer->refer->replaces_callid_fromtag))) {
14306 if (transferer->refer->localtransfer) {
14307 /* We did not find the refered call. Sorry, can't accept then */
14308 transmit_response(transferer, "202 Accepted", req);
14309 /* Let's fake a response from someone else in order
14310 to follow the standard */
14311 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
14312 append_history(transferer, "Xfer", "Refer failed");
14313 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
14314 transferer->refer->status = REFER_FAILED;
14315 return -1;
14317 /* Fall through for remote transfers that we did not find locally */
14318 if (option_debug > 2)
14319 ast_log(LOG_DEBUG, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
14320 return 0;
14323 /* Ok, we can accept this transfer */
14324 transmit_response(transferer, "202 Accepted", req);
14325 append_history(transferer, "Xfer", "Refer accepted");
14326 if (!targetcall_pvt->owner) { /* No active channel */
14327 if (option_debug > 3)
14328 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No owner of target call\n");
14329 /* Cancel transfer */
14330 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
14331 append_history(transferer, "Xfer", "Refer failed");
14332 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
14333 transferer->refer->status = REFER_FAILED;
14334 ast_mutex_unlock(&targetcall_pvt->lock);
14335 ast_channel_unlock(current->chan1);
14336 return -1;
14339 /* We have a channel, find the bridge */
14340 target.chan1 = targetcall_pvt->owner; /* Transferer to Asterisk */
14341 target.chan2 = ast_bridged_channel(targetcall_pvt->owner); /* Asterisk to target */
14343 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
14344 /* Wrong state of new channel */
14345 if (option_debug > 3) {
14346 if (target.chan2)
14347 ast_log(LOG_DEBUG, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
14348 else if (target.chan1->_state != AST_STATE_RING)
14349 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No target channel\n");
14350 else
14351 ast_log(LOG_DEBUG, "SIP attended transfer: Attempting transfer in ringing state\n");
14355 /* Transfer */
14356 if (option_debug > 3 && sipdebug) {
14357 if (current->chan2) /* We have two bridges */
14358 ast_log(LOG_DEBUG, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
14359 else /* One bridge, propably transfer of IVR/voicemail etc */
14360 ast_log(LOG_DEBUG, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
14363 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
14365 /* Perform the transfer */
14366 res = attempt_transfer(current, &target);
14367 ast_mutex_unlock(&targetcall_pvt->lock);
14368 if (res) {
14369 /* Failed transfer */
14370 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
14371 append_history(transferer, "Xfer", "Refer failed");
14372 transferer->refer->status = REFER_FAILED;
14373 if (targetcall_pvt->owner)
14374 ast_channel_unlock(targetcall_pvt->owner);
14375 /* Right now, we have to hangup, sorry. Bridge is destroyed */
14376 if (res != -2)
14377 ast_hangup(transferer->owner);
14378 else
14379 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
14380 } else {
14381 /* Transfer succeeded! */
14383 /* Tell transferer that we're done. */
14384 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
14385 append_history(transferer, "Xfer", "Refer succeeded");
14386 transferer->refer->status = REFER_200OK;
14387 if (targetcall_pvt->owner) {
14388 if (option_debug)
14389 ast_log(LOG_DEBUG, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
14390 ast_channel_unlock(targetcall_pvt->owner);
14393 return 1;
14397 /*! \brief Handle incoming REFER request */
14398 /*! \page SIP_REFER SIP transfer Support (REFER)
14400 REFER is used for call transfer in SIP. We get a REFER
14401 to place a new call with an INVITE somwhere and then
14402 keep the transferor up-to-date of the transfer. If the
14403 transfer fails, get back on line with the orginal call.
14405 - REFER can be sent outside or inside of a dialog.
14406 Asterisk only accepts REFER inside of a dialog.
14408 - If we get a replaces header, it is an attended transfer
14410 \par Blind transfers
14411 The transferor provides the transferee
14412 with the transfer targets contact. The signalling between
14413 transferer or transferee should not be cancelled, so the
14414 call is recoverable if the transfer target can not be reached
14415 by the transferee.
14417 In this case, Asterisk receives a TRANSFER from
14418 the transferor, thus is the transferee. We should
14419 try to set up a call to the contact provided
14420 and if that fails, re-connect the current session.
14421 If the new call is set up, we issue a hangup.
14422 In this scenario, we are following section 5.2
14423 in the SIP CC Transfer draft. (Transfer without
14424 a GRUU)
14426 \par Transfer with consultation hold
14427 In this case, the transferor
14428 talks to the transfer target before the transfer takes place.
14429 This is implemented with SIP hold and transfer.
14430 Note: The invite From: string could indicate a transfer.
14431 (Section 6. Transfer with consultation hold)
14432 The transferor places the transferee on hold, starts a call
14433 with the transfer target to alert them to the impending
14434 transfer, terminates the connection with the target, then
14435 proceeds with the transfer (as in Blind transfer above)
14437 \par Attended transfer
14438 The transferor places the transferee
14439 on hold, calls the transfer target to alert them,
14440 places the target on hold, then proceeds with the transfer
14441 using a Replaces header field in the Refer-to header. This
14442 will force the transfee to send an Invite to the target,
14443 with a replaces header that instructs the target to
14444 hangup the call between the transferor and the target.
14445 In this case, the Refer/to: uses the AOR address. (The same
14446 URI that the transferee used to establish the session with
14447 the transfer target (To: ). The Require: replaces header should
14448 be in the INVITE to avoid the wrong UA in a forked SIP proxy
14449 scenario to answer and have no call to replace with.
14451 The referred-by header is *NOT* required, but if we get it,
14452 can be copied into the INVITE to the transfer target to
14453 inform the target about the transferor
14455 "Any REFER request has to be appropriately authenticated.".
14457 We can't destroy dialogs, since we want the call to continue.
14460 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock)
14462 struct sip_dual current; /* Chan1: Call between asterisk and transferer */
14463 /* Chan2: Call between asterisk and transferee */
14465 int res = 0;
14467 if (ast_test_flag(req, SIP_PKT_DEBUG))
14468 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");
14470 if (!p->owner) {
14471 /* This is a REFER outside of an existing SIP dialog */
14472 /* We can't handle that, so decline it */
14473 if (option_debug > 2)
14474 ast_log(LOG_DEBUG, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
14475 transmit_response(p, "603 Declined (No dialog)", req);
14476 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
14477 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
14478 sip_alreadygone(p);
14479 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14481 return 0;
14485 /* Check if transfer is allowed from this device */
14486 if (p->allowtransfer == TRANSFER_CLOSED ) {
14487 /* Transfer not allowed, decline */
14488 transmit_response(p, "603 Declined (policy)", req);
14489 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
14490 /* Do not destroy SIP session */
14491 return 0;
14494 if(!ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
14495 /* Already have a pending REFER */
14496 transmit_response(p, "491 Request pending", req);
14497 append_history(p, "Xfer", "Refer failed. Request pending.");
14498 return 0;
14501 /* Allocate memory for call transfer data */
14502 if (!p->refer && !sip_refer_allocate(p)) {
14503 transmit_response(p, "500 Internal Server Error", req);
14504 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
14505 return -3;
14508 res = get_refer_info(p, req); /* Extract headers */
14510 p->refer->status = REFER_SENT;
14512 if (res != 0) {
14513 switch (res) {
14514 case -2: /* Syntax error */
14515 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
14516 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
14517 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14518 ast_log(LOG_DEBUG, "SIP transfer to black hole can't be handled (no refer-to: )\n");
14519 break;
14520 case -3:
14521 transmit_response(p, "603 Declined (Non sip: uri)", req);
14522 append_history(p, "Xfer", "Refer failed. Non SIP uri");
14523 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14524 ast_log(LOG_DEBUG, "SIP transfer to non-SIP uri denied\n");
14525 break;
14526 default:
14527 /* Refer-to extension not found, fake a failed transfer */
14528 transmit_response(p, "202 Accepted", req);
14529 append_history(p, "Xfer", "Refer failed. Bad extension.");
14530 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
14531 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14532 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14533 ast_log(LOG_DEBUG, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
14534 break;
14536 return 0;
14538 if (ast_strlen_zero(p->context))
14539 ast_string_field_set(p, context, default_context);
14541 /* If we do not support SIP domains, all transfers are local */
14542 if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
14543 p->refer->localtransfer = 1;
14544 if (sipdebug && option_debug > 2)
14545 ast_log(LOG_DEBUG, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
14546 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
14547 /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
14548 p->refer->localtransfer = 1;
14549 } else if (sipdebug && option_debug > 2)
14550 ast_log(LOG_DEBUG, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
14552 /* Is this a repeat of a current request? Ignore it */
14553 /* Don't know what else to do right now. */
14554 if (ignore)
14555 return res;
14557 /* If this is a blind transfer, we have the following
14558 channels to work with:
14559 - chan1, chan2: The current call between transferer and transferee (2 channels)
14560 - target_channel: A new call from the transferee to the target (1 channel)
14561 We need to stay tuned to what happens in order to be able
14562 to bring back the call to the transferer */
14564 /* If this is a attended transfer, we should have all call legs within reach:
14565 - chan1, chan2: The call between the transferer and transferee (2 channels)
14566 - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
14567 We want to bridge chan2 with targetcall_pvt!
14569 The replaces call id in the refer message points
14570 to the call leg between Asterisk and the transferer.
14571 So we need to connect the target and the transferee channel
14572 and hangup the two other channels silently
14574 If the target is non-local, the call ID could be on a remote
14575 machine and we need to send an INVITE with replaces to the
14576 target. We basically handle this as a blind transfer
14577 and let the sip_call function catch that we need replaces
14578 header in the INVITE.
14582 /* Get the transferer's channel */
14583 current.chan1 = p->owner;
14585 /* Find the other part of the bridge (2) - transferee */
14586 current.chan2 = ast_bridged_channel(current.chan1);
14588 if (sipdebug && option_debug > 2)
14589 ast_log(LOG_DEBUG, "SIP %s transfer: Transferer channel %s, transferee channel %s\n", p->refer->attendedtransfer ? "attended" : "blind", current.chan1->name, current.chan2 ? current.chan2->name : "<none>");
14591 if (!current.chan2 && !p->refer->attendedtransfer) {
14592 /* No bridged channel, propably IVR or echo or similar... */
14593 /* Guess we should masquerade or something here */
14594 /* Until we figure it out, refuse transfer of such calls */
14595 if (sipdebug && option_debug > 2)
14596 ast_log(LOG_DEBUG,"Refused SIP transfer on non-bridged channel.\n");
14597 p->refer->status = REFER_FAILED;
14598 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
14599 transmit_response(p, "603 Declined", req);
14600 return -1;
14603 if (current.chan2) {
14604 if (sipdebug && option_debug > 3)
14605 ast_log(LOG_DEBUG, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
14607 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
14610 ast_set_flag(&p->flags[0], SIP_GOTREFER);
14612 /* Attended transfer: Find all call legs and bridge transferee with target*/
14613 if (p->refer->attendedtransfer) {
14614 if ((res = local_attended_transfer(p, &current, req, seqno)))
14615 return res; /* We're done with the transfer */
14616 /* Fall through for remote transfers that we did not find locally */
14617 if (sipdebug && option_debug > 3)
14618 ast_log(LOG_DEBUG, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
14619 /* Fallthrough if we can't find the call leg internally */
14623 /* Parking a call */
14624 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
14625 /* Must release c's lock now, because it will not longer be accessible after the transfer! */
14626 *nounlock = 1;
14627 ast_channel_unlock(current.chan1);
14628 copy_request(&current.req, req);
14629 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14630 p->refer->status = REFER_200OK;
14631 append_history(p, "Xfer", "REFER to call parking.");
14632 if (sipdebug && option_debug > 3)
14633 ast_log(LOG_DEBUG, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
14634 sip_park(current.chan2, current.chan1, req, seqno);
14635 return res;
14638 /* Blind transfers and remote attended xfers */
14639 transmit_response(p, "202 Accepted", req);
14641 if (current.chan1 && current.chan2) {
14642 if (option_debug > 2)
14643 ast_log(LOG_DEBUG, "chan1->name: %s\n", current.chan1->name);
14644 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
14646 if (current.chan2) {
14647 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
14648 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
14649 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
14650 /* One for the new channel */
14651 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
14652 /* Attended transfer to remote host, prepare headers for the INVITE */
14653 if (p->refer->referred_by)
14654 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
14656 /* Generate a Replaces string to be used in the INVITE during attended transfer */
14657 if (p->refer->replaces_callid && !ast_strlen_zero(p->refer->replaces_callid)) {
14658 char tempheader[SIPBUFSIZE];
14659 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
14660 p->refer->replaces_callid_totag ? ";to-tag=" : "",
14661 p->refer->replaces_callid_totag,
14662 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
14663 p->refer->replaces_callid_fromtag);
14664 if (current.chan2)
14665 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
14667 /* Must release lock now, because it will not longer
14668 be accessible after the transfer! */
14669 *nounlock = 1;
14670 ast_channel_unlock(current.chan1);
14672 /* Connect the call */
14674 /* FAKE ringing if not attended transfer */
14675 if (!p->refer->attendedtransfer)
14676 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
14678 /* For blind transfer, this will lead to a new call */
14679 /* For attended transfer to remote host, this will lead to
14680 a new SIP call with a replaces header, if the dial plan allows it
14682 if (!current.chan2) {
14683 /* We have no bridge, so we're talking with Asterisk somehow */
14684 /* We need to masquerade this call */
14685 /* What to do to fix this situation:
14686 * Set up the new call in a new channel
14687 * Let the new channel masq into this channel
14688 Please add that code here :-)
14690 p->refer->status = REFER_FAILED;
14691 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
14692 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14693 append_history(p, "Xfer", "Refer failed (only bridged calls).");
14694 return -1;
14696 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
14698 /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
14699 servers - generate an INVITE with Replaces. Either way, let the dial plan decided */
14700 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
14702 if (!res) {
14703 /* Success - we have a new channel */
14704 if (option_debug > 2)
14705 ast_log(LOG_DEBUG, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
14706 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
14707 if (p->refer->localtransfer)
14708 p->refer->status = REFER_200OK;
14709 if (p->owner)
14710 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
14711 append_history(p, "Xfer", "Refer succeeded.");
14712 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14713 /* Do not hangup call, the other side do that when we say 200 OK */
14714 /* We could possibly implement a timer here, auto congestion */
14715 res = 0;
14716 } else {
14717 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
14718 if (option_debug > 2)
14719 ast_log(LOG_DEBUG, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
14720 append_history(p, "Xfer", "Refer failed.");
14721 /* Failure of some kind */
14722 p->refer->status = REFER_FAILED;
14723 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
14724 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14725 res = -1;
14727 return res;
14730 /*! \brief Handle incoming CANCEL request */
14731 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
14734 check_via(p, req);
14735 sip_alreadygone(p);
14737 /* At this point, we could have cancelled the invite at the same time
14738 as the other side sends a CANCEL. Our final reply with error code
14739 might not have been received by the other side before the CANCEL
14740 was sent, so let's just give up retransmissions and waiting for
14741 ACK on our error code. The call is hanging up any way. */
14742 if (p->invitestate == INV_TERMINATED)
14743 __sip_pretend_ack(p);
14744 else
14745 p->invitestate = INV_CANCELLED;
14747 if (p->owner && p->owner->_state == AST_STATE_UP) {
14748 /* This call is up, cancel is ignored, we need a bye */
14749 transmit_response(p, "200 OK", req);
14750 if (option_debug)
14751 ast_log(LOG_DEBUG, "Got CANCEL on an answered call. Ignoring... \n");
14752 return 0;
14755 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
14756 update_call_counter(p, DEC_CALL_LIMIT);
14758 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
14759 if (p->owner)
14760 ast_queue_hangup(p->owner);
14761 else
14762 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14763 if (p->initreq.len > 0) {
14764 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
14765 transmit_response(p, "200 OK", req);
14766 return 1;
14767 } else {
14768 transmit_response(p, "481 Call Leg Does Not Exist", req);
14769 return 0;
14773 static int acf_channel_read(struct ast_channel *chan, char *funcname, char *preparse, char *buf, size_t buflen)
14775 struct ast_rtp_quality qos;
14776 struct sip_pvt *p = chan->tech_pvt;
14777 char *all = "", *parse = ast_strdupa(preparse);
14778 AST_DECLARE_APP_ARGS(args,
14779 AST_APP_ARG(param);
14780 AST_APP_ARG(type);
14781 AST_APP_ARG(field);
14783 AST_STANDARD_APP_ARGS(args, parse);
14785 /* Sanity check */
14786 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
14787 ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
14788 return 0;
14791 if (strcasecmp(args.param, "rtpqos"))
14792 return 0;
14794 /* Default arguments of audio,all */
14795 if (ast_strlen_zero(args.type))
14796 args.type = "audio";
14797 if (ast_strlen_zero(args.field))
14798 args.field = "all";
14800 memset(buf, 0, buflen);
14801 memset(&qos, 0, sizeof(qos));
14803 if (strcasecmp(args.type, "AUDIO") == 0) {
14804 all = ast_rtp_get_quality(p->rtp, &qos);
14805 } else if (strcasecmp(args.type, "VIDEO") == 0) {
14806 all = ast_rtp_get_quality(p->vrtp, &qos);
14809 if (strcasecmp(args.field, "local_ssrc") == 0)
14810 snprintf(buf, buflen, "%u", qos.local_ssrc);
14811 else if (strcasecmp(args.field, "local_lostpackets") == 0)
14812 snprintf(buf, buflen, "%u", qos.local_lostpackets);
14813 else if (strcasecmp(args.field, "local_jitter") == 0)
14814 snprintf(buf, buflen, "%.0lf", qos.local_jitter * 1000.0);
14815 else if (strcasecmp(args.field, "local_count") == 0)
14816 snprintf(buf, buflen, "%u", qos.local_count);
14817 else if (strcasecmp(args.field, "remote_ssrc") == 0)
14818 snprintf(buf, buflen, "%u", qos.remote_ssrc);
14819 else if (strcasecmp(args.field, "remote_lostpackets") == 0)
14820 snprintf(buf, buflen, "%u", qos.remote_lostpackets);
14821 else if (strcasecmp(args.field, "remote_jitter") == 0)
14822 snprintf(buf, buflen, "%.0lf", qos.remote_jitter * 1000.0);
14823 else if (strcasecmp(args.field, "remote_count") == 0)
14824 snprintf(buf, buflen, "%u", qos.remote_count);
14825 else if (strcasecmp(args.field, "rtt") == 0)
14826 snprintf(buf, buflen, "%.0lf", qos.rtt * 1000.0);
14827 else if (strcasecmp(args.field, "all") == 0)
14828 ast_copy_string(buf, all, buflen);
14829 else {
14830 ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
14831 return -1;
14833 return 0;
14836 /*! \brief Handle incoming BYE request */
14837 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
14839 struct ast_channel *c=NULL;
14840 int res;
14841 struct ast_channel *bridged_to;
14843 /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
14844 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner)
14845 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
14847 p->invitestate = INV_TERMINATED;
14849 copy_request(&p->initreq, req);
14850 check_via(p, req);
14851 sip_alreadygone(p);
14853 /* Get RTCP quality before end of call */
14854 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY) || p->owner) {
14855 char *audioqos, *videoqos;
14856 if (p->rtp) {
14857 audioqos = ast_rtp_get_quality(p->rtp, NULL);
14858 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
14859 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
14860 if (p->owner)
14861 pbx_builtin_setvar_helper(p->owner, "RTPAUDIOQOS", audioqos);
14863 if (p->vrtp) {
14864 videoqos = ast_rtp_get_quality(p->vrtp, NULL);
14865 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
14866 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
14867 if (p->owner)
14868 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
14872 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
14874 if (!ast_strlen_zero(get_header(req, "Also"))) {
14875 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
14876 ast_inet_ntoa(p->recv.sin_addr));
14877 if (ast_strlen_zero(p->context))
14878 ast_string_field_set(p, context, default_context);
14879 res = get_also_info(p, req);
14880 if (!res) {
14881 c = p->owner;
14882 if (c) {
14883 bridged_to = ast_bridged_channel(c);
14884 if (bridged_to) {
14885 /* Don't actually hangup here... */
14886 ast_queue_control(c, AST_CONTROL_UNHOLD);
14887 ast_async_goto(bridged_to, p->context, p->refer->refer_to,1);
14888 } else
14889 ast_queue_hangup(p->owner);
14891 } else {
14892 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
14893 if (p->owner)
14894 ast_queue_hangup(p->owner);
14896 } else if (p->owner) {
14897 ast_queue_hangup(p->owner);
14898 if (option_debug > 2)
14899 ast_log(LOG_DEBUG, "Received bye, issuing owner hangup\n");
14900 } else {
14901 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14902 if (option_debug > 2)
14903 ast_log(LOG_DEBUG, "Received bye, no owner, selfdestruct soon.\n");
14905 transmit_response(p, "200 OK", req);
14907 return 1;
14910 /*! \brief Handle incoming MESSAGE request */
14911 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
14913 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
14914 if (ast_test_flag(req, SIP_PKT_DEBUG))
14915 ast_verbose("Receiving message!\n");
14916 receive_message(p, req);
14917 } else
14918 transmit_response(p, "202 Accepted", req);
14919 return 1;
14922 /*! \brief Handle incoming SUBSCRIBE request */
14923 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
14925 int gotdest;
14926 int res = 0;
14927 int firststate = AST_EXTENSION_REMOVED;
14928 struct sip_peer *authpeer = NULL;
14929 const char *eventheader = get_header(req, "Event"); /* Get Event package name */
14930 const char *accept = get_header(req, "Accept");
14931 int resubscribe = (p->subscribed != NONE);
14932 char *temp, *event;
14934 if (p->initreq.headers) {
14935 /* We already have a dialog */
14936 if (p->initreq.method != SIP_SUBSCRIBE) {
14937 /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
14938 /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
14939 transmit_response(p, "403 Forbidden (within dialog)", req);
14940 /* Do not destroy session, since we will break the call if we do */
14941 if (option_debug)
14942 ast_log(LOG_DEBUG, "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);
14943 return 0;
14944 } else if (ast_test_flag(req, SIP_PKT_DEBUG)) {
14945 if (option_debug) {
14946 if (resubscribe)
14947 ast_log(LOG_DEBUG, "Got a re-subscribe on existing subscription %s\n", p->callid);
14948 else
14949 ast_log(LOG_DEBUG, "Got a new subscription %s (possibly with auth)\n", p->callid);
14954 /* Check if we have a global disallow setting on subscriptions.
14955 if so, we don't have to check peer/user settings after auth, which saves a lot of processing
14957 if (!global_allowsubscribe) {
14958 transmit_response(p, "403 Forbidden (policy)", req);
14959 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14960 return 0;
14963 if (!ast_test_flag(req, SIP_PKT_IGNORE) && !resubscribe) { /* Set up dialog, new subscription */
14964 const char *to = get_header(req, "To");
14965 char totag[128];
14967 /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
14968 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
14969 if (ast_test_flag(req, SIP_PKT_DEBUG))
14970 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
14971 transmit_response(p, "481 Subscription does not exist", req);
14972 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14973 return 0;
14976 /* Use this as the basis */
14977 if (ast_test_flag(req, SIP_PKT_DEBUG))
14978 ast_verbose("Creating new subscription\n");
14980 copy_request(&p->initreq, req);
14981 check_via(p, req);
14982 } else if (ast_test_flag(req, SIP_PKT_DEBUG) && ast_test_flag(req, SIP_PKT_IGNORE))
14983 ast_verbose("Ignoring this SUBSCRIBE request\n");
14985 /* Find parameters to Event: header value and remove them for now */
14986 if (ast_strlen_zero(eventheader)) {
14987 transmit_response(p, "489 Bad Event", req);
14988 if (option_debug > 1)
14989 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: <none>\n");
14990 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14991 return 0;
14994 if ( (strchr(eventheader, ';'))) {
14995 event = ast_strdupa(eventheader); /* Since eventheader is a const, we can't change it */
14996 temp = strchr(event, ';');
14997 *temp = '\0'; /* Remove any options for now */
14998 /* We might need to use them later :-) */
14999 } else
15000 event = (char *) eventheader; /* XXX is this legal ? */
15002 /* Handle authentication */
15003 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
15004 /* if an authentication response was sent, we are done here */
15005 if (res == AUTH_CHALLENGE_SENT) {
15006 if (authpeer)
15007 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15008 return 0;
15010 if (res < 0) {
15011 if (res == AUTH_FAKE_AUTH) {
15012 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
15013 transmit_fake_auth_response(p, req, 1);
15014 } else {
15015 ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
15016 transmit_response_reliable(p, "403 Forbidden", req);
15018 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15019 if (authpeer)
15020 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15021 return 0;
15024 /* Check if this user/peer is allowed to subscribe at all */
15025 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
15026 transmit_response(p, "403 Forbidden (policy)", req);
15027 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15028 if (authpeer)
15029 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15030 return 0;
15033 /* Get destination right away */
15034 gotdest = get_destination(p, NULL);
15036 /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
15037 parse_ok_contact(p, req);
15039 build_contact(p);
15040 if (strcmp(event, "message-summary") && gotdest) {
15041 transmit_response(p, "404 Not Found", req);
15042 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15043 if (authpeer)
15044 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15045 return 0;
15048 /* Initialize tag for new subscriptions */
15049 if (ast_strlen_zero(p->tag))
15050 make_our_tag(p->tag, sizeof(p->tag));
15052 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
15053 if (authpeer) /* No need for authpeer here */
15054 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15056 /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
15057 /* Polycom phones only handle xpidf+xml, even if they say they can
15058 handle pidf+xml as well
15060 if (strstr(p->useragent, "Polycom")) {
15061 p->subscribed = XPIDF_XML;
15062 } else if (strstr(accept, "application/pidf+xml")) {
15063 p->subscribed = PIDF_XML; /* RFC 3863 format */
15064 } else if (strstr(accept, "application/dialog-info+xml")) {
15065 p->subscribed = DIALOG_INFO_XML;
15066 /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
15067 } else if (strstr(accept, "application/cpim-pidf+xml")) {
15068 p->subscribed = CPIM_PIDF_XML; /* RFC 3863 format */
15069 } else if (strstr(accept, "application/xpidf+xml")) {
15070 p->subscribed = XPIDF_XML; /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
15071 } else if (ast_strlen_zero(accept)) {
15072 if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
15073 transmit_response(p, "489 Bad Event", req);
15075 ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
15076 p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
15077 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15078 return 0;
15080 /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
15081 so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
15082 } else {
15083 /* Can't find a format for events that we know about */
15084 char mybuf[200];
15085 snprintf(mybuf,sizeof(mybuf),"489 Bad Event (format %s)", accept);
15086 transmit_response(p, mybuf, req);
15088 ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
15089 accept, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
15090 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15091 return 0;
15093 } else if (!strcmp(event, "message-summary")) {
15094 if (!ast_strlen_zero(accept) && strcmp(accept, "application/simple-message-summary")) {
15095 /* Format requested that we do not support */
15096 transmit_response(p, "406 Not Acceptable", req);
15097 if (option_debug > 1)
15098 ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", accept);
15099 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15100 if (authpeer) /* No need for authpeer here */
15101 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15102 return 0;
15104 /* Looks like they actually want a mailbox status
15105 This version of Asterisk supports mailbox subscriptions
15106 The subscribed URI needs to exist in the dial plan
15107 In most devices, this is configurable to the voicemailmain extension you use
15109 if (!authpeer || ast_strlen_zero(authpeer->mailbox)) {
15110 transmit_response(p, "404 Not found (no mailbox)", req);
15111 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15112 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
15113 if (authpeer) /* No need for authpeer here */
15114 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15115 return 0;
15118 p->subscribed = MWI_NOTIFICATION;
15119 if (authpeer->mwipvt && authpeer->mwipvt != p) /* Destroy old PVT if this is a new one */
15120 /* We only allow one subscription per peer */
15121 sip_destroy(authpeer->mwipvt);
15122 authpeer->mwipvt = p; /* Link from peer to pvt */
15123 p->relatedpeer = ASTOBJ_REF(authpeer); /* Link from pvt to peer */
15124 } else { /* At this point, Asterisk does not understand the specified event */
15125 transmit_response(p, "489 Bad Event", req);
15126 if (option_debug > 1)
15127 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: %s\n", event);
15128 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15129 if (authpeer) /* No need for authpeer here */
15130 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15131 return 0;
15134 if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
15135 if (p->stateid > -1)
15136 ast_extension_state_del(p->stateid, cb_extensionstate);
15137 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, p);
15140 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
15141 p->lastinvite = seqno;
15142 if (p && !ast_test_flag(&p->flags[0], SIP_NEEDDESTROY)) {
15143 p->expiry = atoi(get_header(req, "Expires"));
15145 /* check if the requested expiry-time is within the approved limits from sip.conf */
15146 if (p->expiry > max_expiry)
15147 p->expiry = max_expiry;
15148 if (p->expiry < min_expiry && p->expiry > 0)
15149 p->expiry = min_expiry;
15151 if (sipdebug || option_debug > 1) {
15152 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
15153 ast_log(LOG_DEBUG, "Adding subscription for mailbox notification - peer %s Mailbox %s\n", p->relatedpeer->name, p->relatedpeer->mailbox);
15154 else
15155 ast_log(LOG_DEBUG, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
15157 if (p->autokillid > -1 && sip_cancel_destroy(p)) /* Remove subscription expiry for renewals */
15158 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15159 if (p->expiry > 0)
15160 sip_scheddestroy(p, (p->expiry + 10) * 1000); /* Set timer for destruction of call at expiration */
15162 if (p->subscribed == MWI_NOTIFICATION) {
15163 transmit_response(p, "200 OK", req);
15164 if (p->relatedpeer) { /* Send first notification */
15165 ASTOBJ_WRLOCK(p->relatedpeer);
15166 sip_send_mwi_to_peer(p->relatedpeer);
15167 ASTOBJ_UNLOCK(p->relatedpeer);
15169 } else {
15170 struct sip_pvt *p_old;
15172 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
15174 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));
15175 transmit_response(p, "404 Not found", req);
15176 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15177 return 0;
15180 transmit_response(p, "200 OK", req);
15181 transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
15182 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
15183 /* hide the 'complete' exten/context in the refer_to field for later display */
15184 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
15186 /* remove any old subscription from this peer for the same exten/context,
15187 as the peer has obviously forgotten about it and it's wasteful to wait
15188 for it to expire and send NOTIFY messages to the peer only to have them
15189 ignored (or generate errors)
15191 ast_mutex_lock(&iflock);
15192 for (p_old = iflist; p_old; p_old = p_old->next) {
15193 if (p_old == p)
15194 continue;
15195 if (p_old->initreq.method != SIP_SUBSCRIBE)
15196 continue;
15197 if (p_old->subscribed == NONE)
15198 continue;
15199 ast_mutex_lock(&p_old->lock);
15200 if (!strcmp(p_old->username, p->username)) {
15201 if (!strcmp(p_old->exten, p->exten) &&
15202 !strcmp(p_old->context, p->context)) {
15203 ast_set_flag(&p_old->flags[0], SIP_NEEDDESTROY);
15204 ast_mutex_unlock(&p_old->lock);
15205 break;
15208 ast_mutex_unlock(&p_old->lock);
15210 ast_mutex_unlock(&iflock);
15212 if (!p->expiry)
15213 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15215 return 1;
15218 /*! \brief Handle incoming REGISTER request */
15219 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
15221 enum check_auth_result res;
15223 /* Use this as the basis */
15224 if (ast_test_flag(req, SIP_PKT_DEBUG))
15225 ast_verbose("Using latest REGISTER request as basis request\n");
15226 copy_request(&p->initreq, req);
15227 check_via(p, req);
15228 if ((res = register_verify(p, sin, req, e)) < 0) {
15229 const char *reason;
15231 switch (res) {
15232 case AUTH_SECRET_FAILED:
15233 reason = "Wrong password";
15234 break;
15235 case AUTH_USERNAME_MISMATCH:
15236 reason = "Username/auth name mismatch";
15237 break;
15238 case AUTH_NOT_FOUND:
15239 reason = "No matching peer found";
15240 break;
15241 case AUTH_UNKNOWN_DOMAIN:
15242 reason = "Not a local domain";
15243 break;
15244 case AUTH_PEER_NOT_DYNAMIC:
15245 reason = "Peer is not supposed to register";
15246 break;
15247 case AUTH_ACL_FAILED:
15248 reason = "Device does not match ACL";
15249 break;
15250 default:
15251 reason = "Unknown failure";
15252 break;
15254 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
15255 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
15256 reason);
15257 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
15258 } else
15259 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
15261 if (res < 1) {
15262 /* Destroy the session, but keep us around for just a bit in case they don't
15263 get our 200 OK */
15264 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15266 return res;
15269 /*! \brief Handle incoming SIP requests (methods)
15270 \note This is where all incoming requests go first */
15271 /* called with p and p->owner locked */
15272 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
15274 /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
15275 relatively static */
15276 const char *cmd;
15277 const char *cseq;
15278 const char *useragent;
15279 int seqno;
15280 int len;
15281 int ignore = FALSE;
15282 int respid;
15283 int res = 0;
15284 int debug = sip_debug_test_pvt(p);
15285 char *e;
15286 int error = 0;
15288 /* Get Method and Cseq */
15289 cseq = get_header(req, "Cseq");
15290 cmd = req->header[0];
15292 /* Must have Cseq */
15293 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
15294 ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
15295 error = 1;
15297 if (!error && sscanf(cseq, "%d%n", &seqno, &len) != 1) {
15298 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
15299 error = 1;
15301 if (error) {
15302 if (!p->initreq.headers) /* New call */
15303 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); /* Make sure we destroy this dialog */
15304 return -1;
15306 /* Get the command XXX */
15308 cmd = req->rlPart1;
15309 e = req->rlPart2;
15311 /* Save useragent of the client */
15312 useragent = get_header(req, "User-Agent");
15313 if (!ast_strlen_zero(useragent))
15314 ast_string_field_set(p, useragent, useragent);
15316 /* Find out SIP method for incoming request */
15317 if (req->method == SIP_RESPONSE) { /* Response to our request */
15318 /* Response to our request -- Do some sanity checks */
15319 if (!p->initreq.headers) {
15320 if (option_debug)
15321 ast_log(LOG_DEBUG, "That's odd... Got a response on a call we dont know about. Cseq %d Cmd %s\n", seqno, cmd);
15322 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15323 return 0;
15324 } else if (p->ocseq && (p->ocseq < seqno) && (seqno != p->lastnoninvite)) {
15325 if (option_debug)
15326 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
15327 return -1;
15328 } else if (p->ocseq && (p->ocseq != seqno) && (seqno != p->lastnoninvite)) {
15329 /* ignore means "don't do anything with it" but still have to
15330 respond appropriately */
15331 ignore = TRUE;
15332 ast_set_flag(req, SIP_PKT_IGNORE);
15333 ast_set_flag(req, SIP_PKT_IGNORE_RESP);
15334 append_history(p, "Ignore", "Ignoring this retransmit\n");
15335 } else if (e) {
15336 e = ast_skip_blanks(e);
15337 if (sscanf(e, "%d %n", &respid, &len) != 1) {
15338 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
15339 } else {
15340 if (respid <= 0) {
15341 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
15342 return 0;
15344 /* More SIP ridiculousness, we have to ignore bogus contacts in 100 etc responses */
15345 if ((respid == 200) || ((respid >= 300) && (respid <= 399)))
15346 extract_uri(p, req);
15347 handle_response(p, respid, e + len, req, ignore, seqno);
15350 return 0;
15353 /* New SIP request coming in
15354 (could be new request in existing SIP dialog as well...)
15357 p->method = req->method; /* Find out which SIP method they are using */
15358 if (option_debug > 3)
15359 ast_log(LOG_DEBUG, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
15361 if (p->icseq && (p->icseq > seqno) ) {
15362 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
15363 if (option_debug > 2)
15364 ast_log(LOG_DEBUG, "Got CANCEL or ACK on INVITE with transactions in between.\n");
15365 } else {
15366 if (option_debug)
15367 ast_log(LOG_DEBUG, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
15368 if (req->method != SIP_ACK)
15369 transmit_response(p, "503 Server error", req); /* We must respond according to RFC 3261 sec 12.2 */
15370 return -1;
15372 } else if (p->icseq &&
15373 p->icseq == seqno &&
15374 req->method != SIP_ACK &&
15375 (p->method != SIP_CANCEL || ast_test_flag(&p->flags[0], SIP_ALREADYGONE))) {
15376 /* ignore means "don't do anything with it" but still have to
15377 respond appropriately. We do this if we receive a repeat of
15378 the last sequence number */
15379 ignore = 2;
15380 ast_set_flag(req, SIP_PKT_IGNORE);
15381 ast_set_flag(req, SIP_PKT_IGNORE_REQ);
15382 if (option_debug > 2)
15383 ast_log(LOG_DEBUG, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
15386 if (seqno >= p->icseq)
15387 /* Next should follow monotonically (but not necessarily
15388 incrementally -- thanks again to the genius authors of SIP --
15389 increasing */
15390 p->icseq = seqno;
15392 /* Find their tag if we haven't got it */
15393 if (ast_strlen_zero(p->theirtag)) {
15394 char tag[128];
15396 gettag(req, "From", tag, sizeof(tag));
15397 ast_string_field_set(p, theirtag, tag);
15399 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
15401 if (pedanticsipchecking) {
15402 /* If this is a request packet without a from tag, it's not
15403 correct according to RFC 3261 */
15404 /* Check if this a new request in a new dialog with a totag already attached to it,
15405 RFC 3261 - section 12.2 - and we don't want to mess with recovery */
15406 if (!p->initreq.headers && ast_test_flag(req, SIP_PKT_WITH_TOTAG)) {
15407 /* If this is a first request and it got a to-tag, it is not for us */
15408 if (!ast_test_flag(req, SIP_PKT_IGNORE) && req->method == SIP_INVITE) {
15409 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
15410 /* Will cease to exist after ACK */
15411 } else if (req->method != SIP_ACK) {
15412 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
15413 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15415 return res;
15419 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
15420 transmit_response(p, "400 Bad request", req);
15421 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15422 return -1;
15425 /* Handle various incoming SIP methods in requests */
15426 switch (p->method) {
15427 case SIP_OPTIONS:
15428 res = handle_request_options(p, req);
15429 break;
15430 case SIP_INVITE:
15431 res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
15432 break;
15433 case SIP_REFER:
15434 res = handle_request_refer(p, req, debug, ignore, seqno, nounlock);
15435 break;
15436 case SIP_CANCEL:
15437 res = handle_request_cancel(p, req);
15438 break;
15439 case SIP_BYE:
15440 res = handle_request_bye(p, req);
15441 break;
15442 case SIP_MESSAGE:
15443 res = handle_request_message(p, req);
15444 break;
15445 case SIP_SUBSCRIBE:
15446 res = handle_request_subscribe(p, req, sin, seqno, e);
15447 break;
15448 case SIP_REGISTER:
15449 res = handle_request_register(p, req, sin, e);
15450 break;
15451 case SIP_INFO:
15452 if (ast_test_flag(req, SIP_PKT_DEBUG))
15453 ast_verbose("Receiving INFO!\n");
15454 if (!ignore)
15455 handle_request_info(p, req);
15456 else /* if ignoring, transmit response */
15457 transmit_response(p, "200 OK", req);
15458 break;
15459 case SIP_NOTIFY:
15460 res = handle_request_notify(p, req, sin, seqno, e);
15461 break;
15462 case SIP_ACK:
15463 /* Make sure we don't ignore this */
15464 if (seqno == p->pendinginvite) {
15465 p->invitestate = INV_TERMINATED;
15466 p->pendinginvite = 0;
15467 __sip_ack(p, seqno, FLAG_RESPONSE, 0);
15468 if (find_sdp(req)) {
15469 if (process_sdp(p, req))
15470 return -1;
15472 check_pendings(p);
15474 /* Got an ACK that we did not match. Ignore silently */
15475 if (!p->lastinvite && ast_strlen_zero(p->randdata))
15476 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15477 break;
15478 default:
15479 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
15480 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
15481 cmd, ast_inet_ntoa(p->sa.sin_addr));
15482 /* If this is some new method, and we don't have a call, destroy it now */
15483 if (!p->initreq.headers)
15484 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15485 break;
15487 return res;
15490 /*! \brief Read data from SIP socket
15491 \note sipsock_read locks the owner channel while we are processing the SIP message
15492 \return 1 on error, 0 on success
15493 \note Successful messages is connected to SIP call and forwarded to handle_request()
15495 static int sipsock_read(int *id, int fd, short events, void *ignore)
15497 struct sip_request req;
15498 struct sockaddr_in sin = { 0, };
15499 struct sip_pvt *p;
15500 int res;
15501 socklen_t len = sizeof(sin);
15502 int nounlock;
15503 int recount = 0;
15504 int lockretry;
15506 memset(&req, 0, sizeof(req));
15507 res = recvfrom(sipsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
15508 if (res < 0) {
15509 #if !defined(__FreeBSD__)
15510 if (errno == EAGAIN)
15511 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
15512 else
15513 #endif
15514 if (errno != ECONNREFUSED)
15515 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
15516 return 1;
15518 if (option_debug && res == sizeof(req.data) - 1)
15519 ast_log(LOG_DEBUG, "Received packet exceeds buffer. Data is possibly lost\n");
15521 req.data[res] = '\0';
15522 req.len = res;
15523 if(sip_debug_test_addr(&sin)) /* Set the debug flag early on packet level */
15524 ast_set_flag(&req, SIP_PKT_DEBUG);
15525 if (pedanticsipchecking)
15526 req.len = lws2sws(req.data, req.len); /* Fix multiline headers */
15527 if (ast_test_flag(&req, SIP_PKT_DEBUG))
15528 ast_verbose("\n<--- SIP read from %s:%d --->\n%s\n<------------->\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), req.data);
15530 if(parse_request(&req) == -1) /* Bad packet, can't parse */
15531 return 1;
15533 req.method = find_sip_method(req.rlPart1);
15535 if (ast_test_flag(&req, SIP_PKT_DEBUG))
15536 ast_verbose("--- (%d headers %d lines)%s ---\n", req.headers, req.lines, (req.headers + req.lines == 0) ? " Nat keepalive" : "");
15538 if (req.headers < 2) /* Must have at least two headers */
15539 return 1;
15541 /* Process request, with netlock held, and with usual deadlock avoidance */
15542 for (lockretry = 100; lockretry > 0; lockretry--) {
15543 ast_mutex_lock(&netlock);
15545 /* Find the active SIP dialog or create a new one */
15546 p = find_call(&req, &sin, req.method); /* returns p locked */
15547 if (p == NULL) {
15548 if (option_debug)
15549 ast_log(LOG_DEBUG, "Invalid SIP message - rejected , no callid, len %d\n", req.len);
15550 ast_mutex_unlock(&netlock);
15551 return 1;
15553 /* Go ahead and lock the owner if it has one -- we may need it */
15554 /* becaues this is deadlock-prone, we need to try and unlock if failed */
15555 if (!p->owner || !ast_channel_trylock(p->owner))
15556 break; /* locking succeeded */
15557 if (option_debug)
15558 ast_log(LOG_DEBUG, "Failed to grab owner channel lock, trying again. (SIP call %s)\n", p->callid);
15559 ast_mutex_unlock(&p->lock);
15560 ast_mutex_unlock(&netlock);
15561 /* Sleep for a very short amount of time */
15562 usleep(1);
15564 p->recv = sin;
15566 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) /* This is a request or response, note what it was for */
15567 append_history(p, "Rx", "%s / %s / %s", req.data, get_header(&req, "CSeq"), req.rlPart2);
15569 if (!lockretry) {
15570 if (p->owner)
15571 ast_log(LOG_ERROR, "We could NOT get the channel lock for %s! \n", S_OR(p->owner->name, "- no channel name ??? - "));
15572 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
15573 if (req.method != SIP_ACK)
15574 transmit_response(p, "503 Server error", &req); /* We must respond according to RFC 3261 sec 12.2 */
15575 /* XXX We could add retry-after to make sure they come back */
15576 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
15577 return 1;
15579 nounlock = 0;
15580 if (handle_request(p, &req, &sin, &recount, &nounlock) == -1) {
15581 /* Request failed */
15582 if (option_debug)
15583 ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
15586 if (p->owner && !nounlock)
15587 ast_channel_unlock(p->owner);
15588 ast_mutex_unlock(&p->lock);
15589 ast_mutex_unlock(&netlock);
15590 if (recount)
15591 ast_update_use_count();
15593 return 1;
15596 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
15597 static int sip_send_mwi_to_peer(struct sip_peer *peer)
15599 /* Called with peerl lock, but releases it */
15600 struct sip_pvt *p;
15601 int newmsgs, oldmsgs;
15603 /* Do we have an IP address? If not, skip this peer */
15604 if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr)
15605 return 0;
15607 /* Check for messages */
15608 ast_app_inboxcount(peer->mailbox, &newmsgs, &oldmsgs);
15610 peer->lastmsgcheck = time(NULL);
15612 /* Return now if it's the same thing we told them last time */
15613 if (((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)) == peer->lastmsgssent) {
15614 return 0;
15618 peer->lastmsgssent = ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs));
15620 if (peer->mwipvt) {
15621 /* Base message on subscription */
15622 p = peer->mwipvt;
15623 } else {
15624 /* Build temporary dialog for this message */
15625 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY)))
15626 return -1;
15627 if (create_addr_from_peer(p, peer)) {
15628 /* Maybe they're not registered, etc. */
15629 sip_destroy(p);
15630 return 0;
15632 /* Recalculate our side, and recalculate Call ID */
15633 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
15634 p->ourip = __ourip;
15635 build_via(p);
15636 build_callid_pvt(p);
15637 /* Destroy this session after 32 secs */
15638 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15640 /* Send MWI */
15641 ast_set_flag(&p->flags[0], SIP_OUTGOING);
15642 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
15643 return 0;
15646 /*! \brief Check whether peer needs a new MWI notification check */
15647 static int does_peer_need_mwi(struct sip_peer *peer)
15649 time_t t = time(NULL);
15651 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
15652 !peer->mwipvt) { /* We don't have a subscription */
15653 peer->lastmsgcheck = t; /* Reset timer */
15654 return FALSE;
15657 if (!ast_strlen_zero(peer->mailbox) && (t - peer->lastmsgcheck) > global_mwitime)
15658 return TRUE;
15660 return FALSE;
15664 /*! \brief The SIP monitoring thread
15665 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
15666 (and thus do not have a separate thread) indefinitely
15668 static void *do_monitor(void *data)
15670 int res;
15671 struct sip_pvt *sip;
15672 struct sip_peer *peer = NULL;
15673 time_t t;
15674 int fastrestart = FALSE;
15675 int lastpeernum = -1;
15676 int curpeernum;
15677 int reloading;
15679 /* Add an I/O event to our SIP UDP socket */
15680 if (sipsock > -1)
15681 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
15683 /* From here on out, we die whenever asked */
15684 for(;;) {
15685 /* Check for a reload request */
15686 ast_mutex_lock(&sip_reload_lock);
15687 reloading = sip_reloading;
15688 sip_reloading = FALSE;
15689 ast_mutex_unlock(&sip_reload_lock);
15690 if (reloading) {
15691 if (option_verbose > 0)
15692 ast_verbose(VERBOSE_PREFIX_1 "Reloading SIP\n");
15693 sip_do_reload(sip_reloadreason);
15695 /* Change the I/O fd of our UDP socket */
15696 if (sipsock > -1) {
15697 if (sipsock_read_id)
15698 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
15699 else
15700 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
15701 } else if (sipsock_read_id) {
15702 ast_io_remove(io, sipsock_read_id);
15703 sipsock_read_id = NULL;
15706 restartsearch:
15707 /* Check for interfaces needing to be killed */
15708 ast_mutex_lock(&iflock);
15709 t = time(NULL);
15710 /* don't scan the interface list if it hasn't been a reasonable period
15711 of time since the last time we did it (when MWI is being sent, we can
15712 get back to this point every millisecond or less)
15714 for (sip = iflist; !fastrestart && sip; sip = sip->next) {
15715 /*! \note If we can't get a lock on an interface, skip it and come
15716 * back later. Note that there is the possibility of a deadlock with
15717 * sip_hangup otherwise, because sip_hangup is called with the channel
15718 * locked first, and the iface lock is attempted second.
15720 if (ast_mutex_trylock(&sip->lock))
15721 continue;
15723 /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
15724 if (sip->rtp && sip->owner &&
15725 (sip->owner->_state == AST_STATE_UP) &&
15726 !sip->redirip.sin_addr.s_addr &&
15727 sip->t38.state != T38_ENABLED) {
15728 if (sip->lastrtptx &&
15729 ast_rtp_get_rtpkeepalive(sip->rtp) &&
15730 (t > sip->lastrtptx + ast_rtp_get_rtpkeepalive(sip->rtp))) {
15731 /* Need to send an empty RTP packet */
15732 sip->lastrtptx = time(NULL);
15733 ast_rtp_sendcng(sip->rtp, 0);
15735 if (sip->lastrtprx &&
15736 (ast_rtp_get_rtptimeout(sip->rtp) || ast_rtp_get_rtpholdtimeout(sip->rtp)) &&
15737 (t > sip->lastrtprx + ast_rtp_get_rtptimeout(sip->rtp))) {
15738 /* Might be a timeout now -- see if we're on hold */
15739 struct sockaddr_in sin;
15740 ast_rtp_get_peer(sip->rtp, &sin);
15741 if (sin.sin_addr.s_addr ||
15742 (ast_rtp_get_rtpholdtimeout(sip->rtp) &&
15743 (t > sip->lastrtprx + ast_rtp_get_rtpholdtimeout(sip->rtp)))) {
15744 /* Needs a hangup */
15745 if (ast_rtp_get_rtptimeout(sip->rtp)) {
15746 while (sip->owner && ast_channel_trylock(sip->owner)) {
15747 DEADLOCK_AVOIDANCE(&sip->lock);
15749 if (sip->owner) {
15750 ast_log(LOG_NOTICE,
15751 "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
15752 sip->owner->name,
15753 (long) (t - sip->lastrtprx));
15754 /* Issue a softhangup */
15755 ast_softhangup_nolock(sip->owner, AST_SOFTHANGUP_DEV);
15756 ast_channel_unlock(sip->owner);
15757 /* forget the timeouts for this call, since a hangup
15758 has already been requested and we don't want to
15759 repeatedly request hangups
15761 ast_rtp_set_rtptimeout(sip->rtp, 0);
15762 ast_rtp_set_rtpholdtimeout(sip->rtp, 0);
15763 if (sip->vrtp) {
15764 ast_rtp_set_rtptimeout(sip->vrtp, 0);
15765 ast_rtp_set_rtpholdtimeout(sip->vrtp, 0);
15772 /* If we have sessions that needs to be destroyed, do it now */
15773 if (ast_test_flag(&sip->flags[0], SIP_NEEDDESTROY) && !sip->packets &&
15774 !sip->owner) {
15775 ast_mutex_unlock(&sip->lock);
15776 __sip_destroy(sip, 1);
15777 ast_mutex_unlock(&iflock);
15778 usleep(1);
15779 goto restartsearch;
15781 ast_mutex_unlock(&sip->lock);
15783 ast_mutex_unlock(&iflock);
15785 pthread_testcancel();
15786 /* Wait for sched or io */
15787 res = ast_sched_wait(sched);
15788 if ((res < 0) || (res > 1000))
15789 res = 1000;
15790 /* If we might need to send more mailboxes, don't wait long at all.*/
15791 if (fastrestart)
15792 res = 1;
15793 res = ast_io_wait(io, res);
15794 if (option_debug && res > 20)
15795 ast_log(LOG_DEBUG, "chan_sip: ast_io_wait ran %d all at once\n", res);
15796 ast_mutex_lock(&monlock);
15797 if (res >= 0) {
15798 res = ast_sched_runq(sched);
15799 if (option_debug && res >= 20)
15800 ast_log(LOG_DEBUG, "chan_sip: ast_sched_runq ran %d all at once\n", res);
15803 /* Send MWI notifications to peers - static and cached realtime peers */
15804 t = time(NULL);
15805 fastrestart = FALSE;
15806 curpeernum = 0;
15807 peer = NULL;
15808 /* Find next peer that needs mwi */
15809 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !peer, do {
15810 if ((curpeernum > lastpeernum) && does_peer_need_mwi(iterator)) {
15811 fastrestart = TRUE;
15812 lastpeernum = curpeernum;
15813 peer = ASTOBJ_REF(iterator);
15815 curpeernum++;
15816 } while (0)
15818 /* Send MWI to the peer */
15819 if (peer) {
15820 ASTOBJ_WRLOCK(peer);
15821 sip_send_mwi_to_peer(peer);
15822 ASTOBJ_UNLOCK(peer);
15823 ASTOBJ_UNREF(peer,sip_destroy_peer);
15824 } else {
15825 /* Reset where we come from */
15826 lastpeernum = -1;
15828 ast_mutex_unlock(&monlock);
15830 /* Never reached */
15831 return NULL;
15835 /*! \brief Start the channel monitor thread */
15836 static int restart_monitor(void)
15838 /* If we're supposed to be stopped -- stay stopped */
15839 if (monitor_thread == AST_PTHREADT_STOP)
15840 return 0;
15841 ast_mutex_lock(&monlock);
15842 if (monitor_thread == pthread_self()) {
15843 ast_mutex_unlock(&monlock);
15844 ast_log(LOG_WARNING, "Cannot kill myself\n");
15845 return -1;
15847 if (monitor_thread != AST_PTHREADT_NULL) {
15848 /* Wake up the thread */
15849 pthread_kill(monitor_thread, SIGURG);
15850 } else {
15851 /* Start a new monitor */
15852 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
15853 ast_mutex_unlock(&monlock);
15854 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
15855 return -1;
15858 ast_mutex_unlock(&monlock);
15859 return 0;
15862 /*! \brief React to lack of answer to Qualify poke */
15863 static int sip_poke_noanswer(const void *data)
15865 struct sip_peer *peer = (struct sip_peer *)data;
15867 peer->pokeexpire = -1;
15868 if (peer->lastms > -1) {
15869 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
15870 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
15872 if (peer->call)
15873 sip_destroy(peer->call);
15874 peer->call = NULL;
15875 peer->lastms = -1;
15876 ast_device_state_changed("SIP/%s", peer->name);
15878 /* This function gets called one place outside of the scheduler ... */
15879 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
15880 struct sip_peer *peer_ptr = peer;
15881 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
15884 /* There is no need to ASTOBJ_REF() here. Just let the scheduled callback
15885 * inherit the reference that the current callback already has. */
15886 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
15887 if (peer->pokeexpire == -1) {
15888 ASTOBJ_UNREF(peer, sip_destroy_peer);
15891 return 0;
15894 /*! \brief Check availability of peer, also keep NAT open
15895 \note This is done with the interval in qualify= configuration option
15896 Default is 2 seconds */
15897 static int sip_poke_peer(struct sip_peer *peer)
15899 struct sip_pvt *p;
15900 int xmitres = 0;
15902 if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
15903 /* IF we have no IP, or this isn't to be monitored, return
15904 imeediately after clearing things out */
15905 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
15906 struct sip_peer *peer_ptr = peer;
15907 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
15909 peer->lastms = 0;
15910 peer->call = NULL;
15911 return 0;
15913 if (peer->call) {
15914 if (sipdebug)
15915 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
15916 sip_destroy(peer->call);
15918 if (!(p = peer->call = sip_alloc(NULL, NULL, 0, SIP_OPTIONS)))
15919 return -1;
15921 p->sa = peer->addr;
15922 p->recv = peer->addr;
15923 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
15924 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15926 /* Send OPTIONs to peer's fullcontact */
15927 if (!ast_strlen_zero(peer->fullcontact))
15928 ast_string_field_set(p, fullcontact, peer->fullcontact);
15930 if (!ast_strlen_zero(peer->tohost))
15931 ast_string_field_set(p, tohost, peer->tohost);
15932 else
15933 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
15935 /* Recalculate our side, and recalculate Call ID */
15936 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
15937 p->ourip = __ourip;
15938 build_via(p);
15939 build_callid_pvt(p);
15941 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
15942 struct sip_peer *peer_ptr = peer;
15943 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
15946 p->relatedpeer = ASTOBJ_REF(peer);
15947 ast_set_flag(&p->flags[0], SIP_OUTGOING);
15948 #ifdef VOCAL_DATA_HACK
15949 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
15950 xmitres = transmit_invite(p, SIP_INVITE, 0, 2);
15951 #else
15952 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2);
15953 #endif
15954 gettimeofday(&peer->ps, NULL);
15955 if (xmitres == XMIT_ERROR) {
15956 sip_poke_noanswer(ASTOBJ_REF(peer)); /* Immediately unreachable, network problems */
15957 } else {
15958 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
15959 struct sip_peer *peer_ptr = peer;
15960 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
15962 peer->pokeexpire = ast_sched_add(sched, peer->maxms * 2, sip_poke_noanswer, ASTOBJ_REF(peer));
15963 if (peer->pokeexpire == -1) {
15964 struct sip_peer *peer_ptr = peer;
15965 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
15969 return 0;
15972 /*! \brief Part of PBX channel interface
15973 \note
15974 \par Return values:---
15976 If we have qualify on and the device is not reachable, regardless of registration
15977 state we return AST_DEVICE_UNAVAILABLE
15979 For peers with call limit:
15980 - not registered AST_DEVICE_UNAVAILABLE
15981 - registered, no call AST_DEVICE_NOT_INUSE
15982 - registered, active calls AST_DEVICE_INUSE
15983 - registered, call limit reached AST_DEVICE_BUSY
15984 - registered, onhold AST_DEVICE_ONHOLD
15985 - registered, ringing AST_DEVICE_RINGING
15987 For peers without call limit:
15988 - not registered AST_DEVICE_UNAVAILABLE
15989 - registered AST_DEVICE_NOT_INUSE
15990 - fixed IP (!dynamic) AST_DEVICE_NOT_INUSE
15992 Peers that does not have a known call and can't be reached by OPTIONS
15993 - unreachable AST_DEVICE_UNAVAILABLE
15995 If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
15996 out a state by walking the channel list.
15998 The queue system (\ref app_queue.c) treats a member as "active"
15999 if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
16001 When placing a call to the queue member, queue system sets a member to busy if
16002 != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
16005 static int sip_devicestate(void *data)
16007 char *host;
16008 char *tmp;
16010 struct hostent *hp;
16011 struct ast_hostent ahp;
16012 struct sip_peer *p;
16014 int res = AST_DEVICE_INVALID;
16016 /* make sure data is not null. Maybe unnecessary, but better be safe */
16017 host = ast_strdupa(data ? data : "");
16018 if ((tmp = strchr(host, '@')))
16019 host = tmp + 1;
16021 if (option_debug > 2)
16022 ast_log(LOG_DEBUG, "Checking device state for peer %s\n", host);
16024 if ((p = find_peer(host, NULL, 1))) {
16025 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
16026 /* we have an address for the peer */
16028 /* Check status in this order
16029 - Hold
16030 - Ringing
16031 - Busy (enforced only by call limit)
16032 - Inuse (we have a call)
16033 - Unreachable (qualify)
16034 If we don't find any of these state, report AST_DEVICE_NOT_INUSE
16035 for registered devices */
16037 if (p->onHold)
16038 /* First check for hold or ring states */
16039 res = AST_DEVICE_ONHOLD;
16040 else if (p->inRinging) {
16041 if (p->inRinging == p->inUse)
16042 res = AST_DEVICE_RINGING;
16043 else
16044 res = AST_DEVICE_RINGINUSE;
16045 } else if (p->call_limit && (p->inUse == p->call_limit))
16046 /* check call limit */
16047 res = AST_DEVICE_BUSY;
16048 else if (p->call_limit && p->inUse)
16049 /* Not busy, but we do have a call */
16050 res = AST_DEVICE_INUSE;
16051 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
16052 /* We don't have a call. Are we reachable at all? Requires qualify= */
16053 res = AST_DEVICE_UNAVAILABLE;
16054 else /* Default reply if we're registered and have no other data */
16055 res = AST_DEVICE_NOT_INUSE;
16056 } else {
16057 /* there is no address, it's unavailable */
16058 res = AST_DEVICE_UNAVAILABLE;
16060 ASTOBJ_UNREF(p,sip_destroy_peer);
16061 } else {
16062 char *port = strchr(host, ':');
16063 if (port)
16064 *port = '\0';
16065 hp = ast_gethostbyname(host, &ahp);
16066 if (hp)
16067 res = AST_DEVICE_UNKNOWN;
16070 return res;
16073 /*! \brief PBX interface function -build SIP pvt structure
16074 SIP calls initiated by the PBX arrive here */
16075 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
16077 int oldformat;
16078 struct sip_pvt *p;
16079 struct ast_channel *tmpc = NULL;
16080 char *ext, *host;
16081 char tmp[256];
16082 char *dest = data;
16084 oldformat = format;
16085 if (!(format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1))) {
16086 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));
16087 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL; /* Can't find codec to connect to host */
16088 return NULL;
16090 if (option_debug)
16091 ast_log(LOG_DEBUG, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
16093 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE))) {
16094 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", (char *)data);
16095 *cause = AST_CAUSE_SWITCH_CONGESTION;
16096 return NULL;
16099 ast_set_flag(&p->flags[1], SIP_PAGE2_OUTGOING_CALL);
16101 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
16102 sip_destroy(p);
16103 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
16104 *cause = AST_CAUSE_SWITCH_CONGESTION;
16105 return NULL;
16108 ast_copy_string(tmp, dest, sizeof(tmp));
16109 host = strchr(tmp, '@');
16110 if (host) {
16111 *host++ = '\0';
16112 ext = tmp;
16113 } else {
16114 ext = strchr(tmp, '/');
16115 if (ext)
16116 *ext++ = '\0';
16117 host = tmp;
16120 if (create_addr(p, host)) {
16121 *cause = AST_CAUSE_UNREGISTERED;
16122 if (option_debug > 2)
16123 ast_log(LOG_DEBUG, "Cant create SIP call - target device not registred\n");
16124 sip_destroy(p);
16125 return NULL;
16127 if (ast_strlen_zero(p->peername) && ext)
16128 ast_string_field_set(p, peername, ext);
16129 /* Recalculate our side, and recalculate Call ID */
16130 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
16131 p->ourip = __ourip;
16132 build_via(p);
16133 build_callid_pvt(p);
16135 /* We have an extension to call, don't use the full contact here */
16136 /* This to enable dialing registered peers with extension dialling,
16137 like SIP/peername/extension
16138 SIP/peername will still use the full contact */
16139 if (ext) {
16140 ast_string_field_set(p, username, ext);
16141 ast_string_field_free(p, fullcontact);
16143 #if 0
16144 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
16145 #endif
16146 p->prefcodec = oldformat; /* Format for this call */
16147 ast_mutex_lock(&p->lock);
16148 tmpc = sip_new(p, AST_STATE_DOWN, host); /* Place the call */
16149 ast_mutex_unlock(&p->lock);
16150 if (!tmpc)
16151 sip_destroy(p);
16152 ast_update_use_count();
16153 restart_monitor();
16154 return tmpc;
16158 * \brief Parse the "insecure" setting from sip.conf or from realtime.
16159 * \param flags a pointer to an ast_flags structure
16160 * \param value the value of the SIP insecure setting
16161 * \param lineno linenumber in sip.conf or -1 for realtime
16163 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno)
16165 static int dep_insecure_very = 0;
16166 static int dep_insecure_yes = 0;
16168 if (ast_strlen_zero(value))
16169 return;
16171 if (!strcasecmp(value, "very")) {
16172 ast_set_flag(flags, SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16173 if(!dep_insecure_very) {
16174 if(lineno != -1)
16175 ast_log(LOG_WARNING, "insecure=very at line %d is deprecated; use insecure=port,invite instead\n", lineno);
16176 else
16177 ast_log(LOG_WARNING, "insecure=very is deprecated; use insecure=port,invite instead\n");
16178 dep_insecure_very = 1;
16181 else if (ast_true(value)) {
16182 ast_set_flag(flags, SIP_INSECURE_PORT);
16183 if(!dep_insecure_yes) {
16184 if(lineno != -1)
16185 ast_log(LOG_WARNING, "insecure=%s at line %d is deprecated; use insecure=port instead\n", value, lineno);
16186 else
16187 ast_log(LOG_WARNING, "insecure=%s is deprecated; use insecure=port instead\n", value);
16188 dep_insecure_yes = 1;
16191 else if (!ast_false(value)) {
16192 char buf[64];
16193 char *word, *next;
16194 ast_copy_string(buf, value, sizeof(buf));
16195 next = buf;
16196 while ((word = strsep(&next, ","))) {
16197 if (!strcasecmp(word, "port"))
16198 ast_set_flag(flags, SIP_INSECURE_PORT);
16199 else if (!strcasecmp(word, "invite"))
16200 ast_set_flag(flags, SIP_INSECURE_INVITE);
16201 else
16202 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
16208 \brief Handle flag-type options common to configuration of devices - users and peers
16209 \param flags array of two struct ast_flags
16210 \param mask array of two struct ast_flags
16211 \param v linked list of config variables to process
16212 \returns non-zero if any config options were handled, zero otherwise
16214 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
16216 int res = 1;
16218 if (!strcasecmp(v->name, "trustrpid")) {
16219 ast_set_flag(&mask[0], SIP_TRUSTRPID);
16220 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
16221 } else if (!strcasecmp(v->name, "sendrpid")) {
16222 ast_set_flag(&mask[0], SIP_SENDRPID);
16223 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
16224 } else if (!strcasecmp(v->name, "g726nonstandard")) {
16225 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
16226 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
16227 } else if (!strcasecmp(v->name, "useclientcode")) {
16228 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
16229 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
16230 } else if (!strcasecmp(v->name, "dtmfmode")) {
16231 ast_set_flag(&mask[0], SIP_DTMF);
16232 ast_clear_flag(&flags[0], SIP_DTMF);
16233 if (!strcasecmp(v->value, "inband"))
16234 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
16235 else if (!strcasecmp(v->value, "rfc2833"))
16236 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
16237 else if (!strcasecmp(v->value, "info"))
16238 ast_set_flag(&flags[0], SIP_DTMF_INFO);
16239 else if (!strcasecmp(v->value, "auto"))
16240 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
16241 else {
16242 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
16243 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
16245 } else if (!strcasecmp(v->name, "nat")) {
16246 ast_set_flag(&mask[0], SIP_NAT);
16247 ast_clear_flag(&flags[0], SIP_NAT);
16248 if (!strcasecmp(v->value, "never"))
16249 ast_set_flag(&flags[0], SIP_NAT_NEVER);
16250 else if (!strcasecmp(v->value, "route"))
16251 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
16252 else if (ast_true(v->value))
16253 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
16254 else
16255 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
16256 } else if (!strcasecmp(v->name, "canreinvite")) {
16257 ast_set_flag(&mask[0], SIP_REINVITE);
16258 ast_clear_flag(&flags[0], SIP_REINVITE);
16259 if(ast_true(v->value)) {
16260 ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
16261 } else if (!ast_false(v->value)) {
16262 char buf[64];
16263 char *word, *next = buf;
16265 ast_copy_string(buf, v->value, sizeof(buf));
16266 while ((word = strsep(&next, ","))) {
16267 if(!strcasecmp(word, "update")) {
16268 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
16269 } else if(!strcasecmp(word, "nonat")) {
16270 ast_set_flag(&flags[0], SIP_CAN_REINVITE);
16271 ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
16272 } else {
16273 ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
16277 } else if (!strcasecmp(v->name, "insecure")) {
16278 ast_set_flag(&mask[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16279 ast_clear_flag(&flags[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16280 set_insecure_flags(flags, v->value, v->lineno);
16281 } else if (!strcasecmp(v->name, "progressinband")) {
16282 ast_set_flag(&mask[0], SIP_PROG_INBAND);
16283 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
16284 if (ast_true(v->value))
16285 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
16286 else if (strcasecmp(v->value, "never"))
16287 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
16288 } else if (!strcasecmp(v->name, "promiscredir")) {
16289 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
16290 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
16291 } else if (!strcasecmp(v->name, "videosupport")) {
16292 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
16293 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
16294 } else if (!strcasecmp(v->name, "allowoverlap")) {
16295 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
16296 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
16297 } else if (!strcasecmp(v->name, "allowsubscribe")) {
16298 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
16299 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
16300 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
16301 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_UDPTL);
16302 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_UDPTL);
16303 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
16304 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
16305 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_RTP);
16306 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_RTP);
16307 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
16308 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_TCP);
16309 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_TCP);
16310 #endif
16311 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
16312 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
16313 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
16314 } else if (!strcasecmp(v->name, "buggymwi")) {
16315 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
16316 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
16317 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
16318 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
16319 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
16320 } else
16321 res = 0;
16323 return res;
16326 /*! \brief Add SIP domain to list of domains we are responsible for */
16327 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
16329 struct domain *d;
16331 if (ast_strlen_zero(domain)) {
16332 ast_log(LOG_WARNING, "Zero length domain.\n");
16333 return 1;
16336 if (!(d = ast_calloc(1, sizeof(*d))))
16337 return 0;
16339 ast_copy_string(d->domain, domain, sizeof(d->domain));
16341 if (!ast_strlen_zero(context))
16342 ast_copy_string(d->context, context, sizeof(d->context));
16344 d->mode = mode;
16346 AST_LIST_LOCK(&domain_list);
16347 AST_LIST_INSERT_TAIL(&domain_list, d, list);
16348 AST_LIST_UNLOCK(&domain_list);
16350 if (sipdebug)
16351 ast_log(LOG_DEBUG, "Added local SIP domain '%s'\n", domain);
16353 return 1;
16356 /*! \brief check_sip_domain: Check if domain part of uri is local to our server */
16357 static int check_sip_domain(const char *domain, char *context, size_t len)
16359 struct domain *d;
16360 int result = 0;
16362 AST_LIST_LOCK(&domain_list);
16363 AST_LIST_TRAVERSE(&domain_list, d, list) {
16364 if (strcasecmp(d->domain, domain))
16365 continue;
16367 if (len && !ast_strlen_zero(d->context))
16368 ast_copy_string(context, d->context, len);
16370 result = 1;
16371 break;
16373 AST_LIST_UNLOCK(&domain_list);
16375 return result;
16378 /*! \brief Clear our domain list (at reload) */
16379 static void clear_sip_domains(void)
16381 struct domain *d;
16383 AST_LIST_LOCK(&domain_list);
16384 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
16385 free(d);
16386 AST_LIST_UNLOCK(&domain_list);
16390 /*! \brief Add realm authentication in list */
16391 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno)
16393 char authcopy[256];
16394 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
16395 char *stringp;
16396 struct sip_auth *a, *b, *auth;
16398 if (ast_strlen_zero(configuration))
16399 return authlist;
16401 if (option_debug)
16402 ast_log(LOG_DEBUG, "Auth config :: %s\n", configuration);
16404 ast_copy_string(authcopy, configuration, sizeof(authcopy));
16405 stringp = authcopy;
16407 username = stringp;
16408 realm = strrchr(stringp, '@');
16409 if (realm)
16410 *realm++ = '\0';
16411 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
16412 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
16413 return authlist;
16415 stringp = username;
16416 username = strsep(&stringp, ":");
16417 if (username) {
16418 secret = strsep(&stringp, ":");
16419 if (!secret) {
16420 stringp = username;
16421 md5secret = strsep(&stringp,"#");
16424 if (!(auth = ast_calloc(1, sizeof(*auth))))
16425 return authlist;
16427 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
16428 ast_copy_string(auth->username, username, sizeof(auth->username));
16429 if (secret)
16430 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
16431 if (md5secret)
16432 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
16434 /* find the end of the list */
16435 for (b = NULL, a = authlist; a ; b = a, a = a->next)
16437 if (b)
16438 b->next = auth; /* Add structure add end of list */
16439 else
16440 authlist = auth;
16442 if (option_verbose > 2)
16443 ast_verbose("Added authentication for realm %s\n", realm);
16445 return authlist;
16449 /*! \brief Clear realm authentication list (at reload) */
16450 static int clear_realm_authentication(struct sip_auth *authlist)
16452 struct sip_auth *a = authlist;
16453 struct sip_auth *b;
16455 while (a) {
16456 b = a;
16457 a = a->next;
16458 free(b);
16461 return 1;
16464 /*! \brief Find authentication for a specific realm */
16465 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
16467 struct sip_auth *a;
16469 for (a = authlist; a; a = a->next) {
16470 if (!strcasecmp(a->realm, realm))
16471 break;
16474 return a;
16477 /*! \brief Initiate a SIP user structure from configuration (configuration or realtime) */
16478 static struct sip_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
16480 struct sip_user *user;
16481 int format;
16482 struct ast_ha *oldha = NULL;
16483 char *varname = NULL, *varval = NULL;
16484 struct ast_variable *tmpvar = NULL;
16485 struct ast_flags userflags[2] = {{(0)}};
16486 struct ast_flags mask[2] = {{(0)}};
16489 if (!(user = ast_calloc(1, sizeof(*user))))
16490 return NULL;
16492 suserobjs++;
16493 ASTOBJ_INIT(user);
16494 ast_copy_string(user->name, name, sizeof(user->name));
16495 oldha = user->ha;
16496 user->ha = NULL;
16497 ast_copy_flags(&user->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
16498 ast_copy_flags(&user->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16499 user->capability = global_capability;
16500 user->allowtransfer = global_allowtransfer;
16501 user->maxcallbitrate = default_maxcallbitrate;
16502 user->autoframing = global_autoframing;
16503 user->prefs = default_prefs;
16504 /* set default context */
16505 strcpy(user->context, default_context);
16506 strcpy(user->language, default_language);
16507 strcpy(user->mohinterpret, default_mohinterpret);
16508 strcpy(user->mohsuggest, default_mohsuggest);
16509 /* First we walk through the v parameters list and then the alt parameters list */
16510 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
16511 if (handle_common_options(&userflags[0], &mask[0], v))
16512 continue;
16514 if (!strcasecmp(v->name, "context")) {
16515 ast_copy_string(user->context, v->value, sizeof(user->context));
16516 } else if (!strcasecmp(v->name, "subscribecontext")) {
16517 ast_copy_string(user->subscribecontext, v->value, sizeof(user->subscribecontext));
16518 } else if (!strcasecmp(v->name, "setvar")) {
16519 varname = ast_strdupa(v->value);
16520 if ((varval = strchr(varname,'='))) {
16521 *varval++ = '\0';
16522 if ((tmpvar = ast_variable_new(varname, varval))) {
16523 tmpvar->next = user->chanvars;
16524 user->chanvars = tmpvar;
16527 } else if (!strcasecmp(v->name, "permit") ||
16528 !strcasecmp(v->name, "deny")) {
16529 user->ha = ast_append_ha(v->name, v->value, user->ha);
16530 } else if (!strcasecmp(v->name, "allowtransfer")) {
16531 user->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
16532 } else if (!strcasecmp(v->name, "secret")) {
16533 ast_copy_string(user->secret, v->value, sizeof(user->secret));
16534 } else if (!strcasecmp(v->name, "md5secret")) {
16535 ast_copy_string(user->md5secret, v->value, sizeof(user->md5secret));
16536 } else if (!strcasecmp(v->name, "callerid")) {
16537 ast_callerid_split(v->value, user->cid_name, sizeof(user->cid_name), user->cid_num, sizeof(user->cid_num));
16538 } else if (!strcasecmp(v->name, "fullname")) {
16539 ast_copy_string(user->cid_name, v->value, sizeof(user->cid_name));
16540 } else if (!strcasecmp(v->name, "cid_number")) {
16541 ast_copy_string(user->cid_num, v->value, sizeof(user->cid_num));
16542 } else if (!strcasecmp(v->name, "callgroup")) {
16543 user->callgroup = ast_get_group(v->value);
16544 } else if (!strcasecmp(v->name, "pickupgroup")) {
16545 user->pickupgroup = ast_get_group(v->value);
16546 } else if (!strcasecmp(v->name, "language")) {
16547 ast_copy_string(user->language, v->value, sizeof(user->language));
16548 } else if (!strcasecmp(v->name, "mohinterpret")
16549 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
16550 ast_copy_string(user->mohinterpret, v->value, sizeof(user->mohinterpret));
16551 } else if (!strcasecmp(v->name, "mohsuggest")) {
16552 ast_copy_string(user->mohsuggest, v->value, sizeof(user->mohsuggest));
16553 } else if (!strcasecmp(v->name, "accountcode")) {
16554 ast_copy_string(user->accountcode, v->value, sizeof(user->accountcode));
16555 } else if (!strcasecmp(v->name, "call-limit")) {
16556 user->call_limit = atoi(v->value);
16557 if (user->call_limit < 0)
16558 user->call_limit = 0;
16559 } else if (!strcasecmp(v->name, "amaflags")) {
16560 format = ast_cdr_amaflags2int(v->value);
16561 if (format < 0) {
16562 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
16563 } else {
16564 user->amaflags = format;
16566 } else if (!strcasecmp(v->name, "allow")) {
16567 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
16568 } else if (!strcasecmp(v->name, "disallow")) {
16569 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 0);
16570 } else if (!strcasecmp(v->name, "autoframing")) {
16571 user->autoframing = ast_true(v->value);
16572 } else if (!strcasecmp(v->name, "callingpres")) {
16573 user->callingpres = ast_parse_caller_presentation(v->value);
16574 if (user->callingpres == -1)
16575 user->callingpres = atoi(v->value);
16576 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
16577 user->maxcallbitrate = atoi(v->value);
16578 if (user->maxcallbitrate < 0)
16579 user->maxcallbitrate = default_maxcallbitrate;
16581 /* We can't just report unknown options here because this may be a
16582 * type=friend entry. All user options are valid for a peer, but not
16583 * the other way around. */
16585 ast_copy_flags(&user->flags[0], &userflags[0], mask[0].flags);
16586 ast_copy_flags(&user->flags[1], &userflags[1], mask[1].flags);
16587 if (ast_test_flag(&user->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
16588 global_allowsubscribe = TRUE; /* No global ban any more */
16589 ast_free_ha(oldha);
16590 return user;
16593 /*! \brief Set peer defaults before configuring specific configurations */
16594 static void set_peer_defaults(struct sip_peer *peer)
16596 if (peer->expire == 0) {
16597 /* Don't reset expire or port time during reload
16598 if we have an active registration
16600 peer->expire = -1;
16601 peer->pokeexpire = -1;
16602 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
16604 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
16605 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16606 strcpy(peer->context, default_context);
16607 strcpy(peer->subscribecontext, default_subscribecontext);
16608 strcpy(peer->language, default_language);
16609 strcpy(peer->mohinterpret, default_mohinterpret);
16610 strcpy(peer->mohsuggest, default_mohsuggest);
16611 peer->addr.sin_family = AF_INET;
16612 peer->defaddr.sin_family = AF_INET;
16613 peer->capability = global_capability;
16614 peer->maxcallbitrate = default_maxcallbitrate;
16615 peer->rtptimeout = global_rtptimeout;
16616 peer->rtpholdtimeout = global_rtpholdtimeout;
16617 peer->rtpkeepalive = global_rtpkeepalive;
16618 peer->allowtransfer = global_allowtransfer;
16619 peer->autoframing = global_autoframing;
16620 strcpy(peer->vmexten, default_vmexten);
16621 peer->secret[0] = '\0';
16622 peer->md5secret[0] = '\0';
16623 peer->cid_num[0] = '\0';
16624 peer->cid_name[0] = '\0';
16625 peer->fromdomain[0] = '\0';
16626 peer->fromuser[0] = '\0';
16627 peer->regexten[0] = '\0';
16628 peer->mailbox[0] = '\0';
16629 peer->callgroup = 0;
16630 peer->pickupgroup = 0;
16631 peer->maxms = default_qualify;
16632 peer->prefs = default_prefs;
16635 /*! \brief Create temporary peer (used in autocreatepeer mode) */
16636 static struct sip_peer *temp_peer(const char *name)
16638 struct sip_peer *peer;
16640 if (!(peer = ast_calloc(1, sizeof(*peer))))
16641 return NULL;
16643 apeerobjs++;
16644 ASTOBJ_INIT(peer);
16645 set_peer_defaults(peer);
16647 ast_copy_string(peer->name, name, sizeof(peer->name));
16649 ast_set_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT);
16650 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
16651 peer->prefs = default_prefs;
16652 reg_source_db(peer);
16654 return peer;
16657 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
16658 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
16660 struct sip_peer *peer = NULL;
16661 struct ast_ha *oldha = NULL;
16662 int obproxyfound=0;
16663 int found=0;
16664 int firstpass=1;
16665 int format=0; /* Ama flags */
16666 time_t regseconds = 0;
16667 char *varname = NULL, *varval = NULL;
16668 struct ast_variable *tmpvar = NULL;
16669 struct ast_flags peerflags[2] = {{(0)}};
16670 struct ast_flags mask[2] = {{(0)}};
16671 char fullcontact[sizeof(peer->fullcontact)] = "";
16673 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))
16674 /* Note we do NOT use find_peer here, to avoid realtime recursion */
16675 /* We also use a case-sensitive comparison (unlike find_peer) so
16676 that case changes made to the peer name will be properly handled
16677 during reload
16679 peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);
16681 if (peer) {
16682 /* Already in the list, remove it and it will be added back (or FREE'd) */
16683 found = 1;
16684 if (!(peer->objflags & ASTOBJ_FLAG_MARKED))
16685 firstpass = 0;
16686 } else {
16687 if (!(peer = ast_calloc(1, sizeof(*peer))))
16688 return NULL;
16690 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))
16691 rpeerobjs++;
16692 else
16693 speerobjs++;
16694 ASTOBJ_INIT(peer);
16696 /* Note that our peer HAS had its reference count incrased */
16697 if (firstpass) {
16698 peer->lastmsgssent = -1;
16699 oldha = peer->ha;
16700 peer->ha = NULL;
16701 set_peer_defaults(peer); /* Set peer defaults */
16703 if (!found && name)
16704 ast_copy_string(peer->name, name, sizeof(peer->name));
16706 /* If we have channel variables, remove them (reload) */
16707 if (peer->chanvars) {
16708 ast_variables_destroy(peer->chanvars);
16709 peer->chanvars = NULL;
16710 /* XXX should unregister ? */
16713 /* If we have realm authentication information, remove them (reload) */
16714 clear_realm_authentication(peer->auth);
16715 peer->auth = NULL;
16717 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
16718 if (handle_common_options(&peerflags[0], &mask[0], v))
16719 continue;
16720 if (realtime && !strcasecmp(v->name, "regseconds")) {
16721 ast_get_time_t(v->value, &regseconds, 0, NULL);
16722 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
16723 inet_aton(v->value, &(peer->addr.sin_addr));
16724 } else if (realtime && !strcasecmp(v->name, "name"))
16725 ast_copy_string(peer->name, v->value, sizeof(peer->name));
16726 else if (realtime && !strcasecmp(v->name, "fullcontact")) {
16727 /* Reconstruct field, because realtime separates our value at the ';' */
16728 if (!ast_strlen_zero(fullcontact)) {
16729 strncat(fullcontact, ";", sizeof(fullcontact) - strlen(fullcontact) - 1);
16730 strncat(fullcontact, v->value, sizeof(fullcontact) - strlen(fullcontact) - 1);
16731 } else {
16732 ast_copy_string(fullcontact, v->value, sizeof(fullcontact));
16733 ast_set_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT);
16735 } else if (!strcasecmp(v->name, "secret"))
16736 ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
16737 else if (!strcasecmp(v->name, "md5secret"))
16738 ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
16739 else if (!strcasecmp(v->name, "auth"))
16740 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
16741 else if (!strcasecmp(v->name, "callerid")) {
16742 ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
16743 } else if (!strcasecmp(v->name, "fullname")) {
16744 ast_copy_string(peer->cid_name, v->value, sizeof(peer->cid_name));
16745 } else if (!strcasecmp(v->name, "cid_number")) {
16746 ast_copy_string(peer->cid_num, v->value, sizeof(peer->cid_num));
16747 } else if (!strcasecmp(v->name, "context")) {
16748 ast_copy_string(peer->context, v->value, sizeof(peer->context));
16749 } else if (!strcasecmp(v->name, "subscribecontext")) {
16750 ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
16751 } else if (!strcasecmp(v->name, "fromdomain")) {
16752 ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
16753 } else if (!strcasecmp(v->name, "usereqphone")) {
16754 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
16755 } else if (!strcasecmp(v->name, "fromuser")) {
16756 ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
16757 } else if (!strcasecmp(v->name, "host") || !strcasecmp(v->name, "outboundproxy")) {
16758 if (!strcasecmp(v->value, "dynamic")) {
16759 if (!strcasecmp(v->name, "outboundproxy") || obproxyfound) {
16760 ast_log(LOG_WARNING, "You can't have a dynamic outbound proxy, you big silly head at line %d.\n", v->lineno);
16761 } else {
16762 /* They'll register with us */
16763 if (!found || !ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
16764 /* Initialize stuff if this is a new peer, or if it used to be
16765 * non-dynamic before the reload. */
16766 memset(&peer->addr.sin_addr, 0, 4);
16767 if (peer->addr.sin_port) {
16768 /* If we've already got a port, make it the default rather than absolute */
16769 peer->defaddr.sin_port = peer->addr.sin_port;
16770 peer->addr.sin_port = 0;
16773 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
16775 } else {
16776 /* Non-dynamic. Make sure we become that way if we're not */
16777 if (!AST_SCHED_DEL(sched, peer->expire)) {
16778 struct sip_peer *peer_ptr = peer;
16779 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
16781 ast_clear_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
16782 if (!obproxyfound || !strcasecmp(v->name, "outboundproxy")) {
16783 if (ast_get_ip_or_srv(&peer->addr, v->value, srvlookup ? "_sip._udp" : NULL)) {
16784 ASTOBJ_UNREF(peer, sip_destroy_peer);
16785 return NULL;
16788 if (!strcasecmp(v->name, "outboundproxy"))
16789 obproxyfound=1;
16790 else {
16791 ast_copy_string(peer->tohost, v->value, sizeof(peer->tohost));
16792 if (!peer->addr.sin_port)
16793 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
16796 } else if (!strcasecmp(v->name, "defaultip")) {
16797 if (ast_get_ip(&peer->defaddr, v->value)) {
16798 ASTOBJ_UNREF(peer, sip_destroy_peer);
16799 return NULL;
16801 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
16802 peer->ha = ast_append_ha(v->name, v->value, peer->ha);
16803 } else if (!strcasecmp(v->name, "port")) {
16804 if (!realtime && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC))
16805 peer->defaddr.sin_port = htons(atoi(v->value));
16806 else
16807 peer->addr.sin_port = htons(atoi(v->value));
16808 } else if (!strcasecmp(v->name, "callingpres")) {
16809 peer->callingpres = ast_parse_caller_presentation(v->value);
16810 if (peer->callingpres == -1)
16811 peer->callingpres = atoi(v->value);
16812 } else if (!strcasecmp(v->name, "username")) {
16813 ast_copy_string(peer->username, v->value, sizeof(peer->username));
16814 } else if (!strcasecmp(v->name, "language")) {
16815 ast_copy_string(peer->language, v->value, sizeof(peer->language));
16816 } else if (!strcasecmp(v->name, "regexten")) {
16817 ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
16818 } else if (!strcasecmp(v->name, "call-limit") || !strcasecmp(v->name, "incominglimit")) {
16819 peer->call_limit = atoi(v->value);
16820 if (peer->call_limit < 0)
16821 peer->call_limit = 0;
16822 } else if (!strcasecmp(v->name, "amaflags")) {
16823 format = ast_cdr_amaflags2int(v->value);
16824 if (format < 0) {
16825 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
16826 } else {
16827 peer->amaflags = format;
16829 } else if (!strcasecmp(v->name, "accountcode")) {
16830 ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
16831 } else if (!strcasecmp(v->name, "mohinterpret")
16832 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
16833 ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
16834 } else if (!strcasecmp(v->name, "mohsuggest")) {
16835 ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
16836 } else if (!strcasecmp(v->name, "mailbox")) {
16837 ast_copy_string(peer->mailbox, v->value, sizeof(peer->mailbox));
16838 } else if (!strcasecmp(v->name, "subscribemwi")) {
16839 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
16840 } else if (!strcasecmp(v->name, "vmexten")) {
16841 ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
16842 } else if (!strcasecmp(v->name, "callgroup")) {
16843 peer->callgroup = ast_get_group(v->value);
16844 } else if (!strcasecmp(v->name, "allowtransfer")) {
16845 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
16846 } else if (!strcasecmp(v->name, "pickupgroup")) {
16847 peer->pickupgroup = ast_get_group(v->value);
16848 } else if (!strcasecmp(v->name, "allow")) {
16849 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
16850 } else if (!strcasecmp(v->name, "disallow")) {
16851 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
16852 } else if (!strcasecmp(v->name, "autoframing")) {
16853 peer->autoframing = ast_true(v->value);
16854 } else if (!strcasecmp(v->name, "rtptimeout")) {
16855 if ((sscanf(v->value, "%d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
16856 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16857 peer->rtptimeout = global_rtptimeout;
16859 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
16860 if ((sscanf(v->value, "%d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
16861 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16862 peer->rtpholdtimeout = global_rtpholdtimeout;
16864 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
16865 if ((sscanf(v->value, "%d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
16866 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
16867 peer->rtpkeepalive = global_rtpkeepalive;
16869 } else if (!strcasecmp(v->name, "setvar")) {
16870 /* Set peer channel variable */
16871 varname = ast_strdupa(v->value);
16872 if ((varval = strchr(varname, '='))) {
16873 *varval++ = '\0';
16874 if ((tmpvar = ast_variable_new(varname, varval))) {
16875 tmpvar->next = peer->chanvars;
16876 peer->chanvars = tmpvar;
16879 } else if (!strcasecmp(v->name, "qualify")) {
16880 if (!strcasecmp(v->value, "no")) {
16881 peer->maxms = 0;
16882 } else if (!strcasecmp(v->value, "yes")) {
16883 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
16884 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
16885 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);
16886 peer->maxms = 0;
16888 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
16889 peer->maxcallbitrate = atoi(v->value);
16890 if (peer->maxcallbitrate < 0)
16891 peer->maxcallbitrate = default_maxcallbitrate;
16894 if (!ast_strlen_zero(fullcontact)) {
16895 ast_copy_string(peer->fullcontact, fullcontact, sizeof(peer->fullcontact));
16898 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && realtime) {
16899 time_t nowtime = time(NULL);
16901 if ((nowtime - regseconds) > 0) {
16902 destroy_association(peer);
16903 memset(&peer->addr, 0, sizeof(peer->addr));
16904 if (option_debug)
16905 ast_log(LOG_DEBUG, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
16908 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
16909 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
16910 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
16911 global_allowsubscribe = TRUE; /* No global ban any more */
16912 if (!found && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && !ast_test_flag(&peer->flags[0], SIP_REALTIME))
16913 reg_source_db(peer);
16914 ASTOBJ_UNMARK(peer);
16915 ast_free_ha(oldha);
16916 return peer;
16919 /*! \brief Re-read SIP.conf config file
16920 \note This function reloads all config data, except for
16921 active peers (with registrations). They will only
16922 change configuration data at restart, not at reload.
16923 SIP debug and recordhistory state will not change
16925 static int reload_config(enum channelreloadreason reason)
16927 struct ast_config *cfg, *ucfg;
16928 struct ast_variable *v;
16929 struct sip_peer *peer;
16930 struct sip_user *user;
16931 struct ast_hostent ahp;
16932 char *cat, *stringp, *context, *oldregcontext;
16933 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
16934 struct hostent *hp;
16935 int format;
16936 struct ast_flags dummy[2];
16937 int auto_sip_domains = FALSE;
16938 struct sockaddr_in old_bindaddr = bindaddr;
16939 int registry_count = 0, peer_count = 0, user_count = 0;
16940 unsigned int temp_tos = 0;
16941 struct ast_flags debugflag = {0};
16943 cfg = ast_config_load(config);
16945 /* We *must* have a config file otherwise stop immediately */
16946 if (!cfg) {
16947 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
16948 return -1;
16951 if (option_debug > 3)
16952 ast_log(LOG_DEBUG, "--------------- SIP reload started\n");
16954 clear_realm_authentication(authl);
16955 clear_sip_domains();
16956 authl = NULL;
16958 /* First, destroy all outstanding registry calls */
16959 /* This is needed, since otherwise active registry entries will not be destroyed */
16960 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
16961 ASTOBJ_RDLOCK(iterator);
16962 if (iterator->call) {
16963 if (option_debug > 2)
16964 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
16965 /* This will also remove references to the registry */
16966 sip_destroy(iterator->call);
16968 ASTOBJ_UNLOCK(iterator);
16970 } while(0));
16972 /* Then, actually destroy users and registry */
16973 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
16974 if (option_debug > 3)
16975 ast_log(LOG_DEBUG, "--------------- Done destroying user list\n");
16976 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
16977 if (option_debug > 3)
16978 ast_log(LOG_DEBUG, "--------------- Done destroying registry list\n");
16979 ASTOBJ_CONTAINER_MARKALL(&peerl);
16981 /* Initialize copy of current global_regcontext for later use in removing stale contexts */
16982 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
16983 oldregcontext = oldcontexts;
16985 /* Clear all flags before setting default values */
16986 /* Preserve debugging settings for console */
16987 ast_copy_flags(&debugflag, &global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
16988 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
16989 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
16990 ast_copy_flags(&global_flags[1], &debugflag, SIP_PAGE2_DEBUG_CONSOLE);
16992 /* Reset IP addresses */
16993 memset(&bindaddr, 0, sizeof(bindaddr));
16994 ast_free_ha(localaddr);
16995 memset(&localaddr, 0, sizeof(localaddr));
16996 memset(&externip, 0, sizeof(externip));
16997 memset(&default_prefs, 0 , sizeof(default_prefs));
16998 outboundproxyip.sin_port = htons(STANDARD_SIP_PORT);
16999 outboundproxyip.sin_family = AF_INET; /* Type of address: IPv4 */
17000 ourport = STANDARD_SIP_PORT;
17001 srvlookup = DEFAULT_SRVLOOKUP;
17002 global_tos_sip = DEFAULT_TOS_SIP;
17003 global_tos_audio = DEFAULT_TOS_AUDIO;
17004 global_tos_video = DEFAULT_TOS_VIDEO;
17005 externhost[0] = '\0'; /* External host name (for behind NAT DynDNS support) */
17006 externexpire = 0; /* Expiration for DNS re-issuing */
17007 externrefresh = 10;
17008 memset(&outboundproxyip, 0, sizeof(outboundproxyip));
17010 /* Reset channel settings to default before re-configuring */
17011 allow_external_domains = DEFAULT_ALLOW_EXT_DOM; /* Allow external invites */
17012 global_regcontext[0] = '\0';
17013 expiry = DEFAULT_EXPIRY;
17014 global_notifyringing = DEFAULT_NOTIFYRINGING;
17015 global_limitonpeers = FALSE;
17016 global_directrtpsetup = FALSE; /* Experimental feature, disabled by default */
17017 global_notifyhold = FALSE;
17018 global_alwaysauthreject = 0;
17019 global_allowsubscribe = FALSE;
17020 ast_copy_string(global_useragent, DEFAULT_USERAGENT, sizeof(global_useragent));
17021 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
17022 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME))
17023 ast_copy_string(global_realm, DEFAULT_REALM, sizeof(global_realm));
17024 else
17025 ast_copy_string(global_realm, ast_config_AST_SYSTEM_NAME, sizeof(global_realm));
17026 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
17027 compactheaders = DEFAULT_COMPACTHEADERS;
17028 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
17029 global_regattempts_max = 0;
17030 pedanticsipchecking = DEFAULT_PEDANTIC;
17031 global_mwitime = DEFAULT_MWITIME;
17032 autocreatepeer = DEFAULT_AUTOCREATEPEER;
17033 global_autoframing = 0;
17034 global_allowguest = DEFAULT_ALLOWGUEST;
17035 global_rtptimeout = 0;
17036 global_rtpholdtimeout = 0;
17037 global_rtpkeepalive = 0;
17038 global_allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
17039 global_rtautoclear = 120;
17040 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE); /* Default for peers, users: TRUE */
17041 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP); /* Default for peers, users: TRUE */
17042 ast_set_flag(&global_flags[1], SIP_PAGE2_RTUPDATE);
17044 /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for peers and users */
17045 ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
17046 default_subscribecontext[0] = '\0';
17047 default_language[0] = '\0';
17048 default_fromdomain[0] = '\0';
17049 default_qualify = DEFAULT_QUALIFY;
17050 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
17051 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
17052 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
17053 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
17054 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833); /*!< Default DTMF setting: RFC2833 */
17055 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581); /*!< NAT support if requested by device with rport */
17056 ast_set_flag(&global_flags[0], SIP_CAN_REINVITE); /*!< Allow re-invites */
17058 /* Debugging settings, always default to off */
17059 dumphistory = FALSE;
17060 recordhistory = FALSE;
17061 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
17063 /* Misc settings for the channel */
17064 global_relaxdtmf = FALSE;
17065 global_callevents = FALSE;
17066 global_t1min = DEFAULT_T1MIN;
17068 global_matchexterniplocally = FALSE;
17070 /* Copy the default jb config over global_jbconf */
17071 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
17073 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT);
17075 /* Read the [general] config section of sip.conf (or from realtime config) */
17076 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
17077 if (handle_common_options(&global_flags[0], &dummy[0], v))
17078 continue;
17079 /* handle jb conf */
17080 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
17081 continue;
17083 /* Create the interface list */
17084 if (!strcasecmp(v->name, "context")) {
17085 ast_copy_string(default_context, v->value, sizeof(default_context));
17086 } else if (!strcasecmp(v->name, "subscribecontext")) {
17087 ast_copy_string(default_subscribecontext, v->value, sizeof(default_subscribecontext));
17088 } else if (!strcasecmp(v->name, "allowguest")) {
17089 global_allowguest = ast_true(v->value) ? 1 : 0;
17090 } else if (!strcasecmp(v->name, "realm")) {
17091 ast_copy_string(global_realm, v->value, sizeof(global_realm));
17092 } else if (!strcasecmp(v->name, "useragent")) {
17093 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
17094 if (option_debug)
17095 ast_log(LOG_DEBUG, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
17096 } else if (!strcasecmp(v->name, "allowtransfer")) {
17097 global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
17098 } else if (!strcasecmp(v->name, "rtcachefriends")) {
17099 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
17100 } else if (!strcasecmp(v->name, "rtsavesysname")) {
17101 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTSAVE_SYSNAME);
17102 } else if (!strcasecmp(v->name, "rtupdate")) {
17103 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTUPDATE);
17104 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
17105 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_IGNOREREGEXPIRE);
17106 } else if (!strcasecmp(v->name, "t1min")) {
17107 global_t1min = atoi(v->value);
17108 } else if (!strcasecmp(v->name, "rtautoclear")) {
17109 int i = atoi(v->value);
17110 if (i > 0)
17111 global_rtautoclear = i;
17112 else
17113 i = 0;
17114 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
17115 } else if (!strcasecmp(v->name, "usereqphone")) {
17116 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
17117 } else if (!strcasecmp(v->name, "relaxdtmf")) {
17118 global_relaxdtmf = ast_true(v->value);
17119 } else if (!strcasecmp(v->name, "checkmwi")) {
17120 if ((sscanf(v->value, "%d", &global_mwitime) != 1) || (global_mwitime < 0)) {
17121 ast_log(LOG_WARNING, "'%s' is not a valid MWI time setting at line %d. Using default (10).\n", v->value, v->lineno);
17122 global_mwitime = DEFAULT_MWITIME;
17124 } else if (!strcasecmp(v->name, "vmexten")) {
17125 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
17126 } else if (!strcasecmp(v->name, "rtptimeout")) {
17127 if ((sscanf(v->value, "%d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
17128 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
17129 global_rtptimeout = 0;
17131 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
17132 if ((sscanf(v->value, "%d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
17133 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
17134 global_rtpholdtimeout = 0;
17136 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
17137 if ((sscanf(v->value, "%d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
17138 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
17139 global_rtpkeepalive = 0;
17141 } else if (!strcasecmp(v->name, "compactheaders")) {
17142 compactheaders = ast_true(v->value);
17143 } else if (!strcasecmp(v->name, "notifymimetype")) {
17144 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
17145 } else if (!strncasecmp(v->name, "limitonpeer", 11)) {
17146 global_limitonpeers = ast_true(v->value);
17147 } else if (!strcasecmp(v->name, "directrtpsetup")) {
17148 global_directrtpsetup = ast_true(v->value);
17149 } else if (!strcasecmp(v->name, "notifyringing")) {
17150 global_notifyringing = ast_true(v->value);
17151 } else if (!strcasecmp(v->name, "notifyhold")) {
17152 global_notifyhold = ast_true(v->value);
17153 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
17154 global_alwaysauthreject = ast_true(v->value);
17155 } else if (!strcasecmp(v->name, "mohinterpret")
17156 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
17157 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
17158 } else if (!strcasecmp(v->name, "mohsuggest")) {
17159 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
17160 } else if (!strcasecmp(v->name, "language")) {
17161 ast_copy_string(default_language, v->value, sizeof(default_language));
17162 } else if (!strcasecmp(v->name, "regcontext")) {
17163 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
17164 stringp = newcontexts;
17165 /* Let's remove any contexts that are no longer defined in regcontext */
17166 cleanup_stale_contexts(stringp, oldregcontext);
17167 /* Create contexts if they don't exist already */
17168 while ((context = strsep(&stringp, "&"))) {
17169 if (!ast_context_find(context))
17170 ast_context_create(NULL, context,"SIP");
17172 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
17173 } else if (!strcasecmp(v->name, "callerid")) {
17174 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
17175 } else if (!strcasecmp(v->name, "fromdomain")) {
17176 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
17177 } else if (!strcasecmp(v->name, "outboundproxy")) {
17178 if (ast_get_ip_or_srv(&outboundproxyip, v->value, srvlookup ? "_sip._udp" : NULL) < 0)
17179 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", v->value);
17180 } else if (!strcasecmp(v->name, "outboundproxyport")) {
17181 /* Port needs to be after IP */
17182 sscanf(v->value, "%d", &format);
17183 outboundproxyip.sin_port = htons(format);
17184 } else if (!strcasecmp(v->name, "autocreatepeer")) {
17185 autocreatepeer = ast_true(v->value);
17186 } else if (!strcasecmp(v->name, "srvlookup")) {
17187 srvlookup = ast_true(v->value);
17188 } else if (!strcasecmp(v->name, "pedantic")) {
17189 pedanticsipchecking = ast_true(v->value);
17190 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
17191 max_expiry = atoi(v->value);
17192 if (max_expiry < 1)
17193 max_expiry = DEFAULT_MAX_EXPIRY;
17194 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
17195 min_expiry = atoi(v->value);
17196 if (min_expiry < 1)
17197 min_expiry = DEFAULT_MIN_EXPIRY;
17198 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
17199 default_expiry = atoi(v->value);
17200 if (default_expiry < 1)
17201 default_expiry = DEFAULT_DEFAULT_EXPIRY;
17202 } else if (!strcasecmp(v->name, "sipdebug")) { /* XXX maybe ast_set2_flags ? */
17203 if (ast_true(v->value))
17204 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
17205 } else if (!strcasecmp(v->name, "dumphistory")) {
17206 dumphistory = ast_true(v->value);
17207 } else if (!strcasecmp(v->name, "recordhistory")) {
17208 recordhistory = ast_true(v->value);
17209 } else if (!strcasecmp(v->name, "registertimeout")) {
17210 global_reg_timeout = atoi(v->value);
17211 if (global_reg_timeout < 1)
17212 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
17213 } else if (!strcasecmp(v->name, "registerattempts")) {
17214 global_regattempts_max = atoi(v->value);
17215 } else if (!strcasecmp(v->name, "bindaddr")) {
17216 if (!(hp = ast_gethostbyname(v->value, &ahp))) {
17217 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
17218 } else {
17219 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
17221 } else if (!strcasecmp(v->name, "localnet")) {
17222 struct ast_ha *na;
17223 if (!(na = ast_append_ha("d", v->value, localaddr)))
17224 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
17225 else
17226 localaddr = na;
17227 } else if (!strcasecmp(v->name, "localmask")) {
17228 ast_log(LOG_WARNING, "Use of localmask is no long supported -- use localnet with mask syntax\n");
17229 } else if (!strcasecmp(v->name, "externip")) {
17230 if (!(hp = ast_gethostbyname(v->value, &ahp)))
17231 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
17232 else
17233 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
17234 externexpire = 0;
17235 } else if (!strcasecmp(v->name, "externhost")) {
17236 ast_copy_string(externhost, v->value, sizeof(externhost));
17237 if (!(hp = ast_gethostbyname(externhost, &ahp)))
17238 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
17239 else
17240 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
17241 externexpire = time(NULL);
17242 } else if (!strcasecmp(v->name, "externrefresh")) {
17243 if (sscanf(v->value, "%d", &externrefresh) != 1) {
17244 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
17245 externrefresh = 10;
17247 } else if (!strcasecmp(v->name, "allow")) {
17248 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 1);
17249 } else if (!strcasecmp(v->name, "disallow")) {
17250 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 0);
17251 } else if (!strcasecmp(v->name, "autoframing")) {
17252 global_autoframing = ast_true(v->value);
17253 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
17254 allow_external_domains = ast_true(v->value);
17255 } else if (!strcasecmp(v->name, "autodomain")) {
17256 auto_sip_domains = ast_true(v->value);
17257 } else if (!strcasecmp(v->name, "domain")) {
17258 char *domain = ast_strdupa(v->value);
17259 char *context = strchr(domain, ',');
17261 if (context)
17262 *context++ = '\0';
17264 if (option_debug && ast_strlen_zero(context))
17265 ast_log(LOG_DEBUG, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
17266 if (ast_strlen_zero(domain))
17267 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
17268 else
17269 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, context ? ast_strip(context) : "");
17270 } else if (!strcasecmp(v->name, "register")) {
17271 if (sip_register(v->value, v->lineno) == 0)
17272 registry_count++;
17273 } else if (!strcasecmp(v->name, "tos")) {
17274 if (!ast_str2tos(v->value, &temp_tos)) {
17275 global_tos_sip = temp_tos;
17276 global_tos_audio = temp_tos;
17277 global_tos_video = temp_tos;
17278 ast_log(LOG_WARNING, "tos value at line %d is deprecated. See doc/ip-tos.txt for more information.\n", v->lineno);
17279 } else
17280 ast_log(LOG_WARNING, "Invalid tos value at line %d, See doc/ip-tos.txt for more information.\n", v->lineno);
17281 } else if (!strcasecmp(v->name, "tos_sip")) {
17282 if (ast_str2tos(v->value, &global_tos_sip))
17283 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, recommended value is 'cs3'. See doc/ip-tos.txt.\n", v->lineno);
17284 } else if (!strcasecmp(v->name, "tos_audio")) {
17285 if (ast_str2tos(v->value, &global_tos_audio))
17286 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, recommended value is 'ef'. See doc/ip-tos.txt.\n", v->lineno);
17287 } else if (!strcasecmp(v->name, "tos_video")) {
17288 if (ast_str2tos(v->value, &global_tos_video))
17289 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, recommended value is 'af41'. See doc/ip-tos.txt.\n", v->lineno);
17290 } else if (!strcasecmp(v->name, "bindport")) {
17291 if (sscanf(v->value, "%d", &ourport) == 1) {
17292 bindaddr.sin_port = htons(ourport);
17293 } else {
17294 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
17296 } else if (!strcasecmp(v->name, "qualify")) {
17297 if (!strcasecmp(v->value, "no")) {
17298 default_qualify = 0;
17299 } else if (!strcasecmp(v->value, "yes")) {
17300 default_qualify = DEFAULT_MAXMS;
17301 } else if (sscanf(v->value, "%d", &default_qualify) != 1) {
17302 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
17303 default_qualify = 0;
17305 } else if (!strcasecmp(v->name, "callevents")) {
17306 global_callevents = ast_true(v->value);
17307 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
17308 default_maxcallbitrate = atoi(v->value);
17309 if (default_maxcallbitrate < 0)
17310 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
17311 } else if (!strcasecmp(v->name, "matchexterniplocally")) {
17312 global_matchexterniplocally = ast_true(v->value);
17316 if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
17317 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
17318 allow_external_domains = 1;
17321 /* Build list of authentication to various SIP realms, i.e. service providers */
17322 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
17323 /* Format for authentication is auth = username:password@realm */
17324 if (!strcasecmp(v->name, "auth"))
17325 authl = add_realm_authentication(authl, v->value, v->lineno);
17328 ucfg = ast_config_load("users.conf");
17329 if (ucfg) {
17330 struct ast_variable *gen;
17331 int genhassip, genregistersip;
17332 const char *hassip, *registersip;
17334 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
17335 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
17336 gen = ast_variable_browse(ucfg, "general");
17337 cat = ast_category_browse(ucfg, NULL);
17338 while (cat) {
17339 if (strcasecmp(cat, "general")) {
17340 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
17341 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
17342 if (ast_true(hassip) || (!hassip && genhassip)) {
17343 user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
17344 if (user) {
17345 ASTOBJ_CONTAINER_LINK(&userl,user);
17346 ASTOBJ_UNREF(user, sip_destroy_user);
17347 user_count++;
17349 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
17350 if (peer) {
17351 ast_device_state_changed("SIP/%s", peer->name);
17352 ASTOBJ_CONTAINER_LINK(&peerl,peer);
17353 ASTOBJ_UNREF(peer, sip_destroy_peer);
17354 peer_count++;
17357 if (ast_true(registersip) || (!registersip && genregistersip)) {
17358 char tmp[256];
17359 const char *host = ast_variable_retrieve(ucfg, cat, "host");
17360 const char *username = ast_variable_retrieve(ucfg, cat, "username");
17361 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
17362 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
17363 if (!host)
17364 host = ast_variable_retrieve(ucfg, "general", "host");
17365 if (!username)
17366 username = ast_variable_retrieve(ucfg, "general", "username");
17367 if (!secret)
17368 secret = ast_variable_retrieve(ucfg, "general", "secret");
17369 if (!contact)
17370 contact = "s";
17371 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
17372 if (!ast_strlen_zero(secret))
17373 snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
17374 else
17375 snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
17376 if (sip_register(tmp, 0) == 0)
17377 registry_count++;
17381 cat = ast_category_browse(ucfg, cat);
17383 ast_config_destroy(ucfg);
17387 /* Load peers, users and friends */
17388 cat = NULL;
17389 while ( (cat = ast_category_browse(cfg, cat)) ) {
17390 const char *utype;
17391 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
17392 continue;
17393 utype = ast_variable_retrieve(cfg, cat, "type");
17394 if (!utype) {
17395 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
17396 continue;
17397 } else {
17398 int is_user = 0, is_peer = 0;
17399 if (!strcasecmp(utype, "user"))
17400 is_user = 1;
17401 else if (!strcasecmp(utype, "friend"))
17402 is_user = is_peer = 1;
17403 else if (!strcasecmp(utype, "peer"))
17404 is_peer = 1;
17405 else {
17406 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
17407 continue;
17409 if (is_user) {
17410 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
17411 if (user) {
17412 ASTOBJ_CONTAINER_LINK(&userl,user);
17413 ASTOBJ_UNREF(user, sip_destroy_user);
17414 user_count++;
17417 if (is_peer) {
17418 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
17419 if (peer) {
17420 ASTOBJ_CONTAINER_LINK(&peerl,peer);
17421 ASTOBJ_UNREF(peer, sip_destroy_peer);
17422 peer_count++;
17427 if (ast_find_ourip(&__ourip, bindaddr)) {
17428 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
17429 ast_config_destroy(cfg);
17430 return 0;
17432 if (!ntohs(bindaddr.sin_port))
17433 bindaddr.sin_port = ntohs(STANDARD_SIP_PORT);
17434 bindaddr.sin_family = AF_INET;
17435 ast_mutex_lock(&netlock);
17436 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
17437 close(sipsock);
17438 sipsock = -1;
17440 if (sipsock < 0) {
17441 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
17442 if (sipsock < 0) {
17443 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
17444 ast_config_destroy(cfg);
17445 return -1;
17446 } else {
17447 /* Allow SIP clients on the same host to access us: */
17448 const int reuseFlag = 1;
17450 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
17451 (const char*)&reuseFlag,
17452 sizeof reuseFlag);
17454 ast_enable_packet_fragmentation(sipsock);
17456 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
17457 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
17458 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
17459 strerror(errno));
17460 close(sipsock);
17461 sipsock = -1;
17462 } else {
17463 if (option_verbose > 1) {
17464 ast_verbose(VERBOSE_PREFIX_2 "SIP Listening on %s:%d\n",
17465 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
17466 ast_verbose(VERBOSE_PREFIX_2 "Using SIP TOS: %s\n", ast_tos2str(global_tos_sip));
17468 if (setsockopt(sipsock, IPPROTO_IP, IP_TOS, &global_tos_sip, sizeof(global_tos_sip)))
17469 ast_log(LOG_WARNING, "Unable to set SIP TOS to %s\n", ast_tos2str(global_tos_sip));
17473 ast_mutex_unlock(&netlock);
17475 /* Add default domains - host name, IP address and IP:port */
17476 /* Only do this if user added any sip domain with "localdomains" */
17477 /* In order to *not* break backwards compatibility */
17478 /* Some phones address us at IP only, some with additional port number */
17479 if (auto_sip_domains) {
17480 char temp[MAXHOSTNAMELEN];
17482 /* First our default IP address */
17483 if (bindaddr.sin_addr.s_addr)
17484 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
17485 else
17486 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
17488 /* Our extern IP address, if configured */
17489 if (externip.sin_addr.s_addr)
17490 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
17492 /* Extern host name (NAT traversal support) */
17493 if (!ast_strlen_zero(externhost))
17494 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
17496 /* Our host name */
17497 if (!gethostname(temp, sizeof(temp)))
17498 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
17501 /* Release configuration from memory */
17502 ast_config_destroy(cfg);
17504 /* Load the list of manual NOTIFY types to support */
17505 if (notify_types)
17506 ast_config_destroy(notify_types);
17507 notify_types = ast_config_load(notify_config);
17509 /* Done, tell the manager */
17510 manager_event(EVENT_FLAG_SYSTEM, "ChannelReload", "Channel: 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);
17512 return 0;
17515 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
17517 struct sip_pvt *p;
17518 struct ast_udptl *udptl = NULL;
17520 p = chan->tech_pvt;
17521 if (!p)
17522 return NULL;
17524 ast_mutex_lock(&p->lock);
17525 if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
17526 udptl = p->udptl;
17527 ast_mutex_unlock(&p->lock);
17528 return udptl;
17531 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
17533 struct sip_pvt *p;
17535 p = chan->tech_pvt;
17536 if (!p)
17537 return -1;
17538 ast_mutex_lock(&p->lock);
17539 if (udptl)
17540 ast_udptl_get_peer(udptl, &p->udptlredirip);
17541 else
17542 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
17543 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
17544 if (!p->pendinginvite) {
17545 if (option_debug > 2) {
17546 ast_log(LOG_DEBUG, "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), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
17548 transmit_reinvite_with_t38_sdp(p);
17549 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17550 if (option_debug > 2) {
17551 ast_log(LOG_DEBUG, "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), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
17553 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17556 /* Reset lastrtprx timer */
17557 p->lastrtprx = p->lastrtptx = time(NULL);
17558 ast_mutex_unlock(&p->lock);
17559 return 0;
17562 /*! \brief Handle T38 reinvite
17563 \todo Make sure we don't destroy the call if we can't handle the re-invite.
17564 Nothing should be changed until we have processed the SDP and know that we
17565 can handle it.
17567 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite)
17569 struct sip_pvt *p;
17570 int flag = 0;
17572 p = chan->tech_pvt;
17573 if (!p || !pvt->udptl)
17574 return -1;
17576 /* Setup everything on the other side like offered/responded from first side */
17577 ast_mutex_lock(&p->lock);
17579 /*! \todo check if this is not set earlier when setting up the PVT. If not
17580 maybe it should move there. */
17581 p->t38.jointcapability = p->t38.peercapability = pvt->t38.jointcapability;
17583 ast_udptl_set_far_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
17584 ast_udptl_set_local_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
17585 ast_udptl_set_error_correction_scheme(p->udptl, ast_udptl_get_error_correction_scheme(pvt->udptl));
17587 if (reinvite) { /* If we are handling sending re-invite to the other side of the bridge */
17588 /*! \note The SIP_CAN_REINVITE flag is for RTP media redirects,
17589 not really T38 re-invites which are different. In this
17590 case it's used properly, to see if we can reinvite over
17591 NAT
17593 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
17594 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
17595 flag =1;
17596 } else {
17597 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
17599 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
17600 if (!p->pendinginvite) {
17601 if (option_debug > 2) {
17602 if (flag)
17603 ast_log(LOG_DEBUG, "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));
17604 else
17605 ast_log(LOG_DEBUG, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to us (IP %s)\n", p->callid, ast_inet_ntoa(p->ourip));
17607 transmit_reinvite_with_t38_sdp(p);
17608 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17609 if (option_debug > 2) {
17610 if (flag)
17611 ast_log(LOG_DEBUG, "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));
17612 else
17613 ast_log(LOG_DEBUG, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to us (IP %s)\n", p->callid, ast_inet_ntoa(p->ourip));
17615 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17618 /* Reset lastrtprx timer */
17619 p->lastrtprx = p->lastrtptx = time(NULL);
17620 ast_mutex_unlock(&p->lock);
17621 return 0;
17622 } else { /* If we are handling sending 200 OK to the other side of the bridge */
17623 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
17624 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
17625 flag = 1;
17626 } else {
17627 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
17629 if (option_debug > 2) {
17630 if (flag)
17631 ast_log(LOG_DEBUG, "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));
17632 else
17633 ast_log(LOG_DEBUG, "Responding 200 OK on SIP '%s' - It's UDPTL soon redirected to us (IP %s)\n", p->callid, ast_inet_ntoa(p->ourip));
17635 pvt->t38.state = T38_ENABLED;
17636 p->t38.state = T38_ENABLED;
17637 if (option_debug > 1) {
17638 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", pvt->t38.state, pvt->owner ? pvt->owner->name : "<none>");
17639 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
17641 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
17642 p->lastrtprx = p->lastrtptx = time(NULL);
17643 ast_mutex_unlock(&p->lock);
17644 return 0;
17649 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
17650 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
17652 struct sip_pvt *p = NULL;
17653 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
17655 if (!(p = chan->tech_pvt))
17656 return AST_RTP_GET_FAILED;
17658 ast_mutex_lock(&p->lock);
17659 if (!(p->rtp)) {
17660 ast_mutex_unlock(&p->lock);
17661 return AST_RTP_GET_FAILED;
17664 *rtp = p->rtp;
17666 if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT))
17667 res = AST_RTP_TRY_PARTIAL;
17668 else if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
17669 res = AST_RTP_TRY_NATIVE;
17670 else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
17671 res = AST_RTP_GET_FAILED;
17673 ast_mutex_unlock(&p->lock);
17675 return res;
17678 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
17679 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
17681 struct sip_pvt *p = NULL;
17682 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
17684 if (!(p = chan->tech_pvt))
17685 return AST_RTP_GET_FAILED;
17687 ast_mutex_lock(&p->lock);
17688 if (!(p->vrtp)) {
17689 ast_mutex_unlock(&p->lock);
17690 return AST_RTP_GET_FAILED;
17693 *rtp = p->vrtp;
17695 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
17696 res = AST_RTP_TRY_NATIVE;
17698 ast_mutex_unlock(&p->lock);
17700 return res;
17703 /*! \brief Set the RTP peer for this call */
17704 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
17706 struct sip_pvt *p;
17707 int changed = 0;
17709 p = chan->tech_pvt;
17710 if (!p)
17711 return -1;
17713 /* Disable early RTP bridge */
17714 if (chan->_state != AST_STATE_UP && !global_directrtpsetup) /* We are in early state */
17715 return 0;
17717 ast_mutex_lock(&p->lock);
17718 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) {
17719 /* If we're destroyed, don't bother */
17720 ast_mutex_unlock(&p->lock);
17721 return 0;
17724 /* if this peer cannot handle reinvites of the media stream to devices
17725 that are known to be behind a NAT, then stop the process now
17727 if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
17728 ast_mutex_unlock(&p->lock);
17729 return 0;
17732 if (rtp) {
17733 changed |= ast_rtp_get_peer(rtp, &p->redirip);
17734 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
17735 memset(&p->redirip, 0, sizeof(p->redirip));
17736 changed = 1;
17738 if (vrtp) {
17739 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
17740 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
17741 memset(&p->vredirip, 0, sizeof(p->vredirip));
17742 changed = 1;
17744 if (codecs) {
17745 if ((p->redircodecs != codecs)) {
17746 p->redircodecs = codecs;
17747 changed = 1;
17749 if ((p->capability & codecs) != p->capability) {
17750 p->jointcapability &= codecs;
17751 p->capability &= codecs;
17752 changed = 1;
17755 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
17756 if (chan->_state != AST_STATE_UP) { /* We are in early state */
17757 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
17758 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
17759 if (option_debug)
17760 ast_log(LOG_DEBUG, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip));
17761 } else if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
17762 if (option_debug > 2) {
17763 ast_log(LOG_DEBUG, "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));
17765 transmit_reinvite_with_sdp(p);
17766 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17767 if (option_debug > 2) {
17768 ast_log(LOG_DEBUG, "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));
17770 /* We have a pending Invite. Send re-invite when we're done with the invite */
17771 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17774 /* Reset lastrtprx timer */
17775 p->lastrtprx = p->lastrtptx = time(NULL);
17776 ast_mutex_unlock(&p->lock);
17777 return 0;
17780 static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
17781 static char *descrip_dtmfmode = "SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
17782 static char *app_dtmfmode = "SIPDtmfMode";
17784 static char *app_sipaddheader = "SIPAddHeader";
17785 static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
17787 static char *descrip_sipaddheader = ""
17788 " SIPAddHeader(Header: Content)\n"
17789 "Adds a header to a SIP call placed with DIAL.\n"
17790 "Remember to user the X-header if you are adding non-standard SIP\n"
17791 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
17792 "Adding the wrong headers may jeopardize the SIP dialog.\n"
17793 "Always returns 0\n";
17796 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
17797 static int sip_dtmfmode(struct ast_channel *chan, void *data)
17799 struct sip_pvt *p;
17800 char *mode;
17801 if (data)
17802 mode = (char *)data;
17803 else {
17804 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
17805 return 0;
17807 ast_channel_lock(chan);
17808 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
17809 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
17810 ast_channel_unlock(chan);
17811 return 0;
17813 p = chan->tech_pvt;
17814 if (!p) {
17815 ast_channel_unlock(chan);
17816 return 0;
17818 ast_mutex_lock(&p->lock);
17819 if (!strcasecmp(mode,"info")) {
17820 ast_clear_flag(&p->flags[0], SIP_DTMF);
17821 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
17822 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
17823 } else if (!strcasecmp(mode,"rfc2833")) {
17824 ast_clear_flag(&p->flags[0], SIP_DTMF);
17825 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
17826 p->jointnoncodeccapability |= AST_RTP_DTMF;
17827 } else if (!strcasecmp(mode,"inband")) {
17828 ast_clear_flag(&p->flags[0], SIP_DTMF);
17829 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
17830 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
17831 } else
17832 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n",mode);
17833 if (p->rtp)
17834 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
17835 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
17836 if (!p->vad) {
17837 p->vad = ast_dsp_new();
17838 ast_dsp_set_features(p->vad, DSP_FEATURE_DTMF_DETECT);
17840 } else {
17841 if (p->vad) {
17842 ast_dsp_free(p->vad);
17843 p->vad = NULL;
17846 ast_mutex_unlock(&p->lock);
17847 ast_channel_unlock(chan);
17848 return 0;
17851 /*! \brief Add a SIP header to an outbound INVITE */
17852 static int sip_addheader(struct ast_channel *chan, void *data)
17854 int no = 0;
17855 int ok = FALSE;
17856 char varbuf[30];
17857 char *inbuf = (char *) data;
17859 if (ast_strlen_zero(inbuf)) {
17860 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
17861 return 0;
17863 ast_channel_lock(chan);
17865 /* Check for headers */
17866 while (!ok && no <= 50) {
17867 no++;
17868 snprintf(varbuf, sizeof(varbuf), "_SIPADDHEADER%.2d", no);
17870 /* Compare without the leading underscore */
17871 if( (pbx_builtin_getvar_helper(chan, (const char *) varbuf + 1) == (const char *) NULL) )
17872 ok = TRUE;
17874 if (ok) {
17875 pbx_builtin_setvar_helper (chan, varbuf, inbuf);
17876 if (sipdebug)
17877 ast_log(LOG_DEBUG,"SIP Header added \"%s\" as %s\n", inbuf, varbuf);
17878 } else {
17879 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
17881 ast_channel_unlock(chan);
17882 return 0;
17885 /*! \brief Transfer call before connect with a 302 redirect
17886 \note Called by the transfer() dialplan application through the sip_transfer()
17887 pbx interface function if the call is in ringing state
17888 \todo Fix this function so that we wait for reply to the REFER and
17889 react to errors, denials or other issues the other end might have.
17891 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
17893 char *cdest;
17894 char *extension, *host, *port;
17895 char tmp[80];
17897 cdest = ast_strdupa(dest);
17899 extension = strsep(&cdest, "@");
17900 host = strsep(&cdest, ":");
17901 port = strsep(&cdest, ":");
17902 if (ast_strlen_zero(extension)) {
17903 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
17904 return 0;
17907 /* we'll issue the redirect message here */
17908 if (!host) {
17909 char *localtmp;
17910 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
17911 if (ast_strlen_zero(tmp)) {
17912 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
17913 return 0;
17915 if ((localtmp = strcasestr(tmp, "sip:")) && (localtmp = strchr(localtmp, '@'))) {
17916 char lhost[80], lport[80];
17917 memset(lhost, 0, sizeof(lhost));
17918 memset(lport, 0, sizeof(lport));
17919 localtmp++;
17920 /* This is okey because lhost and lport are as big as tmp */
17921 sscanf(localtmp, "%[^<>:; ]:%[^<>:; ]", lhost, lport);
17922 if (ast_strlen_zero(lhost)) {
17923 ast_log(LOG_ERROR, "Can't find the host address\n");
17924 return 0;
17926 host = ast_strdupa(lhost);
17927 if (!ast_strlen_zero(lport)) {
17928 port = ast_strdupa(lport);
17933 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
17934 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
17936 sip_scheddestroy(p, SIP_TRANS_TIMEOUT); /* Make sure we stop send this reply. */
17937 sip_alreadygone(p);
17938 return 0;
17941 /*! \brief Return SIP UA's codec (part of the RTP interface) */
17942 static int sip_get_codec(struct ast_channel *chan)
17944 struct sip_pvt *p = chan->tech_pvt;
17945 return p->peercapability ? p->peercapability : p->capability;
17948 /*! \brief Send a poke to all known peers
17949 Space them out 100 ms apart
17950 XXX We might have a cool algorithm for this or use random - any suggestions?
17952 static void sip_poke_all_peers(void)
17954 int ms = 0;
17956 if (!speerobjs) /* No peers, just give up */
17957 return;
17959 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
17960 ASTOBJ_WRLOCK(iterator);
17961 if (!AST_SCHED_DEL(sched, iterator->pokeexpire)) {
17962 struct sip_peer *peer_ptr = iterator;
17963 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
17965 ms += 100;
17966 iterator->pokeexpire = ast_sched_add(sched, ms, sip_poke_peer_s, ASTOBJ_REF(iterator));
17967 if (iterator->pokeexpire == -1) {
17968 struct sip_peer *peer_ptr = iterator;
17969 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
17971 ASTOBJ_UNLOCK(iterator);
17972 } while (0)
17976 /*! \brief Send all known registrations */
17977 static void sip_send_all_registers(void)
17979 int ms;
17980 int regspacing;
17981 if (!regobjs)
17982 return;
17983 regspacing = default_expiry * 1000/regobjs;
17984 if (regspacing > 100)
17985 regspacing = 100;
17986 ms = regspacing;
17987 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
17988 ASTOBJ_WRLOCK(iterator);
17989 AST_SCHED_DEL(sched, iterator->expire);
17990 ms += regspacing;
17991 iterator->expire = ast_sched_add(sched, ms, sip_reregister, iterator);
17992 ASTOBJ_UNLOCK(iterator);
17993 } while (0)
17997 /*! \brief Reload module */
17998 static int sip_do_reload(enum channelreloadreason reason)
18000 reload_config(reason);
18002 /* Prune peers who still are supposed to be deleted */
18003 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
18004 if (option_debug > 3)
18005 ast_log(LOG_DEBUG, "--------------- Done destroying pruned peers\n");
18007 /* Send qualify (OPTIONS) to all peers */
18008 sip_poke_all_peers();
18010 /* Register with all services */
18011 sip_send_all_registers();
18013 if (option_debug > 3)
18014 ast_log(LOG_DEBUG, "--------------- SIP reload done\n");
18016 return 0;
18019 /*! \brief Force reload of module from cli */
18020 static int sip_reload(int fd, int argc, char *argv[])
18022 ast_mutex_lock(&sip_reload_lock);
18023 if (sip_reloading)
18024 ast_verbose("Previous SIP reload not yet done\n");
18025 else {
18026 sip_reloading = TRUE;
18027 if (fd)
18028 sip_reloadreason = CHANNEL_CLI_RELOAD;
18029 else
18030 sip_reloadreason = CHANNEL_MODULE_RELOAD;
18032 ast_mutex_unlock(&sip_reload_lock);
18033 restart_monitor();
18035 return 0;
18038 /*! \brief Part of Asterisk module interface */
18039 static int reload(void)
18041 return sip_reload(0, 0, NULL);
18044 static struct ast_cli_entry cli_sip_debug_deprecated =
18045 { { "sip", "debug", NULL },
18046 sip_do_debug_deprecated, "Enable SIP debugging",
18047 debug_usage };
18049 static struct ast_cli_entry cli_sip_no_debug_deprecated =
18050 { { "sip", "no", "debug", NULL },
18051 sip_no_debug_deprecated, "Disable SIP debugging",
18052 debug_usage };
18054 static struct ast_cli_entry cli_sip[] = {
18055 { { "sip", "show", "channels", NULL },
18056 sip_show_channels, "List active SIP channels",
18057 show_channels_usage },
18059 { { "sip", "show", "domains", NULL },
18060 sip_show_domains, "List our local SIP domains.",
18061 show_domains_usage },
18063 { { "sip", "show", "inuse", NULL },
18064 sip_show_inuse, "List all inuse/limits",
18065 show_inuse_usage },
18067 { { "sip", "show", "objects", NULL },
18068 sip_show_objects, "List all SIP object allocations",
18069 show_objects_usage },
18071 { { "sip", "show", "peers", NULL },
18072 sip_show_peers, "List defined SIP peers",
18073 show_peers_usage },
18075 { { "sip", "show", "registry", NULL },
18076 sip_show_registry, "List SIP registration status",
18077 show_reg_usage },
18079 { { "sip", "show", "settings", NULL },
18080 sip_show_settings, "Show SIP global settings",
18081 show_settings_usage },
18083 { { "sip", "show", "subscriptions", NULL },
18084 sip_show_subscriptions, "List active SIP subscriptions",
18085 show_subscriptions_usage },
18087 { { "sip", "show", "users", NULL },
18088 sip_show_users, "List defined SIP users",
18089 show_users_usage },
18091 { { "sip", "notify", NULL },
18092 sip_notify, "Send a notify packet to a SIP peer",
18093 notify_usage, complete_sipnotify },
18095 { { "sip", "show", "channel", NULL },
18096 sip_show_channel, "Show detailed SIP channel info",
18097 show_channel_usage, complete_sipch },
18099 { { "sip", "show", "history", NULL },
18100 sip_show_history, "Show SIP dialog history",
18101 show_history_usage, complete_sipch },
18103 { { "sip", "show", "peer", NULL },
18104 sip_show_peer, "Show details on specific SIP peer",
18105 show_peer_usage, complete_sip_show_peer },
18107 { { "sip", "show", "user", NULL },
18108 sip_show_user, "Show details on specific SIP user",
18109 show_user_usage, complete_sip_show_user },
18111 { { "sip", "prune", "realtime", NULL },
18112 sip_prune_realtime, "Prune cached Realtime object(s)",
18113 prune_realtime_usage },
18115 { { "sip", "prune", "realtime", "peer", NULL },
18116 sip_prune_realtime, "Prune cached Realtime peer(s)",
18117 prune_realtime_usage, complete_sip_prune_realtime_peer },
18119 { { "sip", "prune", "realtime", "user", NULL },
18120 sip_prune_realtime, "Prune cached Realtime user(s)",
18121 prune_realtime_usage, complete_sip_prune_realtime_user },
18123 { { "sip", "set", "debug", NULL },
18124 sip_do_debug, "Enable SIP debugging",
18125 debug_usage, NULL, &cli_sip_debug_deprecated },
18127 { { "sip", "set", "debug", "ip", NULL },
18128 sip_do_debug, "Enable SIP debugging on IP",
18129 debug_usage },
18131 { { "sip", "set", "debug", "peer", NULL },
18132 sip_do_debug, "Enable SIP debugging on Peername",
18133 debug_usage, complete_sip_debug_peer },
18135 { { "sip", "set", "debug", "off", NULL },
18136 sip_no_debug, "Disable SIP debugging",
18137 no_debug_usage, NULL, &cli_sip_no_debug_deprecated },
18139 { { "sip", "history", NULL },
18140 sip_do_history, "Enable SIP history",
18141 history_usage },
18143 { { "sip", "history", "off", NULL },
18144 sip_no_history, "Disable SIP history",
18145 no_history_usage },
18147 { { "sip", "reload", NULL },
18148 sip_reload, "Reload SIP configuration",
18149 sip_reload_usage },
18152 /*! \brief PBX load module - initialization */
18153 static int load_module(void)
18155 ASTOBJ_CONTAINER_INIT(&userl); /* User object list */
18156 ASTOBJ_CONTAINER_INIT(&peerl); /* Peer object list */
18157 ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list */
18159 if (!(sched = sched_context_create())) {
18160 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
18161 return AST_MODULE_LOAD_FAILURE;
18164 if (!(io = io_context_create())) {
18165 ast_log(LOG_ERROR, "Unable to create I/O context\n");
18166 sched_context_destroy(sched);
18167 return AST_MODULE_LOAD_FAILURE;
18170 sip_reloadreason = CHANNEL_MODULE_LOAD;
18172 if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
18173 return AST_MODULE_LOAD_DECLINE;
18175 /* Make sure we can register our sip channel type */
18176 if (ast_channel_register(&sip_tech)) {
18177 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
18178 io_context_destroy(io);
18179 sched_context_destroy(sched);
18180 return AST_MODULE_LOAD_FAILURE;
18183 /* Register all CLI functions for SIP */
18184 ast_cli_register_multiple(cli_sip, sizeof(cli_sip)/ sizeof(struct ast_cli_entry));
18186 /* Tell the RTP subdriver that we're here */
18187 ast_rtp_proto_register(&sip_rtp);
18189 /* Tell the UDPTL subdriver that we're here */
18190 ast_udptl_proto_register(&sip_udptl);
18192 /* Register dialplan applications */
18193 ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
18194 ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
18196 /* Register dialplan functions */
18197 ast_custom_function_register(&sip_header_function);
18198 ast_custom_function_register(&sippeer_function);
18199 ast_custom_function_register(&sipchaninfo_function);
18200 ast_custom_function_register(&checksipdomain_function);
18202 /* Register manager commands */
18203 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM, manager_sip_show_peers,
18204 "List SIP peers (text format)", mandescr_show_peers);
18205 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM, manager_sip_show_peer,
18206 "Show SIP peer (text format)", mandescr_show_peer);
18208 sip_poke_all_peers();
18209 sip_send_all_registers();
18211 /* And start the monitor for the first time */
18212 restart_monitor();
18214 return AST_MODULE_LOAD_SUCCESS;
18217 /*! \brief PBX unload module API */
18218 static int unload_module(void)
18220 struct sip_pvt *p, *pl;
18222 /* First, take us out of the channel type list */
18223 ast_channel_unregister(&sip_tech);
18225 /* Unregister dial plan functions */
18226 ast_custom_function_unregister(&sipchaninfo_function);
18227 ast_custom_function_unregister(&sippeer_function);
18228 ast_custom_function_unregister(&sip_header_function);
18229 ast_custom_function_unregister(&checksipdomain_function);
18231 /* Unregister dial plan applications */
18232 ast_unregister_application(app_dtmfmode);
18233 ast_unregister_application(app_sipaddheader);
18235 /* Unregister CLI commands */
18236 ast_cli_unregister_multiple(cli_sip, sizeof(cli_sip) / sizeof(struct ast_cli_entry));
18238 /* Disconnect from the RTP subsystem */
18239 ast_rtp_proto_unregister(&sip_rtp);
18241 /* Disconnect from UDPTL */
18242 ast_udptl_proto_unregister(&sip_udptl);
18244 /* Unregister AMI actions */
18245 ast_manager_unregister("SIPpeers");
18246 ast_manager_unregister("SIPshowpeer");
18248 ast_mutex_lock(&iflock);
18249 /* Hangup all interfaces if they have an owner */
18250 for (p = iflist; p ; p = p->next) {
18251 if (p->owner)
18252 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
18254 ast_mutex_unlock(&iflock);
18256 ast_mutex_lock(&monlock);
18257 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
18258 pthread_cancel(monitor_thread);
18259 pthread_kill(monitor_thread, SIGURG);
18260 pthread_join(monitor_thread, NULL);
18262 monitor_thread = AST_PTHREADT_STOP;
18263 ast_mutex_unlock(&monlock);
18265 restartdestroy:
18266 ast_mutex_lock(&iflock);
18267 /* Destroy all the interfaces and free their memory */
18268 p = iflist;
18269 while (p) {
18270 pl = p;
18271 p = p->next;
18272 if (__sip_destroy(pl, TRUE) < 0) {
18273 /* Something is still bridged, let it react to getting a hangup */
18274 iflist = p;
18275 ast_mutex_unlock(&iflock);
18276 usleep(1);
18277 goto restartdestroy;
18280 iflist = NULL;
18281 ast_mutex_unlock(&iflock);
18283 /* Free memory for local network address mask */
18284 ast_free_ha(localaddr);
18286 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
18287 ASTOBJ_CONTAINER_DESTROY(&userl);
18288 ASTOBJ_CONTAINER_DESTROYALL(&peerl, sip_destroy_peer);
18289 ASTOBJ_CONTAINER_DESTROY(&peerl);
18290 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
18291 ASTOBJ_CONTAINER_DESTROY(&regl);
18293 clear_realm_authentication(authl);
18294 clear_sip_domains();
18295 close(sipsock);
18296 sched_context_destroy(sched);
18298 return 0;
18301 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
18302 .load = load_module,
18303 .unload = unload_module,
18304 .reload = reload,