Let's also include aclocal.m4
[asterisk-bristuff.git] / channels / chan_sip.c
blob07b923629a76865e2c2994120ebe87acc5c14efb
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 /*! \brief Global list of addresses dynamic peers are not allowed to use */
578 static struct ast_ha *global_contact_ha = NULL;
579 static int global_dynamic_exclude_static = 0;
581 /* Object counters */
582 static int suserobjs = 0; /*!< Static users */
583 static int ruserobjs = 0; /*!< Realtime users */
584 static int speerobjs = 0; /*!< Statis peers */
585 static int rpeerobjs = 0; /*!< Realtime peers */
586 static int apeerobjs = 0; /*!< Autocreated peer objects */
587 static int regobjs = 0; /*!< Registry objects */
589 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
591 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
592 AST_MUTEX_DEFINE_STATIC(iflock);
594 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
595 when it's doing something critical. */
596 AST_MUTEX_DEFINE_STATIC(netlock);
598 AST_MUTEX_DEFINE_STATIC(monlock);
600 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
602 /*! \brief This is the thread for the monitor which checks for input on the channels
603 which are not currently in use. */
604 static pthread_t monitor_thread = AST_PTHREADT_NULL;
606 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
607 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
609 static struct sched_context *sched; /*!< The scheduling context */
610 static struct io_context *io; /*!< The IO context */
611 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
613 #define DEC_CALL_LIMIT 0
614 #define INC_CALL_LIMIT 1
615 #define DEC_CALL_RINGING 2
616 #define INC_CALL_RINGING 3
618 /*! \brief sip_request: The data grabbed from the UDP socket */
619 struct sip_request {
620 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
621 char *rlPart2; /*!< The Request URI or Response Status */
622 int len; /*!< Length */
623 int headers; /*!< # of SIP Headers */
624 int method; /*!< Method of this request */
625 int lines; /*!< Body Content */
626 unsigned int flags; /*!< SIP_PKT Flags for this packet */
627 char *header[SIP_MAX_HEADERS];
628 char *line[SIP_MAX_LINES];
629 char data[SIP_MAX_PACKET];
630 unsigned int sdp_start; /*!< the line number where the SDP begins */
631 unsigned int sdp_end; /*!< the line number where the SDP ends */
635 * A sip packet is stored into the data[] buffer, with the header followed
636 * by an empty line and the body of the message.
637 * On outgoing packets, data is accumulated in data[] with len reflecting
638 * the next available byte, headers and lines count the number of lines
639 * in both parts. There are no '\0' in data[0..len-1].
641 * On received packet, the input read from the socket is copied into data[],
642 * len is set and the string is NUL-terminated. Then a parser fills up
643 * the other fields -header[] and line[] to point to the lines of the
644 * message, rlPart1 and rlPart2 parse the first lnie as below:
646 * Requests have in the first line METHOD URI SIP/2.0
647 * rlPart1 = method; rlPart2 = uri;
648 * Responses have in the first line SIP/2.0 code description
649 * rlPart1 = SIP/2.0; rlPart2 = code + description;
653 /*! \brief structure used in transfers */
654 struct sip_dual {
655 struct ast_channel *chan1; /*!< First channel involved */
656 struct ast_channel *chan2; /*!< Second channel involved */
657 struct sip_request req; /*!< Request that caused the transfer (REFER) */
658 int seqno; /*!< Sequence number */
661 struct sip_pkt;
663 /*! \brief Parameters to the transmit_invite function */
664 struct sip_invite_param {
665 const char *distinctive_ring; /*!< Distinctive ring header */
666 int addsipheaders; /*!< Add extra SIP headers */
667 const char *uri_options; /*!< URI options to add to the URI */
668 const char *vxml_url; /*!< VXML url for Cisco phones */
669 char *auth; /*!< Authentication */
670 char *authheader; /*!< Auth header */
671 enum sip_auth_type auth_type; /*!< Authentication type */
672 const char *replaces; /*!< Replaces header for call transfers */
673 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
676 /*! \brief Structure to save routing information for a SIP session */
677 struct sip_route {
678 struct sip_route *next;
679 char hop[0];
682 /*! \brief Modes for SIP domain handling in the PBX */
683 enum domain_mode {
684 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
685 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
688 /*! \brief Domain data structure.
689 \note In the future, we will connect this to a configuration tree specific
690 for this domain
692 struct domain {
693 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
694 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
695 enum domain_mode mode; /*!< How did we find this domain? */
696 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
699 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
702 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
703 struct sip_history {
704 AST_LIST_ENTRY(sip_history) list;
705 char event[0]; /* actually more, depending on needs */
708 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
710 /*! \brief sip_auth: Credentials for authentication to other SIP services */
711 struct sip_auth {
712 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
713 char username[256]; /*!< Username */
714 char secret[256]; /*!< Secret */
715 char md5secret[256]; /*!< MD5Secret */
716 struct sip_auth *next; /*!< Next auth structure in list */
719 /*--- Various flags for the flags field in the pvt structure */
720 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
721 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed by the monitor thread */
722 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
723 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
724 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
725 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
726 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
727 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
728 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
729 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
730 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
731 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
732 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
733 #define SIP_OUTGOING (1 << 13) /*!< Direction of the last transaction in this dialog */
734 #define SIP_FREE_BIT (1 << 14) /*!< ---- */
735 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 15) /*!< Do not hangup at first ast_hangup */
736 #define SIP_DTMF (3 << 16) /*!< DTMF Support: four settings, uses two bits */
737 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DTMF Support: RTP DTMF - "rfc2833" */
738 #define SIP_DTMF_INBAND (1 << 16) /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
739 #define SIP_DTMF_INFO (2 << 16) /*!< DTMF Support: SIP Info messages - "info" */
740 #define SIP_DTMF_AUTO (3 << 16) /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
741 /* NAT settings */
742 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
743 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
744 #define SIP_NAT_RFC3581 (1 << 18) /*!< NAT RFC3581 */
745 #define SIP_NAT_ROUTE (2 << 18) /*!< NAT Only ROUTE */
746 #define SIP_NAT_ALWAYS (3 << 18) /*!< NAT Both ROUTE and RFC3581 */
747 /* re-INVITE related settings */
748 #define SIP_REINVITE (7 << 20) /*!< three bits used */
749 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
750 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< allow media reinvite when new peer is behind NAT */
751 #define SIP_REINVITE_UPDATE (4 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
752 /* "insecure" settings */
753 #define SIP_INSECURE_PORT (1 << 23) /*!< don't require matching port for incoming requests */
754 #define SIP_INSECURE_INVITE (1 << 24) /*!< don't require authentication for incoming INVITEs */
755 /* Sending PROGRESS in-band settings */
756 #define SIP_PROG_INBAND (3 << 25) /*!< three settings, uses two bits */
757 #define SIP_PROG_INBAND_NEVER (0 << 25)
758 #define SIP_PROG_INBAND_NO (1 << 25)
759 #define SIP_PROG_INBAND_YES (2 << 25)
760 #define SIP_NO_HISTORY (1 << 27) /*!< Suppress recording request/response history */
761 #define SIP_CALL_LIMIT (1 << 28) /*!< Call limit enforced for this call */
762 #define SIP_SENDRPID (1 << 29) /*!< Remote Party-ID Support */
763 #define SIP_INC_COUNT (1 << 30) /*!< Did this connection increment the counter of in-use calls? */
764 #define SIP_G726_NONSTANDARD (1 << 31) /*!< Use non-standard packing for G726-32 data */
766 #define SIP_FLAGS_TO_COPY \
767 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
768 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
769 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
771 /*--- a new page of flags (for flags[1] */
772 /* realtime flags */
773 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
774 #define SIP_PAGE2_RTUPDATE (1 << 1)
775 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
776 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
777 #define SIP_PAGE2_RTSAVE_SYSNAME (1 << 5)
778 /* Space for addition of other realtime flags in the future */
779 #define SIP_PAGE2_STATECHANGEQUEUE (1 << 9) /*!< D: Unsent state pending change exists */
780 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 10)
781 #define SIP_PAGE2_DEBUG (3 << 11)
782 #define SIP_PAGE2_DEBUG_CONFIG (1 << 11)
783 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 12)
784 #define SIP_PAGE2_DYNAMIC (1 << 13) /*!< Dynamic Peers register with Asterisk */
785 #define SIP_PAGE2_SELFDESTRUCT (1 << 14) /*!< Automatic peers need to destruct themselves */
786 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15)
787 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< Allow subscriptions from this peer? */
788 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< Allow overlap dialing ? */
789 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< Only issue MWI notification if subscribed to */
790 #define SIP_PAGE2_INC_RINGING (1 << 19) /*!< Did this connection increment the counter of in-use calls? */
791 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< T38 Fax Passthrough Support */
792 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< 20: T38 Fax Passthrough Support */
793 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< 21: T38 Fax Passthrough Support (not implemented) */
794 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< 22: T38 Fax Passthrough Support (not implemented) */
795 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< Call states */
796 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23) /*!< 23: Active hold */
797 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23) /*!< 23: One directional hold */
798 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23) /*!< 23: Inactive hold */
799 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25) /*!< 25: ???? */
800 #define SIP_PAGE2_BUGGY_MWI (1 << 26) /*!< 26: Buggy CISCO MWI fix */
801 #define SIP_PAGE2_OUTGOING_CALL (1 << 27) /*!< 27: Is this an outgoing call? */
802 #define SIP_PAGE2_UDPTL_DESTINATION (1 << 28) /*!< 28: Use source IP of RTP as destination if NAT is enabled */
803 #define SIP_PAGE2_DIALOG_ESTABLISHED (1 << 29) /*!< 29: Has a dialog been established? */
805 #define SIP_PAGE2_FLAGS_TO_COPY \
806 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
807 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_UDPTL_DESTINATION)
809 /* SIP packet flags */
810 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
811 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
812 #define SIP_PKT_IGNORE (1 << 2) /*!< This is a re-transmit, ignore it */
813 #define SIP_PKT_IGNORE_RESP (1 << 3) /*!< Resp ignore - ??? */
814 #define SIP_PKT_IGNORE_REQ (1 << 4) /*!< Req ignore - ??? */
816 /* T.38 set of flags */
817 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
818 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
819 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
820 /* Rate management */
821 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
822 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
823 /* UDP Error correction */
824 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
825 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
826 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
827 /* T38 Spec version */
828 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
829 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
830 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
831 /* Maximum Fax Rate */
832 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
833 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
834 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
835 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
836 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
837 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
839 /*!< This is default: NO MMR and JBIG trancoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
840 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
842 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
843 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
844 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
846 /*! \brief T38 States for a call */
847 enum t38state {
848 T38_DISABLED = 0, /*!< Not enabled */
849 T38_LOCAL_DIRECT, /*!< Offered from local */
850 T38_LOCAL_REINVITE, /*!< Offered from local - REINVITE */
851 T38_PEER_DIRECT, /*!< Offered from peer */
852 T38_PEER_REINVITE, /*!< Offered from peer - REINVITE */
853 T38_ENABLED /*!< Negotiated (enabled) */
856 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
857 struct t38properties {
858 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
859 int capability; /*!< Our T38 capability */
860 int peercapability; /*!< Peers T38 capability */
861 int jointcapability; /*!< Supported T38 capability at both ends */
862 enum t38state state; /*!< T.38 state */
865 /*! \brief Parameters to know status of transfer */
866 enum referstatus {
867 REFER_IDLE, /*!< No REFER is in progress */
868 REFER_SENT, /*!< Sent REFER to transferee */
869 REFER_RECEIVED, /*!< Received REFER from transferer */
870 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING */
871 REFER_ACCEPTED, /*!< Accepted by transferee */
872 REFER_RINGING, /*!< Target Ringing */
873 REFER_200OK, /*!< Answered by transfer target */
874 REFER_FAILED, /*!< REFER declined - go on */
875 REFER_NOAUTH /*!< We had no auth for REFER */
878 static const struct c_referstatusstring {
879 enum referstatus status;
880 char *text;
881 } referstatusstrings[] = {
882 { REFER_IDLE, "<none>" },
883 { REFER_SENT, "Request sent" },
884 { REFER_RECEIVED, "Request received" },
885 { REFER_ACCEPTED, "Accepted" },
886 { REFER_RINGING, "Target ringing" },
887 { REFER_200OK, "Done" },
888 { REFER_FAILED, "Failed" },
889 { REFER_NOAUTH, "Failed - auth failure" }
892 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed */
893 /* OEJ: Should be moved to string fields */
894 struct sip_refer {
895 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
896 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
897 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
898 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
899 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
900 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
901 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
902 char replaces_callid[SIPBUFSIZE]; /*!< Replace info: callid */
903 char replaces_callid_totag[SIPBUFSIZE/2]; /*!< Replace info: to-tag */
904 char replaces_callid_fromtag[SIPBUFSIZE/2]; /*!< Replace info: from-tag */
905 struct sip_pvt *refer_call; /*!< Call we are referring */
906 int attendedtransfer; /*!< Attended or blind transfer? */
907 int localtransfer; /*!< Transfer to local domain? */
908 enum referstatus status; /*!< REFER status */
911 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
912 static struct sip_pvt {
913 ast_mutex_t lock; /*!< Dialog private lock */
914 int method; /*!< SIP method that opened this dialog */
915 enum invitestates invitestate; /*!< The state of the INVITE transaction only */
916 AST_DECLARE_STRING_FIELDS(
917 AST_STRING_FIELD(callid); /*!< Global CallID */
918 AST_STRING_FIELD(randdata); /*!< Random data */
919 AST_STRING_FIELD(accountcode); /*!< Account code */
920 AST_STRING_FIELD(realm); /*!< Authorization realm */
921 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
922 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
923 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
924 AST_STRING_FIELD(domain); /*!< Authorization domain */
925 AST_STRING_FIELD(from); /*!< The From: header */
926 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
927 AST_STRING_FIELD(exten); /*!< Extension where to start */
928 AST_STRING_FIELD(context); /*!< Context for this call */
929 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
930 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
931 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
932 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
933 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
934 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
935 AST_STRING_FIELD(language); /*!< Default language for this call */
936 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
937 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
938 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
939 AST_STRING_FIELD(theirtag); /*!< Their tag */
940 AST_STRING_FIELD(username); /*!< [user] name */
941 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
942 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
943 AST_STRING_FIELD(uri); /*!< Original requested URI */
944 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
945 AST_STRING_FIELD(peersecret); /*!< Password */
946 AST_STRING_FIELD(peermd5secret);
947 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
948 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
949 AST_STRING_FIELD(via); /*!< Via: header */
950 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
951 AST_STRING_FIELD(our_contact); /*!< Our contact header */
952 AST_STRING_FIELD(rpid); /*!< Our RPID header */
953 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
955 unsigned int ocseq; /*!< Current outgoing seqno */
956 unsigned int icseq; /*!< Current incoming seqno */
957 ast_group_t callgroup; /*!< Call group */
958 ast_group_t pickupgroup; /*!< Pickup group */
959 int lastinvite; /*!< Last Cseq of invite */
960 int lastnoninvite; /*!< Last Cseq of non-invite */
961 struct ast_flags flags[2]; /*!< SIP_ flags */
962 int timer_t1; /*!< SIP timer T1, ms rtt */
963 unsigned int sipoptions; /*!< Supported SIP options on the other end */
964 struct ast_codec_pref prefs; /*!< codec prefs */
965 int capability; /*!< Special capability (codec) */
966 int jointcapability; /*!< Supported capability at both ends (codecs) */
967 int peercapability; /*!< Supported peer capability */
968 int prefcodec; /*!< Preferred codec (outbound only) */
969 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
970 int jointnoncodeccapability; /*!< Joint Non codec capability */
971 int redircodecs; /*!< Redirect codecs */
972 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
973 struct t38properties t38; /*!< T38 settings */
974 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
975 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
976 int callingpres; /*!< Calling presentation */
977 int authtries; /*!< Times we've tried to authenticate */
978 int expiry; /*!< How long we take to expire */
979 long branch; /*!< The branch identifier of this session */
980 long invite_branch; /*!< The branch used when we sent the initial INVITE */
981 char tag[11]; /*!< Our tag for this session */
982 int sessionid; /*!< SDP Session ID */
983 int sessionversion; /*!< SDP Session Version */
984 struct sockaddr_in sa; /*!< Our peer */
985 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
986 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
987 time_t lastrtprx; /*!< Last RTP received */
988 time_t lastrtptx; /*!< Last RTP sent */
989 int rtptimeout; /*!< RTP timeout time */
990 struct sockaddr_in recv; /*!< Received as */
991 struct in_addr ourip; /*!< Our IP */
992 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
993 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
994 int route_persistant; /*!< Is this the "real" route? */
995 struct sip_auth *peerauth; /*!< Realm authentication */
996 int noncecount; /*!< Nonce-count */
997 char lastmsg[256]; /*!< Last Message sent/received */
998 int amaflags; /*!< AMA Flags */
999 int pendinginvite; /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
1000 struct sip_request initreq; /*!< Request that opened the latest transaction
1001 within this SIP dialog */
1003 int maxtime; /*!< Max time for first response */
1004 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
1005 int waitid; /*!< Wait ID for scheduler after 491 or other delays */
1006 int autokillid; /*!< Auto-kill ID (scheduler) */
1007 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
1008 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
1009 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
1010 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
1011 int laststate; /*!< SUBSCRIBE: Last known extension state */
1012 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
1014 struct ast_dsp *vad; /*!< Voice Activation Detection dsp */
1016 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
1017 Used in peerpoke, mwi subscriptions */
1018 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
1019 struct ast_rtp *rtp; /*!< RTP Session */
1020 struct ast_rtp *vrtp; /*!< Video RTP session */
1021 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
1022 struct sip_history_head *history; /*!< History of this SIP dialog */
1023 size_t history_entries; /*!< Number of entires in the history */
1024 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1025 struct sip_pvt *next; /*!< Next dialog in chain */
1026 struct sip_invite_param *options; /*!< Options for INVITE */
1027 int autoframing;
1028 } *iflist = NULL;
1030 /*! Max entires in the history list for a sip_pvt */
1031 #define MAX_HISTORY_ENTRIES 50
1033 #define FLAG_RESPONSE (1 << 0)
1034 #define FLAG_FATAL (1 << 1)
1036 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */
1037 struct sip_pkt {
1038 struct sip_pkt *next; /*!< Next packet in linked list */
1039 int retrans; /*!< Retransmission number */
1040 int method; /*!< SIP method for this packet */
1041 int seqno; /*!< Sequence number */
1042 unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */
1043 struct sip_pvt *owner; /*!< Owner AST call */
1044 int retransid; /*!< Retransmission ID */
1045 int timer_a; /*!< SIP timer A, retransmission timer */
1046 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
1047 int packetlen; /*!< Length of packet */
1048 char data[0];
1051 /*! \brief Structure for SIP user data. User's place calls to us */
1052 struct sip_user {
1053 /* Users who can access various contexts */
1054 ASTOBJ_COMPONENTS(struct sip_user);
1055 char secret[80]; /*!< Password */
1056 char md5secret[80]; /*!< Password in md5 */
1057 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1058 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
1059 char cid_num[80]; /*!< Caller ID num */
1060 char cid_name[80]; /*!< Caller ID name */
1061 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
1062 char language[MAX_LANGUAGE]; /*!< Default language for this user */
1063 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1064 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1065 char useragent[256]; /*!< User agent in SIP request */
1066 struct ast_codec_pref prefs; /*!< codec prefs */
1067 ast_group_t callgroup; /*!< Call group */
1068 ast_group_t pickupgroup; /*!< Pickup Group */
1069 unsigned int sipoptions; /*!< Supported SIP options */
1070 struct ast_flags flags[2]; /*!< SIP_ flags */
1071 int amaflags; /*!< AMA flags for billing */
1072 int callingpres; /*!< Calling id presentation */
1073 int capability; /*!< Codec capability */
1074 int inUse; /*!< Number of calls in use */
1075 int call_limit; /*!< Limit of concurrent calls */
1076 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1077 struct ast_ha *ha; /*!< ACL setting */
1078 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1079 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1080 int autoframing;
1083 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1084 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1085 struct sip_peer {
1086 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
1087 /*!< peer->name is the unique name of this object */
1088 char secret[80]; /*!< Password */
1089 char md5secret[80]; /*!< Password in MD5 */
1090 struct sip_auth *auth; /*!< Realm authentication list */
1091 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1092 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1093 char username[80]; /*!< Temporary username until registration */
1094 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1095 int amaflags; /*!< AMA Flags (for billing) */
1096 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1097 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1098 char fromuser[80]; /*!< From: user when calling this peer */
1099 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1100 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1101 char cid_num[80]; /*!< Caller ID num */
1102 char cid_name[80]; /*!< Caller ID name */
1103 int callingpres; /*!< Calling id presentation */
1104 int inUse; /*!< Number of calls in use */
1105 int inRinging; /*!< Number of calls ringing */
1106 int onHold; /*!< Peer has someone on hold */
1107 int call_limit; /*!< Limit of concurrent calls */
1108 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1109 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1110 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
1111 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1112 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1113 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1114 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1115 struct ast_codec_pref prefs; /*!< codec prefs */
1116 int lastmsgssent;
1117 time_t lastmsgcheck; /*!< Last time we checked for MWI */
1118 unsigned int sipoptions; /*!< Supported SIP options */
1119 struct ast_flags flags[2]; /*!< SIP_ flags */
1120 int expire; /*!< When to expire this peer registration */
1121 int capability; /*!< Codec capability */
1122 int rtptimeout; /*!< RTP timeout */
1123 int rtpholdtimeout; /*!< RTP Hold Timeout */
1124 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1125 ast_group_t callgroup; /*!< Call group */
1126 ast_group_t pickupgroup; /*!< Pickup group */
1127 struct sockaddr_in addr; /*!< IP address of peer */
1128 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1130 /* Qualification */
1131 struct sip_pvt *call; /*!< Call pointer */
1132 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1133 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1134 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1135 struct timeval ps; /*!< Ping send time */
1137 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1138 struct ast_ha *ha; /*!< Access control list */
1139 struct ast_ha *contactha; /*!< Restrict what IPs are allowed in the Contact header (for registration) */
1140 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1141 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1142 int lastmsg;
1143 int autoframing;
1148 /*! \brief Registrations with other SIP proxies */
1149 struct sip_registry {
1150 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1151 AST_DECLARE_STRING_FIELDS(
1152 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1153 AST_STRING_FIELD(realm); /*!< Authorization realm */
1154 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1155 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1156 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1157 AST_STRING_FIELD(domain); /*!< Authorization domain */
1158 AST_STRING_FIELD(username); /*!< Who we are registering as */
1159 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1160 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1161 AST_STRING_FIELD(secret); /*!< Password in clear text */
1162 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1163 AST_STRING_FIELD(contact); /*!< Contact extension */
1164 AST_STRING_FIELD(random);
1166 int portno; /*!< Optional port override */
1167 int expire; /*!< Sched ID of expiration */
1168 int regattempts; /*!< Number of attempts (since the last success) */
1169 int timeout; /*!< sched id of sip_reg_timeout */
1170 int refresh; /*!< How often to refresh */
1171 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1172 enum sipregistrystate regstate; /*!< Registration state (see above) */
1173 time_t regtime; /*!< Last succesful registration time */
1174 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1175 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1176 struct sockaddr_in us; /*!< Who the server thinks we are */
1177 int noncecount; /*!< Nonce-count */
1178 char lastmsg[256]; /*!< Last Message sent/received */
1181 /* --- Linked lists of various objects --------*/
1183 /*! \brief The user list: Users and friends */
1184 static struct ast_user_list {
1185 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1186 } userl;
1188 /*! \brief The peer list: Peers and Friends */
1189 static struct ast_peer_list {
1190 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1191 } peerl;
1193 /*! \brief The register list: Other SIP proxys we register with and place calls to */
1194 static struct ast_register_list {
1195 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1196 int recheck;
1197 } regl;
1199 static void temp_pvt_cleanup(void *);
1201 /*! \brief A per-thread temporary pvt structure */
1202 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1204 #ifdef LOW_MEMORY
1205 static void ts_ast_rtp_destroy(void *);
1207 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, ts_audio_rtp_init, ts_ast_rtp_destroy);
1208 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, ts_video_rtp_init, ts_ast_rtp_destroy);
1209 #endif
1211 /*! \todo Move the sip_auth list to AST_LIST */
1212 static struct sip_auth *authl = NULL; /*!< Authentication list for realm authentication */
1215 /* --- Sockets and networking --------------*/
1216 static int sipsock = -1; /*!< Main socket for SIP network communication */
1217 static struct sockaddr_in bindaddr = { 0, }; /*!< The address we bind to */
1218 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1219 static char externhost[MAXHOSTNAMELEN]; /*!< External host name (possibly with dynamic DNS and DHCP */
1220 static time_t externexpire = 0; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1221 static int externrefresh = 10;
1222 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1223 static struct in_addr __ourip;
1224 static struct sockaddr_in outboundproxyip;
1225 static int ourport;
1226 static struct sockaddr_in debugaddr;
1228 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1230 /*---------------------------- Forward declarations of functions in chan_sip.c */
1231 /*! \note This is added to help splitting up chan_sip.c into several files
1232 in coming releases */
1234 /*--- PBX interface functions */
1235 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1236 static int sip_devicestate(void *data);
1237 static int sip_sendtext(struct ast_channel *ast, const char *text);
1238 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1239 static int sip_hangup(struct ast_channel *ast);
1240 static int sip_answer(struct ast_channel *ast);
1241 static struct ast_frame *sip_read(struct ast_channel *ast);
1242 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1243 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1244 static int sip_transfer(struct ast_channel *ast, const char *dest);
1245 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1246 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1247 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1249 /*--- Transmitting responses and requests */
1250 static int sipsock_read(int *id, int fd, short events, void *ignore);
1251 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
1252 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
1253 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1254 static int retrans_pkt(const void *data);
1255 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
1256 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);
1257 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1258 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1259 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1260 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1261 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1262 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);
1263 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1264 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1265 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1266 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1267 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1268 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
1269 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1270 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1271 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1272 static int transmit_refer(struct sip_pvt *p, const char *dest);
1273 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1274 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1275 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1276 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1277 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1278 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1279 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1280 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1281 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1282 static int does_peer_need_mwi(struct sip_peer *peer);
1284 /*--- Dialog management */
1285 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1286 int useglobal_nat, const int intended_method);
1287 static int __sip_autodestruct(const void *data);
1288 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1289 static int sip_cancel_destroy(struct sip_pvt *p);
1290 static void sip_destroy(struct sip_pvt *p);
1291 static int __sip_destroy(struct sip_pvt *p, int lockowner);
1292 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1293 static void __sip_pretend_ack(struct sip_pvt *p);
1294 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1295 static int auto_congest(const void *nothing);
1296 static int update_call_counter(struct sip_pvt *fup, int event);
1297 static int hangup_sip2cause(int cause);
1298 static const char *hangup_cause2sip(int cause);
1299 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1300 static void free_old_route(struct sip_route *route);
1301 static void list_route(struct sip_route *route);
1302 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1303 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1304 struct sip_request *req, char *uri);
1305 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1306 static void check_pendings(struct sip_pvt *p);
1307 static void *sip_park_thread(void *stuff);
1308 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1309 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1311 /*--- Codec handling / SDP */
1312 static void try_suggested_sip_codec(struct sip_pvt *p);
1313 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1314 static const char *get_sdp(struct sip_request *req, const char *name);
1315 static int find_sdp(struct sip_request *req);
1316 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
1317 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1318 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1319 int debug, int *min_packet_size);
1320 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1321 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1322 int debug);
1323 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p);
1324 static void stop_media_flows(struct sip_pvt *p);
1326 /*--- Authentication stuff */
1327 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1328 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1329 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1330 const char *secret, const char *md5secret, int sipmethod,
1331 char *uri, enum xmittype reliable, int ignore);
1332 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1333 int sipmethod, char *uri, enum xmittype reliable,
1334 struct sockaddr_in *sin, struct sip_peer **authpeer);
1335 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1337 /*--- Domain handling */
1338 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1339 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1340 static void clear_sip_domains(void);
1342 /*--- SIP realm authentication */
1343 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
1344 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1345 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1347 /*--- Misc functions */
1348 static int sip_do_reload(enum channelreloadreason reason);
1349 static int reload_config(enum channelreloadreason reason);
1350 static int expire_register(const void *data);
1351 static void *do_monitor(void *data);
1352 static int restart_monitor(void);
1353 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1354 static int sip_addrcmp(char *name, struct sockaddr_in *sin); /* Support for peer matching */
1355 static int sip_refer_allocate(struct sip_pvt *p);
1356 static void ast_quiet_chan(struct ast_channel *chan);
1357 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1359 /*--- Device monitoring and Device/extension state handling */
1360 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1361 static int sip_devicestate(void *data);
1362 static int sip_poke_noanswer(const void *data);
1363 static int sip_poke_peer(struct sip_peer *peer);
1364 static void sip_poke_all_peers(void);
1365 static void sip_peer_hold(struct sip_pvt *p, int hold);
1367 /*--- Applications, functions, CLI and manager command helpers */
1368 static const char *sip_nat_mode(const struct sip_pvt *p);
1369 static int sip_show_inuse(int fd, int argc, char *argv[]);
1370 static char *transfermode2str(enum transfermodes mode) attribute_const;
1371 static char *nat2str(int nat) attribute_const;
1372 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1373 static int sip_show_users(int fd, int argc, char *argv[]);
1374 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1375 static int sip_show_peers(int fd, int argc, char *argv[]);
1376 static int sip_show_objects(int fd, int argc, char *argv[]);
1377 static void print_group(int fd, ast_group_t group, int crlf);
1378 static const char *dtmfmode2str(int mode) attribute_const;
1379 static const char *insecure2str(int port, int invite) attribute_const;
1380 static void cleanup_stale_contexts(char *new, char *old);
1381 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1382 static const char *domain_mode_to_text(const enum domain_mode mode);
1383 static int sip_show_domains(int fd, int argc, char *argv[]);
1384 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1385 static int sip_show_peer(int fd, int argc, char *argv[]);
1386 static int sip_show_user(int fd, int argc, char *argv[]);
1387 static int sip_show_registry(int fd, int argc, char *argv[]);
1388 static int sip_show_settings(int fd, int argc, char *argv[]);
1389 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1390 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1391 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1392 static int sip_show_channels(int fd, int argc, char *argv[]);
1393 static int sip_show_subscriptions(int fd, int argc, char *argv[]);
1394 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1395 static char *complete_sipch(const char *line, const char *word, int pos, int state);
1396 static char *complete_sip_peer(const char *word, int state, int flags2);
1397 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1398 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state);
1399 static char *complete_sip_user(const char *word, int state, int flags2);
1400 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
1401 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1402 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state);
1403 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state);
1404 static int sip_show_channel(int fd, int argc, char *argv[]);
1405 static int sip_show_history(int fd, int argc, char *argv[]);
1406 static int sip_do_debug_ip(int fd, int argc, char *argv[]);
1407 static int sip_do_debug_peer(int fd, int argc, char *argv[]);
1408 static int sip_do_debug(int fd, int argc, char *argv[]);
1409 static int sip_no_debug(int fd, int argc, char *argv[]);
1410 static int sip_notify(int fd, int argc, char *argv[]);
1411 static int sip_do_history(int fd, int argc, char *argv[]);
1412 static int sip_no_history(int fd, int argc, char *argv[]);
1413 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
1414 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1415 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1416 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1417 static int sip_dtmfmode(struct ast_channel *chan, void *data);
1418 static int sip_addheader(struct ast_channel *chan, void *data);
1419 static int sip_do_reload(enum channelreloadreason reason);
1420 static int sip_reload(int fd, int argc, char *argv[]);
1421 static int acf_channel_read(struct ast_channel *chan, char *funcname, char *preparse, char *buf, size_t buflen);
1423 /*--- Debugging
1424 Functions for enabling debug per IP or fully, or enabling history logging for
1425 a SIP dialog
1427 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1428 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1429 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1430 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1431 static void sip_dump_history(struct sip_pvt *dialog);
1433 /*--- Device object handling */
1434 static struct sip_peer *temp_peer(const char *name);
1435 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1436 static struct sip_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1437 static int update_call_counter(struct sip_pvt *fup, int event);
1438 static void sip_destroy_peer(struct sip_peer *peer);
1439 static void sip_destroy_user(struct sip_user *user);
1440 static int sip_poke_peer(struct sip_peer *peer);
1441 static int sip_poke_peer_s(const void *data);
1442 static void set_peer_defaults(struct sip_peer *peer);
1443 static struct sip_peer *temp_peer(const char *name);
1444 static void register_peer_exten(struct sip_peer *peer, int onoff);
1445 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int devstate_only);
1446 static struct sip_user *find_user(const char *name, int realtime);
1447 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1448 static int expire_register(const void *data);
1449 static void reg_source_db(struct sip_peer *peer);
1450 static void destroy_association(struct sip_peer *peer);
1451 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1453 /* Realtime device support */
1454 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
1455 static struct sip_user *realtime_user(const char *username);
1456 static void update_peer(struct sip_peer *p, int expiry);
1457 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
1458 static int sip_prune_realtime(int fd, int argc, char *argv[]);
1460 /*--- Internal UA client handling (outbound registrations) */
1461 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
1462 static void sip_registry_destroy(struct sip_registry *reg);
1463 static int sip_register(char *value, int lineno);
1464 static char *regstate2str(enum sipregistrystate regstate) attribute_const;
1465 static int sip_reregister(const void *data);
1466 static int __sip_do_register(struct sip_registry *r);
1467 static int sip_reg_timeout(const void *data);
1468 static void sip_send_all_registers(void);
1470 /*--- Parsing SIP requests and responses */
1471 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1472 static int determine_firstline_parts(struct sip_request *req);
1473 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1474 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1475 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1476 static int find_sip_method(const char *msg);
1477 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1478 static int parse_request(struct sip_request *req);
1479 static const char *get_header(const struct sip_request *req, const char *name);
1480 static char *referstatus2str(enum referstatus rstatus) attribute_pure;
1481 static int method_match(enum sipmethod id, const char *name);
1482 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1483 static char *get_in_brackets(char *tmp);
1484 static const char *find_alias(const char *name, const char *_default);
1485 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1486 static int lws2sws(char *msgbuf, int len);
1487 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1488 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1489 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1490 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1491 static int set_address_from_contact(struct sip_pvt *pvt);
1492 static void check_via(struct sip_pvt *p, const struct sip_request *req);
1493 static char *get_calleridname(const char *input, char *output, size_t outputsize);
1494 static int get_rpid_num(const char *input, char *output, int maxlen);
1495 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
1496 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1497 static int get_msg_text(char *buf, int len, struct sip_request *req);
1498 static void free_old_route(struct sip_route *route);
1499 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1501 /*--- Constructing requests and responses */
1502 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1503 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1504 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1505 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1506 static int init_resp(struct sip_request *resp, const char *msg);
1507 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1508 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1509 static void build_via(struct sip_pvt *p);
1510 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1511 static int create_addr(struct sip_pvt *dialog, const char *opeer);
1512 static char *generate_random_string(char *buf, size_t size);
1513 static void build_callid_pvt(struct sip_pvt *pvt);
1514 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1515 static void make_our_tag(char *tagbuf, size_t len);
1516 static int add_header(struct sip_request *req, const char *var, const char *value);
1517 static int add_header_contentLength(struct sip_request *req, int len);
1518 static int add_line(struct sip_request *req, const char *line);
1519 static int add_text(struct sip_request *req, const char *text);
1520 static int add_digit(struct sip_request *req, char digit, unsigned int duration);
1521 static int add_vidupdate(struct sip_request *req);
1522 static void add_route(struct sip_request *req, struct sip_route *route);
1523 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1524 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1525 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1526 static void set_destination(struct sip_pvt *p, char *uri);
1527 static void append_date(struct sip_request *req);
1528 static void build_contact(struct sip_pvt *p);
1529 static void build_rpid(struct sip_pvt *p);
1531 /*------Request handling functions */
1532 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1533 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);
1534 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock);
1535 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1536 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1537 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1538 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1539 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1540 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1541 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1542 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1543 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1544 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
1546 /*------Response handling functions */
1547 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1548 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1549 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
1550 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
1552 /*----- RTP interface functions */
1553 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
1554 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1555 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1556 static int sip_get_codec(struct ast_channel *chan);
1557 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
1559 /*------ T38 Support --------- */
1560 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite); /*!< T38 negotiation helper function */
1561 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1562 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p);
1563 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1564 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1566 /*! \brief Definition of this channel for PBX channel registration */
1567 static const struct ast_channel_tech sip_tech = {
1568 .type = "SIP",
1569 .description = "Session Initiation Protocol (SIP)",
1570 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1571 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1572 .requester = sip_request_call,
1573 .devicestate = sip_devicestate,
1574 .call = sip_call,
1575 .hangup = sip_hangup,
1576 .answer = sip_answer,
1577 .read = sip_read,
1578 .write = sip_write,
1579 .write_video = sip_write,
1580 .indicate = sip_indicate,
1581 .transfer = sip_transfer,
1582 .fixup = sip_fixup,
1583 .send_digit_begin = sip_senddigit_begin,
1584 .send_digit_end = sip_senddigit_end,
1585 .bridge = ast_rtp_bridge,
1586 .send_text = sip_sendtext,
1587 .func_channel_read = acf_channel_read,
1590 /*! \brief This version of the sip channel tech has no send_digit_begin
1591 * callback. This is for use with channels using SIP INFO DTMF so that
1592 * the core knows that the channel doesn't want DTMF BEGIN frames. */
1593 static const struct ast_channel_tech sip_tech_info = {
1594 .type = "SIP",
1595 .description = "Session Initiation Protocol (SIP)",
1596 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1597 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1598 .requester = sip_request_call,
1599 .devicestate = sip_devicestate,
1600 .call = sip_call,
1601 .hangup = sip_hangup,
1602 .answer = sip_answer,
1603 .read = sip_read,
1604 .write = sip_write,
1605 .write_video = sip_write,
1606 .indicate = sip_indicate,
1607 .transfer = sip_transfer,
1608 .fixup = sip_fixup,
1609 .send_digit_end = sip_senddigit_end,
1610 .bridge = ast_rtp_bridge,
1611 .send_text = sip_sendtext,
1612 .func_channel_read = acf_channel_read,
1615 /**--- some list management macros. **/
1617 #define UNLINK(element, head, prev) do { \
1618 if (prev) \
1619 (prev)->next = (element)->next; \
1620 else \
1621 (head) = (element)->next; \
1622 } while (0)
1624 /*! \brief Interface structure with callbacks used to connect to RTP module */
1625 static struct ast_rtp_protocol sip_rtp = {
1626 type: "SIP",
1627 get_rtp_info: sip_get_rtp_peer,
1628 get_vrtp_info: sip_get_vrtp_peer,
1629 set_rtp_peer: sip_set_rtp_peer,
1630 get_codec: sip_get_codec,
1633 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1634 static struct ast_udptl_protocol sip_udptl = {
1635 type: "SIP",
1636 get_udptl_info: sip_get_udptl_peer,
1637 set_udptl_peer: sip_set_udptl_peer,
1640 /*! \brief Convert transfer status to string */
1641 static char *referstatus2str(enum referstatus rstatus)
1643 int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
1644 int x;
1646 for (x = 0; x < i; x++) {
1647 if (referstatusstrings[x].status == rstatus)
1648 return (char *) referstatusstrings[x].text;
1650 return "";
1653 /*! \brief Initialize the initital request packet in the pvt structure.
1654 This packet is used for creating replies and future requests in
1655 a dialog */
1656 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
1658 if (p->initreq.headers && option_debug) {
1659 ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
1661 /* Use this as the basis */
1662 copy_request(&p->initreq, req);
1663 parse_request(&p->initreq);
1664 if (ast_test_flag(req, SIP_PKT_DEBUG))
1665 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
1668 static void sip_alreadygone(struct sip_pvt *dialog)
1670 if (option_debug > 2)
1671 ast_log(LOG_DEBUG, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
1672 ast_set_flag(&dialog->flags[0], SIP_ALREADYGONE);
1676 /*! \brief returns true if 'name' (with optional trailing whitespace)
1677 * matches the sip method 'id'.
1678 * Strictly speaking, SIP methods are case SENSITIVE, but we do
1679 * a case-insensitive comparison to be more tolerant.
1680 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1682 static int method_match(enum sipmethod id, const char *name)
1684 int len = strlen(sip_methods[id].text);
1685 int l_name = name ? strlen(name) : 0;
1686 /* true if the string is long enough, and ends with whitespace, and matches */
1687 return (l_name >= len && name[len] < 33 &&
1688 !strncasecmp(sip_methods[id].text, name, len));
1691 /*! \brief find_sip_method: Find SIP method from header */
1692 static int find_sip_method(const char *msg)
1694 int i, res = 0;
1696 if (ast_strlen_zero(msg))
1697 return 0;
1698 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
1699 if (method_match(i, msg))
1700 res = sip_methods[i].id;
1702 return res;
1705 /*! \brief Parse supported header in incoming packet */
1706 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
1708 char *next, *sep;
1709 char *temp;
1710 unsigned int profile = 0;
1711 int i, found;
1713 if (ast_strlen_zero(supported) )
1714 return 0;
1715 temp = ast_strdupa(supported);
1717 if (option_debug > 2 && sipdebug)
1718 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1720 for (next = temp; next; next = sep) {
1721 found = FALSE;
1722 if ( (sep = strchr(next, ',')) != NULL)
1723 *sep++ = '\0';
1724 next = ast_skip_blanks(next);
1725 if (option_debug > 2 && sipdebug)
1726 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1727 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
1728 if (!strcasecmp(next, sip_options[i].text)) {
1729 profile |= sip_options[i].id;
1730 found = TRUE;
1731 if (option_debug > 2 && sipdebug)
1732 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1733 break;
1736 if (!found && option_debug > 2 && sipdebug) {
1737 if (!strncasecmp(next, "x-", 2))
1738 ast_log(LOG_DEBUG, "Found private SIP option, not supported: %s\n", next);
1739 else
1740 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1744 if (pvt)
1745 pvt->sipoptions = profile;
1746 return profile;
1749 /*! \brief See if we pass debug IP filter */
1750 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
1752 if (!sipdebug)
1753 return 0;
1754 if (debugaddr.sin_addr.s_addr) {
1755 if (((ntohs(debugaddr.sin_port) != 0)
1756 && (debugaddr.sin_port != addr->sin_port))
1757 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1758 return 0;
1760 return 1;
1763 /*! \brief The real destination address for a write */
1764 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
1766 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
1769 /*! \brief Display SIP nat mode */
1770 static const char *sip_nat_mode(const struct sip_pvt *p)
1772 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
1775 /*! \brief Test PVT for debugging output */
1776 static inline int sip_debug_test_pvt(struct sip_pvt *p)
1778 if (!sipdebug)
1779 return 0;
1780 return sip_debug_test_addr(sip_real_dst(p));
1783 /*! \brief Transmit SIP message */
1784 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1786 int res;
1787 const struct sockaddr_in *dst = sip_real_dst(p);
1788 res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
1790 if (res == -1) {
1791 switch (errno) {
1792 case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
1793 case EHOSTUNREACH: /* Host can't be reached */
1794 case ENETDOWN: /* Inteface down */
1795 case ENETUNREACH: /* Network failure */
1796 case ECONNREFUSED: /* ICMP port unreachable */
1797 res = XMIT_ERROR; /* Don't bother with trying to transmit again */
1800 if (res != len)
1801 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));
1802 return res;
1806 /*! \brief Build a Via header for a request */
1807 static void build_via(struct sip_pvt *p)
1809 /* Work around buggy UNIDEN UIP200 firmware */
1810 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1812 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1813 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1814 ast_inet_ntoa(p->ourip), ourport, p->branch, rport);
1817 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1819 * Using the localaddr structure built up with localnet statements in sip.conf
1820 * apply it to their address to see if we need to substitute our
1821 * externip or can get away with our internal bindaddr
1823 static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1825 struct sockaddr_in theirs, ours;
1827 /* Get our local information */
1828 ast_ouraddrfor(them, us);
1829 theirs.sin_addr = *them;
1830 ours.sin_addr = *us;
1832 if (localaddr && externip.sin_addr.s_addr &&
1833 (ast_apply_ha(localaddr, &theirs)) &&
1834 (!global_matchexterniplocally || !ast_apply_ha(localaddr, &ours))) {
1835 if (externexpire && time(NULL) >= externexpire) {
1836 struct ast_hostent ahp;
1837 struct hostent *hp;
1839 externexpire = time(NULL) + externrefresh;
1840 if ((hp = ast_gethostbyname(externhost, &ahp))) {
1841 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1842 } else
1843 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1845 *us = externip.sin_addr;
1846 if (option_debug) {
1847 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n",
1848 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
1850 } else if (bindaddr.sin_addr.s_addr)
1851 *us = bindaddr.sin_addr;
1852 return AST_SUCCESS;
1855 /*! \brief Append to SIP dialog history
1856 \return Always returns 0 */
1857 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1859 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1860 __attribute__ ((format (printf, 2, 3)));
1862 /*! \brief Append to SIP dialog history with arg list */
1863 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1865 char buf[80], *c = buf; /* max history length */
1866 struct sip_history *hist;
1867 int l;
1869 vsnprintf(buf, sizeof(buf), fmt, ap);
1870 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1871 l = strlen(buf) + 1;
1872 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1873 return;
1874 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1875 free(hist);
1876 return;
1878 memcpy(hist->event, buf, l);
1879 if (p->history_entries == MAX_HISTORY_ENTRIES) {
1880 struct sip_history *oldest;
1881 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
1882 p->history_entries--;
1883 free(oldest);
1885 AST_LIST_INSERT_TAIL(p->history, hist, list);
1886 p->history_entries++;
1889 /*! \brief Append to SIP dialog history with arg list */
1890 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1892 va_list ap;
1894 if (!p)
1895 return;
1897 if (ast_test_flag(&p->flags[0], SIP_NO_HISTORY)
1898 && !recordhistory && !dumphistory) {
1899 return;
1902 va_start(ap, fmt);
1903 append_history_va(p, fmt, ap);
1904 va_end(ap);
1906 return;
1909 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
1910 static int retrans_pkt(const void *data)
1912 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
1913 int reschedule = DEFAULT_RETRANS;
1914 int xmitres = 0;
1916 /* Lock channel PVT */
1917 ast_mutex_lock(&pkt->owner->lock);
1919 if (pkt->retrans < MAX_RETRANS) {
1920 pkt->retrans++;
1921 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
1922 if (sipdebug && option_debug > 3)
1923 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);
1924 } else {
1925 int siptimer_a;
1927 if (sipdebug && option_debug > 3)
1928 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1929 if (!pkt->timer_a)
1930 pkt->timer_a = 2 ;
1931 else
1932 pkt->timer_a = 2 * pkt->timer_a;
1934 /* For non-invites, a maximum of 4 secs */
1935 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
1936 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1937 siptimer_a = 4000;
1939 /* Reschedule re-transmit */
1940 reschedule = siptimer_a;
1941 if (option_debug > 3)
1942 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);
1945 if (sip_debug_test_pvt(pkt->owner)) {
1946 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
1947 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
1948 pkt->retrans, sip_nat_mode(pkt->owner),
1949 ast_inet_ntoa(dst->sin_addr),
1950 ntohs(dst->sin_port), pkt->data);
1953 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1954 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1955 ast_mutex_unlock(&pkt->owner->lock);
1956 if (xmitres == XMIT_ERROR)
1957 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
1958 else
1959 return reschedule;
1961 /* Too many retries */
1962 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
1963 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1964 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n", pkt->owner->callid, pkt->seqno, (ast_test_flag(pkt, FLAG_FATAL)) ? "Critical" : "Non-critical", (ast_test_flag(pkt, FLAG_RESPONSE)) ? "Response" : "Request");
1965 } else if ((pkt->method == SIP_OPTIONS) && sipdebug) {
1966 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
1968 if (xmitres == XMIT_ERROR) {
1969 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission of transaction in call id %s \n", pkt->owner->callid);
1970 append_history(pkt->owner, "XmitErr", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1971 } else
1972 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1974 pkt->retransid = -1;
1976 if (ast_test_flag(pkt, FLAG_FATAL)) {
1977 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
1978 DEADLOCK_AVOIDANCE(&pkt->owner->lock); /* SIP_PVT, not channel */
1981 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
1982 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
1984 if (pkt->owner->owner) {
1985 sip_alreadygone(pkt->owner);
1986 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
1987 ast_queue_hangup(pkt->owner->owner);
1988 ast_channel_unlock(pkt->owner->owner);
1989 } else {
1990 /* If no channel owner, destroy now */
1992 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
1993 if (pkt->method != SIP_OPTIONS) {
1994 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
1995 sip_alreadygone(pkt->owner);
1996 if (option_debug)
1997 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
2002 if (pkt->method == SIP_BYE) {
2003 /* We're not getting answers on SIP BYE's. Tear down the call anyway. */
2004 if (pkt->owner->owner)
2005 ast_channel_unlock(pkt->owner->owner);
2006 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
2007 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
2010 /* In any case, go ahead and remove the packet */
2011 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
2012 if (cur == pkt)
2013 break;
2015 if (cur) {
2016 if (prev)
2017 prev->next = cur->next;
2018 else
2019 pkt->owner->packets = cur->next;
2020 ast_mutex_unlock(&pkt->owner->lock);
2021 free(cur);
2022 pkt = NULL;
2023 } else
2024 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
2025 if (pkt)
2026 ast_mutex_unlock(&pkt->owner->lock);
2027 return 0;
2030 /*! \brief Transmit packet with retransmits
2031 \return 0 on success, -1 on failure to allocate packet
2033 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
2035 struct sip_pkt *pkt;
2036 int siptimer_a = DEFAULT_RETRANS;
2037 int xmitres = 0;
2039 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
2040 return AST_FAILURE;
2041 memcpy(pkt->data, data, len);
2042 pkt->method = sipmethod;
2043 pkt->packetlen = len;
2044 pkt->next = p->packets;
2045 pkt->owner = p;
2046 pkt->seqno = seqno;
2047 if (resp)
2048 ast_set_flag(pkt, FLAG_RESPONSE);
2049 pkt->data[len] = '\0';
2050 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
2051 pkt->retransid = -1;
2052 if (fatal)
2053 ast_set_flag(pkt, FLAG_FATAL);
2054 if (pkt->timer_t1)
2055 siptimer_a = pkt->timer_t1 * 2;
2057 if (option_debug > 3 && sipdebug)
2058 ast_log(LOG_DEBUG, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
2059 pkt->retransid = -1;
2060 pkt->next = p->packets;
2061 p->packets = pkt;
2062 if (sipmethod == SIP_INVITE) {
2063 /* Note this is a pending invite */
2064 p->pendinginvite = seqno;
2067 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
2069 if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
2070 append_history(pkt->owner, "XmitErr", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
2071 return AST_FAILURE;
2072 } else {
2073 /* Schedule retransmission */
2074 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
2075 return AST_SUCCESS;
2079 /*! \brief Kill a SIP dialog (called by scheduler) */
2080 static int __sip_autodestruct(const void *data)
2082 struct sip_pvt *p = (struct sip_pvt *)data;
2084 /* If this is a subscription, tell the phone that we got a timeout */
2085 if (p->subscribed) {
2086 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */
2087 p->subscribed = NONE;
2088 append_history(p, "Subscribestatus", "timeout");
2089 if (option_debug > 2)
2090 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
2091 return 10000; /* Reschedule this destruction so that we know that it's gone */
2094 /* If there are packets still waiting for delivery, delay the destruction */
2095 /* via bug 12101, the two usages of SIP_NEEDDESTROY in the following block
2096 * of code make a sort of "safety relief valve", that allows sip channels
2097 * that were created via INVITE, then thru some sequence were CANCELED,
2098 * to die, rather than infinitely be rescheduled */
2099 if (p->packets && !ast_test_flag(&p->flags[0], SIP_NEEDDESTROY)) {
2100 if (option_debug > 2)
2101 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
2102 append_history(p, "ReliableXmit", "timeout");
2103 if (p->method == SIP_CANCEL || p->method == SIP_BYE) {
2104 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
2106 return 10000;
2109 /* If we're destroying a subscription, dereference peer object too */
2110 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
2111 ASTOBJ_UNREF(p->relatedpeer,sip_destroy_peer);
2113 /* Reset schedule ID */
2114 p->autokillid = -1;
2116 if (option_debug)
2117 ast_log(LOG_DEBUG, "Auto destroying SIP dialog '%s'\n", p->callid);
2118 append_history(p, "AutoDestroy", "%s", p->callid);
2119 if (p->owner) {
2120 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
2121 ast_queue_hangup(p->owner);
2122 } else if (p->refer && !ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) {
2123 if (option_debug > 2)
2124 ast_log(LOG_DEBUG, "Finally hanging up channel after transfer: %s\n", p->callid);
2125 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2126 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
2127 } else
2128 sip_destroy(p);
2129 return 0;
2132 /*! \brief Schedule destruction of SIP dialog */
2133 static void sip_scheddestroy(struct sip_pvt *p, int ms)
2135 if (ms < 0) {
2136 if (p->timer_t1 == 0)
2137 p->timer_t1 = 500; /* Set timer T1 if not set (RFC 3261) */
2138 ms = p->timer_t1 * 64;
2140 if (sip_debug_test_pvt(p))
2141 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
2142 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
2143 append_history(p, "SchedDestroy", "%d ms", ms);
2145 AST_SCHED_DEL(sched, p->autokillid);
2146 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
2149 /*! \brief Cancel destruction of SIP dialog */
2150 static int sip_cancel_destroy(struct sip_pvt *p)
2152 int res = 0;
2153 if (p->autokillid > -1) {
2154 if (!(res = ast_sched_del(sched, p->autokillid))) {
2155 append_history(p, "CancelDestroy", "");
2156 p->autokillid = -1;
2159 return res;
2162 /*! \brief Acknowledges receipt of a packet and stops retransmission
2163 * called with p locked*/
2164 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2166 struct sip_pkt *cur, *prev = NULL;
2168 /* Just in case... */
2169 char *msg;
2170 int res = FALSE;
2172 msg = sip_methods[sipmethod].text;
2174 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
2175 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
2176 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
2177 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
2178 if (!resp && (seqno == p->pendinginvite)) {
2179 if (option_debug)
2180 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
2181 p->pendinginvite = 0;
2183 /* this is our baby */
2184 res = TRUE;
2185 UNLINK(cur, p->packets, prev);
2186 if (cur->retransid > -1) {
2187 if (sipdebug && option_debug > 3)
2188 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
2190 /* This odd section is designed to thwart a
2191 * race condition in the packet scheduler. There are
2192 * two conditions under which deleting the packet from the
2193 * scheduler can fail.
2195 * 1. The packet has been removed from the scheduler because retransmission
2196 * is being attempted. The problem is that if the packet is currently attempting
2197 * retransmission and we are at this point in the code, then that MUST mean
2198 * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
2199 * lock temporarily to allow retransmission.
2201 * 2. The packet has reached its maximum number of retransmissions and has
2202 * been permanently removed from the packet scheduler. If this is the case, then
2203 * the packet's retransid will be set to -1. The atomicity of the setting and checking
2204 * of the retransid to -1 is ensured since in both cases p's lock is held.
2206 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
2207 DEADLOCK_AVOIDANCE(&p->lock);
2209 free(cur);
2210 break;
2213 if (option_debug)
2214 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");
2217 /*! \brief Pretend to ack all packets
2218 * called with p locked */
2219 static void __sip_pretend_ack(struct sip_pvt *p)
2221 struct sip_pkt *cur = NULL;
2223 while (p->packets) {
2224 int method;
2225 if (cur == p->packets) {
2226 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
2227 return;
2229 cur = p->packets;
2230 method = (cur->method) ? cur->method : find_sip_method(cur->data);
2231 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method);
2235 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2236 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2238 struct sip_pkt *cur;
2239 int res = -1;
2241 for (cur = p->packets; cur; cur = cur->next) {
2242 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
2243 (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
2244 /* this is our baby */
2245 if (cur->retransid > -1) {
2246 if (option_debug > 3 && sipdebug)
2247 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
2249 AST_SCHED_DEL(sched, cur->retransid);
2250 res = 0;
2251 break;
2254 if (option_debug)
2255 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");
2256 return res;
2260 /*! \brief Copy SIP request, parse it */
2261 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2263 memset(dst, 0, sizeof(*dst));
2264 memcpy(dst->data, src->data, sizeof(dst->data));
2265 dst->len = src->len;
2266 parse_request(dst);
2269 /*! \brief add a blank line if no body */
2270 static void add_blank(struct sip_request *req)
2272 if (!req->lines) {
2273 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2274 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2275 req->len += strlen(req->data + req->len);
2279 /*! \brief Transmit response on SIP request*/
2280 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2282 int res;
2284 add_blank(req);
2285 if (sip_debug_test_pvt(p)) {
2286 const struct sockaddr_in *dst = sip_real_dst(p);
2288 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
2289 reliable ? "Reliably " : "", sip_nat_mode(p),
2290 ast_inet_ntoa(dst->sin_addr),
2291 ntohs(dst->sin_port), req->data);
2293 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2294 struct sip_request tmp;
2295 parse_copy(&tmp, req);
2296 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
2297 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
2299 res = (reliable) ?
2300 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2301 __sip_xmit(p, req->data, req->len);
2302 if (res > 0)
2303 return 0;
2304 return res;
2307 /*! \brief Send SIP Request to the other part of the dialogue */
2308 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2310 int res;
2312 add_blank(req);
2313 if (sip_debug_test_pvt(p)) {
2314 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
2315 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);
2316 else
2317 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);
2319 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2320 struct sip_request tmp;
2321 parse_copy(&tmp, req);
2322 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
2324 res = (reliable) ?
2325 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2326 __sip_xmit(p, req->data, req->len);
2327 return res;
2330 /*! \brief Locate closing quote in a string, skipping escaped quotes.
2331 * optionally with a limit on the search.
2332 * start must be past the first quote.
2334 static const char *find_closing_quote(const char *start, const char *lim)
2336 char last_char = '\0';
2337 const char *s;
2338 for (s = start; *s && s != lim; last_char = *s++) {
2339 if (*s == '"' && last_char != '\\')
2340 break;
2342 return s;
2345 /*! \brief Pick out text in brackets from character string
2346 \return pointer to terminated stripped string
2347 \param tmp input string that will be modified
2348 Examples:
2350 "foo" <bar> valid input, returns bar
2351 foo returns the whole string
2352 < "foo ... > returns the string between brackets
2353 < "foo... bogus (missing closing bracket), returns the whole string
2354 XXX maybe should still skip the opening bracket
2356 static char *get_in_brackets(char *tmp)
2358 const char *parse = tmp;
2359 char *first_bracket;
2362 * Skip any quoted text until we find the part in brackets.
2363 * On any error give up and return the full string.
2365 while ( (first_bracket = strchr(parse, '<')) ) {
2366 char *first_quote = strchr(parse, '"');
2368 if (!first_quote || first_quote > first_bracket)
2369 break; /* no need to look at quoted part */
2370 /* the bracket is within quotes, so ignore it */
2371 parse = find_closing_quote(first_quote + 1, NULL);
2372 if (!*parse) { /* not found, return full string ? */
2373 /* XXX or be robust and return in-bracket part ? */
2374 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
2375 break;
2377 parse++;
2379 if (first_bracket) {
2380 char *second_bracket = strchr(first_bracket + 1, '>');
2381 if (second_bracket) {
2382 *second_bracket = '\0';
2383 tmp = first_bracket + 1;
2384 } else {
2385 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
2388 return tmp;
2391 /*! \brief Send SIP MESSAGE text within a call
2392 Called from PBX core sendtext() application */
2393 static int sip_sendtext(struct ast_channel *ast, const char *text)
2395 struct sip_pvt *p = ast->tech_pvt;
2396 int debug = sip_debug_test_pvt(p);
2398 if (debug)
2399 ast_verbose("Sending text %s on %s\n", text, ast->name);
2400 if (!p)
2401 return -1;
2402 if (ast_strlen_zero(text))
2403 return 0;
2404 if (debug)
2405 ast_verbose("Really sending text %s on %s\n", text, ast->name);
2406 transmit_message_with_text(p, text);
2407 return 0;
2410 /*! \brief Update peer object in realtime storage
2411 If the Asterisk system name is set in asterisk.conf, we will use
2412 that name and store that in the "regserver" field in the sippeers
2413 table to facilitate multi-server setups.
2415 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
2417 char port[10];
2418 char ipaddr[INET_ADDRSTRLEN];
2419 char regseconds[20];
2421 char *sysname = ast_config_AST_SYSTEM_NAME;
2422 char *syslabel = NULL;
2424 time_t nowtime = time(NULL) + expirey;
2425 const char *fc = fullcontact ? "fullcontact" : NULL;
2427 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
2428 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2429 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2431 if (ast_strlen_zero(sysname)) /* No system name, disable this */
2432 sysname = NULL;
2433 else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME))
2434 syslabel = "regserver";
2436 if (fc)
2437 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2438 "port", port, "regseconds", regseconds,
2439 "username", username, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
2440 else
2441 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2442 "port", port, "regseconds", regseconds,
2443 "username", username, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
2446 /*! \brief Automatically add peer extension to dial plan */
2447 static void register_peer_exten(struct sip_peer *peer, int onoff)
2449 char multi[256];
2450 char *stringp, *ext, *context;
2452 /* XXX note that global_regcontext is both a global 'enable' flag and
2453 * the name of the global regexten context, if not specified
2454 * individually.
2456 if (ast_strlen_zero(global_regcontext))
2457 return;
2459 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
2460 stringp = multi;
2461 while ((ext = strsep(&stringp, "&"))) {
2462 if ((context = strchr(ext, '@'))) {
2463 *context++ = '\0'; /* split ext@context */
2464 if (!ast_context_find(context)) {
2465 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
2466 continue;
2468 } else {
2469 context = global_regcontext;
2471 if (onoff)
2472 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2473 ast_strdup(peer->name), ast_free, "SIP");
2474 else
2475 ast_context_remove_extension(context, ext, 1, NULL);
2479 /*! \brief Destroy peer object from memory */
2480 static void sip_destroy_peer(struct sip_peer *peer)
2482 if (option_debug > 2)
2483 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
2485 /* Delete it, it needs to disappear */
2486 if (peer->call)
2487 sip_destroy(peer->call);
2489 if (peer->mwipvt) /* We have an active subscription, delete it */
2490 sip_destroy(peer->mwipvt);
2492 if (peer->chanvars) {
2493 ast_variables_destroy(peer->chanvars);
2494 peer->chanvars = NULL;
2497 register_peer_exten(peer, FALSE);
2498 ast_free_ha(peer->ha);
2499 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
2500 apeerobjs--;
2501 else if (ast_test_flag(&peer->flags[0], SIP_REALTIME))
2502 rpeerobjs--;
2503 else
2504 speerobjs--;
2505 clear_realm_authentication(peer->auth);
2506 peer->auth = NULL;
2507 free(peer);
2510 /*! \brief Update peer data in database (if used) */
2511 static void update_peer(struct sip_peer *p, int expiry)
2513 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2514 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
2515 (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
2516 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
2521 /*! \brief realtime_peer: Get peer from realtime storage
2522 * Checks the "sippeers" realtime family from extconfig.conf
2523 * \todo Consider adding check of port address when matching here to follow the same
2524 * algorithm as for static peers. Will we break anything by adding that?
2526 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
2528 struct sip_peer *peer=NULL;
2529 struct ast_variable *var = NULL;
2530 struct ast_config *peerlist = NULL;
2531 struct ast_variable *tmp;
2532 struct ast_flags flags = {0};
2533 const char *iabuf = NULL;
2534 char portstring[6]; /*up to five digits plus null terminator*/
2535 const char *insecure;
2536 char *cat = NULL;
2537 unsigned short portnum;
2539 /* First check on peer name */
2540 if (newpeername) {
2541 var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", NULL);
2542 if (!var && sin)
2543 var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), NULL);
2544 if (!var) {
2545 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
2546 /*!\note
2547 * If this one loaded something, then we need to ensure that the host
2548 * field matched. The only reason why we can't have this as a criteria
2549 * is because we only have the IP address and the host field might be
2550 * set as a name (and the reverse PTR might not match).
2552 if (var && sin) {
2553 for (tmp = var; tmp; tmp = tmp->next) {
2554 if (!strcasecmp(tmp->name, "host")) {
2555 struct hostent *hp;
2556 struct ast_hostent ahp;
2557 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
2558 /* No match */
2559 ast_variables_destroy(var);
2560 var = NULL;
2562 break;
2569 if (!var && sin) { /* Then check on IP address */
2570 iabuf = ast_inet_ntoa(sin->sin_addr);
2571 portnum = ntohs(sin->sin_port);
2572 sprintf(portstring, "%d", portnum);
2573 var = ast_load_realtime("sippeers", "host", iabuf, "port", portstring, NULL); /* First check for fixed IP hosts */
2574 if (!var)
2575 var = ast_load_realtime("sippeers", "ipaddr", iabuf, "port", portstring, NULL); /* Then check for registered hosts */
2576 if (!var) {
2577 peerlist = ast_load_realtime_multientry("sippeers", "host", iabuf, NULL); /*No exact match, see if port is insecure, try host match first*/
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;
2589 if(!var) {
2590 ast_config_destroy(peerlist);
2591 peerlist = NULL; /*for safety's sake*/
2592 cat = NULL;
2593 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", iabuf, NULL); /*No exact match, see if port is insecure, now try ip address match*/
2594 if(peerlist) {
2595 while((cat = ast_category_browse(peerlist, cat)))
2597 insecure = ast_variable_retrieve(peerlist, cat, "insecure");
2598 set_insecure_flags(&flags, insecure, -1);
2599 if(ast_test_flag(&flags, SIP_INSECURE_PORT)) {
2600 var = ast_category_root(peerlist, cat);
2601 break;
2609 if (!var) {
2610 if(peerlist)
2611 ast_config_destroy(peerlist);
2612 return NULL;
2615 for (tmp = var; tmp; tmp = tmp->next) {
2616 /* If this is type=user, then skip this object. */
2617 if (!strcasecmp(tmp->name, "type") &&
2618 !strcasecmp(tmp->value, "user")) {
2619 ast_variables_destroy(var);
2620 return NULL;
2621 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
2622 newpeername = tmp->value;
2626 if (!newpeername) { /* Did not find peer in realtime */
2627 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
2628 if(peerlist)
2629 ast_config_destroy(peerlist);
2630 else
2631 ast_variables_destroy(var);
2632 return NULL;
2635 /* Peer found in realtime, now build it in memory */
2636 peer = build_peer(newpeername, var, NULL, 1);
2637 if (!peer) {
2638 if(peerlist)
2639 ast_config_destroy(peerlist);
2640 else
2641 ast_variables_destroy(var);
2642 return NULL;
2645 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
2646 /* Cache peer */
2647 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
2648 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
2649 if (!AST_SCHED_DEL(sched, peer->expire)) {
2650 struct sip_peer *peer_ptr = peer;
2651 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
2653 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, ASTOBJ_REF(peer));
2654 if (peer->expire == -1) {
2655 struct sip_peer *peer_ptr = peer;
2656 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
2659 ASTOBJ_CONTAINER_LINK(&peerl,peer);
2661 ast_set_flag(&peer->flags[0], SIP_REALTIME);
2662 if(peerlist)
2663 ast_config_destroy(peerlist);
2664 else
2665 ast_variables_destroy(var);
2666 return peer;
2669 /*! \brief Support routine for find_peer */
2670 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
2672 /* We know name is the first field, so we can cast */
2673 struct sip_peer *p = (struct sip_peer *) name;
2674 return !(!inaddrcmp(&p->addr, sin) ||
2675 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
2676 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
2679 /*! \brief Locate peer by name or ip address
2680 * This is used on incoming SIP message to find matching peer on ip
2681 or outgoing message to find matching peer on name */
2682 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int devstate_only)
2684 struct sip_peer *p = NULL;
2686 if (peer)
2687 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
2688 else
2689 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
2691 if (!p && (realtime || devstate_only))
2692 p = realtime_peer(peer, sin, devstate_only);
2694 return p;
2697 /*! \brief Remove user object from in-memory storage */
2698 static void sip_destroy_user(struct sip_user *user)
2700 if (option_debug > 2)
2701 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
2702 ast_free_ha(user->ha);
2703 if (user->chanvars) {
2704 ast_variables_destroy(user->chanvars);
2705 user->chanvars = NULL;
2707 if (ast_test_flag(&user->flags[0], SIP_REALTIME))
2708 ruserobjs--;
2709 else
2710 suserobjs--;
2711 free(user);
2714 /*! \brief Load user from realtime storage
2715 * Loads user from "sipusers" category in realtime (extconfig.conf)
2716 * Users are matched on From: user name (the domain in skipped) */
2717 static struct sip_user *realtime_user(const char *username)
2719 struct ast_variable *var;
2720 struct ast_variable *tmp;
2721 struct sip_user *user = NULL;
2723 var = ast_load_realtime("sipusers", "name", username, NULL);
2725 if (!var)
2726 return NULL;
2728 for (tmp = var; tmp; tmp = tmp->next) {
2729 if (!strcasecmp(tmp->name, "type") &&
2730 !strcasecmp(tmp->value, "peer")) {
2731 ast_variables_destroy(var);
2732 return NULL;
2736 user = build_user(username, var, NULL, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2738 if (!user) { /* No user found */
2739 ast_variables_destroy(var);
2740 return NULL;
2743 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2744 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2745 suserobjs++;
2746 ASTOBJ_CONTAINER_LINK(&userl,user);
2747 } else {
2748 /* Move counter from s to r... */
2749 suserobjs--;
2750 ruserobjs++;
2752 ast_set_flag(&user->flags[0], SIP_REALTIME);
2753 ast_variables_destroy(var);
2754 return user;
2757 /*! \brief Locate user by name
2758 * Locates user by name (From: sip uri user name part) first
2759 * from in-memory list (static configuration) then from
2760 * realtime storage (defined in extconfig.conf) */
2761 static struct sip_user *find_user(const char *name, int realtime)
2763 struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
2764 if (!u && realtime)
2765 u = realtime_user(name);
2766 return u;
2769 /*! \brief Set nat mode on the various data sockets */
2770 static void do_setnat(struct sip_pvt *p, int natflags)
2772 const char *mode = natflags ? "On" : "Off";
2774 if (p->rtp) {
2775 if (option_debug)
2776 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", mode);
2777 ast_rtp_setnat(p->rtp, natflags);
2779 if (p->vrtp) {
2780 if (option_debug)
2781 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", mode);
2782 ast_rtp_setnat(p->vrtp, natflags);
2784 if (p->udptl) {
2785 if (option_debug)
2786 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", mode);
2787 ast_udptl_setnat(p->udptl, natflags);
2791 /*! \brief Create address structure from peer reference.
2792 * return -1 on error, 0 on success.
2794 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
2796 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
2797 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
2798 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
2799 dialog->recv = dialog->sa;
2800 } else
2801 return -1;
2803 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
2804 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
2805 dialog->capability = peer->capability;
2806 if ((!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(dialog->capability & AST_FORMAT_VIDEO_MASK)) && dialog->vrtp) {
2807 ast_rtp_destroy(dialog->vrtp);
2808 dialog->vrtp = NULL;
2810 dialog->prefs = peer->prefs;
2811 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
2812 dialog->t38.capability = global_t38_capability;
2813 if (dialog->udptl) {
2814 if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_FEC )
2815 dialog->t38.capability |= T38FAX_UDP_EC_FEC;
2816 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
2817 dialog->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
2818 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_NONE )
2819 dialog->t38.capability |= T38FAX_UDP_EC_NONE;
2820 dialog->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
2821 if (option_debug > 1)
2822 ast_log(LOG_DEBUG,"Our T38 capability (%d)\n", dialog->t38.capability);
2824 dialog->t38.jointcapability = dialog->t38.capability;
2825 } else if (dialog->udptl) {
2826 ast_udptl_destroy(dialog->udptl);
2827 dialog->udptl = NULL;
2829 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE );
2831 if (dialog->rtp) {
2832 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
2833 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
2834 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
2835 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
2836 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
2837 /* Set Frame packetization */
2838 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
2839 dialog->autoframing = peer->autoframing;
2841 if (dialog->vrtp) {
2842 ast_rtp_setdtmf(dialog->vrtp, 0);
2843 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
2844 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
2845 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
2846 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
2849 ast_string_field_set(dialog, peername, peer->name);
2850 ast_string_field_set(dialog, authname, peer->username);
2851 ast_string_field_set(dialog, username, peer->username);
2852 ast_string_field_set(dialog, peersecret, peer->secret);
2853 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
2854 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
2855 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
2856 ast_string_field_set(dialog, tohost, peer->tohost);
2857 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
2858 if (!dialog->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
2859 char *tmpcall;
2860 char *c;
2861 tmpcall = ast_strdupa(dialog->callid);
2862 c = strchr(tmpcall, '@');
2863 if (c) {
2864 *c = '\0';
2865 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
2868 if (ast_strlen_zero(dialog->tohost))
2869 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
2870 if (!ast_strlen_zero(peer->fromdomain))
2871 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
2872 if (!ast_strlen_zero(peer->fromuser))
2873 ast_string_field_set(dialog, fromuser, peer->fromuser);
2874 if (!ast_strlen_zero(peer->language))
2875 ast_string_field_set(dialog, language, peer->language);
2876 dialog->maxtime = peer->maxms;
2877 dialog->callgroup = peer->callgroup;
2878 dialog->pickupgroup = peer->pickupgroup;
2879 dialog->peerauth = peer->auth;
2880 dialog->allowtransfer = peer->allowtransfer;
2881 /* Set timer T1 to RTT for this peer (if known by qualify=) */
2882 /* Minimum is settable or default to 100 ms */
2883 if (peer->maxms && peer->lastms)
2884 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
2885 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
2886 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
2887 dialog->noncodeccapability |= AST_RTP_DTMF;
2888 else
2889 dialog->noncodeccapability &= ~AST_RTP_DTMF;
2890 dialog->jointnoncodeccapability = dialog->noncodeccapability;
2891 ast_string_field_set(dialog, context, peer->context);
2892 dialog->rtptimeout = peer->rtptimeout;
2893 if (peer->call_limit)
2894 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
2895 dialog->maxcallbitrate = peer->maxcallbitrate;
2897 return 0;
2900 /*! \brief create address structure from peer name
2901 * Or, if peer not found, find it in the global DNS
2902 * returns TRUE (-1) on failure, FALSE on success */
2903 static int create_addr(struct sip_pvt *dialog, const char *opeer)
2905 struct hostent *hp;
2906 struct ast_hostent ahp;
2907 struct sip_peer *p;
2908 char *port;
2909 int portno;
2910 char host[MAXHOSTNAMELEN], *hostn;
2911 char peer[256];
2913 ast_copy_string(peer, opeer, sizeof(peer));
2914 port = strchr(peer, ':');
2915 if (port)
2916 *port++ = '\0';
2917 dialog->sa.sin_family = AF_INET;
2918 dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
2919 p = find_peer(peer, NULL, 1, 0);
2921 if (p) {
2922 int res = create_addr_from_peer(dialog, p);
2923 if (port) {
2924 portno = atoi(port);
2925 dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
2927 ASTOBJ_UNREF(p, sip_destroy_peer);
2928 return res;
2930 hostn = peer;
2931 portno = port ? atoi(port) : STANDARD_SIP_PORT;
2932 if (srvlookup) {
2933 char service[MAXHOSTNAMELEN];
2934 int tportno;
2935 int ret;
2937 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
2938 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
2939 if (ret > 0) {
2940 hostn = host;
2941 portno = tportno;
2944 hp = ast_gethostbyname(hostn, &ahp);
2945 if (!hp) {
2946 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2947 return -1;
2949 ast_string_field_set(dialog, tohost, peer);
2950 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
2951 dialog->sa.sin_port = htons(portno);
2952 dialog->recv = dialog->sa;
2953 return 0;
2956 /*! \brief Scheduled congestion on a call */
2957 static int auto_congest(const void *nothing)
2959 struct sip_pvt *p = (struct sip_pvt *)nothing;
2961 ast_mutex_lock(&p->lock);
2962 p->initid = -1;
2963 if (p->owner) {
2964 /* XXX fails on possible deadlock */
2965 if (!ast_channel_trylock(p->owner)) {
2966 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
2967 append_history(p, "Cong", "Auto-congesting (timer)");
2968 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
2969 ast_channel_unlock(p->owner);
2972 ast_mutex_unlock(&p->lock);
2973 return 0;
2977 /*! \brief Initiate SIP call from PBX
2978 * used from the dial() application */
2979 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2981 int res, xmitres = 0;
2982 struct sip_pvt *p;
2983 struct varshead *headp;
2984 struct ast_var_t *current;
2985 const char *referer = NULL; /* SIP refererer */
2987 p = ast->tech_pvt;
2988 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2989 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2990 return -1;
2993 /* Check whether there is vxml_url, distinctive ring variables */
2994 headp=&ast->varshead;
2995 AST_LIST_TRAVERSE(headp,current,entries) {
2996 /* Check whether there is a VXML_URL variable */
2997 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2998 p->options->vxml_url = ast_var_value(current);
2999 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
3000 p->options->uri_options = ast_var_value(current);
3001 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
3002 /* Check whether there is a ALERT_INFO variable */
3003 p->options->distinctive_ring = ast_var_value(current);
3004 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
3005 /* Check whether there is a variable with a name starting with SIPADDHEADER */
3006 p->options->addsipheaders = 1;
3007 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
3008 /* This is a transfered call */
3009 p->options->transfer = 1;
3010 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
3011 /* This is the referer */
3012 referer = ast_var_value(current);
3013 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
3014 /* We're replacing a call. */
3015 p->options->replaces = ast_var_value(current);
3016 } else if (!strcasecmp(ast_var_name(current), "T38CALL")) {
3017 p->t38.state = T38_LOCAL_DIRECT;
3018 if (option_debug)
3019 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
3024 res = 0;
3025 ast_set_flag(&p->flags[0], SIP_OUTGOING);
3027 if (p->options->transfer) {
3028 char buf[SIPBUFSIZE/2];
3030 if (referer) {
3031 if (sipdebug && option_debug > 2)
3032 ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->username, referer);
3033 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
3034 } else
3035 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
3036 ast_string_field_set(p, cid_name, buf);
3038 if (option_debug)
3039 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
3041 res = update_call_counter(p, INC_CALL_RINGING);
3042 if ( res != -1 ) {
3043 p->callingpres = ast->cid.cid_pres;
3044 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
3045 p->jointnoncodeccapability = p->noncodeccapability;
3047 /* If there are no audio formats left to offer, punt */
3048 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
3049 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
3050 res = -1;
3051 } else {
3052 p->t38.jointcapability = p->t38.capability;
3053 if (option_debug > 1)
3054 ast_log(LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
3055 xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
3056 if (xmitres == XMIT_ERROR)
3057 return -1; /* Transmission error */
3059 p->invitestate = INV_CALLING;
3061 /* Initialize auto-congest time */
3062 AST_SCHED_DEL(sched, p->initid);
3063 p->initid = ast_sched_add(sched, p->maxtime ? (p->maxtime * 4) : SIP_TRANS_TIMEOUT, auto_congest, p);
3066 return res;
3069 /*! \brief Destroy registry object
3070 Objects created with the register= statement in static configuration */
3071 static void sip_registry_destroy(struct sip_registry *reg)
3073 /* Really delete */
3074 if (option_debug > 2)
3075 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
3077 if (reg->call) {
3078 /* Clear registry before destroying to ensure
3079 we don't get reentered trying to grab the registry lock */
3080 reg->call->registry = NULL;
3081 if (option_debug > 2)
3082 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
3083 sip_destroy(reg->call);
3085 AST_SCHED_DEL(sched, reg->expire);
3086 AST_SCHED_DEL(sched, reg->timeout);
3087 ast_string_field_free_memory(reg);
3088 regobjs--;
3089 free(reg);
3093 /*! \brief Execute destruction of SIP dialog structure, release memory */
3094 static int __sip_destroy(struct sip_pvt *p, int lockowner)
3096 struct sip_pvt *cur, *prev = NULL;
3097 struct sip_pkt *cp;
3099 /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
3100 if (p->rtp && ast_rtp_get_bridged(p->rtp)) {
3101 ast_verbose("Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
3102 return -1;
3105 if (p->vrtp && ast_rtp_get_bridged(p->vrtp)) {
3106 ast_verbose("Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
3107 return -1;
3110 if (sip_debug_test_pvt(p) || option_debug > 2)
3111 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
3113 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
3114 update_call_counter(p, DEC_CALL_LIMIT);
3115 if (option_debug > 1)
3116 ast_log(LOG_DEBUG, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
3119 /* Unlink us from the owner if we have one */
3120 if (p->owner) {
3121 if (lockowner)
3122 ast_channel_lock(p->owner);
3123 if (option_debug)
3124 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
3125 p->owner->tech_pvt = NULL;
3126 /* Make sure that the channel knows its backend is going away */
3127 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
3128 if (lockowner)
3129 ast_channel_unlock(p->owner);
3130 /* Give the channel a chance to react before deallocation */
3131 usleep(1);
3134 /* Remove link from peer to subscription of MWI */
3135 if (p->relatedpeer) {
3136 if (p->relatedpeer->mwipvt == p) {
3137 p->relatedpeer->mwipvt = NULL;
3139 ASTOBJ_UNREF(p->relatedpeer, sip_destroy_peer);
3142 if (dumphistory)
3143 sip_dump_history(p);
3145 if (p->options)
3146 free(p->options);
3148 if (p->stateid > -1)
3149 ast_extension_state_del(p->stateid, NULL);
3150 AST_SCHED_DEL(sched, p->initid);
3151 AST_SCHED_DEL(sched, p->waitid);
3152 AST_SCHED_DEL(sched, p->autokillid);
3154 if (p->rtp) {
3155 ast_rtp_destroy(p->rtp);
3157 if (p->vrtp) {
3158 ast_rtp_destroy(p->vrtp);
3160 if (p->udptl)
3161 ast_udptl_destroy(p->udptl);
3162 if (p->refer)
3163 free(p->refer);
3164 if (p->route) {
3165 free_old_route(p->route);
3166 p->route = NULL;
3168 if (p->registry) {
3169 if (p->registry->call == p)
3170 p->registry->call = NULL;
3171 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
3174 /* Clear history */
3175 if (p->history) {
3176 struct sip_history *hist;
3177 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
3178 free(hist);
3179 p->history_entries--;
3181 free(p->history);
3182 p->history = NULL;
3185 for (prev = NULL, cur = iflist; cur; prev = cur, cur = cur->next) {
3186 if (cur == p) {
3187 UNLINK(cur, iflist, prev);
3188 break;
3191 if (!cur) {
3192 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
3193 return 0;
3196 /* remove all current packets in this dialog */
3197 while((cp = p->packets)) {
3198 p->packets = p->packets->next;
3199 AST_SCHED_DEL(sched, cp->retransid);
3200 free(cp);
3202 if (p->chanvars) {
3203 ast_variables_destroy(p->chanvars);
3204 p->chanvars = NULL;
3206 ast_mutex_destroy(&p->lock);
3208 ast_string_field_free_memory(p);
3210 free(p);
3211 return 0;
3214 /*! \brief update_call_counter: Handle call_limit for SIP users
3215 * Setting a call-limit will cause calls above the limit not to be accepted.
3217 * Remember that for a type=friend, there's one limit for the user and
3218 * another for the peer, not a combined call limit.
3219 * This will cause unexpected behaviour in subscriptions, since a "friend"
3220 * is *two* devices in Asterisk, not one.
3222 * Thought: For realtime, we should propably update storage with inuse counter...
3224 * \return 0 if call is ok (no call limit, below treshold)
3225 * -1 on rejection of call
3228 static int update_call_counter(struct sip_pvt *fup, int event)
3230 char name[256];
3231 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
3232 int outgoing = ast_test_flag(&fup->flags[1], SIP_PAGE2_OUTGOING_CALL);
3233 struct sip_user *u = NULL;
3234 struct sip_peer *p = NULL;
3236 if (option_debug > 2)
3237 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
3239 /* Test if we need to check call limits, in order to avoid
3240 realtime lookups if we do not need it */
3241 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
3242 return 0;
3244 ast_copy_string(name, fup->username, sizeof(name));
3246 /* Check the list of users only for incoming calls */
3247 if (global_limitonpeers == FALSE && !outgoing && (u = find_user(name, 1))) {
3248 inuse = &u->inUse;
3249 call_limit = &u->call_limit;
3250 inringing = NULL;
3251 } else if ( (p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, 1, 0) ) ) { /* Try to find peer */
3252 inuse = &p->inUse;
3253 call_limit = &p->call_limit;
3254 inringing = &p->inRinging;
3255 ast_copy_string(name, fup->peername, sizeof(name));
3257 if (!p && !u) {
3258 if (option_debug > 1)
3259 ast_log(LOG_DEBUG, "%s is not a local device, no call limit\n", name);
3260 return 0;
3263 switch(event) {
3264 /* incoming and outgoing affects the inUse counter */
3265 case DEC_CALL_LIMIT:
3266 if ( *inuse > 0 ) {
3267 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
3268 (*inuse)--;
3269 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
3271 } else {
3272 *inuse = 0;
3274 if (inringing) {
3275 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3276 if (*inringing > 0)
3277 (*inringing)--;
3278 else if (!ast_test_flag(&p->flags[0], SIP_REALTIME) || ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS))
3279 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", fup->peername);
3280 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3283 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && global_notifyhold) {
3284 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
3285 sip_peer_hold(fup, 0);
3287 if (option_debug > 1 || sipdebug) {
3288 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
3290 break;
3292 case INC_CALL_RINGING:
3293 case INC_CALL_LIMIT:
3294 if (*call_limit > 0 ) {
3295 if (*inuse >= *call_limit) {
3296 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);
3297 if (u)
3298 ASTOBJ_UNREF(u, sip_destroy_user);
3299 else
3300 ASTOBJ_UNREF(p, sip_destroy_peer);
3301 return -1;
3304 if (inringing && (event == INC_CALL_RINGING)) {
3305 if (!ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3306 (*inringing)++;
3307 ast_set_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3310 /* Continue */
3311 (*inuse)++;
3312 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
3313 if (option_debug > 1 || sipdebug) {
3314 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
3316 break;
3318 case DEC_CALL_RINGING:
3319 if (inringing) {
3320 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3321 if (*inringing > 0)
3322 (*inringing)--;
3323 else if (!ast_test_flag(&p->flags[0], SIP_REALTIME) || ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS))
3324 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", p->name);
3325 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3328 break;
3330 default:
3331 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
3333 if (p) {
3334 ast_device_state_changed("SIP/%s", p->name);
3335 ASTOBJ_UNREF(p, sip_destroy_peer);
3336 } else /* u must be set */
3337 ASTOBJ_UNREF(u, sip_destroy_user);
3338 return 0;
3341 /*! \brief Destroy SIP call structure */
3342 static void sip_destroy(struct sip_pvt *p)
3344 ast_mutex_lock(&iflock);
3345 if (option_debug > 2)
3346 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
3347 __sip_destroy(p, 1);
3348 ast_mutex_unlock(&iflock);
3351 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
3352 static int hangup_sip2cause(int cause)
3354 /* Possible values taken from causes.h */
3356 switch(cause) {
3357 case 401: /* Unauthorized */
3358 return AST_CAUSE_CALL_REJECTED;
3359 case 403: /* Not found */
3360 return AST_CAUSE_CALL_REJECTED;
3361 case 404: /* Not found */
3362 return AST_CAUSE_UNALLOCATED;
3363 case 405: /* Method not allowed */
3364 return AST_CAUSE_INTERWORKING;
3365 case 407: /* Proxy authentication required */
3366 return AST_CAUSE_CALL_REJECTED;
3367 case 408: /* No reaction */
3368 return AST_CAUSE_NO_USER_RESPONSE;
3369 case 409: /* Conflict */
3370 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
3371 case 410: /* Gone */
3372 return AST_CAUSE_UNALLOCATED;
3373 case 411: /* Length required */
3374 return AST_CAUSE_INTERWORKING;
3375 case 413: /* Request entity too large */
3376 return AST_CAUSE_INTERWORKING;
3377 case 414: /* Request URI too large */
3378 return AST_CAUSE_INTERWORKING;
3379 case 415: /* Unsupported media type */
3380 return AST_CAUSE_INTERWORKING;
3381 case 420: /* Bad extension */
3382 return AST_CAUSE_NO_ROUTE_DESTINATION;
3383 case 480: /* No answer */
3384 return AST_CAUSE_NO_ANSWER;
3385 case 481: /* No answer */
3386 return AST_CAUSE_INTERWORKING;
3387 case 482: /* Loop detected */
3388 return AST_CAUSE_INTERWORKING;
3389 case 483: /* Too many hops */
3390 return AST_CAUSE_NO_ANSWER;
3391 case 484: /* Address incomplete */
3392 return AST_CAUSE_INVALID_NUMBER_FORMAT;
3393 case 485: /* Ambigous */
3394 return AST_CAUSE_UNALLOCATED;
3395 case 486: /* Busy everywhere */
3396 return AST_CAUSE_BUSY;
3397 case 487: /* Request terminated */
3398 return AST_CAUSE_INTERWORKING;
3399 case 488: /* No codecs approved */
3400 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3401 case 491: /* Request pending */
3402 return AST_CAUSE_INTERWORKING;
3403 case 493: /* Undecipherable */
3404 return AST_CAUSE_INTERWORKING;
3405 case 500: /* Server internal failure */
3406 return AST_CAUSE_FAILURE;
3407 case 501: /* Call rejected */
3408 return AST_CAUSE_FACILITY_REJECTED;
3409 case 502:
3410 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
3411 case 503: /* Service unavailable */
3412 return AST_CAUSE_CONGESTION;
3413 case 504: /* Gateway timeout */
3414 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
3415 case 505: /* SIP version not supported */
3416 return AST_CAUSE_INTERWORKING;
3417 case 600: /* Busy everywhere */
3418 return AST_CAUSE_USER_BUSY;
3419 case 603: /* Decline */
3420 return AST_CAUSE_CALL_REJECTED;
3421 case 604: /* Does not exist anywhere */
3422 return AST_CAUSE_UNALLOCATED;
3423 case 606: /* Not acceptable */
3424 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3425 default:
3426 return AST_CAUSE_NORMAL;
3428 /* Never reached */
3429 return 0;
3432 /*! \brief Convert Asterisk hangup causes to SIP codes
3433 \verbatim
3434 Possible values from causes.h
3435 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
3436 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
3438 In addition to these, a lot of PRI codes is defined in causes.h
3439 ...should we take care of them too ?
3441 Quote RFC 3398
3443 ISUP Cause value SIP response
3444 ---------------- ------------
3445 1 unallocated number 404 Not Found
3446 2 no route to network 404 Not found
3447 3 no route to destination 404 Not found
3448 16 normal call clearing --- (*)
3449 17 user busy 486 Busy here
3450 18 no user responding 408 Request Timeout
3451 19 no answer from the user 480 Temporarily unavailable
3452 20 subscriber absent 480 Temporarily unavailable
3453 21 call rejected 403 Forbidden (+)
3454 22 number changed (w/o diagnostic) 410 Gone
3455 22 number changed (w/ diagnostic) 301 Moved Permanently
3456 23 redirection to new destination 410 Gone
3457 26 non-selected user clearing 404 Not Found (=)
3458 27 destination out of order 502 Bad Gateway
3459 28 address incomplete 484 Address incomplete
3460 29 facility rejected 501 Not implemented
3461 31 normal unspecified 480 Temporarily unavailable
3462 \endverbatim
3464 static const char *hangup_cause2sip(int cause)
3466 switch (cause) {
3467 case AST_CAUSE_UNALLOCATED: /* 1 */
3468 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
3469 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
3470 return "404 Not Found";
3471 case AST_CAUSE_CONGESTION: /* 34 */
3472 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
3473 return "503 Service Unavailable";
3474 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
3475 return "408 Request Timeout";
3476 case AST_CAUSE_NO_ANSWER: /* 19 */
3477 case AST_CAUSE_UNREGISTERED: /* 20 */
3478 return "480 Temporarily unavailable";
3479 case AST_CAUSE_CALL_REJECTED: /* 21 */
3480 return "403 Forbidden";
3481 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
3482 return "410 Gone";
3483 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
3484 return "480 Temporarily unavailable";
3485 case AST_CAUSE_INVALID_NUMBER_FORMAT:
3486 return "484 Address incomplete";
3487 case AST_CAUSE_USER_BUSY:
3488 return "486 Busy here";
3489 case AST_CAUSE_FAILURE:
3490 return "500 Server internal failure";
3491 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
3492 return "501 Not Implemented";
3493 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
3494 return "503 Service Unavailable";
3495 /* Used in chan_iax2 */
3496 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
3497 return "502 Bad Gateway";
3498 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
3499 return "488 Not Acceptable Here";
3501 case AST_CAUSE_NOTDEFINED:
3502 default:
3503 if (option_debug)
3504 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
3505 return NULL;
3508 /* Never reached */
3509 return 0;
3513 /*! \brief sip_hangup: Hangup SIP call
3514 * Part of PBX interface, called from ast_hangup */
3515 static int sip_hangup(struct ast_channel *ast)
3517 struct sip_pvt *p = ast->tech_pvt;
3518 int needcancel = FALSE;
3519 int needdestroy = 0;
3520 struct ast_channel *oldowner = ast;
3522 if (!p) {
3523 if (option_debug)
3524 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
3525 return 0;
3528 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
3529 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
3530 if (option_debug && sipdebug)
3531 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
3532 update_call_counter(p, DEC_CALL_LIMIT);
3534 if (option_debug >3)
3535 ast_log(LOG_DEBUG, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
3536 if (p->autokillid > -1 && sip_cancel_destroy(p))
3537 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
3538 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3539 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
3540 ast_clear_flag(&p->flags[0], SIP_NEEDDESTROY);
3541 p->owner->tech_pvt = NULL;
3542 p->owner = NULL; /* Owner will be gone after we return, so take it away */
3543 return 0;
3545 if (option_debug) {
3546 if (ast_test_flag(ast, AST_FLAG_ZOMBIE) && p->refer && option_debug)
3547 ast_log(LOG_DEBUG, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
3548 else {
3549 if (option_debug)
3550 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
3553 if (option_debug && ast_test_flag(ast, AST_FLAG_ZOMBIE))
3554 ast_log(LOG_DEBUG, "Hanging up zombie call. Be scared.\n");
3556 ast_mutex_lock(&p->lock);
3557 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
3558 if (option_debug && sipdebug)
3559 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
3560 update_call_counter(p, DEC_CALL_LIMIT);
3563 /* Determine how to disconnect */
3564 if (p->owner != ast) {
3565 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
3566 ast_mutex_unlock(&p->lock);
3567 return 0;
3569 /* If the call is not UP, we need to send CANCEL instead of BYE */
3570 if (ast->_state == AST_STATE_RING || ast->_state == AST_STATE_RINGING || (p->invitestate < INV_COMPLETED && ast->_state != AST_STATE_UP)) {
3571 needcancel = TRUE;
3572 if (option_debug > 3)
3573 ast_log(LOG_DEBUG, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
3576 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
3578 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->owner->hangupcause) : "Unknown");
3580 /* Disconnect */
3581 if (p->vad)
3582 ast_dsp_free(p->vad);
3584 p->owner = NULL;
3585 ast->tech_pvt = NULL;
3587 ast_module_unref(ast_module_info->self);
3589 /* Do not destroy this pvt until we have timeout or
3590 get an answer to the BYE or INVITE/CANCEL
3591 If we get no answer during retransmit period, drop the call anyway.
3592 (Sorry, mother-in-law, you can't deny a hangup by sending
3593 603 declined to BYE...)
3595 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE))
3596 needdestroy = 1; /* Set destroy flag at end of this function */
3597 else if (p->invitestate != INV_CALLING)
3598 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3600 /* Start the process if it's not already started */
3601 if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
3602 if (needcancel) { /* Outgoing call, not up */
3603 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3604 /* stop retransmitting an INVITE that has not received a response */
3605 __sip_pretend_ack(p);
3606 p->invitestate = INV_CANCELLED;
3608 /* if we can't send right now, mark it pending */
3609 if (p->invitestate == INV_CALLING) {
3610 /* We can't send anything in CALLING state */
3611 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3612 /* 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. */
3613 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3614 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
3615 } else {
3616 /* Send a new request: CANCEL */
3617 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
3618 /* Actually don't destroy us yet, wait for the 487 on our original
3619 INVITE, but do set an autodestruct just in case we never get it. */
3620 needdestroy = 0;
3621 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3623 if ( p->initid != -1 ) {
3624 /* channel still up - reverse dec of inUse counter
3625 only if the channel is not auto-congested */
3626 update_call_counter(p, INC_CALL_LIMIT);
3628 } else { /* Incoming call, not up */
3629 const char *res;
3630 if (ast->hangupcause && (res = hangup_cause2sip(ast->hangupcause)))
3631 transmit_response_reliable(p, res, &p->initreq);
3632 else
3633 transmit_response_reliable(p, "603 Declined", &p->initreq);
3634 p->invitestate = INV_TERMINATED;
3636 } else { /* Call is in UP state, send BYE */
3637 if (!p->pendinginvite) {
3638 char *audioqos = "";
3639 char *videoqos = "";
3640 if (p->rtp)
3641 audioqos = ast_rtp_get_quality(p->rtp, NULL);
3642 if (p->vrtp)
3643 videoqos = ast_rtp_get_quality(p->vrtp, NULL);
3644 /* Send a hangup */
3645 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3647 /* Get RTCP quality before end of call */
3648 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
3649 if (p->rtp)
3650 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
3651 if (p->vrtp)
3652 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
3654 if (p->rtp && oldowner)
3655 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
3656 if (p->vrtp && oldowner)
3657 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
3658 } else {
3659 /* Note we will need a BYE when this all settles out
3660 but we can't send one while we have "INVITE" outstanding. */
3661 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3662 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
3663 AST_SCHED_DEL(sched, p->waitid);
3664 if (sip_cancel_destroy(p))
3665 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
3669 if (needdestroy)
3670 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
3671 ast_mutex_unlock(&p->lock);
3672 return 0;
3675 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
3676 static void try_suggested_sip_codec(struct sip_pvt *p)
3678 int fmt;
3679 const char *codec;
3681 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
3682 if (!codec)
3683 return;
3685 fmt = ast_getformatbyname(codec);
3686 if (fmt) {
3687 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
3688 if (p->jointcapability & fmt) {
3689 p->jointcapability &= fmt;
3690 p->capability &= fmt;
3691 } else
3692 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
3693 } else
3694 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
3695 return;
3698 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
3699 * Part of PBX interface */
3700 static int sip_answer(struct ast_channel *ast)
3702 int res = 0;
3703 struct sip_pvt *p = ast->tech_pvt;
3705 ast_mutex_lock(&p->lock);
3706 if (ast->_state != AST_STATE_UP) {
3707 try_suggested_sip_codec(p);
3709 ast_setstate(ast, AST_STATE_UP);
3710 if (option_debug)
3711 ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name);
3712 if (p->t38.state == T38_PEER_DIRECT) {
3713 p->t38.state = T38_ENABLED;
3714 if (option_debug > 1)
3715 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
3716 res = transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
3717 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
3718 } else {
3719 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
3720 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
3723 ast_mutex_unlock(&p->lock);
3724 return res;
3727 /*! \brief Send frame to media channel (rtp) */
3728 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
3730 struct sip_pvt *p = ast->tech_pvt;
3731 int res = 0;
3733 switch (frame->frametype) {
3734 case AST_FRAME_VOICE:
3735 if (!(frame->subclass & ast->nativeformats)) {
3736 char s1[512], s2[512], s3[512];
3737 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
3738 frame->subclass,
3739 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
3740 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
3741 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
3742 ast->readformat,
3743 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
3744 ast->writeformat);
3745 return 0;
3747 if (p) {
3748 ast_mutex_lock(&p->lock);
3749 if (p->rtp) {
3750 /* If channel is not up, activate early media session */
3751 if ((ast->_state != AST_STATE_UP) &&
3752 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3753 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3754 ast_rtp_new_source(p->rtp);
3755 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3756 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3758 p->lastrtptx = time(NULL);
3759 res = ast_rtp_write(p->rtp, frame);
3761 ast_mutex_unlock(&p->lock);
3763 break;
3764 case AST_FRAME_VIDEO:
3765 if (p) {
3766 ast_mutex_lock(&p->lock);
3767 if (p->vrtp) {
3768 /* Activate video early media */
3769 if ((ast->_state != AST_STATE_UP) &&
3770 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3771 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3772 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3773 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3775 p->lastrtptx = time(NULL);
3776 res = ast_rtp_write(p->vrtp, frame);
3778 ast_mutex_unlock(&p->lock);
3780 break;
3781 case AST_FRAME_IMAGE:
3782 return 0;
3783 break;
3784 case AST_FRAME_MODEM:
3785 if (p) {
3786 ast_mutex_lock(&p->lock);
3787 /* UDPTL requires two-way communication, so early media is not needed here.
3788 we simply forget the frames if we get modem frames before the bridge is up.
3789 Fax will re-transmit.
3791 if (p->udptl && ast->_state == AST_STATE_UP)
3792 res = ast_udptl_write(p->udptl, frame);
3793 ast_mutex_unlock(&p->lock);
3795 break;
3796 default:
3797 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
3798 return 0;
3801 return res;
3804 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
3805 Basically update any ->owner links */
3806 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
3808 int ret = -1;
3809 struct sip_pvt *p;
3811 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE) && option_debug)
3812 ast_log(LOG_DEBUG, "New channel is zombie\n");
3813 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE) && option_debug)
3814 ast_log(LOG_DEBUG, "Old channel is zombie\n");
3816 if (!newchan || !newchan->tech_pvt) {
3817 if (!newchan)
3818 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
3819 else
3820 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
3821 return -1;
3823 p = newchan->tech_pvt;
3825 if (!p) {
3826 ast_log(LOG_WARNING, "No pvt after masquerade. Strange things may happen\n");
3827 return -1;
3830 ast_mutex_lock(&p->lock);
3831 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
3832 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
3833 if (p->owner != oldchan)
3834 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
3835 else {
3836 p->owner = newchan;
3837 /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
3838 RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
3839 able to do this if the masquerade happens before the bridge breaks (e.g., AMI
3840 redirect of both channels). Note that a channel can not be masqueraded *into*
3841 a native bridge. So there is no danger that this breaks a native bridge that
3842 should stay up. */
3843 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0);
3844 ret = 0;
3846 if (option_debug > 2)
3847 ast_log(LOG_DEBUG, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
3849 ast_mutex_unlock(&p->lock);
3850 return ret;
3853 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
3855 struct sip_pvt *p = ast->tech_pvt;
3856 int res = 0;
3858 ast_mutex_lock(&p->lock);
3859 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
3860 case SIP_DTMF_INBAND:
3861 res = -1; /* Tell Asterisk to generate inband indications */
3862 break;
3863 case SIP_DTMF_RFC2833:
3864 if (p->rtp)
3865 ast_rtp_senddigit_begin(p->rtp, digit);
3866 break;
3867 default:
3868 break;
3870 ast_mutex_unlock(&p->lock);
3872 return res;
3875 /*! \brief Send DTMF character on SIP channel
3876 within one call, we're able to transmit in many methods simultaneously */
3877 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
3879 struct sip_pvt *p = ast->tech_pvt;
3880 int res = 0;
3882 ast_mutex_lock(&p->lock);
3883 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
3884 case SIP_DTMF_INFO:
3885 transmit_info_with_digit(p, digit, duration);
3886 break;
3887 case SIP_DTMF_RFC2833:
3888 if (p->rtp)
3889 ast_rtp_senddigit_end(p->rtp, digit);
3890 break;
3891 case SIP_DTMF_INBAND:
3892 res = -1; /* Tell Asterisk to stop inband indications */
3893 break;
3895 ast_mutex_unlock(&p->lock);
3897 return res;
3900 /*! \brief Transfer SIP call */
3901 static int sip_transfer(struct ast_channel *ast, const char *dest)
3903 struct sip_pvt *p = ast->tech_pvt;
3904 int res;
3906 if (dest == NULL) /* functions below do not take a NULL */
3907 dest = "";
3908 ast_mutex_lock(&p->lock);
3909 if (ast->_state == AST_STATE_RING)
3910 res = sip_sipredirect(p, dest);
3911 else
3912 res = transmit_refer(p, dest);
3913 ast_mutex_unlock(&p->lock);
3914 return res;
3917 /*! \brief Play indication to user
3918 * With SIP a lot of indications is sent as messages, letting the device play
3919 the indication - busy signal, congestion etc
3920 \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
3922 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
3924 struct sip_pvt *p = ast->tech_pvt;
3925 int res = 0;
3927 ast_mutex_lock(&p->lock);
3928 switch(condition) {
3929 case AST_CONTROL_RINGING:
3930 if (ast->_state == AST_STATE_RING) {
3931 p->invitestate = INV_EARLY_MEDIA;
3932 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
3933 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
3934 /* Send 180 ringing if out-of-band seems reasonable */
3935 transmit_response(p, "180 Ringing", &p->initreq);
3936 ast_set_flag(&p->flags[0], SIP_RINGING);
3937 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
3938 break;
3939 } else {
3940 /* Well, if it's not reasonable, just send in-band */
3943 res = -1;
3944 break;
3945 case AST_CONTROL_BUSY:
3946 if (ast->_state != AST_STATE_UP) {
3947 transmit_response_reliable(p, "486 Busy Here", &p->initreq);
3948 p->invitestate = INV_COMPLETED;
3949 sip_alreadygone(p);
3950 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
3951 break;
3953 res = -1;
3954 break;
3955 case AST_CONTROL_CONGESTION:
3956 if (ast->_state != AST_STATE_UP) {
3957 transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
3958 p->invitestate = INV_COMPLETED;
3959 sip_alreadygone(p);
3960 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
3961 break;
3963 res = -1;
3964 break;
3965 case AST_CONTROL_PROCEEDING:
3966 if ((ast->_state != AST_STATE_UP) &&
3967 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3968 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3969 transmit_response(p, "100 Trying", &p->initreq);
3970 p->invitestate = INV_PROCEEDING;
3971 break;
3973 res = -1;
3974 break;
3975 case AST_CONTROL_PROGRESS:
3976 if ((ast->_state != AST_STATE_UP) &&
3977 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3978 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3979 p->invitestate = INV_EARLY_MEDIA;
3980 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3981 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3982 break;
3984 res = -1;
3985 break;
3986 case AST_CONTROL_HOLD:
3987 ast_rtp_new_source(p->rtp);
3988 ast_moh_start(ast, data, p->mohinterpret);
3989 break;
3990 case AST_CONTROL_UNHOLD:
3991 ast_rtp_new_source(p->rtp);
3992 ast_moh_stop(ast);
3993 break;
3994 case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
3995 if (p->vrtp && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
3996 transmit_info_with_vidupdate(p);
3997 /* ast_rtcp_send_h261fur(p->vrtp); */
3998 } else
3999 res = -1;
4000 break;
4001 case AST_CONTROL_SRCUPDATE:
4002 ast_rtp_new_source(p->rtp);
4003 break;
4004 case -1:
4005 res = -1;
4006 break;
4007 default:
4008 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
4009 res = -1;
4010 break;
4012 ast_mutex_unlock(&p->lock);
4013 return res;
4017 /*! \brief Initiate a call in the SIP channel
4018 called from sip_request_call (calls from the pbx ) for outbound channels
4019 and from handle_request_invite for inbound channels
4022 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
4024 struct ast_channel *tmp;
4025 struct ast_variable *v = NULL;
4026 int fmt;
4027 int what;
4028 int needvideo = 0, video = 0;
4029 char *decoded_exten;
4031 const char *my_name; /* pick a good name */
4033 if (title)
4034 my_name = title;
4035 else if ( (my_name = strchr(i->fromdomain,':')) )
4036 my_name++; /* skip ':' */
4037 else
4038 my_name = i->fromdomain;
4040 ast_mutex_unlock(&i->lock);
4041 /* Don't hold a sip pvt lock while we allocate a channel */
4042 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);
4045 if (!tmp) {
4046 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
4047 ast_mutex_lock(&i->lock);
4048 return NULL;
4050 ast_mutex_lock(&i->lock);
4052 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO)
4053 tmp->tech = &sip_tech_info;
4054 else
4055 tmp->tech = &sip_tech;
4057 /* Select our native format based on codec preference until we receive
4058 something from another device to the contrary. */
4059 if (i->jointcapability) { /* The joint capabilities of us and peer */
4060 what = i->jointcapability;
4061 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
4062 } else if (i->capability) { /* Our configured capability for this peer */
4063 what = i->capability;
4064 video = i->capability & AST_FORMAT_VIDEO_MASK;
4065 } else {
4066 what = global_capability; /* Global codec support */
4067 video = global_capability & AST_FORMAT_VIDEO_MASK;
4070 /* Set the native formats for audio and merge in video */
4071 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video;
4072 if (option_debug > 2) {
4073 char buf[SIPBUFSIZE];
4074 ast_log(LOG_DEBUG, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
4075 ast_log(LOG_DEBUG, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
4076 ast_log(LOG_DEBUG, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
4077 ast_log(LOG_DEBUG, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
4078 if (i->prefcodec)
4079 ast_log(LOG_DEBUG, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
4082 /* XXX Why are we choosing a codec from the native formats?? */
4083 fmt = ast_best_codec(tmp->nativeformats);
4085 /* If we have a prefcodec setting, we have an inbound channel that set a
4086 preferred format for this call. Otherwise, we check the jointcapability
4087 We also check for vrtp. If it's not there, we are not allowed do any video anyway.
4089 if (i->vrtp) {
4090 if (i->prefcodec)
4091 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK; /* Outbound call */
4092 else
4093 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK; /* Inbound call */
4096 if (option_debug > 2) {
4097 if (needvideo)
4098 ast_log(LOG_DEBUG, "This channel can handle video! HOLLYWOOD next!\n");
4099 else
4100 ast_log(LOG_DEBUG, "This channel will not be able to handle video.\n");
4105 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
4106 i->vad = ast_dsp_new();
4107 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
4108 if (global_relaxdtmf)
4109 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
4111 if (i->rtp) {
4112 tmp->fds[0] = ast_rtp_fd(i->rtp);
4113 tmp->fds[1] = ast_rtcp_fd(i->rtp);
4115 if (needvideo && i->vrtp) {
4116 tmp->fds[2] = ast_rtp_fd(i->vrtp);
4117 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
4119 if (i->udptl) {
4120 tmp->fds[5] = ast_udptl_fd(i->udptl);
4122 if (state == AST_STATE_RING)
4123 tmp->rings = 1;
4124 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
4125 tmp->writeformat = fmt;
4126 tmp->rawwriteformat = fmt;
4127 tmp->readformat = fmt;
4128 tmp->rawreadformat = fmt;
4129 tmp->tech_pvt = i;
4131 tmp->callgroup = i->callgroup;
4132 tmp->pickupgroup = i->pickupgroup;
4133 tmp->cid.cid_pres = i->callingpres;
4134 if (!ast_strlen_zero(i->accountcode))
4135 ast_string_field_set(tmp, accountcode, i->accountcode);
4136 if (i->amaflags)
4137 tmp->amaflags = i->amaflags;
4138 if (!ast_strlen_zero(i->language))
4139 ast_string_field_set(tmp, language, i->language);
4140 i->owner = tmp;
4141 ast_module_ref(ast_module_info->self);
4142 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
4143 /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
4144 * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
4145 * structure so that there aren't issues when forming URI's
4147 decoded_exten = ast_strdupa(i->exten);
4148 ast_uri_decode(decoded_exten);
4149 ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
4151 /* Don't use ast_set_callerid() here because it will
4152 * generate an unnecessary NewCallerID event */
4153 tmp->cid.cid_ani = ast_strdup(i->cid_num);
4154 if (!ast_strlen_zero(i->rdnis))
4155 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
4157 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
4158 tmp->cid.cid_dnid = ast_strdup(i->exten);
4160 tmp->priority = 1;
4161 if (!ast_strlen_zero(i->uri))
4162 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
4163 if (!ast_strlen_zero(i->domain))
4164 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
4165 if (!ast_strlen_zero(i->useragent))
4166 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
4167 if (!ast_strlen_zero(i->callid))
4168 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
4169 if (i->rtp)
4170 ast_jb_configure(tmp, &global_jbconf);
4172 /* If the INVITE contains T.38 SDP information set the proper channel variable so a created outgoing call will also have T.38 */
4173 if (i->udptl && i->t38.state == T38_PEER_DIRECT)
4174 pbx_builtin_setvar_helper(tmp, "_T38CALL", "1");
4176 /* Set channel variables for this call from configuration */
4177 for (v = i->chanvars ; v ; v = v->next)
4178 pbx_builtin_setvar_helper(tmp, v->name, v->value);
4180 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
4181 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
4182 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
4183 ast_hangup(tmp);
4184 tmp = NULL;
4187 if (!ast_test_flag(&i->flags[0], SIP_NO_HISTORY))
4188 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
4190 return tmp;
4193 /*! \brief Reads one line of SIP message body */
4194 static char *get_body_by_line(const char *line, const char *name, int nameLen)
4196 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=')
4197 return ast_skip_blanks(line + nameLen + 1);
4199 return "";
4202 /*! \brief Lookup 'name' in the SDP starting
4203 * at the 'start' line. Returns the matching line, and 'start'
4204 * is updated with the next line number.
4206 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
4208 int len = strlen(name);
4210 while (*start < req->sdp_end) {
4211 const char *r = get_body_by_line(req->line[(*start)++], name, len);
4212 if (r[0] != '\0')
4213 return r;
4216 return "";
4219 /*! \brief Get a line from an SDP message body */
4220 static const char *get_sdp(struct sip_request *req, const char *name)
4222 int dummy = 0;
4224 return get_sdp_iterate(&dummy, req, name);
4227 /*! \brief Get a specific line from the message body */
4228 static char *get_body(struct sip_request *req, char *name)
4230 int x;
4231 int len = strlen(name);
4232 char *r;
4234 for (x = 0; x < req->lines; x++) {
4235 r = get_body_by_line(req->line[x], name, len);
4236 if (r[0] != '\0')
4237 return r;
4240 return "";
4243 /*! \brief Find compressed SIP alias */
4244 static const char *find_alias(const char *name, const char *_default)
4246 /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
4247 static const struct cfalias {
4248 char * const fullname;
4249 char * const shortname;
4250 } aliases[] = {
4251 { "Content-Type", "c" },
4252 { "Content-Encoding", "e" },
4253 { "From", "f" },
4254 { "Call-ID", "i" },
4255 { "Contact", "m" },
4256 { "Content-Length", "l" },
4257 { "Subject", "s" },
4258 { "To", "t" },
4259 { "Supported", "k" },
4260 { "Refer-To", "r" },
4261 { "Referred-By", "b" },
4262 { "Allow-Events", "u" },
4263 { "Event", "o" },
4264 { "Via", "v" },
4265 { "Accept-Contact", "a" },
4266 { "Reject-Contact", "j" },
4267 { "Request-Disposition", "d" },
4268 { "Session-Expires", "x" },
4269 { "Identity", "y" },
4270 { "Identity-Info", "n" },
4272 int x;
4274 for (x=0; x<sizeof(aliases) / sizeof(aliases[0]); x++)
4275 if (!strcasecmp(aliases[x].fullname, name))
4276 return aliases[x].shortname;
4278 return _default;
4281 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
4283 int pass;
4286 * Technically you can place arbitrary whitespace both before and after the ':' in
4287 * a header, although RFC3261 clearly says you shouldn't before, and place just
4288 * one afterwards. If you shouldn't do it, what absolute idiot decided it was
4289 * a good idea to say you can do it, and if you can do it, why in the hell would.
4290 * you say you shouldn't.
4291 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
4292 * and we always allow spaces after that for compatibility.
4294 for (pass = 0; name && pass < 2;pass++) {
4295 int x, len = strlen(name);
4296 for (x=*start; x<req->headers; x++) {
4297 if (!strncasecmp(req->header[x], name, len)) {
4298 char *r = req->header[x] + len; /* skip name */
4299 if (pedanticsipchecking)
4300 r = ast_skip_blanks(r);
4302 if (*r == ':') {
4303 *start = x+1;
4304 return ast_skip_blanks(r+1);
4308 if (pass == 0) /* Try aliases */
4309 name = find_alias(name, NULL);
4312 /* Don't return NULL, so get_header is always a valid pointer */
4313 return "";
4316 /*! \brief Get header from SIP request */
4317 static const char *get_header(const struct sip_request *req, const char *name)
4319 int start = 0;
4320 return __get_header(req, name, &start);
4323 /*! \brief Read RTP from network */
4324 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
4326 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
4327 struct ast_frame *f;
4329 if (!p->rtp) {
4330 /* We have no RTP allocated for this channel */
4331 return &ast_null_frame;
4334 switch(ast->fdno) {
4335 case 0:
4336 f = ast_rtp_read(p->rtp); /* RTP Audio */
4337 break;
4338 case 1:
4339 f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
4340 break;
4341 case 2:
4342 f = ast_rtp_read(p->vrtp); /* RTP Video */
4343 break;
4344 case 3:
4345 f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
4346 break;
4347 case 5:
4348 f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
4349 break;
4350 default:
4351 f = &ast_null_frame;
4353 /* Don't forward RFC2833 if we're not supposed to */
4354 if (f && (f->frametype == AST_FRAME_DTMF) &&
4355 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833))
4356 return &ast_null_frame;
4358 /* We already hold the channel lock */
4359 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
4360 return f;
4362 if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
4363 if (!(f->subclass & p->jointcapability)) {
4364 if (option_debug) {
4365 ast_log(LOG_DEBUG, "Bogus frame of format '%s' received from '%s'!\n",
4366 ast_getformatname(f->subclass), p->owner->name);
4368 return &ast_null_frame;
4370 if (option_debug)
4371 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
4372 p->owner->nativeformats = (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
4373 ast_set_read_format(p->owner, p->owner->readformat);
4374 ast_set_write_format(p->owner, p->owner->writeformat);
4377 if (f && (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
4378 f = ast_dsp_process(p->owner, p->vad, f);
4379 if (f && f->frametype == AST_FRAME_DTMF) {
4380 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && f->subclass == 'f') {
4381 if (option_debug)
4382 ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
4383 *faxdetect = 1;
4384 } else if (option_debug) {
4385 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
4390 return f;
4393 /*! \brief Read SIP RTP from channel */
4394 static struct ast_frame *sip_read(struct ast_channel *ast)
4396 struct ast_frame *fr;
4397 struct sip_pvt *p = ast->tech_pvt;
4398 int faxdetected = FALSE;
4400 ast_mutex_lock(&p->lock);
4401 fr = sip_rtp_read(ast, p, &faxdetected);
4402 p->lastrtprx = time(NULL);
4404 /* If we are NOT bridged to another channel, and we have detected fax tone we issue T38 re-invite to a peer */
4405 /* 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 */
4406 if (faxdetected && ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && (p->t38.state == T38_DISABLED) && !(ast_bridged_channel(ast))) {
4407 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
4408 if (!p->pendinginvite) {
4409 if (option_debug > 2)
4410 ast_log(LOG_DEBUG, "Sending reinvite on SIP (%s) for T.38 negotiation.\n",ast->name);
4411 p->t38.state = T38_LOCAL_REINVITE;
4412 transmit_reinvite_with_t38_sdp(p);
4413 if (option_debug > 1)
4414 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, ast->name);
4416 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
4417 if (option_debug > 2)
4418 ast_log(LOG_DEBUG, "Deferring reinvite on SIP (%s) - it will be re-negotiated for T.38\n", ast->name);
4419 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
4423 /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
4424 if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
4425 fr = &ast_null_frame;
4428 ast_mutex_unlock(&p->lock);
4429 return fr;
4433 /*! \brief Generate 32 byte random string for callid's etc */
4434 static char *generate_random_string(char *buf, size_t size)
4436 long val[4];
4437 int x;
4439 for (x=0; x<4; x++)
4440 val[x] = ast_random();
4441 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
4443 return buf;
4446 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
4447 static void build_callid_pvt(struct sip_pvt *pvt)
4449 char buf[33];
4451 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip));
4453 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
4457 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
4458 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
4460 char buf[33];
4462 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
4464 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
4467 /*! \brief Make our SIP dialog tag */
4468 static void make_our_tag(char *tagbuf, size_t len)
4470 snprintf(tagbuf, len, "as%08lx", ast_random());
4473 /*! \brief Allocate SIP_PVT structure and set defaults */
4474 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
4475 int useglobal_nat, const int intended_method)
4477 struct sip_pvt *p;
4479 if (!(p = ast_calloc(1, sizeof(*p))))
4480 return NULL;
4482 if (ast_string_field_init(p, 512)) {
4483 free(p);
4484 return NULL;
4487 ast_mutex_init(&p->lock);
4489 p->method = intended_method;
4490 p->initid = -1;
4491 p->waitid = -1;
4492 p->autokillid = -1;
4493 p->subscribed = NONE;
4494 p->stateid = -1;
4495 p->prefs = default_prefs; /* Set default codecs for this call */
4497 if (intended_method != SIP_OPTIONS) /* Peerpoke has it's own system */
4498 p->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
4500 if (sin) {
4501 p->sa = *sin;
4502 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
4503 p->ourip = __ourip;
4504 } else
4505 p->ourip = __ourip;
4507 /* Copy global flags to this PVT at setup. */
4508 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
4509 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
4511 ast_set2_flag(&p->flags[0], !recordhistory, SIP_NO_HISTORY);
4513 p->branch = ast_random();
4514 make_our_tag(p->tag, sizeof(p->tag));
4515 p->ocseq = INITIAL_CSEQ;
4517 if (sip_methods[intended_method].need_rtp) {
4518 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
4519 /* If the global videosupport flag is on, we always create a RTP interface for video */
4520 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
4521 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
4522 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
4523 p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
4524 if (!p->rtp || (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)) {
4525 ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n",
4526 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video" : "", strerror(errno));
4527 ast_mutex_destroy(&p->lock);
4528 if (p->chanvars) {
4529 ast_variables_destroy(p->chanvars);
4530 p->chanvars = NULL;
4532 free(p);
4533 return NULL;
4535 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
4536 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
4537 ast_rtp_settos(p->rtp, global_tos_audio);
4538 ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
4539 ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
4540 ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
4541 if (p->vrtp) {
4542 ast_rtp_settos(p->vrtp, global_tos_video);
4543 ast_rtp_setdtmf(p->vrtp, 0);
4544 ast_rtp_setdtmfcompensate(p->vrtp, 0);
4545 ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
4546 ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
4547 ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
4549 if (p->udptl)
4550 ast_udptl_settos(p->udptl, global_tos_audio);
4551 p->maxcallbitrate = default_maxcallbitrate;
4552 p->autoframing = global_autoframing;
4553 ast_rtp_codec_setpref(p->rtp, &p->prefs);
4556 if (useglobal_nat && sin) {
4557 /* Setup NAT structure according to global settings if we have an address */
4558 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
4559 p->recv = *sin;
4560 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
4563 if (p->method != SIP_REGISTER)
4564 ast_string_field_set(p, fromdomain, default_fromdomain);
4565 build_via(p);
4566 if (!callid)
4567 build_callid_pvt(p);
4568 else
4569 ast_string_field_set(p, callid, callid);
4570 /* Assign default music on hold class */
4571 ast_string_field_set(p, mohinterpret, default_mohinterpret);
4572 ast_string_field_set(p, mohsuggest, default_mohsuggest);
4573 p->capability = global_capability;
4574 p->allowtransfer = global_allowtransfer;
4575 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
4576 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
4577 p->noncodeccapability |= AST_RTP_DTMF;
4578 if (p->udptl) {
4579 p->t38.capability = global_t38_capability;
4580 if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY)
4581 p->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
4582 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_FEC)
4583 p->t38.capability |= T38FAX_UDP_EC_FEC;
4584 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_NONE)
4585 p->t38.capability |= T38FAX_UDP_EC_NONE;
4586 p->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
4587 p->t38.jointcapability = p->t38.capability;
4589 ast_string_field_set(p, context, default_context);
4591 /* Add to active dialog list */
4592 ast_mutex_lock(&iflock);
4593 p->next = iflist;
4594 iflist = p;
4595 ast_mutex_unlock(&iflock);
4596 if (option_debug)
4597 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");
4598 return p;
4601 /*! \brief Connect incoming SIP message to current dialog or create new dialog structure
4602 Called by handle_request, sipsock_read */
4603 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
4605 struct sip_pvt *p = NULL;
4606 char *tag = ""; /* note, tag is never NULL */
4607 char totag[128];
4608 char fromtag[128];
4609 const char *callid = get_header(req, "Call-ID");
4610 const char *from = get_header(req, "From");
4611 const char *to = get_header(req, "To");
4612 const char *cseq = get_header(req, "Cseq");
4614 /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
4615 /* get_header always returns non-NULL so we must use ast_strlen_zero() */
4616 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
4617 ast_strlen_zero(from) || ast_strlen_zero(cseq))
4618 return NULL; /* Invalid packet */
4620 if (pedanticsipchecking) {
4621 /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
4622 we need more to identify a branch - so we have to check branch, from
4623 and to tags to identify a call leg.
4624 For Asterisk to behave correctly, you need to turn on pedanticsipchecking
4625 in sip.conf
4627 if (gettag(req, "To", totag, sizeof(totag)))
4628 ast_set_flag(req, SIP_PKT_WITH_TOTAG); /* Used in handle_request/response */
4629 gettag(req, "From", fromtag, sizeof(fromtag));
4631 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
4633 if (option_debug > 4 )
4634 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);
4637 ast_mutex_lock(&iflock);
4638 for (p = iflist; p; p = p->next) {
4639 /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
4640 int found = FALSE;
4641 if (ast_strlen_zero(p->callid))
4642 continue;
4643 if (req->method == SIP_REGISTER)
4644 found = (!strcmp(p->callid, callid));
4645 else {
4646 found = !strcmp(p->callid, callid);
4647 if (pedanticsipchecking && found) {
4648 found = ast_strlen_zero(tag) || ast_strlen_zero(p->theirtag) || !ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED) || !strcmp(p->theirtag, tag);
4652 if (option_debug > 4)
4653 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);
4655 /* If we get a new request within an existing to-tag - check the to tag as well */
4656 if (pedanticsipchecking && found && req->method != SIP_RESPONSE) { /* SIP Request */
4657 if (p->tag[0] == '\0' && totag[0]) {
4658 /* We have no to tag, but they have. Wrong dialog */
4659 found = FALSE;
4660 } else if (totag[0]) { /* Both have tags, compare them */
4661 if (strcmp(totag, p->tag)) {
4662 found = FALSE; /* This is not our packet */
4665 if (!found && option_debug > 4)
4666 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);
4668 if (found) {
4669 /* Found the call */
4670 ast_mutex_lock(&p->lock);
4671 ast_mutex_unlock(&iflock);
4672 return p;
4675 ast_mutex_unlock(&iflock);
4677 /* See if the method is capable of creating a dialog */
4678 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
4679 if (intended_method == SIP_REFER) {
4680 /* We do support REFER, but not outside of a dialog yet */
4681 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
4682 } else if (intended_method == SIP_NOTIFY) {
4683 /* We do not support out-of-dialog NOTIFY either,
4684 like voicemail notification, so cancel that early */
4685 transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
4686 } else {
4687 /* Ok, time to create a new SIP dialog object, a pvt */
4688 if ((p = sip_alloc(callid, sin, 1, intended_method))) {
4689 /* Ok, we've created a dialog, let's go and process it */
4690 ast_mutex_lock(&p->lock);
4691 } else {
4692 /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
4693 getting a dialog from sip_alloc.
4695 Without a dialog we can't retransmit and handle ACKs and all that, but at least
4696 send an error message.
4698 Sorry, we apologize for the inconvienience
4700 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
4701 if (option_debug > 3)
4702 ast_log(LOG_DEBUG, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
4705 return p;
4706 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
4707 /* A method we do not support, let's take it on the volley */
4708 transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
4709 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
4710 /* This is a request outside of a dialog that we don't know about
4711 ...never reply to an ACK!
4713 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
4715 /* We do not respond to responses for dialogs that we don't know about, we just drop
4716 the session quickly */
4718 return p;
4721 /*! \brief Parse register=> line in sip.conf and add to registry */
4722 static int sip_register(char *value, int lineno)
4724 struct sip_registry *reg;
4725 int portnum = 0;
4726 char username[256] = "";
4727 char *hostname=NULL, *secret=NULL, *authuser=NULL;
4728 char *porta=NULL;
4729 char *contact=NULL;
4731 if (!value)
4732 return -1;
4733 ast_copy_string(username, value, sizeof(username));
4734 /* First split around the last '@' then parse the two components. */
4735 hostname = strrchr(username, '@'); /* allow @ in the first part */
4736 if (hostname)
4737 *hostname++ = '\0';
4738 if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
4739 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
4740 return -1;
4742 /* split user[:secret[:authuser]] */
4743 secret = strchr(username, ':');
4744 if (secret) {
4745 *secret++ = '\0';
4746 authuser = strchr(secret, ':');
4747 if (authuser)
4748 *authuser++ = '\0';
4750 /* split host[:port][/contact] */
4751 contact = strchr(hostname, '/');
4752 if (contact)
4753 *contact++ = '\0';
4754 if (ast_strlen_zero(contact))
4755 contact = "s";
4756 porta = strchr(hostname, ':');
4757 if (porta) {
4758 *porta++ = '\0';
4759 portnum = atoi(porta);
4760 if (portnum == 0) {
4761 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
4762 return -1;
4765 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
4766 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
4767 return -1;
4770 if (ast_string_field_init(reg, 256)) {
4771 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
4772 free(reg);
4773 return -1;
4776 regobjs++;
4777 ASTOBJ_INIT(reg);
4778 ast_string_field_set(reg, contact, contact);
4779 if (!ast_strlen_zero(username))
4780 ast_string_field_set(reg, username, username);
4781 if (hostname)
4782 ast_string_field_set(reg, hostname, hostname);
4783 if (authuser)
4784 ast_string_field_set(reg, authuser, authuser);
4785 if (secret)
4786 ast_string_field_set(reg, secret, secret);
4787 reg->expire = -1;
4788 reg->timeout = -1;
4789 reg->refresh = default_expiry;
4790 reg->portno = portnum;
4791 reg->callid_valid = FALSE;
4792 reg->ocseq = INITIAL_CSEQ;
4793 ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
4794 ASTOBJ_UNREF(reg,sip_registry_destroy);
4795 return 0;
4798 /*! \brief Parse multiline SIP headers into one header
4799 This is enabled if pedanticsipchecking is enabled */
4800 static int lws2sws(char *msgbuf, int len)
4802 int h = 0, t = 0;
4803 int lws = 0;
4805 for (; h < len;) {
4806 /* Eliminate all CRs */
4807 if (msgbuf[h] == '\r') {
4808 h++;
4809 continue;
4811 /* Check for end-of-line */
4812 if (msgbuf[h] == '\n') {
4813 /* Check for end-of-message */
4814 if (h + 1 == len)
4815 break;
4816 /* Check for a continuation line */
4817 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
4818 /* Merge continuation line */
4819 h++;
4820 continue;
4822 /* Propagate LF and start new line */
4823 msgbuf[t++] = msgbuf[h++];
4824 lws = 0;
4825 continue;
4827 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
4828 if (lws) {
4829 h++;
4830 continue;
4832 msgbuf[t++] = msgbuf[h++];
4833 lws = 1;
4834 continue;
4836 msgbuf[t++] = msgbuf[h++];
4837 if (lws)
4838 lws = 0;
4840 msgbuf[t] = '\0';
4841 return t;
4844 /*! \brief Parse a SIP message
4845 \note this function is used both on incoming and outgoing packets
4847 static int parse_request(struct sip_request *req)
4849 /* Divide fields by NULL's */
4850 char *c;
4851 int f = 0;
4853 c = req->data;
4855 /* First header starts immediately */
4856 req->header[f] = c;
4857 while(*c) {
4858 if (*c == '\n') {
4859 /* We've got a new header */
4860 *c = 0;
4862 if (sipdebug && option_debug > 3)
4863 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
4864 if (ast_strlen_zero(req->header[f])) {
4865 /* Line by itself means we're now in content */
4866 c++;
4867 break;
4869 if (f >= SIP_MAX_HEADERS - 1) {
4870 ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n");
4871 } else
4872 f++;
4873 req->header[f] = c + 1;
4874 } else if (*c == '\r') {
4875 /* Ignore but eliminate \r's */
4876 *c = 0;
4878 c++;
4880 /* Check for last header */
4881 if (!ast_strlen_zero(req->header[f])) {
4882 if (sipdebug && option_debug > 3)
4883 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
4884 f++;
4886 req->headers = f;
4887 /* Now we process any mime content */
4888 f = 0;
4889 req->line[f] = c;
4890 while(*c) {
4891 if (*c == '\n') {
4892 /* We've got a new line */
4893 *c = 0;
4894 if (sipdebug && option_debug > 3)
4895 ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
4896 if (f >= SIP_MAX_LINES - 1) {
4897 ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n");
4898 } else
4899 f++;
4900 req->line[f] = c + 1;
4901 } else if (*c == '\r') {
4902 /* Ignore and eliminate \r's */
4903 *c = 0;
4905 c++;
4907 /* Check for last line */
4908 if (!ast_strlen_zero(req->line[f]))
4909 f++;
4910 req->lines = f;
4911 if (*c)
4912 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
4913 /* Split up the first line parts */
4914 return determine_firstline_parts(req);
4918 \brief Determine whether a SIP message contains an SDP in its body
4919 \param req the SIP request to process
4920 \return 1 if SDP found, 0 if not found
4922 Also updates req->sdp_start and req->sdp_end to indicate where the SDP
4923 lives in the message body.
4925 static int find_sdp(struct sip_request *req)
4927 const char *content_type;
4928 const char *content_length;
4929 const char *search;
4930 char *boundary;
4931 unsigned int x;
4932 int boundaryisquoted = FALSE;
4933 int found_application_sdp = FALSE;
4934 int found_end_of_headers = FALSE;
4936 content_length = get_header(req, "Content-Length");
4938 if (!ast_strlen_zero(content_length)) {
4939 if (sscanf(content_length, "%ud", &x) != 1) {
4940 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
4941 return 0;
4944 /* Content-Length of zero means there can't possibly be an
4945 SDP here, even if the Content-Type says there is */
4946 if (x == 0)
4947 return 0;
4950 content_type = get_header(req, "Content-Type");
4952 /* if the body contains only SDP, this is easy */
4953 if (!strncasecmp(content_type, "application/sdp", 15)) {
4954 req->sdp_start = 0;
4955 req->sdp_end = req->lines;
4956 return req->lines ? 1 : 0;
4959 /* if it's not multipart/mixed, there cannot be an SDP */
4960 if (strncasecmp(content_type, "multipart/mixed", 15))
4961 return 0;
4963 /* if there is no boundary marker, it's invalid */
4964 if ((search = strcasestr(content_type, ";boundary=")))
4965 search += 10;
4966 else if ((search = strcasestr(content_type, "; boundary=")))
4967 search += 11;
4968 else
4969 return 0;
4971 if (ast_strlen_zero(search))
4972 return 0;
4974 /* If the boundary is quoted with ", remove quote */
4975 if (*search == '\"') {
4976 search++;
4977 boundaryisquoted = TRUE;
4980 /* make a duplicate of the string, with two extra characters
4981 at the beginning */
4982 boundary = ast_strdupa(search - 2);
4983 boundary[0] = boundary[1] = '-';
4984 /* Remove final quote */
4985 if (boundaryisquoted)
4986 boundary[strlen(boundary) - 1] = '\0';
4988 /* search for the boundary marker, the empty line delimiting headers from
4989 sdp part and the end boundry if it exists */
4991 for (x = 0; x < (req->lines ); x++) {
4992 if(!strncasecmp(req->line[x], boundary, strlen(boundary))){
4993 if(found_application_sdp && found_end_of_headers){
4994 req->sdp_end = x-1;
4995 return 1;
4997 found_application_sdp = FALSE;
4999 if(!strcasecmp(req->line[x], "Content-Type: application/sdp"))
5000 found_application_sdp = TRUE;
5002 if(strlen(req->line[x]) == 0 ){
5003 if(found_application_sdp && !found_end_of_headers){
5004 req->sdp_start = x;
5005 found_end_of_headers = TRUE;
5009 if(found_application_sdp && found_end_of_headers) {
5010 req->sdp_end = x;
5011 return TRUE;
5013 return FALSE;
5016 /*! \brief Change hold state for a call */
5017 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
5019 if (global_notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
5020 sip_peer_hold(dialog, holdstate);
5021 if (global_callevents)
5022 manager_event(EVENT_FLAG_CALL, holdstate ? "Hold" : "Unhold",
5023 "Channel: %s\r\n"
5024 "Uniqueid: %s\r\n",
5025 dialog->owner->name,
5026 dialog->owner->uniqueid);
5027 append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data);
5028 if (!holdstate) { /* Put off remote hold */
5029 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
5030 return;
5032 /* No address for RTP, we're on hold */
5034 if (sendonly == 1) /* One directional hold (sendonly/recvonly) */
5035 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
5036 else if (sendonly == 2) /* Inactive stream */
5037 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
5038 else
5039 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
5040 return;
5043 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
5044 If offer is rejected, we will not change any properties of the call
5045 Return 0 on success, a negative value on errors.
5046 Must be called after find_sdp().
5048 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
5050 const char *m; /* SDP media offer */
5051 const char *c;
5052 const char *a;
5053 char host[258];
5054 int len = -1;
5055 int portno = -1; /*!< RTP Audio port number */
5056 int vportno = -1; /*!< RTP Video port number */
5057 int udptlportno = -1;
5058 int peert38capability = 0;
5059 char s[256];
5060 int old = 0;
5062 /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
5063 int peercapability = 0, peernoncodeccapability = 0;
5064 int vpeercapability = 0, vpeernoncodeccapability = 0;
5065 struct sockaddr_in sin; /*!< media socket address */
5066 struct sockaddr_in vsin; /*!< Video socket address */
5068 const char *codecs;
5069 struct hostent *hp; /*!< RTP Audio host IP */
5070 struct hostent *vhp = NULL; /*!< RTP video host IP */
5071 struct ast_hostent audiohp;
5072 struct ast_hostent videohp;
5073 int codec;
5074 int destiterator = 0;
5075 int iterator;
5076 int sendonly = -1;
5077 int numberofports;
5078 struct ast_rtp *newaudiortp, *newvideortp; /* Buffers for codec handling */
5079 int newjointcapability; /* Negotiated capability */
5080 int newpeercapability;
5081 int newnoncodeccapability;
5082 int numberofmediastreams = 0;
5083 int debug = sip_debug_test_pvt(p);
5085 int found_rtpmap_codecs[SDP_MAX_RTPMAP_CODECS];
5086 int last_rtpmap_codec=0;
5088 if (!p->rtp) {
5089 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
5090 return -1;
5093 /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
5094 #ifdef LOW_MEMORY
5095 newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
5096 #else
5097 newaudiortp = alloca(ast_rtp_alloc_size());
5098 #endif
5099 memset(newaudiortp, 0, ast_rtp_alloc_size());
5100 ast_rtp_new_init(newaudiortp);
5101 ast_rtp_pt_clear(newaudiortp);
5103 #ifdef LOW_MEMORY
5104 newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
5105 #else
5106 newvideortp = alloca(ast_rtp_alloc_size());
5107 #endif
5108 memset(newvideortp, 0, ast_rtp_alloc_size());
5109 ast_rtp_new_init(newvideortp);
5110 ast_rtp_pt_clear(newvideortp);
5112 /* Update our last rtprx when we receive an SDP, too */
5113 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
5116 /* Try to find first media stream */
5117 m = get_sdp(req, "m");
5118 destiterator = req->sdp_start;
5119 c = get_sdp_iterate(&destiterator, req, "c");
5120 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
5121 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
5122 return -1;
5125 /* Check for IPv4 address (not IPv6 yet) */
5126 if (sscanf(c, "IN IP4 %256s", host) != 1) {
5127 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
5128 return -1;
5131 /* XXX This could block for a long time, and block the main thread! XXX */
5132 hp = ast_gethostbyname(host, &audiohp);
5133 if (!hp) {
5134 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
5135 return -1;
5137 vhp = hp; /* Copy to video address as default too */
5139 iterator = req->sdp_start;
5140 ast_set_flag(&p->flags[0], SIP_NOVIDEO);
5143 /* Find media streams in this SDP offer */
5144 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
5145 int x;
5146 int audio = FALSE;
5148 numberofports = 1;
5149 if ((sscanf(m, "audio %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
5150 (sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
5151 audio = TRUE;
5152 numberofmediastreams++;
5153 /* Found audio stream in this media definition */
5154 portno = x;
5155 /* Scan through the RTP payload types specified in a "m=" line: */
5156 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
5157 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
5158 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
5159 return -1;
5161 if (debug)
5162 ast_verbose("Found RTP audio format %d\n", codec);
5163 ast_rtp_set_m_type(newaudiortp, codec);
5165 } else if ((sscanf(m, "video %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
5166 (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
5167 /* If it is not audio - is it video ? */
5168 ast_clear_flag(&p->flags[0], SIP_NOVIDEO);
5169 numberofmediastreams++;
5170 vportno = x;
5171 /* Scan through the RTP payload types specified in a "m=" line: */
5172 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
5173 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
5174 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
5175 return -1;
5177 if (debug)
5178 ast_verbose("Found RTP video format %d\n", codec);
5179 ast_rtp_set_m_type(newvideortp, codec);
5181 } else if (p->udptl && ( (sscanf(m, "image %d udptl t38%n", &x, &len) == 1) ||
5182 (sscanf(m, "image %d UDPTL t38%n", &x, &len) == 1) )) {
5183 if (debug)
5184 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
5185 udptlportno = x;
5186 numberofmediastreams++;
5188 if (p->owner && p->lastinvite) {
5189 p->t38.state = T38_PEER_REINVITE; /* T38 Offered in re-invite from remote party */
5190 if (option_debug > 1)
5191 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>" );
5192 } else {
5193 p->t38.state = T38_PEER_DIRECT; /* T38 Offered directly from peer in first invite */
5194 if (option_debug > 1)
5195 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
5197 } else
5198 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
5199 if (numberofports > 1)
5200 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
5203 /* Check for Media-description-level-address for audio */
5204 c = get_sdp_iterate(&destiterator, req, "c");
5205 if (!ast_strlen_zero(c)) {
5206 if (sscanf(c, "IN IP4 %256s", host) != 1) {
5207 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
5208 } else {
5209 /* XXX This could block for a long time, and block the main thread! XXX */
5210 if (audio) {
5211 if ( !(hp = ast_gethostbyname(host, &audiohp))) {
5212 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in secondary c= line, '%s'\n", c);
5213 return -2;
5215 } else if (!(vhp = ast_gethostbyname(host, &videohp))) {
5216 ast_log(LOG_WARNING, "Unable to lookup RTP video host in secondary c= line, '%s'\n", c);
5217 return -2;
5223 if (portno == -1 && vportno == -1 && udptlportno == -1)
5224 /* No acceptable offer found in SDP - we have no ports */
5225 /* Do not change RTP or VRTP if this is a re-invite */
5226 return -2;
5228 if (numberofmediastreams > 2)
5229 /* We have too many fax, audio and/or video media streams, fail this offer */
5230 return -3;
5232 /* RTP addresses and ports for audio and video */
5233 sin.sin_family = AF_INET;
5234 vsin.sin_family = AF_INET;
5235 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
5236 if (vhp)
5237 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
5239 /* Setup UDPTL port number */
5240 if (p->udptl) {
5241 if (udptlportno > 0) {
5242 sin.sin_port = htons(udptlportno);
5243 if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
5244 struct sockaddr_in peer;
5245 ast_rtp_get_peer(p->rtp, &peer);
5246 if (peer.sin_addr.s_addr) {
5247 memcpy(&sin.sin_addr, &peer.sin_addr, sizeof(&sin.sin_addr));
5248 if (debug) {
5249 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));
5253 ast_udptl_set_peer(p->udptl, &sin);
5254 if (debug)
5255 ast_log(LOG_DEBUG,"Peer T.38 UDPTL is at port %s:%d\n",ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
5256 } else {
5257 ast_udptl_stop(p->udptl);
5258 if (debug)
5259 ast_log(LOG_DEBUG, "Peer doesn't provide T.38 UDPTL\n");
5264 if (p->rtp) {
5265 if (portno > 0) {
5266 sin.sin_port = htons(portno);
5267 ast_rtp_set_peer(p->rtp, &sin);
5268 if (debug)
5269 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
5270 } else {
5271 if (udptlportno > 0) {
5272 if (debug)
5273 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session. Callid %s\n", p->callid);
5274 } else {
5275 ast_rtp_stop(p->rtp);
5276 if (debug)
5277 ast_verbose("Peer doesn't provide audio. Callid %s\n", p->callid);
5281 /* Setup video port number */
5282 if (vportno != -1)
5283 vsin.sin_port = htons(vportno);
5285 /* Next, scan through each "a=rtpmap:" line, noting each
5286 * specified RTP payload type (with corresponding MIME subtype):
5288 /* XXX This needs to be done per media stream, since it's media stream specific */
5289 iterator = req->sdp_start;
5290 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
5291 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
5292 if (option_debug > 1) {
5293 int breakout = FALSE;
5295 /* If we're debugging, check for unsupported sdp options */
5296 if (!strncasecmp(a, "rtcp:", (size_t) 5)) {
5297 if (debug)
5298 ast_verbose("Got unsupported a:rtcp in SDP offer \n");
5299 breakout = TRUE;
5300 } else if (!strncasecmp(a, "fmtp:", (size_t) 5)) {
5301 /* Format parameters: Not supported */
5302 /* Note: This is used for codec parameters, like bitrate for
5303 G722 and video formats for H263 and H264
5304 See RFC2327 for an example */
5305 if (debug)
5306 ast_verbose("Got unsupported a:fmtp in SDP offer \n");
5307 breakout = TRUE;
5308 } else if (!strncasecmp(a, "framerate:", (size_t) 10)) {
5309 /* Video stuff: Not supported */
5310 if (debug)
5311 ast_verbose("Got unsupported a:framerate in SDP offer \n");
5312 breakout = TRUE;
5313 } else if (!strncasecmp(a, "maxprate:", (size_t) 9)) {
5314 /* Video stuff: Not supported */
5315 if (debug)
5316 ast_verbose("Got unsupported a:maxprate in SDP offer \n");
5317 breakout = TRUE;
5318 } else if (!strncasecmp(a, "crypto:", (size_t) 7)) {
5319 /* SRTP stuff, not yet supported */
5320 if (debug)
5321 ast_verbose("Got unsupported a:crypto in SDP offer \n");
5322 breakout = TRUE;
5324 if (breakout) /* We have a match, skip to next header */
5325 continue;
5327 if (!strcasecmp(a, "sendonly")) {
5328 if (sendonly == -1)
5329 sendonly = 1;
5330 continue;
5331 } else if (!strcasecmp(a, "inactive")) {
5332 if (sendonly == -1)
5333 sendonly = 2;
5334 continue;
5335 } else if (!strcasecmp(a, "sendrecv")) {
5336 if (sendonly == -1)
5337 sendonly = 0;
5338 continue;
5339 } else if (strlen(a) > 5 && !strncasecmp(a, "ptime", 5)) {
5340 char *tmp = strrchr(a, ':');
5341 long int framing = 0;
5342 if (tmp) {
5343 tmp++;
5344 framing = strtol(tmp, NULL, 10);
5345 if (framing == LONG_MIN || framing == LONG_MAX) {
5346 framing = 0;
5347 if (option_debug)
5348 ast_log(LOG_DEBUG, "Can't read framing from SDP: %s\n", a);
5351 if (framing && p->autoframing) {
5352 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
5353 int codec_n;
5354 int format = 0;
5355 for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
5356 format = ast_rtp_codec_getformat(codec_n);
5357 if (!format) /* non-codec or not found */
5358 continue;
5359 if (option_debug)
5360 ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
5361 ast_codec_pref_setsize(pref, format, framing);
5363 ast_rtp_codec_setpref(p->rtp, pref);
5365 continue;
5366 } else if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) == 2) {
5367 /* We have a rtpmap to handle */
5368 int found = FALSE;
5369 /* We should propably check if this is an audio or video codec
5370 so we know where to look */
5372 if (last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
5373 /* Note: should really look at the 'freq' and '#chans' params too */
5374 if(ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
5375 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0) != -1) {
5376 if (debug)
5377 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
5378 found_rtpmap_codecs[last_rtpmap_codec] = codec;
5379 last_rtpmap_codec++;
5380 found = TRUE;
5382 } else if (p->vrtp) {
5383 if(ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0) != -1) {
5384 if (debug)
5385 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
5386 found_rtpmap_codecs[last_rtpmap_codec] = codec;
5387 last_rtpmap_codec++;
5388 found = TRUE;
5391 } else {
5392 if (debug)
5393 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
5396 if (!found) {
5397 /* Remove this codec since it's an unknown media type for us */
5398 /* XXX This is buggy since the media line for audio and video can have the
5399 same numbers. We need to check as described above, but for testing this works... */
5400 ast_rtp_unset_m_type(newaudiortp, codec);
5401 ast_rtp_unset_m_type(newvideortp, codec);
5402 if (debug)
5403 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
5408 if (udptlportno != -1) {
5409 int found = 0, x;
5411 old = 0;
5413 /* Scan trough the a= lines for T38 attributes and set apropriate fileds */
5414 iterator = req->sdp_start;
5415 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
5416 if ((sscanf(a, "T38FaxMaxBuffer:%d", &x) == 1)) {
5417 found = 1;
5418 if (option_debug > 2)
5419 ast_log(LOG_DEBUG, "MaxBufferSize:%d\n",x);
5420 } else if ((sscanf(a, "T38MaxBitRate:%d", &x) == 1)) {
5421 found = 1;
5422 if (option_debug > 2)
5423 ast_log(LOG_DEBUG,"T38MaxBitRate: %d\n",x);
5424 switch (x) {
5425 case 14400:
5426 peert38capability |= T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5427 break;
5428 case 12000:
5429 peert38capability |= T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5430 break;
5431 case 9600:
5432 peert38capability |= T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5433 break;
5434 case 7200:
5435 peert38capability |= T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5436 break;
5437 case 4800:
5438 peert38capability |= T38FAX_RATE_4800 | T38FAX_RATE_2400;
5439 break;
5440 case 2400:
5441 peert38capability |= T38FAX_RATE_2400;
5442 break;
5444 } else if ((sscanf(a, "T38FaxVersion:%d", &x) == 1)) {
5445 found = 1;
5446 if (option_debug > 2)
5447 ast_log(LOG_DEBUG, "FaxVersion: %d\n",x);
5448 if (x == 0)
5449 peert38capability |= T38FAX_VERSION_0;
5450 else if (x == 1)
5451 peert38capability |= T38FAX_VERSION_1;
5452 } else if ((sscanf(a, "T38FaxMaxDatagram:%d", &x) == 1)) {
5453 found = 1;
5454 if (option_debug > 2)
5455 ast_log(LOG_DEBUG, "FaxMaxDatagram: %d\n",x);
5456 ast_udptl_set_far_max_datagram(p->udptl, x);
5457 ast_udptl_set_local_max_datagram(p->udptl, x);
5458 } else if ((sscanf(a, "T38FaxFillBitRemoval:%d", &x) == 1)) {
5459 found = 1;
5460 if (option_debug > 2)
5461 ast_log(LOG_DEBUG, "FillBitRemoval: %d\n",x);
5462 if (x == 1)
5463 peert38capability |= T38FAX_FILL_BIT_REMOVAL;
5464 } else if ((sscanf(a, "T38FaxTranscodingMMR:%d", &x) == 1)) {
5465 found = 1;
5466 if (option_debug > 2)
5467 ast_log(LOG_DEBUG, "Transcoding MMR: %d\n",x);
5468 if (x == 1)
5469 peert38capability |= T38FAX_TRANSCODING_MMR;
5471 if ((sscanf(a, "T38FaxTranscodingJBIG:%d", &x) == 1)) {
5472 found = 1;
5473 if (option_debug > 2)
5474 ast_log(LOG_DEBUG, "Transcoding JBIG: %d\n",x);
5475 if (x == 1)
5476 peert38capability |= T38FAX_TRANSCODING_JBIG;
5477 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
5478 found = 1;
5479 if (option_debug > 2)
5480 ast_log(LOG_DEBUG, "RateManagement: %s\n", s);
5481 if (!strcasecmp(s, "localTCF"))
5482 peert38capability |= T38FAX_RATE_MANAGEMENT_LOCAL_TCF;
5483 else if (!strcasecmp(s, "transferredTCF"))
5484 peert38capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
5485 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
5486 found = 1;
5487 if (option_debug > 2)
5488 ast_log(LOG_DEBUG, "UDP EC: %s\n", s);
5489 if (!strcasecmp(s, "t38UDPRedundancy")) {
5490 peert38capability |= T38FAX_UDP_EC_REDUNDANCY;
5491 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
5492 } else if (!strcasecmp(s, "t38UDPFEC")) {
5493 peert38capability |= T38FAX_UDP_EC_FEC;
5494 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
5495 } else {
5496 peert38capability |= T38FAX_UDP_EC_NONE;
5497 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
5501 if (found) { /* Some cisco equipment returns nothing beside c= and m= lines in 200 OK T38 SDP */
5502 p->t38.peercapability = peert38capability;
5503 p->t38.jointcapability = (peert38capability & 255); /* Put everything beside supported speeds settings */
5504 peert38capability &= (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400);
5505 p->t38.jointcapability |= (peert38capability & p->t38.capability); /* Put the lower of our's and peer's speed */
5507 if (debug)
5508 ast_log(LOG_DEBUG, "Our T38 capability = (%d), peer T38 capability (%d), joint T38 capability (%d)\n",
5509 p->t38.capability,
5510 p->t38.peercapability,
5511 p->t38.jointcapability);
5512 } else {
5513 p->t38.state = T38_DISABLED;
5514 if (option_debug > 2)
5515 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
5518 /* Now gather all of the codecs that we are asked for: */
5519 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
5520 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
5522 newjointcapability = p->capability & (peercapability | vpeercapability);
5523 newpeercapability = (peercapability | vpeercapability);
5524 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
5527 if (debug) {
5528 /* shame on whoever coded this.... */
5529 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE];
5531 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
5532 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
5533 ast_getformatname_multiple(s2, SIPBUFSIZE, newpeercapability),
5534 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
5535 ast_getformatname_multiple(s4, SIPBUFSIZE, newjointcapability));
5537 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
5538 ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
5539 ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
5540 ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
5542 if (!newjointcapability) {
5543 /* If T.38 was not negotiated either, totally bail out... */
5544 if (!p->t38.jointcapability || !udptlportno) {
5545 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
5546 /* Do NOT Change current setting */
5547 return -1;
5548 } else {
5549 if (option_debug > 2)
5550 ast_log(LOG_DEBUG, "Have T.38 but no audio codecs, accepting offer anyway\n");
5551 return 0;
5555 /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
5556 they are acceptable */
5557 p->jointcapability = newjointcapability; /* Our joint codec profile for this call */
5558 p->peercapability = newpeercapability; /* The other sides capability in latest offer */
5559 p->jointnoncodeccapability = newnoncodeccapability; /* DTMF capabilities */
5561 ast_rtp_pt_copy(p->rtp, newaudiortp);
5562 if (p->vrtp)
5563 ast_rtp_pt_copy(p->vrtp, newvideortp);
5565 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
5566 ast_clear_flag(&p->flags[0], SIP_DTMF);
5567 if (newnoncodeccapability & AST_RTP_DTMF) {
5568 /* XXX Would it be reasonable to drop the DSP at this point? XXX */
5569 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
5570 /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
5571 ast_rtp_setdtmf(p->rtp, 1);
5572 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
5573 } else {
5574 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
5578 /* Setup audio port number */
5579 if (p->rtp && sin.sin_port) {
5580 ast_rtp_set_peer(p->rtp, &sin);
5581 if (debug)
5582 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
5585 /* Setup video port number */
5586 if (p->vrtp && vsin.sin_port) {
5587 ast_rtp_set_peer(p->vrtp, &vsin);
5588 if (debug)
5589 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
5592 /* Ok, we're going with this offer */
5593 if (option_debug > 1) {
5594 char buf[SIPBUFSIZE];
5595 ast_log(LOG_DEBUG, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
5598 if (!p->owner) /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
5599 return 0;
5601 if (option_debug > 3)
5602 ast_log(LOG_DEBUG, "We have an owner, now see if we need to change this call\n");
5604 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
5605 if (debug) {
5606 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
5607 ast_log(LOG_DEBUG, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
5608 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
5609 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
5611 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability);
5612 ast_set_read_format(p->owner, p->owner->readformat);
5613 ast_set_write_format(p->owner, p->owner->writeformat);
5616 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
5617 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
5618 /* Activate a re-invite */
5619 ast_queue_frame(p->owner, &ast_null_frame);
5620 } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
5621 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
5622 S_OR(p->mohsuggest, NULL),
5623 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
5624 if (sendonly)
5625 ast_rtp_stop(p->rtp);
5626 /* RTCP needs to go ahead, even if we're on hold!!! */
5627 /* Activate a re-invite */
5628 ast_queue_frame(p->owner, &ast_null_frame);
5631 /* Manager Hold and Unhold events must be generated, if necessary */
5632 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1))
5633 change_hold_state(p, req, FALSE, sendonly);
5634 else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1))
5635 change_hold_state(p, req, TRUE, sendonly);
5636 return 0;
5639 #ifdef LOW_MEMORY
5640 static void ts_ast_rtp_destroy(void *data)
5642 struct ast_rtp *tmp = data;
5643 ast_rtp_destroy(tmp);
5645 #endif
5647 /*! \brief Add header to SIP message */
5648 static int add_header(struct sip_request *req, const char *var, const char *value)
5650 int maxlen = sizeof(req->data) - 4 - req->len; /* 4 bytes are for two \r\n ? */
5652 if (req->headers == SIP_MAX_HEADERS) {
5653 ast_log(LOG_WARNING, "Out of SIP header space\n");
5654 return -1;
5657 if (req->lines) {
5658 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
5659 return -1;
5662 if (maxlen <= 0) {
5663 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
5664 return -1;
5667 req->header[req->headers] = req->data + req->len;
5669 if (compactheaders)
5670 var = find_alias(var, var);
5672 snprintf(req->header[req->headers], maxlen, "%s: %s\r\n", var, value);
5673 req->len += strlen(req->header[req->headers]);
5674 req->headers++;
5676 return 0;
5679 /*! \brief Add 'Content-Length' header to SIP message */
5680 static int add_header_contentLength(struct sip_request *req, int len)
5682 char clen[10];
5684 snprintf(clen, sizeof(clen), "%d", len);
5685 return add_header(req, "Content-Length", clen);
5688 /*! \brief Add content (not header) to SIP message */
5689 static int add_line(struct sip_request *req, const char *line)
5691 if (req->lines == SIP_MAX_LINES) {
5692 ast_log(LOG_WARNING, "Out of SIP line space\n");
5693 return -1;
5695 if (!req->lines) {
5696 /* Add extra empty return */
5697 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
5698 req->len += strlen(req->data + req->len);
5700 if (req->len >= sizeof(req->data) - 4) {
5701 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
5702 return -1;
5704 req->line[req->lines] = req->data + req->len;
5705 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
5706 req->len += strlen(req->line[req->lines]);
5707 req->lines++;
5708 return 0;
5711 /*! \brief Copy one header field from one request to another */
5712 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
5714 const char *tmp = get_header(orig, field);
5716 if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
5717 return add_header(req, field, tmp);
5718 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
5719 return -1;
5722 /*! \brief Copy all headers from one request to another */
5723 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
5725 int start = 0;
5726 int copied = 0;
5727 for (;;) {
5728 const char *tmp = __get_header(orig, field, &start);
5730 if (ast_strlen_zero(tmp))
5731 break;
5732 /* Add what we're responding to */
5733 add_header(req, field, tmp);
5734 copied++;
5736 return copied ? 0 : -1;
5739 /*! \brief Copy SIP VIA Headers from the request to the response
5740 \note If the client indicates that it wishes to know the port we received from,
5741 it adds ;rport without an argument to the topmost via header. We need to
5742 add the port number (from our point of view) to that parameter.
5743 We always add ;received=<ip address> to the topmost via header.
5744 Received: RFC 3261, rport RFC 3581 */
5745 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
5747 int copied = 0;
5748 int start = 0;
5750 for (;;) {
5751 char new[512];
5752 const char *oh = __get_header(orig, field, &start);
5754 if (ast_strlen_zero(oh))
5755 break;
5757 if (!copied) { /* Only check for empty rport in topmost via header */
5758 char leftmost[512], *others, *rport;
5760 /* Only work on leftmost value */
5761 ast_copy_string(leftmost, oh, sizeof(leftmost));
5762 others = strchr(leftmost, ',');
5763 if (others)
5764 *others++ = '\0';
5766 /* Find ;rport; (empty request) */
5767 rport = strstr(leftmost, ";rport");
5768 if (rport && *(rport+6) == '=')
5769 rport = NULL; /* We already have a parameter to rport */
5771 /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting) */
5772 if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
5773 /* We need to add received port - rport */
5774 char *end;
5776 rport = strstr(leftmost, ";rport");
5778 if (rport) {
5779 end = strchr(rport + 1, ';');
5780 if (end)
5781 memmove(rport, end, strlen(end) + 1);
5782 else
5783 *rport = '\0';
5786 /* Add rport to first VIA header if requested */
5787 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
5788 leftmost, ast_inet_ntoa(p->recv.sin_addr),
5789 ntohs(p->recv.sin_port),
5790 others ? "," : "", others ? others : "");
5791 } else {
5792 /* We should *always* add a received to the topmost via */
5793 snprintf(new, sizeof(new), "%s;received=%s%s%s",
5794 leftmost, ast_inet_ntoa(p->recv.sin_addr),
5795 others ? "," : "", others ? others : "");
5797 oh = new; /* the header to copy */
5798 } /* else add the following via headers untouched */
5799 add_header(req, field, oh);
5800 copied++;
5802 if (!copied) {
5803 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
5804 return -1;
5806 return 0;
5809 /*! \brief Add route header into request per learned route */
5810 static void add_route(struct sip_request *req, struct sip_route *route)
5812 char r[SIPBUFSIZE*2], *p;
5813 int n, rem = sizeof(r);
5815 if (!route)
5816 return;
5818 p = r;
5819 for (;route ; route = route->next) {
5820 n = strlen(route->hop);
5821 if (rem < n+3) /* we need room for ",<route>" */
5822 break;
5823 if (p != r) { /* add a separator after fist route */
5824 *p++ = ',';
5825 --rem;
5827 *p++ = '<';
5828 ast_copy_string(p, route->hop, rem); /* cannot fail */
5829 p += n;
5830 *p++ = '>';
5831 rem -= (n+2);
5833 *p = '\0';
5834 add_header(req, "Route", r);
5837 /*! \brief Set destination from SIP URI */
5838 static void set_destination(struct sip_pvt *p, char *uri)
5840 char *h, *maddr, hostname[256];
5841 int port, hn;
5842 struct hostent *hp;
5843 struct ast_hostent ahp;
5844 int debug=sip_debug_test_pvt(p);
5846 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
5847 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
5849 if (debug)
5850 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
5852 /* Find and parse hostname */
5853 h = strchr(uri, '@');
5854 if (h)
5855 ++h;
5856 else {
5857 h = uri;
5858 if (strncasecmp(h, "sip:", 4) == 0)
5859 h += 4;
5860 else if (strncasecmp(h, "sips:", 5) == 0)
5861 h += 5;
5863 hn = strcspn(h, ":;>") + 1;
5864 if (hn > sizeof(hostname))
5865 hn = sizeof(hostname);
5866 ast_copy_string(hostname, h, hn);
5867 /* XXX bug here if string has been trimmed to sizeof(hostname) */
5868 h += hn - 1;
5870 /* Is "port" present? if not default to STANDARD_SIP_PORT */
5871 if (*h == ':') {
5872 /* Parse port */
5873 ++h;
5874 port = strtol(h, &h, 10);
5876 else
5877 port = STANDARD_SIP_PORT;
5879 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
5880 maddr = strstr(h, "maddr=");
5881 if (maddr) {
5882 maddr += 6;
5883 hn = strspn(maddr, "0123456789.") + 1;
5884 if (hn > sizeof(hostname))
5885 hn = sizeof(hostname);
5886 ast_copy_string(hostname, maddr, hn);
5889 hp = ast_gethostbyname(hostname, &ahp);
5890 if (hp == NULL) {
5891 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
5892 return;
5894 p->sa.sin_family = AF_INET;
5895 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
5896 p->sa.sin_port = htons(port);
5897 if (debug)
5898 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
5901 /*! \brief Initialize SIP response, based on SIP request */
5902 static int init_resp(struct sip_request *resp, const char *msg)
5904 /* Initialize a response */
5905 memset(resp, 0, sizeof(*resp));
5906 resp->method = SIP_RESPONSE;
5907 resp->header[0] = resp->data;
5908 snprintf(resp->header[0], sizeof(resp->data), "SIP/2.0 %s\r\n", msg);
5909 resp->len = strlen(resp->header[0]);
5910 resp->headers++;
5911 return 0;
5914 /*! \brief Initialize SIP request */
5915 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
5917 /* Initialize a request */
5918 memset(req, 0, sizeof(*req));
5919 req->method = sipmethod;
5920 req->header[0] = req->data;
5921 snprintf(req->header[0], sizeof(req->data), "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
5922 req->len = strlen(req->header[0]);
5923 req->headers++;
5924 return 0;
5928 /*! \brief Prepare SIP response packet */
5929 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
5931 char newto[256];
5932 const char *ot;
5934 init_resp(resp, msg);
5935 copy_via_headers(p, resp, req, "Via");
5936 if (msg[0] == '1' || msg[0] == '2')
5937 copy_all_header(resp, req, "Record-Route");
5938 copy_header(resp, req, "From");
5939 ot = get_header(req, "To");
5940 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
5941 /* Add the proper tag if we don't have it already. If they have specified
5942 their tag, use it. Otherwise, use our own tag */
5943 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
5944 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
5945 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
5946 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
5947 else
5948 ast_copy_string(newto, ot, sizeof(newto));
5949 ot = newto;
5951 add_header(resp, "To", ot);
5952 copy_header(resp, req, "Call-ID");
5953 copy_header(resp, req, "CSeq");
5954 if (!ast_strlen_zero(global_useragent))
5955 add_header(resp, "User-Agent", global_useragent);
5956 add_header(resp, "Allow", ALLOWED_METHODS);
5957 add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
5958 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
5959 /* For registration responses, we also need expiry and
5960 contact info */
5961 char tmp[256];
5963 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
5964 add_header(resp, "Expires", tmp);
5965 if (p->expiry) { /* Only add contact if we have an expiry time */
5966 char contact[SIPBUFSIZE];
5967 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
5968 add_header(resp, "Contact", contact); /* Not when we unregister */
5970 } else if (msg[0] != '4' && !ast_strlen_zero(p->our_contact)) {
5971 add_header(resp, "Contact", p->our_contact);
5973 return 0;
5976 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
5977 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
5979 struct sip_request *orig = &p->initreq;
5980 char stripped[80];
5981 char tmp[80];
5982 char newto[256];
5983 const char *c;
5984 const char *ot, *of;
5985 int is_strict = FALSE; /*!< Strict routing flag */
5987 memset(req, 0, sizeof(struct sip_request));
5989 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
5991 if (!seqno) {
5992 p->ocseq++;
5993 seqno = p->ocseq;
5996 if (sipmethod == SIP_CANCEL) {
5997 p->branch = p->invite_branch;
5998 build_via(p);
5999 } else if (newbranch) {
6000 p->branch ^= ast_random();
6001 build_via(p);
6004 /* Check for strict or loose router */
6005 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop,";lr") == NULL) {
6006 is_strict = TRUE;
6007 if (sipdebug)
6008 ast_log(LOG_DEBUG, "Strict routing enforced for session %s\n", p->callid);
6011 if (sipmethod == SIP_CANCEL)
6012 c = p->initreq.rlPart2; /* Use original URI */
6013 else if (sipmethod == SIP_ACK) {
6014 /* Use URI from Contact: in 200 OK (if INVITE)
6015 (we only have the contacturi on INVITEs) */
6016 if (!ast_strlen_zero(p->okcontacturi))
6017 c = is_strict ? p->route->hop : p->okcontacturi;
6018 else
6019 c = p->initreq.rlPart2;
6020 } else if (!ast_strlen_zero(p->okcontacturi))
6021 c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
6022 else if (!ast_strlen_zero(p->uri))
6023 c = p->uri;
6024 else {
6025 char *n;
6026 /* We have no URI, use To: or From: header as URI (depending on direction) */
6027 ast_copy_string(stripped, get_header(orig, (ast_test_flag(&p->flags[0], SIP_OUTGOING)) ? "To" : "From"),
6028 sizeof(stripped));
6029 n = get_in_brackets(stripped);
6030 c = strsep(&n, ";"); /* trim ; and beyond */
6032 init_req(req, sipmethod, c);
6034 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
6036 add_header(req, "Via", p->via);
6037 if (p->route) {
6038 set_destination(p, p->route->hop);
6039 add_route(req, is_strict ? p->route->next : p->route);
6042 ot = get_header(orig, "To");
6043 of = get_header(orig, "From");
6045 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
6046 as our original request, including tag (or presumably lack thereof) */
6047 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
6048 /* Add the proper tag if we don't have it already. If they have specified
6049 their tag, use it. Otherwise, use our own tag */
6050 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_strlen_zero(p->theirtag))
6051 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
6052 else if (!ast_test_flag(&p->flags[0], SIP_OUTGOING))
6053 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
6054 else
6055 snprintf(newto, sizeof(newto), "%s", ot);
6056 ot = newto;
6059 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
6060 add_header(req, "From", of);
6061 add_header(req, "To", ot);
6062 } else {
6063 add_header(req, "From", ot);
6064 add_header(req, "To", of);
6066 /* Do not add Contact for MESSAGE, BYE and Cancel requests */
6067 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
6068 add_header(req, "Contact", p->our_contact);
6070 copy_header(req, orig, "Call-ID");
6071 add_header(req, "CSeq", tmp);
6073 if (!ast_strlen_zero(global_useragent))
6074 add_header(req, "User-Agent", global_useragent);
6075 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
6077 if (!ast_strlen_zero(p->rpid))
6078 add_header(req, "Remote-Party-ID", p->rpid);
6080 return 0;
6083 /*! \brief Base transmit response function */
6084 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
6086 struct sip_request resp;
6087 int seqno = 0;
6089 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
6090 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
6091 return -1;
6093 respprep(&resp, p, msg, req);
6094 add_header_contentLength(&resp, 0);
6095 /* If we are cancelling an incoming invite for some reason, add information
6096 about the reason why we are doing this in clear text */
6097 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
6098 char buf[10];
6100 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
6101 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
6102 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
6104 return send_response(p, &resp, reliable, seqno);
6107 static void temp_pvt_cleanup(void *data)
6109 struct sip_pvt *p = data;
6111 ast_string_field_free_memory(p);
6113 free(data);
6116 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
6117 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)
6119 struct sip_pvt *p = NULL;
6121 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
6122 ast_log(LOG_NOTICE, "Failed to get temporary pvt\n");
6123 return -1;
6126 /* if the structure was just allocated, initialize it */
6127 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
6128 ast_set_flag(&p->flags[0], SIP_NO_HISTORY);
6129 if (ast_string_field_init(p, 512))
6130 return -1;
6133 /* Initialize the bare minimum */
6134 p->method = intended_method;
6136 if (sin) {
6137 p->sa = *sin;
6138 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
6139 p->ourip = __ourip;
6140 } else
6141 p->ourip = __ourip;
6143 p->branch = ast_random();
6144 make_our_tag(p->tag, sizeof(p->tag));
6145 p->ocseq = INITIAL_CSEQ;
6147 if (useglobal_nat && sin) {
6148 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
6149 p->recv = *sin;
6150 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
6152 check_via(p, req);
6154 ast_string_field_set(p, fromdomain, default_fromdomain);
6155 build_via(p);
6156 ast_string_field_set(p, callid, callid);
6158 /* Use this temporary pvt structure to send the message */
6159 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
6161 /* Free the string fields, but not the pool space */
6162 ast_string_field_reset_all(p);
6164 return 0;
6167 /*! \brief Transmit response, no retransmits */
6168 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
6170 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
6173 /*! \brief Transmit response, no retransmits */
6174 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
6176 struct sip_request resp;
6177 respprep(&resp, p, msg, req);
6178 append_date(&resp);
6179 add_header(&resp, "Unsupported", unsupported);
6180 add_header_contentLength(&resp, 0);
6181 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
6184 /*! \brief Transmit response, Make sure you get an ACK
6185 This is only used for responses to INVITEs, where we need to make sure we get an ACK
6187 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
6189 return __transmit_response(p, msg, req, XMIT_CRITICAL);
6192 /*! \brief Append date to SIP message */
6193 static void append_date(struct sip_request *req)
6195 char tmpdat[256];
6196 struct tm tm;
6197 time_t t = time(NULL);
6199 gmtime_r(&t, &tm);
6200 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
6201 add_header(req, "Date", tmpdat);
6204 /*! \brief Append date and content length before transmitting response */
6205 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
6207 struct sip_request resp;
6208 respprep(&resp, p, msg, req);
6209 append_date(&resp);
6210 add_header_contentLength(&resp, 0);
6211 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
6214 /*! \brief Append Accept header, content length before transmitting response */
6215 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
6217 struct sip_request resp;
6218 respprep(&resp, p, msg, req);
6219 add_header(&resp, "Accept", "application/sdp");
6220 add_header_contentLength(&resp, 0);
6221 return send_response(p, &resp, reliable, 0);
6224 /*! \brief Respond with authorization request */
6225 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)
6227 struct sip_request resp;
6228 char tmp[512];
6229 int seqno = 0;
6231 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
6232 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
6233 return -1;
6235 /* Stale means that they sent us correct authentication, but
6236 based it on an old challenge (nonce) */
6237 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
6238 respprep(&resp, p, msg, req);
6239 add_header(&resp, header, tmp);
6240 add_header_contentLength(&resp, 0);
6241 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
6242 return send_response(p, &resp, reliable, seqno);
6245 /*! \brief Add text body to SIP message */
6246 static int add_text(struct sip_request *req, const char *text)
6248 /* XXX Convert \n's to \r\n's XXX */
6249 add_header(req, "Content-Type", "text/plain");
6250 add_header_contentLength(req, strlen(text));
6251 add_line(req, text);
6252 return 0;
6255 /*! \brief Add DTMF INFO tone to sip message */
6256 /* Always adds default duration 250 ms, regardless of what came in over the line */
6257 static int add_digit(struct sip_request *req, char digit, unsigned int duration)
6259 char tmp[256];
6261 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
6262 add_header(req, "Content-Type", "application/dtmf-relay");
6263 add_header_contentLength(req, strlen(tmp));
6264 add_line(req, tmp);
6265 return 0;
6268 /*! \brief add XML encoded media control with update
6269 \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
6270 static int add_vidupdate(struct sip_request *req)
6272 const char *xml_is_a_huge_waste_of_space =
6273 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
6274 " <media_control>\r\n"
6275 " <vc_primitive>\r\n"
6276 " <to_encoder>\r\n"
6277 " <picture_fast_update>\r\n"
6278 " </picture_fast_update>\r\n"
6279 " </to_encoder>\r\n"
6280 " </vc_primitive>\r\n"
6281 " </media_control>\r\n";
6282 add_header(req, "Content-Type", "application/media_control+xml");
6283 add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
6284 add_line(req, xml_is_a_huge_waste_of_space);
6285 return 0;
6288 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
6289 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
6290 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
6291 int debug, int *min_packet_size)
6293 int rtp_code;
6294 struct ast_format_list fmt;
6297 if (debug)
6298 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
6299 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
6300 return;
6302 if (p->rtp) {
6303 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
6304 fmt = ast_codec_pref_getsize(pref, codec);
6305 } 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 */
6306 return;
6307 ast_build_string(m_buf, m_size, " %d", rtp_code);
6308 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
6309 ast_rtp_lookup_mime_subtype(1, codec,
6310 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
6311 sample_rate);
6312 if (codec == AST_FORMAT_G729A) {
6313 /* Indicate that we don't support VAD (G.729 annex B) */
6314 ast_build_string(a_buf, a_size, "a=fmtp:%d annexb=no\r\n", rtp_code);
6315 } else if (codec == AST_FORMAT_G723_1) {
6316 /* Indicate that we don't support VAD (G.723.1 annex A) */
6317 ast_build_string(a_buf, a_size, "a=fmtp:%d annexa=no\r\n", rtp_code);
6318 } else if (codec == AST_FORMAT_ILBC) {
6319 /* Add information about us using only 20/30 ms packetization */
6320 ast_build_string(a_buf, a_size, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
6323 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
6324 *min_packet_size = fmt.cur_ms;
6326 /* Our first codec packetization processed cannot be less than zero */
6327 if ((*min_packet_size) == 0 && fmt.cur_ms)
6328 *min_packet_size = fmt.cur_ms;
6331 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
6332 static int t38_get_rate(int t38cap)
6334 int maxrate = (t38cap & (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400));
6336 if (maxrate & T38FAX_RATE_14400) {
6337 if (option_debug > 1)
6338 ast_log(LOG_DEBUG, "T38MaxFaxRate 14400 found\n");
6339 return 14400;
6340 } else if (maxrate & T38FAX_RATE_12000) {
6341 if (option_debug > 1)
6342 ast_log(LOG_DEBUG, "T38MaxFaxRate 12000 found\n");
6343 return 12000;
6344 } else if (maxrate & T38FAX_RATE_9600) {
6345 if (option_debug > 1)
6346 ast_log(LOG_DEBUG, "T38MaxFaxRate 9600 found\n");
6347 return 9600;
6348 } else if (maxrate & T38FAX_RATE_7200) {
6349 if (option_debug > 1)
6350 ast_log(LOG_DEBUG, "T38MaxFaxRate 7200 found\n");
6351 return 7200;
6352 } else if (maxrate & T38FAX_RATE_4800) {
6353 if (option_debug > 1)
6354 ast_log(LOG_DEBUG, "T38MaxFaxRate 4800 found\n");
6355 return 4800;
6356 } else if (maxrate & T38FAX_RATE_2400) {
6357 if (option_debug > 1)
6358 ast_log(LOG_DEBUG, "T38MaxFaxRate 2400 found\n");
6359 return 2400;
6360 } else {
6361 if (option_debug > 1)
6362 ast_log(LOG_DEBUG, "Strange, T38MaxFaxRate NOT found in peers T38 SDP.\n");
6363 return 0;
6367 /*! \brief Add T.38 Session Description Protocol message */
6368 static int add_t38_sdp(struct sip_request *resp, struct sip_pvt *p)
6370 int len = 0;
6371 int x = 0;
6372 struct sockaddr_in udptlsin;
6373 char v[256] = "";
6374 char s[256] = "";
6375 char o[256] = "";
6376 char c[256] = "";
6377 char t[256] = "";
6378 char m_modem[256];
6379 char a_modem[1024];
6380 char *m_modem_next = m_modem;
6381 size_t m_modem_left = sizeof(m_modem);
6382 char *a_modem_next = a_modem;
6383 size_t a_modem_left = sizeof(a_modem);
6384 struct sockaddr_in udptldest = { 0, };
6385 int debug;
6387 debug = sip_debug_test_pvt(p);
6388 len = 0;
6389 if (!p->udptl) {
6390 ast_log(LOG_WARNING, "No way to add SDP without an UDPTL structure\n");
6391 return -1;
6394 if (!p->sessionid) {
6395 p->sessionid = getpid();
6396 p->sessionversion = p->sessionid;
6397 } else
6398 p->sessionversion++;
6400 /* Our T.38 end is */
6401 ast_udptl_get_us(p->udptl, &udptlsin);
6403 /* Determine T.38 UDPTL destination */
6404 if (p->udptlredirip.sin_addr.s_addr) {
6405 udptldest.sin_port = p->udptlredirip.sin_port;
6406 udptldest.sin_addr = p->udptlredirip.sin_addr;
6407 } else {
6408 udptldest.sin_addr = p->ourip;
6409 udptldest.sin_port = udptlsin.sin_port;
6412 if (debug)
6413 ast_log(LOG_DEBUG, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(udptlsin.sin_port));
6415 /* We break with the "recommendation" and send our IP, in order that our
6416 peer doesn't have to ast_gethostbyname() us */
6418 if (debug) {
6419 ast_log(LOG_DEBUG, "Our T38 capability (%d), peer T38 capability (%d), joint capability (%d)\n",
6420 p->t38.capability,
6421 p->t38.peercapability,
6422 p->t38.jointcapability);
6424 snprintf(v, sizeof(v), "v=0\r\n");
6425 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(udptldest.sin_addr));
6426 snprintf(s, sizeof(s), "s=session\r\n");
6427 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(udptldest.sin_addr));
6428 snprintf(t, sizeof(t), "t=0 0\r\n");
6429 ast_build_string(&m_modem_next, &m_modem_left, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
6431 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_0)
6432 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:0\r\n");
6433 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_1)
6434 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:1\r\n");
6435 if ((x = t38_get_rate(p->t38.jointcapability)))
6436 ast_build_string(&a_modem_next, &a_modem_left, "a=T38MaxBitRate:%d\r\n",x);
6437 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxFillBitRemoval:%d\r\n", (p->t38.jointcapability & T38FAX_FILL_BIT_REMOVAL) ? 1 : 0);
6438 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingMMR:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_MMR) ? 1 : 0);
6439 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingJBIG:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_JBIG) ? 1 : 0);
6440 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxRateManagement:%s\r\n", (p->t38.jointcapability & T38FAX_RATE_MANAGEMENT_LOCAL_TCF) ? "localTCF" : "transferredTCF");
6441 x = ast_udptl_get_local_max_datagram(p->udptl);
6442 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxBuffer:%d\r\n",x);
6443 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxDatagram:%d\r\n",x);
6444 if (p->t38.jointcapability != T38FAX_UDP_EC_NONE)
6445 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxUdpEC:%s\r\n", (p->t38.jointcapability & T38FAX_UDP_EC_REDUNDANCY) ? "t38UDPRedundancy" : "t38UDPFEC");
6446 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m_modem) + strlen(a_modem);
6447 add_header(resp, "Content-Type", "application/sdp");
6448 add_header_contentLength(resp, len);
6449 add_line(resp, v);
6450 add_line(resp, o);
6451 add_line(resp, s);
6452 add_line(resp, c);
6453 add_line(resp, t);
6454 add_line(resp, m_modem);
6455 add_line(resp, a_modem);
6457 /* Update lastrtprx when we send our SDP */
6458 p->lastrtprx = p->lastrtptx = time(NULL);
6460 return 0;
6464 /*! \brief Add RFC 2833 DTMF offer to SDP */
6465 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
6466 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
6467 int debug)
6469 int rtp_code;
6471 if (debug)
6472 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
6473 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
6474 return;
6476 ast_build_string(m_buf, m_size, " %d", rtp_code);
6477 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
6478 ast_rtp_lookup_mime_subtype(0, format, 0),
6479 sample_rate);
6480 if (format == AST_RTP_DTMF)
6481 /* Indicate we support DTMF and FLASH... */
6482 ast_build_string(a_buf, a_size, "a=fmtp:%d 0-16\r\n", rtp_code);
6486 * \note G.722 actually is supposed to specified as 8 kHz, even though it is
6487 * really 16 kHz. Update this macro for other formats as they are added in
6488 * the future.
6490 #define SDP_SAMPLE_RATE(x) 8000
6492 /*! \brief Add Session Description Protocol message */
6493 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p)
6495 int len = 0;
6496 int alreadysent = 0;
6498 struct sockaddr_in sin;
6499 struct sockaddr_in vsin;
6500 struct sockaddr_in dest;
6501 struct sockaddr_in vdest = { 0, };
6503 /* SDP fields */
6504 char *version = "v=0\r\n"; /* Protocol version */
6505 char *subject = "s=session\r\n"; /* Subject of the session */
6506 char owner[256]; /* Session owner/creator */
6507 char connection[256]; /* Connection data */
6508 char *stime = "t=0 0\r\n"; /* Time the session is active */
6509 char bandwidth[256] = ""; /* Max bitrate */
6510 char *hold;
6511 char m_audio[256]; /* Media declaration line for audio */
6512 char m_video[256]; /* Media declaration line for video */
6513 char a_audio[1024]; /* Attributes for audio */
6514 char a_video[1024]; /* Attributes for video */
6515 char *m_audio_next = m_audio;
6516 char *m_video_next = m_video;
6517 size_t m_audio_left = sizeof(m_audio);
6518 size_t m_video_left = sizeof(m_video);
6519 char *a_audio_next = a_audio;
6520 char *a_video_next = a_video;
6521 size_t a_audio_left = sizeof(a_audio);
6522 size_t a_video_left = sizeof(a_video);
6524 int x;
6525 int capability;
6526 int needvideo = FALSE;
6527 int debug = sip_debug_test_pvt(p);
6528 int min_audio_packet_size = 0;
6529 int min_video_packet_size = 0;
6531 m_video[0] = '\0'; /* Reset the video media string if it's not needed */
6533 if (!p->rtp) {
6534 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
6535 return AST_FAILURE;
6538 /* Set RTP Session ID and version */
6539 if (!p->sessionid) {
6540 p->sessionid = getpid();
6541 p->sessionversion = p->sessionid;
6542 } else
6543 p->sessionversion++;
6545 /* Get our addresses */
6546 ast_rtp_get_us(p->rtp, &sin);
6547 if (p->vrtp)
6548 ast_rtp_get_us(p->vrtp, &vsin);
6550 /* Is this a re-invite to move the media out, then use the original offer from caller */
6551 if (p->redirip.sin_addr.s_addr) {
6552 dest.sin_port = p->redirip.sin_port;
6553 dest.sin_addr = p->redirip.sin_addr;
6554 } else {
6555 dest.sin_addr = p->ourip;
6556 dest.sin_port = sin.sin_port;
6559 capability = p->jointcapability;
6562 if (option_debug > 1) {
6563 char codecbuf[SIPBUFSIZE];
6564 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");
6565 ast_log(LOG_DEBUG, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
6568 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
6569 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_RTP)) {
6570 ast_build_string(&m_audio_next, &m_audio_left, " %d", 191);
6571 ast_build_string(&a_audio_next, &a_audio_left, "a=rtpmap:%d %s/%d\r\n", 191, "t38", 8000);
6573 #endif
6575 /* Check if we need video in this call */
6576 if ((capability & AST_FORMAT_VIDEO_MASK) && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
6577 if (p->vrtp) {
6578 needvideo = TRUE;
6579 if (option_debug > 1)
6580 ast_log(LOG_DEBUG, "This call needs video offers!\n");
6581 } else if (option_debug > 1)
6582 ast_log(LOG_DEBUG, "This call needs video offers, but there's no video support enabled!\n");
6586 /* Ok, we need video. Let's add what we need for video and set codecs.
6587 Video is handled differently than audio since we can not transcode. */
6588 if (needvideo) {
6589 /* Determine video destination */
6590 if (p->vredirip.sin_addr.s_addr) {
6591 vdest.sin_addr = p->vredirip.sin_addr;
6592 vdest.sin_port = p->vredirip.sin_port;
6593 } else {
6594 vdest.sin_addr = p->ourip;
6595 vdest.sin_port = vsin.sin_port;
6597 ast_build_string(&m_video_next, &m_video_left, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
6599 /* Build max bitrate string */
6600 if (p->maxcallbitrate)
6601 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
6602 if (debug)
6603 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(vsin.sin_port));
6606 if (debug)
6607 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(sin.sin_port));
6609 /* Start building generic SDP headers */
6611 /* We break with the "recommendation" and send our IP, in order that our
6612 peer doesn't have to ast_gethostbyname() us */
6614 snprintf(owner, sizeof(owner), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
6615 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
6616 ast_build_string(&m_audio_next, &m_audio_left, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
6618 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
6619 hold = "a=recvonly\r\n";
6620 else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
6621 hold = "a=inactive\r\n";
6622 else
6623 hold = "a=sendrecv\r\n";
6625 /* Now, start adding audio codecs. These are added in this order:
6626 - First what was requested by the calling channel
6627 - Then preferences in order from sip.conf device config for this peer/user
6628 - Then other codecs in capabilities, including video
6631 /* Prefer the audio codec we were requested to use, first, no matter what
6632 Note that p->prefcodec can include video codecs, so mask them out
6634 if (capability & p->prefcodec) {
6635 int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
6637 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
6638 &m_audio_next, &m_audio_left,
6639 &a_audio_next, &a_audio_left,
6640 debug, &min_audio_packet_size);
6641 alreadysent |= codec;
6644 /* Start by sending our preferred audio codecs */
6645 for (x = 0; x < 32; x++) {
6646 int codec;
6648 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
6649 break;
6651 if (!(capability & codec))
6652 continue;
6654 if (alreadysent & codec)
6655 continue;
6657 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
6658 &m_audio_next, &m_audio_left,
6659 &a_audio_next, &a_audio_left,
6660 debug, &min_audio_packet_size);
6661 alreadysent |= codec;
6664 /* Now send any other common audio and video codecs, and non-codec formats: */
6665 for (x = 1; x <= (needvideo ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
6666 if (!(capability & x)) /* Codec not requested */
6667 continue;
6669 if (alreadysent & x) /* Already added to SDP */
6670 continue;
6672 if (x <= AST_FORMAT_MAX_AUDIO)
6673 add_codec_to_sdp(p, x, SDP_SAMPLE_RATE(x),
6674 &m_audio_next, &m_audio_left,
6675 &a_audio_next, &a_audio_left,
6676 debug, &min_audio_packet_size);
6677 else
6678 add_codec_to_sdp(p, x, 90000,
6679 &m_video_next, &m_video_left,
6680 &a_video_next, &a_video_left,
6681 debug, &min_video_packet_size);
6684 /* Now add DTMF RFC2833 telephony-event as a codec */
6685 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
6686 if (!(p->jointnoncodeccapability & x))
6687 continue;
6689 add_noncodec_to_sdp(p, x, 8000,
6690 &m_audio_next, &m_audio_left,
6691 &a_audio_next, &a_audio_left,
6692 debug);
6695 if (option_debug > 2)
6696 ast_log(LOG_DEBUG, "-- Done with adding codecs to SDP\n");
6698 if (!p->owner || !ast_internal_timing_enabled(p->owner))
6699 ast_build_string(&a_audio_next, &a_audio_left, "a=silenceSupp:off - - - -\r\n");
6701 if (min_audio_packet_size)
6702 ast_build_string(&a_audio_next, &a_audio_left, "a=ptime:%d\r\n", min_audio_packet_size);
6704 if (min_video_packet_size)
6705 ast_build_string(&a_video_next, &a_video_left, "a=ptime:%d\r\n", min_video_packet_size);
6707 if ((m_audio_left < 2) || (m_video_left < 2) || (a_audio_left == 0) || (a_video_left == 0))
6708 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
6710 ast_build_string(&m_audio_next, &m_audio_left, "\r\n");
6711 if (needvideo)
6712 ast_build_string(&m_video_next, &m_video_left, "\r\n");
6714 len = strlen(version) + strlen(subject) + strlen(owner) + strlen(connection) + strlen(stime) + strlen(m_audio) + strlen(a_audio) + strlen(hold);
6715 if (needvideo) /* only if video response is appropriate */
6716 len += strlen(m_video) + strlen(a_video) + strlen(bandwidth) + strlen(hold);
6718 add_header(resp, "Content-Type", "application/sdp");
6719 add_header_contentLength(resp, len);
6720 add_line(resp, version);
6721 add_line(resp, owner);
6722 add_line(resp, subject);
6723 add_line(resp, connection);
6724 if (needvideo) /* only if video response is appropriate */
6725 add_line(resp, bandwidth);
6726 add_line(resp, stime);
6727 add_line(resp, m_audio);
6728 add_line(resp, a_audio);
6729 add_line(resp, hold);
6730 if (needvideo) { /* only if video response is appropriate */
6731 add_line(resp, m_video);
6732 add_line(resp, a_video);
6733 add_line(resp, hold); /* Repeat hold for the video stream */
6736 /* Update lastrtprx when we send our SDP */
6737 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
6739 if (option_debug > 2) {
6740 char buf[SIPBUFSIZE];
6741 ast_log(LOG_DEBUG, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
6744 return AST_SUCCESS;
6747 /*! \brief Used for 200 OK and 183 early media */
6748 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
6750 struct sip_request resp;
6751 int seqno;
6753 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
6754 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
6755 return -1;
6757 respprep(&resp, p, msg, req);
6758 if (p->udptl) {
6759 ast_udptl_offered_from_local(p->udptl, 0);
6760 add_t38_sdp(&resp, p);
6761 } else
6762 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
6763 if (retrans && !p->pendinginvite)
6764 p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
6765 return send_response(p, &resp, retrans, seqno);
6768 /*! \brief copy SIP request (mostly used to save request for responses) */
6769 static void copy_request(struct sip_request *dst, const struct sip_request *src)
6771 long offset;
6772 int x;
6773 offset = ((void *)dst) - ((void *)src);
6774 /* First copy stuff */
6775 memcpy(dst, src, sizeof(*dst));
6776 /* Now fix pointer arithmetic */
6777 for (x=0; x < src->headers; x++)
6778 dst->header[x] += offset;
6779 for (x=0; x < src->lines; x++)
6780 dst->line[x] += offset;
6781 dst->rlPart1 += offset;
6782 dst->rlPart2 += offset;
6785 /*! \brief Used for 200 OK and 183 early media
6786 \return Will return XMIT_ERROR for network errors.
6788 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
6790 struct sip_request resp;
6791 int seqno;
6792 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
6793 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
6794 return -1;
6796 respprep(&resp, p, msg, req);
6797 if (p->rtp) {
6798 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
6799 if (option_debug)
6800 ast_log(LOG_DEBUG, "Setting framing from config on incoming call\n");
6801 ast_rtp_codec_setpref(p->rtp, &p->prefs);
6803 try_suggested_sip_codec(p);
6804 add_sdp(&resp, p);
6805 } else
6806 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
6807 if (reliable && !p->pendinginvite)
6808 p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
6809 return send_response(p, &resp, reliable, seqno);
6812 /*! \brief Parse first line of incoming SIP request */
6813 static int determine_firstline_parts(struct sip_request *req)
6815 char *e = ast_skip_blanks(req->header[0]); /* there shouldn't be any */
6817 if (!*e)
6818 return -1;
6819 req->rlPart1 = e; /* method or protocol */
6820 e = ast_skip_nonblanks(e);
6821 if (*e)
6822 *e++ = '\0';
6823 /* Get URI or status code */
6824 e = ast_skip_blanks(e);
6825 if ( !*e )
6826 return -1;
6827 ast_trim_blanks(e);
6829 if (!strcasecmp(req->rlPart1, "SIP/2.0") ) { /* We have a response */
6830 if (strlen(e) < 3) /* status code is 3 digits */
6831 return -1;
6832 req->rlPart2 = e;
6833 } else { /* We have a request */
6834 if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
6835 ast_log(LOG_WARNING, "bogus uri in <> %s\n", e);
6836 e++;
6837 if (!*e)
6838 return -1;
6840 req->rlPart2 = e; /* URI */
6841 e = ast_skip_nonblanks(e);
6842 if (*e)
6843 *e++ = '\0';
6844 e = ast_skip_blanks(e);
6845 if (strcasecmp(e, "SIP/2.0") ) {
6846 ast_log(LOG_WARNING, "Bad request protocol %s\n", e);
6847 return -1;
6850 return 1;
6853 /*! \brief Transmit reinvite with SDP
6854 \note A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
6855 INVITE that opened the SIP dialogue
6856 We reinvite so that the audio stream (RTP) go directly between
6857 the SIP UAs. SIP Signalling stays with * in the path.
6859 static int transmit_reinvite_with_sdp(struct sip_pvt *p)
6861 struct sip_request req;
6863 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
6865 add_header(&req, "Allow", ALLOWED_METHODS);
6866 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6867 if (sipdebug)
6868 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
6869 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
6870 append_history(p, "ReInv", "Re-invite sent");
6871 add_sdp(&req, p);
6872 /* Use this as the basis */
6873 initialize_initreq(p, &req);
6874 p->lastinvite = p->ocseq;
6875 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Change direction of this dialog */
6876 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
6879 /*! \brief Transmit reinvite with T38 SDP
6880 We reinvite so that the T38 processing can take place.
6881 SIP Signalling stays with * in the path.
6883 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p)
6885 struct sip_request req;
6887 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
6889 add_header(&req, "Allow", ALLOWED_METHODS);
6890 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6891 if (sipdebug)
6892 add_header(&req, "X-asterisk-info", "SIP re-invite (T38 switchover)");
6893 ast_udptl_offered_from_local(p->udptl, 1);
6894 add_t38_sdp(&req, p);
6895 /* Use this as the basis */
6896 initialize_initreq(p, &req);
6897 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Change direction of this dialog */
6898 p->lastinvite = p->ocseq;
6899 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
6902 /*! \brief Check Contact: URI of SIP message */
6903 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
6905 char stripped[SIPBUFSIZE];
6906 char *c;
6908 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
6909 c = get_in_brackets(stripped);
6910 c = strsep(&c, ";"); /* trim ; and beyond */
6911 if (!ast_strlen_zero(c))
6912 ast_string_field_set(p, uri, c);
6915 /*! \brief Build contact header - the contact header we send out */
6916 static void build_contact(struct sip_pvt *p)
6918 /* Construct Contact: header */
6919 if (ourport != STANDARD_SIP_PORT)
6920 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);
6921 else
6922 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip));
6925 /*! \brief Build the Remote Party-ID & From using callingpres options */
6926 static void build_rpid(struct sip_pvt *p)
6928 int send_pres_tags = TRUE;
6929 const char *privacy=NULL;
6930 const char *screen=NULL;
6931 char buf[256];
6932 const char *clid = default_callerid;
6933 const char *clin = NULL;
6934 const char *fromdomain;
6936 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
6937 return;
6939 if (p->owner && p->owner->cid.cid_num)
6940 clid = p->owner->cid.cid_num;
6941 if (p->owner && p->owner->cid.cid_name)
6942 clin = p->owner->cid.cid_name;
6943 if (ast_strlen_zero(clin))
6944 clin = clid;
6946 switch (p->callingpres) {
6947 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
6948 privacy = "off";
6949 screen = "no";
6950 break;
6951 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
6952 privacy = "off";
6953 screen = "yes";
6954 break;
6955 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
6956 privacy = "off";
6957 screen = "no";
6958 break;
6959 case AST_PRES_ALLOWED_NETWORK_NUMBER:
6960 privacy = "off";
6961 screen = "yes";
6962 break;
6963 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
6964 privacy = "full";
6965 screen = "no";
6966 break;
6967 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
6968 privacy = "full";
6969 screen = "yes";
6970 break;
6971 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
6972 privacy = "full";
6973 screen = "no";
6974 break;
6975 case AST_PRES_PROHIB_NETWORK_NUMBER:
6976 privacy = "full";
6977 screen = "yes";
6978 break;
6979 case AST_PRES_NUMBER_NOT_AVAILABLE:
6980 send_pres_tags = FALSE;
6981 break;
6982 default:
6983 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
6984 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
6985 privacy = "full";
6986 else
6987 privacy = "off";
6988 screen = "no";
6989 break;
6992 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip));
6994 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
6995 if (send_pres_tags)
6996 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
6997 ast_string_field_set(p, rpid, buf);
6999 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
7000 S_OR(p->fromuser, clid),
7001 fromdomain, p->tag);
7004 /*! \brief Initiate new SIP request to peer/user */
7005 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
7007 char invite_buf[256] = "";
7008 char *invite = invite_buf;
7009 size_t invite_max = sizeof(invite_buf);
7010 char from[256];
7011 char to[256];
7012 char tmp[SIPBUFSIZE/2];
7013 char tmp2[SIPBUFSIZE/2];
7014 const char *l = NULL, *n = NULL;
7015 const char *urioptions = "";
7017 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
7018 const char *s = p->username; /* being a string field, cannot be NULL */
7020 /* Test p->username against allowed characters in AST_DIGIT_ANY
7021 If it matches the allowed characters list, then sipuser = ";user=phone"
7022 If not, then sipuser = ""
7024 /* + is allowed in first position in a tel: uri */
7025 if (*s == '+')
7026 s++;
7027 for (; *s; s++) {
7028 if (!strchr(AST_DIGIT_ANYNUM, *s) )
7029 break;
7031 /* If we have only digits, add ;user=phone to the uri */
7032 if (*s)
7033 urioptions = ";user=phone";
7037 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
7039 if (p->owner) {
7040 l = p->owner->cid.cid_num;
7041 n = p->owner->cid.cid_name;
7043 /* if we are not sending RPID and user wants his callerid restricted */
7044 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
7045 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
7046 l = CALLERID_UNKNOWN;
7047 n = l;
7049 if (ast_strlen_zero(l))
7050 l = default_callerid;
7051 if (ast_strlen_zero(n))
7052 n = l;
7053 /* Allow user to be overridden */
7054 if (!ast_strlen_zero(p->fromuser))
7055 l = p->fromuser;
7056 else /* Save for any further attempts */
7057 ast_string_field_set(p, fromuser, l);
7059 /* Allow user to be overridden */
7060 if (!ast_strlen_zero(p->fromname))
7061 n = p->fromname;
7062 else /* Save for any further attempts */
7063 ast_string_field_set(p, fromname, n);
7065 if (pedanticsipchecking) {
7066 ast_uri_encode(n, tmp, sizeof(tmp), 0);
7067 n = tmp;
7068 ast_uri_encode(l, tmp2, sizeof(tmp2), 0);
7069 l = tmp2;
7072 if (ourport != STANDARD_SIP_PORT && ast_strlen_zero(p->fromdomain))
7073 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);
7074 else
7075 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)), p->tag);
7077 /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
7078 if (!ast_strlen_zero(p->fullcontact)) {
7079 /* If we have full contact, trust it */
7080 ast_build_string(&invite, &invite_max, "%s", p->fullcontact);
7081 } else {
7082 /* Otherwise, use the username while waiting for registration */
7083 ast_build_string(&invite, &invite_max, "sip:");
7084 if (!ast_strlen_zero(p->username)) {
7085 n = p->username;
7086 if (pedanticsipchecking) {
7087 ast_uri_encode(n, tmp, sizeof(tmp), 0);
7088 n = tmp;
7090 ast_build_string(&invite, &invite_max, "%s@", n);
7092 ast_build_string(&invite, &invite_max, "%s", p->tohost);
7093 if (ntohs(p->sa.sin_port) != STANDARD_SIP_PORT)
7094 ast_build_string(&invite, &invite_max, ":%d", ntohs(p->sa.sin_port));
7095 ast_build_string(&invite, &invite_max, "%s", urioptions);
7098 /* If custom URI options have been provided, append them */
7099 if (p->options && !ast_strlen_zero(p->options->uri_options))
7100 ast_build_string(&invite, &invite_max, ";%s", p->options->uri_options);
7102 ast_string_field_set(p, uri, invite_buf);
7104 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
7105 /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
7106 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "" : "sip:"), p->uri, p->theirtag);
7107 } else if (p->options && p->options->vxml_url) {
7108 /* If there is a VXML URL append it to the SIP URL */
7109 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
7110 } else
7111 snprintf(to, sizeof(to), "<%s>", p->uri);
7113 init_req(req, sipmethod, p->uri);
7114 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
7116 add_header(req, "Via", p->via);
7117 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
7118 * OTOH, then we won't have anything in p->route anyway */
7119 /* Build Remote Party-ID and From */
7120 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
7121 build_rpid(p);
7122 add_header(req, "From", p->rpid_from);
7123 } else
7124 add_header(req, "From", from);
7125 add_header(req, "To", to);
7126 ast_string_field_set(p, exten, l);
7127 build_contact(p);
7128 add_header(req, "Contact", p->our_contact);
7129 add_header(req, "Call-ID", p->callid);
7130 add_header(req, "CSeq", tmp);
7131 if (!ast_strlen_zero(global_useragent))
7132 add_header(req, "User-Agent", global_useragent);
7133 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
7134 if (!ast_strlen_zero(p->rpid))
7135 add_header(req, "Remote-Party-ID", p->rpid);
7138 /*! \brief Build REFER/INVITE/OPTIONS message and transmit it */
7139 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
7141 struct sip_request req;
7143 req.method = sipmethod;
7144 if (init) { /* Seems like init always is 2 */
7145 /* Bump branch even on initial requests */
7146 p->branch ^= ast_random();
7147 p->invite_branch = p->branch;
7148 build_via(p);
7149 if (init > 1)
7150 initreqprep(&req, p, sipmethod);
7151 else
7152 reqprep(&req, p, sipmethod, 0, 1);
7153 } else
7154 reqprep(&req, p, sipmethod, 0, 1);
7156 if (p->options && p->options->auth)
7157 add_header(&req, p->options->authheader, p->options->auth);
7158 append_date(&req);
7159 if (sipmethod == SIP_REFER) { /* Call transfer */
7160 if (p->refer) {
7161 char buf[SIPBUFSIZE];
7162 if (!ast_strlen_zero(p->refer->refer_to))
7163 add_header(&req, "Refer-To", p->refer->refer_to);
7164 if (!ast_strlen_zero(p->refer->referred_by)) {
7165 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
7166 add_header(&req, "Referred-By", buf);
7170 /* This new INVITE is part of an attended transfer. Make sure that the
7171 other end knows and replace the current call with this new call */
7172 if (p->options && p->options->replaces && !ast_strlen_zero(p->options->replaces)) {
7173 add_header(&req, "Replaces", p->options->replaces);
7174 add_header(&req, "Require", "replaces");
7177 add_header(&req, "Allow", ALLOWED_METHODS);
7178 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7179 if (p->options && p->options->addsipheaders && p->owner) {
7180 struct ast_channel *chan = p->owner; /* The owner channel */
7181 struct varshead *headp;
7183 ast_channel_lock(chan);
7185 headp = &chan->varshead;
7187 if (!headp)
7188 ast_log(LOG_WARNING,"No Headp for the channel...ooops!\n");
7189 else {
7190 const struct ast_var_t *current;
7191 AST_LIST_TRAVERSE(headp, current, entries) {
7192 /* SIPADDHEADER: Add SIP header to outgoing call */
7193 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
7194 char *content, *end;
7195 const char *header = ast_var_value(current);
7196 char *headdup = ast_strdupa(header);
7198 /* Strip of the starting " (if it's there) */
7199 if (*headdup == '"')
7200 headdup++;
7201 if ((content = strchr(headdup, ':'))) {
7202 *content++ = '\0';
7203 content = ast_skip_blanks(content); /* Skip white space */
7204 /* Strip the ending " (if it's there) */
7205 end = content + strlen(content) -1;
7206 if (*end == '"')
7207 *end = '\0';
7209 add_header(&req, headdup, content);
7210 if (sipdebug)
7211 ast_log(LOG_DEBUG, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
7217 ast_channel_unlock(chan);
7219 if (sdp) {
7220 if (p->udptl && (p->t38.state == T38_LOCAL_DIRECT || p->t38.state == T38_LOCAL_REINVITE)) {
7221 ast_udptl_offered_from_local(p->udptl, 1);
7222 if (option_debug)
7223 ast_log(LOG_DEBUG, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
7224 add_t38_sdp(&req, p);
7225 } else if (p->rtp)
7226 add_sdp(&req, p);
7227 } else {
7228 add_header_contentLength(&req, 0);
7231 if (!p->initreq.headers || init > 2)
7232 initialize_initreq(p, &req);
7233 p->lastinvite = p->ocseq;
7234 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
7237 /*! \brief Used in the SUBSCRIBE notification subsystem */
7238 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
7240 char tmp[4000], from[256], to[256];
7241 char *t = tmp, *c, *mfrom, *mto;
7242 size_t maxbytes = sizeof(tmp);
7243 struct sip_request req;
7244 char hint[AST_MAX_EXTENSION];
7245 char *statestring = "terminated";
7246 const struct cfsubscription_types *subscriptiontype;
7247 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
7248 char *pidfstate = "--";
7249 char *pidfnote= "Ready";
7251 memset(from, 0, sizeof(from));
7252 memset(to, 0, sizeof(to));
7253 memset(tmp, 0, sizeof(tmp));
7255 switch (state) {
7256 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
7257 statestring = (global_notifyringing) ? "early" : "confirmed";
7258 local_state = NOTIFY_INUSE;
7259 pidfstate = "busy";
7260 pidfnote = "Ringing";
7261 break;
7262 case AST_EXTENSION_RINGING:
7263 statestring = "early";
7264 local_state = NOTIFY_INUSE;
7265 pidfstate = "busy";
7266 pidfnote = "Ringing";
7267 break;
7268 case AST_EXTENSION_INUSE:
7269 statestring = "confirmed";
7270 local_state = NOTIFY_INUSE;
7271 pidfstate = "busy";
7272 pidfnote = "On the phone";
7273 break;
7274 case AST_EXTENSION_BUSY:
7275 statestring = "confirmed";
7276 local_state = NOTIFY_CLOSED;
7277 pidfstate = "busy";
7278 pidfnote = "On the phone";
7279 break;
7280 case AST_EXTENSION_UNAVAILABLE:
7281 statestring = "terminated";
7282 local_state = NOTIFY_CLOSED;
7283 pidfstate = "away";
7284 pidfnote = "Unavailable";
7285 break;
7286 case AST_EXTENSION_ONHOLD:
7287 statestring = "confirmed";
7288 local_state = NOTIFY_CLOSED;
7289 pidfstate = "busy";
7290 pidfnote = "On Hold";
7291 break;
7292 case AST_EXTENSION_NOT_INUSE:
7293 default:
7294 /* Default setting */
7295 break;
7298 subscriptiontype = find_subscription_type(p->subscribed);
7300 /* Check which device/devices we are watching and if they are registered */
7301 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
7302 char *hint2 = hint, *individual_hint = NULL;
7303 int hint_count = 0, unavailable_count = 0;
7305 while ((individual_hint = strsep(&hint2, "&"))) {
7306 hint_count++;
7308 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
7309 unavailable_count++;
7312 /* If none of the hinted devices are registered, we will
7313 * override notification and show no availability.
7315 if (hint_count > 0 && hint_count == unavailable_count) {
7316 local_state = NOTIFY_CLOSED;
7317 pidfstate = "away";
7318 pidfnote = "Not online";
7322 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
7323 c = get_in_brackets(from);
7324 if (strncasecmp(c, "sip:", 4)) {
7325 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
7326 return -1;
7328 mfrom = strsep(&c, ";"); /* trim ; and beyond */
7330 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
7331 c = get_in_brackets(to);
7332 if (strncasecmp(c, "sip:", 4)) {
7333 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
7334 return -1;
7336 mto = strsep(&c, ";"); /* trim ; and beyond */
7338 reqprep(&req, p, SIP_NOTIFY, 0, 1);
7341 add_header(&req, "Event", subscriptiontype->event);
7342 add_header(&req, "Content-Type", subscriptiontype->mediatype);
7343 switch(state) {
7344 case AST_EXTENSION_DEACTIVATED:
7345 if (timeout)
7346 add_header(&req, "Subscription-State", "terminated;reason=timeout");
7347 else {
7348 add_header(&req, "Subscription-State", "terminated;reason=probation");
7349 add_header(&req, "Retry-After", "60");
7351 break;
7352 case AST_EXTENSION_REMOVED:
7353 add_header(&req, "Subscription-State", "terminated;reason=noresource");
7354 break;
7355 default:
7356 if (p->expiry)
7357 add_header(&req, "Subscription-State", "active");
7358 else /* Expired */
7359 add_header(&req, "Subscription-State", "terminated;reason=timeout");
7361 switch (p->subscribed) {
7362 case XPIDF_XML:
7363 case CPIM_PIDF_XML:
7364 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
7365 ast_build_string(&t, &maxbytes, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
7366 ast_build_string(&t, &maxbytes, "<presence>\n");
7367 ast_build_string(&t, &maxbytes, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
7368 ast_build_string(&t, &maxbytes, "<atom id=\"%s\">\n", p->exten);
7369 ast_build_string(&t, &maxbytes, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
7370 ast_build_string(&t, &maxbytes, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
7371 ast_build_string(&t, &maxbytes, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
7372 ast_build_string(&t, &maxbytes, "</address>\n</atom>\n</presence>\n");
7373 break;
7374 case PIDF_XML: /* Eyebeam supports this format */
7375 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
7376 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);
7377 ast_build_string(&t, &maxbytes, "<pp:person><status>\n");
7378 if (pidfstate[0] != '-')
7379 ast_build_string(&t, &maxbytes, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
7380 ast_build_string(&t, &maxbytes, "</status></pp:person>\n");
7381 ast_build_string(&t, &maxbytes, "<note>%s</note>\n", pidfnote); /* Note */
7382 ast_build_string(&t, &maxbytes, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
7383 ast_build_string(&t, &maxbytes, "<contact priority=\"1\">%s</contact>\n", mto);
7384 if (pidfstate[0] == 'b') /* Busy? Still open ... */
7385 ast_build_string(&t, &maxbytes, "<status><basic>open</basic></status>\n");
7386 else
7387 ast_build_string(&t, &maxbytes, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
7388 ast_build_string(&t, &maxbytes, "</tuple>\n</presence>\n");
7389 break;
7390 case DIALOG_INFO_XML: /* SNOM subscribes in this format */
7391 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
7392 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);
7393 if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
7394 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
7395 else
7396 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\">\n", p->exten);
7397 ast_build_string(&t, &maxbytes, "<state>%s</state>\n", statestring);
7398 if (state == AST_EXTENSION_ONHOLD) {
7399 ast_build_string(&t, &maxbytes, "<local>\n<target uri=\"%s\">\n"
7400 "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
7401 "</target>\n</local>\n", mto);
7403 ast_build_string(&t, &maxbytes, "</dialog>\n</dialog-info>\n");
7404 break;
7405 case NONE:
7406 default:
7407 break;
7410 if (t > tmp + sizeof(tmp))
7411 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
7413 add_header_contentLength(&req, strlen(tmp));
7414 add_line(&req, tmp);
7415 p->pendinginvite = p->ocseq; /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
7417 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7420 /*! \brief Notify user of messages waiting in voicemail
7421 \note - Notification only works for registered peers with mailbox= definitions
7422 in sip.conf
7423 - We use the SIP Event package message-summary
7424 MIME type defaults to "application/simple-message-summary";
7426 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
7428 struct sip_request req;
7429 char tmp[500];
7430 char *t = tmp;
7431 size_t maxbytes = sizeof(tmp);
7433 initreqprep(&req, p, SIP_NOTIFY);
7434 add_header(&req, "Event", "message-summary");
7435 add_header(&req, "Content-Type", default_notifymime);
7437 ast_build_string(&t, &maxbytes, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
7438 ast_build_string(&t, &maxbytes, "Message-Account: sip:%s@%s\r\n",
7439 S_OR(vmexten, default_vmexten), S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)));
7440 /* Cisco has a bug in the SIP stack where it can't accept the
7441 (0/0) notification. This can temporarily be disabled in
7442 sip.conf with the "buggymwi" option */
7443 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)"));
7445 if (p->subscribed) {
7446 if (p->expiry)
7447 add_header(&req, "Subscription-State", "active");
7448 else /* Expired */
7449 add_header(&req, "Subscription-State", "terminated;reason=timeout");
7452 if (t > tmp + sizeof(tmp))
7453 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
7455 add_header_contentLength(&req, strlen(tmp));
7456 add_line(&req, tmp);
7458 if (!p->initreq.headers)
7459 initialize_initreq(p, &req);
7460 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7463 /*! \brief Transmit SIP request unreliably (only used in sip_notify subsystem) */
7464 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req)
7466 if (!p->initreq.headers) /* Initialize first request before sending */
7467 initialize_initreq(p, req);
7468 return send_request(p, req, XMIT_UNRELIABLE, p->ocseq);
7471 /*! \brief Notify a transferring party of the status of transfer */
7472 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
7474 struct sip_request req;
7475 char tmp[SIPBUFSIZE/2];
7477 reqprep(&req, p, SIP_NOTIFY, 0, 1);
7478 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
7479 add_header(&req, "Event", tmp);
7480 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
7481 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
7482 add_header(&req, "Allow", ALLOWED_METHODS);
7483 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7485 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
7486 add_header_contentLength(&req, strlen(tmp));
7487 add_line(&req, tmp);
7489 if (!p->initreq.headers)
7490 initialize_initreq(p, &req);
7492 p->lastnoninvite = p->ocseq;
7494 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7497 /*! \brief Convert registration state status to string */
7498 static char *regstate2str(enum sipregistrystate regstate)
7500 switch(regstate) {
7501 case REG_STATE_FAILED:
7502 return "Failed";
7503 case REG_STATE_UNREGISTERED:
7504 return "Unregistered";
7505 case REG_STATE_REGSENT:
7506 return "Request Sent";
7507 case REG_STATE_AUTHSENT:
7508 return "Auth. Sent";
7509 case REG_STATE_REGISTERED:
7510 return "Registered";
7511 case REG_STATE_REJECTED:
7512 return "Rejected";
7513 case REG_STATE_TIMEOUT:
7514 return "Timeout";
7515 case REG_STATE_NOAUTH:
7516 return "No Authentication";
7517 default:
7518 return "Unknown";
7522 /*! \brief Update registration with SIP Proxy */
7523 static int sip_reregister(const void *data)
7525 /* if we are here, we know that we need to reregister. */
7526 struct sip_registry *r= ASTOBJ_REF((struct sip_registry *) data);
7528 /* if we couldn't get a reference to the registry object, punt */
7529 if (!r)
7530 return 0;
7532 if (r->call && !ast_test_flag(&r->call->flags[0], SIP_NO_HISTORY))
7533 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
7534 /* Since registry's are only added/removed by the the monitor thread, this
7535 may be overkill to reference/dereference at all here */
7536 if (sipdebug)
7537 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
7539 r->expire = -1;
7540 __sip_do_register(r);
7541 ASTOBJ_UNREF(r, sip_registry_destroy);
7542 return 0;
7545 /*! \brief Register with SIP proxy */
7546 static int __sip_do_register(struct sip_registry *r)
7548 int res;
7550 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
7551 return res;
7554 /*! \brief Registration timeout, register again */
7555 static int sip_reg_timeout(const void *data)
7558 /* if we are here, our registration timed out, so we'll just do it over */
7559 struct sip_registry *r = ASTOBJ_REF((struct sip_registry *) data);
7560 struct sip_pvt *p;
7561 int res;
7563 /* if we couldn't get a reference to the registry object, punt */
7564 if (!r)
7565 return 0;
7567 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
7568 if (r->call) {
7569 /* Unlink us, destroy old call. Locking is not relevant here because all this happens
7570 in the single SIP manager thread. */
7571 p = r->call;
7572 ast_mutex_lock(&p->lock);
7573 if (p->registry)
7574 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
7575 r->call = NULL;
7576 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
7577 /* Pretend to ACK anything just in case */
7578 __sip_pretend_ack(p);
7579 ast_mutex_unlock(&p->lock);
7581 /* If we have a limit, stop registration and give up */
7582 if (global_regattempts_max && (r->regattempts > global_regattempts_max)) {
7583 /* Ok, enough is enough. Don't try any more */
7584 /* We could add an external notification here...
7585 steal it from app_voicemail :-) */
7586 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
7587 r->regstate = REG_STATE_FAILED;
7588 } else {
7589 r->regstate = REG_STATE_UNREGISTERED;
7590 r->timeout = -1;
7591 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
7593 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));
7594 ASTOBJ_UNREF(r, sip_registry_destroy);
7595 return 0;
7598 /*! \brief Transmit register to SIP proxy or UA */
7599 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
7601 struct sip_request req;
7602 char from[256];
7603 char to[256];
7604 char tmp[80];
7605 char addr[80];
7606 struct sip_pvt *p;
7607 char *fromdomain;
7609 /* exit if we are already in process with this registrar ?*/
7610 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
7611 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
7612 return 0;
7615 if (r->call) { /* We have a registration */
7616 if (!auth) {
7617 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
7618 return 0;
7619 } else {
7620 p = r->call;
7621 make_our_tag(p->tag, sizeof(p->tag)); /* create a new local tag for every register attempt */
7622 ast_string_field_free(p, theirtag); /* forget their old tag, so we don't match tags when getting response */
7624 } else {
7625 /* Build callid for registration if we haven't registered before */
7626 if (!r->callid_valid) {
7627 build_callid_registry(r, __ourip, default_fromdomain);
7628 r->callid_valid = TRUE;
7630 /* Allocate SIP packet for registration */
7631 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER))) {
7632 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
7633 return 0;
7635 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
7636 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
7637 /* Find address to hostname */
7638 if (create_addr(p, r->hostname)) {
7639 /* we have what we hope is a temporary network error,
7640 * probably DNS. We need to reschedule a registration try */
7641 sip_destroy(p);
7643 if (r->timeout > -1)
7644 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
7645 else
7646 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);
7648 AST_SCHED_DEL(sched, r->timeout);
7649 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
7650 r->regattempts++;
7651 return 0;
7653 /* Copy back Call-ID in case create_addr changed it */
7654 ast_string_field_set(r, callid, p->callid);
7655 if (r->portno) {
7656 p->sa.sin_port = htons(r->portno);
7657 p->recv.sin_port = htons(r->portno);
7658 } else /* Set registry port to the port set from the peer definition/srv or default */
7659 r->portno = ntohs(p->sa.sin_port);
7660 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
7661 r->call=p; /* Save pointer to SIP packet */
7662 p->registry = ASTOBJ_REF(r); /* Add pointer to registry in packet */
7663 if (!ast_strlen_zero(r->secret)) /* Secret (password) */
7664 ast_string_field_set(p, peersecret, r->secret);
7665 if (!ast_strlen_zero(r->md5secret))
7666 ast_string_field_set(p, peermd5secret, r->md5secret);
7667 /* User name in this realm
7668 - if authuser is set, use that, otherwise use username */
7669 if (!ast_strlen_zero(r->authuser)) {
7670 ast_string_field_set(p, peername, r->authuser);
7671 ast_string_field_set(p, authname, r->authuser);
7672 } else if (!ast_strlen_zero(r->username)) {
7673 ast_string_field_set(p, peername, r->username);
7674 ast_string_field_set(p, authname, r->username);
7675 ast_string_field_set(p, fromuser, r->username);
7677 if (!ast_strlen_zero(r->username))
7678 ast_string_field_set(p, username, r->username);
7679 /* Save extension in packet */
7680 ast_string_field_set(p, exten, r->contact);
7683 check which address we should use in our contact header
7684 based on whether the remote host is on the external or
7685 internal network so we can register through nat
7687 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
7688 p->ourip = bindaddr.sin_addr;
7689 build_contact(p);
7692 /* set up a timeout */
7693 if (auth == NULL) {
7694 if (r->timeout > -1)
7695 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
7696 AST_SCHED_DEL(sched, r->timeout);
7697 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
7698 if (option_debug)
7699 ast_log(LOG_DEBUG, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
7702 if ((fromdomain = strchr(r->username, '@'))) {
7703 /* We have a domain in the username for registration */
7704 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
7705 if (!ast_strlen_zero(p->theirtag))
7706 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
7707 else
7708 snprintf(to, sizeof(to), "<sip:%s>", r->username);
7710 /* If the registration username contains '@', then the domain should be used as
7711 the equivalent of "fromdomain" for the registration */
7712 if (ast_strlen_zero(p->fromdomain)) {
7713 ast_string_field_set(p, fromdomain, ++fromdomain);
7715 } else {
7716 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
7717 if (!ast_strlen_zero(p->theirtag))
7718 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
7719 else
7720 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
7723 /* Fromdomain is what we are registering to, regardless of actual
7724 host name from SRV */
7725 if (!ast_strlen_zero(p->fromdomain)) {
7726 if (r->portno && r->portno != STANDARD_SIP_PORT)
7727 snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
7728 else
7729 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
7730 } else {
7731 if (r->portno && r->portno != STANDARD_SIP_PORT)
7732 snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
7733 else
7734 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
7736 ast_string_field_set(p, uri, addr);
7738 p->branch ^= ast_random();
7740 init_req(&req, sipmethod, addr);
7742 /* Add to CSEQ */
7743 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
7744 p->ocseq = r->ocseq;
7746 build_via(p);
7747 add_header(&req, "Via", p->via);
7748 add_header(&req, "From", from);
7749 add_header(&req, "To", to);
7750 add_header(&req, "Call-ID", p->callid);
7751 add_header(&req, "CSeq", tmp);
7752 if (!ast_strlen_zero(global_useragent))
7753 add_header(&req, "User-Agent", global_useragent);
7754 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
7757 if (auth) /* Add auth header */
7758 add_header(&req, authheader, auth);
7759 else if (!ast_strlen_zero(r->nonce)) {
7760 char digest[1024];
7762 /* We have auth data to reuse, build a digest header! */
7763 if (sipdebug)
7764 ast_log(LOG_DEBUG, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
7765 ast_string_field_set(p, realm, r->realm);
7766 ast_string_field_set(p, nonce, r->nonce);
7767 ast_string_field_set(p, domain, r->domain);
7768 ast_string_field_set(p, opaque, r->opaque);
7769 ast_string_field_set(p, qop, r->qop);
7770 r->noncecount++;
7771 p->noncecount = r->noncecount;
7773 memset(digest,0,sizeof(digest));
7774 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
7775 add_header(&req, "Authorization", digest);
7776 else
7777 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
7781 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
7782 add_header(&req, "Expires", tmp);
7783 add_header(&req, "Contact", p->our_contact);
7784 add_header(&req, "Event", "registration");
7785 add_header_contentLength(&req, 0);
7787 initialize_initreq(p, &req);
7788 if (sip_debug_test_pvt(p))
7789 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
7790 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
7791 r->regattempts++; /* Another attempt */
7792 if (option_debug > 3)
7793 ast_verbose("REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
7794 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
7797 /*! \brief Transmit text with SIP MESSAGE method */
7798 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
7800 struct sip_request req;
7802 reqprep(&req, p, SIP_MESSAGE, 0, 1);
7803 add_text(&req, text);
7804 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7807 /*! \brief Allocate SIP refer structure */
7808 static int sip_refer_allocate(struct sip_pvt *p)
7810 p->refer = ast_calloc(1, sizeof(struct sip_refer));
7811 return p->refer ? 1 : 0;
7814 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
7815 \note this is currently broken as we have no way of telling the dialplan
7816 engine whether a transfer succeeds or fails.
7817 \todo Fix the transfer() dialplan function so that a transfer may fail
7819 static int transmit_refer(struct sip_pvt *p, const char *dest)
7821 struct sip_request req = {
7822 .headers = 0,
7824 char from[256];
7825 const char *of;
7826 char *c;
7827 char referto[256];
7828 char *ttag, *ftag;
7829 char *theirtag = ast_strdupa(p->theirtag);
7831 if (option_debug || sipdebug)
7832 ast_log(LOG_DEBUG, "SIP transfer of %s to %s\n", p->callid, dest);
7834 /* Are we transfering an inbound or outbound call ? */
7835 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
7836 of = get_header(&p->initreq, "To");
7837 ttag = theirtag;
7838 ftag = p->tag;
7839 } else {
7840 of = get_header(&p->initreq, "From");
7841 ftag = theirtag;
7842 ttag = p->tag;
7845 ast_copy_string(from, of, sizeof(from));
7846 of = get_in_brackets(from);
7847 ast_string_field_set(p, from, of);
7848 if (strncasecmp(of, "sip:", 4))
7849 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
7850 else
7851 of += 4;
7852 /* Get just the username part */
7853 if ((c = strchr(dest, '@')))
7854 c = NULL;
7855 else if ((c = strchr(of, '@')))
7856 *c++ = '\0';
7857 if (c)
7858 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
7859 else
7860 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
7862 /* save in case we get 407 challenge */
7863 sip_refer_allocate(p);
7864 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
7865 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
7866 p->refer->status = REFER_SENT; /* Set refer status */
7868 reqprep(&req, p, SIP_REFER, 0, 1);
7870 add_header(&req, "Refer-To", referto);
7871 add_header(&req, "Allow", ALLOWED_METHODS);
7872 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7873 if (!ast_strlen_zero(p->our_contact))
7874 add_header(&req, "Referred-By", p->our_contact);
7876 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7877 /* We should propably wait for a NOTIFY here until we ack the transfer */
7878 /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
7880 /*! \todo In theory, we should hang around and wait for a reply, before
7881 returning to the dial plan here. Don't know really how that would
7882 affect the transfer() app or the pbx, but, well, to make this
7883 useful we should have a STATUS code on transfer().
7888 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
7889 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
7891 struct sip_request req;
7893 reqprep(&req, p, SIP_INFO, 0, 1);
7894 add_digit(&req, digit, duration);
7895 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7898 /*! \brief Send SIP INFO with video update request */
7899 static int transmit_info_with_vidupdate(struct sip_pvt *p)
7901 struct sip_request req;
7903 reqprep(&req, p, SIP_INFO, 0, 1);
7904 add_vidupdate(&req);
7905 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7908 /*! \brief Transmit generic SIP request
7909 returns XMIT_ERROR if transmit failed with a critical error (don't retry)
7911 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
7913 struct sip_request resp;
7915 if (sipmethod == SIP_ACK)
7916 p->invitestate = INV_CONFIRMED;
7918 reqprep(&resp, p, sipmethod, seqno, newbranch);
7919 add_header_contentLength(&resp, 0);
7920 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
7923 /*! \brief Transmit SIP request, auth added */
7924 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
7926 struct sip_request resp;
7928 reqprep(&resp, p, sipmethod, seqno, newbranch);
7929 if (!ast_strlen_zero(p->realm)) {
7930 char digest[1024];
7932 memset(digest, 0, sizeof(digest));
7933 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
7934 if (p->options && p->options->auth_type == PROXY_AUTH)
7935 add_header(&resp, "Proxy-Authorization", digest);
7936 else if (p->options && p->options->auth_type == WWW_AUTH)
7937 add_header(&resp, "Authorization", digest);
7938 else /* Default, to be backwards compatible (maybe being too careful, but leaving it for now) */
7939 add_header(&resp, "Proxy-Authorization", digest);
7940 } else
7941 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
7943 /* If we are hanging up and know a cause for that, send it in clear text to make
7944 debugging easier. */
7945 if (sipmethod == SIP_BYE && p->owner && p->owner->hangupcause) {
7946 char buf[10];
7948 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
7949 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
7950 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
7953 add_header_contentLength(&resp, 0);
7954 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
7957 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
7958 static void destroy_association(struct sip_peer *peer)
7960 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE)) {
7961 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
7962 ast_update_realtime("sippeers", "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "username", "", "regserver", "", NULL);
7963 else
7964 ast_db_del("SIP/Registry", peer->name);
7968 /*! \brief Expire registration of SIP peer */
7969 static int expire_register(const void *data)
7971 struct sip_peer *peer = (struct sip_peer *)data;
7973 if (!peer) /* Hmmm. We have no peer. Weird. */
7974 return 0;
7976 memset(&peer->addr, 0, sizeof(peer->addr));
7978 destroy_association(peer); /* remove registration data from storage */
7980 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
7981 register_peer_exten(peer, FALSE); /* Remove regexten */
7982 peer->expire = -1;
7983 ast_device_state_changed("SIP/%s", peer->name);
7985 /* Do we need to release this peer from memory?
7986 Only for realtime peers and autocreated peers
7988 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT) ||
7989 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
7990 struct sip_peer *peer_ptr = peer_ptr;
7991 peer_ptr = ASTOBJ_CONTAINER_UNLINK(&peerl, peer);
7992 if (peer_ptr) {
7993 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
7997 ASTOBJ_UNREF(peer, sip_destroy_peer);
7999 return 0;
8002 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
8003 static int sip_poke_peer_s(const void *data)
8005 struct sip_peer *peer = (struct sip_peer *) data;
8007 peer->pokeexpire = -1;
8009 sip_poke_peer(peer);
8011 ASTOBJ_UNREF(peer, sip_destroy_peer);
8013 return 0;
8016 /*! \brief Get registration details from Asterisk DB */
8017 static void reg_source_db(struct sip_peer *peer)
8019 char data[256];
8020 struct in_addr in;
8021 int expiry;
8022 int port;
8023 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
8025 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
8026 return;
8027 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
8028 return;
8030 scan = data;
8031 addr = strsep(&scan, ":");
8032 port_str = strsep(&scan, ":");
8033 expiry_str = strsep(&scan, ":");
8034 username = strsep(&scan, ":");
8035 contact = scan; /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
8037 if (!inet_aton(addr, &in))
8038 return;
8040 if (port_str)
8041 port = atoi(port_str);
8042 else
8043 return;
8045 if (expiry_str)
8046 expiry = atoi(expiry_str);
8047 else
8048 return;
8050 if (username)
8051 ast_copy_string(peer->username, username, sizeof(peer->username));
8052 if (contact)
8053 ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
8055 if (option_debug > 1)
8056 ast_log(LOG_DEBUG, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
8057 peer->name, peer->username, ast_inet_ntoa(in), port, expiry);
8059 memset(&peer->addr, 0, sizeof(peer->addr));
8060 peer->addr.sin_family = AF_INET;
8061 peer->addr.sin_addr = in;
8062 peer->addr.sin_port = htons(port);
8063 if (sipsock < 0) {
8064 /* SIP isn't up yet, so schedule a poke only, pretty soon */
8065 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
8066 struct sip_peer *peer_ptr = peer;
8067 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8069 peer->pokeexpire = ast_sched_add(sched, ast_random() % 5000 + 1, sip_poke_peer_s, ASTOBJ_REF(peer));
8070 if (peer->pokeexpire == -1) {
8071 struct sip_peer *peer_ptr = peer;
8072 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8074 } else
8075 sip_poke_peer(peer);
8076 if (!AST_SCHED_DEL(sched, peer->expire)) {
8077 struct sip_peer *peer_ptr = peer;
8078 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8080 peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, ASTOBJ_REF(peer));
8081 if (peer->expire == -1) {
8082 struct sip_peer *peer_ptr = peer;
8083 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8085 register_peer_exten(peer, TRUE);
8088 /*! \brief Save contact header for 200 OK on INVITE */
8089 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
8091 char contact[SIPBUFSIZE];
8092 char *c;
8094 /* Look for brackets */
8095 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
8096 c = get_in_brackets(contact);
8098 /* Save full contact to call pvt for later bye or re-invite */
8099 ast_string_field_set(pvt, fullcontact, c);
8101 /* Save URI for later ACKs, BYE or RE-invites */
8102 ast_string_field_set(pvt, okcontacturi, c);
8104 /* We should return false for URI:s we can't handle,
8105 like sips:, tel:, mailto:,ldap: etc */
8106 return TRUE;
8109 static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin)
8111 struct hostent *hp;
8112 struct ast_hostent ahp;
8113 int port;
8114 char *c, *host, *pt;
8115 char contact_buf[256];
8116 char *contact;
8118 /* Work on a copy */
8119 ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
8120 contact = contact_buf;
8122 /* Make sure it's a SIP URL */
8123 if (strncasecmp(contact, "sip:", 4)) {
8124 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
8125 } else
8126 contact += 4;
8128 /* Ditch arguments */
8129 /* XXX this code is replicated also shortly below */
8131 /* Grab host */
8132 host = strchr(contact, '@');
8133 if (!host) { /* No username part */
8134 host = contact;
8135 c = NULL;
8136 } else {
8137 *host++ = '\0';
8139 pt = strchr(host, ':');
8140 if (pt) {
8141 *pt++ = '\0';
8142 port = atoi(pt);
8143 } else
8144 port = STANDARD_SIP_PORT;
8146 contact = strsep(&contact, ";"); /* trim ; and beyond in username part */
8147 host = strsep(&host, ";"); /* trim ; and beyond in host/domain part */
8149 /* XXX This could block for a long time XXX */
8150 /* We should only do this if it's a name, not an IP */
8151 hp = ast_gethostbyname(host, &ahp);
8152 if (!hp) {
8153 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
8154 return -1;
8156 sin->sin_family = AF_INET;
8157 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
8158 sin->sin_port = htons(port);
8160 return 0;
8163 /*! \brief Change the other partys IP address based on given contact */
8164 static int set_address_from_contact(struct sip_pvt *pvt)
8166 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
8167 /* NAT: Don't trust the contact field. Just use what they came to us
8168 with. */
8169 pvt->sa = pvt->recv;
8170 return 0;
8173 return __set_address_from_contact(pvt->fullcontact, &pvt->sa);
8177 /*! \brief Parse contact header and save registration (peer registration) */
8178 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
8180 char contact[SIPBUFSIZE];
8181 char data[SIPBUFSIZE];
8182 const char *expires = get_header(req, "Expires");
8183 int expiry = atoi(expires);
8184 char *curi, *n, *pt;
8185 int port;
8186 const char *useragent;
8187 struct hostent *hp;
8188 struct ast_hostent ahp;
8189 struct sockaddr_in oldsin, testsin;
8191 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
8193 if (ast_strlen_zero(expires)) { /* No expires header */
8194 expires = strcasestr(contact, ";expires=");
8195 if (expires) {
8196 /* XXX bug here, we overwrite the string */
8197 expires = strsep((char **) &expires, ";"); /* trim ; and beyond */
8198 if (sscanf(expires + 9, "%d", &expiry) != 1)
8199 expiry = default_expiry;
8200 } else {
8201 /* Nothing has been specified */
8202 expiry = default_expiry;
8206 /* Look for brackets */
8207 curi = contact;
8208 if (strchr(contact, '<') == NULL) /* No <, check for ; and strip it */
8209 strsep(&curi, ";"); /* This is Header options, not URI options */
8210 curi = get_in_brackets(contact);
8212 /* if they did not specify Contact: or Expires:, they are querying
8213 what we currently have stored as their contact address, so return
8216 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
8217 /* If we have an active registration, tell them when the registration is going to expire */
8218 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
8219 pvt->expiry = ast_sched_when(sched, peer->expire);
8220 return PARSE_REGISTER_QUERY;
8221 } else if (!strcasecmp(curi, "*") || !expiry) { /* Unregister this peer */
8222 /* This means remove all registrations and return OK */
8223 memset(&peer->addr, 0, sizeof(peer->addr));
8224 if (!AST_SCHED_DEL(sched, peer->expire)) {
8225 struct sip_peer *peer_ptr = peer;
8226 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8229 destroy_association(peer);
8231 register_peer_exten(peer, 0); /* Add extension from regexten= setting in sip.conf */
8232 peer->fullcontact[0] = '\0';
8233 peer->useragent[0] = '\0';
8234 peer->sipoptions = 0;
8235 peer->lastms = 0;
8237 if (option_verbose > 2)
8238 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", peer->name);
8240 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
8241 return PARSE_REGISTER_UPDATE;
8244 /* Store whatever we got as a contact from the client */
8245 ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));
8247 /* For the 200 OK, we should use the received contact */
8248 ast_string_field_build(pvt, our_contact, "<%s>", curi);
8250 /* Make sure it's a SIP URL */
8251 if (strncasecmp(curi, "sip:", 4)) {
8252 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", curi);
8253 } else
8254 curi += 4;
8255 /* Ditch q */
8256 curi = strsep(&curi, ";");
8257 /* Grab host */
8258 n = strchr(curi, '@');
8259 if (!n) {
8260 n = curi;
8261 curi = NULL;
8262 } else
8263 *n++ = '\0';
8264 pt = strchr(n, ':');
8265 if (pt) {
8266 *pt++ = '\0';
8267 port = atoi(pt);
8268 } else
8269 port = STANDARD_SIP_PORT;
8270 oldsin = peer->addr;
8272 /* Check that they're allowed to register at this IP */
8273 /* XXX This could block for a long time XXX */
8274 hp = ast_gethostbyname(n, &ahp);
8275 if (!hp) {
8276 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
8277 *peer->fullcontact = '\0';
8278 ast_string_field_set(pvt, our_contact, "");
8279 return PARSE_REGISTER_FAILED;
8281 memcpy(&testsin.sin_addr, hp->h_addr, sizeof(testsin.sin_addr));
8282 if ( ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
8283 ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
8284 ast_log(LOG_WARNING, "Host '%s' disallowed by rule\n", n);
8285 *peer->fullcontact = '\0';
8286 ast_string_field_set(pvt, our_contact, "");
8287 return PARSE_REGISTER_FAILED;
8290 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
8291 peer->addr.sin_family = AF_INET;
8292 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
8293 peer->addr.sin_port = htons(port);
8294 } else {
8295 /* Don't trust the contact field. Just use what they came to us
8296 with */
8297 peer->addr = pvt->recv;
8300 /* Save SIP options profile */
8301 peer->sipoptions = pvt->sipoptions;
8303 if (curi && ast_strlen_zero(peer->username))
8304 ast_copy_string(peer->username, curi, sizeof(peer->username));
8306 if (!AST_SCHED_DEL(sched, peer->expire)) {
8307 struct sip_peer *peer_ptr = peer;
8308 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8310 if (expiry > max_expiry)
8311 expiry = max_expiry;
8312 if (expiry < min_expiry)
8313 expiry = min_expiry;
8314 if (ast_test_flag(&peer->flags[0], SIP_REALTIME) && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
8315 peer->expire = -1;
8316 } else {
8317 peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, ASTOBJ_REF(peer));
8318 if (peer->expire == -1) {
8319 struct sip_peer *peer_ptr = peer;
8320 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8323 pvt->expiry = expiry;
8324 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);
8325 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
8326 ast_db_put("SIP/Registry", peer->name, data);
8327 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
8329 /* Is this a new IP address for us? */
8330 if (inaddrcmp(&peer->addr, &oldsin)) {
8331 sip_poke_peer(peer);
8332 if (option_verbose > 2)
8333 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);
8334 register_peer_exten(peer, 1);
8337 /* Save User agent */
8338 useragent = get_header(req, "User-Agent");
8339 if (strcasecmp(useragent, peer->useragent)) { /* XXX copy if they are different ? */
8340 ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
8341 if (option_verbose > 3)
8342 ast_verbose(VERBOSE_PREFIX_3 "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
8344 return PARSE_REGISTER_UPDATE;
8347 /*! \brief Remove route from route list */
8348 static void free_old_route(struct sip_route *route)
8350 struct sip_route *next;
8352 while (route) {
8353 next = route->next;
8354 free(route);
8355 route = next;
8359 /*! \brief List all routes - mostly for debugging */
8360 static void list_route(struct sip_route *route)
8362 if (!route)
8363 ast_verbose("list_route: no route\n");
8364 else {
8365 for (;route; route = route->next)
8366 ast_verbose("list_route: hop: <%s>\n", route->hop);
8370 /*! \brief Build route list from Record-Route header */
8371 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
8373 struct sip_route *thishop, *head, *tail;
8374 int start = 0;
8375 int len;
8376 const char *rr, *contact, *c;
8378 /* Once a persistant route is set, don't fool with it */
8379 if (p->route && p->route_persistant) {
8380 if (option_debug)
8381 ast_log(LOG_DEBUG, "build_route: Retaining previous route: <%s>\n", p->route->hop);
8382 return;
8385 if (p->route) {
8386 free_old_route(p->route);
8387 p->route = NULL;
8390 /* We only want to create the route set the first time this is called */
8391 p->route_persistant = 1;
8393 /* Build a tailq, then assign it to p->route when done.
8394 * If backwards, we add entries from the head so they end up
8395 * in reverse order. However, we do need to maintain a correct
8396 * tail pointer because the contact is always at the end.
8398 head = NULL;
8399 tail = head;
8400 /* 1st we pass through all the hops in any Record-Route headers */
8401 for (;;) {
8402 /* Each Record-Route header */
8403 rr = __get_header(req, "Record-Route", &start);
8404 if (*rr == '\0')
8405 break;
8406 for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
8407 ++rr;
8408 len = strcspn(rr, ">") + 1;
8409 /* Make a struct route */
8410 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
8411 /* ast_calloc is not needed because all fields are initialized in this block */
8412 ast_copy_string(thishop->hop, rr, len);
8413 if (option_debug > 1)
8414 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
8415 /* Link in */
8416 if (backwards) {
8417 /* Link in at head so they end up in reverse order */
8418 thishop->next = head;
8419 head = thishop;
8420 /* If this was the first then it'll be the tail */
8421 if (!tail)
8422 tail = thishop;
8423 } else {
8424 thishop->next = NULL;
8425 /* Link in at the end */
8426 if (tail)
8427 tail->next = thishop;
8428 else
8429 head = thishop;
8430 tail = thishop;
8436 /* Only append the contact if we are dealing with a strict router */
8437 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop,";lr") == NULL) ) {
8438 /* 2nd append the Contact: if there is one */
8439 /* Can be multiple Contact headers, comma separated values - we just take the first */
8440 contact = get_header(req, "Contact");
8441 if (!ast_strlen_zero(contact)) {
8442 if (option_debug > 1)
8443 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
8444 /* Look for <: delimited address */
8445 c = strchr(contact, '<');
8446 if (c) {
8447 /* Take to > */
8448 ++c;
8449 len = strcspn(c, ">") + 1;
8450 } else {
8451 /* No <> - just take the lot */
8452 c = contact;
8453 len = strlen(contact) + 1;
8455 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
8456 /* ast_calloc is not needed because all fields are initialized in this block */
8457 ast_copy_string(thishop->hop, c, len);
8458 thishop->next = NULL;
8459 /* Goes at the end */
8460 if (tail)
8461 tail->next = thishop;
8462 else
8463 head = thishop;
8468 /* Store as new route */
8469 p->route = head;
8471 /* For debugging dump what we ended up with */
8472 if (sip_debug_test_pvt(p))
8473 list_route(p->route);
8476 AST_THREADSTORAGE(check_auth_buf, check_auth_buf_init);
8477 #define CHECK_AUTH_BUF_INITLEN 256
8479 /*! \brief Check user authorization from peer definition
8480 Some actions, like REGISTER and INVITEs from peers require
8481 authentication (if peer have secret set)
8482 \return 0 on success, non-zero on error
8484 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
8485 const char *secret, const char *md5secret, int sipmethod,
8486 char *uri, enum xmittype reliable, int ignore)
8488 const char *response = "407 Proxy Authentication Required";
8489 const char *reqheader = "Proxy-Authorization";
8490 const char *respheader = "Proxy-Authenticate";
8491 const char *authtoken;
8492 char a1_hash[256];
8493 char resp_hash[256]="";
8494 char *c;
8495 int wrongnonce = FALSE;
8496 int good_response;
8497 const char *usednonce = p->randdata;
8498 struct ast_dynamic_str *buf;
8499 int res;
8501 /* table of recognised keywords, and their value in the digest */
8502 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
8503 struct x {
8504 const char *key;
8505 const char *s;
8506 } *i, keys[] = {
8507 [K_RESP] = { "response=", "" },
8508 [K_URI] = { "uri=", "" },
8509 [K_USER] = { "username=", "" },
8510 [K_NONCE] = { "nonce=", "" },
8511 [K_LAST] = { NULL, NULL}
8514 /* Always OK if no secret */
8515 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
8516 return AUTH_SUCCESSFUL;
8517 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
8518 /* On a REGISTER, we have to use 401 and its family of headers instead of 407 and its family
8519 of headers -- GO SIP! Whoo hoo! Two things that do the same thing but are used in
8520 different circumstances! What a surprise. */
8521 response = "401 Unauthorized";
8522 reqheader = "Authorization";
8523 respheader = "WWW-Authenticate";
8525 authtoken = get_header(req, reqheader);
8526 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
8527 /* This is a retransmitted invite/register/etc, don't reconstruct authentication
8528 information */
8529 if (!reliable) {
8530 /* Resend message if this was NOT a reliable delivery. Otherwise the
8531 retransmission should get it */
8532 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
8533 /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
8534 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8536 return AUTH_CHALLENGE_SENT;
8537 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
8538 /* We have no auth, so issue challenge and request authentication */
8539 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
8540 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
8541 /* Schedule auto destroy in 32 seconds */
8542 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8543 return AUTH_CHALLENGE_SENT;
8546 /* --- We have auth, so check it */
8548 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
8549 an example in the spec of just what it is you're doing a hash on. */
8551 if (!(buf = ast_dynamic_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
8552 return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
8554 /* Make a copy of the response and parse it */
8555 res = ast_dynamic_str_thread_set(&buf, 0, &check_auth_buf, "%s", authtoken);
8557 if (res == AST_DYNSTR_BUILD_FAILED)
8558 return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
8560 c = buf->str;
8562 while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
8563 for (i = keys; i->key != NULL; i++) {
8564 const char *separator = ","; /* default */
8566 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
8567 continue;
8568 /* Found. Skip keyword, take text in quotes or up to the separator. */
8569 c += strlen(i->key);
8570 if (*c == '"') { /* in quotes. Skip first and look for last */
8571 c++;
8572 separator = "\"";
8574 i->s = c;
8575 strsep(&c, separator);
8576 break;
8578 if (i->key == NULL) /* not found, jump after space or comma */
8579 strsep(&c, " ,");
8582 /* Verify that digest username matches the username we auth as */
8583 if (strcmp(username, keys[K_USER].s)) {
8584 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
8585 username, keys[K_USER].s);
8586 /* Oops, we're trying something here */
8587 return AUTH_USERNAME_MISMATCH;
8590 /* Verify nonce from request matches our nonce. If not, send 401 with new nonce */
8591 if (strcasecmp(p->randdata, keys[K_NONCE].s)) { /* XXX it was 'n'casecmp ? */
8592 wrongnonce = TRUE;
8593 usednonce = keys[K_NONCE].s;
8596 if (!ast_strlen_zero(md5secret))
8597 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
8598 else {
8599 char a1[256];
8600 snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
8601 ast_md5_hash(a1_hash, a1);
8604 /* compute the expected response to compare with what we received */
8606 char a2[256];
8607 char a2_hash[256];
8608 char resp[256];
8610 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
8611 S_OR(keys[K_URI].s, uri));
8612 ast_md5_hash(a2_hash, a2);
8613 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
8614 ast_md5_hash(resp_hash, resp);
8617 good_response = keys[K_RESP].s &&
8618 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
8619 if (wrongnonce) {
8620 if (good_response) {
8621 if (sipdebug)
8622 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
8623 /* We got working auth token, based on stale nonce . */
8624 ast_string_field_build(p, randdata, "%08lx", ast_random());
8625 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
8626 } else {
8627 /* Everything was wrong, so give the device one more try with a new challenge */
8628 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
8629 if (sipdebug)
8630 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
8631 ast_string_field_build(p, randdata, "%08lx", ast_random());
8632 } else {
8633 if (sipdebug)
8634 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
8636 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
8639 /* Schedule auto destroy in 32 seconds */
8640 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8641 return AUTH_CHALLENGE_SENT;
8643 if (good_response) {
8644 append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
8645 return AUTH_SUCCESSFUL;
8648 /* Ok, we have a bad username/secret pair */
8649 /* Tell the UAS not to re-send this authentication data, because
8650 it will continue to fail
8653 return AUTH_SECRET_FAILED;
8656 /*! \brief Change onhold state of a peer using a pvt structure */
8657 static void sip_peer_hold(struct sip_pvt *p, int hold)
8659 struct sip_peer *peer = find_peer(p->peername, NULL, 1, 0);
8661 if (!peer)
8662 return;
8664 /* If they put someone on hold, increment the value... otherwise decrement it */
8665 if (hold)
8666 peer->onHold++;
8667 else
8668 peer->onHold--;
8670 /* Request device state update */
8671 ast_device_state_changed("SIP/%s", peer->name);
8673 return;
8676 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
8677 \note If you add an "hint" priority to the extension in the dial plan,
8678 you will get notifications on device state changes */
8679 static int cb_extensionstate(char *context, char* exten, int state, void *data)
8681 struct sip_pvt *p = data;
8683 ast_mutex_lock(&p->lock);
8685 switch(state) {
8686 case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
8687 case AST_EXTENSION_REMOVED: /* Extension is gone */
8688 if (p->autokillid > -1 && sip_cancel_destroy(p)) /* Remove subscription expiry for renewals */
8689 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
8690 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); /* Delete subscription in 32 secs */
8691 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);
8692 p->stateid = -1;
8693 p->subscribed = NONE;
8694 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
8695 break;
8696 default: /* Tell user */
8697 p->laststate = state;
8698 break;
8700 if (p->subscribed != NONE) { /* Only send state NOTIFY if we know the format */
8701 if (!p->pendinginvite) {
8702 transmit_state_notify(p, state, 1, FALSE);
8703 } else {
8704 /* We already have a NOTIFY sent that is not answered. Queue the state up.
8705 if many state changes happen meanwhile, we will only send a notification of the last one */
8706 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
8709 if (option_verbose > 1)
8710 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,
8711 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
8714 ast_mutex_unlock(&p->lock);
8716 return 0;
8719 /*! \brief Send a fake 401 Unauthorized response when the administrator
8720 wants to hide the names of local users/peers from fishers
8722 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable)
8724 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
8725 transmit_response_with_auth(p, "401 Unauthorized", req, p->randdata, reliable, "WWW-Authenticate", 0);
8728 /*! \brief Verify registration of user
8729 - Registration is done in several steps, first a REGISTER without auth
8730 to get a challenge (nonce) then a second one with auth
8731 - Registration requests are only matched with peers that are marked as "dynamic"
8733 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
8734 struct sip_request *req, char *uri)
8736 enum check_auth_result res = AUTH_NOT_FOUND;
8737 struct sip_peer *peer;
8738 char tmp[256];
8739 char *name, *c;
8740 char *t;
8741 char *domain;
8743 /* Terminate URI */
8744 t = uri;
8745 while(*t && (*t > 32) && (*t != ';'))
8746 t++;
8747 *t = '\0';
8749 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
8750 if (pedanticsipchecking)
8751 ast_uri_decode(tmp);
8753 c = get_in_brackets(tmp);
8754 c = strsep(&c, ";"); /* Ditch ;user=phone */
8756 if (!strncasecmp(c, "sip:", 4)) {
8757 name = c + 4;
8758 } else {
8759 name = c;
8760 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
8763 /* Strip off the domain name */
8764 if ((c = strchr(name, '@'))) {
8765 *c++ = '\0';
8766 domain = c;
8767 if ((c = strchr(domain, ':'))) /* Remove :port */
8768 *c = '\0';
8769 if (!AST_LIST_EMPTY(&domain_list)) {
8770 if (!check_sip_domain(domain, NULL, 0)) {
8771 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
8772 return AUTH_UNKNOWN_DOMAIN;
8777 ast_string_field_set(p, exten, name);
8778 build_contact(p);
8779 peer = find_peer(name, NULL, 1, 0);
8780 if (!(peer && ast_apply_ha(peer->ha, sin))) {
8781 /* Peer fails ACL check */
8782 if (peer) {
8783 ASTOBJ_UNREF(peer, sip_destroy_peer);
8784 res = AUTH_ACL_FAILED;
8785 } else
8786 res = AUTH_NOT_FOUND;
8788 if (peer) {
8789 /* Set Frame packetization */
8790 if (p->rtp) {
8791 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
8792 p->autoframing = peer->autoframing;
8794 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
8795 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
8796 res = AUTH_PEER_NOT_DYNAMIC;
8797 } else {
8798 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
8799 transmit_response(p, "100 Trying", req);
8800 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, ast_test_flag(req, SIP_PKT_IGNORE)))) {
8801 if (sip_cancel_destroy(p))
8802 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
8804 /* We have a succesful registration attemp with proper authentication,
8805 now, update the peer */
8806 switch (parse_register_contact(p, peer, req)) {
8807 case PARSE_REGISTER_FAILED:
8808 ast_log(LOG_WARNING, "Failed to parse contact info\n");
8809 transmit_response_with_date(p, "400 Bad Request", req);
8810 peer->lastmsgssent = -1;
8811 res = 0;
8812 break;
8813 case PARSE_REGISTER_QUERY:
8814 transmit_response_with_date(p, "200 OK", req);
8815 peer->lastmsgssent = -1;
8816 res = 0;
8817 break;
8818 case PARSE_REGISTER_UPDATE:
8819 update_peer(peer, p->expiry);
8820 /* Say OK and ask subsystem to retransmit msg counter */
8821 transmit_response_with_date(p, "200 OK", req);
8822 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
8823 peer->lastmsgssent = -1;
8824 res = 0;
8825 break;
8830 if (!peer && autocreatepeer) {
8831 /* Create peer if we have autocreate mode enabled */
8832 peer = temp_peer(name);
8833 if (peer) {
8834 ASTOBJ_CONTAINER_LINK(&peerl, peer);
8835 if (sip_cancel_destroy(p))
8836 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
8837 switch (parse_register_contact(p, peer, req)) {
8838 case PARSE_REGISTER_FAILED:
8839 ast_log(LOG_WARNING, "Failed to parse contact info\n");
8840 transmit_response_with_date(p, "400 Bad Request", req);
8841 peer->lastmsgssent = -1;
8842 res = 0;
8843 break;
8844 case PARSE_REGISTER_QUERY:
8845 transmit_response_with_date(p, "200 OK", req);
8846 peer->lastmsgssent = -1;
8847 res = 0;
8848 break;
8849 case PARSE_REGISTER_UPDATE:
8850 /* Say OK and ask subsystem to retransmit msg counter */
8851 transmit_response_with_date(p, "200 OK", req);
8852 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
8853 peer->lastmsgssent = -1;
8854 res = 0;
8855 break;
8859 if (!res) {
8860 ast_device_state_changed("SIP/%s", peer->name);
8862 if (res < 0) {
8863 switch (res) {
8864 case AUTH_SECRET_FAILED:
8865 /* Wrong password in authentication. Go away, don't try again until you fixed it */
8866 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
8867 break;
8868 case AUTH_USERNAME_MISMATCH:
8869 /* Username and digest username does not match.
8870 Asterisk uses the From: username for authentication. We need the
8871 users to use the same authentication user name until we support
8872 proper authentication by digest auth name */
8873 transmit_response(p, "403 Authentication user name does not match account name", &p->initreq);
8874 break;
8875 case AUTH_NOT_FOUND:
8876 case AUTH_PEER_NOT_DYNAMIC:
8877 case AUTH_ACL_FAILED:
8878 if (global_alwaysauthreject) {
8879 transmit_fake_auth_response(p, &p->initreq, 1);
8880 } else {
8881 /* URI not found */
8882 if (res == AUTH_PEER_NOT_DYNAMIC)
8883 transmit_response(p, "403 Forbidden", &p->initreq);
8884 else
8885 transmit_response(p, "404 Not found", &p->initreq);
8887 break;
8888 default:
8889 break;
8892 if (peer)
8893 ASTOBJ_UNREF(peer, sip_destroy_peer);
8895 return res;
8898 /*! \brief Get referring dnis */
8899 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
8901 char tmp[256], *c, *a;
8902 struct sip_request *req;
8904 req = oreq;
8905 if (!req)
8906 req = &p->initreq;
8907 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
8908 if (ast_strlen_zero(tmp))
8909 return 0;
8910 c = get_in_brackets(tmp);
8911 if (strncasecmp(c, "sip:", 4)) {
8912 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", c);
8913 return -1;
8915 c += 4;
8916 a = c;
8917 strsep(&a, "@;"); /* trim anything after @ or ; */
8918 if (sip_debug_test_pvt(p))
8919 ast_verbose("RDNIS is %s\n", c);
8920 ast_string_field_set(p, rdnis, c);
8922 return 0;
8925 /*! \brief Find out who the call is for
8926 We use the INVITE uri to find out
8928 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
8930 char tmp[256] = "", *uri, *a;
8931 char tmpf[256] = "", *from;
8932 struct sip_request *req;
8933 char *colon;
8934 char *decoded_uri;
8936 req = oreq;
8937 if (!req)
8938 req = &p->initreq;
8940 /* Find the request URI */
8941 if (req->rlPart2)
8942 ast_copy_string(tmp, req->rlPart2, sizeof(tmp));
8944 if (pedanticsipchecking)
8945 ast_uri_decode(tmp);
8947 uri = get_in_brackets(tmp);
8949 if (strncasecmp(uri, "sip:", 4)) {
8950 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
8951 return -1;
8953 uri += 4;
8955 /* Now find the From: caller ID and name */
8956 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
8957 if (!ast_strlen_zero(tmpf)) {
8958 if (pedanticsipchecking)
8959 ast_uri_decode(tmpf);
8960 from = get_in_brackets(tmpf);
8961 } else {
8962 from = NULL;
8965 if (!ast_strlen_zero(from)) {
8966 if (strncasecmp(from, "sip:", 4)) {
8967 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
8968 return -1;
8970 from += 4;
8971 if ((a = strchr(from, '@')))
8972 *a++ = '\0';
8973 else
8974 a = from; /* just a domain */
8975 from = strsep(&from, ";"); /* Remove userinfo options */
8976 a = strsep(&a, ";"); /* Remove URI options */
8977 ast_string_field_set(p, fromdomain, a);
8980 /* Skip any options and find the domain */
8982 /* Get the target domain */
8983 if ((a = strchr(uri, '@'))) {
8984 *a++ = '\0';
8985 } else { /* No username part */
8986 a = uri;
8987 uri = "s"; /* Set extension to "s" */
8989 colon = strchr(a, ':'); /* Remove :port */
8990 if (colon)
8991 *colon = '\0';
8993 uri = strsep(&uri, ";"); /* Remove userinfo options */
8994 a = strsep(&a, ";"); /* Remove URI options */
8996 ast_string_field_set(p, domain, a);
8998 if (!AST_LIST_EMPTY(&domain_list)) {
8999 char domain_context[AST_MAX_EXTENSION];
9001 domain_context[0] = '\0';
9002 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
9003 if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
9004 if (option_debug)
9005 ast_log(LOG_DEBUG, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
9006 return -2;
9009 /* If we have a context defined, overwrite the original context */
9010 if (!ast_strlen_zero(domain_context))
9011 ast_string_field_set(p, context, domain_context);
9014 /* If the request coming in is a subscription and subscribecontext has been specified use it */
9015 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
9016 ast_string_field_set(p, context, p->subscribecontext);
9018 if (sip_debug_test_pvt(p))
9019 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
9021 /* If this is a subscription we actually just need to see if a hint exists for the extension */
9022 if (req->method == SIP_SUBSCRIBE) {
9023 char hint[AST_MAX_EXTENSION];
9024 return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
9025 } else {
9026 decoded_uri = ast_strdupa(uri);
9027 ast_uri_decode(decoded_uri);
9028 /* Check the dialplan for the username part of the request URI,
9029 the domain will be stored in the SIPDOMAIN variable
9030 Since extensions.conf can have unescaped characters, try matching a decoded
9031 uri in addition to the non-decoded uri
9032 Return 0 if we have a matching extension */
9033 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)) ||
9034 !strcmp(decoded_uri, ast_pickup_ext())) {
9035 if (!oreq)
9036 ast_string_field_set(p, exten, decoded_uri);
9037 return 0;
9041 /* Return 1 for pickup extension or overlap dialling support (if we support it) */
9042 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
9043 ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
9044 !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
9045 return 1;
9048 return -1;
9051 /*! \brief Lock interface lock and find matching pvt lock
9053 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
9055 struct sip_pvt *sip_pvt_ptr;
9057 ast_mutex_lock(&iflock);
9059 if (option_debug > 3 && totag)
9060 ast_log(LOG_DEBUG, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
9062 /* Search interfaces and find the match */
9063 for (sip_pvt_ptr = iflist; sip_pvt_ptr; sip_pvt_ptr = sip_pvt_ptr->next) {
9064 if (!strcmp(sip_pvt_ptr->callid, callid)) {
9065 int match = 1;
9067 /* Go ahead and lock it (and its owner) before returning */
9068 ast_mutex_lock(&sip_pvt_ptr->lock);
9070 /* Check if tags match. If not, this is not the call we want
9071 (With a forking SIP proxy, several call legs share the
9072 call id, but have different tags)
9074 if (pedanticsipchecking) {
9075 const char *pvt_fromtag, *pvt_totag;
9077 if (ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_OUTGOING_CALL)) {
9078 /* Outgoing call tags : from is "our", to is "their" */
9079 pvt_fromtag = sip_pvt_ptr->tag ;
9080 pvt_totag = sip_pvt_ptr->theirtag ;
9081 } else {
9082 /* Incoming call tags : from is "their", to is "our" */
9083 pvt_fromtag = sip_pvt_ptr->theirtag ;
9084 pvt_totag = sip_pvt_ptr->tag ;
9086 if (ast_strlen_zero(fromtag) || strcmp(fromtag, pvt_fromtag) || (!ast_strlen_zero(totag) && strcmp(totag, pvt_totag)))
9087 match = 0;
9090 if (!match) {
9091 ast_mutex_unlock(&sip_pvt_ptr->lock);
9092 continue;
9095 if (option_debug > 3 && totag)
9096 ast_log(LOG_DEBUG, "Matched %s call - their tag is %s Our tag is %s\n",
9097 ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_OUTGOING_CALL) ? "OUTGOING": "INCOMING",
9098 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
9100 /* deadlock avoidance... */
9101 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
9102 DEADLOCK_AVOIDANCE(&sip_pvt_ptr->lock);
9104 break;
9107 ast_mutex_unlock(&iflock);
9108 if (option_debug > 3 && !sip_pvt_ptr)
9109 ast_log(LOG_DEBUG, "Found no match for callid %s to-tag %s from-tag %s\n", callid, totag, fromtag);
9110 return sip_pvt_ptr;
9113 /*! \brief Call transfer support (the REFER method)
9114 * Extracts Refer headers into pvt dialog structure */
9115 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
9118 const char *p_referred_by = NULL;
9119 char *h_refer_to = NULL;
9120 char *h_referred_by = NULL;
9121 char *refer_to;
9122 const char *p_refer_to;
9123 char *referred_by_uri = NULL;
9124 char *ptr;
9125 struct sip_request *req = NULL;
9126 const char *transfer_context = NULL;
9127 struct sip_refer *referdata;
9130 req = outgoing_req;
9131 referdata = transferer->refer;
9133 if (!req)
9134 req = &transferer->initreq;
9136 p_refer_to = get_header(req, "Refer-To");
9137 if (ast_strlen_zero(p_refer_to)) {
9138 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
9139 return -2; /* Syntax error */
9141 h_refer_to = ast_strdupa(p_refer_to);
9142 refer_to = get_in_brackets(h_refer_to);
9143 if (pedanticsipchecking)
9144 ast_uri_decode(refer_to);
9146 if (strncasecmp(refer_to, "sip:", 4)) {
9147 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
9148 return -3;
9150 refer_to += 4; /* Skip sip: */
9152 /* Get referred by header if it exists */
9153 p_referred_by = get_header(req, "Referred-By");
9154 if (!ast_strlen_zero(p_referred_by)) {
9155 char *lessthan;
9156 h_referred_by = ast_strdupa(p_referred_by);
9157 if (pedanticsipchecking)
9158 ast_uri_decode(h_referred_by);
9160 /* Store referrer's caller ID name */
9161 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
9162 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
9163 *(lessthan - 1) = '\0'; /* Space */
9166 referred_by_uri = get_in_brackets(h_referred_by);
9167 if(strncasecmp(referred_by_uri, "sip:", 4)) {
9168 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
9169 referred_by_uri = (char *) NULL;
9170 } else {
9171 referred_by_uri += 4; /* Skip sip: */
9175 /* Check for arguments in the refer_to header */
9176 if ((ptr = strchr(refer_to, '?'))) { /* Search for arguments */
9177 *ptr++ = '\0';
9178 if (!strncasecmp(ptr, "REPLACES=", 9)) {
9179 char *to = NULL, *from = NULL;
9181 /* This is an attended transfer */
9182 referdata->attendedtransfer = 1;
9183 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
9184 ast_uri_decode(referdata->replaces_callid);
9185 if ((ptr = strchr(referdata->replaces_callid, ';'))) /* Find options */ {
9186 *ptr++ = '\0';
9189 if (ptr) {
9190 /* Find the different tags before we destroy the string */
9191 to = strcasestr(ptr, "to-tag=");
9192 from = strcasestr(ptr, "from-tag=");
9195 /* Grab the to header */
9196 if (to) {
9197 ptr = to + 7;
9198 if ((to = strchr(ptr, '&')))
9199 *to = '\0';
9200 if ((to = strchr(ptr, ';')))
9201 *to = '\0';
9202 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
9205 if (from) {
9206 ptr = from + 9;
9207 if ((to = strchr(ptr, '&')))
9208 *to = '\0';
9209 if ((to = strchr(ptr, ';')))
9210 *to = '\0';
9211 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
9214 if (option_debug > 1) {
9215 if (!pedanticsipchecking)
9216 ast_log(LOG_DEBUG,"Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
9217 else
9218 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>" );
9223 if ((ptr = strchr(refer_to, '@'))) { /* Separate domain */
9224 char *urioption = NULL, *domain;
9225 *ptr++ = '\0';
9227 if ((urioption = strchr(ptr, ';'))) /* Separate urioptions */
9228 *urioption++ = '\0';
9230 domain = ptr;
9231 if ((ptr = strchr(domain, ':'))) /* Remove :port */
9232 *ptr = '\0';
9234 /* Save the domain for the dial plan */
9235 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
9236 if (urioption)
9237 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
9240 if ((ptr = strchr(refer_to, ';'))) /* Remove options */
9241 *ptr = '\0';
9242 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
9244 if (referred_by_uri) {
9245 if ((ptr = strchr(referred_by_uri, ';'))) /* Remove options */
9246 *ptr = '\0';
9247 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
9248 } else {
9249 referdata->referred_by[0] = '\0';
9252 /* Determine transfer context */
9253 if (transferer->owner) /* Mimic behaviour in res_features.c */
9254 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
9256 /* By default, use the context in the channel sending the REFER */
9257 if (ast_strlen_zero(transfer_context)) {
9258 transfer_context = S_OR(transferer->owner->macrocontext,
9259 S_OR(transferer->context, default_context));
9262 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
9264 /* Either an existing extension or the parking extension */
9265 if (ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
9266 if (sip_debug_test_pvt(transferer)) {
9267 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
9269 /* We are ready to transfer to the extension */
9270 return 0;
9272 if (sip_debug_test_pvt(transferer))
9273 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
9275 /* Failure, we can't find this extension */
9276 return -1;
9280 /*! \brief Call transfer support (old way, deprecated by the IETF)--*/
9281 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
9283 char tmp[256] = "", *c, *a;
9284 struct sip_request *req = oreq ? oreq : &p->initreq;
9285 struct sip_refer *referdata = NULL;
9286 const char *transfer_context = NULL;
9288 if (!p->refer && !sip_refer_allocate(p))
9289 return -1;
9291 referdata = p->refer;
9293 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
9294 c = get_in_brackets(tmp);
9296 if (pedanticsipchecking)
9297 ast_uri_decode(c);
9299 if (strncasecmp(c, "sip:", 4)) {
9300 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
9301 return -1;
9303 c += 4;
9304 if ((a = strchr(c, ';'))) /* Remove arguments */
9305 *a = '\0';
9307 if ((a = strchr(c, '@'))) { /* Separate Domain */
9308 *a++ = '\0';
9309 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
9312 if (sip_debug_test_pvt(p))
9313 ast_verbose("Looking for %s in %s\n", c, p->context);
9315 if (p->owner) /* Mimic behaviour in res_features.c */
9316 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
9318 /* By default, use the context in the channel sending the REFER */
9319 if (ast_strlen_zero(transfer_context)) {
9320 transfer_context = S_OR(p->owner->macrocontext,
9321 S_OR(p->context, default_context));
9323 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
9324 /* This is a blind transfer */
9325 if (option_debug)
9326 ast_log(LOG_DEBUG,"SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
9327 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
9328 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
9329 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
9330 referdata->refer_call = NULL;
9331 /* Set new context */
9332 ast_string_field_set(p, context, transfer_context);
9333 return 0;
9334 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
9335 return 1;
9338 return -1;
9340 /*! \brief check Via: header for hostname, port and rport request/answer */
9341 static void check_via(struct sip_pvt *p, const struct sip_request *req)
9343 char via[512];
9344 char *c, *pt;
9345 struct hostent *hp;
9346 struct ast_hostent ahp;
9348 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
9350 /* Work on the leftmost value of the topmost Via header */
9351 c = strchr(via, ',');
9352 if (c)
9353 *c = '\0';
9355 /* Check for rport */
9356 c = strstr(via, ";rport");
9357 if (c && (c[6] != '=')) /* rport query, not answer */
9358 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
9360 c = strchr(via, ';');
9361 if (c)
9362 *c = '\0';
9364 c = strchr(via, ' ');
9365 if (c) {
9366 *c = '\0';
9367 c = ast_skip_blanks(c+1);
9368 if (strcasecmp(via, "SIP/2.0/UDP")) {
9369 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
9370 return;
9372 pt = strchr(c, ':');
9373 if (pt)
9374 *pt++ = '\0'; /* remember port pointer */
9375 hp = ast_gethostbyname(c, &ahp);
9376 if (!hp) {
9377 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
9378 return;
9380 memset(&p->sa, 0, sizeof(p->sa));
9381 p->sa.sin_family = AF_INET;
9382 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
9383 p->sa.sin_port = htons(pt ? atoi(pt) : STANDARD_SIP_PORT);
9385 if (sip_debug_test_pvt(p)) {
9386 const struct sockaddr_in *dst = sip_real_dst(p);
9387 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
9392 /*! \brief Get caller id name from SIP headers */
9393 static char *get_calleridname(const char *input, char *output, size_t outputsize)
9395 const char *end = strchr(input,'<'); /* first_bracket */
9396 const char *tmp = strchr(input,'"'); /* first quote */
9397 int bytes = 0;
9398 int maxbytes = outputsize - 1;
9400 if (!end || end == input) /* we require a part in brackets */
9401 return NULL;
9403 end--; /* move just before "<" */
9405 if (tmp && tmp <= end) {
9406 /* The quote (tmp) precedes the bracket (end+1).
9407 * Find the matching quote and return the content.
9409 end = strchr(tmp+1, '"');
9410 if (!end)
9411 return NULL;
9412 bytes = (int) (end - tmp);
9413 /* protect the output buffer */
9414 if (bytes > maxbytes)
9415 bytes = maxbytes;
9416 ast_copy_string(output, tmp + 1, bytes);
9417 } else {
9418 /* No quoted string, or it is inside brackets. */
9419 /* clear the empty characters in the begining*/
9420 input = ast_skip_blanks(input);
9421 /* clear the empty characters in the end */
9422 while(*end && *end < 33 && end > input)
9423 end--;
9424 if (end >= input) {
9425 bytes = (int) (end - input) + 2;
9426 /* protect the output buffer */
9427 if (bytes > maxbytes)
9428 bytes = maxbytes;
9429 ast_copy_string(output, input, bytes);
9430 } else
9431 return NULL;
9433 return output;
9436 /*! \brief Get caller id number from Remote-Party-ID header field
9437 * Returns true if number should be restricted (privacy setting found)
9438 * output is set to NULL if no number found
9440 static int get_rpid_num(const char *input, char *output, int maxlen)
9442 char *start;
9443 char *end;
9445 start = strchr(input,':');
9446 if (!start) {
9447 output[0] = '\0';
9448 return 0;
9450 start++;
9452 /* we found "number" */
9453 ast_copy_string(output,start,maxlen);
9454 output[maxlen-1] = '\0';
9456 end = strchr(output,'@');
9457 if (end)
9458 *end = '\0';
9459 else
9460 output[0] = '\0';
9461 if (strstr(input,"privacy=full") || strstr(input,"privacy=uri"))
9462 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
9464 return 0;
9468 /*! \brief Check if matching user or peer is defined
9469 Match user on From: user name and peer on IP/port
9470 This is used on first invite (not re-invites) and subscribe requests
9471 \return 0 on success, non-zero on failure
9473 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
9474 int sipmethod, char *uri, enum xmittype reliable,
9475 struct sockaddr_in *sin, struct sip_peer **authpeer)
9477 struct sip_user *user = NULL;
9478 struct sip_peer *peer;
9479 char from[256], *c;
9480 char *of;
9481 char rpid_num[50];
9482 const char *rpid;
9483 enum check_auth_result res = AUTH_SUCCESSFUL;
9484 char *t;
9485 char calleridname[50];
9486 int debug=sip_debug_test_addr(sin);
9487 struct ast_variable *tmpvar = NULL, *v = NULL;
9488 char *uri2 = ast_strdupa(uri);
9490 /* Terminate URI */
9491 t = uri2;
9492 while (*t && *t > 32 && *t != ';')
9493 t++;
9494 *t = '\0';
9495 ast_copy_string(from, get_header(req, "From"), sizeof(from)); /* XXX bug in original code, overwrote string */
9496 if (pedanticsipchecking)
9497 ast_uri_decode(from);
9498 /* XXX here tries to map the username for invite things */
9499 memset(calleridname, 0, sizeof(calleridname));
9500 get_calleridname(from, calleridname, sizeof(calleridname));
9501 if (calleridname[0])
9502 ast_string_field_set(p, cid_name, calleridname);
9504 rpid = get_header(req, "Remote-Party-ID");
9505 memset(rpid_num, 0, sizeof(rpid_num));
9506 if (!ast_strlen_zero(rpid))
9507 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
9509 of = get_in_brackets(from);
9510 if (ast_strlen_zero(p->exten)) {
9511 t = uri2;
9512 if (!strncasecmp(t, "sip:", 4))
9513 t+= 4;
9514 ast_string_field_set(p, exten, t);
9515 t = strchr(p->exten, '@');
9516 if (t)
9517 *t = '\0';
9518 if (ast_strlen_zero(p->our_contact))
9519 build_contact(p);
9521 /* save the URI part of the From header */
9522 ast_string_field_set(p, from, of);
9523 if (strncasecmp(of, "sip:", 4)) {
9524 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
9525 } else
9526 of += 4;
9527 /* Get just the username part */
9528 if ((c = strchr(of, '@'))) {
9529 char *tmp;
9530 *c = '\0';
9531 if ((c = strchr(of, ':')))
9532 *c = '\0';
9533 tmp = ast_strdupa(of);
9534 /* We need to be able to handle auth-headers looking like
9535 <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
9537 tmp = strsep(&tmp, ";");
9538 if (ast_is_shrinkable_phonenumber(tmp))
9539 ast_shrink_phone_number(tmp);
9540 ast_string_field_set(p, cid_num, tmp);
9543 if (!authpeer) /* If we are looking for a peer, don't check the user objects (or realtime) */
9544 user = find_user(of, 1);
9546 /* Find user based on user name in the from header */
9547 if (user && ast_apply_ha(user->ha, sin)) {
9548 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
9549 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9550 /* copy channel vars */
9551 for (v = user->chanvars ; v ; v = v->next) {
9552 if ((tmpvar = ast_variable_new(v->name, v->value))) {
9553 tmpvar->next = p->chanvars;
9554 p->chanvars = tmpvar;
9557 p->prefs = user->prefs;
9558 /* Set Frame packetization */
9559 if (p->rtp) {
9560 ast_rtp_codec_setpref(p->rtp, &p->prefs);
9561 p->autoframing = user->autoframing;
9563 /* replace callerid if rpid found, and not restricted */
9564 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
9565 char *tmp;
9566 if (*calleridname)
9567 ast_string_field_set(p, cid_name, calleridname);
9568 tmp = ast_strdupa(rpid_num);
9569 if (ast_is_shrinkable_phonenumber(tmp))
9570 ast_shrink_phone_number(tmp);
9571 ast_string_field_set(p, cid_num, tmp);
9574 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE) );
9576 if (!(res = check_auth(p, req, user->name, user->secret, user->md5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
9577 if (sip_cancel_destroy(p))
9578 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
9579 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
9580 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9581 /* Copy SIP extensions profile from INVITE */
9582 if (p->sipoptions)
9583 user->sipoptions = p->sipoptions;
9585 /* If we have a call limit, set flag */
9586 if (user->call_limit)
9587 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
9588 if (!ast_strlen_zero(user->context))
9589 ast_string_field_set(p, context, user->context);
9590 if (!ast_strlen_zero(user->cid_num)) {
9591 char *tmp = ast_strdupa(user->cid_num);
9592 if (ast_is_shrinkable_phonenumber(tmp))
9593 ast_shrink_phone_number(tmp);
9594 ast_string_field_set(p, cid_num, tmp);
9596 if (!ast_strlen_zero(user->cid_name))
9597 ast_string_field_set(p, cid_name, user->cid_name);
9598 ast_string_field_set(p, username, user->name);
9599 ast_string_field_set(p, peername, user->name);
9600 ast_string_field_set(p, peersecret, user->secret);
9601 ast_string_field_set(p, peermd5secret, user->md5secret);
9602 ast_string_field_set(p, subscribecontext, user->subscribecontext);
9603 ast_string_field_set(p, accountcode, user->accountcode);
9604 ast_string_field_set(p, language, user->language);
9605 ast_string_field_set(p, mohsuggest, user->mohsuggest);
9606 ast_string_field_set(p, mohinterpret, user->mohinterpret);
9607 p->allowtransfer = user->allowtransfer;
9608 p->amaflags = user->amaflags;
9609 p->callgroup = user->callgroup;
9610 p->pickupgroup = user->pickupgroup;
9611 if (user->callingpres) /* User callingpres setting will override RPID header */
9612 p->callingpres = user->callingpres;
9614 /* Set default codec settings for this call */
9615 p->capability = user->capability; /* User codec choice */
9616 p->jointcapability = user->capability; /* Our codecs */
9617 if (p->peercapability) /* AND with peer's codecs */
9618 p->jointcapability &= p->peercapability;
9619 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
9620 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
9621 p->noncodeccapability |= AST_RTP_DTMF;
9622 else
9623 p->noncodeccapability &= ~AST_RTP_DTMF;
9624 p->jointnoncodeccapability = p->noncodeccapability;
9625 if (p->t38.peercapability)
9626 p->t38.jointcapability &= p->t38.peercapability;
9627 p->maxcallbitrate = user->maxcallbitrate;
9628 /* If we do not support video, remove video from call structure */
9629 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
9630 ast_rtp_destroy(p->vrtp);
9631 p->vrtp = NULL;
9634 if (user && debug)
9635 ast_verbose("Found user '%s'\n", user->name);
9636 } else {
9637 if (user) {
9638 if (!authpeer && debug)
9639 ast_verbose("Found user '%s', but fails host access\n", user->name);
9640 ASTOBJ_UNREF(user,sip_destroy_user);
9642 user = NULL;
9645 if (!user) {
9646 /* If we didn't find a user match, check for peers */
9647 if (sipmethod == SIP_SUBSCRIBE)
9648 /* For subscribes, match on peer name only */
9649 peer = find_peer(of, NULL, 1, 0);
9650 else
9651 /* Look for peer based on the IP address we received data from */
9652 /* If peer is registered from this IP address or have this as a default
9653 IP address, this call is from the peer
9655 peer = find_peer(NULL, &p->recv, 1, 0);
9657 if (peer) {
9658 /* Set Frame packetization */
9659 if (p->rtp) {
9660 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
9661 p->autoframing = peer->autoframing;
9663 if (debug)
9664 ast_verbose("Found peer '%s'\n", peer->name);
9666 /* Take the peer */
9667 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
9668 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9670 /* Copy SIP extensions profile to peer */
9671 if (p->sipoptions)
9672 peer->sipoptions = p->sipoptions;
9674 /* replace callerid if rpid found, and not restricted */
9675 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
9676 char *tmp = ast_strdupa(rpid_num);
9677 if (*calleridname)
9678 ast_string_field_set(p, cid_name, calleridname);
9679 if (ast_is_shrinkable_phonenumber(tmp))
9680 ast_shrink_phone_number(tmp);
9681 ast_string_field_set(p, cid_num, tmp);
9683 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
9685 ast_string_field_set(p, peersecret, peer->secret);
9686 ast_string_field_set(p, peermd5secret, peer->md5secret);
9687 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
9688 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
9689 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
9690 if (peer->callingpres) /* Peer calling pres setting will override RPID */
9691 p->callingpres = peer->callingpres;
9692 if (peer->maxms && peer->lastms)
9693 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
9694 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
9695 /* Pretend there is no required authentication */
9696 ast_string_field_free(p, peersecret);
9697 ast_string_field_free(p, peermd5secret);
9699 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
9700 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
9701 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9702 /* If we have a call limit, set flag */
9703 if (peer->call_limit)
9704 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
9705 ast_string_field_set(p, peername, peer->name);
9706 ast_string_field_set(p, authname, peer->name);
9708 /* copy channel vars */
9709 for (v = peer->chanvars ; v ; v = v->next) {
9710 if ((tmpvar = ast_variable_new(v->name, v->value))) {
9711 tmpvar->next = p->chanvars;
9712 p->chanvars = tmpvar;
9715 if (authpeer) {
9716 (*authpeer) = ASTOBJ_REF(peer); /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
9719 if (!ast_strlen_zero(peer->username)) {
9720 ast_string_field_set(p, username, peer->username);
9721 /* Use the default username for authentication on outbound calls */
9722 /* XXX this takes the name from the caller... can we override ? */
9723 ast_string_field_set(p, authname, peer->username);
9725 if (!ast_strlen_zero(peer->cid_num)) {
9726 char *tmp = ast_strdupa(peer->cid_num);
9727 if (ast_is_shrinkable_phonenumber(tmp))
9728 ast_shrink_phone_number(tmp);
9729 ast_string_field_set(p, cid_num, tmp);
9731 if (!ast_strlen_zero(peer->cid_name))
9732 ast_string_field_set(p, cid_name, peer->cid_name);
9733 ast_string_field_set(p, fullcontact, peer->fullcontact);
9734 if (!ast_strlen_zero(peer->context))
9735 ast_string_field_set(p, context, peer->context);
9736 ast_string_field_set(p, peersecret, peer->secret);
9737 ast_string_field_set(p, peermd5secret, peer->md5secret);
9738 ast_string_field_set(p, language, peer->language);
9739 ast_string_field_set(p, accountcode, peer->accountcode);
9740 p->amaflags = peer->amaflags;
9741 p->callgroup = peer->callgroup;
9742 p->pickupgroup = peer->pickupgroup;
9743 p->capability = peer->capability;
9744 p->prefs = peer->prefs;
9745 p->jointcapability = peer->capability;
9746 if (p->peercapability)
9747 p->jointcapability &= p->peercapability;
9748 p->maxcallbitrate = peer->maxcallbitrate;
9749 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
9750 ast_rtp_destroy(p->vrtp);
9751 p->vrtp = NULL;
9753 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
9754 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
9755 p->noncodeccapability |= AST_RTP_DTMF;
9756 else
9757 p->noncodeccapability &= ~AST_RTP_DTMF;
9758 p->jointnoncodeccapability = p->noncodeccapability;
9759 if (p->t38.peercapability)
9760 p->t38.jointcapability &= p->t38.peercapability;
9762 ASTOBJ_UNREF(peer, sip_destroy_peer);
9763 } else {
9764 if (debug)
9765 ast_verbose("Found no matching peer or user for '%s:%d'\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
9767 /* do we allow guests? */
9768 if (!global_allowguest) {
9769 if (global_alwaysauthreject)
9770 res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
9771 else
9772 res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
9773 } else if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
9774 char *tmp = ast_strdupa(rpid_num);
9775 if (*calleridname)
9776 ast_string_field_set(p, cid_name, calleridname);
9777 if (ast_is_shrinkable_phonenumber(tmp))
9778 ast_shrink_phone_number(tmp);
9779 ast_string_field_set(p, cid_num, tmp);
9785 if (user)
9786 ASTOBJ_UNREF(user, sip_destroy_user);
9787 return res;
9790 /*! \brief Find user
9791 If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
9793 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
9795 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
9798 /*! \brief Get text out of a SIP MESSAGE packet */
9799 static int get_msg_text(char *buf, int len, struct sip_request *req)
9801 int x;
9802 int y;
9804 buf[0] = '\0';
9805 y = len - strlen(buf) - 5;
9806 if (y < 0)
9807 y = 0;
9808 for (x=0;x<req->lines;x++) {
9809 strncat(buf, req->line[x], y); /* safe */
9810 y -= strlen(req->line[x]) + 1;
9811 if (y < 0)
9812 y = 0;
9813 if (y != 0)
9814 strcat(buf, "\n"); /* safe */
9816 return 0;
9820 /*! \brief Receive SIP MESSAGE method messages
9821 \note We only handle messages within current calls currently
9822 Reference: RFC 3428 */
9823 static void receive_message(struct sip_pvt *p, struct sip_request *req)
9825 char buf[1024];
9826 struct ast_frame f;
9827 const char *content_type = get_header(req, "Content-Type");
9829 if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
9830 transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
9831 if (!p->owner)
9832 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
9833 return;
9836 if (get_msg_text(buf, sizeof(buf), req)) {
9837 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
9838 transmit_response(p, "202 Accepted", req);
9839 if (!p->owner)
9840 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
9841 return;
9844 if (p->owner) {
9845 if (sip_debug_test_pvt(p))
9846 ast_verbose("Message received: '%s'\n", buf);
9847 memset(&f, 0, sizeof(f));
9848 f.frametype = AST_FRAME_TEXT;
9849 f.subclass = 0;
9850 f.offset = 0;
9851 f.data = buf;
9852 f.datalen = strlen(buf);
9853 ast_queue_frame(p->owner, &f);
9854 transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
9855 } else { /* Message outside of a call, we do not support that */
9856 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);
9857 transmit_response(p, "405 Method Not Allowed", req); /* Good enough, or? */
9858 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
9860 return;
9863 /*! \brief CLI Command to show calls within limits set by call_limit */
9864 static int sip_show_inuse(int fd, int argc, char *argv[])
9866 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
9867 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
9868 char ilimits[40];
9869 char iused[40];
9870 int showall = FALSE;
9872 if (argc < 3)
9873 return RESULT_SHOWUSAGE;
9875 if (argc == 4 && !strcmp(argv[3],"all"))
9876 showall = TRUE;
9878 ast_cli(fd, FORMAT, "* User name", "In use", "Limit");
9879 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
9880 ASTOBJ_RDLOCK(iterator);
9881 if (iterator->call_limit)
9882 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
9883 else
9884 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
9885 snprintf(iused, sizeof(iused), "%d", iterator->inUse);
9886 if (showall || iterator->call_limit)
9887 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
9888 ASTOBJ_UNLOCK(iterator);
9889 } while (0) );
9891 ast_cli(fd, FORMAT, "* Peer name", "In use", "Limit");
9893 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
9894 ASTOBJ_RDLOCK(iterator);
9895 if (iterator->call_limit)
9896 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
9897 else
9898 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
9899 snprintf(iused, sizeof(iused), "%d/%d", iterator->inUse, iterator->inRinging);
9900 if (showall || iterator->call_limit)
9901 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
9902 ASTOBJ_UNLOCK(iterator);
9903 } while (0) );
9905 return RESULT_SUCCESS;
9906 #undef FORMAT
9907 #undef FORMAT2
9910 /*! \brief Convert transfer mode to text string */
9911 static char *transfermode2str(enum transfermodes mode)
9913 if (mode == TRANSFER_OPENFORALL)
9914 return "open";
9915 else if (mode == TRANSFER_CLOSED)
9916 return "closed";
9917 return "strict";
9920 /*! \brief Convert NAT setting to text string */
9921 static char *nat2str(int nat)
9923 switch(nat) {
9924 case SIP_NAT_NEVER:
9925 return "No";
9926 case SIP_NAT_ROUTE:
9927 return "Route";
9928 case SIP_NAT_ALWAYS:
9929 return "Always";
9930 case SIP_NAT_RFC3581:
9931 return "RFC3581";
9932 default:
9933 return "Unknown";
9937 /*! \brief Report Peer status in character string
9938 * \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
9940 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
9942 int res = 0;
9943 if (peer->maxms) {
9944 if (peer->lastms < 0) {
9945 ast_copy_string(status, "UNREACHABLE", statuslen);
9946 } else if (peer->lastms > peer->maxms) {
9947 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
9948 res = 1;
9949 } else if (peer->lastms) {
9950 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
9951 res = 1;
9952 } else {
9953 ast_copy_string(status, "UNKNOWN", statuslen);
9955 } else {
9956 ast_copy_string(status, "Unmonitored", statuslen);
9957 /* Checking if port is 0 */
9958 res = -1;
9960 return res;
9963 /*! \brief CLI Command 'SIP Show Users' */
9964 static int sip_show_users(int fd, int argc, char *argv[])
9966 regex_t regexbuf;
9967 int havepattern = FALSE;
9969 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
9971 switch (argc) {
9972 case 5:
9973 if (!strcasecmp(argv[3], "like")) {
9974 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
9975 return RESULT_SHOWUSAGE;
9976 havepattern = TRUE;
9977 } else
9978 return RESULT_SHOWUSAGE;
9979 case 3:
9980 break;
9981 default:
9982 return RESULT_SHOWUSAGE;
9985 ast_cli(fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
9986 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
9987 ASTOBJ_RDLOCK(iterator);
9989 if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
9990 ASTOBJ_UNLOCK(iterator);
9991 continue;
9994 ast_cli(fd, FORMAT, iterator->name,
9995 iterator->secret,
9996 iterator->accountcode,
9997 iterator->context,
9998 iterator->ha ? "Yes" : "No",
9999 nat2str(ast_test_flag(&iterator->flags[0], SIP_NAT)));
10000 ASTOBJ_UNLOCK(iterator);
10001 } while (0)
10004 if (havepattern)
10005 regfree(&regexbuf);
10007 return RESULT_SUCCESS;
10008 #undef FORMAT
10011 static char mandescr_show_peers[] =
10012 "Description: Lists SIP peers in text format with details on current status.\n"
10013 "Variables: \n"
10014 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
10016 /*! \brief Show SIP peers in the manager API */
10017 /* Inspired from chan_iax2 */
10018 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
10020 const char *id = astman_get_header(m,"ActionID");
10021 const char *a[] = {"sip", "show", "peers"};
10022 char idtext[256] = "";
10023 int total = 0;
10025 if (!ast_strlen_zero(id))
10026 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
10028 astman_send_ack(s, m, "Peer status list will follow");
10029 /* List the peers in separate manager events */
10030 _sip_show_peers(-1, &total, s, m, 3, a);
10031 /* Send final confirmation */
10032 astman_append(s,
10033 "Event: PeerlistComplete\r\n"
10034 "ListItems: %d\r\n"
10035 "%s"
10036 "\r\n", total, idtext);
10037 return 0;
10040 /*! \brief CLI Show Peers command */
10041 static int sip_show_peers(int fd, int argc, char *argv[])
10043 return _sip_show_peers(fd, NULL, NULL, NULL, argc, (const char **) argv);
10046 /*! \brief _sip_show_peers: Execute sip show peers command */
10047 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
10049 regex_t regexbuf;
10050 int havepattern = FALSE;
10052 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %-10s\n"
10053 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %-10s\n"
10055 char name[256];
10056 int total_peers = 0;
10057 int peers_mon_online = 0;
10058 int peers_mon_offline = 0;
10059 int peers_unmon_offline = 0;
10060 int peers_unmon_online = 0;
10061 const char *id;
10062 char idtext[256] = "";
10063 int realtimepeers;
10065 realtimepeers = ast_check_realtime("sippeers");
10067 if (s) { /* Manager - get ActionID */
10068 id = astman_get_header(m,"ActionID");
10069 if (!ast_strlen_zero(id))
10070 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
10073 switch (argc) {
10074 case 5:
10075 if (!strcasecmp(argv[3], "like")) {
10076 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
10077 return RESULT_SHOWUSAGE;
10078 havepattern = TRUE;
10079 } else
10080 return RESULT_SHOWUSAGE;
10081 case 3:
10082 break;
10083 default:
10084 return RESULT_SHOWUSAGE;
10087 if (!s) /* Normal list */
10088 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
10090 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
10091 char status[20] = "";
10092 char srch[2000];
10093 char pstatus;
10095 ASTOBJ_RDLOCK(iterator);
10097 if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
10098 ASTOBJ_UNLOCK(iterator);
10099 continue;
10102 if (!ast_strlen_zero(iterator->username) && !s)
10103 snprintf(name, sizeof(name), "%s/%s", iterator->name, iterator->username);
10104 else
10105 ast_copy_string(name, iterator->name, sizeof(name));
10107 pstatus = peer_status(iterator, status, sizeof(status));
10108 if (pstatus == 1)
10109 peers_mon_online++;
10110 else if (pstatus == 0)
10111 peers_mon_offline++;
10112 else {
10113 if (iterator->addr.sin_port == 0)
10114 peers_unmon_offline++;
10115 else
10116 peers_unmon_online++;
10119 snprintf(srch, sizeof(srch), FORMAT, name,
10120 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
10121 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ", /* Dynamic or not? */
10122 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
10123 iterator->ha ? " A " : " ", /* permit/deny */
10124 ntohs(iterator->addr.sin_port), status,
10125 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
10127 if (!s) {/* Normal CLI list */
10128 ast_cli(fd, FORMAT, name,
10129 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
10130 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ", /* Dynamic or not? */
10131 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
10132 iterator->ha ? " A " : " ", /* permit/deny */
10134 ntohs(iterator->addr.sin_port), status,
10135 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
10136 } else { /* Manager format */
10137 /* The names here need to be the same as other channels */
10138 astman_append(s,
10139 "Event: PeerEntry\r\n%s"
10140 "Channeltype: SIP\r\n"
10141 "ObjectName: %s\r\n"
10142 "ChanObjectType: peer\r\n" /* "peer" or "user" */
10143 "IPaddress: %s\r\n"
10144 "IPport: %d\r\n"
10145 "Dynamic: %s\r\n"
10146 "Natsupport: %s\r\n"
10147 "VideoSupport: %s\r\n"
10148 "ACL: %s\r\n"
10149 "Status: %s\r\n"
10150 "RealtimeDevice: %s\r\n\r\n",
10151 idtext,
10152 iterator->name,
10153 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "-none-",
10154 ntohs(iterator->addr.sin_port),
10155 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no", /* Dynamic or not? */
10156 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? "yes" : "no", /* NAT=yes? */
10157 ast_test_flag(&iterator->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no", /* VIDEOSUPPORT=yes? */
10158 iterator->ha ? "yes" : "no", /* permit/deny */
10159 status,
10160 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "yes":"no") : "no");
10163 ASTOBJ_UNLOCK(iterator);
10165 total_peers++;
10166 } while(0) );
10168 if (!s)
10169 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
10170 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
10172 if (havepattern)
10173 regfree(&regexbuf);
10175 if (total)
10176 *total = total_peers;
10179 return RESULT_SUCCESS;
10180 #undef FORMAT
10181 #undef FORMAT2
10184 /*! \brief List all allocated SIP Objects (realtime or static) */
10185 static int sip_show_objects(int fd, int argc, char *argv[])
10187 char tmp[256];
10188 if (argc != 3)
10189 return RESULT_SHOWUSAGE;
10190 ast_cli(fd, "-= User objects: %d static, %d realtime =-\n\n", suserobjs, ruserobjs);
10191 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &userl);
10192 ast_cli(fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
10193 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &peerl);
10194 ast_cli(fd, "-= Registry objects: %d =-\n\n", regobjs);
10195 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &regl);
10196 return RESULT_SUCCESS;
10198 /*! \brief Print call group and pickup group */
10199 static void print_group(int fd, ast_group_t group, int crlf)
10201 char buf[256];
10202 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
10205 /*! \brief Convert DTMF mode to printable string */
10206 static const char *dtmfmode2str(int mode)
10208 switch (mode) {
10209 case SIP_DTMF_RFC2833:
10210 return "rfc2833";
10211 case SIP_DTMF_INFO:
10212 return "info";
10213 case SIP_DTMF_INBAND:
10214 return "inband";
10215 case SIP_DTMF_AUTO:
10216 return "auto";
10218 return "<error>";
10221 /*! \brief Convert Insecure setting to printable string */
10222 static const char *insecure2str(int port, int invite)
10224 if (port && invite)
10225 return "port,invite";
10226 else if (port)
10227 return "port";
10228 else if (invite)
10229 return "invite";
10230 else
10231 return "no";
10234 /*! \brief Destroy disused contexts between reloads
10235 Only used in reload_config so the code for regcontext doesn't get ugly
10237 static void cleanup_stale_contexts(char *new, char *old)
10239 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
10241 while ((oldcontext = strsep(&old, "&"))) {
10242 stalecontext = '\0';
10243 ast_copy_string(newlist, new, sizeof(newlist));
10244 stringp = newlist;
10245 while ((newcontext = strsep(&stringp, "&"))) {
10246 if (strcmp(newcontext, oldcontext) == 0) {
10247 /* This is not the context you're looking for */
10248 stalecontext = '\0';
10249 break;
10250 } else if (strcmp(newcontext, oldcontext)) {
10251 stalecontext = oldcontext;
10255 if (stalecontext)
10256 ast_context_destroy(ast_context_find(stalecontext), "SIP");
10260 /*! \brief Remove temporary realtime objects from memory (CLI) */
10261 static int sip_prune_realtime(int fd, int argc, char *argv[])
10263 struct sip_peer *peer;
10264 struct sip_user *user;
10265 int pruneuser = FALSE;
10266 int prunepeer = FALSE;
10267 int multi = FALSE;
10268 char *name = NULL;
10269 regex_t regexbuf;
10271 switch (argc) {
10272 case 4:
10273 if (!strcasecmp(argv[3], "user"))
10274 return RESULT_SHOWUSAGE;
10275 if (!strcasecmp(argv[3], "peer"))
10276 return RESULT_SHOWUSAGE;
10277 if (!strcasecmp(argv[3], "like"))
10278 return RESULT_SHOWUSAGE;
10279 if (!strcasecmp(argv[3], "all")) {
10280 multi = TRUE;
10281 pruneuser = prunepeer = TRUE;
10282 } else {
10283 pruneuser = prunepeer = TRUE;
10284 name = argv[3];
10286 break;
10287 case 5:
10288 if (!strcasecmp(argv[4], "like"))
10289 return RESULT_SHOWUSAGE;
10290 if (!strcasecmp(argv[3], "all"))
10291 return RESULT_SHOWUSAGE;
10292 if (!strcasecmp(argv[3], "like")) {
10293 multi = TRUE;
10294 name = argv[4];
10295 pruneuser = prunepeer = TRUE;
10296 } else if (!strcasecmp(argv[3], "user")) {
10297 pruneuser = TRUE;
10298 if (!strcasecmp(argv[4], "all"))
10299 multi = TRUE;
10300 else
10301 name = argv[4];
10302 } else if (!strcasecmp(argv[3], "peer")) {
10303 prunepeer = TRUE;
10304 if (!strcasecmp(argv[4], "all"))
10305 multi = TRUE;
10306 else
10307 name = argv[4];
10308 } else
10309 return RESULT_SHOWUSAGE;
10310 break;
10311 case 6:
10312 if (strcasecmp(argv[4], "like"))
10313 return RESULT_SHOWUSAGE;
10314 if (!strcasecmp(argv[3], "user")) {
10315 pruneuser = TRUE;
10316 name = argv[5];
10317 } else if (!strcasecmp(argv[3], "peer")) {
10318 prunepeer = TRUE;
10319 name = argv[5];
10320 } else
10321 return RESULT_SHOWUSAGE;
10322 break;
10323 default:
10324 return RESULT_SHOWUSAGE;
10327 if (multi && name) {
10328 if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
10329 return RESULT_SHOWUSAGE;
10332 if (multi) {
10333 if (prunepeer) {
10334 int pruned = 0;
10336 ASTOBJ_CONTAINER_WRLOCK(&peerl);
10337 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
10338 ASTOBJ_RDLOCK(iterator);
10339 if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
10340 ASTOBJ_UNLOCK(iterator);
10341 continue;
10343 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10344 ASTOBJ_MARK(iterator);
10345 pruned++;
10347 ASTOBJ_UNLOCK(iterator);
10348 } while (0) );
10349 if (pruned) {
10350 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
10351 ast_cli(fd, "%d peers pruned.\n", pruned);
10352 } else
10353 ast_cli(fd, "No peers found to prune.\n");
10354 ASTOBJ_CONTAINER_UNLOCK(&peerl);
10356 if (pruneuser) {
10357 int pruned = 0;
10359 ASTOBJ_CONTAINER_WRLOCK(&userl);
10360 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
10361 ASTOBJ_RDLOCK(iterator);
10362 if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
10363 ASTOBJ_UNLOCK(iterator);
10364 continue;
10366 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10367 ASTOBJ_MARK(iterator);
10368 pruned++;
10370 ASTOBJ_UNLOCK(iterator);
10371 } while (0) );
10372 if (pruned) {
10373 ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, sip_destroy_user);
10374 ast_cli(fd, "%d users pruned.\n", pruned);
10375 } else
10376 ast_cli(fd, "No users found to prune.\n");
10377 ASTOBJ_CONTAINER_UNLOCK(&userl);
10379 } else {
10380 if (prunepeer) {
10381 if ((peer = ASTOBJ_CONTAINER_FIND_UNLINK(&peerl, name))) {
10382 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10383 ast_cli(fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
10384 ASTOBJ_CONTAINER_LINK(&peerl, peer);
10385 } else
10386 ast_cli(fd, "Peer '%s' pruned.\n", name);
10387 ASTOBJ_UNREF(peer, sip_destroy_peer);
10388 } else
10389 ast_cli(fd, "Peer '%s' not found.\n", name);
10391 if (pruneuser) {
10392 if ((user = ASTOBJ_CONTAINER_FIND_UNLINK(&userl, name))) {
10393 if (!ast_test_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10394 ast_cli(fd, "User '%s' is not a Realtime user, cannot be pruned.\n", name);
10395 ASTOBJ_CONTAINER_LINK(&userl, user);
10396 } else
10397 ast_cli(fd, "User '%s' pruned.\n", name);
10398 ASTOBJ_UNREF(user, sip_destroy_user);
10399 } else
10400 ast_cli(fd, "User '%s' not found.\n", name);
10404 return RESULT_SUCCESS;
10407 /*! \brief Print codec list from preference to CLI/manager */
10408 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
10410 int x, codec;
10412 for(x = 0; x < 32 ; x++) {
10413 codec = ast_codec_pref_index(pref, x);
10414 if (!codec)
10415 break;
10416 ast_cli(fd, "%s", ast_getformatname(codec));
10417 ast_cli(fd, ":%d", pref->framing[x]);
10418 if (x < 31 && ast_codec_pref_index(pref, x + 1))
10419 ast_cli(fd, ",");
10421 if (!x)
10422 ast_cli(fd, "none");
10425 /*! \brief Print domain mode to cli */
10426 static const char *domain_mode_to_text(const enum domain_mode mode)
10428 switch (mode) {
10429 case SIP_DOMAIN_AUTO:
10430 return "[Automatic]";
10431 case SIP_DOMAIN_CONFIG:
10432 return "[Configured]";
10435 return "";
10438 /*! \brief CLI command to list local domains */
10439 static int sip_show_domains(int fd, int argc, char *argv[])
10441 struct domain *d;
10442 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
10444 if (AST_LIST_EMPTY(&domain_list)) {
10445 ast_cli(fd, "SIP Domain support not enabled.\n\n");
10446 return RESULT_SUCCESS;
10447 } else {
10448 ast_cli(fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
10449 AST_LIST_LOCK(&domain_list);
10450 AST_LIST_TRAVERSE(&domain_list, d, list)
10451 ast_cli(fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
10452 domain_mode_to_text(d->mode));
10453 AST_LIST_UNLOCK(&domain_list);
10454 ast_cli(fd, "\n");
10455 return RESULT_SUCCESS;
10458 #undef FORMAT
10460 static char mandescr_show_peer[] =
10461 "Description: Show one SIP peer with details on current status.\n"
10462 "Variables: \n"
10463 " Peer: <name> The peer name you want to check.\n"
10464 " ActionID: <id> Optional action ID for this AMI transaction.\n";
10466 /*! \brief Show SIP peers in the manager API */
10467 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
10469 const char *a[4];
10470 const char *peer;
10471 int ret;
10473 peer = astman_get_header(m,"Peer");
10474 if (ast_strlen_zero(peer)) {
10475 astman_send_error(s, m, "Peer: <name> missing.");
10476 return 0;
10478 a[0] = "sip";
10479 a[1] = "show";
10480 a[2] = "peer";
10481 a[3] = peer;
10483 ret = _sip_show_peer(1, -1, s, m, 4, a);
10484 astman_append(s, "\r\n\r\n" );
10485 return ret;
10490 /*! \brief Show one peer in detail */
10491 static int sip_show_peer(int fd, int argc, char *argv[])
10493 return _sip_show_peer(0, fd, NULL, NULL, argc, (const char **) argv);
10496 /*! \brief Show one peer in detail (main function) */
10497 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
10499 char status[30] = "";
10500 char cbuf[256];
10501 struct sip_peer *peer;
10502 char codec_buf[512];
10503 struct ast_codec_pref *pref;
10504 struct ast_variable *v;
10505 struct sip_auth *auth;
10506 int x = 0, codec = 0, load_realtime;
10507 int realtimepeers;
10509 realtimepeers = ast_check_realtime("sippeers");
10511 if (argc < 4)
10512 return RESULT_SHOWUSAGE;
10514 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
10515 peer = find_peer(argv[3], NULL, load_realtime, 0);
10516 if (s) { /* Manager */
10517 if (peer) {
10518 const char *id = astman_get_header(m,"ActionID");
10520 astman_append(s, "Response: Success\r\n");
10521 if (!ast_strlen_zero(id))
10522 astman_append(s, "ActionID: %s\r\n",id);
10523 } else {
10524 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
10525 astman_send_error(s, m, cbuf);
10526 return 0;
10529 if (peer && type==0 ) { /* Normal listing */
10530 ast_cli(fd,"\n\n");
10531 ast_cli(fd, " * Name : %s\n", peer->name);
10532 if (realtimepeers) { /* Realtime is enabled */
10533 ast_cli(fd, " Realtime peer: %s\n", ast_test_flag(&peer->flags[0], SIP_REALTIME) ? "Yes, cached" : "No");
10535 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
10536 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
10537 for (auth = peer->auth; auth; auth = auth->next) {
10538 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
10539 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
10541 ast_cli(fd, " Context : %s\n", peer->context);
10542 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
10543 ast_cli(fd, " Language : %s\n", peer->language);
10544 if (!ast_strlen_zero(peer->accountcode))
10545 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
10546 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
10547 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
10548 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
10549 if (!ast_strlen_zero(peer->fromuser))
10550 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
10551 if (!ast_strlen_zero(peer->fromdomain))
10552 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
10553 ast_cli(fd, " Callgroup : ");
10554 print_group(fd, peer->callgroup, 0);
10555 ast_cli(fd, " Pickupgroup : ");
10556 print_group(fd, peer->pickupgroup, 0);
10557 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
10558 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
10559 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
10560 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
10561 ast_cli(fd, " Dynamic : %s\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Yes":"No"));
10562 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
10563 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
10564 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
10565 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)));
10566 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
10567 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
10568 ast_cli(fd, " T38 pt UDPTL : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL)?"Yes":"No");
10569 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10570 ast_cli(fd, " T38 pt RTP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_RTP)?"Yes":"No");
10571 ast_cli(fd, " T38 pt TCP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_TCP)?"Yes":"No");
10572 #endif
10573 ast_cli(fd, " CanReinvite : %s\n", ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Yes":"No");
10574 ast_cli(fd, " PromiscRedir : %s\n", ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Yes":"No");
10575 ast_cli(fd, " User=Phone : %s\n", ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Yes":"No");
10576 ast_cli(fd, " Video Support: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Yes":"No");
10577 ast_cli(fd, " Trust RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_TRUSTRPID) ? "Yes" : "No");
10578 ast_cli(fd, " Send RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_SENDRPID) ? "Yes" : "No");
10579 ast_cli(fd, " Subscriptions: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
10580 ast_cli(fd, " Overlap dial : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
10582 /* - is enumerated */
10583 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
10584 ast_cli(fd, " LastMsg : %d\n", peer->lastmsg);
10585 ast_cli(fd, " ToHost : %s\n", peer->tohost);
10586 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));
10587 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
10588 if (!ast_strlen_zero(global_regcontext))
10589 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
10590 ast_cli(fd, " Def. Username: %s\n", peer->username);
10591 ast_cli(fd, " SIP Options : ");
10592 if (peer->sipoptions) {
10593 int lastoption = -1;
10594 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
10595 if (sip_options[x].id != lastoption) {
10596 if (peer->sipoptions & sip_options[x].id)
10597 ast_cli(fd, "%s ", sip_options[x].text);
10598 lastoption = x;
10601 } else
10602 ast_cli(fd, "(none)");
10604 ast_cli(fd, "\n");
10605 ast_cli(fd, " Codecs : ");
10606 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
10607 ast_cli(fd, "%s\n", codec_buf);
10608 ast_cli(fd, " Codec Order : (");
10609 print_codec_to_cli(fd, &peer->prefs);
10610 ast_cli(fd, ")\n");
10612 ast_cli(fd, " Auto-Framing: %s \n", peer->autoframing ? "Yes" : "No");
10613 ast_cli(fd, " Status : ");
10614 peer_status(peer, status, sizeof(status));
10615 ast_cli(fd, "%s\n",status);
10616 ast_cli(fd, " Useragent : %s\n", peer->useragent);
10617 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
10618 if (peer->chanvars) {
10619 ast_cli(fd, " Variables :\n");
10620 for (v = peer->chanvars ; v ; v = v->next)
10621 ast_cli(fd, " %s = %s\n", v->name, v->value);
10623 ast_cli(fd,"\n");
10624 ASTOBJ_UNREF(peer,sip_destroy_peer);
10625 } else if (peer && type == 1) { /* manager listing */
10626 char buf[256];
10627 astman_append(s, "Channeltype: SIP\r\n");
10628 astman_append(s, "ObjectName: %s\r\n", peer->name);
10629 astman_append(s, "ChanObjectType: peer\r\n");
10630 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
10631 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
10632 astman_append(s, "Context: %s\r\n", peer->context);
10633 astman_append(s, "Language: %s\r\n", peer->language);
10634 if (!ast_strlen_zero(peer->accountcode))
10635 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
10636 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
10637 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
10638 if (!ast_strlen_zero(peer->fromuser))
10639 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
10640 if (!ast_strlen_zero(peer->fromdomain))
10641 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
10642 astman_append(s, "Callgroup: ");
10643 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->callgroup));
10644 astman_append(s, "Pickupgroup: ");
10645 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->pickupgroup));
10646 astman_append(s, "VoiceMailbox: %s\r\n", peer->mailbox);
10647 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
10648 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
10649 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
10650 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
10651 astman_append(s, "Dynamic: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Y":"N"));
10652 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
10653 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched,peer->expire));
10654 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)));
10655 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
10656 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
10657 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
10658 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
10659 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
10660 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
10662 /* - is enumerated */
10663 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
10664 astman_append(s, "SIPLastMsg: %d\r\n", peer->lastmsg);
10665 astman_append(s, "ToHost: %s\r\n", peer->tohost);
10666 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));
10667 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));
10668 astman_append(s, "Default-Username: %s\r\n", peer->username);
10669 if (!ast_strlen_zero(global_regcontext))
10670 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
10671 astman_append(s, "Codecs: ");
10672 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
10673 astman_append(s, "%s\r\n", codec_buf);
10674 astman_append(s, "CodecOrder: ");
10675 pref = &peer->prefs;
10676 for(x = 0; x < 32 ; x++) {
10677 codec = ast_codec_pref_index(pref,x);
10678 if (!codec)
10679 break;
10680 astman_append(s, "%s", ast_getformatname(codec));
10681 if (x < 31 && ast_codec_pref_index(pref,x+1))
10682 astman_append(s, ",");
10685 astman_append(s, "\r\n");
10686 astman_append(s, "Status: ");
10687 peer_status(peer, status, sizeof(status));
10688 astman_append(s, "%s\r\n", status);
10689 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
10690 astman_append(s, "Reg-Contact : %s\r\n", peer->fullcontact);
10691 if (peer->chanvars) {
10692 for (v = peer->chanvars ; v ; v = v->next) {
10693 astman_append(s, "ChanVariable:\n");
10694 astman_append(s, " %s,%s\r\n", v->name, v->value);
10698 ASTOBJ_UNREF(peer,sip_destroy_peer);
10700 } else {
10701 ast_cli(fd,"Peer %s not found.\n", argv[3]);
10702 ast_cli(fd,"\n");
10705 return RESULT_SUCCESS;
10708 /*! \brief Show one user in detail */
10709 static int sip_show_user(int fd, int argc, char *argv[])
10711 char cbuf[256];
10712 struct sip_user *user;
10713 struct ast_variable *v;
10714 int load_realtime;
10716 if (argc < 4)
10717 return RESULT_SHOWUSAGE;
10719 /* Load from realtime storage? */
10720 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
10722 user = find_user(argv[3], load_realtime);
10723 if (user) {
10724 ast_cli(fd,"\n\n");
10725 ast_cli(fd, " * Name : %s\n", user->name);
10726 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
10727 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
10728 ast_cli(fd, " Context : %s\n", user->context);
10729 ast_cli(fd, " Language : %s\n", user->language);
10730 if (!ast_strlen_zero(user->accountcode))
10731 ast_cli(fd, " Accountcode : %s\n", user->accountcode);
10732 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
10733 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
10734 ast_cli(fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
10735 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
10736 ast_cli(fd, " Call limit : %d\n", user->call_limit);
10737 ast_cli(fd, " Callgroup : ");
10738 print_group(fd, user->callgroup, 0);
10739 ast_cli(fd, " Pickupgroup : ");
10740 print_group(fd, user->pickupgroup, 0);
10741 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
10742 ast_cli(fd, " ACL : %s\n", (user->ha?"Yes":"No"));
10743 ast_cli(fd, " Codec Order : (");
10744 print_codec_to_cli(fd, &user->prefs);
10745 ast_cli(fd, ")\n");
10747 ast_cli(fd, " Auto-Framing: %s \n", user->autoframing ? "Yes" : "No");
10748 if (user->chanvars) {
10749 ast_cli(fd, " Variables :\n");
10750 for (v = user->chanvars ; v ; v = v->next)
10751 ast_cli(fd, " %s = %s\n", v->name, v->value);
10753 ast_cli(fd,"\n");
10754 ASTOBJ_UNREF(user,sip_destroy_user);
10755 } else {
10756 ast_cli(fd,"User %s not found.\n", argv[3]);
10757 ast_cli(fd,"\n");
10760 return RESULT_SUCCESS;
10763 /*! \brief Show SIP Registry (registrations with other SIP proxies */
10764 static int sip_show_registry(int fd, int argc, char *argv[])
10766 #define FORMAT2 "%-30.30s %-12.12s %8.8s %-20.20s %-25.25s\n"
10767 #define FORMAT "%-30.30s %-12.12s %8d %-20.20s %-25.25s\n"
10768 char host[80];
10769 char tmpdat[256];
10770 struct tm tm;
10773 if (argc != 3)
10774 return RESULT_SHOWUSAGE;
10775 ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State", "Reg.Time");
10776 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
10777 ASTOBJ_RDLOCK(iterator);
10778 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
10779 if (iterator->regtime) {
10780 ast_localtime(&iterator->regtime, &tm, NULL);
10781 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
10782 } else {
10783 tmpdat[0] = 0;
10785 ast_cli(fd, FORMAT, host, iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
10786 ASTOBJ_UNLOCK(iterator);
10787 } while(0));
10788 return RESULT_SUCCESS;
10789 #undef FORMAT
10790 #undef FORMAT2
10793 /*! \brief List global settings for the SIP channel */
10794 static int sip_show_settings(int fd, int argc, char *argv[])
10796 int realtimepeers;
10797 int realtimeusers;
10798 char codec_buf[SIPBUFSIZE];
10800 realtimepeers = ast_check_realtime("sippeers");
10801 realtimeusers = ast_check_realtime("sipusers");
10803 if (argc != 3)
10804 return RESULT_SHOWUSAGE;
10805 ast_cli(fd, "\n\nGlobal Settings:\n");
10806 ast_cli(fd, "----------------\n");
10807 ast_cli(fd, " SIP Port: %d\n", ntohs(bindaddr.sin_port));
10808 ast_cli(fd, " Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
10809 ast_cli(fd, " Videosupport: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "Yes" : "No");
10810 ast_cli(fd, " AutoCreatePeer: %s\n", autocreatepeer ? "Yes" : "No");
10811 ast_cli(fd, " Allow unknown access: %s\n", global_allowguest ? "Yes" : "No");
10812 ast_cli(fd, " Allow subscriptions: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
10813 ast_cli(fd, " Allow overlap dialing: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
10814 ast_cli(fd, " Promsic. redir: %s\n", ast_test_flag(&global_flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
10815 ast_cli(fd, " SIP domain support: %s\n", AST_LIST_EMPTY(&domain_list) ? "No" : "Yes");
10816 ast_cli(fd, " Call to non-local dom.: %s\n", allow_external_domains ? "Yes" : "No");
10817 ast_cli(fd, " URI user is phone no: %s\n", ast_test_flag(&global_flags[0], SIP_USEREQPHONE) ? "Yes" : "No");
10818 ast_cli(fd, " Our auth realm %s\n", global_realm);
10819 ast_cli(fd, " Realm. auth: %s\n", authl ? "Yes": "No");
10820 ast_cli(fd, " Always auth rejects: %s\n", global_alwaysauthreject ? "Yes" : "No");
10821 ast_cli(fd, " Call limit peers only: %s\n", global_limitonpeers ? "Yes" : "No");
10822 ast_cli(fd, " Direct RTP setup: %s\n", global_directrtpsetup ? "Yes" : "No");
10823 ast_cli(fd, " User Agent: %s\n", global_useragent);
10824 ast_cli(fd, " MWI checking interval: %d secs\n", global_mwitime);
10825 ast_cli(fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
10826 ast_cli(fd, " Caller ID: %s\n", default_callerid);
10827 ast_cli(fd, " From: Domain: %s\n", default_fromdomain);
10828 ast_cli(fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
10829 ast_cli(fd, " Call Events: %s\n", global_callevents ? "On" : "Off");
10830 ast_cli(fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
10831 ast_cli(fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
10832 ast_cli(fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
10833 ast_cli(fd, " T38 fax pt UDPTL: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_UDPTL) ? "Yes" : "No");
10834 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10835 ast_cli(fd, " T38 fax pt RTP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_RTP) ? "Yes" : "No");
10836 ast_cli(fd, " T38 fax pt TCP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_TCP) ? "Yes" : "No");
10837 #endif
10838 ast_cli(fd, " RFC2833 Compensation: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE) ? "Yes" : "No");
10839 if (!realtimepeers && !realtimeusers)
10840 ast_cli(fd, " SIP realtime: Disabled\n" );
10841 else
10842 ast_cli(fd, " SIP realtime: Enabled\n" );
10844 ast_cli(fd, "\nGlobal Signalling Settings:\n");
10845 ast_cli(fd, "---------------------------\n");
10846 ast_cli(fd, " Codecs: ");
10847 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
10848 ast_cli(fd, "%s\n", codec_buf);
10849 ast_cli(fd, " Codec Order: ");
10850 print_codec_to_cli(fd, &default_prefs);
10851 ast_cli(fd, "\n");
10852 ast_cli(fd, " T1 minimum: %d\n", global_t1min);
10853 ast_cli(fd, " Relax DTMF: %s\n", global_relaxdtmf ? "Yes" : "No");
10854 ast_cli(fd, " Compact SIP headers: %s\n", compactheaders ? "Yes" : "No");
10855 ast_cli(fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
10856 ast_cli(fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
10857 ast_cli(fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
10858 ast_cli(fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
10859 ast_cli(fd, " DNS SRV lookup: %s\n", srvlookup ? "Yes" : "No");
10860 ast_cli(fd, " Pedantic SIP support: %s\n", pedanticsipchecking ? "Yes" : "No");
10861 ast_cli(fd, " Reg. min duration %d secs\n", min_expiry);
10862 ast_cli(fd, " Reg. max duration: %d secs\n", max_expiry);
10863 ast_cli(fd, " Reg. default duration: %d secs\n", default_expiry);
10864 ast_cli(fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
10865 ast_cli(fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
10866 ast_cli(fd, " Notify ringing state: %s\n", global_notifyringing ? "Yes" : "No");
10867 ast_cli(fd, " Notify hold state: %s\n", global_notifyhold ? "Yes" : "No");
10868 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(global_allowtransfer));
10869 ast_cli(fd, " Max Call Bitrate: %d kbps\r\n", default_maxcallbitrate);
10870 ast_cli(fd, " Auto-Framing: %s \r\n", global_autoframing ? "Yes" : "No");
10871 ast_cli(fd, "\nDefault Settings:\n");
10872 ast_cli(fd, "-----------------\n");
10873 ast_cli(fd, " Context: %s\n", default_context);
10874 ast_cli(fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
10875 ast_cli(fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
10876 ast_cli(fd, " Qualify: %d\n", default_qualify);
10877 ast_cli(fd, " Use ClientCode: %s\n", ast_test_flag(&global_flags[0], SIP_USECLIENTCODE) ? "Yes" : "No");
10878 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" );
10879 ast_cli(fd, " Language: %s\n", S_OR(default_language, "(Defaults to English)"));
10880 ast_cli(fd, " MOH Interpret: %s\n", default_mohinterpret);
10881 ast_cli(fd, " MOH Suggest: %s\n", default_mohsuggest);
10882 ast_cli(fd, " Voice Mail Extension: %s\n", default_vmexten);
10885 if (realtimepeers || realtimeusers) {
10886 ast_cli(fd, "\nRealtime SIP Settings:\n");
10887 ast_cli(fd, "----------------------\n");
10888 ast_cli(fd, " Realtime Peers: %s\n", realtimepeers ? "Yes" : "No");
10889 ast_cli(fd, " Realtime Users: %s\n", realtimeusers ? "Yes" : "No");
10890 ast_cli(fd, " Cache Friends: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? "Yes" : "No");
10891 ast_cli(fd, " Update: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) ? "Yes" : "No");
10892 ast_cli(fd, " Ignore Reg. Expire: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) ? "Yes" : "No");
10893 ast_cli(fd, " Save sys. name: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME) ? "Yes" : "No");
10894 ast_cli(fd, " Auto Clear: %d\n", global_rtautoclear);
10896 ast_cli(fd, "\n----\n");
10897 return RESULT_SUCCESS;
10900 /*! \brief Show subscription type in string format */
10901 static const char *subscription_type2str(enum subscriptiontype subtype)
10903 int i;
10905 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10906 if (subscription_types[i].type == subtype) {
10907 return subscription_types[i].text;
10910 return subscription_types[0].text;
10913 /*! \brief Find subscription type in array */
10914 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
10916 int i;
10918 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10919 if (subscription_types[i].type == subtype) {
10920 return &subscription_types[i];
10923 return &subscription_types[0];
10926 /*! \brief Show active SIP channels */
10927 static int sip_show_channels(int fd, int argc, char *argv[])
10929 return __sip_show_channels(fd, argc, argv, 0);
10932 /*! \brief Show active SIP subscriptions */
10933 static int sip_show_subscriptions(int fd, int argc, char *argv[])
10935 return __sip_show_channels(fd, argc, argv, 1);
10938 /*! \brief SIP show channels CLI (main function) */
10939 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions)
10941 #define FORMAT3 "%-15.15s %-10.10s %-11.11s %-15.15s %-13.13s %-15.15s %-10.10s\n"
10942 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-15.15s %-7.7s %-15.15s\n"
10943 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s\n"
10944 struct sip_pvt *cur;
10945 int numchans = 0;
10946 char *referstatus = NULL;
10948 if (argc != 3)
10949 return RESULT_SHOWUSAGE;
10950 ast_mutex_lock(&iflock);
10951 cur = iflist;
10952 if (!subscriptions)
10953 ast_cli(fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Seq (Tx/Rx)", "Format", "Hold", "Last Message");
10954 else
10955 ast_cli(fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox");
10956 for (; cur; cur = cur->next) {
10957 referstatus = "";
10958 if (cur->refer) { /* SIP transfer in progress */
10959 referstatus = referstatus2str(cur->refer->status);
10961 if (cur->subscribed == NONE && !subscriptions) {
10962 char formatbuf[SIPBUFSIZE/2];
10963 ast_cli(fd, FORMAT, ast_inet_ntoa(cur->sa.sin_addr),
10964 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10965 cur->callid,
10966 cur->ocseq, cur->icseq,
10967 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
10968 ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD) ? "Yes" : "No",
10969 ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY) ? "(d)" : "",
10970 cur->lastmsg ,
10971 referstatus
10973 numchans++;
10975 if (cur->subscribed != NONE && subscriptions) {
10976 ast_cli(fd, FORMAT3, ast_inet_ntoa(cur->sa.sin_addr),
10977 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10978 cur->callid,
10979 /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
10980 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
10981 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
10982 subscription_type2str(cur->subscribed),
10983 cur->subscribed == MWI_NOTIFICATION ? (cur->relatedpeer ? cur->relatedpeer->mailbox : "<none>") : "<none>"
10985 numchans++;
10988 ast_mutex_unlock(&iflock);
10989 if (!subscriptions)
10990 ast_cli(fd, "%d active SIP channel%s\n", numchans, (numchans != 1) ? "s" : "");
10991 else
10992 ast_cli(fd, "%d active SIP subscription%s\n", numchans, (numchans != 1) ? "s" : "");
10993 return RESULT_SUCCESS;
10994 #undef FORMAT
10995 #undef FORMAT2
10996 #undef FORMAT3
10999 /*! \brief Support routine for 'sip show channel' CLI */
11000 static char *complete_sipch(const char *line, const char *word, int pos, int state)
11002 int which=0;
11003 struct sip_pvt *cur;
11004 char *c = NULL;
11005 int wordlen = strlen(word);
11007 if (pos != 3) {
11008 return NULL;
11011 ast_mutex_lock(&iflock);
11012 for (cur = iflist; cur; cur = cur->next) {
11013 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
11014 c = ast_strdup(cur->callid);
11015 break;
11018 ast_mutex_unlock(&iflock);
11019 return c;
11022 /*! \brief Do completion on peer name */
11023 static char *complete_sip_peer(const char *word, int state, int flags2)
11025 char *result = NULL;
11026 int wordlen = strlen(word);
11027 int which = 0;
11029 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !result, do {
11030 /* locking of the object is not required because only the name and flags are being compared */
11031 if (!strncasecmp(word, iterator->name, wordlen) &&
11032 (!flags2 || ast_test_flag(&iterator->flags[1], flags2)) &&
11033 ++which > state)
11034 result = ast_strdup(iterator->name);
11035 } while(0) );
11036 return result;
11039 /*! \brief Support routine for 'sip show peer' CLI */
11040 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
11042 if (pos == 3)
11043 return complete_sip_peer(word, state, 0);
11045 return NULL;
11048 /*! \brief Support routine for 'sip debug peer' CLI */
11049 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state)
11051 if (pos == 3)
11052 return complete_sip_peer(word, state, 0);
11054 return NULL;
11057 /*! \brief Do completion on user name */
11058 static char *complete_sip_user(const char *word, int state, int flags2)
11060 char *result = NULL;
11061 int wordlen = strlen(word);
11062 int which = 0;
11064 ASTOBJ_CONTAINER_TRAVERSE(&userl, !result, do {
11065 /* locking of the object is not required because only the name and flags are being compared */
11066 if (!strncasecmp(word, iterator->name, wordlen)) {
11067 if (flags2 && !ast_test_flag(&iterator->flags[1], flags2))
11068 continue;
11069 if (++which > state) {
11070 result = ast_strdup(iterator->name);
11073 } while(0) );
11074 return result;
11077 /*! \brief Support routine for 'sip show user' CLI */
11078 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
11080 if (pos == 3)
11081 return complete_sip_user(word, state, 0);
11083 return NULL;
11086 /*! \brief Support routine for 'sip notify' CLI */
11087 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
11089 char *c = NULL;
11091 if (pos == 2) {
11092 int which = 0;
11093 char *cat = NULL;
11094 int wordlen = strlen(word);
11096 /* do completion for notify type */
11098 if (!notify_types)
11099 return NULL;
11101 while ( (cat = ast_category_browse(notify_types, cat)) ) {
11102 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
11103 c = ast_strdup(cat);
11104 break;
11107 return c;
11110 if (pos > 2)
11111 return complete_sip_peer(word, state, 0);
11113 return NULL;
11116 /*! \brief Support routine for 'sip prune realtime peer' CLI */
11117 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state)
11119 if (pos == 4)
11120 return complete_sip_peer(word, state, SIP_PAGE2_RTCACHEFRIENDS);
11121 return NULL;
11124 /*! \brief Support routine for 'sip prune realtime user' CLI */
11125 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state)
11127 if (pos == 4)
11128 return complete_sip_user(word, state, SIP_PAGE2_RTCACHEFRIENDS);
11130 return NULL;
11133 /*! \brief Show details of one active dialog */
11134 static int sip_show_channel(int fd, int argc, char *argv[])
11136 struct sip_pvt *cur;
11137 size_t len;
11138 int found = 0;
11140 if (argc != 4)
11141 return RESULT_SHOWUSAGE;
11142 len = strlen(argv[3]);
11143 ast_mutex_lock(&iflock);
11144 for (cur = iflist; cur; cur = cur->next) {
11145 if (!strncasecmp(cur->callid, argv[3], len)) {
11146 char formatbuf[SIPBUFSIZE/2];
11147 ast_cli(fd,"\n");
11148 if (cur->subscribed != NONE)
11149 ast_cli(fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
11150 else
11151 ast_cli(fd, " * SIP Call\n");
11152 ast_cli(fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
11153 ast_cli(fd, " Call-ID: %s\n", cur->callid);
11154 ast_cli(fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
11155 ast_cli(fd, " Our Codec Capability: %d\n", cur->capability);
11156 ast_cli(fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
11157 ast_cli(fd, " Their Codec Capability: %d\n", cur->peercapability);
11158 ast_cli(fd, " Joint Codec Capability: %d\n", cur->jointcapability);
11159 ast_cli(fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
11160 ast_cli(fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
11161 ast_cli(fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
11162 ast_cli(fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
11163 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
11164 ast_cli(fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
11165 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)" );
11166 ast_cli(fd, " Our Tag: %s\n", cur->tag);
11167 ast_cli(fd, " Their Tag: %s\n", cur->theirtag);
11168 ast_cli(fd, " SIP User agent: %s\n", cur->useragent);
11169 if (!ast_strlen_zero(cur->username))
11170 ast_cli(fd, " Username: %s\n", cur->username);
11171 if (!ast_strlen_zero(cur->peername))
11172 ast_cli(fd, " Peername: %s\n", cur->peername);
11173 if (!ast_strlen_zero(cur->uri))
11174 ast_cli(fd, " Original uri: %s\n", cur->uri);
11175 if (!ast_strlen_zero(cur->cid_num))
11176 ast_cli(fd, " Caller-ID: %s\n", cur->cid_num);
11177 ast_cli(fd, " Need Destroy: %d\n", ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY));
11178 ast_cli(fd, " Last Message: %s\n", cur->lastmsg);
11179 ast_cli(fd, " Promiscuous Redir: %s\n", ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
11180 ast_cli(fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
11181 ast_cli(fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
11182 ast_cli(fd, " SIP Options: ");
11183 if (cur->sipoptions) {
11184 int x;
11185 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
11186 if (cur->sipoptions & sip_options[x].id)
11187 ast_cli(fd, "%s ", sip_options[x].text);
11189 } else
11190 ast_cli(fd, "(none)\n");
11191 ast_cli(fd, "\n\n");
11192 found++;
11195 ast_mutex_unlock(&iflock);
11196 if (!found)
11197 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
11198 return RESULT_SUCCESS;
11201 /*! \brief Show history details of one dialog */
11202 static int sip_show_history(int fd, int argc, char *argv[])
11204 struct sip_pvt *cur;
11205 size_t len;
11206 int found = 0;
11208 if (argc != 4)
11209 return RESULT_SHOWUSAGE;
11210 if (!recordhistory)
11211 ast_cli(fd, "\n***Note: History recording is currently DISABLED. Use 'sip history' to ENABLE.\n");
11212 len = strlen(argv[3]);
11213 ast_mutex_lock(&iflock);
11214 for (cur = iflist; cur; cur = cur->next) {
11215 if (!strncasecmp(cur->callid, argv[3], len)) {
11216 struct sip_history *hist;
11217 int x = 0;
11219 ast_cli(fd,"\n");
11220 if (cur->subscribed != NONE)
11221 ast_cli(fd, " * Subscription\n");
11222 else
11223 ast_cli(fd, " * SIP Call\n");
11224 if (cur->history)
11225 AST_LIST_TRAVERSE(cur->history, hist, list)
11226 ast_cli(fd, "%d. %s\n", ++x, hist->event);
11227 if (x == 0)
11228 ast_cli(fd, "Call '%s' has no history\n", cur->callid);
11229 found++;
11232 ast_mutex_unlock(&iflock);
11233 if (!found)
11234 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
11235 return RESULT_SUCCESS;
11238 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
11239 static void sip_dump_history(struct sip_pvt *dialog)
11241 int x = 0;
11242 struct sip_history *hist;
11243 static int errmsg = 0;
11245 if (!dialog)
11246 return;
11248 if (!option_debug && !sipdebug) {
11249 if (!errmsg) {
11250 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
11251 errmsg = 1;
11253 return;
11256 ast_log(LOG_DEBUG, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
11257 if (dialog->subscribed)
11258 ast_log(LOG_DEBUG, " * Subscription\n");
11259 else
11260 ast_log(LOG_DEBUG, " * SIP Call\n");
11261 if (dialog->history)
11262 AST_LIST_TRAVERSE(dialog->history, hist, list)
11263 ast_log(LOG_DEBUG, " %-3.3d. %s\n", ++x, hist->event);
11264 if (!x)
11265 ast_log(LOG_DEBUG, "Call '%s' has no history\n", dialog->callid);
11266 ast_log(LOG_DEBUG, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
11270 /*! \brief Receive SIP INFO Message
11271 \note Doesn't read the duration of the DTMF signal */
11272 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
11274 char buf[1024];
11275 unsigned int event;
11276 const char *c = get_header(req, "Content-Type");
11278 /* Need to check the media/type */
11279 if (!strcasecmp(c, "application/dtmf-relay") ||
11280 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
11281 unsigned int duration = 0;
11283 /* Try getting the "signal=" part */
11284 if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
11285 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
11286 transmit_response(p, "200 OK", req); /* Should return error */
11287 return;
11288 } else {
11289 ast_copy_string(buf, c, sizeof(buf));
11292 if (!ast_strlen_zero((c = get_body(req, "Duration"))))
11293 duration = atoi(c);
11294 if (!duration)
11295 duration = 100; /* 100 ms */
11297 if (!p->owner) { /* not a PBX call */
11298 transmit_response(p, "481 Call leg/transaction does not exist", req);
11299 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11300 return;
11303 if (ast_strlen_zero(buf)) {
11304 transmit_response(p, "200 OK", req);
11305 return;
11308 if (buf[0] == '*')
11309 event = 10;
11310 else if (buf[0] == '#')
11311 event = 11;
11312 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
11313 event = 12 + buf[0] - 'A';
11314 else
11315 event = atoi(buf);
11316 if (event == 16) {
11317 /* send a FLASH event */
11318 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
11319 ast_queue_frame(p->owner, &f);
11320 if (sipdebug)
11321 ast_verbose("* DTMF-relay event received: FLASH\n");
11322 } else {
11323 /* send a DTMF event */
11324 struct ast_frame f = { AST_FRAME_DTMF, };
11325 if (event < 10) {
11326 f.subclass = '0' + event;
11327 } else if (event < 11) {
11328 f.subclass = '*';
11329 } else if (event < 12) {
11330 f.subclass = '#';
11331 } else if (event < 16) {
11332 f.subclass = 'A' + (event - 12);
11334 f.len = duration;
11335 ast_queue_frame(p->owner, &f);
11336 if (sipdebug)
11337 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
11339 transmit_response(p, "200 OK", req);
11340 return;
11341 } else if (!strcasecmp(c, "application/media_control+xml")) {
11342 /* Eh, we'll just assume it's a fast picture update for now */
11343 if (p->owner)
11344 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
11345 transmit_response(p, "200 OK", req);
11346 return;
11347 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
11348 /* Client code (from SNOM phone) */
11349 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
11350 if (p->owner && p->owner->cdr)
11351 ast_cdr_setuserfield(p->owner, c);
11352 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
11353 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
11354 transmit_response(p, "200 OK", req);
11355 } else {
11356 transmit_response(p, "403 Unauthorized", req);
11358 return;
11359 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
11360 /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
11361 transmit_response(p, "200 OK", req);
11362 return;
11365 /* Other type of INFO message, not really understood by Asterisk */
11366 /* if (get_msg_text(buf, sizeof(buf), req)) { */
11368 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
11369 transmit_response(p, "415 Unsupported media type", req);
11370 return;
11373 /*! \brief Enable SIP Debugging in CLI */
11374 static int sip_do_debug_ip(int fd, int argc, char *argv[])
11376 struct hostent *hp;
11377 struct ast_hostent ahp;
11378 int port = 0;
11379 char *p, *arg;
11381 /* sip set debug ip <ip> */
11382 if (argc != 5)
11383 return RESULT_SHOWUSAGE;
11384 p = arg = argv[4];
11385 strsep(&p, ":");
11386 if (p)
11387 port = atoi(p);
11388 hp = ast_gethostbyname(arg, &ahp);
11389 if (hp == NULL)
11390 return RESULT_SHOWUSAGE;
11392 debugaddr.sin_family = AF_INET;
11393 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
11394 debugaddr.sin_port = htons(port);
11395 if (port == 0)
11396 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
11397 else
11398 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
11400 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11402 return RESULT_SUCCESS;
11405 /*! \brief sip_do_debug_peer: Turn on SIP debugging with peer mask */
11406 static int sip_do_debug_peer(int fd, int argc, char *argv[])
11408 struct sip_peer *peer;
11409 if (argc != 5)
11410 return RESULT_SHOWUSAGE;
11411 peer = find_peer(argv[4], NULL, 1, 0);
11412 if (peer) {
11413 if (peer->addr.sin_addr.s_addr) {
11414 debugaddr.sin_family = AF_INET;
11415 debugaddr.sin_addr = peer->addr.sin_addr;
11416 debugaddr.sin_port = peer->addr.sin_port;
11417 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
11418 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11419 } else
11420 ast_cli(fd, "Unable to get IP address of peer '%s'\n", argv[4]);
11421 ASTOBJ_UNREF(peer,sip_destroy_peer);
11422 } else
11423 ast_cli(fd, "No such peer '%s'\n", argv[4]);
11424 return RESULT_SUCCESS;
11427 /*! \brief Turn on SIP debugging (CLI command) */
11428 static int sip_do_debug(int fd, int argc, char *argv[])
11430 int oldsipdebug = sipdebug_console;
11431 if (argc != 3) {
11432 if (argc != 5)
11433 return RESULT_SHOWUSAGE;
11434 else if (strcmp(argv[3], "ip") == 0)
11435 return sip_do_debug_ip(fd, argc, argv);
11436 else if (strcmp(argv[3], "peer") == 0)
11437 return sip_do_debug_peer(fd, argc, argv);
11438 else
11439 return RESULT_SHOWUSAGE;
11441 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11442 memset(&debugaddr, 0, sizeof(debugaddr));
11443 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
11444 return RESULT_SUCCESS;
11447 static int sip_do_debug_deprecated(int fd, int argc, char *argv[])
11449 int oldsipdebug = sipdebug_console;
11450 char *newargv[6] = { "sip", "set", "debug", NULL };
11451 if (argc != 2) {
11452 if (argc != 4)
11453 return RESULT_SHOWUSAGE;
11454 else if (strcmp(argv[2], "ip") == 0) {
11455 newargv[3] = argv[2];
11456 newargv[4] = argv[3];
11457 return sip_do_debug_ip(fd, argc + 1, newargv);
11458 } else if (strcmp(argv[2], "peer") == 0) {
11459 newargv[3] = argv[2];
11460 newargv[4] = argv[3];
11461 return sip_do_debug_peer(fd, argc + 1, newargv);
11462 } else
11463 return RESULT_SHOWUSAGE;
11465 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11466 memset(&debugaddr, 0, sizeof(debugaddr));
11467 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
11468 return RESULT_SUCCESS;
11471 /*! \brief Cli command to send SIP notify to peer */
11472 static int sip_notify(int fd, int argc, char *argv[])
11474 struct ast_variable *varlist;
11475 int i;
11477 if (argc < 4)
11478 return RESULT_SHOWUSAGE;
11480 if (!notify_types) {
11481 ast_cli(fd, "No %s file found, or no types listed there\n", notify_config);
11482 return RESULT_FAILURE;
11485 varlist = ast_variable_browse(notify_types, argv[2]);
11487 if (!varlist) {
11488 ast_cli(fd, "Unable to find notify type '%s'\n", argv[2]);
11489 return RESULT_FAILURE;
11492 for (i = 3; i < argc; i++) {
11493 struct sip_pvt *p;
11494 struct sip_request req;
11495 struct ast_variable *var;
11497 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY))) {
11498 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
11499 return RESULT_FAILURE;
11502 if (create_addr(p, argv[i])) {
11503 /* Maybe they're not registered, etc. */
11504 sip_destroy(p);
11505 ast_cli(fd, "Could not create address for '%s'\n", argv[i]);
11506 continue;
11509 initreqprep(&req, p, SIP_NOTIFY);
11511 for (var = varlist; var; var = var->next)
11512 add_header(&req, var->name, ast_unescape_semicolon(var->value));
11514 /* Recalculate our side, and recalculate Call ID */
11515 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
11516 p->ourip = __ourip;
11517 build_via(p);
11518 build_callid_pvt(p);
11519 ast_cli(fd, "Sending NOTIFY of type '%s' to '%s'\n", argv[2], argv[i]);
11520 transmit_sip_request(p, &req);
11521 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11524 return RESULT_SUCCESS;
11527 /*! \brief Disable SIP Debugging in CLI */
11528 static int sip_no_debug(int fd, int argc, char *argv[])
11530 if (argc != 4)
11531 return RESULT_SHOWUSAGE;
11532 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11533 ast_cli(fd, "SIP Debugging Disabled\n");
11534 return RESULT_SUCCESS;
11537 static int sip_no_debug_deprecated(int fd, int argc, char *argv[])
11539 if (argc != 3)
11540 return RESULT_SHOWUSAGE;
11541 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11542 ast_cli(fd, "SIP Debugging Disabled\n");
11543 return RESULT_SUCCESS;
11546 /*! \brief Enable SIP History logging (CLI) */
11547 static int sip_do_history(int fd, int argc, char *argv[])
11549 if (argc != 2) {
11550 return RESULT_SHOWUSAGE;
11552 recordhistory = TRUE;
11553 ast_cli(fd, "SIP History Recording Enabled (use 'sip show history')\n");
11554 return RESULT_SUCCESS;
11557 /*! \brief Disable SIP History logging (CLI) */
11558 static int sip_no_history(int fd, int argc, char *argv[])
11560 if (argc != 3) {
11561 return RESULT_SHOWUSAGE;
11563 recordhistory = FALSE;
11564 ast_cli(fd, "SIP History Recording Disabled\n");
11565 return RESULT_SUCCESS;
11568 /*! \brief Authenticate for outbound registration */
11569 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader)
11571 char digest[1024];
11572 p->authtries++;
11573 memset(digest,0,sizeof(digest));
11574 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
11575 /* There's nothing to use for authentication */
11576 /* No digest challenge in request */
11577 if (sip_debug_test_pvt(p) && p->registry)
11578 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
11579 /* No old challenge */
11580 return -1;
11582 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
11583 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
11584 if (sip_debug_test_pvt(p) && p->registry)
11585 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
11586 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
11589 /*! \brief Add authentication on outbound SIP packet */
11590 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init)
11592 char digest[1024];
11594 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
11595 return -2;
11597 p->authtries++;
11598 if (option_debug > 1)
11599 ast_log(LOG_DEBUG, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
11600 memset(digest, 0, sizeof(digest));
11601 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
11602 /* No way to authenticate */
11603 return -1;
11605 /* Now we have a reply digest */
11606 p->options->auth = digest;
11607 p->options->authheader = respheader;
11608 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
11611 /*! \brief reply to authentication for outbound registrations
11612 \return Returns -1 if we have no auth
11613 \note This is used for register= servers in sip.conf, SIP proxies we register
11614 with for receiving calls from. */
11615 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
11617 char tmp[512];
11618 char *c;
11619 char oldnonce[256];
11621 /* table of recognised keywords, and places where they should be copied */
11622 const struct x {
11623 const char *key;
11624 int field_index;
11625 } *i, keys[] = {
11626 { "realm=", ast_string_field_index(p, realm) },
11627 { "nonce=", ast_string_field_index(p, nonce) },
11628 { "opaque=", ast_string_field_index(p, opaque) },
11629 { "qop=", ast_string_field_index(p, qop) },
11630 { "domain=", ast_string_field_index(p, domain) },
11631 { NULL, 0 },
11634 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
11635 if (ast_strlen_zero(tmp))
11636 return -1;
11637 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
11638 ast_log(LOG_WARNING, "missing Digest.\n");
11639 return -1;
11641 c = tmp + strlen("Digest ");
11642 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
11643 while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
11644 for (i = keys; i->key != NULL; i++) {
11645 char *src, *separator;
11646 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
11647 continue;
11648 /* Found. Skip keyword, take text in quotes or up to the separator. */
11649 c += strlen(i->key);
11650 if (*c == '"') {
11651 src = ++c;
11652 separator = "\"";
11653 } else {
11654 src = c;
11655 separator = ",";
11657 strsep(&c, separator); /* clear separator and move ptr */
11658 ast_string_field_index_set(p, i->field_index, src);
11659 break;
11661 if (i->key == NULL) /* not found, try ',' */
11662 strsep(&c, ",");
11664 /* Reset nonce count */
11665 if (strcmp(p->nonce, oldnonce))
11666 p->noncecount = 0;
11668 /* Save auth data for following registrations */
11669 if (p->registry) {
11670 struct sip_registry *r = p->registry;
11672 if (strcmp(r->nonce, p->nonce)) {
11673 ast_string_field_set(r, realm, p->realm);
11674 ast_string_field_set(r, nonce, p->nonce);
11675 ast_string_field_set(r, domain, p->domain);
11676 ast_string_field_set(r, opaque, p->opaque);
11677 ast_string_field_set(r, qop, p->qop);
11678 r->noncecount = 0;
11681 return build_reply_digest(p, sipmethod, digest, digest_len);
11684 /*! \brief Build reply digest
11685 \return Returns -1 if we have no auth
11686 \note Build digest challenge for authentication of peers (for registration)
11687 and users (for calls). Also used for authentication of CANCEL and BYE
11689 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
11691 char a1[256];
11692 char a2[256];
11693 char a1_hash[256];
11694 char a2_hash[256];
11695 char resp[256];
11696 char resp_hash[256];
11697 char uri[256];
11698 char opaque[256] = "";
11699 char cnonce[80];
11700 const char *username;
11701 const char *secret;
11702 const char *md5secret;
11703 struct sip_auth *auth = NULL; /* Realm authentication */
11705 if (!ast_strlen_zero(p->domain))
11706 ast_copy_string(uri, p->domain, sizeof(uri));
11707 else if (!ast_strlen_zero(p->uri))
11708 ast_copy_string(uri, p->uri, sizeof(uri));
11709 else
11710 snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, ast_inet_ntoa(p->sa.sin_addr));
11712 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
11714 /* Check if we have separate auth credentials */
11715 if(!(auth = find_realm_authentication(p->peerauth, p->realm))) /* Start with peer list */
11716 auth = find_realm_authentication(authl, p->realm); /* If not, global list */
11718 if (auth) {
11719 ast_log(LOG_DEBUG, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
11720 username = auth->username;
11721 secret = auth->secret;
11722 md5secret = auth->md5secret;
11723 if (sipdebug)
11724 ast_log(LOG_DEBUG,"Using realm %s authentication for call %s\n", p->realm, p->callid);
11725 } else {
11726 /* No authentication, use peer or register= config */
11727 username = p->authname;
11728 secret = p->peersecret;
11729 md5secret = p->peermd5secret;
11731 if (ast_strlen_zero(username)) /* We have no authentication */
11732 return -1;
11734 /* Calculate SIP digest response */
11735 snprintf(a1,sizeof(a1),"%s:%s:%s", username, p->realm, secret);
11736 snprintf(a2,sizeof(a2),"%s:%s", sip_methods[method].text, uri);
11737 if (!ast_strlen_zero(md5secret))
11738 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
11739 else
11740 ast_md5_hash(a1_hash,a1);
11741 ast_md5_hash(a2_hash,a2);
11743 p->noncecount++;
11744 if (!ast_strlen_zero(p->qop))
11745 snprintf(resp,sizeof(resp),"%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
11746 else
11747 snprintf(resp,sizeof(resp),"%s:%s:%s", a1_hash, p->nonce, a2_hash);
11748 ast_md5_hash(resp_hash, resp);
11750 /* only include the opaque string if it's set */
11751 if (!ast_strlen_zero(p->opaque)) {
11752 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
11755 /* XXX We hard code our qop to "auth" for now. XXX */
11756 if (!ast_strlen_zero(p->qop))
11757 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);
11758 else
11759 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);
11761 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
11763 return 0;
11766 static char show_domains_usage[] =
11767 "Usage: sip show domains\n"
11768 " Lists all configured SIP local domains.\n"
11769 " Asterisk only responds to SIP messages to local domains.\n";
11771 static char notify_usage[] =
11772 "Usage: sip notify <type> <peer> [<peer>...]\n"
11773 " Send a NOTIFY message to a SIP peer or peers\n"
11774 " Message types are defined in sip_notify.conf\n";
11776 static char show_users_usage[] =
11777 "Usage: sip show users [like <pattern>]\n"
11778 " Lists all known SIP users.\n"
11779 " Optional regular expression pattern is used to filter the user list.\n";
11781 static char show_user_usage[] =
11782 "Usage: sip show user <name> [load]\n"
11783 " Shows all details on one SIP user and the current status.\n"
11784 " Option \"load\" forces lookup of peer in realtime storage.\n";
11786 static char show_inuse_usage[] =
11787 "Usage: sip show inuse [all]\n"
11788 " List all SIP users and peers usage counters and limits.\n"
11789 " Add option \"all\" to show all devices, not only those with a limit.\n";
11791 static char show_channels_usage[] =
11792 "Usage: sip show channels\n"
11793 " Lists all currently active SIP channels.\n";
11795 static char show_channel_usage[] =
11796 "Usage: sip show channel <channel>\n"
11797 " Provides detailed status on a given SIP channel.\n";
11799 static char show_history_usage[] =
11800 "Usage: sip show history <channel>\n"
11801 " Provides detailed dialog history on a given SIP channel.\n";
11803 static char show_peers_usage[] =
11804 "Usage: sip show peers [like <pattern>]\n"
11805 " Lists all known SIP peers.\n"
11806 " Optional regular expression pattern is used to filter the peer list.\n";
11808 static char show_peer_usage[] =
11809 "Usage: sip show peer <name> [load]\n"
11810 " Shows all details on one SIP peer and the current status.\n"
11811 " Option \"load\" forces lookup of peer in realtime storage.\n";
11813 static char prune_realtime_usage[] =
11814 "Usage: sip prune realtime [peer|user] [<name>|all|like <pattern>]\n"
11815 " Prunes object(s) from the cache.\n"
11816 " Optional regular expression pattern is used to filter the objects.\n";
11818 static char show_reg_usage[] =
11819 "Usage: sip show registry\n"
11820 " Lists all registration requests and status.\n";
11822 static char debug_usage[] =
11823 "Usage: sip set debug\n"
11824 " Enables dumping of SIP packets for debugging purposes\n\n"
11825 " sip set debug ip <host[:PORT]>\n"
11826 " Enables dumping of SIP packets to and from host.\n\n"
11827 " sip set debug peer <peername>\n"
11828 " Enables dumping of SIP packets to and from host.\n"
11829 " Require peer to be registered.\n";
11831 static char no_debug_usage[] =
11832 "Usage: sip set debug off\n"
11833 " Disables dumping of SIP packets for debugging purposes\n";
11835 static char no_history_usage[] =
11836 "Usage: sip history off\n"
11837 " Disables recording of SIP dialog history for debugging purposes\n";
11839 static char history_usage[] =
11840 "Usage: sip history\n"
11841 " Enables recording of SIP dialog history for debugging purposes.\n"
11842 "Use 'sip show history' to view the history of a call number.\n";
11844 static char sip_reload_usage[] =
11845 "Usage: sip reload\n"
11846 " Reloads SIP configuration from sip.conf\n";
11848 static char show_subscriptions_usage[] =
11849 "Usage: sip show subscriptions\n"
11850 " Lists active SIP subscriptions for extension states\n";
11852 static char show_objects_usage[] =
11853 "Usage: sip show objects\n"
11854 " Lists status of known SIP objects\n";
11856 static char show_settings_usage[] =
11857 "Usage: sip show settings\n"
11858 " Provides detailed list of the configuration of the SIP channel.\n";
11860 /*! \brief Read SIP header (dialplan function) */
11861 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len)
11863 struct sip_pvt *p;
11864 const char *content = NULL;
11865 AST_DECLARE_APP_ARGS(args,
11866 AST_APP_ARG(header);
11867 AST_APP_ARG(number);
11869 int i, number, start = 0;
11871 if (ast_strlen_zero(data)) {
11872 ast_log(LOG_WARNING, "This function requires a header name.\n");
11873 return -1;
11876 ast_channel_lock(chan);
11877 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
11878 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
11879 ast_channel_unlock(chan);
11880 return -1;
11883 AST_STANDARD_APP_ARGS(args, data);
11884 if (!args.number) {
11885 number = 1;
11886 } else {
11887 sscanf(args.number, "%d", &number);
11888 if (number < 1)
11889 number = 1;
11892 p = chan->tech_pvt;
11894 /* If there is no private structure, this channel is no longer alive */
11895 if (!p) {
11896 ast_channel_unlock(chan);
11897 return -1;
11900 for (i = 0; i < number; i++)
11901 content = __get_header(&p->initreq, args.header, &start);
11903 if (ast_strlen_zero(content)) {
11904 ast_channel_unlock(chan);
11905 return -1;
11908 ast_copy_string(buf, content, len);
11909 ast_channel_unlock(chan);
11911 return 0;
11914 static struct ast_custom_function sip_header_function = {
11915 .name = "SIP_HEADER",
11916 .synopsis = "Gets the specified SIP header",
11917 .syntax = "SIP_HEADER(<name>[,<number>])",
11918 .desc = "Since there are several headers (such as Via) which can occur multiple\n"
11919 "times, SIP_HEADER takes an optional second argument to specify which header with\n"
11920 "that name to retrieve. Headers start at offset 1.\n",
11921 .read = func_header_read,
11924 /*! \brief Dial plan function to check if domain is local */
11925 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11927 if (ast_strlen_zero(data)) {
11928 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
11929 return -1;
11931 if (check_sip_domain(data, NULL, 0))
11932 ast_copy_string(buf, data, len);
11933 else
11934 buf[0] = '\0';
11935 return 0;
11938 static struct ast_custom_function checksipdomain_function = {
11939 .name = "CHECKSIPDOMAIN",
11940 .synopsis = "Checks if domain is a local domain",
11941 .syntax = "CHECKSIPDOMAIN(<domain|IP>)",
11942 .read = func_check_sipdomain,
11943 .desc = "This function checks if the domain in the argument is configured\n"
11944 "as a local SIP domain that this Asterisk server is configured to handle.\n"
11945 "Returns the domain name if it is locally handled, otherwise an empty string.\n"
11946 "Check the domain= configuration in sip.conf\n",
11949 /*! \brief ${SIPPEER()} Dialplan function - reads peer data */
11950 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11952 struct sip_peer *peer;
11953 char *colname;
11955 if ((colname = strchr(data, ':'))) /*! \todo Will be deprecated after 1.4 */
11956 *colname++ = '\0';
11957 else if ((colname = strchr(data, '|')))
11958 *colname++ = '\0';
11959 else
11960 colname = "ip";
11962 if (!(peer = find_peer(data, NULL, 1, 0)))
11963 return -1;
11965 if (!strcasecmp(colname, "ip")) {
11966 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
11967 } else if (!strcasecmp(colname, "status")) {
11968 peer_status(peer, buf, len);
11969 } else if (!strcasecmp(colname, "language")) {
11970 ast_copy_string(buf, peer->language, len);
11971 } else if (!strcasecmp(colname, "regexten")) {
11972 ast_copy_string(buf, peer->regexten, len);
11973 } else if (!strcasecmp(colname, "limit")) {
11974 snprintf(buf, len, "%d", peer->call_limit);
11975 } else if (!strcasecmp(colname, "curcalls")) {
11976 snprintf(buf, len, "%d", peer->inUse);
11977 } else if (!strcasecmp(colname, "accountcode")) {
11978 ast_copy_string(buf, peer->accountcode, len);
11979 } else if (!strcasecmp(colname, "useragent")) {
11980 ast_copy_string(buf, peer->useragent, len);
11981 } else if (!strcasecmp(colname, "mailbox")) {
11982 ast_copy_string(buf, peer->mailbox, len);
11983 } else if (!strcasecmp(colname, "context")) {
11984 ast_copy_string(buf, peer->context, len);
11985 } else if (!strcasecmp(colname, "expire")) {
11986 snprintf(buf, len, "%d", peer->expire);
11987 } else if (!strcasecmp(colname, "dynamic")) {
11988 ast_copy_string(buf, (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no"), len);
11989 } else if (!strcasecmp(colname, "callerid_name")) {
11990 ast_copy_string(buf, peer->cid_name, len);
11991 } else if (!strcasecmp(colname, "callerid_num")) {
11992 ast_copy_string(buf, peer->cid_num, len);
11993 } else if (!strcasecmp(colname, "codecs")) {
11994 ast_getformatname_multiple(buf, len -1, peer->capability);
11995 } else if (!strncasecmp(colname, "codec[", 6)) {
11996 char *codecnum;
11997 int index = 0, codec = 0;
11999 codecnum = colname + 6; /* move past the '[' */
12000 codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
12001 index = atoi(codecnum);
12002 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
12003 ast_copy_string(buf, ast_getformatname(codec), len);
12004 } else {
12005 buf[0] = '\0';
12007 } else {
12008 buf[0] = '\0';
12011 ASTOBJ_UNREF(peer, sip_destroy_peer);
12013 return 0;
12016 /*! \brief Structure to declare a dialplan function: SIPPEER */
12017 struct ast_custom_function sippeer_function = {
12018 .name = "SIPPEER",
12019 .synopsis = "Gets SIP peer information",
12020 .syntax = "SIPPEER(<peername>[|item])",
12021 .read = function_sippeer,
12022 .desc = "Valid items are:\n"
12023 "- ip (default) The IP address.\n"
12024 "- mailbox The configured mailbox.\n"
12025 "- context The configured context.\n"
12026 "- expire The epoch time of the next expire.\n"
12027 "- dynamic Is it dynamic? (yes/no).\n"
12028 "- callerid_name The configured Caller ID name.\n"
12029 "- callerid_num The configured Caller ID number.\n"
12030 "- codecs The configured codecs.\n"
12031 "- status Status (if qualify=yes).\n"
12032 "- regexten Registration extension\n"
12033 "- limit Call limit (call-limit)\n"
12034 "- curcalls Current amount of calls \n"
12035 " Only available if call-limit is set\n"
12036 "- language Default language for peer\n"
12037 "- accountcode Account code for this peer\n"
12038 "- useragent Current user agent id for peer\n"
12039 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
12040 "\n"
12043 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
12044 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
12046 struct sip_pvt *p;
12048 *buf = 0;
12050 if (!data) {
12051 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
12052 return -1;
12055 ast_channel_lock(chan);
12056 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
12057 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
12058 ast_channel_unlock(chan);
12059 return -1;
12062 p = chan->tech_pvt;
12064 /* If there is no private structure, this channel is no longer alive */
12065 if (!p) {
12066 ast_channel_unlock(chan);
12067 return -1;
12070 if (!strcasecmp(data, "peerip")) {
12071 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
12072 } else if (!strcasecmp(data, "recvip")) {
12073 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
12074 } else if (!strcasecmp(data, "from")) {
12075 ast_copy_string(buf, p->from, len);
12076 } else if (!strcasecmp(data, "uri")) {
12077 ast_copy_string(buf, p->uri, len);
12078 } else if (!strcasecmp(data, "useragent")) {
12079 ast_copy_string(buf, p->useragent, len);
12080 } else if (!strcasecmp(data, "peername")) {
12081 ast_copy_string(buf, p->peername, len);
12082 } else if (!strcasecmp(data, "t38passthrough")) {
12083 if (p->t38.state == T38_DISABLED)
12084 ast_copy_string(buf, "0", sizeof("0"));
12085 else /* T38 is offered or enabled in this call */
12086 ast_copy_string(buf, "1", sizeof("1"));
12087 } else {
12088 ast_channel_unlock(chan);
12089 return -1;
12091 ast_channel_unlock(chan);
12093 return 0;
12096 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
12097 static struct ast_custom_function sipchaninfo_function = {
12098 .name = "SIPCHANINFO",
12099 .synopsis = "Gets the specified SIP parameter from the current channel",
12100 .syntax = "SIPCHANINFO(item)",
12101 .read = function_sipchaninfo_read,
12102 .desc = "Valid items are:\n"
12103 "- peerip The IP address of the peer.\n"
12104 "- recvip The source IP address of the peer.\n"
12105 "- from The URI from the From: header.\n"
12106 "- uri The URI from the Contact: header.\n"
12107 "- useragent The useragent.\n"
12108 "- peername The name of the peer.\n"
12109 "- t38passthrough 1 if T38 is offered or enabled in this channel, otherwise 0\n"
12112 /*! \brief Parse 302 Moved temporalily response */
12113 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
12115 char tmp[SIPBUFSIZE];
12116 char *s, *e, *uri, *t;
12117 char *domain;
12119 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
12120 if ((t = strchr(tmp, ',')))
12121 *t = '\0';
12122 s = get_in_brackets(tmp);
12123 uri = ast_strdupa(s);
12124 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
12125 if (!strncasecmp(s, "sip:", 4))
12126 s += 4;
12127 e = strchr(s, ';');
12128 if (e)
12129 *e = '\0';
12130 if (option_debug)
12131 ast_log(LOG_DEBUG, "Found promiscuous redirection to 'SIP/%s'\n", s);
12132 if (p->owner)
12133 ast_string_field_build(p->owner, call_forward, "SIP/%s", s);
12134 } else {
12135 e = strchr(tmp, '@');
12136 if (e) {
12137 *e++ = '\0';
12138 domain = e;
12139 } else {
12140 /* No username part */
12141 domain = tmp;
12143 e = strchr(s, ';'); /* Strip of parameters in the username part */
12144 if (e)
12145 *e = '\0';
12146 e = strchr(domain, ';'); /* Strip of parameters in the domain part */
12147 if (e)
12148 *e = '\0';
12150 if (!strncasecmp(s, "sip:", 4))
12151 s += 4;
12152 if (option_debug > 1)
12153 ast_log(LOG_DEBUG, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
12154 if (p->owner) {
12155 pbx_builtin_setvar_helper(p->owner, "SIPREDIRECTURI", uri);
12156 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
12157 ast_string_field_set(p->owner, call_forward, s);
12162 /*! \brief Check pending actions on SIP call */
12163 static void check_pendings(struct sip_pvt *p)
12165 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
12166 /* if we can't BYE, then this is really a pending CANCEL */
12167 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
12168 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
12169 /* Actually don't destroy us yet, wait for the 487 on our original
12170 INVITE, but do set an autodestruct just in case we never get it. */
12171 else {
12172 /* We have a pending outbound invite, don't send someting
12173 new in-transaction */
12174 if (p->pendinginvite)
12175 return;
12177 /* Perhaps there is an SD change INVITE outstanding */
12178 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
12180 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
12181 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12182 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
12183 /* if we can't REINVITE, hold it for later */
12184 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
12185 if (option_debug)
12186 ast_log(LOG_DEBUG, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
12187 } else {
12188 if (option_debug)
12189 ast_log(LOG_DEBUG, "Sending pending reinvite on '%s'\n", p->callid);
12190 /* Didn't get to reinvite yet, so do it now */
12191 transmit_reinvite_with_sdp(p);
12192 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
12197 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
12198 to avoid race conditions between asterisk servers.
12199 Called from the scheduler.
12201 static int sip_reinvite_retry(const void *data)
12203 struct sip_pvt *p = (struct sip_pvt *) data;
12205 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
12206 p->waitid = -1;
12207 return 0;
12211 /*! \brief Handle SIP response to INVITE dialogue */
12212 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
12214 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
12215 int res = 0;
12216 int xmitres = 0;
12217 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
12218 struct ast_channel *bridgepeer = NULL;
12220 if (option_debug > 3) {
12221 if (reinvite)
12222 ast_log(LOG_DEBUG, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
12223 else
12224 ast_log(LOG_DEBUG, "SIP response %d to standard invite\n", resp);
12227 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) { /* This call is already gone */
12228 if (option_debug)
12229 ast_log(LOG_DEBUG, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
12230 return;
12233 /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
12234 /* Don't auto congest anymore since we've gotten something useful back */
12235 AST_SCHED_DEL(sched, p->initid);
12237 /* RFC3261 says we must treat every 1xx response (but not 100)
12238 that we don't recognize as if it was 183.
12240 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
12241 resp = 183;
12243 /* Any response between 100 and 199 is PROCEEDING */
12244 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
12245 p->invitestate = INV_PROCEEDING;
12247 /* Final response, not 200 ? */
12248 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
12249 p->invitestate = INV_COMPLETED;
12252 switch (resp) {
12253 case 100: /* Trying */
12254 case 101: /* Dialog establishment */
12255 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12256 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12257 check_pendings(p);
12258 break;
12260 case 180: /* 180 Ringing */
12261 case 182: /* 182 Queued */
12262 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12263 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12264 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12265 ast_queue_control(p->owner, AST_CONTROL_RINGING);
12266 if (p->owner->_state != AST_STATE_UP) {
12267 ast_setstate(p->owner, AST_STATE_RINGING);
12270 if (find_sdp(req)) {
12271 if (p->invitestate != INV_CANCELLED)
12272 p->invitestate = INV_EARLY_MEDIA;
12273 res = process_sdp(p, req);
12274 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12275 /* Queue a progress frame only if we have SDP in 180 or 182 */
12276 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
12279 check_pendings(p);
12280 break;
12282 case 183: /* Session progress */
12283 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12284 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12285 /* Ignore 183 Session progress without SDP */
12286 if (find_sdp(req)) {
12287 if (p->invitestate != INV_CANCELLED)
12288 p->invitestate = INV_EARLY_MEDIA;
12289 res = process_sdp(p, req);
12290 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12291 /* Queue a progress frame */
12292 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
12295 check_pendings(p);
12296 break;
12298 case 200: /* 200 OK on invite - someone's answering our call */
12299 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12300 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12301 p->authtries = 0;
12302 if (find_sdp(req)) {
12303 if ((res = process_sdp(p, req)) && !ast_test_flag(req, SIP_PKT_IGNORE))
12304 if (!reinvite)
12305 /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
12306 /* For re-invites, we try to recover */
12307 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12310 /* Parse contact header for continued conversation */
12311 /* When we get 200 OK, we know which device (and IP) to contact for this call */
12312 /* This is important when we have a SIP proxy between us and the phone */
12313 if (outgoing) {
12314 update_call_counter(p, DEC_CALL_RINGING);
12315 parse_ok_contact(p, req);
12316 /* Save Record-Route for any later requests we make on this dialogue */
12317 if (!reinvite)
12318 build_route(p, req, 1);
12320 if(set_address_from_contact(p)) {
12321 /* Bad contact - we don't know how to reach this device */
12322 /* We need to ACK, but then send a bye */
12323 if (!p->route && !ast_test_flag(req, SIP_PKT_IGNORE))
12324 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12329 if (p->owner && (p->owner->_state == AST_STATE_UP) && (bridgepeer = ast_bridged_channel(p->owner))) { /* if this is a re-invite */
12330 struct sip_pvt *bridgepvt = NULL;
12332 if (!bridgepeer->tech) {
12333 ast_log(LOG_WARNING, "Ooooh.. no tech! That's REALLY bad\n");
12334 break;
12336 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
12337 bridgepvt = (struct sip_pvt*)(bridgepeer->tech_pvt);
12338 if (bridgepvt->udptl) {
12339 if (p->t38.state == T38_PEER_REINVITE) {
12340 sip_handle_t38_reinvite(bridgepeer, p, 0);
12341 ast_rtp_set_rtptimers_onhold(p->rtp);
12342 if (p->vrtp)
12343 ast_rtp_set_rtptimers_onhold(p->vrtp); /* Turn off RTP timers while we send fax */
12344 } else if (p->t38.state == T38_DISABLED && bridgepeer && (bridgepvt->t38.state == T38_ENABLED)) {
12345 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
12346 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
12347 /* XXXX Should we really destroy this session here, without any response at all??? */
12348 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12350 } else {
12351 if (option_debug > 1)
12352 ast_log(LOG_DEBUG, "Strange... The other side of the bridge does not have a udptl struct\n");
12353 ast_mutex_lock(&bridgepvt->lock);
12354 bridgepvt->t38.state = T38_DISABLED;
12355 ast_mutex_unlock(&bridgepvt->lock);
12356 if (option_debug)
12357 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->tech->type);
12358 p->t38.state = T38_DISABLED;
12359 if (option_debug > 1)
12360 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12362 } else {
12363 /* Other side is not a SIP channel */
12364 if (option_debug > 1)
12365 ast_log(LOG_DEBUG, "Strange... The other side of the bridge is not a SIP channel\n");
12366 p->t38.state = T38_DISABLED;
12367 if (option_debug > 1)
12368 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12371 if ((p->t38.state == T38_LOCAL_REINVITE) || (p->t38.state == T38_LOCAL_DIRECT)) {
12372 /* If there was T38 reinvite and we are supposed to answer with 200 OK than this should set us to T38 negotiated mode */
12373 p->t38.state = T38_ENABLED;
12374 if (option_debug)
12375 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12378 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12379 if (!reinvite) {
12380 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
12381 } else { /* RE-invite */
12382 ast_queue_frame(p->owner, &ast_null_frame);
12384 } else {
12385 /* It's possible we're getting an 200 OK after we've tried to disconnect
12386 by sending CANCEL */
12387 /* First send ACK, then send bye */
12388 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12389 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12391 /* If I understand this right, the branch is different for a non-200 ACK only */
12392 p->invitestate = INV_TERMINATED;
12393 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
12394 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
12395 check_pendings(p);
12396 break;
12397 case 407: /* Proxy authentication */
12398 case 401: /* Www auth */
12399 /* First we ACK */
12400 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12401 if (p->options)
12402 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
12404 /* Then we AUTH */
12405 ast_string_field_free(p, theirtag); /* forget their old tag, so we don't match tags when getting response */
12406 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
12407 char *authenticate = (resp == 401 ? "WWW-Authenticate" : "Proxy-Authenticate");
12408 char *authorization = (resp == 401 ? "Authorization" : "Proxy-Authorization");
12409 if (p->authtries < MAX_AUTHTRIES)
12410 p->invitestate = INV_CALLING;
12411 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, authenticate, authorization, SIP_INVITE, 1)) {
12412 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
12413 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12414 sip_alreadygone(p);
12415 if (p->owner)
12416 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12419 break;
12421 case 403: /* Forbidden */
12422 /* First we ACK */
12423 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12424 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
12425 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner)
12426 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12427 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12428 sip_alreadygone(p);
12429 break;
12431 case 404: /* Not found */
12432 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12433 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12434 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12435 sip_alreadygone(p);
12436 break;
12438 case 408: /* Request timeout */
12439 case 481: /* Call leg does not exist */
12440 /* Could be REFER caused INVITE with replaces */
12441 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
12442 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12443 if (p->owner)
12444 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12445 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12446 break;
12447 case 487: /* Cancelled transaction */
12448 /* We have sent CANCEL on an outbound INVITE
12449 This transaction is already scheduled to be killed by sip_hangup().
12451 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12452 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE)) {
12453 ast_queue_hangup(p->owner);
12454 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
12455 } else if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
12456 update_call_counter(p, DEC_CALL_LIMIT);
12457 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
12458 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12459 sip_alreadygone(p);
12461 break;
12462 case 488: /* Not acceptable here */
12463 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12464 if (reinvite && p->udptl) {
12465 /* If this is a T.38 call, we should go back to
12466 audio. If this is an audio call - something went
12467 terribly wrong since we don't renegotiate codecs,
12468 only IP/port .
12470 p->t38.state = T38_DISABLED;
12471 /* Try to reset RTP timers */
12472 ast_rtp_set_rtptimers_onhold(p->rtp);
12473 ast_log(LOG_ERROR, "Got error on T.38 re-invite. Bad configuration. Peer needs to have T.38 disabled.\n");
12475 /*! \bug Is there any way we can go back to the audio call on both
12476 sides here?
12478 /* While figuring that out, hangup the call */
12479 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12480 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12481 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12482 } else if (p->udptl && p->t38.state == T38_LOCAL_DIRECT) {
12483 /* We tried to send T.38 out in an initial INVITE and the remote side rejected it,
12484 right now we can't fall back to audio so totally abort.
12486 p->t38.state = T38_DISABLED;
12487 /* Try to reset RTP timers */
12488 ast_rtp_set_rtptimers_onhold(p->rtp);
12489 ast_log(LOG_ERROR, "Got error on T.38 initial invite. Bailing out.\n");
12491 /* The dialog is now terminated */
12492 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12493 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12494 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12495 sip_alreadygone(p);
12496 } else {
12497 /* We can't set up this call, so give up */
12498 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12499 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12500 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12501 /* If there's no dialog to end, then mark p as already gone */
12502 if (!reinvite)
12503 sip_alreadygone(p);
12505 break;
12506 case 491: /* Pending */
12507 /* we really should have to wait a while, then retransmit
12508 * We should support the retry-after at some point
12509 * At this point, we treat this as a congestion if the call is not in UP state
12511 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12512 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE)) {
12513 if (p->owner->_state != AST_STATE_UP) {
12514 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12515 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12516 } else {
12517 /* This is a re-invite that failed.
12518 * Reset the flag after a while
12520 int wait = 3 + ast_random() % 5;
12521 p->waitid = ast_sched_add(sched, wait, sip_reinvite_retry, p);
12522 if (option_debug > 2)
12523 ast_log(LOG_DEBUG, "Reinvite race. Waiting %d secs before retry\n", wait);
12526 break;
12528 case 501: /* Not implemented */
12529 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12530 if (p->owner)
12531 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12532 break;
12534 if (xmitres == XMIT_ERROR)
12535 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
12538 /* \brief Handle SIP response in REFER transaction
12539 We've sent a REFER, now handle responses to it
12541 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
12543 char *auth = "Proxy-Authenticate";
12544 char *auth2 = "Proxy-Authorization";
12546 /* If no refer structure exists, then do nothing */
12547 if (!p->refer)
12548 return;
12550 switch (resp) {
12551 case 202: /* Transfer accepted */
12552 /* We need to do something here */
12553 /* The transferee is now sending INVITE to target */
12554 p->refer->status = REFER_ACCEPTED;
12555 /* Now wait for next message */
12556 if (option_debug > 2)
12557 ast_log(LOG_DEBUG, "Got 202 accepted on transfer\n");
12558 /* We should hang along, waiting for NOTIFY's here */
12559 break;
12561 case 401: /* Not www-authorized on SIP method */
12562 case 407: /* Proxy auth */
12563 if (ast_strlen_zero(p->authname)) {
12564 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
12565 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12566 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12568 if (resp == 401) {
12569 auth = "WWW-Authenticate";
12570 auth2 = "Authorization";
12572 if ((p->authtries > 1) || do_proxy_auth(p, req, auth, auth2, SIP_REFER, 0)) {
12573 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
12574 p->refer->status = REFER_NOAUTH;
12575 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12577 break;
12578 case 481: /* Call leg does not exist */
12580 /* A transfer with Replaces did not work */
12581 /* OEJ: We should Set flag, cancel the REFER, go back
12582 to original call - but right now we can't */
12583 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
12584 if (p->owner)
12585 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12586 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12587 break;
12589 case 500: /* Server error */
12590 case 501: /* Method not implemented */
12591 /* Return to the current call onhold */
12592 /* Status flag needed to be reset */
12593 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
12594 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12595 p->refer->status = REFER_FAILED;
12596 break;
12597 case 603: /* Transfer declined */
12598 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
12599 p->refer->status = REFER_FAILED;
12600 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12601 break;
12605 /*! \brief Handle responses on REGISTER to services */
12606 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
12608 int expires, expires_ms;
12609 struct sip_registry *r;
12610 r=p->registry;
12612 switch (resp) {
12613 case 401: /* Unauthorized */
12614 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "WWW-Authenticate", "Authorization")) {
12615 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
12616 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12618 break;
12619 case 403: /* Forbidden */
12620 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
12621 if (global_regattempts_max)
12622 p->registry->regattempts = global_regattempts_max+1;
12623 AST_SCHED_DEL(sched, r->timeout);
12624 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12625 break;
12626 case 404: /* Not found */
12627 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username,p->registry->hostname);
12628 if (global_regattempts_max)
12629 p->registry->regattempts = global_regattempts_max+1;
12630 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12631 r->call = NULL;
12632 AST_SCHED_DEL(sched, r->timeout);
12633 break;
12634 case 407: /* Proxy auth */
12635 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization")) {
12636 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
12637 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12639 break;
12640 case 408: /* Request timeout */
12641 /* Got a timeout response, so reset the counter of failed responses */
12642 r->regattempts = 0;
12643 break;
12644 case 479: /* SER: Not able to process the URI - address is wrong in register*/
12645 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username,p->registry->hostname);
12646 if (global_regattempts_max)
12647 p->registry->regattempts = global_regattempts_max+1;
12648 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12649 r->call = NULL;
12650 AST_SCHED_DEL(sched, r->timeout);
12651 break;
12652 case 200: /* 200 OK */
12653 if (!r) {
12654 ast_log(LOG_WARNING, "Got 200 OK on REGISTER that isn't a register\n");
12655 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12656 return 0;
12659 r->regstate = REG_STATE_REGISTERED;
12660 r->regtime = time(NULL); /* Reset time of last succesful registration */
12661 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
12662 r->regattempts = 0;
12663 if (option_debug)
12664 ast_log(LOG_DEBUG, "Registration successful\n");
12665 if (r->timeout > -1) {
12666 if (option_debug)
12667 ast_log(LOG_DEBUG, "Cancelling timeout %d\n", r->timeout);
12669 AST_SCHED_DEL(sched, r->timeout);
12670 r->call = NULL;
12671 p->registry = NULL;
12672 /* Let this one hang around until we have all the responses */
12673 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12674 /* ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); */
12676 /* set us up for re-registering */
12677 /* figure out how long we got registered for */
12678 AST_SCHED_DEL(sched, r->expire);
12679 /* according to section 6.13 of RFC, contact headers override
12680 expires headers, so check those first */
12681 expires = 0;
12683 /* XXX todo: try to save the extra call */
12684 if (!ast_strlen_zero(get_header(req, "Contact"))) {
12685 const char *contact = NULL;
12686 const char *tmptmp = NULL;
12687 int start = 0;
12688 for(;;) {
12689 contact = __get_header(req, "Contact", &start);
12690 /* this loop ensures we get a contact header about our register request */
12691 if(!ast_strlen_zero(contact)) {
12692 if( (tmptmp=strstr(contact, p->our_contact))) {
12693 contact=tmptmp;
12694 break;
12696 } else
12697 break;
12699 tmptmp = strcasestr(contact, "expires=");
12700 if (tmptmp) {
12701 if (sscanf(tmptmp + 8, "%d;", &expires) != 1)
12702 expires = 0;
12706 if (!expires)
12707 expires=atoi(get_header(req, "expires"));
12708 if (!expires)
12709 expires=default_expiry;
12711 expires_ms = expires * 1000;
12712 if (expires <= EXPIRY_GUARD_LIMIT)
12713 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT),EXPIRY_GUARD_MIN);
12714 else
12715 expires_ms -= EXPIRY_GUARD_SECS * 1000;
12716 if (sipdebug)
12717 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
12719 r->refresh= (int) expires_ms / 1000;
12721 /* Schedule re-registration before we expire */
12722 AST_SCHED_DEL(sched, r->expire);
12723 r->expire = ast_sched_add(sched, expires_ms, sip_reregister, r);
12724 ASTOBJ_UNREF(r, sip_registry_destroy);
12726 return 1;
12729 /*! \brief Handle qualification responses (OPTIONS) */
12730 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
12732 struct sip_peer *peer = p->relatedpeer;
12733 int statechanged, is_reachable, was_reachable;
12734 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
12737 * Compute the response time to a ping (goes in peer->lastms.)
12738 * -1 means did not respond, 0 means unknown,
12739 * 1..maxms is a valid response, >maxms means late response.
12741 if (pingtime < 1) /* zero = unknown, so round up to 1 */
12742 pingtime = 1;
12744 /* Now determine new state and whether it has changed.
12745 * Use some helper variables to simplify the writing
12746 * of the expressions.
12748 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
12749 is_reachable = pingtime <= peer->maxms;
12750 statechanged = peer->lastms == 0 /* yes, unknown before */
12751 || was_reachable != is_reachable;
12753 peer->lastms = pingtime;
12754 peer->call = NULL;
12755 if (statechanged) {
12756 const char *s = is_reachable ? "Reachable" : "Lagged";
12758 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
12759 peer->name, s, pingtime, peer->maxms);
12760 ast_device_state_changed("SIP/%s", peer->name);
12761 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
12762 "Peer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
12763 peer->name, s, pingtime);
12766 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
12767 struct sip_peer *peer_ptr = peer;
12768 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
12771 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12773 /* Try again eventually */
12774 peer->pokeexpire = ast_sched_add(sched,
12775 is_reachable ? DEFAULT_FREQ_OK : DEFAULT_FREQ_NOTOK,
12776 sip_poke_peer_s, ASTOBJ_REF(peer));
12778 if (peer->pokeexpire == -1) {
12779 ASTOBJ_UNREF(peer, sip_destroy_peer);
12783 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
12784 static void stop_media_flows(struct sip_pvt *p)
12786 /* Immediately stop RTP, VRTP and UDPTL as applicable */
12787 if (p->rtp)
12788 ast_rtp_stop(p->rtp);
12789 if (p->vrtp)
12790 ast_rtp_stop(p->vrtp);
12791 if (p->udptl)
12792 ast_udptl_stop(p->udptl);
12795 /*! \brief Handle SIP response in dialogue */
12796 /* XXX only called by handle_request */
12797 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
12799 struct ast_channel *owner;
12800 int sipmethod;
12801 int res = 1;
12802 const char *c = get_header(req, "Cseq");
12803 /* GCC 4.2 complains if I try to cast c as a char * when passing it to ast_skip_nonblanks, so make a copy of it */
12804 char *c_copy = ast_strdupa(c);
12805 /* Skip the Cseq and its subsequent spaces */
12806 const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
12808 if (!msg)
12809 msg = "";
12811 sipmethod = find_sip_method(msg);
12813 owner = p->owner;
12814 if (owner)
12815 owner->hangupcause = hangup_sip2cause(resp);
12817 /* Acknowledge whatever it is destined for */
12818 if ((resp >= 100) && (resp <= 199))
12819 __sip_semi_ack(p, seqno, 0, sipmethod);
12820 else
12821 __sip_ack(p, seqno, 0, sipmethod);
12823 /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
12824 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite)
12825 p->pendinginvite = 0;
12827 /* Get their tag if we haven't already */
12828 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
12829 char tag[128];
12831 gettag(req, "To", tag, sizeof(tag));
12832 ast_string_field_set(p, theirtag, tag);
12834 if (p->relatedpeer && p->method == SIP_OPTIONS) {
12835 /* We don't really care what the response is, just that it replied back.
12836 Well, as long as it's not a 100 response... since we might
12837 need to hang around for something more "definitive" */
12838 if (resp != 100)
12839 handle_response_peerpoke(p, resp, req);
12840 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12841 switch(resp) {
12842 case 100: /* 100 Trying */
12843 case 101: /* 101 Dialog establishment */
12844 if (sipmethod == SIP_INVITE)
12845 handle_response_invite(p, resp, rest, req, seqno);
12846 break;
12847 case 183: /* 183 Session Progress */
12848 if (sipmethod == SIP_INVITE)
12849 handle_response_invite(p, resp, rest, req, seqno);
12850 break;
12851 case 180: /* 180 Ringing */
12852 if (sipmethod == SIP_INVITE)
12853 handle_response_invite(p, resp, rest, req, seqno);
12854 break;
12855 case 182: /* 182 Queued */
12856 if (sipmethod == SIP_INVITE)
12857 handle_response_invite(p, resp, rest, req, seqno);
12858 break;
12859 case 200: /* 200 OK */
12860 p->authtries = 0; /* Reset authentication counter */
12861 if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
12862 /* We successfully transmitted a message
12863 or a video update request in INFO */
12864 /* Nothing happens here - the message is inside a dialog */
12865 } else if (sipmethod == SIP_INVITE) {
12866 handle_response_invite(p, resp, rest, req, seqno);
12867 } else if (sipmethod == SIP_NOTIFY) {
12868 /* They got the notify, this is the end */
12869 if (p->owner) {
12870 if (!p->refer) {
12871 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
12872 ast_queue_hangup(p->owner);
12873 } else if (option_debug > 3)
12874 ast_log(LOG_DEBUG, "Got OK on REFER Notify message\n");
12875 } else {
12876 if (p->subscribed == NONE)
12877 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12878 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
12879 /* Ready to send the next state we have on queue */
12880 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
12881 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
12884 } else if (sipmethod == SIP_REGISTER)
12885 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12886 else if (sipmethod == SIP_BYE) { /* Ok, we're ready to go */
12887 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12888 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
12889 } else if (sipmethod == SIP_SUBSCRIBE)
12890 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
12891 break;
12892 case 202: /* Transfer accepted */
12893 if (sipmethod == SIP_REFER)
12894 handle_response_refer(p, resp, rest, req, seqno);
12895 break;
12896 case 401: /* Not www-authorized on SIP method */
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 (p->registry && sipmethod == SIP_REGISTER)
12902 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12903 else if (sipmethod == SIP_BYE) {
12904 if (ast_strlen_zero(p->authname)) {
12905 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12906 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12907 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12908 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "WWW-Authenticate", "Authorization", sipmethod, 0)) {
12909 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
12910 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12911 /* We fail to auth bye on our own call, but still needs to tear down the call.
12912 Life, they call it. */
12914 } else {
12915 ast_log(LOG_WARNING, "Got authentication request (401) on unknown %s to '%s'\n", sip_methods[sipmethod].text, get_header(req, "To"));
12916 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12918 break;
12919 case 403: /* Forbidden - we failed authentication */
12920 if (sipmethod == SIP_INVITE)
12921 handle_response_invite(p, resp, rest, req, seqno);
12922 else if (p->registry && sipmethod == SIP_REGISTER)
12923 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12924 else {
12925 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
12926 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12928 break;
12929 case 404: /* Not found */
12930 if (p->registry && sipmethod == SIP_REGISTER)
12931 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12932 else if (sipmethod == SIP_INVITE)
12933 handle_response_invite(p, resp, rest, req, seqno);
12934 else if (owner)
12935 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12936 break;
12937 case 407: /* Proxy auth required */
12938 if (sipmethod == SIP_INVITE)
12939 handle_response_invite(p, resp, rest, req, seqno);
12940 else if (sipmethod == SIP_REFER)
12941 handle_response_refer(p, resp, rest, req, seqno);
12942 else if (p->registry && sipmethod == SIP_REGISTER)
12943 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12944 else if (sipmethod == SIP_BYE) {
12945 if (ast_strlen_zero(p->authname)) {
12946 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12947 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12948 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12949 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", sipmethod, 0)) {
12950 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
12951 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12953 } else /* We can't handle this, giving up in a bad way */
12954 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12956 break;
12957 case 408: /* Request timeout - terminate dialog */
12958 if (sipmethod == SIP_INVITE)
12959 handle_response_invite(p, resp, rest, req, seqno);
12960 else if (sipmethod == SIP_REGISTER)
12961 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12962 else if (sipmethod == SIP_BYE) {
12963 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12964 if (option_debug)
12965 ast_log(LOG_DEBUG, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
12966 } else {
12967 if (owner)
12968 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12969 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12971 break;
12972 case 481: /* Call leg does not exist */
12973 if (sipmethod == SIP_INVITE) {
12974 handle_response_invite(p, resp, rest, req, seqno);
12975 } else if (sipmethod == SIP_REFER) {
12976 handle_response_refer(p, resp, rest, req, seqno);
12977 } else if (sipmethod == SIP_BYE) {
12978 /* The other side has no transaction to bye,
12979 just assume it's all right then */
12980 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12981 } else if (sipmethod == SIP_CANCEL) {
12982 /* The other side has no transaction to cancel,
12983 just assume it's all right then */
12984 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12985 } else {
12986 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12987 /* Guessing that this is not an important request */
12989 break;
12990 case 487:
12991 if (sipmethod == SIP_INVITE)
12992 handle_response_invite(p, resp, rest, req, seqno);
12993 break;
12994 case 488: /* Not acceptable here - codec error */
12995 if (sipmethod == SIP_INVITE)
12996 handle_response_invite(p, resp, rest, req, seqno);
12997 break;
12998 case 491: /* Pending */
12999 if (sipmethod == SIP_INVITE)
13000 handle_response_invite(p, resp, rest, req, seqno);
13001 else {
13002 if (option_debug)
13003 ast_log(LOG_DEBUG, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
13004 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13006 break;
13007 case 501: /* Not Implemented */
13008 if (sipmethod == SIP_INVITE)
13009 handle_response_invite(p, resp, rest, req, seqno);
13010 else if (sipmethod == SIP_REFER)
13011 handle_response_refer(p, resp, rest, req, seqno);
13012 else
13013 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
13014 break;
13015 case 603: /* Declined transfer */
13016 if (sipmethod == SIP_REFER) {
13017 handle_response_refer(p, resp, rest, req, seqno);
13018 break;
13020 /* Fallthrough */
13021 default:
13022 if ((resp >= 300) && (resp < 700)) {
13023 /* Fatal response */
13024 if ((option_verbose > 2) && (resp != 487))
13025 ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
13027 if (sipmethod == SIP_INVITE)
13028 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
13030 /* XXX Locking issues?? XXX */
13031 switch(resp) {
13032 case 300: /* Multiple Choices */
13033 case 301: /* Moved permenantly */
13034 case 302: /* Moved temporarily */
13035 case 305: /* Use Proxy */
13036 parse_moved_contact(p, req);
13037 /* Fall through */
13038 case 486: /* Busy here */
13039 case 600: /* Busy everywhere */
13040 case 603: /* Decline */
13041 if (p->owner)
13042 ast_queue_control(p->owner, AST_CONTROL_BUSY);
13043 break;
13044 case 482: /*
13045 \note SIP is incapable of performing a hairpin call, which
13046 is yet another failure of not having a layer 2 (again, YAY
13047 IETF for thinking ahead). So we treat this as a call
13048 forward and hope we end up at the right place... */
13049 if (option_debug)
13050 ast_log(LOG_DEBUG, "Hairpin detected, setting up call forward for what it's worth\n");
13051 if (p->owner)
13052 ast_string_field_build(p->owner, call_forward,
13053 "Local/%s@%s", p->username, p->context);
13054 /* Fall through */
13055 case 480: /* Temporarily Unavailable */
13056 case 404: /* Not Found */
13057 case 410: /* Gone */
13058 case 400: /* Bad Request */
13059 case 500: /* Server error */
13060 if (sipmethod == SIP_REFER) {
13061 handle_response_refer(p, resp, rest, req, seqno);
13062 break;
13064 /* Fall through */
13065 case 502: /* Bad gateway */
13066 case 503: /* Service Unavailable */
13067 case 504: /* Server Timeout */
13068 if (owner)
13069 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
13070 break;
13071 default:
13072 /* Send hangup */
13073 if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
13074 ast_queue_hangup(p->owner);
13075 break;
13077 /* ACK on invite */
13078 if (sipmethod == SIP_INVITE)
13079 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
13080 if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
13081 sip_alreadygone(p);
13082 if (!p->owner)
13083 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13084 } else if ((resp >= 100) && (resp < 200)) {
13085 if (sipmethod == SIP_INVITE) {
13086 if (!ast_test_flag(req, SIP_PKT_IGNORE) && sip_cancel_destroy(p))
13087 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13088 if (find_sdp(req))
13089 process_sdp(p, req);
13090 if (p->owner) {
13091 /* Queue a progress frame */
13092 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
13095 } else
13096 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));
13098 } else {
13099 /* Responses to OUTGOING SIP requests on INCOMING calls
13100 get handled here. As well as out-of-call message responses */
13101 if (ast_test_flag(req, SIP_PKT_DEBUG))
13102 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
13104 if (sipmethod == SIP_INVITE && resp == 200) {
13105 /* Tags in early session is replaced by the tag in 200 OK, which is
13106 the final reply to our INVITE */
13107 char tag[128];
13109 gettag(req, "To", tag, sizeof(tag));
13110 ast_string_field_set(p, theirtag, tag);
13113 switch(resp) {
13114 case 200:
13115 if (sipmethod == SIP_INVITE) {
13116 handle_response_invite(p, resp, rest, req, seqno);
13117 } else if (sipmethod == SIP_CANCEL) {
13118 if (option_debug)
13119 ast_log(LOG_DEBUG, "Got 200 OK on CANCEL\n");
13121 /* Wait for 487, then destroy */
13122 } else if (sipmethod == SIP_NOTIFY) {
13123 /* They got the notify, this is the end */
13124 if (p->owner) {
13125 if (p->refer) {
13126 if (option_debug)
13127 ast_log(LOG_DEBUG, "Got 200 OK on NOTIFY for transfer\n");
13128 } else
13129 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
13130 /* ast_queue_hangup(p->owner); Disabled */
13131 } else {
13132 if (!p->subscribed && !p->refer)
13133 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13134 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
13135 /* Ready to send the next state we have on queue */
13136 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
13137 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
13140 } else if (sipmethod == SIP_BYE)
13141 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13142 else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO)
13143 /* We successfully transmitted a message or
13144 a video update request in INFO */
13146 else if (sipmethod == SIP_BYE)
13147 /* Ok, we're ready to go */
13148 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13149 break;
13150 case 202: /* Transfer accepted */
13151 if (sipmethod == SIP_REFER)
13152 handle_response_refer(p, resp, rest, req, seqno);
13153 break;
13154 case 401: /* www-auth */
13155 case 407:
13156 if (sipmethod == SIP_REFER)
13157 handle_response_refer(p, resp, rest, req, seqno);
13158 else if (sipmethod == SIP_INVITE)
13159 handle_response_invite(p, resp, rest, req, seqno);
13160 else if (sipmethod == SIP_BYE) {
13161 char *auth, *auth2;
13163 auth = (resp == 407 ? "Proxy-Authenticate" : "WWW-Authenticate");
13164 auth2 = (resp == 407 ? "Proxy-Authorization" : "Authorization");
13165 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, auth, auth2, sipmethod, 0)) {
13166 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
13167 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13170 break;
13171 case 481: /* Call leg does not exist */
13172 if (sipmethod == SIP_INVITE) {
13173 /* Re-invite failed */
13174 handle_response_invite(p, resp, rest, req, seqno);
13175 } else if (sipmethod == SIP_BYE) {
13176 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13177 } else if (sipdebug) {
13178 ast_log (LOG_DEBUG, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
13180 break;
13181 case 501: /* Not Implemented */
13182 if (sipmethod == SIP_INVITE)
13183 handle_response_invite(p, resp, rest, req, seqno);
13184 else if (sipmethod == SIP_REFER)
13185 handle_response_refer(p, resp, rest, req, seqno);
13186 break;
13187 case 603: /* Declined transfer */
13188 if (sipmethod == SIP_REFER) {
13189 handle_response_refer(p, resp, rest, req, seqno);
13190 break;
13192 /* Fallthrough */
13193 default: /* Errors without handlers */
13194 if ((resp >= 100) && (resp < 200)) {
13195 if (sipmethod == SIP_INVITE) { /* re-invite */
13196 if (!ast_test_flag(req, SIP_PKT_IGNORE) && sip_cancel_destroy(p))
13197 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13200 if ((resp >= 300) && (resp < 700)) {
13201 if ((option_verbose > 2) && (resp != 487))
13202 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));
13203 switch(resp) {
13204 case 488: /* Not acceptable here - codec error */
13205 case 603: /* Decline */
13206 case 500: /* Server error */
13207 case 502: /* Bad gateway */
13208 case 503: /* Service Unavailable */
13209 case 504: /* Server timeout */
13211 /* re-invite failed */
13212 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
13213 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13214 break;
13217 break;
13223 /*! \brief Park SIP call support function
13224 Starts in a new thread, then parks the call
13225 XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
13226 audio can't be heard before hangup
13228 static void *sip_park_thread(void *stuff)
13230 struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
13231 struct sip_dual *d;
13232 struct sip_request req;
13233 int ext;
13234 int res;
13236 d = stuff;
13237 transferee = d->chan1;
13238 transferer = d->chan2;
13239 copy_request(&req, &d->req);
13241 if (!transferee || !transferer) {
13242 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
13243 return NULL;
13245 if (option_debug > 3)
13246 ast_log(LOG_DEBUG, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
13248 ast_channel_lock(transferee);
13249 if (ast_do_masquerade(transferee)) {
13250 ast_log(LOG_WARNING, "Masquerade failed.\n");
13251 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
13252 ast_channel_unlock(transferee);
13253 return NULL;
13255 ast_channel_unlock(transferee);
13257 res = ast_park_call(transferee, transferer, 0, &ext);
13260 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
13261 if (!res) {
13262 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
13263 } else {
13264 /* Then tell the transferer what happened */
13265 sprintf(buf, "Call parked on extension '%d'", ext);
13266 transmit_message_with_text(transferer->tech_pvt, buf);
13268 #endif
13270 /* Any way back to the current call??? */
13271 /* Transmit response to the REFER request */
13272 transmit_response(transferer->tech_pvt, "202 Accepted", &req);
13273 if (!res) {
13274 /* Transfer succeeded */
13275 append_history(transferer->tech_pvt, "SIPpark","Parked call on %d", ext);
13276 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
13277 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
13278 ast_hangup(transferer); /* This will cause a BYE */
13279 if (option_debug)
13280 ast_log(LOG_DEBUG, "SIP Call parked on extension '%d'\n", ext);
13281 } else {
13282 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
13283 append_history(transferer->tech_pvt, "SIPpark","Parking failed\n");
13284 if (option_debug)
13285 ast_log(LOG_DEBUG, "SIP Call parked failed \n");
13286 /* Do not hangup call */
13288 free(d);
13289 return NULL;
13292 /*! \brief Park a call using the subsystem in res_features.c
13293 This is executed in a separate thread
13295 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
13297 struct sip_dual *d;
13298 struct ast_channel *transferee, *transferer;
13299 /* Chan2m: The transferer, chan1m: The transferee */
13300 pthread_t th;
13302 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
13303 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
13304 if ((!transferer) || (!transferee)) {
13305 if (transferee) {
13306 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13307 ast_hangup(transferee);
13309 if (transferer) {
13310 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13311 ast_hangup(transferer);
13313 return -1;
13316 /* Make formats okay */
13317 transferee->readformat = chan1->readformat;
13318 transferee->writeformat = chan1->writeformat;
13320 /* Prepare for taking over the channel */
13321 ast_channel_masquerade(transferee, chan1);
13323 /* Setup the extensions and such */
13324 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
13325 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
13326 transferee->priority = chan1->priority;
13328 /* We make a clone of the peer channel too, so we can play
13329 back the announcement */
13331 /* Make formats okay */
13332 transferer->readformat = chan2->readformat;
13333 transferer->writeformat = chan2->writeformat;
13335 /* Prepare for taking over the channel. Go ahead and grab this channel
13336 * lock here to avoid a deadlock with callbacks into the channel driver
13337 * that hold the channel lock and want the pvt lock. */
13338 while (ast_channel_trylock(chan2)) {
13339 struct sip_pvt *pvt = chan2->tech_pvt;
13340 DEADLOCK_AVOIDANCE(&pvt->lock);
13342 ast_channel_masquerade(transferer, chan2);
13343 ast_channel_unlock(chan2);
13345 /* Setup the extensions and such */
13346 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
13347 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
13348 transferer->priority = chan2->priority;
13350 ast_channel_lock(transferer);
13351 if (ast_do_masquerade(transferer)) {
13352 ast_log(LOG_WARNING, "Masquerade failed :(\n");
13353 ast_channel_unlock(transferer);
13354 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13355 ast_hangup(transferer);
13356 return -1;
13358 ast_channel_unlock(transferer);
13359 if (!transferer || !transferee) {
13360 if (!transferer) {
13361 if (option_debug)
13362 ast_log(LOG_DEBUG, "No transferer channel, giving up parking\n");
13364 if (!transferee) {
13365 if (option_debug)
13366 ast_log(LOG_DEBUG, "No transferee channel, giving up parking\n");
13368 return -1;
13370 if ((d = ast_calloc(1, sizeof(*d)))) {
13371 pthread_attr_t attr;
13373 pthread_attr_init(&attr);
13374 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
13376 /* Save original request for followup */
13377 copy_request(&d->req, req);
13378 d->chan1 = transferee; /* Transferee */
13379 d->chan2 = transferer; /* Transferer */
13380 d->seqno = seqno;
13381 if (ast_pthread_create_background(&th, &attr, sip_park_thread, d) < 0) {
13382 /* Could not start thread */
13383 free(d); /* We don't need it anymore. If thread is created, d will be free'd
13384 by sip_park_thread() */
13385 pthread_attr_destroy(&attr);
13386 return 0;
13388 pthread_attr_destroy(&attr);
13390 return -1;
13393 /*! \brief Turn off generator data
13394 XXX Does this function belong in the SIP channel?
13396 static void ast_quiet_chan(struct ast_channel *chan)
13398 if (chan && chan->_state == AST_STATE_UP) {
13399 if (ast_test_flag(chan, AST_FLAG_MOH))
13400 ast_moh_stop(chan);
13401 else if (chan->generatordata)
13402 ast_deactivate_generator(chan);
13406 /*! \brief Attempt transfer of SIP call
13407 This fix for attended transfers on a local PBX */
13408 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
13410 int res = 0;
13411 struct ast_channel *peera = NULL,
13412 *peerb = NULL,
13413 *peerc = NULL,
13414 *peerd = NULL;
13417 /* We will try to connect the transferee with the target and hangup
13418 all channels to the transferer */
13419 if (option_debug > 3) {
13420 ast_log(LOG_DEBUG, "Sip transfer:--------------------\n");
13421 if (transferer->chan1)
13422 ast_log(LOG_DEBUG, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
13423 else
13424 ast_log(LOG_DEBUG, "-- No transferer first channel - odd??? \n");
13425 if (target->chan1)
13426 ast_log(LOG_DEBUG, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
13427 else
13428 ast_log(LOG_DEBUG, "-- No target first channel ---\n");
13429 if (transferer->chan2)
13430 ast_log(LOG_DEBUG, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
13431 else
13432 ast_log(LOG_DEBUG, "-- No bridged call to transferee\n");
13433 if (target->chan2)
13434 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)");
13435 else
13436 ast_log(LOG_DEBUG, "-- No target second channel ---\n");
13437 ast_log(LOG_DEBUG, "-- END Sip transfer:--------------------\n");
13439 if (transferer->chan2) { /* We have a bridge on the transferer's channel */
13440 peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
13441 peerb = target->chan1; /* Transferer - PBX -> target channel - This will get lost in masq */
13442 peerc = transferer->chan2; /* Asterisk to Transferee */
13443 peerd = target->chan2; /* Asterisk to Target */
13444 if (option_debug > 2)
13445 ast_log(LOG_DEBUG, "SIP transfer: Four channels to handle\n");
13446 } else if (target->chan2) { /* Transferer has no bridge (IVR), but transferee */
13447 peera = target->chan1; /* Transferer to PBX -> target channel */
13448 peerb = transferer->chan1; /* Transferer to IVR*/
13449 peerc = target->chan2; /* Asterisk to Target */
13450 peerd = transferer->chan2; /* Nothing */
13451 if (option_debug > 2)
13452 ast_log(LOG_DEBUG, "SIP transfer: Three channels to handle\n");
13455 if (peera && peerb && peerc && (peerb != peerc)) {
13456 ast_quiet_chan(peera); /* Stop generators */
13457 ast_quiet_chan(peerb);
13458 ast_quiet_chan(peerc);
13459 if (peerd)
13460 ast_quiet_chan(peerd);
13462 if (option_debug > 3)
13463 ast_log(LOG_DEBUG, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
13464 if (ast_channel_masquerade(peerb, peerc)) {
13465 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
13466 res = -1;
13467 } else
13468 ast_log(LOG_DEBUG, "SIP transfer: Succeeded to masquerade channels.\n");
13469 return res;
13470 } else {
13471 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
13472 if (transferer->chan1)
13473 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
13474 if (target->chan1)
13475 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
13476 return -2;
13478 return 0;
13481 /*! \brief Get tag from packet
13483 * \return Returns the pointer to the provided tag buffer,
13484 * or NULL if the tag was not found.
13486 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
13488 const char *thetag;
13490 if (!tagbuf)
13491 return NULL;
13492 tagbuf[0] = '\0'; /* reset the buffer */
13493 thetag = get_header(req, header);
13494 thetag = strcasestr(thetag, ";tag=");
13495 if (thetag) {
13496 thetag += 5;
13497 ast_copy_string(tagbuf, thetag, tagbufsize);
13498 return strsep(&tagbuf, ";");
13500 return NULL;
13503 /*! \brief Handle incoming notifications */
13504 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
13506 /* This is mostly a skeleton for future improvements */
13507 /* Mostly created to return proper answers on notifications on outbound REFER's */
13508 int res = 0;
13509 const char *event = get_header(req, "Event");
13510 char *eventid = NULL;
13511 char *sep;
13513 if( (sep = strchr(event, ';')) ) { /* XXX bug here - overwriting string ? */
13514 *sep++ = '\0';
13515 eventid = sep;
13518 if (option_debug > 1 && sipdebug)
13519 ast_log(LOG_DEBUG, "Got NOTIFY Event: %s\n", event);
13521 if (strcmp(event, "refer")) {
13522 /* We don't understand this event. */
13523 /* Here's room to implement incoming voicemail notifications :-) */
13524 transmit_response(p, "489 Bad event", req);
13525 res = -1;
13526 } else {
13527 /* Save nesting depth for now, since there might be other events we will
13528 support in the future */
13530 /* Handle REFER notifications */
13532 char buf[1024];
13533 char *cmd, *code;
13534 int respcode;
13535 int success = TRUE;
13537 /* EventID for each transfer... EventID is basically the REFER cseq
13539 We are getting notifications on a call that we transfered
13540 We should hangup when we are getting a 200 OK in a sipfrag
13541 Check if we have an owner of this event */
13543 /* Check the content type */
13544 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
13545 /* We need a sipfrag */
13546 transmit_response(p, "400 Bad request", req);
13547 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13548 return -1;
13551 /* Get the text of the attachment */
13552 if (get_msg_text(buf, sizeof(buf), req)) {
13553 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
13554 transmit_response(p, "400 Bad request", req);
13555 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13556 return -1;
13560 From the RFC...
13561 A minimal, but complete, implementation can respond with a single
13562 NOTIFY containing either the body:
13563 SIP/2.0 100 Trying
13565 if the subscription is pending, the body:
13566 SIP/2.0 200 OK
13567 if the reference was successful, the body:
13568 SIP/2.0 503 Service Unavailable
13569 if the reference failed, or the body:
13570 SIP/2.0 603 Declined
13572 if the REFER request was accepted before approval to follow the
13573 reference could be obtained and that approval was subsequently denied
13574 (see Section 2.4.7).
13576 If there are several REFERs in the same dialog, we need to
13577 match the ID of the event header...
13579 if (option_debug > 2)
13580 ast_log(LOG_DEBUG, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
13581 cmd = ast_skip_blanks(buf);
13582 code = cmd;
13583 /* We are at SIP/2.0 */
13584 while(*code && (*code > 32)) { /* Search white space */
13585 code++;
13587 *code++ = '\0';
13588 code = ast_skip_blanks(code);
13589 sep = code;
13590 sep++;
13591 while(*sep && (*sep > 32)) { /* Search white space */
13592 sep++;
13594 *sep++ = '\0'; /* Response string */
13595 respcode = atoi(code);
13596 switch (respcode) {
13597 case 100: /* Trying: */
13598 case 101: /* dialog establishment */
13599 /* Don't do anything yet */
13600 break;
13601 case 183: /* Ringing: */
13602 /* Don't do anything yet */
13603 break;
13604 case 200: /* OK: The new call is up, hangup this call */
13605 /* Hangup the call that we are replacing */
13606 break;
13607 case 301: /* Moved permenantly */
13608 case 302: /* Moved temporarily */
13609 /* Do we get the header in the packet in this case? */
13610 success = FALSE;
13611 break;
13612 case 503: /* Service Unavailable: The new call failed */
13613 /* Cancel transfer, continue the call */
13614 success = FALSE;
13615 break;
13616 case 603: /* Declined: Not accepted */
13617 /* Cancel transfer, continue the current call */
13618 success = FALSE;
13619 break;
13621 if (!success) {
13622 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
13625 /* Confirm that we received this packet */
13626 transmit_response(p, "200 OK", req);
13629 if (!p->lastinvite)
13630 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13632 return res;
13635 /*! \brief Handle incoming OPTIONS request */
13636 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
13638 int res;
13641 /* XXX Should we authenticate OPTIONS? XXX */
13643 if (p->lastinvite) {
13644 /* if this is a request in an active dialog, just confirm that the dialog exists. */
13645 transmit_response_with_allow(p, "200 OK", req, 0);
13646 return 0;
13649 res = get_destination(p, req);
13650 build_contact(p);
13652 if (ast_strlen_zero(p->context))
13653 ast_string_field_set(p, context, default_context);
13655 if (ast_shutting_down())
13656 transmit_response_with_allow(p, "503 Unavailable", req, 0);
13657 else if (res < 0)
13658 transmit_response_with_allow(p, "404 Not Found", req, 0);
13659 else
13660 transmit_response_with_allow(p, "200 OK", req, 0);
13662 /* Destroy if this OPTIONS was the opening request, but not if
13663 it's in the middle of a normal call flow. */
13664 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13666 return res;
13669 /*! \brief Handle the transfer part of INVITE with a replaces: header,
13670 meaning a target pickup or an attended transfer */
13671 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin)
13673 struct ast_frame *f;
13674 int earlyreplace = 0;
13675 int oneleggedreplace = 0; /* Call with no bridge, propably IVR or voice message */
13676 struct ast_channel *c = p->owner; /* Our incoming call */
13677 struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
13678 struct ast_channel *targetcall; /* The bridge to the take-over target */
13680 /* Check if we're in ring state */
13681 if (replacecall->_state == AST_STATE_RING)
13682 earlyreplace = 1;
13684 /* Check if we have a bridge */
13685 if (!(targetcall = ast_bridged_channel(replacecall))) {
13686 /* We have no bridge */
13687 if (!earlyreplace) {
13688 if (option_debug > 1)
13689 ast_log(LOG_DEBUG, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
13690 oneleggedreplace = 1;
13693 if (option_debug > 3 && targetcall && targetcall->_state == AST_STATE_RINGING)
13694 ast_log(LOG_DEBUG, "SIP transfer: Target channel is in ringing state\n");
13696 if (option_debug > 3) {
13697 if (targetcall)
13698 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);
13699 else
13700 ast_log(LOG_DEBUG, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
13703 if (ignore) {
13704 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
13705 /* We should answer something here. If we are here, the
13706 call we are replacing exists, so an accepted
13707 can't harm */
13708 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
13709 /* Do something more clever here */
13710 ast_channel_unlock(c);
13711 ast_mutex_unlock(&p->refer->refer_call->lock);
13712 return 1;
13714 if (!c) {
13715 /* What to do if no channel ??? */
13716 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
13717 transmit_response_reliable(p, "503 Service Unavailable", req);
13718 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
13719 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13720 ast_mutex_unlock(&p->refer->refer_call->lock);
13721 return 1;
13723 append_history(p, "Xfer", "INVITE/Replace received");
13724 /* We have three channels to play with
13725 channel c: New incoming call
13726 targetcall: Call from PBX to target
13727 p->refer->refer_call: SIP pvt dialog from transferer to pbx.
13728 replacecall: The owner of the previous
13729 We need to masq C into refer_call to connect to
13730 targetcall;
13731 If we are talking to internal audio stream, target call is null.
13734 /* Fake call progress */
13735 transmit_response(p, "100 Trying", req);
13736 ast_setstate(c, AST_STATE_RING);
13738 /* Masquerade the new call into the referred call to connect to target call
13739 Targetcall is not touched by the masq */
13741 /* Answer the incoming call and set channel to UP state */
13742 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
13744 ast_setstate(c, AST_STATE_UP);
13746 /* Stop music on hold and other generators */
13747 ast_quiet_chan(replacecall);
13748 ast_quiet_chan(targetcall);
13749 if (option_debug > 3)
13750 ast_log(LOG_DEBUG, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
13751 /* Unlock clone, but not original (replacecall) */
13752 if (!oneleggedreplace)
13753 ast_channel_unlock(c);
13755 /* Unlock PVT */
13756 ast_mutex_unlock(&p->refer->refer_call->lock);
13758 /* Make sure that the masq does not free our PVT for the old call */
13759 if (! earlyreplace && ! oneleggedreplace )
13760 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
13762 /* Prepare the masquerade - if this does not happen, we will be gone */
13763 if(ast_channel_masquerade(replacecall, c))
13764 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
13765 else if (option_debug > 3)
13766 ast_log(LOG_DEBUG, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
13768 /* The masquerade will happen as soon as someone reads a frame from the channel */
13770 /* C should now be in place of replacecall */
13771 /* ast_read needs to lock channel */
13772 ast_channel_unlock(c);
13774 if (earlyreplace || oneleggedreplace ) {
13775 /* Force the masq to happen */
13776 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
13777 ast_frfree(f);
13778 f = NULL;
13779 if (option_debug > 3)
13780 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from RING channel!\n");
13781 } else {
13782 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from RING channel \n");
13784 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13785 if (!oneleggedreplace)
13786 ast_channel_unlock(replacecall);
13787 } else { /* Bridged call, UP channel */
13788 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
13789 /* Masq ok */
13790 ast_frfree(f);
13791 f = NULL;
13792 if (option_debug > 2)
13793 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from channel! Masq done.\n");
13794 } else {
13795 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from channel. Transfer failed\n");
13797 ast_channel_unlock(replacecall);
13799 ast_mutex_unlock(&p->refer->refer_call->lock);
13801 ast_setstate(c, AST_STATE_DOWN);
13802 if (option_debug > 3) {
13803 struct ast_channel *test;
13804 ast_log(LOG_DEBUG, "After transfer:----------------------------\n");
13805 ast_log(LOG_DEBUG, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
13806 if (replacecall)
13807 ast_log(LOG_DEBUG, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
13808 if (p->owner) {
13809 ast_log(LOG_DEBUG, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
13810 test = ast_bridged_channel(p->owner);
13811 if (test)
13812 ast_log(LOG_DEBUG, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
13813 else
13814 ast_log(LOG_DEBUG, " -- No call bridged to C->owner \n");
13815 } else
13816 ast_log(LOG_DEBUG, " -- No channel yet \n");
13817 ast_log(LOG_DEBUG, "End After transfer:----------------------------\n");
13820 ast_channel_unlock(p->owner); /* Unlock new owner */
13821 if (!oneleggedreplace)
13822 ast_mutex_unlock(&p->lock); /* Unlock SIP structure */
13824 /* The call should be down with no ast_channel, so hang it up */
13825 c->tech_pvt = NULL;
13826 ast_hangup(c);
13827 return 0;
13830 /*! \brief helper routine for sip_uri_cmp
13832 * This takes the parameters from two SIP URIs and determines
13833 * if the URIs match. The rules for parameters *suck*. Here's a breakdown
13834 * 1. If a parameter appears in both URIs, then they must have the same value
13835 * in order for the URIs to match
13836 * 2. If one URI has a user, maddr, ttl, or method parameter, then the other
13837 * URI must also have that parameter and must have the same value
13838 * in order for the URIs to match
13839 * 3. All other headers appearing in only one URI are not considered when
13840 * determining if URIs match
13842 * \param input1 Parameters from URI 1
13843 * \param input2 Parameters from URI 2
13844 * \return Return 0 if the URIs' parameters match, 1 if they do not
13846 static int sip_uri_params_cmp(const char *input1, const char *input2)
13848 char *params1 = ast_strdupa(input1);
13849 char *params2 = ast_strdupa(input2);
13850 char *pos1;
13851 char *pos2;
13852 int maddrmatch = 0;
13853 int ttlmatch = 0;
13854 int usermatch = 0;
13855 int methodmatch = 0;
13857 /*Quick optimization. If both params are zero-length, then
13858 * they match
13860 if (ast_strlen_zero(params1) && ast_strlen_zero(params2)) {
13861 return 0;
13864 pos1 = params1;
13865 while (!ast_strlen_zero(pos1)) {
13866 char *name1 = pos1;
13867 char *value1 = strchr(pos1, '=');
13868 char *semicolon1 = strchr(pos1, ';');
13869 int matched = 0;
13870 if (semicolon1) {
13871 *semicolon1++ = '\0';
13873 if (!value1) {
13874 goto fail;
13876 *value1++ = '\0';
13877 /* Checkpoint reached. We have the name and value parsed for param1
13878 * We have to duplicate params2 each time through the second loop
13879 * or else we can't search and replace the semicolons with \0 each
13880 * time
13882 pos2 = ast_strdupa(params2);
13883 while (!ast_strlen_zero(pos2)) {
13884 char *name2 = pos2;
13885 char *value2 = strchr(pos2, '=');
13886 char *semicolon2 = strchr(pos2, ';');
13887 if (semicolon2) {
13888 *semicolon2++ = '\0';
13890 if (!value2) {
13891 goto fail;
13893 *value2++ = '\0';
13894 if (!strcasecmp(name1, name2)) {
13895 if (strcasecmp(value1, value2)) {
13896 goto fail;
13897 } else {
13898 matched = 1;
13899 break;
13902 pos2 = semicolon2;
13904 /* Need to see if the parameter we're looking at is one of the 'must-match' parameters */
13905 if (!strcasecmp(name1, "maddr")) {
13906 if (matched) {
13907 maddrmatch = 1;
13908 } else {
13909 goto fail;
13911 } else if (!strcasecmp(name1, "ttl")) {
13912 if (matched) {
13913 ttlmatch = 1;
13914 } else {
13915 goto fail;
13917 } else if (!strcasecmp(name1, "user")) {
13918 if (matched) {
13919 usermatch = 1;
13920 } else {
13921 goto fail;
13923 } else if (!strcasecmp(name1, "method")) {
13924 if (matched) {
13925 methodmatch = 1;
13926 } else {
13927 goto fail;
13930 pos1 = semicolon1;
13933 /* We've made it out of that horrible O(m*n) construct and there are no
13934 * failures yet. We're not done yet, though, because params2 could have
13935 * an maddr, ttl, user, or method header and params1 did not.
13937 pos2 = params2;
13938 while (!ast_strlen_zero(pos2)) {
13939 char *name2 = pos2;
13940 char *value2 = strchr(pos2, '=');
13941 char *semicolon2 = strchr(pos2, ';');
13942 if (semicolon2) {
13943 *semicolon2++ = '\0';
13945 if (!value2) {
13946 goto fail;
13948 *value2++ = '\0';
13949 if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
13950 (!strcasecmp(name2, "ttl") && !ttlmatch) ||
13951 (!strcasecmp(name2, "user") && !usermatch) ||
13952 (!strcasecmp(name2, "method") && !methodmatch)) {
13953 goto fail;
13956 return 0;
13958 fail:
13959 return 1;
13962 /*! \brief helper routine for sip_uri_cmp
13964 * This takes the "headers" from two SIP URIs and determines
13965 * if the URIs match. The rules for headers is simple. If a header
13966 * appears in one URI, then it must also appear in the other URI. The
13967 * order in which the headers appear does not matter.
13969 * \param input1 Headers from URI 1
13970 * \param input2 Headers from URI 2
13971 * \return Return 0 if the URIs' headers match, 1 if they do not
13973 static int sip_uri_headers_cmp(const char *input1, const char *input2)
13975 char *headers1 = ast_strdupa(input1);
13976 char *headers2 = ast_strdupa(input2);
13977 int zerolength1 = ast_strlen_zero(headers1);
13978 int zerolength2 = ast_strlen_zero(headers2);
13979 int different = 0;
13980 char *header1;
13982 if ((zerolength1 && !zerolength2) ||
13983 (zerolength2 && !zerolength1))
13984 return 1;
13986 if (zerolength1 && zerolength2)
13987 return 0;
13989 /* At this point, we can definitively state that both inputs are
13990 * not zero-length. First, one more optimization. If the length
13991 * of the headers is not equal, then we definitely have no match
13993 if (strlen(headers1) != strlen(headers2)) {
13994 return 1;
13997 for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
13998 if (!strcasestr(headers2, header1)) {
13999 different = 1;
14000 break;
14004 return different;
14007 static int sip_uri_cmp(const char *input1, const char *input2)
14009 char *uri1 = ast_strdupa(input1);
14010 char *uri2 = ast_strdupa(input2);
14011 char *host1;
14012 char *host2;
14013 char *params1;
14014 char *params2;
14015 char *headers1;
14016 char *headers2;
14018 /* Strip off "sip:" from the URI. We know this is present
14019 * because it was checked back in parse_request()
14021 strsep(&uri1, ":");
14022 strsep(&uri2, ":");
14024 if ((host1 = strchr(uri1, '@'))) {
14025 *host1++ = '\0';
14027 if ((host2 = strchr(uri2, '@'))) {
14028 *host2++ = '\0';
14031 /* Check for mismatched username and passwords. This is the
14032 * only case-sensitive comparison of a SIP URI
14034 if ((host1 && !host2) ||
14035 (host2 && !host1) ||
14036 (host1 && host2 && strcmp(uri1, uri2))) {
14037 return 1;
14040 if (!host1)
14041 host1 = uri1;
14042 if (!host2)
14043 host2 = uri2;
14045 /* Strip off the parameters and headers so we can compare
14046 * host and port
14049 if ((params1 = strchr(host1, ';'))) {
14050 *params1++ = '\0';
14052 if ((params2 = strchr(host2, ';'))) {
14053 *params2++ = '\0';
14056 /* Headers come after parameters, but there may be headers without
14057 * parameters, thus the S_OR
14059 if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
14060 *headers1++ = '\0';
14062 if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
14063 *headers2++ = '\0';
14066 /* Now the host/port are properly isolated. We can get by with a string comparison
14067 * because the SIP URI checking rules have some interesting exceptions that make
14068 * this possible. I will note 2 in particular
14069 * 1. hostnames which resolve to the same IP address as well as a hostname and its
14070 * IP address are not considered a match with SIP URI's.
14071 * 2. If one URI specifies a port and the other does not, then the URIs do not match.
14072 * This includes if one URI explicitly contains port 5060 and the other implies it
14073 * by not having a port specified.
14076 if (strcasecmp(host1, host2)) {
14077 return 1;
14080 /* Headers have easier rules to follow, so do those first */
14081 if (sip_uri_headers_cmp(headers1, headers2)) {
14082 return 1;
14085 /* And now the parameters. Ugh */
14086 return sip_uri_params_cmp(params1, params2);
14090 /*! \brief Handle incoming INVITE request
14091 \note If the INVITE has a Replaces header, it is part of an
14092 * attended transfer. If so, we do not go through the dial
14093 * plan but tries to find the active call and masquerade
14094 * into it
14096 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)
14098 int res = 1;
14099 int gotdest;
14100 const char *p_replaces;
14101 char *replace_id = NULL;
14102 const char *required;
14103 unsigned int required_profile = 0;
14104 struct ast_channel *c = NULL; /* New channel */
14105 int reinvite = 0;
14107 /* Find out what they support */
14108 if (!p->sipoptions) {
14109 const char *supported = get_header(req, "Supported");
14110 if (!ast_strlen_zero(supported))
14111 parse_sip_options(p, supported);
14114 /* Find out what they require */
14115 required = get_header(req, "Require");
14116 if (!ast_strlen_zero(required)) {
14117 required_profile = parse_sip_options(NULL, required);
14118 if (required_profile && required_profile != SIP_OPT_REPLACES) {
14119 /* At this point we only support REPLACES */
14120 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
14121 ast_log(LOG_WARNING,"Received SIP INVITE with unsupported required extension: %s\n", required);
14122 p->invitestate = INV_COMPLETED;
14123 if (!p->lastinvite)
14124 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14125 return -1;
14129 /* Check if this is a loop */
14130 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->owner->_state != AST_STATE_UP)) {
14131 /* This is a call to ourself. Send ourselves an error code and stop
14132 processing immediately, as SIP really has no good mechanism for
14133 being able to call yourself */
14134 /* If pedantic is on, we need to check the tags. If they're different, this is
14135 in fact a forked call through a SIP proxy somewhere. */
14136 int different;
14137 if (pedanticsipchecking)
14138 different = sip_uri_cmp(p->initreq.rlPart2, req->rlPart2);
14139 else
14140 different = strcmp(p->initreq.rlPart2, req->rlPart2);
14141 if (!different) {
14142 transmit_response(p, "482 Loop Detected", req);
14143 p->invitestate = INV_COMPLETED;
14144 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14145 return 0;
14146 } else {
14147 /* This is a spiral. What we need to do is to just change the outgoing INVITE
14148 * so that it now routes to the new Request URI. Since we created the INVITE ourselves
14149 * that should be all we need to do.
14151 char *uri = ast_strdupa(req->rlPart2);
14152 char *at = strchr(uri, '@');
14153 char *peerorhost;
14154 struct sip_pkt *pkt = NULL;
14155 if (option_debug > 2) {
14156 ast_log(LOG_DEBUG, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", p->initreq.rlPart2, req->rlPart2);
14158 if (at) {
14159 *at = '\0';
14161 /* Parse out "sip:" */
14162 if ((peerorhost = strchr(uri, ':'))) {
14163 *peerorhost++ = '\0';
14165 create_addr(p, peerorhost);
14166 ast_string_field_free(p, theirtag);
14167 for (pkt = p->packets; pkt; pkt = pkt->next) {
14168 if (pkt->seqno == p->icseq && pkt->method == SIP_INVITE) {
14169 AST_SCHED_DEL(sched, pkt->retransid);
14172 return transmit_invite(p, SIP_INVITE, 1, 3);
14176 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->pendinginvite) {
14177 /* We already have a pending invite. Sorry. You are on hold. */
14178 transmit_response_reliable(p, "491 Request Pending", req);
14179 if (option_debug)
14180 ast_log(LOG_DEBUG, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
14181 /* Don't destroy dialog here */
14182 return 0;
14185 p_replaces = get_header(req, "Replaces");
14186 if (!ast_strlen_zero(p_replaces)) {
14187 /* We have a replaces header */
14188 char *ptr;
14189 char *fromtag = NULL;
14190 char *totag = NULL;
14191 char *start, *to;
14192 int error = 0;
14194 if (p->owner) {
14195 if (option_debug > 2)
14196 ast_log(LOG_DEBUG, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
14197 transmit_response_reliable(p, "400 Bad request", req); /* The best way to not not accept the transfer */
14198 /* Do not destroy existing call */
14199 return -1;
14202 if (sipdebug && option_debug > 2)
14203 ast_log(LOG_DEBUG, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
14204 /* Create a buffer we can manipulate */
14205 replace_id = ast_strdupa(p_replaces);
14206 ast_uri_decode(replace_id);
14208 if (!p->refer && !sip_refer_allocate(p)) {
14209 transmit_response_reliable(p, "500 Server Internal Error", req);
14210 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
14211 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14212 p->invitestate = INV_COMPLETED;
14213 return -1;
14216 /* Todo: (When we find phones that support this)
14217 if the replaces header contains ";early-only"
14218 we can only replace the call in early
14219 stage, not after it's up.
14221 If it's not in early mode, 486 Busy.
14224 /* Skip leading whitespace */
14225 replace_id = ast_skip_blanks(replace_id);
14227 start = replace_id;
14228 while ( (ptr = strsep(&start, ";")) ) {
14229 ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
14230 if ( (to = strcasestr(ptr, "to-tag=") ) )
14231 totag = to + 7; /* skip the keyword */
14232 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
14233 fromtag = to + 9; /* skip the keyword */
14234 fromtag = strsep(&fromtag, "&"); /* trim what ? */
14238 if (sipdebug && option_debug > 3)
14239 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>");
14242 /* Try to find call that we are replacing
14243 If we have a Replaces header, we need to cancel that call if we succeed with this call
14245 if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
14246 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
14247 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
14248 error = 1;
14251 /* At this point, bot the pvt and the owner of the call to be replaced is locked */
14253 /* The matched call is the call from the transferer to Asterisk .
14254 We want to bridge the bridged part of the call to the
14255 incoming invite, thus taking over the refered call */
14257 if (p->refer->refer_call == p) {
14258 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
14259 p->refer->refer_call = NULL;
14260 transmit_response_reliable(p, "400 Bad request", req); /* The best way to not not accept the transfer */
14261 error = 1;
14264 if (!error && !p->refer->refer_call->owner) {
14265 /* Oops, someting wrong anyway, no owner, no call */
14266 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
14267 /* Check for better return code */
14268 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
14269 error = 1;
14272 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 ) {
14273 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
14274 transmit_response_reliable(p, "603 Declined (Replaces)", req);
14275 error = 1;
14278 if (error) { /* Give up this dialog */
14279 append_history(p, "Xfer", "INVITE/Replace Failed.");
14280 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14281 ast_mutex_unlock(&p->lock);
14282 if (p->refer->refer_call) {
14283 ast_mutex_unlock(&p->refer->refer_call->lock);
14284 ast_channel_unlock(p->refer->refer_call->owner);
14286 p->invitestate = INV_COMPLETED;
14287 return -1;
14292 /* Check if this is an INVITE that sets up a new dialog or
14293 a re-invite in an existing dialog */
14295 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
14296 int newcall = (p->initreq.headers ? TRUE : FALSE);
14298 if (sip_cancel_destroy(p))
14299 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
14300 /* This also counts as a pending invite */
14301 p->pendinginvite = seqno;
14302 check_via(p, req);
14304 copy_request(&p->initreq, req); /* Save this INVITE as the transaction basis */
14305 if (!p->owner) { /* Not a re-invite */
14306 if (debug)
14307 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
14308 if (newcall)
14309 append_history(p, "Invite", "New call: %s", p->callid);
14310 parse_ok_contact(p, req);
14311 } else { /* Re-invite on existing call */
14312 ast_clear_flag(&p->flags[0], SIP_OUTGOING); /* This is now an inbound dialog */
14313 /* Handle SDP here if we already have an owner */
14314 if (find_sdp(req)) {
14315 if (process_sdp(p, req)) {
14316 transmit_response_reliable(p, "488 Not acceptable here", req);
14317 if (!p->lastinvite)
14318 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14319 return -1;
14321 } else {
14322 p->jointcapability = p->capability;
14323 if (option_debug > 2)
14324 ast_log(LOG_DEBUG, "Hm.... No sdp for the moment\n");
14325 /* Some devices signal they want to be put off hold by sending a re-invite
14326 *without* an SDP, which is supposed to mean "Go back to your state"
14327 and since they put os on remote hold, we go back to off hold */
14328 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
14329 change_hold_state(p, req, FALSE, 0);
14331 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) /* This is a response, note what it was for */
14332 append_history(p, "ReInv", "Re-invite received");
14334 } else if (debug)
14335 ast_verbose("Ignoring this INVITE request\n");
14338 if (!p->lastinvite && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner) {
14339 /* This is a new invite */
14340 /* Handle authentication if this is our first invite */
14341 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
14342 if (res == AUTH_CHALLENGE_SENT) {
14343 p->invitestate = INV_COMPLETED; /* Needs to restart in another INVITE transaction */
14344 return 0;
14346 if (res < 0) { /* Something failed in authentication */
14347 if (res == AUTH_FAKE_AUTH) {
14348 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
14349 transmit_fake_auth_response(p, req, 1);
14350 } else {
14351 ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
14352 transmit_response_reliable(p, "403 Forbidden", req);
14354 p->invitestate = INV_COMPLETED;
14355 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14356 ast_string_field_free(p, theirtag);
14357 return 0;
14360 /* We have a succesful authentication, process the SDP portion if there is one */
14361 if (find_sdp(req)) {
14362 if (process_sdp(p, req)) {
14363 /* Unacceptable codecs */
14364 transmit_response_reliable(p, "488 Not acceptable here", req);
14365 p->invitestate = INV_COMPLETED;
14366 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14367 if (option_debug)
14368 ast_log(LOG_DEBUG, "No compatible codecs for this SIP call.\n");
14369 return -1;
14371 } else { /* No SDP in invite, call control session */
14372 p->jointcapability = p->capability;
14373 if (option_debug > 1)
14374 ast_log(LOG_DEBUG, "No SDP in Invite, third party call control\n");
14377 /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
14378 /* This seems redundant ... see !p-owner above */
14379 if (p->owner)
14380 ast_queue_frame(p->owner, &ast_null_frame);
14383 /* Initialize the context if it hasn't been already */
14384 if (ast_strlen_zero(p->context))
14385 ast_string_field_set(p, context, default_context);
14388 /* Check number of concurrent calls -vs- incoming limit HERE */
14389 if (option_debug)
14390 ast_log(LOG_DEBUG, "Checking SIP call limits for device %s\n", p->username);
14391 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
14392 if (res < 0) {
14393 ast_log(LOG_NOTICE, "Failed to place call for user %s, too many calls\n", p->username);
14394 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
14395 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14396 p->invitestate = INV_COMPLETED;
14398 return 0;
14400 gotdest = get_destination(p, NULL); /* Get destination right away */
14401 get_rdnis(p, NULL); /* Get redirect information */
14402 extract_uri(p, req); /* Get the Contact URI */
14403 build_contact(p); /* Build our contact header */
14405 if (p->rtp) {
14406 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
14407 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
14410 if (!replace_id && gotdest) { /* No matching extension found */
14411 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
14412 transmit_response_reliable(p, "484 Address Incomplete", req);
14413 else {
14414 char *decoded_exten = ast_strdupa(p->exten);
14416 transmit_response_reliable(p, "404 Not Found", req);
14417 ast_uri_decode(decoded_exten);
14418 ast_log(LOG_NOTICE, "Call from '%s' to extension"
14419 " '%s' rejected because extension not found.\n",
14420 S_OR(p->username, p->peername), decoded_exten);
14422 p->invitestate = INV_COMPLETED;
14423 update_call_counter(p, DEC_CALL_LIMIT);
14424 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14425 return 0;
14426 } else {
14427 /* If no extension was specified, use the s one */
14428 /* Basically for calling to IP/Host name only */
14429 if (ast_strlen_zero(p->exten))
14430 ast_string_field_set(p, exten, "s");
14431 /* Initialize our tag */
14433 make_our_tag(p->tag, sizeof(p->tag));
14434 /* First invitation - create the channel */
14435 c = sip_new(p, AST_STATE_DOWN, S_OR(p->username, NULL));
14436 *recount = 1;
14438 /* Save Record-Route for any later requests we make on this dialogue */
14439 build_route(p, req, 0);
14441 if (c) {
14442 /* Pre-lock the call */
14443 ast_channel_lock(c);
14446 } else {
14447 if (option_debug > 1 && sipdebug) {
14448 if (!ast_test_flag(req, SIP_PKT_IGNORE))
14449 ast_log(LOG_DEBUG, "Got a SIP re-invite for call %s\n", p->callid);
14450 else
14451 ast_log(LOG_DEBUG, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
14453 if (!ast_test_flag(req, SIP_PKT_IGNORE))
14454 reinvite = 1;
14455 c = p->owner;
14458 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
14459 p->lastinvite = seqno;
14461 if (replace_id) { /* Attended transfer or call pickup - we're the target */
14462 /* Go and take over the target call */
14463 if (sipdebug && option_debug > 3)
14464 ast_log(LOG_DEBUG, "Sending this call to the invite/replcaes handler %s\n", p->callid);
14465 return handle_invite_replaces(p, req, debug, ast_test_flag(req, SIP_PKT_IGNORE), seqno, sin);
14469 if (c) { /* We have a call -either a new call or an old one (RE-INVITE) */
14470 switch(c->_state) {
14471 case AST_STATE_DOWN:
14472 if (option_debug > 1)
14473 ast_log(LOG_DEBUG, "%s: New call is still down.... Trying... \n", c->name);
14474 transmit_response(p, "100 Trying", req);
14475 p->invitestate = INV_PROCEEDING;
14476 ast_setstate(c, AST_STATE_RING);
14477 if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
14478 enum ast_pbx_result res;
14480 res = ast_pbx_start(c);
14482 switch(res) {
14483 case AST_PBX_FAILED:
14484 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
14485 p->invitestate = INV_COMPLETED;
14486 if (ast_test_flag(req, SIP_PKT_IGNORE))
14487 transmit_response(p, "503 Unavailable", req);
14488 else
14489 transmit_response_reliable(p, "503 Unavailable", req);
14490 break;
14491 case AST_PBX_CALL_LIMIT:
14492 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
14493 p->invitestate = INV_COMPLETED;
14494 if (ast_test_flag(req, SIP_PKT_IGNORE))
14495 transmit_response(p, "480 Temporarily Unavailable", req);
14496 else
14497 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
14498 break;
14499 case AST_PBX_SUCCESS:
14500 /* nothing to do */
14501 break;
14504 if (res) {
14506 /* Unlock locks so ast_hangup can do its magic */
14507 ast_mutex_unlock(&c->lock);
14508 ast_mutex_unlock(&p->lock);
14509 ast_hangup(c);
14510 ast_mutex_lock(&p->lock);
14511 c = NULL;
14513 } else { /* Pickup call in call group */
14514 ast_channel_unlock(c);
14515 *nounlock = 1;
14516 if (ast_pickup_call(c)) {
14517 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
14518 if (ast_test_flag(req, SIP_PKT_IGNORE))
14519 transmit_response(p, "503 Unavailable", req); /* OEJ - Right answer? */
14520 else
14521 transmit_response_reliable(p, "503 Unavailable", req);
14522 sip_alreadygone(p);
14523 /* Unlock locks so ast_hangup can do its magic */
14524 ast_mutex_unlock(&p->lock);
14525 c->hangupcause = AST_CAUSE_CALL_REJECTED;
14526 } else {
14527 ast_mutex_unlock(&p->lock);
14528 ast_setstate(c, AST_STATE_DOWN);
14529 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
14531 p->invitestate = INV_COMPLETED;
14532 ast_hangup(c);
14533 ast_mutex_lock(&p->lock);
14534 c = NULL;
14536 break;
14537 case AST_STATE_RING:
14538 transmit_response(p, "100 Trying", req);
14539 p->invitestate = INV_PROCEEDING;
14540 break;
14541 case AST_STATE_RINGING:
14542 transmit_response(p, "180 Ringing", req);
14543 p->invitestate = INV_PROCEEDING;
14544 break;
14545 case AST_STATE_UP:
14546 if (option_debug > 1)
14547 ast_log(LOG_DEBUG, "%s: This call is UP.... \n", c->name);
14549 transmit_response(p, "100 Trying", req);
14551 if (p->t38.state == T38_PEER_REINVITE) {
14552 struct ast_channel *bridgepeer = NULL;
14553 struct sip_pvt *bridgepvt = NULL;
14555 if ((bridgepeer = ast_bridged_channel(p->owner))) {
14556 /* 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*/
14557 /*! XXX: we should also check here does the other side supports t38 at all !!! XXX */
14558 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
14559 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
14560 if (bridgepvt->t38.state == T38_DISABLED) {
14561 if (bridgepvt->udptl) { /* If everything is OK with other side's udptl struct */
14562 /* Send re-invite to the bridged channel */
14563 sip_handle_t38_reinvite(bridgepeer, p, 1);
14564 } else { /* Something is wrong with peers udptl struct */
14565 ast_log(LOG_WARNING, "Strange... The other side of the bridge don't have udptl struct\n");
14566 ast_mutex_lock(&bridgepvt->lock);
14567 bridgepvt->t38.state = T38_DISABLED;
14568 ast_mutex_unlock(&bridgepvt->lock);
14569 if (option_debug > 1)
14570 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->name);
14571 if (ast_test_flag(req, SIP_PKT_IGNORE))
14572 transmit_response(p, "488 Not acceptable here", req);
14573 else
14574 transmit_response_reliable(p, "488 Not acceptable here", req);
14577 } else {
14578 /* The other side is already setup for T.38 most likely so we need to acknowledge this too */
14579 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
14580 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
14581 p->t38.state = T38_ENABLED;
14582 if (option_debug)
14583 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14585 } else {
14586 /* Other side is not a SIP channel */
14587 if (ast_test_flag(req, SIP_PKT_IGNORE))
14588 transmit_response(p, "488 Not acceptable here", req);
14589 else
14590 transmit_response_reliable(p, "488 Not acceptable here", req);
14591 p->t38.state = T38_DISABLED;
14592 if (option_debug > 1)
14593 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14595 if (!p->lastinvite) /* Only destroy if this is *not* a re-invite */
14596 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14598 } else {
14599 /* we are not bridged in a call */
14600 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
14601 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
14602 p->t38.state = T38_ENABLED;
14603 if (option_debug)
14604 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14606 } else if (p->t38.state == T38_DISABLED) { /* Channel doesn't have T38 offered or enabled */
14607 int sendok = TRUE;
14609 /* If we are bridged to a channel that has T38 enabled than this is a case of RTP re-invite after T38 session */
14610 /* so handle it here (re-invite other party to RTP) */
14611 struct ast_channel *bridgepeer = NULL;
14612 struct sip_pvt *bridgepvt = NULL;
14613 if ((bridgepeer = ast_bridged_channel(p->owner))) {
14614 if ((bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) && !ast_check_hangup(bridgepeer)) {
14615 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
14616 /* Does the bridged peer have T38 ? */
14617 if (bridgepvt->t38.state == T38_ENABLED) {
14618 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
14619 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
14620 if (ast_test_flag(req, SIP_PKT_IGNORE))
14621 transmit_response(p, "488 Not Acceptable Here (unsupported)", req);
14622 else
14623 transmit_response_reliable(p, "488 Not Acceptable Here (unsupported)", req);
14624 sendok = FALSE;
14626 /* No bridged peer with T38 enabled*/
14629 /* Respond to normal re-invite */
14630 if (sendok) {
14631 /* If this is not a re-invite or something to ignore - it's critical */
14632 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
14633 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (ast_test_flag(req, SIP_PKT_IGNORE) ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
14636 p->invitestate = INV_TERMINATED;
14637 break;
14638 default:
14639 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
14640 transmit_response(p, "100 Trying", req);
14641 break;
14643 } else {
14644 if (p && (p->autokillid == -1)) {
14645 const char *msg;
14647 if (!p->jointcapability)
14648 msg = "488 Not Acceptable Here (codec error)";
14649 else {
14650 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
14651 msg = "503 Unavailable";
14653 if (ast_test_flag(req, SIP_PKT_IGNORE))
14654 transmit_response(p, msg, req);
14655 else
14656 transmit_response_reliable(p, msg, req);
14657 p->invitestate = INV_COMPLETED;
14658 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14661 return res;
14664 /*! \brief Find all call legs and bridge transferee with target
14665 * called from handle_request_refer */
14666 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
14668 struct sip_dual target; /* Chan 1: Call from tranferer to Asterisk */
14669 /* Chan 2: Call from Asterisk to target */
14670 int res = 0;
14671 struct sip_pvt *targetcall_pvt;
14673 /* Check if the call ID of the replaces header does exist locally */
14674 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
14675 transferer->refer->replaces_callid_fromtag))) {
14676 if (transferer->refer->localtransfer) {
14677 /* We did not find the refered call. Sorry, can't accept then */
14678 transmit_response(transferer, "202 Accepted", req);
14679 /* Let's fake a response from someone else in order
14680 to follow the standard */
14681 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
14682 append_history(transferer, "Xfer", "Refer failed");
14683 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
14684 transferer->refer->status = REFER_FAILED;
14685 return -1;
14687 /* Fall through for remote transfers that we did not find locally */
14688 if (option_debug > 2)
14689 ast_log(LOG_DEBUG, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
14690 return 0;
14693 /* Ok, we can accept this transfer */
14694 transmit_response(transferer, "202 Accepted", req);
14695 append_history(transferer, "Xfer", "Refer accepted");
14696 if (!targetcall_pvt->owner) { /* No active channel */
14697 if (option_debug > 3)
14698 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No owner of target call\n");
14699 /* Cancel transfer */
14700 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
14701 append_history(transferer, "Xfer", "Refer failed");
14702 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
14703 transferer->refer->status = REFER_FAILED;
14704 ast_mutex_unlock(&targetcall_pvt->lock);
14705 ast_channel_unlock(current->chan1);
14706 return -1;
14709 /* We have a channel, find the bridge */
14710 target.chan1 = targetcall_pvt->owner; /* Transferer to Asterisk */
14711 target.chan2 = ast_bridged_channel(targetcall_pvt->owner); /* Asterisk to target */
14713 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
14714 /* Wrong state of new channel */
14715 if (option_debug > 3) {
14716 if (target.chan2)
14717 ast_log(LOG_DEBUG, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
14718 else if (target.chan1->_state != AST_STATE_RING)
14719 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No target channel\n");
14720 else
14721 ast_log(LOG_DEBUG, "SIP attended transfer: Attempting transfer in ringing state\n");
14725 /* Transfer */
14726 if (option_debug > 3 && sipdebug) {
14727 if (current->chan2) /* We have two bridges */
14728 ast_log(LOG_DEBUG, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
14729 else /* One bridge, propably transfer of IVR/voicemail etc */
14730 ast_log(LOG_DEBUG, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
14733 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
14735 /* Perform the transfer */
14736 res = attempt_transfer(current, &target);
14737 ast_mutex_unlock(&targetcall_pvt->lock);
14738 if (res) {
14739 /* Failed transfer */
14740 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
14741 append_history(transferer, "Xfer", "Refer failed");
14742 transferer->refer->status = REFER_FAILED;
14743 if (targetcall_pvt->owner)
14744 ast_channel_unlock(targetcall_pvt->owner);
14745 /* Right now, we have to hangup, sorry. Bridge is destroyed */
14746 if (res != -2)
14747 ast_hangup(transferer->owner);
14748 else
14749 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
14750 } else {
14751 /* Transfer succeeded! */
14753 /* Tell transferer that we're done. */
14754 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
14755 append_history(transferer, "Xfer", "Refer succeeded");
14756 transferer->refer->status = REFER_200OK;
14757 if (targetcall_pvt->owner) {
14758 if (option_debug)
14759 ast_log(LOG_DEBUG, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
14760 ast_channel_unlock(targetcall_pvt->owner);
14763 return 1;
14767 /*! \brief Handle incoming REFER request */
14768 /*! \page SIP_REFER SIP transfer Support (REFER)
14770 REFER is used for call transfer in SIP. We get a REFER
14771 to place a new call with an INVITE somwhere and then
14772 keep the transferor up-to-date of the transfer. If the
14773 transfer fails, get back on line with the orginal call.
14775 - REFER can be sent outside or inside of a dialog.
14776 Asterisk only accepts REFER inside of a dialog.
14778 - If we get a replaces header, it is an attended transfer
14780 \par Blind transfers
14781 The transferor provides the transferee
14782 with the transfer targets contact. The signalling between
14783 transferer or transferee should not be cancelled, so the
14784 call is recoverable if the transfer target can not be reached
14785 by the transferee.
14787 In this case, Asterisk receives a TRANSFER from
14788 the transferor, thus is the transferee. We should
14789 try to set up a call to the contact provided
14790 and if that fails, re-connect the current session.
14791 If the new call is set up, we issue a hangup.
14792 In this scenario, we are following section 5.2
14793 in the SIP CC Transfer draft. (Transfer without
14794 a GRUU)
14796 \par Transfer with consultation hold
14797 In this case, the transferor
14798 talks to the transfer target before the transfer takes place.
14799 This is implemented with SIP hold and transfer.
14800 Note: The invite From: string could indicate a transfer.
14801 (Section 6. Transfer with consultation hold)
14802 The transferor places the transferee on hold, starts a call
14803 with the transfer target to alert them to the impending
14804 transfer, terminates the connection with the target, then
14805 proceeds with the transfer (as in Blind transfer above)
14807 \par Attended transfer
14808 The transferor places the transferee
14809 on hold, calls the transfer target to alert them,
14810 places the target on hold, then proceeds with the transfer
14811 using a Replaces header field in the Refer-to header. This
14812 will force the transfee to send an Invite to the target,
14813 with a replaces header that instructs the target to
14814 hangup the call between the transferor and the target.
14815 In this case, the Refer/to: uses the AOR address. (The same
14816 URI that the transferee used to establish the session with
14817 the transfer target (To: ). The Require: replaces header should
14818 be in the INVITE to avoid the wrong UA in a forked SIP proxy
14819 scenario to answer and have no call to replace with.
14821 The referred-by header is *NOT* required, but if we get it,
14822 can be copied into the INVITE to the transfer target to
14823 inform the target about the transferor
14825 "Any REFER request has to be appropriately authenticated.".
14827 We can't destroy dialogs, since we want the call to continue.
14830 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock)
14832 struct sip_dual current; /* Chan1: Call between asterisk and transferer */
14833 /* Chan2: Call between asterisk and transferee */
14835 int res = 0;
14837 if (ast_test_flag(req, SIP_PKT_DEBUG))
14838 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");
14840 if (!p->owner) {
14841 /* This is a REFER outside of an existing SIP dialog */
14842 /* We can't handle that, so decline it */
14843 if (option_debug > 2)
14844 ast_log(LOG_DEBUG, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
14845 transmit_response(p, "603 Declined (No dialog)", req);
14846 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
14847 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
14848 sip_alreadygone(p);
14849 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14851 return 0;
14855 /* Check if transfer is allowed from this device */
14856 if (p->allowtransfer == TRANSFER_CLOSED ) {
14857 /* Transfer not allowed, decline */
14858 transmit_response(p, "603 Declined (policy)", req);
14859 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
14860 /* Do not destroy SIP session */
14861 return 0;
14864 if(!ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
14865 /* Already have a pending REFER */
14866 transmit_response(p, "491 Request pending", req);
14867 append_history(p, "Xfer", "Refer failed. Request pending.");
14868 return 0;
14871 /* Allocate memory for call transfer data */
14872 if (!p->refer && !sip_refer_allocate(p)) {
14873 transmit_response(p, "500 Internal Server Error", req);
14874 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
14875 return -3;
14878 res = get_refer_info(p, req); /* Extract headers */
14880 p->refer->status = REFER_SENT;
14882 if (res != 0) {
14883 switch (res) {
14884 case -2: /* Syntax error */
14885 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
14886 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
14887 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14888 ast_log(LOG_DEBUG, "SIP transfer to black hole can't be handled (no refer-to: )\n");
14889 break;
14890 case -3:
14891 transmit_response(p, "603 Declined (Non sip: uri)", req);
14892 append_history(p, "Xfer", "Refer failed. Non SIP uri");
14893 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14894 ast_log(LOG_DEBUG, "SIP transfer to non-SIP uri denied\n");
14895 break;
14896 default:
14897 /* Refer-to extension not found, fake a failed transfer */
14898 transmit_response(p, "202 Accepted", req);
14899 append_history(p, "Xfer", "Refer failed. Bad extension.");
14900 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
14901 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14902 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14903 ast_log(LOG_DEBUG, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
14904 break;
14906 return 0;
14908 if (ast_strlen_zero(p->context))
14909 ast_string_field_set(p, context, default_context);
14911 /* If we do not support SIP domains, all transfers are local */
14912 if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
14913 p->refer->localtransfer = 1;
14914 if (sipdebug && option_debug > 2)
14915 ast_log(LOG_DEBUG, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
14916 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
14917 /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
14918 p->refer->localtransfer = 1;
14919 } else if (sipdebug && option_debug > 2)
14920 ast_log(LOG_DEBUG, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
14922 /* Is this a repeat of a current request? Ignore it */
14923 /* Don't know what else to do right now. */
14924 if (ignore)
14925 return res;
14927 /* If this is a blind transfer, we have the following
14928 channels to work with:
14929 - chan1, chan2: The current call between transferer and transferee (2 channels)
14930 - target_channel: A new call from the transferee to the target (1 channel)
14931 We need to stay tuned to what happens in order to be able
14932 to bring back the call to the transferer */
14934 /* If this is a attended transfer, we should have all call legs within reach:
14935 - chan1, chan2: The call between the transferer and transferee (2 channels)
14936 - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
14937 We want to bridge chan2 with targetcall_pvt!
14939 The replaces call id in the refer message points
14940 to the call leg between Asterisk and the transferer.
14941 So we need to connect the target and the transferee channel
14942 and hangup the two other channels silently
14944 If the target is non-local, the call ID could be on a remote
14945 machine and we need to send an INVITE with replaces to the
14946 target. We basically handle this as a blind transfer
14947 and let the sip_call function catch that we need replaces
14948 header in the INVITE.
14952 /* Get the transferer's channel */
14953 current.chan1 = p->owner;
14955 /* Find the other part of the bridge (2) - transferee */
14956 current.chan2 = ast_bridged_channel(current.chan1);
14958 if (sipdebug && option_debug > 2)
14959 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>");
14961 if (!current.chan2 && !p->refer->attendedtransfer) {
14962 /* No bridged channel, propably IVR or echo or similar... */
14963 /* Guess we should masquerade or something here */
14964 /* Until we figure it out, refuse transfer of such calls */
14965 if (sipdebug && option_debug > 2)
14966 ast_log(LOG_DEBUG,"Refused SIP transfer on non-bridged channel.\n");
14967 p->refer->status = REFER_FAILED;
14968 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
14969 transmit_response(p, "603 Declined", req);
14970 return -1;
14973 if (current.chan2) {
14974 if (sipdebug && option_debug > 3)
14975 ast_log(LOG_DEBUG, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
14977 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
14980 ast_set_flag(&p->flags[0], SIP_GOTREFER);
14982 /* Attended transfer: Find all call legs and bridge transferee with target*/
14983 if (p->refer->attendedtransfer) {
14984 if ((res = local_attended_transfer(p, &current, req, seqno)))
14985 return res; /* We're done with the transfer */
14986 /* Fall through for remote transfers that we did not find locally */
14987 if (sipdebug && option_debug > 3)
14988 ast_log(LOG_DEBUG, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
14989 /* Fallthrough if we can't find the call leg internally */
14993 /* Parking a call */
14994 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
14995 /* Must release c's lock now, because it will not longer be accessible after the transfer! */
14996 *nounlock = 1;
14997 ast_channel_unlock(current.chan1);
14998 copy_request(&current.req, req);
14999 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
15000 p->refer->status = REFER_200OK;
15001 append_history(p, "Xfer", "REFER to call parking.");
15002 if (sipdebug && option_debug > 3)
15003 ast_log(LOG_DEBUG, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
15004 sip_park(current.chan2, current.chan1, req, seqno);
15005 return res;
15008 /* Blind transfers and remote attended xfers */
15009 transmit_response(p, "202 Accepted", req);
15011 if (current.chan1 && current.chan2) {
15012 if (option_debug > 2)
15013 ast_log(LOG_DEBUG, "chan1->name: %s\n", current.chan1->name);
15014 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
15016 if (current.chan2) {
15017 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
15018 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
15019 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
15020 /* One for the new channel */
15021 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
15022 /* Attended transfer to remote host, prepare headers for the INVITE */
15023 if (p->refer->referred_by)
15024 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
15026 /* Generate a Replaces string to be used in the INVITE during attended transfer */
15027 if (p->refer->replaces_callid && !ast_strlen_zero(p->refer->replaces_callid)) {
15028 char tempheader[SIPBUFSIZE];
15029 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
15030 p->refer->replaces_callid_totag ? ";to-tag=" : "",
15031 p->refer->replaces_callid_totag,
15032 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
15033 p->refer->replaces_callid_fromtag);
15034 if (current.chan2)
15035 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
15037 /* Must release lock now, because it will not longer
15038 be accessible after the transfer! */
15039 *nounlock = 1;
15040 ast_channel_unlock(current.chan1);
15042 /* Connect the call */
15044 /* FAKE ringing if not attended transfer */
15045 if (!p->refer->attendedtransfer)
15046 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
15048 /* For blind transfer, this will lead to a new call */
15049 /* For attended transfer to remote host, this will lead to
15050 a new SIP call with a replaces header, if the dial plan allows it
15052 if (!current.chan2) {
15053 /* We have no bridge, so we're talking with Asterisk somehow */
15054 /* We need to masquerade this call */
15055 /* What to do to fix this situation:
15056 * Set up the new call in a new channel
15057 * Let the new channel masq into this channel
15058 Please add that code here :-)
15060 p->refer->status = REFER_FAILED;
15061 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
15062 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
15063 append_history(p, "Xfer", "Refer failed (only bridged calls).");
15064 return -1;
15066 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
15068 /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
15069 servers - generate an INVITE with Replaces. Either way, let the dial plan decided */
15070 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
15072 if (!res) {
15073 /* Success - we have a new channel */
15074 if (option_debug > 2)
15075 ast_log(LOG_DEBUG, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
15076 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
15077 if (p->refer->localtransfer)
15078 p->refer->status = REFER_200OK;
15079 if (p->owner)
15080 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
15081 append_history(p, "Xfer", "Refer succeeded.");
15082 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
15083 /* Do not hangup call, the other side do that when we say 200 OK */
15084 /* We could possibly implement a timer here, auto congestion */
15085 res = 0;
15086 } else {
15087 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
15088 if (option_debug > 2)
15089 ast_log(LOG_DEBUG, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
15090 append_history(p, "Xfer", "Refer failed.");
15091 /* Failure of some kind */
15092 p->refer->status = REFER_FAILED;
15093 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
15094 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
15095 res = -1;
15097 return res;
15100 /*! \brief Handle incoming CANCEL request */
15101 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
15104 check_via(p, req);
15105 sip_alreadygone(p);
15107 /* At this point, we could have cancelled the invite at the same time
15108 as the other side sends a CANCEL. Our final reply with error code
15109 might not have been received by the other side before the CANCEL
15110 was sent, so let's just give up retransmissions and waiting for
15111 ACK on our error code. The call is hanging up any way. */
15112 if (p->invitestate == INV_TERMINATED)
15113 __sip_pretend_ack(p);
15114 else
15115 p->invitestate = INV_CANCELLED;
15117 if (p->owner && p->owner->_state == AST_STATE_UP) {
15118 /* This call is up, cancel is ignored, we need a bye */
15119 transmit_response(p, "200 OK", req);
15120 if (option_debug)
15121 ast_log(LOG_DEBUG, "Got CANCEL on an answered call. Ignoring... \n");
15122 return 0;
15125 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
15126 update_call_counter(p, DEC_CALL_LIMIT);
15128 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
15129 if (p->owner)
15130 ast_queue_hangup(p->owner);
15131 else
15132 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15133 if (p->initreq.len > 0) {
15134 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
15135 transmit_response(p, "200 OK", req);
15136 return 1;
15137 } else {
15138 transmit_response(p, "481 Call Leg Does Not Exist", req);
15139 return 0;
15143 static int acf_channel_read(struct ast_channel *chan, char *funcname, char *preparse, char *buf, size_t buflen)
15145 struct ast_rtp_quality qos;
15146 struct sip_pvt *p = chan->tech_pvt;
15147 char *all = "", *parse = ast_strdupa(preparse);
15148 AST_DECLARE_APP_ARGS(args,
15149 AST_APP_ARG(param);
15150 AST_APP_ARG(type);
15151 AST_APP_ARG(field);
15153 AST_STANDARD_APP_ARGS(args, parse);
15155 /* Sanity check */
15156 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
15157 ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
15158 return 0;
15161 if (strcasecmp(args.param, "rtpqos"))
15162 return 0;
15164 /* Default arguments of audio,all */
15165 if (ast_strlen_zero(args.type))
15166 args.type = "audio";
15167 if (ast_strlen_zero(args.field))
15168 args.field = "all";
15170 memset(buf, 0, buflen);
15171 memset(&qos, 0, sizeof(qos));
15173 if (strcasecmp(args.type, "AUDIO") == 0) {
15174 all = ast_rtp_get_quality(p->rtp, &qos);
15175 } else if (strcasecmp(args.type, "VIDEO") == 0) {
15176 all = ast_rtp_get_quality(p->vrtp, &qos);
15179 if (strcasecmp(args.field, "local_ssrc") == 0)
15180 snprintf(buf, buflen, "%u", qos.local_ssrc);
15181 else if (strcasecmp(args.field, "local_lostpackets") == 0)
15182 snprintf(buf, buflen, "%u", qos.local_lostpackets);
15183 else if (strcasecmp(args.field, "local_jitter") == 0)
15184 snprintf(buf, buflen, "%.0lf", qos.local_jitter * 1000.0);
15185 else if (strcasecmp(args.field, "local_count") == 0)
15186 snprintf(buf, buflen, "%u", qos.local_count);
15187 else if (strcasecmp(args.field, "remote_ssrc") == 0)
15188 snprintf(buf, buflen, "%u", qos.remote_ssrc);
15189 else if (strcasecmp(args.field, "remote_lostpackets") == 0)
15190 snprintf(buf, buflen, "%u", qos.remote_lostpackets);
15191 else if (strcasecmp(args.field, "remote_jitter") == 0)
15192 snprintf(buf, buflen, "%.0lf", qos.remote_jitter * 1000.0);
15193 else if (strcasecmp(args.field, "remote_count") == 0)
15194 snprintf(buf, buflen, "%u", qos.remote_count);
15195 else if (strcasecmp(args.field, "rtt") == 0)
15196 snprintf(buf, buflen, "%.0lf", qos.rtt * 1000.0);
15197 else if (strcasecmp(args.field, "all") == 0)
15198 ast_copy_string(buf, all, buflen);
15199 else {
15200 ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
15201 return -1;
15203 return 0;
15206 /*! \brief Handle incoming BYE request */
15207 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
15209 struct ast_channel *c=NULL;
15210 int res;
15211 struct ast_channel *bridged_to;
15213 /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
15214 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner)
15215 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
15217 __sip_pretend_ack(p);
15219 p->invitestate = INV_TERMINATED;
15221 copy_request(&p->initreq, req);
15222 check_via(p, req);
15223 sip_alreadygone(p);
15225 /* Get RTCP quality before end of call */
15226 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY) || p->owner) {
15227 char *audioqos, *videoqos;
15228 if (p->rtp) {
15229 audioqos = ast_rtp_get_quality(p->rtp, NULL);
15230 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
15231 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
15232 if (p->owner)
15233 pbx_builtin_setvar_helper(p->owner, "RTPAUDIOQOS", audioqos);
15235 if (p->vrtp) {
15236 videoqos = ast_rtp_get_quality(p->vrtp, NULL);
15237 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
15238 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
15239 if (p->owner)
15240 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
15244 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
15246 if (!ast_strlen_zero(get_header(req, "Also"))) {
15247 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
15248 ast_inet_ntoa(p->recv.sin_addr));
15249 if (ast_strlen_zero(p->context))
15250 ast_string_field_set(p, context, default_context);
15251 res = get_also_info(p, req);
15252 if (!res) {
15253 c = p->owner;
15254 if (c) {
15255 bridged_to = ast_bridged_channel(c);
15256 if (bridged_to) {
15257 /* Don't actually hangup here... */
15258 ast_queue_control(c, AST_CONTROL_UNHOLD);
15259 ast_async_goto(bridged_to, p->context, p->refer->refer_to,1);
15260 } else
15261 ast_queue_hangup(p->owner);
15263 } else {
15264 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
15265 if (p->owner)
15266 ast_queue_hangup(p->owner);
15268 } else if (p->owner) {
15269 ast_queue_hangup(p->owner);
15270 if (option_debug > 2)
15271 ast_log(LOG_DEBUG, "Received bye, issuing owner hangup\n");
15272 } else {
15273 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15274 if (option_debug > 2)
15275 ast_log(LOG_DEBUG, "Received bye, no owner, selfdestruct soon.\n");
15277 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
15278 transmit_response(p, "200 OK", req);
15280 return 1;
15283 /*! \brief Handle incoming MESSAGE request */
15284 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
15286 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
15287 if (ast_test_flag(req, SIP_PKT_DEBUG))
15288 ast_verbose("Receiving message!\n");
15289 receive_message(p, req);
15290 } else
15291 transmit_response(p, "202 Accepted", req);
15292 return 1;
15295 /*! \brief Handle incoming SUBSCRIBE request */
15296 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
15298 int gotdest;
15299 int res = 0;
15300 int firststate = AST_EXTENSION_REMOVED;
15301 struct sip_peer *authpeer = NULL;
15302 const char *eventheader = get_header(req, "Event"); /* Get Event package name */
15303 const char *accept = get_header(req, "Accept");
15304 int resubscribe = (p->subscribed != NONE);
15305 char *temp, *event;
15307 if (p->initreq.headers) {
15308 /* We already have a dialog */
15309 if (p->initreq.method != SIP_SUBSCRIBE) {
15310 /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
15311 /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
15312 transmit_response(p, "403 Forbidden (within dialog)", req);
15313 /* Do not destroy session, since we will break the call if we do */
15314 if (option_debug)
15315 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);
15316 return 0;
15317 } else if (ast_test_flag(req, SIP_PKT_DEBUG)) {
15318 if (option_debug) {
15319 if (resubscribe)
15320 ast_log(LOG_DEBUG, "Got a re-subscribe on existing subscription %s\n", p->callid);
15321 else
15322 ast_log(LOG_DEBUG, "Got a new subscription %s (possibly with auth)\n", p->callid);
15327 /* Check if we have a global disallow setting on subscriptions.
15328 if so, we don't have to check peer/user settings after auth, which saves a lot of processing
15330 if (!global_allowsubscribe) {
15331 transmit_response(p, "403 Forbidden (policy)", req);
15332 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15333 return 0;
15336 if (!ast_test_flag(req, SIP_PKT_IGNORE) && !resubscribe) { /* Set up dialog, new subscription */
15337 const char *to = get_header(req, "To");
15338 char totag[128];
15340 /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
15341 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
15342 if (ast_test_flag(req, SIP_PKT_DEBUG))
15343 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
15344 transmit_response(p, "481 Subscription does not exist", req);
15345 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15346 return 0;
15349 /* Use this as the basis */
15350 if (ast_test_flag(req, SIP_PKT_DEBUG))
15351 ast_verbose("Creating new subscription\n");
15353 copy_request(&p->initreq, req);
15354 check_via(p, req);
15355 } else if (ast_test_flag(req, SIP_PKT_DEBUG) && ast_test_flag(req, SIP_PKT_IGNORE))
15356 ast_verbose("Ignoring this SUBSCRIBE request\n");
15358 /* Find parameters to Event: header value and remove them for now */
15359 if (ast_strlen_zero(eventheader)) {
15360 transmit_response(p, "489 Bad Event", req);
15361 if (option_debug > 1)
15362 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: <none>\n");
15363 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15364 return 0;
15367 if ( (strchr(eventheader, ';'))) {
15368 event = ast_strdupa(eventheader); /* Since eventheader is a const, we can't change it */
15369 temp = strchr(event, ';');
15370 *temp = '\0'; /* Remove any options for now */
15371 /* We might need to use them later :-) */
15372 } else
15373 event = (char *) eventheader; /* XXX is this legal ? */
15375 /* Handle authentication */
15376 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
15377 /* if an authentication response was sent, we are done here */
15378 if (res == AUTH_CHALLENGE_SENT) {
15379 if (authpeer)
15380 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15381 return 0;
15383 if (res < 0) {
15384 if (res == AUTH_FAKE_AUTH) {
15385 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
15386 transmit_fake_auth_response(p, req, 1);
15387 } else {
15388 ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
15389 transmit_response_reliable(p, "403 Forbidden", req);
15391 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15392 if (authpeer)
15393 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15394 return 0;
15397 /* Check if this user/peer is allowed to subscribe at all */
15398 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
15399 transmit_response(p, "403 Forbidden (policy)", req);
15400 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15401 if (authpeer)
15402 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15403 return 0;
15406 /* Get destination right away */
15407 gotdest = get_destination(p, NULL);
15409 /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
15410 parse_ok_contact(p, req);
15412 build_contact(p);
15413 if (strcmp(event, "message-summary") && gotdest) {
15414 transmit_response(p, "404 Not Found", req);
15415 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15416 if (authpeer)
15417 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15418 return 0;
15421 /* Initialize tag for new subscriptions */
15422 if (ast_strlen_zero(p->tag))
15423 make_our_tag(p->tag, sizeof(p->tag));
15425 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
15426 if (authpeer) /* No need for authpeer here */
15427 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15429 /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
15430 /* Polycom phones only handle xpidf+xml, even if they say they can
15431 handle pidf+xml as well
15433 if (strstr(p->useragent, "Polycom")) {
15434 p->subscribed = XPIDF_XML;
15435 } else if (strstr(accept, "application/pidf+xml")) {
15436 p->subscribed = PIDF_XML; /* RFC 3863 format */
15437 } else if (strstr(accept, "application/dialog-info+xml")) {
15438 p->subscribed = DIALOG_INFO_XML;
15439 /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
15440 } else if (strstr(accept, "application/cpim-pidf+xml")) {
15441 p->subscribed = CPIM_PIDF_XML; /* RFC 3863 format */
15442 } else if (strstr(accept, "application/xpidf+xml")) {
15443 p->subscribed = XPIDF_XML; /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
15444 } else if (ast_strlen_zero(accept)) {
15445 if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
15446 transmit_response(p, "489 Bad Event", req);
15448 ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
15449 p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
15450 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15451 return 0;
15453 /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
15454 so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
15455 } else {
15456 /* Can't find a format for events that we know about */
15457 char mybuf[200];
15458 snprintf(mybuf,sizeof(mybuf),"489 Bad Event (format %s)", accept);
15459 transmit_response(p, mybuf, req);
15461 ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
15462 accept, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
15463 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15464 return 0;
15466 } else if (!strcmp(event, "message-summary")) {
15467 if (!ast_strlen_zero(accept) && strcmp(accept, "application/simple-message-summary")) {
15468 /* Format requested that we do not support */
15469 transmit_response(p, "406 Not Acceptable", req);
15470 if (option_debug > 1)
15471 ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", accept);
15472 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15473 if (authpeer) /* No need for authpeer here */
15474 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15475 return 0;
15477 /* Looks like they actually want a mailbox status
15478 This version of Asterisk supports mailbox subscriptions
15479 The subscribed URI needs to exist in the dial plan
15480 In most devices, this is configurable to the voicemailmain extension you use
15482 if (!authpeer || ast_strlen_zero(authpeer->mailbox)) {
15483 transmit_response(p, "404 Not found (no mailbox)", req);
15484 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15485 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
15486 if (authpeer) /* No need for authpeer here */
15487 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15488 return 0;
15491 p->subscribed = MWI_NOTIFICATION;
15492 if (authpeer->mwipvt && authpeer->mwipvt != p) /* Destroy old PVT if this is a new one */
15493 /* We only allow one subscription per peer */
15494 sip_destroy(authpeer->mwipvt);
15495 authpeer->mwipvt = p; /* Link from peer to pvt */
15496 p->relatedpeer = ASTOBJ_REF(authpeer); /* Link from pvt to peer */
15497 } else { /* At this point, Asterisk does not understand the specified event */
15498 transmit_response(p, "489 Bad Event", req);
15499 if (option_debug > 1)
15500 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: %s\n", event);
15501 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15502 if (authpeer) /* No need for authpeer here */
15503 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15504 return 0;
15507 if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
15508 if (p->stateid > -1)
15509 ast_extension_state_del(p->stateid, cb_extensionstate);
15510 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, p);
15513 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
15514 p->lastinvite = seqno;
15515 if (p && !ast_test_flag(&p->flags[0], SIP_NEEDDESTROY)) {
15516 p->expiry = atoi(get_header(req, "Expires"));
15518 /* check if the requested expiry-time is within the approved limits from sip.conf */
15519 if (p->expiry > max_expiry)
15520 p->expiry = max_expiry;
15521 if (p->expiry < min_expiry && p->expiry > 0)
15522 p->expiry = min_expiry;
15524 if (sipdebug || option_debug > 1) {
15525 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
15526 ast_log(LOG_DEBUG, "Adding subscription for mailbox notification - peer %s Mailbox %s\n", p->relatedpeer->name, p->relatedpeer->mailbox);
15527 else
15528 ast_log(LOG_DEBUG, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
15530 if (p->autokillid > -1 && sip_cancel_destroy(p)) /* Remove subscription expiry for renewals */
15531 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15532 if (p->expiry > 0)
15533 sip_scheddestroy(p, (p->expiry + 10) * 1000); /* Set timer for destruction of call at expiration */
15535 if (p->subscribed == MWI_NOTIFICATION) {
15536 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
15537 transmit_response(p, "200 OK", req);
15538 if (p->relatedpeer) { /* Send first notification */
15539 ASTOBJ_WRLOCK(p->relatedpeer);
15540 sip_send_mwi_to_peer(p->relatedpeer);
15541 ASTOBJ_UNLOCK(p->relatedpeer);
15543 } else {
15544 struct sip_pvt *p_old;
15546 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
15548 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));
15549 transmit_response(p, "404 Not found", req);
15550 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15551 return 0;
15553 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
15554 transmit_response(p, "200 OK", req);
15555 transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
15556 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
15557 /* hide the 'complete' exten/context in the refer_to field for later display */
15558 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
15560 /* remove any old subscription from this peer for the same exten/context,
15561 as the peer has obviously forgotten about it and it's wasteful to wait
15562 for it to expire and send NOTIFY messages to the peer only to have them
15563 ignored (or generate errors)
15565 ast_mutex_lock(&iflock);
15566 for (p_old = iflist; p_old; p_old = p_old->next) {
15567 if (p_old == p)
15568 continue;
15569 if (p_old->initreq.method != SIP_SUBSCRIBE)
15570 continue;
15571 if (p_old->subscribed == NONE)
15572 continue;
15573 ast_mutex_lock(&p_old->lock);
15574 if (!strcmp(p_old->username, p->username)) {
15575 if (!strcmp(p_old->exten, p->exten) &&
15576 !strcmp(p_old->context, p->context)) {
15577 ast_set_flag(&p_old->flags[0], SIP_NEEDDESTROY);
15578 ast_mutex_unlock(&p_old->lock);
15579 break;
15582 ast_mutex_unlock(&p_old->lock);
15584 ast_mutex_unlock(&iflock);
15586 if (!p->expiry)
15587 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15589 return 1;
15592 /*! \brief Handle incoming REGISTER request */
15593 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
15595 enum check_auth_result res;
15597 /* Use this as the basis */
15598 if (ast_test_flag(req, SIP_PKT_DEBUG))
15599 ast_verbose("Using latest REGISTER request as basis request\n");
15600 copy_request(&p->initreq, req);
15601 check_via(p, req);
15602 if ((res = register_verify(p, sin, req, e)) < 0) {
15603 const char *reason;
15605 switch (res) {
15606 case AUTH_SECRET_FAILED:
15607 reason = "Wrong password";
15608 break;
15609 case AUTH_USERNAME_MISMATCH:
15610 reason = "Username/auth name mismatch";
15611 break;
15612 case AUTH_NOT_FOUND:
15613 reason = "No matching peer found";
15614 break;
15615 case AUTH_UNKNOWN_DOMAIN:
15616 reason = "Not a local domain";
15617 break;
15618 case AUTH_PEER_NOT_DYNAMIC:
15619 reason = "Peer is not supposed to register";
15620 break;
15621 case AUTH_ACL_FAILED:
15622 reason = "Device does not match ACL";
15623 break;
15624 default:
15625 reason = "Unknown failure";
15626 break;
15628 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
15629 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
15630 reason);
15631 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
15632 } else
15633 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
15635 if (res < 1) {
15636 /* Destroy the session, but keep us around for just a bit in case they don't
15637 get our 200 OK */
15638 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15640 return res;
15643 /*! \brief Handle incoming SIP requests (methods)
15644 \note This is where all incoming requests go first */
15645 /* called with p and p->owner locked */
15646 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
15648 /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
15649 relatively static */
15650 const char *cmd;
15651 const char *cseq;
15652 const char *useragent;
15653 int seqno;
15654 int len;
15655 int ignore = FALSE;
15656 int respid;
15657 int res = 0;
15658 int debug = sip_debug_test_pvt(p);
15659 char *e;
15660 int error = 0;
15662 /* Get Method and Cseq */
15663 cseq = get_header(req, "Cseq");
15664 cmd = req->header[0];
15666 /* Must have Cseq */
15667 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
15668 ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
15669 error = 1;
15671 if (!error && sscanf(cseq, "%d%n", &seqno, &len) != 1) {
15672 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
15673 error = 1;
15675 if (error) {
15676 if (!p->initreq.headers) /* New call */
15677 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); /* Make sure we destroy this dialog */
15678 return -1;
15680 /* Get the command XXX */
15682 cmd = req->rlPart1;
15683 e = req->rlPart2;
15685 /* Save useragent of the client */
15686 useragent = get_header(req, "User-Agent");
15687 if (!ast_strlen_zero(useragent))
15688 ast_string_field_set(p, useragent, useragent);
15690 /* Find out SIP method for incoming request */
15691 if (req->method == SIP_RESPONSE) { /* Response to our request */
15692 /* Response to our request -- Do some sanity checks */
15693 if (!p->initreq.headers) {
15694 if (option_debug)
15695 ast_log(LOG_DEBUG, "That's odd... Got a response on a call we dont know about. Cseq %d Cmd %s\n", seqno, cmd);
15696 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15697 return 0;
15698 } else if (p->ocseq && (p->ocseq < seqno) && (seqno != p->lastnoninvite)) {
15699 if (option_debug)
15700 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
15701 return -1;
15702 } else if (p->ocseq && (p->ocseq != seqno) && (seqno != p->lastnoninvite)) {
15703 /* ignore means "don't do anything with it" but still have to
15704 respond appropriately */
15705 ignore = TRUE;
15706 ast_set_flag(req, SIP_PKT_IGNORE);
15707 ast_set_flag(req, SIP_PKT_IGNORE_RESP);
15708 append_history(p, "Ignore", "Ignoring this retransmit\n");
15709 } else if (e) {
15710 e = ast_skip_blanks(e);
15711 if (sscanf(e, "%d %n", &respid, &len) != 1) {
15712 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
15713 } else {
15714 if (respid <= 0) {
15715 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
15716 return 0;
15718 /* More SIP ridiculousness, we have to ignore bogus contacts in 100 etc responses */
15719 if ((respid == 200) || ((respid >= 300) && (respid <= 399)))
15720 extract_uri(p, req);
15721 handle_response(p, respid, e + len, req, ignore, seqno);
15724 return 0;
15727 /* New SIP request coming in
15728 (could be new request in existing SIP dialog as well...)
15731 p->method = req->method; /* Find out which SIP method they are using */
15732 if (option_debug > 3)
15733 ast_log(LOG_DEBUG, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
15735 if (p->icseq && (p->icseq > seqno) ) {
15736 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
15737 if (option_debug > 2)
15738 ast_log(LOG_DEBUG, "Got CANCEL or ACK on INVITE with transactions in between.\n");
15739 } else {
15740 if (option_debug)
15741 ast_log(LOG_DEBUG, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
15742 if (req->method != SIP_ACK)
15743 transmit_response(p, "503 Server error", req); /* We must respond according to RFC 3261 sec 12.2 */
15744 return -1;
15746 } else if (p->icseq &&
15747 p->icseq == seqno &&
15748 req->method != SIP_ACK &&
15749 (p->method != SIP_CANCEL || ast_test_flag(&p->flags[0], SIP_ALREADYGONE))) {
15750 /* ignore means "don't do anything with it" but still have to
15751 respond appropriately. We do this if we receive a repeat of
15752 the last sequence number */
15753 ignore = 2;
15754 ast_set_flag(req, SIP_PKT_IGNORE);
15755 ast_set_flag(req, SIP_PKT_IGNORE_REQ);
15756 if (option_debug > 2)
15757 ast_log(LOG_DEBUG, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
15760 if (seqno >= p->icseq)
15761 /* Next should follow monotonically (but not necessarily
15762 incrementally -- thanks again to the genius authors of SIP --
15763 increasing */
15764 p->icseq = seqno;
15766 /* Find their tag if we haven't got it */
15767 if (ast_strlen_zero(p->theirtag)) {
15768 char tag[128];
15770 gettag(req, "From", tag, sizeof(tag));
15771 ast_string_field_set(p, theirtag, tag);
15773 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
15775 if (pedanticsipchecking) {
15776 /* If this is a request packet without a from tag, it's not
15777 correct according to RFC 3261 */
15778 /* Check if this a new request in a new dialog with a totag already attached to it,
15779 RFC 3261 - section 12.2 - and we don't want to mess with recovery */
15780 if (!p->initreq.headers && ast_test_flag(req, SIP_PKT_WITH_TOTAG)) {
15781 /* If this is a first request and it got a to-tag, it is not for us */
15782 if (!ast_test_flag(req, SIP_PKT_IGNORE) && req->method == SIP_INVITE) {
15783 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
15784 /* Will cease to exist after ACK */
15785 } else if (req->method != SIP_ACK) {
15786 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
15787 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15789 return res;
15793 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
15794 transmit_response(p, "400 Bad request", req);
15795 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15796 return -1;
15799 /* Handle various incoming SIP methods in requests */
15800 switch (p->method) {
15801 case SIP_OPTIONS:
15802 res = handle_request_options(p, req);
15803 break;
15804 case SIP_INVITE:
15805 res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
15806 break;
15807 case SIP_REFER:
15808 res = handle_request_refer(p, req, debug, ignore, seqno, nounlock);
15809 break;
15810 case SIP_CANCEL:
15811 res = handle_request_cancel(p, req);
15812 break;
15813 case SIP_BYE:
15814 res = handle_request_bye(p, req);
15815 break;
15816 case SIP_MESSAGE:
15817 res = handle_request_message(p, req);
15818 break;
15819 case SIP_SUBSCRIBE:
15820 res = handle_request_subscribe(p, req, sin, seqno, e);
15821 break;
15822 case SIP_REGISTER:
15823 res = handle_request_register(p, req, sin, e);
15824 break;
15825 case SIP_INFO:
15826 if (ast_test_flag(req, SIP_PKT_DEBUG))
15827 ast_verbose("Receiving INFO!\n");
15828 if (!ignore)
15829 handle_request_info(p, req);
15830 else /* if ignoring, transmit response */
15831 transmit_response(p, "200 OK", req);
15832 break;
15833 case SIP_NOTIFY:
15834 res = handle_request_notify(p, req, sin, seqno, e);
15835 break;
15836 case SIP_ACK:
15837 /* Make sure we don't ignore this */
15838 if (seqno == p->pendinginvite) {
15839 p->invitestate = INV_TERMINATED;
15840 p->pendinginvite = 0;
15841 __sip_ack(p, seqno, FLAG_RESPONSE, 0);
15842 if (find_sdp(req)) {
15843 if (process_sdp(p, req))
15844 return -1;
15846 check_pendings(p);
15848 /* Got an ACK that we did not match. Ignore silently */
15849 if (!p->lastinvite && ast_strlen_zero(p->randdata))
15850 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15851 break;
15852 default:
15853 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
15854 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
15855 cmd, ast_inet_ntoa(p->sa.sin_addr));
15856 /* If this is some new method, and we don't have a call, destroy it now */
15857 if (!p->initreq.headers)
15858 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15859 break;
15861 return res;
15864 /*! \brief Read data from SIP socket
15865 \note sipsock_read locks the owner channel while we are processing the SIP message
15866 \return 1 on error, 0 on success
15867 \note Successful messages is connected to SIP call and forwarded to handle_request()
15869 static int sipsock_read(int *id, int fd, short events, void *ignore)
15871 struct sip_request req;
15872 struct sockaddr_in sin = { 0, };
15873 struct sip_pvt *p;
15874 int res;
15875 socklen_t len = sizeof(sin);
15876 int nounlock;
15877 int recount = 0;
15878 int lockretry;
15880 memset(&req, 0, sizeof(req));
15881 res = recvfrom(sipsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
15882 if (res < 0) {
15883 #if !defined(__FreeBSD__)
15884 if (errno == EAGAIN)
15885 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
15886 else
15887 #endif
15888 if (errno != ECONNREFUSED)
15889 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
15890 return 1;
15892 if (option_debug && res == sizeof(req.data) - 1)
15893 ast_log(LOG_DEBUG, "Received packet exceeds buffer. Data is possibly lost\n");
15895 req.data[res] = '\0';
15896 req.len = res;
15897 if(sip_debug_test_addr(&sin)) /* Set the debug flag early on packet level */
15898 ast_set_flag(&req, SIP_PKT_DEBUG);
15899 if (pedanticsipchecking)
15900 req.len = lws2sws(req.data, req.len); /* Fix multiline headers */
15901 if (ast_test_flag(&req, SIP_PKT_DEBUG))
15902 ast_verbose("\n<--- SIP read from %s:%d --->\n%s\n<------------->\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), req.data);
15904 if(parse_request(&req) == -1) /* Bad packet, can't parse */
15905 return 1;
15907 req.method = find_sip_method(req.rlPart1);
15909 if (ast_test_flag(&req, SIP_PKT_DEBUG))
15910 ast_verbose("--- (%d headers %d lines)%s ---\n", req.headers, req.lines, (req.headers + req.lines == 0) ? " Nat keepalive" : "");
15912 if (req.headers < 2) /* Must have at least two headers */
15913 return 1;
15915 /* Process request, with netlock held, and with usual deadlock avoidance */
15916 for (lockretry = 100; lockretry > 0; lockretry--) {
15917 ast_mutex_lock(&netlock);
15919 /* Find the active SIP dialog or create a new one */
15920 p = find_call(&req, &sin, req.method); /* returns p locked */
15921 if (p == NULL) {
15922 if (option_debug)
15923 ast_log(LOG_DEBUG, "Invalid SIP message - rejected , no callid, len %d\n", req.len);
15924 ast_mutex_unlock(&netlock);
15925 return 1;
15927 /* Go ahead and lock the owner if it has one -- we may need it */
15928 /* because this is deadlock-prone, we need to try and unlock if failed */
15929 if (!p->owner || !ast_channel_trylock(p->owner))
15930 break; /* locking succeeded */
15931 if (lockretry == 1) {
15932 if (option_debug) {
15933 ast_log(LOG_DEBUG, "Failed to grab owner channel lock. (SIP call %s)\n", p->callid);
15935 } else {
15936 if (option_debug) {
15937 ast_log(LOG_DEBUG, "Failed to grab owner channel lock, trying again. (SIP call %s)\n", p->callid);
15939 ast_mutex_unlock(&p->lock);
15940 ast_mutex_unlock(&netlock);
15941 /* Sleep for a very short amount of time */
15942 usleep(1);
15945 p->recv = sin;
15947 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) /* This is a request or response, note what it was for */
15948 append_history(p, "Rx", "%s / %s / %s", req.data, get_header(&req, "CSeq"), req.rlPart2);
15950 if (!lockretry) {
15951 /* XXX Wouldn't p->owner always exist here? */
15952 /* This is unsafe, since p->owner wouldn't be locked. */
15953 if (p->owner)
15954 ast_log(LOG_ERROR, "We could NOT get the channel lock for %s! \n", S_OR(p->owner->name, "- no channel name ??? - "));
15955 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
15956 if (req.method != SIP_ACK)
15957 transmit_response(p, "503 Server error", &req); /* We must respond according to RFC 3261 sec 12.2 */
15958 /* XXX We could add retry-after to make sure they come back */
15959 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
15960 ast_mutex_unlock(&p->lock);
15961 ast_mutex_unlock(&netlock);
15962 return 1;
15964 nounlock = 0;
15965 if (handle_request(p, &req, &sin, &recount, &nounlock) == -1) {
15966 /* Request failed */
15967 if (option_debug)
15968 ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
15971 if (p->owner && !nounlock)
15972 ast_channel_unlock(p->owner);
15973 ast_mutex_unlock(&p->lock);
15974 ast_mutex_unlock(&netlock);
15975 if (recount)
15976 ast_update_use_count();
15978 return 1;
15981 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
15982 static int sip_send_mwi_to_peer(struct sip_peer *peer)
15984 /* Called with peerl lock, but releases it */
15985 struct sip_pvt *p;
15986 int newmsgs, oldmsgs;
15988 /* Do we have an IP address? If not, skip this peer */
15989 if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr)
15990 return 0;
15992 /* Check for messages */
15993 ast_app_inboxcount(peer->mailbox, &newmsgs, &oldmsgs);
15995 peer->lastmsgcheck = time(NULL);
15997 /* Return now if it's the same thing we told them last time */
15998 if (((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)) == peer->lastmsgssent) {
15999 return 0;
16003 peer->lastmsgssent = ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs));
16005 if (peer->mwipvt) {
16006 /* Base message on subscription */
16007 p = peer->mwipvt;
16008 } else {
16009 /* Build temporary dialog for this message */
16010 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY)))
16011 return -1;
16012 if (create_addr_from_peer(p, peer)) {
16013 /* Maybe they're not registered, etc. */
16014 sip_destroy(p);
16015 return 0;
16017 /* Recalculate our side, and recalculate Call ID */
16018 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
16019 p->ourip = __ourip;
16020 build_via(p);
16021 build_callid_pvt(p);
16022 /* Destroy this session after 32 secs */
16023 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16025 /* Send MWI */
16026 ast_set_flag(&p->flags[0], SIP_OUTGOING);
16027 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
16028 return 0;
16031 /*! \brief Check whether peer needs a new MWI notification check */
16032 static int does_peer_need_mwi(struct sip_peer *peer)
16034 time_t t = time(NULL);
16036 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
16037 !peer->mwipvt) { /* We don't have a subscription */
16038 peer->lastmsgcheck = t; /* Reset timer */
16039 return FALSE;
16042 if (!ast_strlen_zero(peer->mailbox) && (t - peer->lastmsgcheck) > global_mwitime)
16043 return TRUE;
16045 return FALSE;
16049 /*! \brief The SIP monitoring thread
16050 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
16051 (and thus do not have a separate thread) indefinitely
16053 static void *do_monitor(void *data)
16055 int res;
16056 struct sip_pvt *sip;
16057 struct sip_peer *peer = NULL;
16058 time_t t;
16059 int fastrestart = FALSE;
16060 int lastpeernum = -1;
16061 int curpeernum;
16062 int reloading;
16064 /* Add an I/O event to our SIP UDP socket */
16065 if (sipsock > -1)
16066 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
16068 /* From here on out, we die whenever asked */
16069 for(;;) {
16070 /* Check for a reload request */
16071 ast_mutex_lock(&sip_reload_lock);
16072 reloading = sip_reloading;
16073 sip_reloading = FALSE;
16074 ast_mutex_unlock(&sip_reload_lock);
16075 if (reloading) {
16076 if (option_verbose > 0)
16077 ast_verbose(VERBOSE_PREFIX_1 "Reloading SIP\n");
16078 sip_do_reload(sip_reloadreason);
16080 /* Change the I/O fd of our UDP socket */
16081 if (sipsock > -1) {
16082 if (sipsock_read_id)
16083 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
16084 else
16085 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
16086 } else if (sipsock_read_id) {
16087 ast_io_remove(io, sipsock_read_id);
16088 sipsock_read_id = NULL;
16091 restartsearch:
16092 /* Check for interfaces needing to be killed */
16093 ast_mutex_lock(&iflock);
16094 t = time(NULL);
16095 /* don't scan the interface list if it hasn't been a reasonable period
16096 of time since the last time we did it (when MWI is being sent, we can
16097 get back to this point every millisecond or less)
16099 for (sip = iflist; !fastrestart && sip; sip = sip->next) {
16100 /*! \note If we can't get a lock on an interface, skip it and come
16101 * back later. Note that there is the possibility of a deadlock with
16102 * sip_hangup otherwise, because sip_hangup is called with the channel
16103 * locked first, and the iface lock is attempted second.
16105 if (ast_mutex_trylock(&sip->lock))
16106 continue;
16108 /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
16109 if (sip->rtp && sip->owner &&
16110 (sip->owner->_state == AST_STATE_UP) &&
16111 !sip->redirip.sin_addr.s_addr &&
16112 sip->t38.state != T38_ENABLED) {
16113 if (sip->lastrtptx &&
16114 ast_rtp_get_rtpkeepalive(sip->rtp) &&
16115 (t > sip->lastrtptx + ast_rtp_get_rtpkeepalive(sip->rtp))) {
16116 /* Need to send an empty RTP packet */
16117 sip->lastrtptx = time(NULL);
16118 ast_rtp_sendcng(sip->rtp, 0);
16120 if (sip->lastrtprx &&
16121 (ast_rtp_get_rtptimeout(sip->rtp) || ast_rtp_get_rtpholdtimeout(sip->rtp)) &&
16122 (t > sip->lastrtprx + ast_rtp_get_rtptimeout(sip->rtp))) {
16123 /* Might be a timeout now -- see if we're on hold */
16124 struct sockaddr_in sin;
16125 ast_rtp_get_peer(sip->rtp, &sin);
16126 if (sin.sin_addr.s_addr ||
16127 (ast_rtp_get_rtpholdtimeout(sip->rtp) &&
16128 (t > sip->lastrtprx + ast_rtp_get_rtpholdtimeout(sip->rtp)))) {
16129 /* Needs a hangup */
16130 if (ast_rtp_get_rtptimeout(sip->rtp)) {
16131 while (sip->owner && ast_channel_trylock(sip->owner)) {
16132 DEADLOCK_AVOIDANCE(&sip->lock);
16134 if (sip->owner) {
16135 ast_log(LOG_NOTICE,
16136 "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
16137 sip->owner->name,
16138 (long) (t - sip->lastrtprx));
16139 /* Issue a softhangup */
16140 ast_softhangup_nolock(sip->owner, AST_SOFTHANGUP_DEV);
16141 ast_channel_unlock(sip->owner);
16142 /* forget the timeouts for this call, since a hangup
16143 has already been requested and we don't want to
16144 repeatedly request hangups
16146 ast_rtp_set_rtptimeout(sip->rtp, 0);
16147 ast_rtp_set_rtpholdtimeout(sip->rtp, 0);
16148 if (sip->vrtp) {
16149 ast_rtp_set_rtptimeout(sip->vrtp, 0);
16150 ast_rtp_set_rtpholdtimeout(sip->vrtp, 0);
16157 /* If we have sessions that needs to be destroyed, do it now */
16158 if (ast_test_flag(&sip->flags[0], SIP_NEEDDESTROY) && !sip->packets &&
16159 !sip->owner) {
16160 ast_mutex_unlock(&sip->lock);
16161 __sip_destroy(sip, 1);
16162 ast_mutex_unlock(&iflock);
16163 usleep(1);
16164 goto restartsearch;
16166 ast_mutex_unlock(&sip->lock);
16168 ast_mutex_unlock(&iflock);
16170 /* XXX TODO The scheduler usage in this module does not have sufficient
16171 * synchronization being done between running the scheduler and places
16172 * scheduling tasks. As it is written, any scheduled item may not run
16173 * any sooner than about 1 second, regardless of whether a sooner time
16174 * was asked for. */
16176 pthread_testcancel();
16177 /* Wait for sched or io */
16178 res = ast_sched_wait(sched);
16179 if ((res < 0) || (res > 1000))
16180 res = 1000;
16181 /* If we might need to send more mailboxes, don't wait long at all.*/
16182 if (fastrestart)
16183 res = 1;
16184 res = ast_io_wait(io, res);
16185 if (option_debug && res > 20)
16186 ast_log(LOG_DEBUG, "chan_sip: ast_io_wait ran %d all at once\n", res);
16187 ast_mutex_lock(&monlock);
16188 res = ast_sched_runq(sched);
16189 if (option_debug && res >= 20)
16190 ast_log(LOG_DEBUG, "chan_sip: ast_sched_runq ran %d all at once\n", res);
16192 /* Send MWI notifications to peers - static and cached realtime peers */
16193 t = time(NULL);
16194 fastrestart = FALSE;
16195 curpeernum = 0;
16196 peer = NULL;
16197 /* Find next peer that needs mwi */
16198 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !peer, do {
16199 if ((curpeernum > lastpeernum) && does_peer_need_mwi(iterator)) {
16200 fastrestart = TRUE;
16201 lastpeernum = curpeernum;
16202 peer = ASTOBJ_REF(iterator);
16204 curpeernum++;
16205 } while (0)
16207 /* Send MWI to the peer */
16208 if (peer) {
16209 ASTOBJ_WRLOCK(peer);
16210 sip_send_mwi_to_peer(peer);
16211 ASTOBJ_UNLOCK(peer);
16212 ASTOBJ_UNREF(peer,sip_destroy_peer);
16213 } else {
16214 /* Reset where we come from */
16215 lastpeernum = -1;
16217 ast_mutex_unlock(&monlock);
16219 /* Never reached */
16220 return NULL;
16224 /*! \brief Start the channel monitor thread */
16225 static int restart_monitor(void)
16227 /* If we're supposed to be stopped -- stay stopped */
16228 if (monitor_thread == AST_PTHREADT_STOP)
16229 return 0;
16230 ast_mutex_lock(&monlock);
16231 if (monitor_thread == pthread_self()) {
16232 ast_mutex_unlock(&monlock);
16233 ast_log(LOG_WARNING, "Cannot kill myself\n");
16234 return -1;
16236 if (monitor_thread != AST_PTHREADT_NULL) {
16237 /* Wake up the thread */
16238 pthread_kill(monitor_thread, SIGURG);
16239 } else {
16240 /* Start a new monitor */
16241 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
16242 ast_mutex_unlock(&monlock);
16243 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
16244 return -1;
16247 ast_mutex_unlock(&monlock);
16248 return 0;
16251 /*! \brief React to lack of answer to Qualify poke */
16252 static int sip_poke_noanswer(const void *data)
16254 struct sip_peer *peer = (struct sip_peer *)data;
16256 peer->pokeexpire = -1;
16257 if (peer->lastms > -1) {
16258 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
16259 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
16261 if (peer->call)
16262 sip_destroy(peer->call);
16263 peer->call = NULL;
16264 peer->lastms = -1;
16265 ast_device_state_changed("SIP/%s", peer->name);
16267 /* This function gets called one place outside of the scheduler ... */
16268 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
16269 struct sip_peer *peer_ptr = peer;
16270 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
16273 /* There is no need to ASTOBJ_REF() here. Just let the scheduled callback
16274 * inherit the reference that the current callback already has. */
16275 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
16276 if (peer->pokeexpire == -1) {
16277 ASTOBJ_UNREF(peer, sip_destroy_peer);
16280 return 0;
16283 /*! \brief Check availability of peer, also keep NAT open
16284 \note This is done with the interval in qualify= configuration option
16285 Default is 2 seconds */
16286 static int sip_poke_peer(struct sip_peer *peer)
16288 struct sip_pvt *p;
16289 int xmitres = 0;
16291 if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
16292 /* IF we have no IP, or this isn't to be monitored, return
16293 imeediately after clearing things out */
16294 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
16295 struct sip_peer *peer_ptr = peer;
16296 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
16298 peer->lastms = 0;
16299 peer->call = NULL;
16300 return 0;
16302 if (peer->call) {
16303 if (sipdebug)
16304 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
16305 sip_destroy(peer->call);
16307 if (!(p = peer->call = sip_alloc(NULL, NULL, 0, SIP_OPTIONS)))
16308 return -1;
16310 p->sa = peer->addr;
16311 p->recv = peer->addr;
16312 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
16313 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16315 /* Send OPTIONs to peer's fullcontact */
16316 if (!ast_strlen_zero(peer->fullcontact))
16317 ast_string_field_set(p, fullcontact, peer->fullcontact);
16319 if (!ast_strlen_zero(peer->tohost))
16320 ast_string_field_set(p, tohost, peer->tohost);
16321 else
16322 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
16324 /* Recalculate our side, and recalculate Call ID */
16325 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
16326 p->ourip = __ourip;
16327 build_via(p);
16328 build_callid_pvt(p);
16330 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
16331 struct sip_peer *peer_ptr = peer;
16332 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
16335 p->relatedpeer = ASTOBJ_REF(peer);
16336 ast_set_flag(&p->flags[0], SIP_OUTGOING);
16337 #ifdef VOCAL_DATA_HACK
16338 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
16339 xmitres = transmit_invite(p, SIP_INVITE, 0, 2);
16340 #else
16341 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2);
16342 #endif
16343 gettimeofday(&peer->ps, NULL);
16344 if (xmitres == XMIT_ERROR) {
16345 sip_poke_noanswer(ASTOBJ_REF(peer)); /* Immediately unreachable, network problems */
16346 } else {
16347 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
16348 struct sip_peer *peer_ptr = peer;
16349 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
16351 peer->pokeexpire = ast_sched_add(sched, peer->maxms * 2, sip_poke_noanswer, ASTOBJ_REF(peer));
16352 if (peer->pokeexpire == -1) {
16353 struct sip_peer *peer_ptr = peer;
16354 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
16358 return 0;
16361 /*! \brief Part of PBX channel interface
16362 \note
16363 \par Return values:---
16365 If we have qualify on and the device is not reachable, regardless of registration
16366 state we return AST_DEVICE_UNAVAILABLE
16368 For peers with call limit:
16369 - not registered AST_DEVICE_UNAVAILABLE
16370 - registered, no call AST_DEVICE_NOT_INUSE
16371 - registered, active calls AST_DEVICE_INUSE
16372 - registered, call limit reached AST_DEVICE_BUSY
16373 - registered, onhold AST_DEVICE_ONHOLD
16374 - registered, ringing AST_DEVICE_RINGING
16376 For peers without call limit:
16377 - not registered AST_DEVICE_UNAVAILABLE
16378 - registered AST_DEVICE_NOT_INUSE
16379 - fixed IP (!dynamic) AST_DEVICE_NOT_INUSE
16381 Peers that does not have a known call and can't be reached by OPTIONS
16382 - unreachable AST_DEVICE_UNAVAILABLE
16384 If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
16385 out a state by walking the channel list.
16387 The queue system (\ref app_queue.c) treats a member as "active"
16388 if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
16390 When placing a call to the queue member, queue system sets a member to busy if
16391 != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
16394 static int sip_devicestate(void *data)
16396 char *host;
16397 char *tmp;
16399 struct hostent *hp;
16400 struct ast_hostent ahp;
16401 struct sip_peer *p;
16403 int res = AST_DEVICE_INVALID;
16405 /* make sure data is not null. Maybe unnecessary, but better be safe */
16406 host = ast_strdupa(data ? data : "");
16407 if ((tmp = strchr(host, '@')))
16408 host = tmp + 1;
16410 if (option_debug > 2)
16411 ast_log(LOG_DEBUG, "Checking device state for peer %s\n", host);
16413 /* If find_peer asks for a realtime peer, then this breaks rtautoclear. This
16414 * is because when a peer tries to autoexpire, the last thing it does is to
16415 * queue up an event telling the system that the devicestate has changed
16416 * (presumably to unavailable). If we ask for a realtime peer here, this would
16417 * load it BACK into memory, thus defeating the point of trying to trying to
16418 * clear dead hosts out of memory.
16420 if ((p = find_peer(host, NULL, 0, 1))) {
16421 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
16422 /* we have an address for the peer */
16424 /* Check status in this order
16425 - Hold
16426 - Ringing
16427 - Busy (enforced only by call limit)
16428 - Inuse (we have a call)
16429 - Unreachable (qualify)
16430 If we don't find any of these state, report AST_DEVICE_NOT_INUSE
16431 for registered devices */
16433 if (p->onHold)
16434 /* First check for hold or ring states */
16435 res = AST_DEVICE_ONHOLD;
16436 else if (p->inRinging) {
16437 if (p->inRinging == p->inUse)
16438 res = AST_DEVICE_RINGING;
16439 else
16440 res = AST_DEVICE_RINGINUSE;
16441 } else if (p->call_limit && (p->inUse == p->call_limit))
16442 /* check call limit */
16443 res = AST_DEVICE_BUSY;
16444 else if (p->call_limit && p->inUse)
16445 /* Not busy, but we do have a call */
16446 res = AST_DEVICE_INUSE;
16447 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
16448 /* We don't have a call. Are we reachable at all? Requires qualify= */
16449 res = AST_DEVICE_UNAVAILABLE;
16450 else /* Default reply if we're registered and have no other data */
16451 res = AST_DEVICE_NOT_INUSE;
16452 } else {
16453 /* there is no address, it's unavailable */
16454 res = AST_DEVICE_UNAVAILABLE;
16456 ASTOBJ_UNREF(p,sip_destroy_peer);
16457 } else {
16458 char *port = strchr(host, ':');
16459 if (port)
16460 *port = '\0';
16461 hp = ast_gethostbyname(host, &ahp);
16462 if (hp)
16463 res = AST_DEVICE_UNKNOWN;
16466 return res;
16469 /*! \brief PBX interface function -build SIP pvt structure
16470 SIP calls initiated by the PBX arrive here */
16471 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
16473 int oldformat;
16474 struct sip_pvt *p;
16475 struct ast_channel *tmpc = NULL;
16476 char *ext, *host;
16477 char tmp[256];
16478 char *dest = data;
16480 oldformat = format;
16481 if (!(format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1))) {
16482 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));
16483 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL; /* Can't find codec to connect to host */
16484 return NULL;
16486 if (option_debug)
16487 ast_log(LOG_DEBUG, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
16489 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE))) {
16490 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", (char *)data);
16491 *cause = AST_CAUSE_SWITCH_CONGESTION;
16492 return NULL;
16495 ast_set_flag(&p->flags[1], SIP_PAGE2_OUTGOING_CALL);
16497 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
16498 sip_destroy(p);
16499 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
16500 *cause = AST_CAUSE_SWITCH_CONGESTION;
16501 return NULL;
16504 ast_copy_string(tmp, dest, sizeof(tmp));
16505 host = strchr(tmp, '@');
16506 if (host) {
16507 *host++ = '\0';
16508 ext = tmp;
16509 } else {
16510 ext = strchr(tmp, '/');
16511 if (ext)
16512 *ext++ = '\0';
16513 host = tmp;
16516 if (create_addr(p, host)) {
16517 *cause = AST_CAUSE_UNREGISTERED;
16518 if (option_debug > 2)
16519 ast_log(LOG_DEBUG, "Cant create SIP call - target device not registred\n");
16520 sip_destroy(p);
16521 return NULL;
16523 if (ast_strlen_zero(p->peername) && ext)
16524 ast_string_field_set(p, peername, ext);
16525 /* Recalculate our side, and recalculate Call ID */
16526 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
16527 p->ourip = __ourip;
16528 build_via(p);
16529 build_callid_pvt(p);
16531 /* We have an extension to call, don't use the full contact here */
16532 /* This to enable dialing registered peers with extension dialling,
16533 like SIP/peername/extension
16534 SIP/peername will still use the full contact */
16535 if (ext) {
16536 ast_string_field_set(p, username, ext);
16537 ast_string_field_free(p, fullcontact);
16539 #if 0
16540 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
16541 #endif
16542 p->prefcodec = oldformat; /* Format for this call */
16543 ast_mutex_lock(&p->lock);
16544 tmpc = sip_new(p, AST_STATE_DOWN, host); /* Place the call */
16545 ast_mutex_unlock(&p->lock);
16546 if (!tmpc)
16547 sip_destroy(p);
16548 ast_update_use_count();
16549 restart_monitor();
16550 return tmpc;
16554 * \brief Parse the "insecure" setting from sip.conf or from realtime.
16555 * \param flags a pointer to an ast_flags structure
16556 * \param value the value of the SIP insecure setting
16557 * \param lineno linenumber in sip.conf or -1 for realtime
16559 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno)
16561 static int dep_insecure_very = 0;
16562 static int dep_insecure_yes = 0;
16564 if (ast_strlen_zero(value))
16565 return;
16567 if (!strcasecmp(value, "very")) {
16568 ast_set_flag(flags, SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16569 if(!dep_insecure_very) {
16570 if(lineno != -1)
16571 ast_log(LOG_WARNING, "insecure=very at line %d is deprecated; use insecure=port,invite instead\n", lineno);
16572 else
16573 ast_log(LOG_WARNING, "insecure=very is deprecated; use insecure=port,invite instead\n");
16574 dep_insecure_very = 1;
16577 else if (ast_true(value)) {
16578 ast_set_flag(flags, SIP_INSECURE_PORT);
16579 if(!dep_insecure_yes) {
16580 if(lineno != -1)
16581 ast_log(LOG_WARNING, "insecure=%s at line %d is deprecated; use insecure=port instead\n", value, lineno);
16582 else
16583 ast_log(LOG_WARNING, "insecure=%s is deprecated; use insecure=port instead\n", value);
16584 dep_insecure_yes = 1;
16587 else if (!ast_false(value)) {
16588 char buf[64];
16589 char *word, *next;
16590 ast_copy_string(buf, value, sizeof(buf));
16591 next = buf;
16592 while ((word = strsep(&next, ","))) {
16593 if (!strcasecmp(word, "port"))
16594 ast_set_flag(flags, SIP_INSECURE_PORT);
16595 else if (!strcasecmp(word, "invite"))
16596 ast_set_flag(flags, SIP_INSECURE_INVITE);
16597 else
16598 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
16604 \brief Handle flag-type options common to configuration of devices - users and peers
16605 \param flags array of two struct ast_flags
16606 \param mask array of two struct ast_flags
16607 \param v linked list of config variables to process
16608 \returns non-zero if any config options were handled, zero otherwise
16610 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
16612 int res = 1;
16614 if (!strcasecmp(v->name, "trustrpid")) {
16615 ast_set_flag(&mask[0], SIP_TRUSTRPID);
16616 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
16617 } else if (!strcasecmp(v->name, "sendrpid")) {
16618 ast_set_flag(&mask[0], SIP_SENDRPID);
16619 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
16620 } else if (!strcasecmp(v->name, "g726nonstandard")) {
16621 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
16622 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
16623 } else if (!strcasecmp(v->name, "useclientcode")) {
16624 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
16625 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
16626 } else if (!strcasecmp(v->name, "dtmfmode")) {
16627 ast_set_flag(&mask[0], SIP_DTMF);
16628 ast_clear_flag(&flags[0], SIP_DTMF);
16629 if (!strcasecmp(v->value, "inband"))
16630 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
16631 else if (!strcasecmp(v->value, "rfc2833"))
16632 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
16633 else if (!strcasecmp(v->value, "info"))
16634 ast_set_flag(&flags[0], SIP_DTMF_INFO);
16635 else if (!strcasecmp(v->value, "auto"))
16636 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
16637 else {
16638 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
16639 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
16641 } else if (!strcasecmp(v->name, "nat")) {
16642 ast_set_flag(&mask[0], SIP_NAT);
16643 ast_clear_flag(&flags[0], SIP_NAT);
16644 if (!strcasecmp(v->value, "never"))
16645 ast_set_flag(&flags[0], SIP_NAT_NEVER);
16646 else if (!strcasecmp(v->value, "route"))
16647 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
16648 else if (ast_true(v->value))
16649 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
16650 else
16651 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
16652 } else if (!strcasecmp(v->name, "canreinvite")) {
16653 ast_set_flag(&mask[0], SIP_REINVITE);
16654 ast_clear_flag(&flags[0], SIP_REINVITE);
16655 if(ast_true(v->value)) {
16656 ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
16657 } else if (!ast_false(v->value)) {
16658 char buf[64];
16659 char *word, *next = buf;
16661 ast_copy_string(buf, v->value, sizeof(buf));
16662 while ((word = strsep(&next, ","))) {
16663 if(!strcasecmp(word, "update")) {
16664 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
16665 } else if(!strcasecmp(word, "nonat")) {
16666 ast_set_flag(&flags[0], SIP_CAN_REINVITE);
16667 ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
16668 } else {
16669 ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
16673 } else if (!strcasecmp(v->name, "insecure")) {
16674 ast_set_flag(&mask[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16675 ast_clear_flag(&flags[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16676 set_insecure_flags(flags, v->value, v->lineno);
16677 } else if (!strcasecmp(v->name, "progressinband")) {
16678 ast_set_flag(&mask[0], SIP_PROG_INBAND);
16679 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
16680 if (ast_true(v->value))
16681 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
16682 else if (strcasecmp(v->value, "never"))
16683 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
16684 } else if (!strcasecmp(v->name, "promiscredir")) {
16685 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
16686 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
16687 } else if (!strcasecmp(v->name, "videosupport")) {
16688 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
16689 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
16690 } else if (!strcasecmp(v->name, "allowoverlap")) {
16691 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
16692 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
16693 } else if (!strcasecmp(v->name, "allowsubscribe")) {
16694 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
16695 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
16696 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
16697 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_UDPTL);
16698 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_UDPTL);
16699 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
16700 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
16701 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_RTP);
16702 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_RTP);
16703 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
16704 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_TCP);
16705 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_TCP);
16706 #endif
16707 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
16708 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
16709 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
16710 } else if (!strcasecmp(v->name, "buggymwi")) {
16711 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
16712 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
16713 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
16714 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
16715 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
16716 } else
16717 res = 0;
16719 return res;
16722 /*! \brief Add SIP domain to list of domains we are responsible for */
16723 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
16725 struct domain *d;
16727 if (ast_strlen_zero(domain)) {
16728 ast_log(LOG_WARNING, "Zero length domain.\n");
16729 return 1;
16732 if (!(d = ast_calloc(1, sizeof(*d))))
16733 return 0;
16735 ast_copy_string(d->domain, domain, sizeof(d->domain));
16737 if (!ast_strlen_zero(context))
16738 ast_copy_string(d->context, context, sizeof(d->context));
16740 d->mode = mode;
16742 AST_LIST_LOCK(&domain_list);
16743 AST_LIST_INSERT_TAIL(&domain_list, d, list);
16744 AST_LIST_UNLOCK(&domain_list);
16746 if (sipdebug)
16747 ast_log(LOG_DEBUG, "Added local SIP domain '%s'\n", domain);
16749 return 1;
16752 /*! \brief check_sip_domain: Check if domain part of uri is local to our server */
16753 static int check_sip_domain(const char *domain, char *context, size_t len)
16755 struct domain *d;
16756 int result = 0;
16758 AST_LIST_LOCK(&domain_list);
16759 AST_LIST_TRAVERSE(&domain_list, d, list) {
16760 if (strcasecmp(d->domain, domain))
16761 continue;
16763 if (len && !ast_strlen_zero(d->context))
16764 ast_copy_string(context, d->context, len);
16766 result = 1;
16767 break;
16769 AST_LIST_UNLOCK(&domain_list);
16771 return result;
16774 /*! \brief Clear our domain list (at reload) */
16775 static void clear_sip_domains(void)
16777 struct domain *d;
16779 AST_LIST_LOCK(&domain_list);
16780 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
16781 free(d);
16782 AST_LIST_UNLOCK(&domain_list);
16786 /*! \brief Add realm authentication in list */
16787 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno)
16789 char authcopy[256];
16790 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
16791 char *stringp;
16792 struct sip_auth *a, *b, *auth;
16794 if (ast_strlen_zero(configuration))
16795 return authlist;
16797 if (option_debug)
16798 ast_log(LOG_DEBUG, "Auth config :: %s\n", configuration);
16800 ast_copy_string(authcopy, configuration, sizeof(authcopy));
16801 stringp = authcopy;
16803 username = stringp;
16804 realm = strrchr(stringp, '@');
16805 if (realm)
16806 *realm++ = '\0';
16807 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
16808 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
16809 return authlist;
16811 stringp = username;
16812 username = strsep(&stringp, ":");
16813 if (username) {
16814 secret = strsep(&stringp, ":");
16815 if (!secret) {
16816 stringp = username;
16817 md5secret = strsep(&stringp,"#");
16820 if (!(auth = ast_calloc(1, sizeof(*auth))))
16821 return authlist;
16823 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
16824 ast_copy_string(auth->username, username, sizeof(auth->username));
16825 if (secret)
16826 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
16827 if (md5secret)
16828 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
16830 /* find the end of the list */
16831 for (b = NULL, a = authlist; a ; b = a, a = a->next)
16833 if (b)
16834 b->next = auth; /* Add structure add end of list */
16835 else
16836 authlist = auth;
16838 if (option_verbose > 2)
16839 ast_verbose("Added authentication for realm %s\n", realm);
16841 return authlist;
16845 /*! \brief Clear realm authentication list (at reload) */
16846 static int clear_realm_authentication(struct sip_auth *authlist)
16848 struct sip_auth *a = authlist;
16849 struct sip_auth *b;
16851 while (a) {
16852 b = a;
16853 a = a->next;
16854 free(b);
16857 return 1;
16860 /*! \brief Find authentication for a specific realm */
16861 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
16863 struct sip_auth *a;
16865 for (a = authlist; a; a = a->next) {
16866 if (!strcasecmp(a->realm, realm))
16867 break;
16870 return a;
16873 /*! \brief Initiate a SIP user structure from configuration (configuration or realtime) */
16874 static struct sip_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
16876 struct sip_user *user;
16877 int format;
16878 struct ast_ha *oldha = NULL;
16879 char *varname = NULL, *varval = NULL;
16880 struct ast_variable *tmpvar = NULL;
16881 struct ast_flags userflags[2] = {{(0)}};
16882 struct ast_flags mask[2] = {{(0)}};
16885 if (!(user = ast_calloc(1, sizeof(*user))))
16886 return NULL;
16888 suserobjs++;
16889 ASTOBJ_INIT(user);
16890 ast_copy_string(user->name, name, sizeof(user->name));
16891 oldha = user->ha;
16892 user->ha = NULL;
16893 ast_copy_flags(&user->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
16894 ast_copy_flags(&user->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16895 user->capability = global_capability;
16896 user->allowtransfer = global_allowtransfer;
16897 user->maxcallbitrate = default_maxcallbitrate;
16898 user->autoframing = global_autoframing;
16899 user->prefs = default_prefs;
16900 /* set default context */
16901 strcpy(user->context, default_context);
16902 strcpy(user->language, default_language);
16903 strcpy(user->mohinterpret, default_mohinterpret);
16904 strcpy(user->mohsuggest, default_mohsuggest);
16905 /* First we walk through the v parameters list and then the alt parameters list */
16906 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
16907 if (handle_common_options(&userflags[0], &mask[0], v))
16908 continue;
16910 if (!strcasecmp(v->name, "context")) {
16911 ast_copy_string(user->context, v->value, sizeof(user->context));
16912 } else if (!strcasecmp(v->name, "subscribecontext")) {
16913 ast_copy_string(user->subscribecontext, v->value, sizeof(user->subscribecontext));
16914 } else if (!strcasecmp(v->name, "setvar")) {
16915 varname = ast_strdupa(v->value);
16916 if ((varval = strchr(varname,'='))) {
16917 *varval++ = '\0';
16918 if ((tmpvar = ast_variable_new(varname, varval))) {
16919 tmpvar->next = user->chanvars;
16920 user->chanvars = tmpvar;
16923 } else if (!strcasecmp(v->name, "permit") ||
16924 !strcasecmp(v->name, "deny")) {
16925 user->ha = ast_append_ha(v->name, v->value, user->ha);
16926 } else if (!strcasecmp(v->name, "allowtransfer")) {
16927 user->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
16928 } else if (!strcasecmp(v->name, "secret")) {
16929 ast_copy_string(user->secret, v->value, sizeof(user->secret));
16930 } else if (!strcasecmp(v->name, "md5secret")) {
16931 ast_copy_string(user->md5secret, v->value, sizeof(user->md5secret));
16932 } else if (!strcasecmp(v->name, "callerid")) {
16933 ast_callerid_split(v->value, user->cid_name, sizeof(user->cid_name), user->cid_num, sizeof(user->cid_num));
16934 } else if (!strcasecmp(v->name, "fullname")) {
16935 ast_copy_string(user->cid_name, v->value, sizeof(user->cid_name));
16936 } else if (!strcasecmp(v->name, "cid_number")) {
16937 ast_copy_string(user->cid_num, v->value, sizeof(user->cid_num));
16938 } else if (!strcasecmp(v->name, "callgroup")) {
16939 user->callgroup = ast_get_group(v->value);
16940 } else if (!strcasecmp(v->name, "pickupgroup")) {
16941 user->pickupgroup = ast_get_group(v->value);
16942 } else if (!strcasecmp(v->name, "language")) {
16943 ast_copy_string(user->language, v->value, sizeof(user->language));
16944 } else if (!strcasecmp(v->name, "mohinterpret")
16945 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
16946 ast_copy_string(user->mohinterpret, v->value, sizeof(user->mohinterpret));
16947 } else if (!strcasecmp(v->name, "mohsuggest")) {
16948 ast_copy_string(user->mohsuggest, v->value, sizeof(user->mohsuggest));
16949 } else if (!strcasecmp(v->name, "accountcode")) {
16950 ast_copy_string(user->accountcode, v->value, sizeof(user->accountcode));
16951 } else if (!strcasecmp(v->name, "call-limit")) {
16952 user->call_limit = atoi(v->value);
16953 if (user->call_limit < 0)
16954 user->call_limit = 0;
16955 } else if (!strcasecmp(v->name, "amaflags")) {
16956 format = ast_cdr_amaflags2int(v->value);
16957 if (format < 0) {
16958 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
16959 } else {
16960 user->amaflags = format;
16962 } else if (!strcasecmp(v->name, "allow")) {
16963 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
16964 } else if (!strcasecmp(v->name, "disallow")) {
16965 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 0);
16966 } else if (!strcasecmp(v->name, "autoframing")) {
16967 user->autoframing = ast_true(v->value);
16968 } else if (!strcasecmp(v->name, "callingpres")) {
16969 user->callingpres = ast_parse_caller_presentation(v->value);
16970 if (user->callingpres == -1)
16971 user->callingpres = atoi(v->value);
16972 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
16973 user->maxcallbitrate = atoi(v->value);
16974 if (user->maxcallbitrate < 0)
16975 user->maxcallbitrate = default_maxcallbitrate;
16977 /* We can't just report unknown options here because this may be a
16978 * type=friend entry. All user options are valid for a peer, but not
16979 * the other way around. */
16981 ast_copy_flags(&user->flags[0], &userflags[0], mask[0].flags);
16982 ast_copy_flags(&user->flags[1], &userflags[1], mask[1].flags);
16983 if (ast_test_flag(&user->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
16984 global_allowsubscribe = TRUE; /* No global ban any more */
16985 ast_free_ha(oldha);
16986 return user;
16989 /*! \brief Set peer defaults before configuring specific configurations */
16990 static void set_peer_defaults(struct sip_peer *peer)
16992 if (peer->expire == 0) {
16993 /* Don't reset expire or port time during reload
16994 if we have an active registration
16996 peer->expire = -1;
16997 peer->pokeexpire = -1;
16998 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
17000 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
17001 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
17002 strcpy(peer->context, default_context);
17003 strcpy(peer->subscribecontext, default_subscribecontext);
17004 strcpy(peer->language, default_language);
17005 strcpy(peer->mohinterpret, default_mohinterpret);
17006 strcpy(peer->mohsuggest, default_mohsuggest);
17007 peer->addr.sin_family = AF_INET;
17008 peer->defaddr.sin_family = AF_INET;
17009 peer->capability = global_capability;
17010 peer->maxcallbitrate = default_maxcallbitrate;
17011 peer->rtptimeout = global_rtptimeout;
17012 peer->rtpholdtimeout = global_rtpholdtimeout;
17013 peer->rtpkeepalive = global_rtpkeepalive;
17014 peer->allowtransfer = global_allowtransfer;
17015 peer->autoframing = global_autoframing;
17016 strcpy(peer->vmexten, default_vmexten);
17017 peer->secret[0] = '\0';
17018 peer->md5secret[0] = '\0';
17019 peer->cid_num[0] = '\0';
17020 peer->cid_name[0] = '\0';
17021 peer->fromdomain[0] = '\0';
17022 peer->fromuser[0] = '\0';
17023 peer->regexten[0] = '\0';
17024 peer->mailbox[0] = '\0';
17025 peer->callgroup = 0;
17026 peer->pickupgroup = 0;
17027 peer->maxms = default_qualify;
17028 peer->prefs = default_prefs;
17031 /*! \brief Create temporary peer (used in autocreatepeer mode) */
17032 static struct sip_peer *temp_peer(const char *name)
17034 struct sip_peer *peer;
17036 if (!(peer = ast_calloc(1, sizeof(*peer))))
17037 return NULL;
17039 apeerobjs++;
17040 ASTOBJ_INIT(peer);
17041 set_peer_defaults(peer);
17043 ast_copy_string(peer->name, name, sizeof(peer->name));
17045 ast_set_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT);
17046 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
17047 peer->prefs = default_prefs;
17048 reg_source_db(peer);
17050 return peer;
17053 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
17054 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
17056 struct sip_peer *peer = NULL;
17057 struct ast_ha *oldha = NULL;
17058 int obproxyfound=0;
17059 int found=0;
17060 int firstpass=1;
17061 int format=0; /* Ama flags */
17062 time_t regseconds = 0;
17063 char *varname = NULL, *varval = NULL;
17064 struct ast_variable *tmpvar = NULL;
17065 struct ast_flags peerflags[2] = {{(0)}};
17066 struct ast_flags mask[2] = {{(0)}};
17067 char fullcontact[sizeof(peer->fullcontact)] = "";
17069 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))
17070 /* Note we do NOT use find_peer here, to avoid realtime recursion */
17071 /* We also use a case-sensitive comparison (unlike find_peer) so
17072 that case changes made to the peer name will be properly handled
17073 during reload
17075 peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);
17077 if (peer) {
17078 /* Already in the list, remove it and it will be added back (or FREE'd) */
17079 found = 1;
17080 if (!(peer->objflags & ASTOBJ_FLAG_MARKED))
17081 firstpass = 0;
17082 } else {
17083 if (!(peer = ast_calloc(1, sizeof(*peer))))
17084 return NULL;
17086 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))
17087 rpeerobjs++;
17088 else
17089 speerobjs++;
17090 ASTOBJ_INIT(peer);
17092 /* Note that our peer HAS had its reference count incrased */
17093 if (firstpass) {
17094 peer->lastmsgssent = -1;
17095 oldha = peer->ha;
17096 peer->ha = NULL;
17097 set_peer_defaults(peer); /* Set peer defaults */
17099 if (!found && name)
17100 ast_copy_string(peer->name, name, sizeof(peer->name));
17102 /* If we have channel variables, remove them (reload) */
17103 if (peer->chanvars) {
17104 ast_variables_destroy(peer->chanvars);
17105 peer->chanvars = NULL;
17106 /* XXX should unregister ? */
17109 /* If we have realm authentication information, remove them (reload) */
17110 clear_realm_authentication(peer->auth);
17111 peer->auth = NULL;
17113 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
17114 if (handle_common_options(&peerflags[0], &mask[0], v))
17115 continue;
17116 if (realtime && !strcasecmp(v->name, "regseconds")) {
17117 ast_get_time_t(v->value, &regseconds, 0, NULL);
17118 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
17119 inet_aton(v->value, &(peer->addr.sin_addr));
17120 } else if (realtime && !strcasecmp(v->name, "name"))
17121 ast_copy_string(peer->name, v->value, sizeof(peer->name));
17122 else if (realtime && !strcasecmp(v->name, "fullcontact")) {
17123 /* Reconstruct field, because realtime separates our value at the ';' */
17124 if (!ast_strlen_zero(fullcontact)) {
17125 strncat(fullcontact, ";", sizeof(fullcontact) - strlen(fullcontact) - 1);
17126 strncat(fullcontact, v->value, sizeof(fullcontact) - strlen(fullcontact) - 1);
17127 } else {
17128 ast_copy_string(fullcontact, v->value, sizeof(fullcontact));
17129 ast_set_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT);
17131 } else if (!strcasecmp(v->name, "secret"))
17132 ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
17133 else if (!strcasecmp(v->name, "md5secret"))
17134 ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
17135 else if (!strcasecmp(v->name, "auth"))
17136 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
17137 else if (!strcasecmp(v->name, "callerid")) {
17138 ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
17139 } else if (!strcasecmp(v->name, "fullname")) {
17140 ast_copy_string(peer->cid_name, v->value, sizeof(peer->cid_name));
17141 } else if (!strcasecmp(v->name, "cid_number")) {
17142 ast_copy_string(peer->cid_num, v->value, sizeof(peer->cid_num));
17143 } else if (!strcasecmp(v->name, "context")) {
17144 ast_copy_string(peer->context, v->value, sizeof(peer->context));
17145 } else if (!strcasecmp(v->name, "subscribecontext")) {
17146 ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
17147 } else if (!strcasecmp(v->name, "fromdomain")) {
17148 ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
17149 } else if (!strcasecmp(v->name, "usereqphone")) {
17150 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
17151 } else if (!strcasecmp(v->name, "fromuser")) {
17152 ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
17153 } else if (!strcasecmp(v->name, "host") || !strcasecmp(v->name, "outboundproxy")) {
17154 if (!strcasecmp(v->value, "dynamic")) {
17155 if (!strcasecmp(v->name, "outboundproxy") || obproxyfound) {
17156 ast_log(LOG_WARNING, "You can't have a dynamic outbound proxy, you big silly head at line %d.\n", v->lineno);
17157 } else {
17158 /* They'll register with us */
17159 if (!found || !ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
17160 /* Initialize stuff if this is a new peer, or if it used to be
17161 * non-dynamic before the reload. */
17162 memset(&peer->addr.sin_addr, 0, 4);
17163 if (peer->addr.sin_port) {
17164 /* If we've already got a port, make it the default rather than absolute */
17165 peer->defaddr.sin_port = peer->addr.sin_port;
17166 peer->addr.sin_port = 0;
17169 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
17171 } else {
17172 /* Non-dynamic. Make sure we become that way if we're not */
17173 if (!AST_SCHED_DEL(sched, peer->expire)) {
17174 struct sip_peer *peer_ptr = peer;
17175 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
17177 ast_clear_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
17178 if (!obproxyfound || !strcasecmp(v->name, "outboundproxy")) {
17179 if (ast_get_ip_or_srv(&peer->addr, v->value, srvlookup ? "_sip._udp" : NULL)) {
17180 ASTOBJ_UNREF(peer, sip_destroy_peer);
17181 return NULL;
17184 if (!strcasecmp(v->name, "outboundproxy"))
17185 obproxyfound=1;
17186 else {
17187 ast_copy_string(peer->tohost, v->value, sizeof(peer->tohost));
17188 if (!peer->addr.sin_port)
17189 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
17191 if (global_dynamic_exclude_static) {
17192 global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha);
17195 } else if (!strcasecmp(v->name, "defaultip")) {
17196 if (ast_get_ip(&peer->defaddr, v->value)) {
17197 ASTOBJ_UNREF(peer, sip_destroy_peer);
17198 return NULL;
17200 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
17201 peer->ha = ast_append_ha(v->name, v->value, peer->ha);
17202 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
17203 peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha);
17204 } else if (!strcasecmp(v->name, "port")) {
17205 if (!realtime && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC))
17206 peer->defaddr.sin_port = htons(atoi(v->value));
17207 else
17208 peer->addr.sin_port = htons(atoi(v->value));
17209 } else if (!strcasecmp(v->name, "callingpres")) {
17210 peer->callingpres = ast_parse_caller_presentation(v->value);
17211 if (peer->callingpres == -1)
17212 peer->callingpres = atoi(v->value);
17213 } else if (!strcasecmp(v->name, "username")) {
17214 ast_copy_string(peer->username, v->value, sizeof(peer->username));
17215 } else if (!strcasecmp(v->name, "language")) {
17216 ast_copy_string(peer->language, v->value, sizeof(peer->language));
17217 } else if (!strcasecmp(v->name, "regexten")) {
17218 ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
17219 } else if (!strcasecmp(v->name, "call-limit") || !strcasecmp(v->name, "incominglimit")) {
17220 peer->call_limit = atoi(v->value);
17221 if (peer->call_limit < 0)
17222 peer->call_limit = 0;
17223 } else if (!strcasecmp(v->name, "amaflags")) {
17224 format = ast_cdr_amaflags2int(v->value);
17225 if (format < 0) {
17226 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
17227 } else {
17228 peer->amaflags = format;
17230 } else if (!strcasecmp(v->name, "accountcode")) {
17231 ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
17232 } else if (!strcasecmp(v->name, "mohinterpret")
17233 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
17234 ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
17235 } else if (!strcasecmp(v->name, "mohsuggest")) {
17236 ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
17237 } else if (!strcasecmp(v->name, "mailbox")) {
17238 ast_copy_string(peer->mailbox, v->value, sizeof(peer->mailbox));
17239 } else if (!strcasecmp(v->name, "hasvoicemail")) {
17240 /* People expect that if 'hasvoicemail' is set, that the mailbox will
17241 * be also set, even if not explicitly specified. */
17242 if (ast_true(v->value) && ast_strlen_zero(peer->mailbox)) {
17243 ast_copy_string(peer->mailbox, name, sizeof(peer->mailbox));
17245 } else if (!strcasecmp(v->name, "subscribemwi")) {
17246 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
17247 } else if (!strcasecmp(v->name, "vmexten")) {
17248 ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
17249 } else if (!strcasecmp(v->name, "callgroup")) {
17250 peer->callgroup = ast_get_group(v->value);
17251 } else if (!strcasecmp(v->name, "allowtransfer")) {
17252 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
17253 } else if (!strcasecmp(v->name, "pickupgroup")) {
17254 peer->pickupgroup = ast_get_group(v->value);
17255 } else if (!strcasecmp(v->name, "allow")) {
17256 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
17257 } else if (!strcasecmp(v->name, "disallow")) {
17258 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
17259 } else if (!strcasecmp(v->name, "autoframing")) {
17260 peer->autoframing = ast_true(v->value);
17261 } else if (!strcasecmp(v->name, "rtptimeout")) {
17262 if ((sscanf(v->value, "%d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
17263 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
17264 peer->rtptimeout = global_rtptimeout;
17266 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
17267 if ((sscanf(v->value, "%d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
17268 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
17269 peer->rtpholdtimeout = global_rtpholdtimeout;
17271 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
17272 if ((sscanf(v->value, "%d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
17273 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
17274 peer->rtpkeepalive = global_rtpkeepalive;
17276 } else if (!strcasecmp(v->name, "setvar")) {
17277 /* Set peer channel variable */
17278 varname = ast_strdupa(v->value);
17279 if ((varval = strchr(varname, '='))) {
17280 *varval++ = '\0';
17281 if ((tmpvar = ast_variable_new(varname, varval))) {
17282 tmpvar->next = peer->chanvars;
17283 peer->chanvars = tmpvar;
17286 } else if (!strcasecmp(v->name, "qualify")) {
17287 if (!strcasecmp(v->value, "no")) {
17288 peer->maxms = 0;
17289 } else if (!strcasecmp(v->value, "yes")) {
17290 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
17291 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
17292 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);
17293 peer->maxms = 0;
17295 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
17296 peer->maxcallbitrate = atoi(v->value);
17297 if (peer->maxcallbitrate < 0)
17298 peer->maxcallbitrate = default_maxcallbitrate;
17301 if (!ast_strlen_zero(fullcontact)) {
17302 ast_copy_string(peer->fullcontact, fullcontact, sizeof(peer->fullcontact));
17303 /* We have a hostname in the fullcontact, but if we don't have an
17304 * address listed on the entry (or if it's 'dynamic'), then we need to
17305 * parse the entry to obtain the IP address, so a dynamic host can be
17306 * contacted immediately after reload (as opposed to waiting for it to
17307 * register once again). */
17308 __set_address_from_contact(fullcontact, &peer->addr);
17311 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && realtime) {
17312 time_t nowtime = time(NULL);
17314 if ((nowtime - regseconds) > 0) {
17315 destroy_association(peer);
17316 memset(&peer->addr, 0, sizeof(peer->addr));
17317 if (option_debug)
17318 ast_log(LOG_DEBUG, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
17321 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
17322 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
17323 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
17324 global_allowsubscribe = TRUE; /* No global ban any more */
17325 if (!found && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && !ast_test_flag(&peer->flags[0], SIP_REALTIME))
17326 reg_source_db(peer);
17327 ASTOBJ_UNMARK(peer);
17328 ast_free_ha(oldha);
17329 return peer;
17332 /*! \brief Re-read SIP.conf config file
17333 \note This function reloads all config data, except for
17334 active peers (with registrations). They will only
17335 change configuration data at restart, not at reload.
17336 SIP debug and recordhistory state will not change
17338 static int reload_config(enum channelreloadreason reason)
17340 struct ast_config *cfg, *ucfg;
17341 struct ast_variable *v;
17342 struct sip_peer *peer;
17343 struct sip_user *user;
17344 struct ast_hostent ahp;
17345 char *cat, *stringp, *context, *oldregcontext;
17346 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
17347 struct hostent *hp;
17348 int format;
17349 struct ast_flags dummy[2];
17350 int auto_sip_domains = FALSE;
17351 struct sockaddr_in old_bindaddr = bindaddr;
17352 int registry_count = 0, peer_count = 0, user_count = 0;
17353 unsigned int temp_tos = 0;
17354 struct ast_flags debugflag = {0};
17356 cfg = ast_config_load(config);
17358 /* We *must* have a config file otherwise stop immediately */
17359 if (!cfg) {
17360 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
17361 return -1;
17364 if (option_debug > 3)
17365 ast_log(LOG_DEBUG, "--------------- SIP reload started\n");
17367 clear_realm_authentication(authl);
17368 clear_sip_domains();
17369 authl = NULL;
17371 ast_free_ha(global_contact_ha);
17372 global_contact_ha = NULL;
17374 /* First, destroy all outstanding registry calls */
17375 /* This is needed, since otherwise active registry entries will not be destroyed */
17376 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
17377 ASTOBJ_RDLOCK(iterator);
17378 if (iterator->call) {
17379 if (option_debug > 2)
17380 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
17381 /* This will also remove references to the registry */
17382 sip_destroy(iterator->call);
17384 ASTOBJ_UNLOCK(iterator);
17386 } while(0));
17388 /* Then, actually destroy users and registry */
17389 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
17390 if (option_debug > 3)
17391 ast_log(LOG_DEBUG, "--------------- Done destroying user list\n");
17392 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
17393 if (option_debug > 3)
17394 ast_log(LOG_DEBUG, "--------------- Done destroying registry list\n");
17395 ASTOBJ_CONTAINER_MARKALL(&peerl);
17397 /* Initialize copy of current global_regcontext for later use in removing stale contexts */
17398 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
17399 oldregcontext = oldcontexts;
17401 /* Clear all flags before setting default values */
17402 /* Preserve debugging settings for console */
17403 ast_copy_flags(&debugflag, &global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
17404 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
17405 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
17406 ast_copy_flags(&global_flags[1], &debugflag, SIP_PAGE2_DEBUG_CONSOLE);
17408 /* Reset IP addresses */
17409 memset(&bindaddr, 0, sizeof(bindaddr));
17410 ast_free_ha(localaddr);
17411 memset(&localaddr, 0, sizeof(localaddr));
17412 memset(&externip, 0, sizeof(externip));
17413 memset(&default_prefs, 0 , sizeof(default_prefs));
17414 outboundproxyip.sin_port = htons(STANDARD_SIP_PORT);
17415 outboundproxyip.sin_family = AF_INET; /* Type of address: IPv4 */
17416 ourport = STANDARD_SIP_PORT;
17417 srvlookup = DEFAULT_SRVLOOKUP;
17418 global_tos_sip = DEFAULT_TOS_SIP;
17419 global_tos_audio = DEFAULT_TOS_AUDIO;
17420 global_tos_video = DEFAULT_TOS_VIDEO;
17421 externhost[0] = '\0'; /* External host name (for behind NAT DynDNS support) */
17422 externexpire = 0; /* Expiration for DNS re-issuing */
17423 externrefresh = 10;
17424 memset(&outboundproxyip, 0, sizeof(outboundproxyip));
17426 /* Reset channel settings to default before re-configuring */
17427 allow_external_domains = DEFAULT_ALLOW_EXT_DOM; /* Allow external invites */
17428 global_regcontext[0] = '\0';
17429 expiry = DEFAULT_EXPIRY;
17430 global_notifyringing = DEFAULT_NOTIFYRINGING;
17431 global_limitonpeers = FALSE;
17432 global_directrtpsetup = FALSE; /* Experimental feature, disabled by default */
17433 global_notifyhold = FALSE;
17434 global_alwaysauthreject = 0;
17435 global_allowsubscribe = FALSE;
17436 ast_copy_string(global_useragent, DEFAULT_USERAGENT, sizeof(global_useragent));
17437 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
17438 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME))
17439 ast_copy_string(global_realm, DEFAULT_REALM, sizeof(global_realm));
17440 else
17441 ast_copy_string(global_realm, ast_config_AST_SYSTEM_NAME, sizeof(global_realm));
17442 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
17443 compactheaders = DEFAULT_COMPACTHEADERS;
17444 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
17445 global_regattempts_max = 0;
17446 pedanticsipchecking = DEFAULT_PEDANTIC;
17447 global_mwitime = DEFAULT_MWITIME;
17448 autocreatepeer = DEFAULT_AUTOCREATEPEER;
17449 global_autoframing = 0;
17450 global_allowguest = DEFAULT_ALLOWGUEST;
17451 global_rtptimeout = 0;
17452 global_rtpholdtimeout = 0;
17453 global_rtpkeepalive = 0;
17454 global_allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
17455 global_rtautoclear = 120;
17456 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE); /* Default for peers, users: TRUE */
17457 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP); /* Default for peers, users: TRUE */
17458 ast_set_flag(&global_flags[1], SIP_PAGE2_RTUPDATE);
17460 /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for peers and users */
17461 ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
17462 default_subscribecontext[0] = '\0';
17463 default_language[0] = '\0';
17464 default_fromdomain[0] = '\0';
17465 default_qualify = DEFAULT_QUALIFY;
17466 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
17467 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
17468 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
17469 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
17470 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833); /*!< Default DTMF setting: RFC2833 */
17471 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581); /*!< NAT support if requested by device with rport */
17472 ast_set_flag(&global_flags[0], SIP_CAN_REINVITE); /*!< Allow re-invites */
17474 /* Debugging settings, always default to off */
17475 dumphistory = FALSE;
17476 recordhistory = FALSE;
17477 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
17479 /* Misc settings for the channel */
17480 global_relaxdtmf = FALSE;
17481 global_callevents = FALSE;
17482 global_t1min = DEFAULT_T1MIN;
17484 global_matchexterniplocally = FALSE;
17486 /* Copy the default jb config over global_jbconf */
17487 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
17489 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT);
17491 /* Read the [general] config section of sip.conf (or from realtime config) */
17492 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
17493 if (handle_common_options(&global_flags[0], &dummy[0], v))
17494 continue;
17495 /* handle jb conf */
17496 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
17497 continue;
17499 /* Create the interface list */
17500 if (!strcasecmp(v->name, "context")) {
17501 ast_copy_string(default_context, v->value, sizeof(default_context));
17502 } else if (!strcasecmp(v->name, "subscribecontext")) {
17503 ast_copy_string(default_subscribecontext, v->value, sizeof(default_subscribecontext));
17504 } else if (!strcasecmp(v->name, "allowguest")) {
17505 global_allowguest = ast_true(v->value) ? 1 : 0;
17506 } else if (!strcasecmp(v->name, "realm")) {
17507 ast_copy_string(global_realm, v->value, sizeof(global_realm));
17508 } else if (!strcasecmp(v->name, "useragent")) {
17509 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
17510 if (option_debug)
17511 ast_log(LOG_DEBUG, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
17512 } else if (!strcasecmp(v->name, "allowtransfer")) {
17513 global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
17514 } else if (!strcasecmp(v->name, "rtcachefriends")) {
17515 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
17516 } else if (!strcasecmp(v->name, "rtsavesysname")) {
17517 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTSAVE_SYSNAME);
17518 } else if (!strcasecmp(v->name, "rtupdate")) {
17519 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTUPDATE);
17520 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
17521 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_IGNOREREGEXPIRE);
17522 } else if (!strcasecmp(v->name, "t1min")) {
17523 global_t1min = atoi(v->value);
17524 } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
17525 global_dynamic_exclude_static = ast_true(v->value);
17526 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
17527 global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha);
17528 } else if (!strcasecmp(v->name, "rtautoclear")) {
17529 int i = atoi(v->value);
17530 if (i > 0)
17531 global_rtautoclear = i;
17532 else
17533 i = 0;
17534 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
17535 } else if (!strcasecmp(v->name, "usereqphone")) {
17536 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
17537 } else if (!strcasecmp(v->name, "relaxdtmf")) {
17538 global_relaxdtmf = ast_true(v->value);
17539 } else if (!strcasecmp(v->name, "checkmwi")) {
17540 if ((sscanf(v->value, "%d", &global_mwitime) != 1) || (global_mwitime < 0)) {
17541 ast_log(LOG_WARNING, "'%s' is not a valid MWI time setting at line %d. Using default (10).\n", v->value, v->lineno);
17542 global_mwitime = DEFAULT_MWITIME;
17544 } else if (!strcasecmp(v->name, "vmexten")) {
17545 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
17546 } else if (!strcasecmp(v->name, "rtptimeout")) {
17547 if ((sscanf(v->value, "%d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
17548 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
17549 global_rtptimeout = 0;
17551 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
17552 if ((sscanf(v->value, "%d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
17553 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
17554 global_rtpholdtimeout = 0;
17556 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
17557 if ((sscanf(v->value, "%d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
17558 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
17559 global_rtpkeepalive = 0;
17561 } else if (!strcasecmp(v->name, "compactheaders")) {
17562 compactheaders = ast_true(v->value);
17563 } else if (!strcasecmp(v->name, "notifymimetype")) {
17564 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
17565 } else if (!strncasecmp(v->name, "limitonpeer", 11)) {
17566 global_limitonpeers = ast_true(v->value);
17567 } else if (!strcasecmp(v->name, "directrtpsetup")) {
17568 global_directrtpsetup = ast_true(v->value);
17569 } else if (!strcasecmp(v->name, "notifyringing")) {
17570 global_notifyringing = ast_true(v->value);
17571 } else if (!strcasecmp(v->name, "notifyhold")) {
17572 global_notifyhold = ast_true(v->value);
17573 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
17574 global_alwaysauthreject = ast_true(v->value);
17575 } else if (!strcasecmp(v->name, "mohinterpret")
17576 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
17577 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
17578 } else if (!strcasecmp(v->name, "mohsuggest")) {
17579 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
17580 } else if (!strcasecmp(v->name, "language")) {
17581 ast_copy_string(default_language, v->value, sizeof(default_language));
17582 } else if (!strcasecmp(v->name, "regcontext")) {
17583 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
17584 stringp = newcontexts;
17585 /* Let's remove any contexts that are no longer defined in regcontext */
17586 cleanup_stale_contexts(stringp, oldregcontext);
17587 /* Create contexts if they don't exist already */
17588 while ((context = strsep(&stringp, "&"))) {
17589 if (!ast_context_find(context))
17590 ast_context_create(NULL, context,"SIP");
17592 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
17593 } else if (!strcasecmp(v->name, "callerid")) {
17594 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
17595 } else if (!strcasecmp(v->name, "fromdomain")) {
17596 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
17597 } else if (!strcasecmp(v->name, "outboundproxy")) {
17598 if (ast_get_ip_or_srv(&outboundproxyip, v->value, srvlookup ? "_sip._udp" : NULL) < 0)
17599 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", v->value);
17600 } else if (!strcasecmp(v->name, "outboundproxyport")) {
17601 /* Port needs to be after IP */
17602 sscanf(v->value, "%d", &format);
17603 outboundproxyip.sin_port = htons(format);
17604 } else if (!strcasecmp(v->name, "autocreatepeer")) {
17605 autocreatepeer = ast_true(v->value);
17606 } else if (!strcasecmp(v->name, "srvlookup")) {
17607 srvlookup = ast_true(v->value);
17608 } else if (!strcasecmp(v->name, "pedantic")) {
17609 pedanticsipchecking = ast_true(v->value);
17610 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
17611 max_expiry = atoi(v->value);
17612 if (max_expiry < 1)
17613 max_expiry = DEFAULT_MAX_EXPIRY;
17614 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
17615 min_expiry = atoi(v->value);
17616 if (min_expiry < 1)
17617 min_expiry = DEFAULT_MIN_EXPIRY;
17618 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
17619 default_expiry = atoi(v->value);
17620 if (default_expiry < 1)
17621 default_expiry = DEFAULT_DEFAULT_EXPIRY;
17622 } else if (!strcasecmp(v->name, "sipdebug")) { /* XXX maybe ast_set2_flags ? */
17623 if (ast_true(v->value))
17624 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
17625 } else if (!strcasecmp(v->name, "dumphistory")) {
17626 dumphistory = ast_true(v->value);
17627 } else if (!strcasecmp(v->name, "recordhistory")) {
17628 recordhistory = ast_true(v->value);
17629 } else if (!strcasecmp(v->name, "registertimeout")) {
17630 global_reg_timeout = atoi(v->value);
17631 if (global_reg_timeout < 1)
17632 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
17633 } else if (!strcasecmp(v->name, "registerattempts")) {
17634 global_regattempts_max = atoi(v->value);
17635 } else if (!strcasecmp(v->name, "bindaddr")) {
17636 if (!(hp = ast_gethostbyname(v->value, &ahp))) {
17637 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
17638 } else {
17639 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
17641 } else if (!strcasecmp(v->name, "localnet")) {
17642 struct ast_ha *na;
17643 if (!(na = ast_append_ha("d", v->value, localaddr)))
17644 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
17645 else
17646 localaddr = na;
17647 } else if (!strcasecmp(v->name, "localmask")) {
17648 ast_log(LOG_WARNING, "Use of localmask is no long supported -- use localnet with mask syntax\n");
17649 } else if (!strcasecmp(v->name, "externip")) {
17650 if (!(hp = ast_gethostbyname(v->value, &ahp)))
17651 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
17652 else
17653 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
17654 externexpire = 0;
17655 } else if (!strcasecmp(v->name, "externhost")) {
17656 ast_copy_string(externhost, v->value, sizeof(externhost));
17657 if (!(hp = ast_gethostbyname(externhost, &ahp)))
17658 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
17659 else
17660 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
17661 externexpire = time(NULL);
17662 } else if (!strcasecmp(v->name, "externrefresh")) {
17663 if (sscanf(v->value, "%d", &externrefresh) != 1) {
17664 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
17665 externrefresh = 10;
17667 } else if (!strcasecmp(v->name, "allow")) {
17668 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 1);
17669 } else if (!strcasecmp(v->name, "disallow")) {
17670 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 0);
17671 } else if (!strcasecmp(v->name, "autoframing")) {
17672 global_autoframing = ast_true(v->value);
17673 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
17674 allow_external_domains = ast_true(v->value);
17675 } else if (!strcasecmp(v->name, "autodomain")) {
17676 auto_sip_domains = ast_true(v->value);
17677 } else if (!strcasecmp(v->name, "domain")) {
17678 char *domain = ast_strdupa(v->value);
17679 char *context = strchr(domain, ',');
17681 if (context)
17682 *context++ = '\0';
17684 if (option_debug && ast_strlen_zero(context))
17685 ast_log(LOG_DEBUG, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
17686 if (ast_strlen_zero(domain))
17687 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
17688 else
17689 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, context ? ast_strip(context) : "");
17690 } else if (!strcasecmp(v->name, "register")) {
17691 if (sip_register(v->value, v->lineno) == 0)
17692 registry_count++;
17693 } else if (!strcasecmp(v->name, "tos")) {
17694 if (!ast_str2tos(v->value, &temp_tos)) {
17695 global_tos_sip = temp_tos;
17696 global_tos_audio = temp_tos;
17697 global_tos_video = temp_tos;
17698 ast_log(LOG_WARNING, "tos value at line %d is deprecated. See doc/ip-tos.txt for more information.\n", v->lineno);
17699 } else
17700 ast_log(LOG_WARNING, "Invalid tos value at line %d, See doc/ip-tos.txt for more information.\n", v->lineno);
17701 } else if (!strcasecmp(v->name, "tos_sip")) {
17702 if (ast_str2tos(v->value, &global_tos_sip))
17703 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, recommended value is 'cs3'. See doc/ip-tos.txt.\n", v->lineno);
17704 } else if (!strcasecmp(v->name, "tos_audio")) {
17705 if (ast_str2tos(v->value, &global_tos_audio))
17706 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, recommended value is 'ef'. See doc/ip-tos.txt.\n", v->lineno);
17707 } else if (!strcasecmp(v->name, "tos_video")) {
17708 if (ast_str2tos(v->value, &global_tos_video))
17709 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, recommended value is 'af41'. See doc/ip-tos.txt.\n", v->lineno);
17710 } else if (!strcasecmp(v->name, "bindport")) {
17711 if (sscanf(v->value, "%d", &ourport) == 1) {
17712 bindaddr.sin_port = htons(ourport);
17713 } else {
17714 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
17716 } else if (!strcasecmp(v->name, "qualify")) {
17717 if (!strcasecmp(v->value, "no")) {
17718 default_qualify = 0;
17719 } else if (!strcasecmp(v->value, "yes")) {
17720 default_qualify = DEFAULT_MAXMS;
17721 } else if (sscanf(v->value, "%d", &default_qualify) != 1) {
17722 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
17723 default_qualify = 0;
17725 } else if (!strcasecmp(v->name, "callevents")) {
17726 global_callevents = ast_true(v->value);
17727 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
17728 default_maxcallbitrate = atoi(v->value);
17729 if (default_maxcallbitrate < 0)
17730 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
17731 } else if (!strcasecmp(v->name, "matchexterniplocally")) {
17732 global_matchexterniplocally = ast_true(v->value);
17736 if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
17737 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
17738 allow_external_domains = 1;
17741 /* Build list of authentication to various SIP realms, i.e. service providers */
17742 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
17743 /* Format for authentication is auth = username:password@realm */
17744 if (!strcasecmp(v->name, "auth"))
17745 authl = add_realm_authentication(authl, v->value, v->lineno);
17748 ucfg = ast_config_load("users.conf");
17749 if (ucfg) {
17750 struct ast_variable *gen;
17751 int genhassip, genregistersip;
17752 const char *hassip, *registersip;
17754 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
17755 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
17756 gen = ast_variable_browse(ucfg, "general");
17757 cat = ast_category_browse(ucfg, NULL);
17758 while (cat) {
17759 if (strcasecmp(cat, "general")) {
17760 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
17761 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
17762 if (ast_true(hassip) || (!hassip && genhassip)) {
17763 user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
17764 if (user) {
17765 ASTOBJ_CONTAINER_LINK(&userl,user);
17766 ASTOBJ_UNREF(user, sip_destroy_user);
17767 user_count++;
17769 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
17770 if (peer) {
17771 ast_device_state_changed("SIP/%s", peer->name);
17772 ASTOBJ_CONTAINER_LINK(&peerl,peer);
17773 ASTOBJ_UNREF(peer, sip_destroy_peer);
17774 peer_count++;
17777 if (ast_true(registersip) || (!registersip && genregistersip)) {
17778 char tmp[256];
17779 const char *host = ast_variable_retrieve(ucfg, cat, "host");
17780 const char *username = ast_variable_retrieve(ucfg, cat, "username");
17781 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
17782 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
17783 if (!host)
17784 host = ast_variable_retrieve(ucfg, "general", "host");
17785 if (!username)
17786 username = ast_variable_retrieve(ucfg, "general", "username");
17787 if (!secret)
17788 secret = ast_variable_retrieve(ucfg, "general", "secret");
17789 if (!contact)
17790 contact = "s";
17791 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
17792 if (!ast_strlen_zero(secret))
17793 snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
17794 else
17795 snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
17796 if (sip_register(tmp, 0) == 0)
17797 registry_count++;
17801 cat = ast_category_browse(ucfg, cat);
17803 ast_config_destroy(ucfg);
17807 /* Load peers, users and friends */
17808 cat = NULL;
17809 while ( (cat = ast_category_browse(cfg, cat)) ) {
17810 const char *utype;
17811 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
17812 continue;
17813 utype = ast_variable_retrieve(cfg, cat, "type");
17814 if (!utype) {
17815 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
17816 continue;
17817 } else {
17818 int is_user = 0, is_peer = 0;
17819 if (!strcasecmp(utype, "user"))
17820 is_user = 1;
17821 else if (!strcasecmp(utype, "friend"))
17822 is_user = is_peer = 1;
17823 else if (!strcasecmp(utype, "peer"))
17824 is_peer = 1;
17825 else {
17826 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
17827 continue;
17829 if (is_user) {
17830 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
17831 if (user) {
17832 ASTOBJ_CONTAINER_LINK(&userl,user);
17833 ASTOBJ_UNREF(user, sip_destroy_user);
17834 user_count++;
17837 if (is_peer) {
17838 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
17839 if (peer) {
17840 ASTOBJ_CONTAINER_LINK(&peerl,peer);
17841 ASTOBJ_UNREF(peer, sip_destroy_peer);
17842 peer_count++;
17847 if (ast_find_ourip(&__ourip, bindaddr)) {
17848 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
17849 ast_config_destroy(cfg);
17850 return 0;
17852 if (!ntohs(bindaddr.sin_port))
17853 bindaddr.sin_port = ntohs(STANDARD_SIP_PORT);
17854 bindaddr.sin_family = AF_INET;
17855 ast_mutex_lock(&netlock);
17856 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
17857 close(sipsock);
17858 sipsock = -1;
17860 if (sipsock < 0) {
17861 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
17862 if (sipsock < 0) {
17863 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
17864 ast_config_destroy(cfg);
17865 return -1;
17866 } else {
17867 /* Allow SIP clients on the same host to access us: */
17868 const int reuseFlag = 1;
17870 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
17871 (const char*)&reuseFlag,
17872 sizeof reuseFlag);
17874 ast_enable_packet_fragmentation(sipsock);
17876 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
17877 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
17878 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
17879 strerror(errno));
17880 close(sipsock);
17881 sipsock = -1;
17882 } else {
17883 if (option_verbose > 1) {
17884 ast_verbose(VERBOSE_PREFIX_2 "SIP Listening on %s:%d\n",
17885 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
17886 ast_verbose(VERBOSE_PREFIX_2 "Using SIP TOS: %s\n", ast_tos2str(global_tos_sip));
17888 if (setsockopt(sipsock, IPPROTO_IP, IP_TOS, &global_tos_sip, sizeof(global_tos_sip)))
17889 ast_log(LOG_WARNING, "Unable to set SIP TOS to %s\n", ast_tos2str(global_tos_sip));
17893 ast_mutex_unlock(&netlock);
17895 /* Add default domains - host name, IP address and IP:port */
17896 /* Only do this if user added any sip domain with "localdomains" */
17897 /* In order to *not* break backwards compatibility */
17898 /* Some phones address us at IP only, some with additional port number */
17899 if (auto_sip_domains) {
17900 char temp[MAXHOSTNAMELEN];
17902 /* First our default IP address */
17903 if (bindaddr.sin_addr.s_addr)
17904 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
17905 else
17906 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
17908 /* Our extern IP address, if configured */
17909 if (externip.sin_addr.s_addr)
17910 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
17912 /* Extern host name (NAT traversal support) */
17913 if (!ast_strlen_zero(externhost))
17914 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
17916 /* Our host name */
17917 if (!gethostname(temp, sizeof(temp)))
17918 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
17921 /* Release configuration from memory */
17922 ast_config_destroy(cfg);
17924 /* Load the list of manual NOTIFY types to support */
17925 if (notify_types)
17926 ast_config_destroy(notify_types);
17927 notify_types = ast_config_load(notify_config);
17929 /* Done, tell the manager */
17930 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);
17932 return 0;
17935 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
17937 struct sip_pvt *p;
17938 struct ast_udptl *udptl = NULL;
17940 p = chan->tech_pvt;
17941 if (!p)
17942 return NULL;
17944 ast_mutex_lock(&p->lock);
17945 if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
17946 udptl = p->udptl;
17947 ast_mutex_unlock(&p->lock);
17948 return udptl;
17951 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
17953 struct sip_pvt *p;
17955 p = chan->tech_pvt;
17956 if (!p)
17957 return -1;
17958 ast_mutex_lock(&p->lock);
17959 if (udptl)
17960 ast_udptl_get_peer(udptl, &p->udptlredirip);
17961 else
17962 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
17963 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
17964 if (!p->pendinginvite) {
17965 if (option_debug > 2) {
17966 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);
17968 transmit_reinvite_with_t38_sdp(p);
17969 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17970 if (option_debug > 2) {
17971 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);
17973 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17976 /* Reset lastrtprx timer */
17977 p->lastrtprx = p->lastrtptx = time(NULL);
17978 ast_mutex_unlock(&p->lock);
17979 return 0;
17982 /*! \brief Handle T38 reinvite
17983 \todo Make sure we don't destroy the call if we can't handle the re-invite.
17984 Nothing should be changed until we have processed the SDP and know that we
17985 can handle it.
17987 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite)
17989 struct sip_pvt *p;
17990 int flag = 0;
17992 p = chan->tech_pvt;
17993 if (!p || !pvt->udptl)
17994 return -1;
17996 /* Setup everything on the other side like offered/responded from first side */
17997 ast_mutex_lock(&p->lock);
17999 /*! \todo check if this is not set earlier when setting up the PVT. If not
18000 maybe it should move there. */
18001 p->t38.jointcapability = p->t38.peercapability = pvt->t38.jointcapability;
18003 ast_udptl_set_far_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
18004 ast_udptl_set_local_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
18005 ast_udptl_set_error_correction_scheme(p->udptl, ast_udptl_get_error_correction_scheme(pvt->udptl));
18007 if (reinvite) { /* If we are handling sending re-invite to the other side of the bridge */
18008 /*! \note The SIP_CAN_REINVITE flag is for RTP media redirects,
18009 not really T38 re-invites which are different. In this
18010 case it's used properly, to see if we can reinvite over
18011 NAT
18013 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
18014 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
18015 flag =1;
18016 } else {
18017 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
18019 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
18020 if (!p->pendinginvite) {
18021 if (option_debug > 2) {
18022 if (flag)
18023 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));
18024 else
18025 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));
18027 transmit_reinvite_with_t38_sdp(p);
18028 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
18029 if (option_debug > 2) {
18030 if (flag)
18031 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));
18032 else
18033 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));
18035 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
18038 /* Reset lastrtprx timer */
18039 p->lastrtprx = p->lastrtptx = time(NULL);
18040 ast_mutex_unlock(&p->lock);
18041 return 0;
18042 } else { /* If we are handling sending 200 OK to the other side of the bridge */
18043 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
18044 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
18045 flag = 1;
18046 } else {
18047 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
18049 if (option_debug > 2) {
18050 if (flag)
18051 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));
18052 else
18053 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));
18055 pvt->t38.state = T38_ENABLED;
18056 p->t38.state = T38_ENABLED;
18057 if (option_debug > 1) {
18058 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", pvt->t38.state, pvt->owner ? pvt->owner->name : "<none>");
18059 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
18061 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
18062 p->lastrtprx = p->lastrtptx = time(NULL);
18063 ast_mutex_unlock(&p->lock);
18064 return 0;
18069 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
18070 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
18072 struct sip_pvt *p = NULL;
18073 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
18075 if (!(p = chan->tech_pvt))
18076 return AST_RTP_GET_FAILED;
18078 ast_mutex_lock(&p->lock);
18079 if (!(p->rtp)) {
18080 ast_mutex_unlock(&p->lock);
18081 return AST_RTP_GET_FAILED;
18084 *rtp = p->rtp;
18086 if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT))
18087 res = AST_RTP_TRY_PARTIAL;
18088 else if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
18089 res = AST_RTP_TRY_NATIVE;
18090 else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
18091 res = AST_RTP_GET_FAILED;
18093 ast_mutex_unlock(&p->lock);
18095 return res;
18098 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
18099 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
18101 struct sip_pvt *p = NULL;
18102 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
18104 if (!(p = chan->tech_pvt))
18105 return AST_RTP_GET_FAILED;
18107 ast_mutex_lock(&p->lock);
18108 if (!(p->vrtp)) {
18109 ast_mutex_unlock(&p->lock);
18110 return AST_RTP_GET_FAILED;
18113 *rtp = p->vrtp;
18115 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
18116 res = AST_RTP_TRY_NATIVE;
18118 ast_mutex_unlock(&p->lock);
18120 return res;
18123 /*! \brief Set the RTP peer for this call */
18124 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
18126 struct sip_pvt *p;
18127 int changed = 0;
18129 p = chan->tech_pvt;
18130 if (!p)
18131 return -1;
18133 /* Disable early RTP bridge */
18134 if (chan->_state != AST_STATE_UP && !global_directrtpsetup) /* We are in early state */
18135 return 0;
18137 ast_mutex_lock(&p->lock);
18138 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) {
18139 /* If we're destroyed, don't bother */
18140 ast_mutex_unlock(&p->lock);
18141 return 0;
18144 /* if this peer cannot handle reinvites of the media stream to devices
18145 that are known to be behind a NAT, then stop the process now
18147 if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
18148 ast_mutex_unlock(&p->lock);
18149 return 0;
18152 if (rtp) {
18153 changed |= ast_rtp_get_peer(rtp, &p->redirip);
18154 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
18155 memset(&p->redirip, 0, sizeof(p->redirip));
18156 changed = 1;
18158 if (vrtp) {
18159 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
18160 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
18161 memset(&p->vredirip, 0, sizeof(p->vredirip));
18162 changed = 1;
18164 if (codecs) {
18165 if ((p->redircodecs != codecs)) {
18166 p->redircodecs = codecs;
18167 changed = 1;
18169 if ((p->capability & codecs) != p->capability) {
18170 p->jointcapability &= codecs;
18171 p->capability &= codecs;
18172 changed = 1;
18175 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
18176 if (chan->_state != AST_STATE_UP) { /* We are in early state */
18177 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
18178 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
18179 if (option_debug)
18180 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));
18181 } else if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
18182 if (option_debug > 2) {
18183 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));
18185 transmit_reinvite_with_sdp(p);
18186 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
18187 if (option_debug > 2) {
18188 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));
18190 /* We have a pending Invite. Send re-invite when we're done with the invite */
18191 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
18194 /* Reset lastrtprx timer */
18195 p->lastrtprx = p->lastrtptx = time(NULL);
18196 ast_mutex_unlock(&p->lock);
18197 return 0;
18200 static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
18201 static char *descrip_dtmfmode = "SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
18202 static char *app_dtmfmode = "SIPDtmfMode";
18204 static char *app_sipaddheader = "SIPAddHeader";
18205 static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
18207 static char *descrip_sipaddheader = ""
18208 " SIPAddHeader(Header: Content)\n"
18209 "Adds a header to a SIP call placed with DIAL.\n"
18210 "Remember to user the X-header if you are adding non-standard SIP\n"
18211 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
18212 "Adding the wrong headers may jeopardize the SIP dialog.\n"
18213 "Always returns 0\n";
18216 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
18217 static int sip_dtmfmode(struct ast_channel *chan, void *data)
18219 struct sip_pvt *p;
18220 char *mode;
18221 if (data)
18222 mode = (char *)data;
18223 else {
18224 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
18225 return 0;
18227 ast_channel_lock(chan);
18228 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
18229 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
18230 ast_channel_unlock(chan);
18231 return 0;
18233 p = chan->tech_pvt;
18234 if (!p) {
18235 ast_channel_unlock(chan);
18236 return 0;
18238 ast_mutex_lock(&p->lock);
18239 if (!strcasecmp(mode,"info")) {
18240 ast_clear_flag(&p->flags[0], SIP_DTMF);
18241 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
18242 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
18243 } else if (!strcasecmp(mode,"rfc2833")) {
18244 ast_clear_flag(&p->flags[0], SIP_DTMF);
18245 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
18246 p->jointnoncodeccapability |= AST_RTP_DTMF;
18247 } else if (!strcasecmp(mode,"inband")) {
18248 ast_clear_flag(&p->flags[0], SIP_DTMF);
18249 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
18250 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
18251 } else
18252 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n",mode);
18253 if (p->rtp)
18254 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
18255 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
18256 if (!p->vad) {
18257 p->vad = ast_dsp_new();
18258 ast_dsp_set_features(p->vad, DSP_FEATURE_DTMF_DETECT);
18260 } else {
18261 if (p->vad) {
18262 ast_dsp_free(p->vad);
18263 p->vad = NULL;
18266 ast_mutex_unlock(&p->lock);
18267 ast_channel_unlock(chan);
18268 return 0;
18271 /*! \brief Add a SIP header to an outbound INVITE */
18272 static int sip_addheader(struct ast_channel *chan, void *data)
18274 int no = 0;
18275 int ok = FALSE;
18276 char varbuf[30];
18277 char *inbuf = (char *) data;
18279 if (ast_strlen_zero(inbuf)) {
18280 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
18281 return 0;
18283 ast_channel_lock(chan);
18285 /* Check for headers */
18286 while (!ok && no <= 50) {
18287 no++;
18288 snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
18290 /* Compare without the leading underscores */
18291 if( (pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL) )
18292 ok = TRUE;
18294 if (ok) {
18295 pbx_builtin_setvar_helper (chan, varbuf, inbuf);
18296 if (sipdebug)
18297 ast_log(LOG_DEBUG,"SIP Header added \"%s\" as %s\n", inbuf, varbuf);
18298 } else {
18299 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
18301 ast_channel_unlock(chan);
18302 return 0;
18305 /*! \brief Transfer call before connect with a 302 redirect
18306 \note Called by the transfer() dialplan application through the sip_transfer()
18307 pbx interface function if the call is in ringing state
18308 \todo Fix this function so that we wait for reply to the REFER and
18309 react to errors, denials or other issues the other end might have.
18311 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
18313 char *cdest;
18314 char *extension, *host, *port;
18315 char tmp[80];
18317 cdest = ast_strdupa(dest);
18319 extension = strsep(&cdest, "@");
18320 host = strsep(&cdest, ":");
18321 port = strsep(&cdest, ":");
18322 if (ast_strlen_zero(extension)) {
18323 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
18324 return 0;
18327 /* we'll issue the redirect message here */
18328 if (!host) {
18329 char *localtmp;
18330 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
18331 if (ast_strlen_zero(tmp)) {
18332 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
18333 return 0;
18335 if ((localtmp = strcasestr(tmp, "sip:")) && (localtmp = strchr(localtmp, '@'))) {
18336 char lhost[80], lport[80];
18337 memset(lhost, 0, sizeof(lhost));
18338 memset(lport, 0, sizeof(lport));
18339 localtmp++;
18340 /* This is okey because lhost and lport are as big as tmp */
18341 sscanf(localtmp, "%[^<>:; ]:%[^<>:; ]", lhost, lport);
18342 if (ast_strlen_zero(lhost)) {
18343 ast_log(LOG_ERROR, "Can't find the host address\n");
18344 return 0;
18346 host = ast_strdupa(lhost);
18347 if (!ast_strlen_zero(lport)) {
18348 port = ast_strdupa(lport);
18353 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
18354 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
18356 sip_scheddestroy(p, SIP_TRANS_TIMEOUT); /* Make sure we stop send this reply. */
18357 sip_alreadygone(p);
18358 return 0;
18361 /*! \brief Return SIP UA's codec (part of the RTP interface) */
18362 static int sip_get_codec(struct ast_channel *chan)
18364 struct sip_pvt *p = chan->tech_pvt;
18365 return p->jointcapability ? p->jointcapability : p->capability;
18368 /*! \brief Send a poke to all known peers
18369 Space them out 100 ms apart
18370 XXX We might have a cool algorithm for this or use random - any suggestions?
18372 static void sip_poke_all_peers(void)
18374 int ms = 0;
18376 if (!speerobjs) /* No peers, just give up */
18377 return;
18379 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
18380 ASTOBJ_WRLOCK(iterator);
18381 if (!AST_SCHED_DEL(sched, iterator->pokeexpire)) {
18382 struct sip_peer *peer_ptr = iterator;
18383 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
18385 ms += 100;
18386 iterator->pokeexpire = ast_sched_add(sched, ms, sip_poke_peer_s, ASTOBJ_REF(iterator));
18387 if (iterator->pokeexpire == -1) {
18388 struct sip_peer *peer_ptr = iterator;
18389 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
18391 ASTOBJ_UNLOCK(iterator);
18392 } while (0)
18396 /*! \brief Send all known registrations */
18397 static void sip_send_all_registers(void)
18399 int ms;
18400 int regspacing;
18401 if (!regobjs)
18402 return;
18403 regspacing = default_expiry * 1000/regobjs;
18404 if (regspacing > 100)
18405 regspacing = 100;
18406 ms = regspacing;
18407 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
18408 ASTOBJ_WRLOCK(iterator);
18409 AST_SCHED_DEL(sched, iterator->expire);
18410 ms += regspacing;
18411 iterator->expire = ast_sched_add(sched, ms, sip_reregister, iterator);
18412 ASTOBJ_UNLOCK(iterator);
18413 } while (0)
18417 /*! \brief Reload module */
18418 static int sip_do_reload(enum channelreloadreason reason)
18420 reload_config(reason);
18422 /* Prune peers who still are supposed to be deleted */
18423 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
18424 if (option_debug > 3)
18425 ast_log(LOG_DEBUG, "--------------- Done destroying pruned peers\n");
18427 /* Send qualify (OPTIONS) to all peers */
18428 sip_poke_all_peers();
18430 /* Register with all services */
18431 sip_send_all_registers();
18433 if (option_debug > 3)
18434 ast_log(LOG_DEBUG, "--------------- SIP reload done\n");
18436 return 0;
18439 /*! \brief Force reload of module from cli */
18440 static int sip_reload(int fd, int argc, char *argv[])
18442 ast_mutex_lock(&sip_reload_lock);
18443 if (sip_reloading)
18444 ast_verbose("Previous SIP reload not yet done\n");
18445 else {
18446 sip_reloading = TRUE;
18447 if (fd)
18448 sip_reloadreason = CHANNEL_CLI_RELOAD;
18449 else
18450 sip_reloadreason = CHANNEL_MODULE_RELOAD;
18452 ast_mutex_unlock(&sip_reload_lock);
18453 restart_monitor();
18455 return 0;
18458 /*! \brief Part of Asterisk module interface */
18459 static int reload(void)
18461 return sip_reload(0, 0, NULL);
18464 static struct ast_cli_entry cli_sip_debug_deprecated =
18465 { { "sip", "debug", NULL },
18466 sip_do_debug_deprecated, "Enable SIP debugging",
18467 debug_usage };
18469 static struct ast_cli_entry cli_sip_no_debug_deprecated =
18470 { { "sip", "no", "debug", NULL },
18471 sip_no_debug_deprecated, "Disable SIP debugging",
18472 debug_usage };
18474 static struct ast_cli_entry cli_sip[] = {
18475 { { "sip", "show", "channels", NULL },
18476 sip_show_channels, "List active SIP channels",
18477 show_channels_usage },
18479 { { "sip", "show", "domains", NULL },
18480 sip_show_domains, "List our local SIP domains.",
18481 show_domains_usage },
18483 { { "sip", "show", "inuse", NULL },
18484 sip_show_inuse, "List all inuse/limits",
18485 show_inuse_usage },
18487 { { "sip", "show", "objects", NULL },
18488 sip_show_objects, "List all SIP object allocations",
18489 show_objects_usage },
18491 { { "sip", "show", "peers", NULL },
18492 sip_show_peers, "List defined SIP peers",
18493 show_peers_usage },
18495 { { "sip", "show", "registry", NULL },
18496 sip_show_registry, "List SIP registration status",
18497 show_reg_usage },
18499 { { "sip", "show", "settings", NULL },
18500 sip_show_settings, "Show SIP global settings",
18501 show_settings_usage },
18503 { { "sip", "show", "subscriptions", NULL },
18504 sip_show_subscriptions, "List active SIP subscriptions",
18505 show_subscriptions_usage },
18507 { { "sip", "show", "users", NULL },
18508 sip_show_users, "List defined SIP users",
18509 show_users_usage },
18511 { { "sip", "notify", NULL },
18512 sip_notify, "Send a notify packet to a SIP peer",
18513 notify_usage, complete_sipnotify },
18515 { { "sip", "show", "channel", NULL },
18516 sip_show_channel, "Show detailed SIP channel info",
18517 show_channel_usage, complete_sipch },
18519 { { "sip", "show", "history", NULL },
18520 sip_show_history, "Show SIP dialog history",
18521 show_history_usage, complete_sipch },
18523 { { "sip", "show", "peer", NULL },
18524 sip_show_peer, "Show details on specific SIP peer",
18525 show_peer_usage, complete_sip_show_peer },
18527 { { "sip", "show", "user", NULL },
18528 sip_show_user, "Show details on specific SIP user",
18529 show_user_usage, complete_sip_show_user },
18531 { { "sip", "prune", "realtime", NULL },
18532 sip_prune_realtime, "Prune cached Realtime object(s)",
18533 prune_realtime_usage },
18535 { { "sip", "prune", "realtime", "peer", NULL },
18536 sip_prune_realtime, "Prune cached Realtime peer(s)",
18537 prune_realtime_usage, complete_sip_prune_realtime_peer },
18539 { { "sip", "prune", "realtime", "user", NULL },
18540 sip_prune_realtime, "Prune cached Realtime user(s)",
18541 prune_realtime_usage, complete_sip_prune_realtime_user },
18543 { { "sip", "set", "debug", NULL },
18544 sip_do_debug, "Enable SIP debugging",
18545 debug_usage, NULL, &cli_sip_debug_deprecated },
18547 { { "sip", "set", "debug", "ip", NULL },
18548 sip_do_debug, "Enable SIP debugging on IP",
18549 debug_usage },
18551 { { "sip", "set", "debug", "peer", NULL },
18552 sip_do_debug, "Enable SIP debugging on Peername",
18553 debug_usage, complete_sip_debug_peer },
18555 { { "sip", "set", "debug", "off", NULL },
18556 sip_no_debug, "Disable SIP debugging",
18557 no_debug_usage, NULL, &cli_sip_no_debug_deprecated },
18559 { { "sip", "history", NULL },
18560 sip_do_history, "Enable SIP history",
18561 history_usage },
18563 { { "sip", "history", "off", NULL },
18564 sip_no_history, "Disable SIP history",
18565 no_history_usage },
18567 { { "sip", "reload", NULL },
18568 sip_reload, "Reload SIP configuration",
18569 sip_reload_usage },
18572 /*! \brief PBX load module - initialization */
18573 static int load_module(void)
18575 ASTOBJ_CONTAINER_INIT(&userl); /* User object list */
18576 ASTOBJ_CONTAINER_INIT(&peerl); /* Peer object list */
18577 ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list */
18579 if (!(sched = sched_context_create())) {
18580 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
18581 return AST_MODULE_LOAD_FAILURE;
18584 if (!(io = io_context_create())) {
18585 ast_log(LOG_ERROR, "Unable to create I/O context\n");
18586 sched_context_destroy(sched);
18587 return AST_MODULE_LOAD_FAILURE;
18590 sip_reloadreason = CHANNEL_MODULE_LOAD;
18592 if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
18593 return AST_MODULE_LOAD_DECLINE;
18595 /* Make sure we can register our sip channel type */
18596 if (ast_channel_register(&sip_tech)) {
18597 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
18598 io_context_destroy(io);
18599 sched_context_destroy(sched);
18600 return AST_MODULE_LOAD_FAILURE;
18603 /* Register all CLI functions for SIP */
18604 ast_cli_register_multiple(cli_sip, sizeof(cli_sip)/ sizeof(struct ast_cli_entry));
18606 /* Tell the RTP subdriver that we're here */
18607 ast_rtp_proto_register(&sip_rtp);
18609 /* Tell the UDPTL subdriver that we're here */
18610 ast_udptl_proto_register(&sip_udptl);
18612 /* Register dialplan applications */
18613 ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
18614 ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
18616 /* Register dialplan functions */
18617 ast_custom_function_register(&sip_header_function);
18618 ast_custom_function_register(&sippeer_function);
18619 ast_custom_function_register(&sipchaninfo_function);
18620 ast_custom_function_register(&checksipdomain_function);
18622 /* Register manager commands */
18623 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM, manager_sip_show_peers,
18624 "List SIP peers (text format)", mandescr_show_peers);
18625 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM, manager_sip_show_peer,
18626 "Show SIP peer (text format)", mandescr_show_peer);
18628 sip_poke_all_peers();
18629 sip_send_all_registers();
18631 /* And start the monitor for the first time */
18632 restart_monitor();
18634 return AST_MODULE_LOAD_SUCCESS;
18637 /*! \brief PBX unload module API */
18638 static int unload_module(void)
18640 struct sip_pvt *p, *pl;
18642 /* First, take us out of the channel type list */
18643 ast_channel_unregister(&sip_tech);
18645 /* Unregister dial plan functions */
18646 ast_custom_function_unregister(&sipchaninfo_function);
18647 ast_custom_function_unregister(&sippeer_function);
18648 ast_custom_function_unregister(&sip_header_function);
18649 ast_custom_function_unregister(&checksipdomain_function);
18651 /* Unregister dial plan applications */
18652 ast_unregister_application(app_dtmfmode);
18653 ast_unregister_application(app_sipaddheader);
18655 /* Unregister CLI commands */
18656 ast_cli_unregister_multiple(cli_sip, sizeof(cli_sip) / sizeof(struct ast_cli_entry));
18658 /* Disconnect from the RTP subsystem */
18659 ast_rtp_proto_unregister(&sip_rtp);
18661 /* Disconnect from UDPTL */
18662 ast_udptl_proto_unregister(&sip_udptl);
18664 /* Unregister AMI actions */
18665 ast_manager_unregister("SIPpeers");
18666 ast_manager_unregister("SIPshowpeer");
18668 ast_mutex_lock(&iflock);
18669 /* Hangup all interfaces if they have an owner */
18670 for (p = iflist; p ; p = p->next) {
18671 if (p->owner)
18672 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
18674 ast_mutex_unlock(&iflock);
18676 ast_mutex_lock(&monlock);
18677 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
18678 pthread_cancel(monitor_thread);
18679 pthread_kill(monitor_thread, SIGURG);
18680 pthread_join(monitor_thread, NULL);
18682 monitor_thread = AST_PTHREADT_STOP;
18683 ast_mutex_unlock(&monlock);
18685 restartdestroy:
18686 ast_mutex_lock(&iflock);
18687 /* Destroy all the interfaces and free their memory */
18688 p = iflist;
18689 while (p) {
18690 pl = p;
18691 p = p->next;
18692 if (__sip_destroy(pl, TRUE) < 0) {
18693 /* Something is still bridged, let it react to getting a hangup */
18694 iflist = p;
18695 ast_mutex_unlock(&iflock);
18696 usleep(1);
18697 goto restartdestroy;
18700 iflist = NULL;
18701 ast_mutex_unlock(&iflock);
18703 /* Free memory for local network address mask */
18704 ast_free_ha(localaddr);
18706 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
18707 ASTOBJ_CONTAINER_DESTROY(&userl);
18708 ASTOBJ_CONTAINER_DESTROYALL(&peerl, sip_destroy_peer);
18709 ASTOBJ_CONTAINER_DESTROY(&peerl);
18710 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
18711 ASTOBJ_CONTAINER_DESTROY(&regl);
18713 clear_realm_authentication(authl);
18714 clear_sip_domains();
18715 close(sipsock);
18716 sched_context_destroy(sched);
18718 return 0;
18721 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
18722 .load = load_module,
18723 .unload = unload_module,
18724 .reload = reload,