Merge changes from team/russell/issue_9520
[asterisk-bristuff.git] / channels / chan_sip.c
blob8ebe9d520a903148a3dcf9e5d087afd710c588b7
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
19 /*!
20 * \file
21 * \brief Implementation of Session Initiation Protocol
23 * \author Mark Spencer <markster@digium.com>
25 * See Also:
26 * \arg \ref AstCREDITS
28 * Implementation of RFC 3261 - without S/MIME, TCP and TLS support
29 * Configuration file \link Config_sip sip.conf \endlink
32 * \todo SIP over TCP
33 * \todo SIP over TLS
34 * \todo Better support of forking
35 * \todo VIA branch tag transaction checking
36 * \todo Transaction support
38 * \ingroup channel_drivers
40 * \par Overview of the handling of SIP sessions
41 * The SIP channel handles several types of SIP sessions, or dialogs,
42 * not all of them being "telephone calls".
43 * - Incoming calls that will be sent to the PBX core
44 * - Outgoing calls, generated by the PBX
45 * - SIP subscriptions and notifications of states and voicemail messages
46 * - SIP registrations, both inbound and outbound
47 * - SIP peer management (peerpoke, OPTIONS)
48 * - SIP text messages
50 * In the SIP channel, there's a list of active SIP dialogs, which includes
51 * all of these when they are active. "sip show channels" in the CLI will
52 * show most of these, excluding subscriptions which are shown by
53 * "sip show subscriptions"
55 * \par incoming packets
56 * Incoming packets are received in the monitoring thread, then handled by
57 * sipsock_read(). This function parses the packet and matches an existing
58 * dialog or starts a new SIP dialog.
60 * sipsock_read sends the packet to handle_request(), that parses a bit more.
61 * if it's a response to an outbound request, it's sent to handle_response().
62 * If it is a request, handle_request sends it to one of a list of functions
63 * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
64 * sipsock_read locks the ast_channel if it exists (an active call) and
65 * unlocks it after we have processed the SIP message.
67 * A new INVITE is sent to handle_request_invite(), that will end up
68 * starting a new channel in the PBX, the new channel after that executing
69 * in a separate channel thread. This is an incoming "call".
70 * When the call is answered, either by a bridged channel or the PBX itself
71 * the sip_answer() function is called.
73 * The actual media - Video or Audio - is mostly handled by the RTP subsystem
74 * in rtp.c
76 * \par Outbound calls
77 * Outbound calls are set up by the PBX through the sip_request_call()
78 * function. After that, they are activated by sip_call().
80 * \par Hanging up
81 * The PBX issues a hangup on both incoming and outgoing calls through
82 * the sip_hangup() function
84 * \par Deprecated stuff
85 * This is deprecated and will be removed after the 1.4 release
86 * - the SIPUSERAGENT dialplan variable
87 * - the ALERT_INFO dialplan variable
90 /*** MODULEINFO
91 <depend>res_features</depend>
92 ***/
95 #include "asterisk.h"
97 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
99 #include <stdio.h>
100 #include <ctype.h>
101 #include <string.h>
102 #include <unistd.h>
103 #include <sys/socket.h>
104 #include <sys/ioctl.h>
105 #include <net/if.h>
106 #include <errno.h>
107 #include <stdlib.h>
108 #include <fcntl.h>
109 #include <netdb.h>
110 #include <signal.h>
111 #include <sys/signal.h>
112 #include <netinet/in.h>
113 #include <netinet/in_systm.h>
114 #include <arpa/inet.h>
115 #include <netinet/ip.h>
116 #include <regex.h>
118 #include "asterisk/lock.h"
119 #include "asterisk/channel.h"
120 #include "asterisk/config.h"
121 #include "asterisk/logger.h"
122 #include "asterisk/module.h"
123 #include "asterisk/pbx.h"
124 #include "asterisk/options.h"
125 #include "asterisk/sched.h"
126 #include "asterisk/io.h"
127 #include "asterisk/rtp.h"
128 #include "asterisk/udptl.h"
129 #include "asterisk/acl.h"
130 #include "asterisk/manager.h"
131 #include "asterisk/callerid.h"
132 #include "asterisk/cli.h"
133 #include "asterisk/app.h"
134 #include "asterisk/musiconhold.h"
135 #include "asterisk/dsp.h"
136 #include "asterisk/features.h"
137 #include "asterisk/srv.h"
138 #include "asterisk/astdb.h"
139 #include "asterisk/causes.h"
140 #include "asterisk/utils.h"
141 #include "asterisk/file.h"
142 #include "asterisk/astobj.h"
143 #include "asterisk/devicestate.h"
144 #include "asterisk/linkedlists.h"
145 #include "asterisk/stringfields.h"
146 #include "asterisk/monitor.h"
147 #include "asterisk/localtime.h"
148 #include "asterisk/abstract_jb.h"
149 #include "asterisk/compiler.h"
150 #include "asterisk/threadstorage.h"
151 #include "asterisk/translate.h"
153 #ifndef FALSE
154 #define FALSE 0
155 #endif
157 #ifndef TRUE
158 #define TRUE 1
159 #endif
161 #define SIPBUFSIZE 512
163 #define XMIT_ERROR -2
165 #define VIDEO_CODEC_MASK 0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
166 #ifndef IPTOS_MINCOST
167 #define IPTOS_MINCOST 0x02
168 #endif
170 /* #define VOCAL_DATA_HACK */
172 #define DEFAULT_DEFAULT_EXPIRY 120
173 #define DEFAULT_MIN_EXPIRY 60
174 #define DEFAULT_MAX_EXPIRY 3600
175 #define DEFAULT_REGISTRATION_TIMEOUT 20
176 #define DEFAULT_MAX_FORWARDS "70"
178 /* guard limit must be larger than guard secs */
179 /* guard min must be < 1000, and should be >= 250 */
180 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
181 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
182 EXPIRY_GUARD_SECS */
183 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
184 GUARD_PCT turns out to be lower than this, it
185 will use this time instead.
186 This is in milliseconds. */
187 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
188 below EXPIRY_GUARD_LIMIT */
189 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
191 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
192 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
193 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
194 static int expiry = DEFAULT_EXPIRY;
196 #ifndef MAX
197 #define MAX(a,b) ((a) > (b) ? (a) : (b))
198 #endif
200 #define CALLERID_UNKNOWN "Unknown"
202 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
203 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
204 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
206 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
207 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
208 #define SIP_TRANS_TIMEOUT 32000 /*!< SIP request timeout (rfc 3261) 64*T1
209 \todo Use known T1 for timeout (peerpoke)
211 #define DEFAULT_TRANS_TIMEOUT -1 /* Use default SIP transaction timeout */
212 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
214 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
215 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
216 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
218 #define SDP_MAX_RTPMAP_CODECS 32 /*!< Maximum number of codecs allowed in received SDP */
220 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
222 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
223 static struct ast_jb_conf default_jbconf =
225 .flags = 0,
226 .max_size = -1,
227 .resync_threshold = -1,
228 .impl = ""
230 static struct ast_jb_conf global_jbconf;
232 static const char config[] = "sip.conf";
233 static const char notify_config[] = "sip_notify.conf";
235 #define RTP 1
236 #define NO_RTP 0
238 /*! \brief Authorization scheme for call transfers
239 \note Not a bitfield flag, since there are plans for other modes,
240 like "only allow transfers for authenticated devices" */
241 enum transfermodes {
242 TRANSFER_OPENFORALL, /*!< Allow all SIP transfers */
243 TRANSFER_CLOSED, /*!< Allow no SIP transfers */
247 enum sip_result {
248 AST_SUCCESS = 0,
249 AST_FAILURE = -1,
252 /*! \brief States for the INVITE transaction, not the dialog
253 \note this is for the INVITE that sets up the dialog
255 enum invitestates {
256 INV_NONE = 0, /*!< No state at all, maybe not an INVITE dialog */
257 INV_CALLING = 1, /*!< Invite sent, no answer */
258 INV_PROCEEDING = 2, /*!< We got/sent 1xx message */
259 INV_EARLY_MEDIA = 3, /*!< We got 18x message with to-tag back */
260 INV_COMPLETED = 4, /*!< Got final response with error. Wait for ACK, then CONFIRMED */
261 INV_CONFIRMED = 5, /*!< Confirmed response - we've got an ack (Incoming calls only) */
262 INV_TERMINATED = 6, /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done
263 The only way out of this is a BYE from one side */
264 INV_CANCELLED = 7, /*!< Transaction cancelled by client or server in non-terminated state */
267 /* Do _NOT_ make any changes to this enum, or the array following it;
268 if you think you are doing the right thing, you are probably
269 not doing the right thing. If you think there are changes
270 needed, get someone else to review them first _before_
271 submitting a patch. If these two lists do not match properly
272 bad things will happen.
275 enum xmittype {
276 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
277 If it fails, it's critical and will cause a teardown of the session */
278 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
279 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
282 enum parse_register_result {
283 PARSE_REGISTER_FAILED,
284 PARSE_REGISTER_UPDATE,
285 PARSE_REGISTER_QUERY,
288 enum subscriptiontype {
289 NONE = 0,
290 XPIDF_XML,
291 DIALOG_INFO_XML,
292 CPIM_PIDF_XML,
293 PIDF_XML,
294 MWI_NOTIFICATION
297 static const struct cfsubscription_types {
298 enum subscriptiontype type;
299 const char * const event;
300 const char * const mediatype;
301 const char * const text;
302 } subscription_types[] = {
303 { NONE, "-", "unknown", "unknown" },
304 /* RFC 4235: SIP Dialog event package */
305 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
306 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
307 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
308 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
309 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
312 /*! \brief SIP Request methods known by Asterisk */
313 enum sipmethod {
314 SIP_UNKNOWN, /* Unknown response */
315 SIP_RESPONSE, /* Not request, response to outbound request */
316 SIP_REGISTER,
317 SIP_OPTIONS,
318 SIP_NOTIFY,
319 SIP_INVITE,
320 SIP_ACK,
321 SIP_PRACK, /* Not supported at all */
322 SIP_BYE,
323 SIP_REFER,
324 SIP_SUBSCRIBE,
325 SIP_MESSAGE,
326 SIP_UPDATE, /* We can send UPDATE; but not accept it */
327 SIP_INFO,
328 SIP_CANCEL,
329 SIP_PUBLISH, /* Not supported at all */
330 SIP_PING, /* Not supported at all, no standard but still implemented out there */
333 /*! \brief Authentication types - proxy or www authentication
334 \note Endpoints, like Asterisk, should always use WWW authentication to
335 allow multiple authentications in the same call - to the proxy and
336 to the end point.
338 enum sip_auth_type {
339 PROXY_AUTH,
340 WWW_AUTH,
343 /*! \brief Authentication result from check_auth* functions */
344 enum check_auth_result {
345 AUTH_SUCCESSFUL = 0,
346 AUTH_CHALLENGE_SENT = 1,
347 AUTH_SECRET_FAILED = -1,
348 AUTH_USERNAME_MISMATCH = -2,
349 AUTH_NOT_FOUND = -3,
350 AUTH_FAKE_AUTH = -4,
351 AUTH_UNKNOWN_DOMAIN = -5,
352 AUTH_PEER_NOT_DYNAMIC = -6,
353 AUTH_ACL_FAILED = -7,
356 /*! \brief States for outbound registrations (with register= lines in sip.conf */
357 enum sipregistrystate {
358 REG_STATE_UNREGISTERED = 0, /*!< We are not registred */
359 REG_STATE_REGSENT, /*!< Registration request sent */
360 REG_STATE_AUTHSENT, /*!< We have tried to authenticate */
361 REG_STATE_REGISTERED, /*!< Registred and done */
362 REG_STATE_REJECTED, /*!< Registration rejected */
363 REG_STATE_TIMEOUT, /*!< Registration timed out */
364 REG_STATE_NOAUTH, /*!< We have no accepted credentials */
365 REG_STATE_FAILED, /*!< Registration failed after several tries */
368 #define CAN_NOT_CREATE_DIALOG 0
369 #define CAN_CREATE_DIALOG 1
370 #define CAN_CREATE_DIALOG_UNSUPPORTED_METHOD 2
372 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
373 static const struct cfsip_methods {
374 enum sipmethod id;
375 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
376 char * const text;
377 int can_create;
378 } sip_methods[] = {
379 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
380 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
381 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
382 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
383 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
384 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
385 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
386 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
387 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
388 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
389 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
390 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
391 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
392 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
393 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
394 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
395 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
398 /*! Define SIP option tags, used in Require: and Supported: headers
399 We need to be aware of these properties in the phones to use
400 the replace: header. We should not do that without knowing
401 that the other end supports it...
402 This is nothing we can configure, we learn by the dialog
403 Supported: header on the REGISTER (peer) or the INVITE
404 (other devices)
405 We are not using many of these today, but will in the future.
406 This is documented in RFC 3261
408 #define SUPPORTED 1
409 #define NOT_SUPPORTED 0
411 #define SIP_OPT_REPLACES (1 << 0)
412 #define SIP_OPT_100REL (1 << 1)
413 #define SIP_OPT_TIMER (1 << 2)
414 #define SIP_OPT_EARLY_SESSION (1 << 3)
415 #define SIP_OPT_JOIN (1 << 4)
416 #define SIP_OPT_PATH (1 << 5)
417 #define SIP_OPT_PREF (1 << 6)
418 #define SIP_OPT_PRECONDITION (1 << 7)
419 #define SIP_OPT_PRIVACY (1 << 8)
420 #define SIP_OPT_SDP_ANAT (1 << 9)
421 #define SIP_OPT_SEC_AGREE (1 << 10)
422 #define SIP_OPT_EVENTLIST (1 << 11)
423 #define SIP_OPT_GRUU (1 << 12)
424 #define SIP_OPT_TARGET_DIALOG (1 << 13)
425 #define SIP_OPT_NOREFERSUB (1 << 14)
426 #define SIP_OPT_HISTINFO (1 << 15)
427 #define SIP_OPT_RESPRIORITY (1 << 16)
429 /*! \brief List of well-known SIP options. If we get this in a require,
430 we should check the list and answer accordingly. */
431 static const struct cfsip_options {
432 int id; /*!< Bitmap ID */
433 int supported; /*!< Supported by Asterisk ? */
434 char * const text; /*!< Text id, as in standard */
435 } sip_options[] = { /* XXX used in 3 places */
436 /* RFC3891: Replaces: header for transfer */
437 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
438 /* One version of Polycom firmware has the wrong label */
439 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
440 /* RFC3262: PRACK 100% reliability */
441 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
442 /* RFC4028: SIP Session Timers */
443 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
444 /* RFC3959: SIP Early session support */
445 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
446 /* RFC3911: SIP Join header support */
447 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
448 /* RFC3327: Path support */
449 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
450 /* RFC3840: Callee preferences */
451 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
452 /* RFC3312: Precondition support */
453 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
454 /* RFC3323: Privacy with proxies*/
455 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
456 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
457 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
458 /* RFC3329: Security agreement mechanism */
459 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
460 /* SIMPLE events: RFC4662 */
461 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
462 /* GRUU: Globally Routable User Agent URI's */
463 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
464 /* RFC4538: Target-dialog */
465 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
466 /* Disable the REFER subscription, RFC 4488 */
467 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
468 /* ietf-sip-history-info-06.txt */
469 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
470 /* ietf-sip-resource-priority-10.txt */
471 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
475 /*! \brief SIP Methods we support */
476 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
478 /*! \brief SIP Extensions we support */
479 #define SUPPORTED_EXTENSIONS "replaces"
481 /*! \brief Standard SIP port from RFC 3261. DO NOT CHANGE THIS */
482 #define STANDARD_SIP_PORT 5060
483 /* Note: in many SIP headers, absence of a port number implies port 5060,
484 * and this is why we cannot change the above constant.
485 * There is a limited number of places in asterisk where we could,
486 * in principle, use a different "default" port number, but
487 * we do not support this feature at the moment.
490 /* Default values, set and reset in reload_config before reading configuration */
491 /* These are default values in the source. There are other recommended values in the
492 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
493 yet encouraging new behaviour on new installations
495 #define DEFAULT_CONTEXT "default"
496 #define DEFAULT_MOHINTERPRET "default"
497 #define DEFAULT_MOHSUGGEST ""
498 #define DEFAULT_VMEXTEN "asterisk"
499 #define DEFAULT_CALLERID "asterisk"
500 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
501 #define DEFAULT_MWITIME 10
502 #define DEFAULT_ALLOWGUEST TRUE
503 #define DEFAULT_SRVLOOKUP TRUE /*!< Recommended setting is ON */
504 #define DEFAULT_COMPACTHEADERS FALSE
505 #define DEFAULT_TOS_SIP 0 /*!< Call signalling packets should be marked as DSCP CS3, but the default is 0 to be compatible with previous versions. */
506 #define DEFAULT_TOS_AUDIO 0 /*!< Audio packets should be marked as DSCP EF (Expedited Forwarding), but the default is 0 to be compatible with previous versions. */
507 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
508 #define DEFAULT_ALLOW_EXT_DOM TRUE
509 #define DEFAULT_REALM "asterisk"
510 #define DEFAULT_NOTIFYRINGING TRUE
511 #define DEFAULT_PEDANTIC FALSE
512 #define DEFAULT_AUTOCREATEPEER FALSE
513 #define DEFAULT_QUALIFY FALSE
514 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
515 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
516 #ifndef DEFAULT_USERAGENT
517 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
518 #endif
521 /* Default setttings are used as a channel setting and as a default when
522 configuring devices */
523 static char default_context[AST_MAX_CONTEXT];
524 static char default_subscribecontext[AST_MAX_CONTEXT];
525 static char default_language[MAX_LANGUAGE];
526 static char default_callerid[AST_MAX_EXTENSION];
527 static char default_fromdomain[AST_MAX_EXTENSION];
528 static char default_notifymime[AST_MAX_EXTENSION];
529 static int default_qualify; /*!< Default Qualify= setting */
530 static char default_vmexten[AST_MAX_EXTENSION];
531 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
532 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
533 * a bridged channel on hold */
534 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
535 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
537 /* Global settings only apply to the channel */
538 static int global_directrtpsetup; /*!< Enable support for Direct RTP setup (no re-invites) */
539 static int global_limitonpeers; /*!< Match call limit on peers only */
540 static int global_rtautoclear;
541 static int global_notifyringing; /*!< Send notifications on ringing */
542 static int global_notifyhold; /*!< Send notifications on hold */
543 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
544 static int srvlookup; /*!< SRV Lookup on or off. Default is on */
545 static int pedanticsipchecking; /*!< Extra checking ? Default off */
546 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
547 static int global_relaxdtmf; /*!< Relax DTMF */
548 static int global_rtptimeout; /*!< Time out call if no RTP */
549 static int global_rtpholdtimeout;
550 static int global_rtpkeepalive; /*!< Send RTP keepalives */
551 static int global_reg_timeout;
552 static int global_regattempts_max; /*!< Registration attempts before giving up */
553 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
554 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
555 the global setting is in globals_flags[1] */
556 static int global_mwitime; /*!< Time between MWI checks for peers */
557 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
558 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
559 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
560 static int compactheaders; /*!< send compact sip headers */
561 static int recordhistory; /*!< Record SIP history. Off by default */
562 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
563 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
564 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
565 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
566 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
567 static int global_callevents; /*!< Whether we send manager events or not */
568 static int global_t1min; /*!< T1 roundtrip time minimum */
569 static int global_autoframing; /*!< Turn autoframing on or off. */
570 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
572 static int global_matchexterniplocally; /*!< Match externip/externhost setting against localnet setting */
574 /*! \brief Codecs that we support by default: */
575 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
577 /* Object counters */
578 static int suserobjs = 0; /*!< Static users */
579 static int ruserobjs = 0; /*!< Realtime users */
580 static int speerobjs = 0; /*!< Statis peers */
581 static int rpeerobjs = 0; /*!< Realtime peers */
582 static int apeerobjs = 0; /*!< Autocreated peer objects */
583 static int regobjs = 0; /*!< Registry objects */
585 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
587 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
588 AST_MUTEX_DEFINE_STATIC(iflock);
590 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
591 when it's doing something critical. */
592 AST_MUTEX_DEFINE_STATIC(netlock);
594 AST_MUTEX_DEFINE_STATIC(monlock);
596 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
598 /*! \brief This is the thread for the monitor which checks for input on the channels
599 which are not currently in use. */
600 static pthread_t monitor_thread = AST_PTHREADT_NULL;
602 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
603 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
605 static struct sched_context *sched; /*!< The scheduling context */
606 static struct io_context *io; /*!< The IO context */
607 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
609 #define DEC_CALL_LIMIT 0
610 #define INC_CALL_LIMIT 1
611 #define DEC_CALL_RINGING 2
612 #define INC_CALL_RINGING 3
614 /*! \brief sip_request: The data grabbed from the UDP socket */
615 struct sip_request {
616 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
617 char *rlPart2; /*!< The Request URI or Response Status */
618 int len; /*!< Length */
619 int headers; /*!< # of SIP Headers */
620 int method; /*!< Method of this request */
621 int lines; /*!< Body Content */
622 unsigned int flags; /*!< SIP_PKT Flags for this packet */
623 char *header[SIP_MAX_HEADERS];
624 char *line[SIP_MAX_LINES];
625 char data[SIP_MAX_PACKET];
626 unsigned int sdp_start; /*!< the line number where the SDP begins */
627 unsigned int sdp_end; /*!< the line number where the SDP ends */
631 * A sip packet is stored into the data[] buffer, with the header followed
632 * by an empty line and the body of the message.
633 * On outgoing packets, data is accumulated in data[] with len reflecting
634 * the next available byte, headers and lines count the number of lines
635 * in both parts. There are no '\0' in data[0..len-1].
637 * On received packet, the input read from the socket is copied into data[],
638 * len is set and the string is NUL-terminated. Then a parser fills up
639 * the other fields -header[] and line[] to point to the lines of the
640 * message, rlPart1 and rlPart2 parse the first lnie as below:
642 * Requests have in the first line METHOD URI SIP/2.0
643 * rlPart1 = method; rlPart2 = uri;
644 * Responses have in the first line SIP/2.0 code description
645 * rlPart1 = SIP/2.0; rlPart2 = code + description;
649 /*! \brief structure used in transfers */
650 struct sip_dual {
651 struct ast_channel *chan1; /*!< First channel involved */
652 struct ast_channel *chan2; /*!< Second channel involved */
653 struct sip_request req; /*!< Request that caused the transfer (REFER) */
654 int seqno; /*!< Sequence number */
657 struct sip_pkt;
659 /*! \brief Parameters to the transmit_invite function */
660 struct sip_invite_param {
661 const char *distinctive_ring; /*!< Distinctive ring header */
662 int addsipheaders; /*!< Add extra SIP headers */
663 const char *uri_options; /*!< URI options to add to the URI */
664 const char *vxml_url; /*!< VXML url for Cisco phones */
665 char *auth; /*!< Authentication */
666 char *authheader; /*!< Auth header */
667 enum sip_auth_type auth_type; /*!< Authentication type */
668 const char *replaces; /*!< Replaces header for call transfers */
669 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
672 /*! \brief Structure to save routing information for a SIP session */
673 struct sip_route {
674 struct sip_route *next;
675 char hop[0];
678 /*! \brief Modes for SIP domain handling in the PBX */
679 enum domain_mode {
680 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
681 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
684 /*! \brief Domain data structure.
685 \note In the future, we will connect this to a configuration tree specific
686 for this domain
688 struct domain {
689 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
690 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
691 enum domain_mode mode; /*!< How did we find this domain? */
692 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
695 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
698 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
699 struct sip_history {
700 AST_LIST_ENTRY(sip_history) list;
701 char event[0]; /* actually more, depending on needs */
704 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
706 /*! \brief sip_auth: Credentials for authentication to other SIP services */
707 struct sip_auth {
708 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
709 char username[256]; /*!< Username */
710 char secret[256]; /*!< Secret */
711 char md5secret[256]; /*!< MD5Secret */
712 struct sip_auth *next; /*!< Next auth structure in list */
715 /*--- Various flags for the flags field in the pvt structure */
716 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
717 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed by the monitor thread */
718 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
719 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
720 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
721 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
722 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
723 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
724 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
725 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
726 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
727 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
728 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
729 #define SIP_OUTGOING (1 << 13) /*!< Direction of the last transaction in this dialog */
730 #define SIP_FREE_BIT (1 << 14) /*!< ---- */
731 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 15) /*!< Do not hangup at first ast_hangup */
732 #define SIP_DTMF (3 << 16) /*!< DTMF Support: four settings, uses two bits */
733 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DTMF Support: RTP DTMF - "rfc2833" */
734 #define SIP_DTMF_INBAND (1 << 16) /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
735 #define SIP_DTMF_INFO (2 << 16) /*!< DTMF Support: SIP Info messages - "info" */
736 #define SIP_DTMF_AUTO (3 << 16) /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
737 /* NAT settings */
738 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
739 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
740 #define SIP_NAT_RFC3581 (1 << 18) /*!< NAT RFC3581 */
741 #define SIP_NAT_ROUTE (2 << 18) /*!< NAT Only ROUTE */
742 #define SIP_NAT_ALWAYS (3 << 18) /*!< NAT Both ROUTE and RFC3581 */
743 /* re-INVITE related settings */
744 #define SIP_REINVITE (7 << 20) /*!< three bits used */
745 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
746 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< allow media reinvite when new peer is behind NAT */
747 #define SIP_REINVITE_UPDATE (4 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
748 /* "insecure" settings */
749 #define SIP_INSECURE_PORT (1 << 23) /*!< don't require matching port for incoming requests */
750 #define SIP_INSECURE_INVITE (1 << 24) /*!< don't require authentication for incoming INVITEs */
751 /* Sending PROGRESS in-band settings */
752 #define SIP_PROG_INBAND (3 << 25) /*!< three settings, uses two bits */
753 #define SIP_PROG_INBAND_NEVER (0 << 25)
754 #define SIP_PROG_INBAND_NO (1 << 25)
755 #define SIP_PROG_INBAND_YES (2 << 25)
756 #define SIP_NO_HISTORY (1 << 27) /*!< Suppress recording request/response history */
757 #define SIP_CALL_LIMIT (1 << 28) /*!< Call limit enforced for this call */
758 #define SIP_SENDRPID (1 << 29) /*!< Remote Party-ID Support */
759 #define SIP_INC_COUNT (1 << 30) /*!< Did this connection increment the counter of in-use calls? */
760 #define SIP_G726_NONSTANDARD (1 << 31) /*!< Use non-standard packing for G726-32 data */
762 #define SIP_FLAGS_TO_COPY \
763 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
764 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
765 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
767 /*--- a new page of flags (for flags[1] */
768 /* realtime flags */
769 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
770 #define SIP_PAGE2_RTUPDATE (1 << 1)
771 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
772 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
773 #define SIP_PAGE2_RTSAVE_SYSNAME (1 << 5)
774 /* Space for addition of other realtime flags in the future */
775 #define SIP_PAGE2_STATECHANGEQUEUE (1 << 9) /*!< D: Unsent state pending change exists */
776 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 10)
777 #define SIP_PAGE2_DEBUG (3 << 11)
778 #define SIP_PAGE2_DEBUG_CONFIG (1 << 11)
779 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 12)
780 #define SIP_PAGE2_DYNAMIC (1 << 13) /*!< Dynamic Peers register with Asterisk */
781 #define SIP_PAGE2_SELFDESTRUCT (1 << 14) /*!< Automatic peers need to destruct themselves */
782 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15)
783 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< Allow subscriptions from this peer? */
784 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< Allow overlap dialing ? */
785 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< Only issue MWI notification if subscribed to */
786 #define SIP_PAGE2_INC_RINGING (1 << 19) /*!< Did this connection increment the counter of in-use calls? */
787 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< T38 Fax Passthrough Support */
788 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< 20: T38 Fax Passthrough Support */
789 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< 21: T38 Fax Passthrough Support (not implemented) */
790 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< 22: T38 Fax Passthrough Support (not implemented) */
791 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< Call states */
792 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23) /*!< 23: Active hold */
793 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23) /*!< 23: One directional hold */
794 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23) /*!< 23: Inactive hold */
795 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25) /*!< 25: ???? */
796 #define SIP_PAGE2_BUGGY_MWI (1 << 26) /*!< 26: Buggy CISCO MWI fix */
797 #define SIP_PAGE2_OUTGOING_CALL (1 << 27) /*!< 27: Is this an outgoing call? */
799 #define SIP_PAGE2_FLAGS_TO_COPY \
800 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
801 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI)
803 /* SIP packet flags */
804 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
805 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
806 #define SIP_PKT_IGNORE (1 << 2) /*!< This is a re-transmit, ignore it */
807 #define SIP_PKT_IGNORE_RESP (1 << 3) /*!< Resp ignore - ??? */
808 #define SIP_PKT_IGNORE_REQ (1 << 4) /*!< Req ignore - ??? */
810 /* T.38 set of flags */
811 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
812 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
813 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
814 /* Rate management */
815 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
816 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
817 /* UDP Error correction */
818 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
819 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
820 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
821 /* T38 Spec version */
822 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
823 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
824 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
825 /* Maximum Fax Rate */
826 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
827 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
828 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
829 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
830 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
831 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
833 /*!< This is default: NO MMR and JBIG trancoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
834 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
836 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
837 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
838 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
840 /*! \brief T38 States for a call */
841 enum t38state {
842 T38_DISABLED = 0, /*!< Not enabled */
843 T38_LOCAL_DIRECT, /*!< Offered from local */
844 T38_LOCAL_REINVITE, /*!< Offered from local - REINVITE */
845 T38_PEER_DIRECT, /*!< Offered from peer */
846 T38_PEER_REINVITE, /*!< Offered from peer - REINVITE */
847 T38_ENABLED /*!< Negotiated (enabled) */
850 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
851 struct t38properties {
852 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
853 int capability; /*!< Our T38 capability */
854 int peercapability; /*!< Peers T38 capability */
855 int jointcapability; /*!< Supported T38 capability at both ends */
856 enum t38state state; /*!< T.38 state */
859 /*! \brief Parameters to know status of transfer */
860 enum referstatus {
861 REFER_IDLE, /*!< No REFER is in progress */
862 REFER_SENT, /*!< Sent REFER to transferee */
863 REFER_RECEIVED, /*!< Received REFER from transferer */
864 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING */
865 REFER_ACCEPTED, /*!< Accepted by transferee */
866 REFER_RINGING, /*!< Target Ringing */
867 REFER_200OK, /*!< Answered by transfer target */
868 REFER_FAILED, /*!< REFER declined - go on */
869 REFER_NOAUTH /*!< We had no auth for REFER */
872 static const struct c_referstatusstring {
873 enum referstatus status;
874 char *text;
875 } referstatusstrings[] = {
876 { REFER_IDLE, "<none>" },
877 { REFER_SENT, "Request sent" },
878 { REFER_RECEIVED, "Request received" },
879 { REFER_ACCEPTED, "Accepted" },
880 { REFER_RINGING, "Target ringing" },
881 { REFER_200OK, "Done" },
882 { REFER_FAILED, "Failed" },
883 { REFER_NOAUTH, "Failed - auth failure" }
886 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed */
887 /* OEJ: Should be moved to string fields */
888 struct sip_refer {
889 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
890 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
891 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
892 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
893 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
894 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
895 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
896 char replaces_callid[SIPBUFSIZE]; /*!< Replace info: callid */
897 char replaces_callid_totag[SIPBUFSIZE/2]; /*!< Replace info: to-tag */
898 char replaces_callid_fromtag[SIPBUFSIZE/2]; /*!< Replace info: from-tag */
899 struct sip_pvt *refer_call; /*!< Call we are referring */
900 int attendedtransfer; /*!< Attended or blind transfer? */
901 int localtransfer; /*!< Transfer to local domain? */
902 enum referstatus status; /*!< REFER status */
905 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
906 static struct sip_pvt {
907 ast_mutex_t lock; /*!< Dialog private lock */
908 int method; /*!< SIP method that opened this dialog */
909 enum invitestates invitestate; /*!< The state of the INVITE transaction only */
910 AST_DECLARE_STRING_FIELDS(
911 AST_STRING_FIELD(callid); /*!< Global CallID */
912 AST_STRING_FIELD(randdata); /*!< Random data */
913 AST_STRING_FIELD(accountcode); /*!< Account code */
914 AST_STRING_FIELD(realm); /*!< Authorization realm */
915 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
916 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
917 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
918 AST_STRING_FIELD(domain); /*!< Authorization domain */
919 AST_STRING_FIELD(from); /*!< The From: header */
920 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
921 AST_STRING_FIELD(exten); /*!< Extension where to start */
922 AST_STRING_FIELD(context); /*!< Context for this call */
923 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
924 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
925 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
926 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
927 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
928 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
929 AST_STRING_FIELD(language); /*!< Default language for this call */
930 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
931 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
932 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
933 AST_STRING_FIELD(theirtag); /*!< Their tag */
934 AST_STRING_FIELD(username); /*!< [user] name */
935 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
936 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
937 AST_STRING_FIELD(uri); /*!< Original requested URI */
938 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
939 AST_STRING_FIELD(peersecret); /*!< Password */
940 AST_STRING_FIELD(peermd5secret);
941 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
942 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
943 AST_STRING_FIELD(via); /*!< Via: header */
944 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
945 AST_STRING_FIELD(our_contact); /*!< Our contact header */
946 AST_STRING_FIELD(rpid); /*!< Our RPID header */
947 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
949 unsigned int ocseq; /*!< Current outgoing seqno */
950 unsigned int icseq; /*!< Current incoming seqno */
951 ast_group_t callgroup; /*!< Call group */
952 ast_group_t pickupgroup; /*!< Pickup group */
953 int lastinvite; /*!< Last Cseq of invite */
954 int lastnoninvite; /*!< Last Cseq of non-invite */
955 struct ast_flags flags[2]; /*!< SIP_ flags */
956 int timer_t1; /*!< SIP timer T1, ms rtt */
957 unsigned int sipoptions; /*!< Supported SIP options on the other end */
958 struct ast_codec_pref prefs; /*!< codec prefs */
959 int capability; /*!< Special capability (codec) */
960 int jointcapability; /*!< Supported capability at both ends (codecs) */
961 int peercapability; /*!< Supported peer capability */
962 int prefcodec; /*!< Preferred codec (outbound only) */
963 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
964 int jointnoncodeccapability; /*!< Joint Non codec capability */
965 int redircodecs; /*!< Redirect codecs */
966 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
967 struct t38properties t38; /*!< T38 settings */
968 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
969 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
970 int callingpres; /*!< Calling presentation */
971 int authtries; /*!< Times we've tried to authenticate */
972 int expiry; /*!< How long we take to expire */
973 long branch; /*!< The branch identifier of this session */
974 char tag[11]; /*!< Our tag for this session */
975 int sessionid; /*!< SDP Session ID */
976 int sessionversion; /*!< SDP Session Version */
977 struct sockaddr_in sa; /*!< Our peer */
978 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
979 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
980 time_t lastrtprx; /*!< Last RTP received */
981 time_t lastrtptx; /*!< Last RTP sent */
982 int rtptimeout; /*!< RTP timeout time */
983 struct sockaddr_in recv; /*!< Received as */
984 struct in_addr ourip; /*!< Our IP */
985 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
986 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
987 int route_persistant; /*!< Is this the "real" route? */
988 struct sip_auth *peerauth; /*!< Realm authentication */
989 int noncecount; /*!< Nonce-count */
990 char lastmsg[256]; /*!< Last Message sent/received */
991 int amaflags; /*!< AMA Flags */
992 int pendinginvite; /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
993 struct sip_request initreq; /*!< Request that opened the latest transaction
994 within this SIP dialog */
996 int maxtime; /*!< Max time for first response */
997 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
998 int waitid; /*!< Wait ID for scheduler after 491 or other delays */
999 int autokillid; /*!< Auto-kill ID (scheduler) */
1000 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
1001 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
1002 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
1003 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
1004 int laststate; /*!< SUBSCRIBE: Last known extension state */
1005 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
1007 struct ast_dsp *vad; /*!< Voice Activation Detection dsp */
1009 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
1010 Used in peerpoke, mwi subscriptions */
1011 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
1012 struct ast_rtp *rtp; /*!< RTP Session */
1013 struct ast_rtp *vrtp; /*!< Video RTP session */
1014 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
1015 struct sip_history_head *history; /*!< History of this SIP dialog */
1016 size_t history_entries; /*!< Number of entires in the history */
1017 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1018 struct sip_pvt *next; /*!< Next dialog in chain */
1019 struct sip_invite_param *options; /*!< Options for INVITE */
1020 int autoframing;
1021 } *iflist = NULL;
1023 /*! Max entires in the history list for a sip_pvt */
1024 #define MAX_HISTORY_ENTRIES 50
1026 #define FLAG_RESPONSE (1 << 0)
1027 #define FLAG_FATAL (1 << 1)
1029 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */
1030 struct sip_pkt {
1031 struct sip_pkt *next; /*!< Next packet in linked list */
1032 int retrans; /*!< Retransmission number */
1033 int method; /*!< SIP method for this packet */
1034 int seqno; /*!< Sequence number */
1035 unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */
1036 struct sip_pvt *owner; /*!< Owner AST call */
1037 int retransid; /*!< Retransmission ID */
1038 int timer_a; /*!< SIP timer A, retransmission timer */
1039 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
1040 int packetlen; /*!< Length of packet */
1041 char data[0];
1044 /*! \brief Structure for SIP user data. User's place calls to us */
1045 struct sip_user {
1046 /* Users who can access various contexts */
1047 ASTOBJ_COMPONENTS(struct sip_user);
1048 char secret[80]; /*!< Password */
1049 char md5secret[80]; /*!< Password in md5 */
1050 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1051 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
1052 char cid_num[80]; /*!< Caller ID num */
1053 char cid_name[80]; /*!< Caller ID name */
1054 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
1055 char language[MAX_LANGUAGE]; /*!< Default language for this user */
1056 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1057 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1058 char useragent[256]; /*!< User agent in SIP request */
1059 struct ast_codec_pref prefs; /*!< codec prefs */
1060 ast_group_t callgroup; /*!< Call group */
1061 ast_group_t pickupgroup; /*!< Pickup Group */
1062 unsigned int sipoptions; /*!< Supported SIP options */
1063 struct ast_flags flags[2]; /*!< SIP_ flags */
1064 int amaflags; /*!< AMA flags for billing */
1065 int callingpres; /*!< Calling id presentation */
1066 int capability; /*!< Codec capability */
1067 int inUse; /*!< Number of calls in use */
1068 int call_limit; /*!< Limit of concurrent calls */
1069 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1070 struct ast_ha *ha; /*!< ACL setting */
1071 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1072 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1073 int autoframing;
1076 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1077 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1078 struct sip_peer {
1079 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
1080 /*!< peer->name is the unique name of this object */
1081 char secret[80]; /*!< Password */
1082 char md5secret[80]; /*!< Password in MD5 */
1083 struct sip_auth *auth; /*!< Realm authentication list */
1084 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1085 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1086 char username[80]; /*!< Temporary username until registration */
1087 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1088 int amaflags; /*!< AMA Flags (for billing) */
1089 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1090 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1091 char fromuser[80]; /*!< From: user when calling this peer */
1092 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1093 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1094 char cid_num[80]; /*!< Caller ID num */
1095 char cid_name[80]; /*!< Caller ID name */
1096 int callingpres; /*!< Calling id presentation */
1097 int inUse; /*!< Number of calls in use */
1098 int inRinging; /*!< Number of calls ringing */
1099 int onHold; /*!< Peer has someone on hold */
1100 int call_limit; /*!< Limit of concurrent calls */
1101 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1102 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1103 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
1104 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1105 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1106 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1107 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1108 struct ast_codec_pref prefs; /*!< codec prefs */
1109 int lastmsgssent;
1110 time_t lastmsgcheck; /*!< Last time we checked for MWI */
1111 unsigned int sipoptions; /*!< Supported SIP options */
1112 struct ast_flags flags[2]; /*!< SIP_ flags */
1113 int expire; /*!< When to expire this peer registration */
1114 int capability; /*!< Codec capability */
1115 int rtptimeout; /*!< RTP timeout */
1116 int rtpholdtimeout; /*!< RTP Hold Timeout */
1117 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1118 ast_group_t callgroup; /*!< Call group */
1119 ast_group_t pickupgroup; /*!< Pickup group */
1120 struct sockaddr_in addr; /*!< IP address of peer */
1121 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1123 /* Qualification */
1124 struct sip_pvt *call; /*!< Call pointer */
1125 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1126 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1127 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1128 struct timeval ps; /*!< Ping send time */
1130 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1131 struct ast_ha *ha; /*!< Access control list */
1132 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1133 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1134 int lastmsg;
1135 int autoframing;
1140 /*! \brief Registrations with other SIP proxies */
1141 struct sip_registry {
1142 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1143 AST_DECLARE_STRING_FIELDS(
1144 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1145 AST_STRING_FIELD(realm); /*!< Authorization realm */
1146 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1147 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1148 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1149 AST_STRING_FIELD(domain); /*!< Authorization domain */
1150 AST_STRING_FIELD(username); /*!< Who we are registering as */
1151 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1152 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1153 AST_STRING_FIELD(secret); /*!< Password in clear text */
1154 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1155 AST_STRING_FIELD(contact); /*!< Contact extension */
1156 AST_STRING_FIELD(random);
1158 int portno; /*!< Optional port override */
1159 int expire; /*!< Sched ID of expiration */
1160 int regattempts; /*!< Number of attempts (since the last success) */
1161 int timeout; /*!< sched id of sip_reg_timeout */
1162 int refresh; /*!< How often to refresh */
1163 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1164 enum sipregistrystate regstate; /*!< Registration state (see above) */
1165 time_t regtime; /*!< Last succesful registration time */
1166 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1167 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1168 struct sockaddr_in us; /*!< Who the server thinks we are */
1169 int noncecount; /*!< Nonce-count */
1170 char lastmsg[256]; /*!< Last Message sent/received */
1173 /* --- Linked lists of various objects --------*/
1175 /*! \brief The user list: Users and friends */
1176 static struct ast_user_list {
1177 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1178 } userl;
1180 /*! \brief The peer list: Peers and Friends */
1181 static struct ast_peer_list {
1182 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1183 } peerl;
1185 /*! \brief The register list: Other SIP proxys we register with and place calls to */
1186 static struct ast_register_list {
1187 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1188 int recheck;
1189 } regl;
1191 static void temp_pvt_cleanup(void *);
1193 /*! \brief A per-thread temporary pvt structure */
1194 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1196 /*! \todo Move the sip_auth list to AST_LIST */
1197 static struct sip_auth *authl = NULL; /*!< Authentication list for realm authentication */
1200 /* --- Sockets and networking --------------*/
1201 static int sipsock = -1; /*!< Main socket for SIP network communication */
1202 static struct sockaddr_in bindaddr = { 0, }; /*!< The address we bind to */
1203 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1204 static char externhost[MAXHOSTNAMELEN]; /*!< External host name (possibly with dynamic DNS and DHCP */
1205 static time_t externexpire = 0; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1206 static int externrefresh = 10;
1207 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1208 static struct in_addr __ourip;
1209 static struct sockaddr_in outboundproxyip;
1210 static int ourport;
1211 static struct sockaddr_in debugaddr;
1213 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1215 /*---------------------------- Forward declarations of functions in chan_sip.c */
1216 /*! \note This is added to help splitting up chan_sip.c into several files
1217 in coming releases */
1219 /*--- PBX interface functions */
1220 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1221 static int sip_devicestate(void *data);
1222 static int sip_sendtext(struct ast_channel *ast, const char *text);
1223 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1224 static int sip_hangup(struct ast_channel *ast);
1225 static int sip_answer(struct ast_channel *ast);
1226 static struct ast_frame *sip_read(struct ast_channel *ast);
1227 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1228 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1229 static int sip_transfer(struct ast_channel *ast, const char *dest);
1230 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1231 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1232 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1234 /*--- Transmitting responses and requests */
1235 static int sipsock_read(int *id, int fd, short events, void *ignore);
1236 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
1237 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
1238 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1239 static int retrans_pkt(const void *data);
1240 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
1241 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);
1242 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1243 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1244 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1245 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1246 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1247 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);
1248 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1249 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1250 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1251 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1252 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1253 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
1254 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1255 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1256 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1257 static int transmit_refer(struct sip_pvt *p, const char *dest);
1258 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1259 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1260 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1261 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1262 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1263 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1264 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1265 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1266 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1267 static int does_peer_need_mwi(struct sip_peer *peer);
1269 /*--- Dialog management */
1270 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1271 int useglobal_nat, const int intended_method);
1272 static int __sip_autodestruct(const void *data);
1273 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1274 static int sip_cancel_destroy(struct sip_pvt *p);
1275 static void sip_destroy(struct sip_pvt *p);
1276 static int __sip_destroy(struct sip_pvt *p, int lockowner);
1277 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1278 static void __sip_pretend_ack(struct sip_pvt *p);
1279 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1280 static int auto_congest(const void *nothing);
1281 static int update_call_counter(struct sip_pvt *fup, int event);
1282 static int hangup_sip2cause(int cause);
1283 static const char *hangup_cause2sip(int cause);
1284 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1285 static void free_old_route(struct sip_route *route);
1286 static void list_route(struct sip_route *route);
1287 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1288 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1289 struct sip_request *req, char *uri);
1290 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1291 static void check_pendings(struct sip_pvt *p);
1292 static void *sip_park_thread(void *stuff);
1293 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1294 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1296 /*--- Codec handling / SDP */
1297 static void try_suggested_sip_codec(struct sip_pvt *p);
1298 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1299 static const char *get_sdp(struct sip_request *req, const char *name);
1300 static int find_sdp(struct sip_request *req);
1301 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
1302 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1303 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1304 int debug, int *min_packet_size);
1305 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1306 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1307 int debug);
1308 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p);
1309 static void stop_media_flows(struct sip_pvt *p);
1311 /*--- Authentication stuff */
1312 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1313 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1314 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1315 const char *secret, const char *md5secret, int sipmethod,
1316 char *uri, enum xmittype reliable, int ignore);
1317 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1318 int sipmethod, char *uri, enum xmittype reliable,
1319 struct sockaddr_in *sin, struct sip_peer **authpeer);
1320 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1322 /*--- Domain handling */
1323 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1324 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1325 static void clear_sip_domains(void);
1327 /*--- SIP realm authentication */
1328 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
1329 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1330 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1332 /*--- Misc functions */
1333 static int sip_do_reload(enum channelreloadreason reason);
1334 static int reload_config(enum channelreloadreason reason);
1335 static int expire_register(const void *data);
1336 static void *do_monitor(void *data);
1337 static int restart_monitor(void);
1338 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1339 static int sip_addrcmp(char *name, struct sockaddr_in *sin); /* Support for peer matching */
1340 static int sip_refer_allocate(struct sip_pvt *p);
1341 static void ast_quiet_chan(struct ast_channel *chan);
1342 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1344 /*--- Device monitoring and Device/extension state handling */
1345 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1346 static int sip_devicestate(void *data);
1347 static int sip_poke_noanswer(const void *data);
1348 static int sip_poke_peer(struct sip_peer *peer);
1349 static void sip_poke_all_peers(void);
1350 static void sip_peer_hold(struct sip_pvt *p, int hold);
1352 /*--- Applications, functions, CLI and manager command helpers */
1353 static const char *sip_nat_mode(const struct sip_pvt *p);
1354 static int sip_show_inuse(int fd, int argc, char *argv[]);
1355 static char *transfermode2str(enum transfermodes mode) attribute_const;
1356 static char *nat2str(int nat) attribute_const;
1357 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1358 static int sip_show_users(int fd, int argc, char *argv[]);
1359 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1360 static int sip_show_peers(int fd, int argc, char *argv[]);
1361 static int sip_show_objects(int fd, int argc, char *argv[]);
1362 static void print_group(int fd, ast_group_t group, int crlf);
1363 static const char *dtmfmode2str(int mode) attribute_const;
1364 static const char *insecure2str(int port, int invite) attribute_const;
1365 static void cleanup_stale_contexts(char *new, char *old);
1366 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1367 static const char *domain_mode_to_text(const enum domain_mode mode);
1368 static int sip_show_domains(int fd, int argc, char *argv[]);
1369 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1370 static int sip_show_peer(int fd, int argc, char *argv[]);
1371 static int sip_show_user(int fd, int argc, char *argv[]);
1372 static int sip_show_registry(int fd, int argc, char *argv[]);
1373 static int sip_show_settings(int fd, int argc, char *argv[]);
1374 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1375 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1376 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1377 static int sip_show_channels(int fd, int argc, char *argv[]);
1378 static int sip_show_subscriptions(int fd, int argc, char *argv[]);
1379 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1380 static char *complete_sipch(const char *line, const char *word, int pos, int state);
1381 static char *complete_sip_peer(const char *word, int state, int flags2);
1382 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1383 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state);
1384 static char *complete_sip_user(const char *word, int state, int flags2);
1385 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
1386 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1387 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state);
1388 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state);
1389 static int sip_show_channel(int fd, int argc, char *argv[]);
1390 static int sip_show_history(int fd, int argc, char *argv[]);
1391 static int sip_do_debug_ip(int fd, int argc, char *argv[]);
1392 static int sip_do_debug_peer(int fd, int argc, char *argv[]);
1393 static int sip_do_debug(int fd, int argc, char *argv[]);
1394 static int sip_no_debug(int fd, int argc, char *argv[]);
1395 static int sip_notify(int fd, int argc, char *argv[]);
1396 static int sip_do_history(int fd, int argc, char *argv[]);
1397 static int sip_no_history(int fd, int argc, char *argv[]);
1398 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
1399 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1400 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1401 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1402 static int sip_dtmfmode(struct ast_channel *chan, void *data);
1403 static int sip_addheader(struct ast_channel *chan, void *data);
1404 static int sip_do_reload(enum channelreloadreason reason);
1405 static int sip_reload(int fd, int argc, char *argv[]);
1406 static int acf_channel_read(struct ast_channel *chan, char *funcname, char *preparse, char *buf, size_t buflen);
1408 /*--- Debugging
1409 Functions for enabling debug per IP or fully, or enabling history logging for
1410 a SIP dialog
1412 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1413 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1414 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1415 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1416 static void sip_dump_history(struct sip_pvt *dialog);
1418 /*--- Device object handling */
1419 static struct sip_peer *temp_peer(const char *name);
1420 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1421 static struct sip_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1422 static int update_call_counter(struct sip_pvt *fup, int event);
1423 static void sip_destroy_peer(struct sip_peer *peer);
1424 static void sip_destroy_user(struct sip_user *user);
1425 static int sip_poke_peer(struct sip_peer *peer);
1426 static int sip_poke_peer_s(const void *data);
1427 static void set_peer_defaults(struct sip_peer *peer);
1428 static struct sip_peer *temp_peer(const char *name);
1429 static void register_peer_exten(struct sip_peer *peer, int onoff);
1430 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
1431 static struct sip_user *find_user(const char *name, int realtime);
1432 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1433 static int expire_register(const void *data);
1434 static void reg_source_db(struct sip_peer *peer);
1435 static void destroy_association(struct sip_peer *peer);
1436 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1438 /* Realtime device support */
1439 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
1440 static struct sip_user *realtime_user(const char *username);
1441 static void update_peer(struct sip_peer *p, int expiry);
1442 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
1443 static int sip_prune_realtime(int fd, int argc, char *argv[]);
1445 /*--- Internal UA client handling (outbound registrations) */
1446 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
1447 static void sip_registry_destroy(struct sip_registry *reg);
1448 static int sip_register(char *value, int lineno);
1449 static char *regstate2str(enum sipregistrystate regstate) attribute_const;
1450 static int sip_reregister(const void *data);
1451 static int __sip_do_register(struct sip_registry *r);
1452 static int sip_reg_timeout(const void *data);
1453 static void sip_send_all_registers(void);
1455 /*--- Parsing SIP requests and responses */
1456 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1457 static int determine_firstline_parts(struct sip_request *req);
1458 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1459 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1460 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1461 static int find_sip_method(const char *msg);
1462 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1463 static void parse_request(struct sip_request *req);
1464 static const char *get_header(const struct sip_request *req, const char *name);
1465 static char *referstatus2str(enum referstatus rstatus) attribute_pure;
1466 static int method_match(enum sipmethod id, const char *name);
1467 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1468 static char *get_in_brackets(char *tmp);
1469 static const char *find_alias(const char *name, const char *_default);
1470 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1471 static int lws2sws(char *msgbuf, int len);
1472 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1473 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1474 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1475 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1476 static int set_address_from_contact(struct sip_pvt *pvt);
1477 static void check_via(struct sip_pvt *p, const struct sip_request *req);
1478 static char *get_calleridname(const char *input, char *output, size_t outputsize);
1479 static int get_rpid_num(const char *input, char *output, int maxlen);
1480 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
1481 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1482 static int get_msg_text(char *buf, int len, struct sip_request *req);
1483 static void free_old_route(struct sip_route *route);
1484 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1486 /*--- Constructing requests and responses */
1487 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1488 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1489 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1490 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1491 static int init_resp(struct sip_request *resp, const char *msg);
1492 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1493 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1494 static void build_via(struct sip_pvt *p);
1495 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1496 static int create_addr(struct sip_pvt *dialog, const char *opeer);
1497 static char *generate_random_string(char *buf, size_t size);
1498 static void build_callid_pvt(struct sip_pvt *pvt);
1499 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1500 static void make_our_tag(char *tagbuf, size_t len);
1501 static int add_header(struct sip_request *req, const char *var, const char *value);
1502 static int add_header_contentLength(struct sip_request *req, int len);
1503 static int add_line(struct sip_request *req, const char *line);
1504 static int add_text(struct sip_request *req, const char *text);
1505 static int add_digit(struct sip_request *req, char digit, unsigned int duration);
1506 static int add_vidupdate(struct sip_request *req);
1507 static void add_route(struct sip_request *req, struct sip_route *route);
1508 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1509 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1510 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1511 static void set_destination(struct sip_pvt *p, char *uri);
1512 static void append_date(struct sip_request *req);
1513 static void build_contact(struct sip_pvt *p);
1514 static void build_rpid(struct sip_pvt *p);
1516 /*------Request handling functions */
1517 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1518 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);
1519 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock);
1520 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1521 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1522 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1523 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1524 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1525 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1526 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1527 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1528 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1529 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
1531 /*------Response handling functions */
1532 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1533 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1534 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
1535 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
1537 /*----- RTP interface functions */
1538 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
1539 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1540 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1541 static int sip_get_codec(struct ast_channel *chan);
1542 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
1544 /*------ T38 Support --------- */
1545 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite); /*!< T38 negotiation helper function */
1546 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1547 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p);
1548 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1549 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1551 /*! \brief Definition of this channel for PBX channel registration */
1552 static const struct ast_channel_tech sip_tech = {
1553 .type = "SIP",
1554 .description = "Session Initiation Protocol (SIP)",
1555 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1556 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1557 .requester = sip_request_call,
1558 .devicestate = sip_devicestate,
1559 .call = sip_call,
1560 .hangup = sip_hangup,
1561 .answer = sip_answer,
1562 .read = sip_read,
1563 .write = sip_write,
1564 .write_video = sip_write,
1565 .indicate = sip_indicate,
1566 .transfer = sip_transfer,
1567 .fixup = sip_fixup,
1568 .send_digit_begin = sip_senddigit_begin,
1569 .send_digit_end = sip_senddigit_end,
1570 .bridge = ast_rtp_bridge,
1571 .send_text = sip_sendtext,
1572 .func_channel_read = acf_channel_read,
1575 /*! \brief This version of the sip channel tech has no send_digit_begin
1576 * callback. This is for use with channels using SIP INFO DTMF so that
1577 * the core knows that the channel doesn't want DTMF BEGIN frames. */
1578 static const struct ast_channel_tech sip_tech_info = {
1579 .type = "SIP",
1580 .description = "Session Initiation Protocol (SIP)",
1581 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1582 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1583 .requester = sip_request_call,
1584 .devicestate = sip_devicestate,
1585 .call = sip_call,
1586 .hangup = sip_hangup,
1587 .answer = sip_answer,
1588 .read = sip_read,
1589 .write = sip_write,
1590 .write_video = sip_write,
1591 .indicate = sip_indicate,
1592 .transfer = sip_transfer,
1593 .fixup = sip_fixup,
1594 .send_digit_end = sip_senddigit_end,
1595 .bridge = ast_rtp_bridge,
1596 .send_text = sip_sendtext,
1597 .func_channel_read = acf_channel_read,
1600 /**--- some list management macros. **/
1602 #define UNLINK(element, head, prev) do { \
1603 if (prev) \
1604 (prev)->next = (element)->next; \
1605 else \
1606 (head) = (element)->next; \
1607 } while (0)
1609 /*! \brief Interface structure with callbacks used to connect to RTP module */
1610 static struct ast_rtp_protocol sip_rtp = {
1611 type: "SIP",
1612 get_rtp_info: sip_get_rtp_peer,
1613 get_vrtp_info: sip_get_vrtp_peer,
1614 set_rtp_peer: sip_set_rtp_peer,
1615 get_codec: sip_get_codec,
1618 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1619 static struct ast_udptl_protocol sip_udptl = {
1620 type: "SIP",
1621 get_udptl_info: sip_get_udptl_peer,
1622 set_udptl_peer: sip_set_udptl_peer,
1625 /*! \brief Convert transfer status to string */
1626 static char *referstatus2str(enum referstatus rstatus)
1628 int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
1629 int x;
1631 for (x = 0; x < i; x++) {
1632 if (referstatusstrings[x].status == rstatus)
1633 return (char *) referstatusstrings[x].text;
1635 return "";
1638 /*! \brief Initialize the initital request packet in the pvt structure.
1639 This packet is used for creating replies and future requests in
1640 a dialog */
1641 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
1643 if (p->initreq.headers && option_debug) {
1644 ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
1646 /* Use this as the basis */
1647 copy_request(&p->initreq, req);
1648 parse_request(&p->initreq);
1649 if (ast_test_flag(req, SIP_PKT_DEBUG))
1650 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
1653 static void sip_alreadygone(struct sip_pvt *dialog)
1655 if (option_debug > 2)
1656 ast_log(LOG_DEBUG, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
1657 ast_set_flag(&dialog->flags[0], SIP_ALREADYGONE);
1661 /*! \brief returns true if 'name' (with optional trailing whitespace)
1662 * matches the sip method 'id'.
1663 * Strictly speaking, SIP methods are case SENSITIVE, but we do
1664 * a case-insensitive comparison to be more tolerant.
1665 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1667 static int method_match(enum sipmethod id, const char *name)
1669 int len = strlen(sip_methods[id].text);
1670 int l_name = name ? strlen(name) : 0;
1671 /* true if the string is long enough, and ends with whitespace, and matches */
1672 return (l_name >= len && name[len] < 33 &&
1673 !strncasecmp(sip_methods[id].text, name, len));
1676 /*! \brief find_sip_method: Find SIP method from header */
1677 static int find_sip_method(const char *msg)
1679 int i, res = 0;
1681 if (ast_strlen_zero(msg))
1682 return 0;
1683 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
1684 if (method_match(i, msg))
1685 res = sip_methods[i].id;
1687 return res;
1690 /*! \brief Parse supported header in incoming packet */
1691 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
1693 char *next, *sep;
1694 char *temp;
1695 unsigned int profile = 0;
1696 int i, found;
1698 if (ast_strlen_zero(supported) )
1699 return 0;
1700 temp = ast_strdupa(supported);
1702 if (option_debug > 2 && sipdebug)
1703 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1705 for (next = temp; next; next = sep) {
1706 found = FALSE;
1707 if ( (sep = strchr(next, ',')) != NULL)
1708 *sep++ = '\0';
1709 next = ast_skip_blanks(next);
1710 if (option_debug > 2 && sipdebug)
1711 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1712 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
1713 if (!strcasecmp(next, sip_options[i].text)) {
1714 profile |= sip_options[i].id;
1715 found = TRUE;
1716 if (option_debug > 2 && sipdebug)
1717 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1718 break;
1721 if (!found && option_debug > 2 && sipdebug) {
1722 if (!strncasecmp(next, "x-", 2))
1723 ast_log(LOG_DEBUG, "Found private SIP option, not supported: %s\n", next);
1724 else
1725 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1729 if (pvt)
1730 pvt->sipoptions = profile;
1731 return profile;
1734 /*! \brief See if we pass debug IP filter */
1735 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
1737 if (!sipdebug)
1738 return 0;
1739 if (debugaddr.sin_addr.s_addr) {
1740 if (((ntohs(debugaddr.sin_port) != 0)
1741 && (debugaddr.sin_port != addr->sin_port))
1742 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1743 return 0;
1745 return 1;
1748 /*! \brief The real destination address for a write */
1749 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
1751 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
1754 /*! \brief Display SIP nat mode */
1755 static const char *sip_nat_mode(const struct sip_pvt *p)
1757 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
1760 /*! \brief Test PVT for debugging output */
1761 static inline int sip_debug_test_pvt(struct sip_pvt *p)
1763 if (!sipdebug)
1764 return 0;
1765 return sip_debug_test_addr(sip_real_dst(p));
1768 /*! \brief Transmit SIP message */
1769 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1771 int res;
1772 const struct sockaddr_in *dst = sip_real_dst(p);
1773 res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
1775 if (res == -1) {
1776 switch (errno) {
1777 case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
1778 case EHOSTUNREACH: /* Host can't be reached */
1779 case ENETDOWN: /* Inteface down */
1780 case ENETUNREACH: /* Network failure */
1781 res = XMIT_ERROR; /* Don't bother with trying to transmit again */
1784 if (res != len)
1785 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));
1786 return res;
1790 /*! \brief Build a Via header for a request */
1791 static void build_via(struct sip_pvt *p)
1793 /* Work around buggy UNIDEN UIP200 firmware */
1794 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1796 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1797 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1798 ast_inet_ntoa(p->ourip), ourport, p->branch, rport);
1801 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1803 * Using the localaddr structure built up with localnet statements in sip.conf
1804 * apply it to their address to see if we need to substitute our
1805 * externip or can get away with our internal bindaddr
1807 static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1809 struct sockaddr_in theirs, ours;
1811 /* Get our local information */
1812 ast_ouraddrfor(them, us);
1813 theirs.sin_addr = *them;
1814 ours.sin_addr = *us;
1816 if (localaddr && externip.sin_addr.s_addr &&
1817 (ast_apply_ha(localaddr, &theirs)) &&
1818 (!global_matchexterniplocally || !ast_apply_ha(localaddr, &ours))) {
1819 if (externexpire && time(NULL) >= externexpire) {
1820 struct ast_hostent ahp;
1821 struct hostent *hp;
1823 externexpire = time(NULL) + externrefresh;
1824 if ((hp = ast_gethostbyname(externhost, &ahp))) {
1825 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1826 } else
1827 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1829 *us = externip.sin_addr;
1830 if (option_debug) {
1831 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n",
1832 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
1834 } else if (bindaddr.sin_addr.s_addr)
1835 *us = bindaddr.sin_addr;
1836 return AST_SUCCESS;
1839 /*! \brief Append to SIP dialog history
1840 \return Always returns 0 */
1841 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1843 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1844 __attribute__ ((format (printf, 2, 3)));
1846 /*! \brief Append to SIP dialog history with arg list */
1847 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1849 char buf[80], *c = buf; /* max history length */
1850 struct sip_history *hist;
1851 int l;
1853 vsnprintf(buf, sizeof(buf), fmt, ap);
1854 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1855 l = strlen(buf) + 1;
1856 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1857 return;
1858 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1859 free(hist);
1860 return;
1862 memcpy(hist->event, buf, l);
1863 if (p->history_entries == MAX_HISTORY_ENTRIES) {
1864 struct sip_history *oldest;
1865 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
1866 p->history_entries--;
1867 free(oldest);
1869 AST_LIST_INSERT_TAIL(p->history, hist, list);
1870 p->history_entries++;
1873 /*! \brief Append to SIP dialog history with arg list */
1874 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1876 va_list ap;
1878 if (!p)
1879 return;
1881 if (ast_test_flag(&p->flags[0], SIP_NO_HISTORY)
1882 && !recordhistory && !dumphistory) {
1883 return;
1886 va_start(ap, fmt);
1887 append_history_va(p, fmt, ap);
1888 va_end(ap);
1890 return;
1893 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
1894 static int retrans_pkt(const void *data)
1896 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
1897 int reschedule = DEFAULT_RETRANS;
1898 int xmitres = 0;
1900 /* Lock channel PVT */
1901 ast_mutex_lock(&pkt->owner->lock);
1903 if (pkt->retrans < MAX_RETRANS) {
1904 pkt->retrans++;
1905 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
1906 if (sipdebug && option_debug > 3)
1907 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);
1908 } else {
1909 int siptimer_a;
1911 if (sipdebug && option_debug > 3)
1912 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1913 if (!pkt->timer_a)
1914 pkt->timer_a = 2 ;
1915 else
1916 pkt->timer_a = 2 * pkt->timer_a;
1918 /* For non-invites, a maximum of 4 secs */
1919 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
1920 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1921 siptimer_a = 4000;
1923 /* Reschedule re-transmit */
1924 reschedule = siptimer_a;
1925 if (option_debug > 3)
1926 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);
1929 if (sip_debug_test_pvt(pkt->owner)) {
1930 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
1931 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
1932 pkt->retrans, sip_nat_mode(pkt->owner),
1933 ast_inet_ntoa(dst->sin_addr),
1934 ntohs(dst->sin_port), pkt->data);
1937 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1938 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1939 ast_mutex_unlock(&pkt->owner->lock);
1940 if (xmitres == XMIT_ERROR)
1941 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
1942 else
1943 return reschedule;
1945 /* Too many retries */
1946 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
1947 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1948 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (ast_test_flag(pkt, FLAG_FATAL)) ? "Critical" : "Non-critical", (ast_test_flag(pkt, FLAG_RESPONSE)) ? "Response" : "Request");
1949 } else if ((pkt->method == SIP_OPTIONS) && sipdebug) {
1950 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1952 if (xmitres == XMIT_ERROR) {
1953 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission of transaction in call id %s \n", pkt->owner->callid);
1954 append_history(pkt->owner, "XmitErr", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1955 } else
1956 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1958 pkt->retransid = -1;
1960 if (ast_test_flag(pkt, FLAG_FATAL)) {
1961 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
1962 ast_mutex_unlock(&pkt->owner->lock); /* SIP_PVT, not channel */
1963 usleep(1);
1964 ast_mutex_lock(&pkt->owner->lock);
1967 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
1968 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
1970 if (pkt->owner->owner) {
1971 sip_alreadygone(pkt->owner);
1972 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1973 ast_queue_hangup(pkt->owner->owner);
1974 ast_channel_unlock(pkt->owner->owner);
1975 } else {
1976 /* If no channel owner, destroy now */
1978 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
1979 if (pkt->method != SIP_OPTIONS) {
1980 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
1981 sip_alreadygone(pkt->owner);
1982 if (option_debug)
1983 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
1988 if (pkt->method == SIP_BYE) {
1989 /* We're not getting answers on SIP BYE's. Tear down the call anyway. */
1990 if (pkt->owner->owner)
1991 ast_channel_unlock(pkt->owner->owner);
1992 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
1993 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
1996 /* In any case, go ahead and remove the packet */
1997 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
1998 if (cur == pkt)
1999 break;
2001 if (cur) {
2002 if (prev)
2003 prev->next = cur->next;
2004 else
2005 pkt->owner->packets = cur->next;
2006 ast_mutex_unlock(&pkt->owner->lock);
2007 free(cur);
2008 pkt = NULL;
2009 } else
2010 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
2011 if (pkt)
2012 ast_mutex_unlock(&pkt->owner->lock);
2013 return 0;
2016 /*! \brief Transmit packet with retransmits
2017 \return 0 on success, -1 on failure to allocate packet
2019 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
2021 struct sip_pkt *pkt;
2022 int siptimer_a = DEFAULT_RETRANS;
2023 int xmitres = 0;
2025 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
2026 return AST_FAILURE;
2027 memcpy(pkt->data, data, len);
2028 pkt->method = sipmethod;
2029 pkt->packetlen = len;
2030 pkt->next = p->packets;
2031 pkt->owner = p;
2032 pkt->seqno = seqno;
2033 if (resp)
2034 ast_set_flag(pkt, FLAG_RESPONSE);
2035 pkt->data[len] = '\0';
2036 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
2037 pkt->retransid = -1;
2038 if (fatal)
2039 ast_set_flag(pkt, FLAG_FATAL);
2040 if (pkt->timer_t1)
2041 siptimer_a = pkt->timer_t1 * 2;
2043 if (option_debug > 3 && sipdebug)
2044 ast_log(LOG_DEBUG, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
2045 pkt->retransid = -1;
2046 pkt->next = p->packets;
2047 p->packets = pkt;
2048 if (sipmethod == SIP_INVITE) {
2049 /* Note this is a pending invite */
2050 p->pendinginvite = seqno;
2053 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
2055 if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
2056 append_history(pkt->owner, "XmitErr", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
2057 return AST_FAILURE;
2058 } else {
2059 /* Schedule retransmission */
2060 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
2061 return AST_SUCCESS;
2065 /*! \brief Kill a SIP dialog (called by scheduler) */
2066 static int __sip_autodestruct(const void *data)
2068 struct sip_pvt *p = (struct sip_pvt *)data;
2070 /* If this is a subscription, tell the phone that we got a timeout */
2071 if (p->subscribed) {
2072 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */
2073 p->subscribed = NONE;
2074 append_history(p, "Subscribestatus", "timeout");
2075 if (option_debug > 2)
2076 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
2077 return 10000; /* Reschedule this destruction so that we know that it's gone */
2080 /* If there are packets still waiting for delivery, delay the destruction */
2081 if (p->packets) {
2082 if (option_debug > 2)
2083 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
2084 append_history(p, "ReliableXmit", "timeout");
2085 return 10000;
2088 /* If we're destroying a subscription, dereference peer object too */
2089 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
2090 ASTOBJ_UNREF(p->relatedpeer,sip_destroy_peer);
2092 /* Reset schedule ID */
2093 p->autokillid = -1;
2095 if (option_debug)
2096 ast_log(LOG_DEBUG, "Auto destroying SIP dialog '%s'\n", p->callid);
2097 append_history(p, "AutoDestroy", "%s", p->callid);
2098 if (p->owner) {
2099 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
2100 ast_queue_hangup(p->owner);
2101 } else if (p->refer) {
2102 if (option_debug > 2)
2103 ast_log(LOG_DEBUG, "Finally hanging up channel after transfer: %s\n", p->callid);
2104 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2105 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
2106 } else
2107 sip_destroy(p);
2108 return 0;
2111 /*! \brief Schedule destruction of SIP dialog */
2112 static void sip_scheddestroy(struct sip_pvt *p, int ms)
2114 if (ms < 0) {
2115 if (p->timer_t1 == 0)
2116 p->timer_t1 = 500; /* Set timer T1 if not set (RFC 3261) */
2117 ms = p->timer_t1 * 64;
2119 if (sip_debug_test_pvt(p))
2120 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
2121 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
2122 append_history(p, "SchedDestroy", "%d ms", ms);
2124 AST_SCHED_DEL(sched, p->autokillid);
2125 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
2128 /*! \brief Cancel destruction of SIP dialog */
2129 static int sip_cancel_destroy(struct sip_pvt *p)
2131 int res = 0;
2132 if (p->autokillid > -1) {
2133 if (!(res = ast_sched_del(sched, p->autokillid))) {
2134 append_history(p, "CancelDestroy", "");
2135 p->autokillid = -1;
2138 return res;
2141 /*! \brief Acknowledges receipt of a packet and stops retransmission
2142 * called with p locked*/
2143 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2145 struct sip_pkt *cur, *prev = NULL;
2147 /* Just in case... */
2148 char *msg;
2149 int res = FALSE;
2151 msg = sip_methods[sipmethod].text;
2153 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
2154 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
2155 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
2156 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
2157 if (!resp && (seqno == p->pendinginvite)) {
2158 if (option_debug)
2159 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
2160 p->pendinginvite = 0;
2162 /* this is our baby */
2163 res = TRUE;
2164 UNLINK(cur, p->packets, prev);
2165 if (cur->retransid > -1) {
2166 if (sipdebug && option_debug > 3)
2167 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
2169 /* This odd section is designed to thwart a
2170 * race condition in the packet scheduler. There are
2171 * two conditions under which deleting the packet from the
2172 * scheduler can fail.
2174 * 1. The packet has been removed from the scheduler because retransmission
2175 * is being attempted. The problem is that if the packet is currently attempting
2176 * retransmission and we are at this point in the code, then that MUST mean
2177 * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
2178 * lock temporarily to allow retransmission.
2180 * 2. The packet has reached its maximum number of retransmissions and has
2181 * been permanently removed from the packet scheduler. If this is the case, then
2182 * the packet's retransid will be set to -1. The atomicity of the setting and checking
2183 * of the retransid to -1 is ensured since in both cases p's lock is held.
2185 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
2186 ast_mutex_unlock(&p->lock);
2187 usleep(1);
2188 ast_mutex_lock(&p->lock);
2190 free(cur);
2191 break;
2194 if (option_debug)
2195 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");
2198 /*! \brief Pretend to ack all packets
2199 * called with p locked */
2200 static void __sip_pretend_ack(struct sip_pvt *p)
2202 struct sip_pkt *cur = NULL;
2204 while (p->packets) {
2205 int method;
2206 if (cur == p->packets) {
2207 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
2208 return;
2210 cur = p->packets;
2211 method = (cur->method) ? cur->method : find_sip_method(cur->data);
2212 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method);
2216 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2217 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2219 struct sip_pkt *cur;
2220 int res = -1;
2222 for (cur = p->packets; cur; cur = cur->next) {
2223 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
2224 (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
2225 /* this is our baby */
2226 if (cur->retransid > -1) {
2227 if (option_debug > 3 && sipdebug)
2228 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
2230 AST_SCHED_DEL(sched, cur->retransid);
2231 res = 0;
2232 break;
2235 if (option_debug)
2236 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");
2237 return res;
2241 /*! \brief Copy SIP request, parse it */
2242 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2244 memset(dst, 0, sizeof(*dst));
2245 memcpy(dst->data, src->data, sizeof(dst->data));
2246 dst->len = src->len;
2247 parse_request(dst);
2250 /*! \brief add a blank line if no body */
2251 static void add_blank(struct sip_request *req)
2253 if (!req->lines) {
2254 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2255 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2256 req->len += strlen(req->data + req->len);
2260 /*! \brief Transmit response on SIP request*/
2261 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2263 int res;
2265 add_blank(req);
2266 if (sip_debug_test_pvt(p)) {
2267 const struct sockaddr_in *dst = sip_real_dst(p);
2269 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
2270 reliable ? "Reliably " : "", sip_nat_mode(p),
2271 ast_inet_ntoa(dst->sin_addr),
2272 ntohs(dst->sin_port), req->data);
2274 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2275 struct sip_request tmp;
2276 parse_copy(&tmp, req);
2277 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
2278 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
2280 res = (reliable) ?
2281 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2282 __sip_xmit(p, req->data, req->len);
2283 if (res > 0)
2284 return 0;
2285 return res;
2288 /*! \brief Send SIP Request to the other part of the dialogue */
2289 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2291 int res;
2293 add_blank(req);
2294 if (sip_debug_test_pvt(p)) {
2295 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
2296 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);
2297 else
2298 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);
2300 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2301 struct sip_request tmp;
2302 parse_copy(&tmp, req);
2303 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
2305 res = (reliable) ?
2306 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2307 __sip_xmit(p, req->data, req->len);
2308 return res;
2311 /*! \brief Locate closing quote in a string, skipping escaped quotes.
2312 * optionally with a limit on the search.
2313 * start must be past the first quote.
2315 static const char *find_closing_quote(const char *start, const char *lim)
2317 char last_char = '\0';
2318 const char *s;
2319 for (s = start; *s && s != lim; last_char = *s++) {
2320 if (*s == '"' && last_char != '\\')
2321 break;
2323 return s;
2326 /*! \brief Pick out text in brackets from character string
2327 \return pointer to terminated stripped string
2328 \param tmp input string that will be modified
2329 Examples:
2331 "foo" <bar> valid input, returns bar
2332 foo returns the whole string
2333 < "foo ... > returns the string between brackets
2334 < "foo... bogus (missing closing bracket), returns the whole string
2335 XXX maybe should still skip the opening bracket
2337 static char *get_in_brackets(char *tmp)
2339 const char *parse = tmp;
2340 char *first_bracket;
2343 * Skip any quoted text until we find the part in brackets.
2344 * On any error give up and return the full string.
2346 while ( (first_bracket = strchr(parse, '<')) ) {
2347 char *first_quote = strchr(parse, '"');
2349 if (!first_quote || first_quote > first_bracket)
2350 break; /* no need to look at quoted part */
2351 /* the bracket is within quotes, so ignore it */
2352 parse = find_closing_quote(first_quote + 1, NULL);
2353 if (!*parse) { /* not found, return full string ? */
2354 /* XXX or be robust and return in-bracket part ? */
2355 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
2356 break;
2358 parse++;
2360 if (first_bracket) {
2361 char *second_bracket = strchr(first_bracket + 1, '>');
2362 if (second_bracket) {
2363 *second_bracket = '\0';
2364 tmp = first_bracket + 1;
2365 } else {
2366 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
2369 return tmp;
2372 /*! \brief Send SIP MESSAGE text within a call
2373 Called from PBX core sendtext() application */
2374 static int sip_sendtext(struct ast_channel *ast, const char *text)
2376 struct sip_pvt *p = ast->tech_pvt;
2377 int debug = sip_debug_test_pvt(p);
2379 if (debug)
2380 ast_verbose("Sending text %s on %s\n", text, ast->name);
2381 if (!p)
2382 return -1;
2383 if (ast_strlen_zero(text))
2384 return 0;
2385 if (debug)
2386 ast_verbose("Really sending text %s on %s\n", text, ast->name);
2387 transmit_message_with_text(p, text);
2388 return 0;
2391 /*! \brief Update peer object in realtime storage
2392 If the Asterisk system name is set in asterisk.conf, we will use
2393 that name and store that in the "regserver" field in the sippeers
2394 table to facilitate multi-server setups.
2396 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
2398 char port[10];
2399 char ipaddr[INET_ADDRSTRLEN];
2400 char regseconds[20];
2402 char *sysname = ast_config_AST_SYSTEM_NAME;
2403 char *syslabel = NULL;
2405 time_t nowtime = time(NULL) + expirey;
2406 const char *fc = fullcontact ? "fullcontact" : NULL;
2408 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
2409 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2410 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2412 if (ast_strlen_zero(sysname)) /* No system name, disable this */
2413 sysname = NULL;
2414 else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME))
2415 syslabel = "regserver";
2417 if (fc)
2418 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2419 "port", port, "regseconds", regseconds,
2420 "username", username, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
2421 else
2422 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2423 "port", port, "regseconds", regseconds,
2424 "username", username, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
2427 /*! \brief Automatically add peer extension to dial plan */
2428 static void register_peer_exten(struct sip_peer *peer, int onoff)
2430 char multi[256];
2431 char *stringp, *ext, *context;
2433 /* XXX note that global_regcontext is both a global 'enable' flag and
2434 * the name of the global regexten context, if not specified
2435 * individually.
2437 if (ast_strlen_zero(global_regcontext))
2438 return;
2440 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
2441 stringp = multi;
2442 while ((ext = strsep(&stringp, "&"))) {
2443 if ((context = strchr(ext, '@'))) {
2444 *context++ = '\0'; /* split ext@context */
2445 if (!ast_context_find(context)) {
2446 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
2447 continue;
2449 } else {
2450 context = global_regcontext;
2452 if (onoff)
2453 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2454 ast_strdup(peer->name), ast_free, "SIP");
2455 else
2456 ast_context_remove_extension(context, ext, 1, NULL);
2460 /*! \brief Destroy peer object from memory */
2461 static void sip_destroy_peer(struct sip_peer *peer)
2463 if (option_debug > 2)
2464 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
2466 /* Delete it, it needs to disappear */
2467 if (peer->call)
2468 sip_destroy(peer->call);
2470 if (peer->mwipvt) /* We have an active subscription, delete it */
2471 sip_destroy(peer->mwipvt);
2473 if (peer->chanvars) {
2474 ast_variables_destroy(peer->chanvars);
2475 peer->chanvars = NULL;
2478 register_peer_exten(peer, FALSE);
2479 ast_free_ha(peer->ha);
2480 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
2481 apeerobjs--;
2482 else if (ast_test_flag(&peer->flags[0], SIP_REALTIME))
2483 rpeerobjs--;
2484 else
2485 speerobjs--;
2486 clear_realm_authentication(peer->auth);
2487 peer->auth = NULL;
2488 free(peer);
2491 /*! \brief Update peer data in database (if used) */
2492 static void update_peer(struct sip_peer *p, int expiry)
2494 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2495 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
2496 (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
2497 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
2502 /*! \brief realtime_peer: Get peer from realtime storage
2503 * Checks the "sippeers" realtime family from extconfig.conf
2504 * \todo Consider adding check of port address when matching here to follow the same
2505 * algorithm as for static peers. Will we break anything by adding that?
2507 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
2509 struct sip_peer *peer=NULL;
2510 struct ast_variable *var = NULL;
2511 struct ast_config *peerlist = NULL;
2512 struct ast_variable *tmp;
2513 struct ast_flags flags = {0};
2514 const char *iabuf = NULL;
2515 char portstring[6]; /*up to five digits plus null terminator*/
2516 const char *insecure;
2517 char *cat = NULL;
2518 unsigned short portnum;
2520 /* First check on peer name */
2521 if (newpeername) {
2522 var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", NULL);
2523 if (!var && sin)
2524 var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), NULL);
2525 if (!var) {
2526 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
2527 /*!\note
2528 * If this one loaded something, then we need to ensure that the host
2529 * field matched. The only reason why we can't have this as a criteria
2530 * is because we only have the IP address and the host field might be
2531 * set as a name (and the reverse PTR might not match).
2533 if (var && sin) {
2534 for (tmp = var; tmp; tmp = tmp->next) {
2535 if (!strcasecmp(tmp->name, "host")) {
2536 struct hostent *hp;
2537 struct ast_hostent ahp;
2538 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
2539 /* No match */
2540 ast_variables_destroy(var);
2541 var = NULL;
2543 break;
2550 if (!var && sin) { /* Then check on IP address */
2551 iabuf = ast_inet_ntoa(sin->sin_addr);
2552 portnum = ntohs(sin->sin_port);
2553 sprintf(portstring, "%d", portnum);
2554 var = ast_load_realtime("sippeers", "host", iabuf, "port", portstring, NULL); /* First check for fixed IP hosts */
2555 if (!var)
2556 var = ast_load_realtime("sippeers", "ipaddr", iabuf, "port", portstring, NULL); /* Then check for registered hosts */
2557 if (!var) {
2558 peerlist = ast_load_realtime_multientry("sippeers", "host", iabuf, NULL); /*No exact match, see if port is insecure, try host match first*/
2559 if(peerlist){
2560 while((cat = ast_category_browse(peerlist, cat)))
2562 insecure = ast_variable_retrieve(peerlist, cat, "insecure");
2563 set_insecure_flags(&flags, insecure, -1);
2564 if(ast_test_flag(&flags, SIP_INSECURE_PORT)) {
2565 var = ast_category_root(peerlist, cat);
2566 break;
2570 if(!var) {
2571 ast_config_destroy(peerlist);
2572 peerlist = NULL; /*for safety's sake*/
2573 cat = NULL;
2574 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", iabuf, NULL); /*No exact match, see if port is insecure, now try ip address match*/
2575 if(peerlist) {
2576 while((cat = ast_category_browse(peerlist, cat)))
2578 insecure = ast_variable_retrieve(peerlist, cat, "insecure");
2579 set_insecure_flags(&flags, insecure, -1);
2580 if(ast_test_flag(&flags, SIP_INSECURE_PORT)) {
2581 var = ast_category_root(peerlist, cat);
2582 break;
2590 if (!var) {
2591 if(peerlist)
2592 ast_config_destroy(peerlist);
2593 return NULL;
2596 for (tmp = var; tmp; tmp = tmp->next) {
2597 /* If this is type=user, then skip this object. */
2598 if (!strcasecmp(tmp->name, "type") &&
2599 !strcasecmp(tmp->value, "user")) {
2600 ast_variables_destroy(var);
2601 return NULL;
2602 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
2603 newpeername = tmp->value;
2607 if (!newpeername) { /* Did not find peer in realtime */
2608 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
2609 if(peerlist)
2610 ast_config_destroy(peerlist);
2611 else
2612 ast_variables_destroy(var);
2613 return NULL;
2616 /* Peer found in realtime, now build it in memory */
2617 peer = build_peer(newpeername, var, NULL, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2618 if (!peer) {
2619 if(peerlist)
2620 ast_config_destroy(peerlist);
2621 else
2622 ast_variables_destroy(var);
2623 return NULL;
2626 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2627 /* Cache peer */
2628 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
2629 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
2630 if (!AST_SCHED_DEL(sched, peer->expire)) {
2631 struct sip_peer *peer_ptr = peer;
2632 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
2634 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, ASTOBJ_REF(peer));
2635 if (peer->expire == -1) {
2636 struct sip_peer *peer_ptr = peer;
2637 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
2640 ASTOBJ_CONTAINER_LINK(&peerl,peer);
2641 } else {
2642 ast_set_flag(&peer->flags[0], SIP_REALTIME);
2644 if(peerlist)
2645 ast_config_destroy(peerlist);
2646 else
2647 ast_variables_destroy(var);
2648 return peer;
2651 /*! \brief Support routine for find_peer */
2652 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
2654 /* We know name is the first field, so we can cast */
2655 struct sip_peer *p = (struct sip_peer *) name;
2656 return !(!inaddrcmp(&p->addr, sin) ||
2657 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
2658 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
2661 /*! \brief Locate peer by name or ip address
2662 * This is used on incoming SIP message to find matching peer on ip
2663 or outgoing message to find matching peer on name */
2664 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
2666 struct sip_peer *p = NULL;
2668 if (peer)
2669 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
2670 else
2671 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
2673 if (!p && realtime)
2674 p = realtime_peer(peer, sin);
2676 return p;
2679 /*! \brief Remove user object from in-memory storage */
2680 static void sip_destroy_user(struct sip_user *user)
2682 if (option_debug > 2)
2683 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
2684 ast_free_ha(user->ha);
2685 if (user->chanvars) {
2686 ast_variables_destroy(user->chanvars);
2687 user->chanvars = NULL;
2689 if (ast_test_flag(&user->flags[0], SIP_REALTIME))
2690 ruserobjs--;
2691 else
2692 suserobjs--;
2693 free(user);
2696 /*! \brief Load user from realtime storage
2697 * Loads user from "sipusers" category in realtime (extconfig.conf)
2698 * Users are matched on From: user name (the domain in skipped) */
2699 static struct sip_user *realtime_user(const char *username)
2701 struct ast_variable *var;
2702 struct ast_variable *tmp;
2703 struct sip_user *user = NULL;
2705 var = ast_load_realtime("sipusers", "name", username, NULL);
2707 if (!var)
2708 return NULL;
2710 for (tmp = var; tmp; tmp = tmp->next) {
2711 if (!strcasecmp(tmp->name, "type") &&
2712 !strcasecmp(tmp->value, "peer")) {
2713 ast_variables_destroy(var);
2714 return NULL;
2718 user = build_user(username, var, NULL, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2720 if (!user) { /* No user found */
2721 ast_variables_destroy(var);
2722 return NULL;
2725 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2726 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2727 suserobjs++;
2728 ASTOBJ_CONTAINER_LINK(&userl,user);
2729 } else {
2730 /* Move counter from s to r... */
2731 suserobjs--;
2732 ruserobjs++;
2733 ast_set_flag(&user->flags[0], SIP_REALTIME);
2735 ast_variables_destroy(var);
2736 return user;
2739 /*! \brief Locate user by name
2740 * Locates user by name (From: sip uri user name part) first
2741 * from in-memory list (static configuration) then from
2742 * realtime storage (defined in extconfig.conf) */
2743 static struct sip_user *find_user(const char *name, int realtime)
2745 struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
2746 if (!u && realtime)
2747 u = realtime_user(name);
2748 return u;
2751 /*! \brief Set nat mode on the various data sockets */
2752 static void do_setnat(struct sip_pvt *p, int natflags)
2754 const char *mode = natflags ? "On" : "Off";
2756 if (p->rtp) {
2757 if (option_debug)
2758 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", mode);
2759 ast_rtp_setnat(p->rtp, natflags);
2761 if (p->vrtp) {
2762 if (option_debug)
2763 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", mode);
2764 ast_rtp_setnat(p->vrtp, natflags);
2766 if (p->udptl) {
2767 if (option_debug)
2768 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", mode);
2769 ast_udptl_setnat(p->udptl, natflags);
2773 /*! \brief Create address structure from peer reference.
2774 * return -1 on error, 0 on success.
2776 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
2778 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
2779 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
2780 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
2781 dialog->recv = dialog->sa;
2782 } else
2783 return -1;
2785 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
2786 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
2787 dialog->capability = peer->capability;
2788 if ((!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(dialog->capability & AST_FORMAT_VIDEO_MASK)) && dialog->vrtp) {
2789 ast_rtp_destroy(dialog->vrtp);
2790 dialog->vrtp = NULL;
2792 dialog->prefs = peer->prefs;
2793 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
2794 dialog->t38.capability = global_t38_capability;
2795 if (dialog->udptl) {
2796 if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_FEC )
2797 dialog->t38.capability |= T38FAX_UDP_EC_FEC;
2798 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
2799 dialog->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
2800 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_NONE )
2801 dialog->t38.capability |= T38FAX_UDP_EC_NONE;
2802 dialog->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
2803 if (option_debug > 1)
2804 ast_log(LOG_DEBUG,"Our T38 capability (%d)\n", dialog->t38.capability);
2806 dialog->t38.jointcapability = dialog->t38.capability;
2807 } else if (dialog->udptl) {
2808 ast_udptl_destroy(dialog->udptl);
2809 dialog->udptl = NULL;
2811 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE );
2813 if (dialog->rtp) {
2814 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
2815 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
2816 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
2817 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
2818 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
2819 /* Set Frame packetization */
2820 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
2821 dialog->autoframing = peer->autoframing;
2823 if (dialog->vrtp) {
2824 ast_rtp_setdtmf(dialog->vrtp, 0);
2825 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
2826 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
2827 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
2828 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
2831 ast_string_field_set(dialog, peername, peer->name);
2832 ast_string_field_set(dialog, authname, peer->username);
2833 ast_string_field_set(dialog, username, peer->username);
2834 ast_string_field_set(dialog, peersecret, peer->secret);
2835 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
2836 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
2837 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
2838 ast_string_field_set(dialog, tohost, peer->tohost);
2839 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
2840 if (!dialog->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
2841 char *tmpcall;
2842 char *c;
2843 tmpcall = ast_strdupa(dialog->callid);
2844 c = strchr(tmpcall, '@');
2845 if (c) {
2846 *c = '\0';
2847 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
2850 if (ast_strlen_zero(dialog->tohost))
2851 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
2852 if (!ast_strlen_zero(peer->fromdomain))
2853 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
2854 if (!ast_strlen_zero(peer->fromuser))
2855 ast_string_field_set(dialog, fromuser, peer->fromuser);
2856 if (!ast_strlen_zero(peer->language))
2857 ast_string_field_set(dialog, language, peer->language);
2858 dialog->maxtime = peer->maxms;
2859 dialog->callgroup = peer->callgroup;
2860 dialog->pickupgroup = peer->pickupgroup;
2861 dialog->allowtransfer = peer->allowtransfer;
2862 /* Set timer T1 to RTT for this peer (if known by qualify=) */
2863 /* Minimum is settable or default to 100 ms */
2864 if (peer->maxms && peer->lastms)
2865 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
2866 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
2867 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
2868 dialog->noncodeccapability |= AST_RTP_DTMF;
2869 else
2870 dialog->noncodeccapability &= ~AST_RTP_DTMF;
2871 dialog->jointnoncodeccapability = dialog->noncodeccapability;
2872 ast_string_field_set(dialog, context, peer->context);
2873 dialog->rtptimeout = peer->rtptimeout;
2874 if (peer->call_limit)
2875 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
2876 dialog->maxcallbitrate = peer->maxcallbitrate;
2878 return 0;
2881 /*! \brief create address structure from peer name
2882 * Or, if peer not found, find it in the global DNS
2883 * returns TRUE (-1) on failure, FALSE on success */
2884 static int create_addr(struct sip_pvt *dialog, const char *opeer)
2886 struct hostent *hp;
2887 struct ast_hostent ahp;
2888 struct sip_peer *p;
2889 char *port;
2890 int portno;
2891 char host[MAXHOSTNAMELEN], *hostn;
2892 char peer[256];
2894 ast_copy_string(peer, opeer, sizeof(peer));
2895 port = strchr(peer, ':');
2896 if (port)
2897 *port++ = '\0';
2898 dialog->sa.sin_family = AF_INET;
2899 dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
2900 p = find_peer(peer, NULL, 1);
2902 if (p) {
2903 int res = create_addr_from_peer(dialog, p);
2904 ASTOBJ_UNREF(p, sip_destroy_peer);
2905 return res;
2907 hostn = peer;
2908 portno = port ? atoi(port) : STANDARD_SIP_PORT;
2909 if (srvlookup) {
2910 char service[MAXHOSTNAMELEN];
2911 int tportno;
2912 int ret;
2914 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
2915 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
2916 if (ret > 0) {
2917 hostn = host;
2918 portno = tportno;
2921 hp = ast_gethostbyname(hostn, &ahp);
2922 if (!hp) {
2923 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2924 return -1;
2926 ast_string_field_set(dialog, tohost, peer);
2927 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
2928 dialog->sa.sin_port = htons(portno);
2929 dialog->recv = dialog->sa;
2930 return 0;
2933 /*! \brief Scheduled congestion on a call */
2934 static int auto_congest(const void *nothing)
2936 struct sip_pvt *p = (struct sip_pvt *)nothing;
2938 ast_mutex_lock(&p->lock);
2939 p->initid = -1;
2940 if (p->owner) {
2941 /* XXX fails on possible deadlock */
2942 if (!ast_channel_trylock(p->owner)) {
2943 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
2944 append_history(p, "Cong", "Auto-congesting (timer)");
2945 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
2946 ast_channel_unlock(p->owner);
2949 ast_mutex_unlock(&p->lock);
2950 return 0;
2954 /*! \brief Initiate SIP call from PBX
2955 * used from the dial() application */
2956 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2958 int res, xmitres = 0;
2959 struct sip_pvt *p;
2960 struct varshead *headp;
2961 struct ast_var_t *current;
2962 const char *referer = NULL; /* SIP refererer */
2964 p = ast->tech_pvt;
2965 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2966 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2967 return -1;
2970 /* Check whether there is vxml_url, distinctive ring variables */
2971 headp=&ast->varshead;
2972 AST_LIST_TRAVERSE(headp,current,entries) {
2973 /* Check whether there is a VXML_URL variable */
2974 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2975 p->options->vxml_url = ast_var_value(current);
2976 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
2977 p->options->uri_options = ast_var_value(current);
2978 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
2979 /* Check whether there is a ALERT_INFO variable */
2980 p->options->distinctive_ring = ast_var_value(current);
2981 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2982 /* Check whether there is a variable with a name starting with SIPADDHEADER */
2983 p->options->addsipheaders = 1;
2984 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
2985 /* This is a transfered call */
2986 p->options->transfer = 1;
2987 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
2988 /* This is the referer */
2989 referer = ast_var_value(current);
2990 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
2991 /* We're replacing a call. */
2992 p->options->replaces = ast_var_value(current);
2993 } else if (!strcasecmp(ast_var_name(current), "T38CALL")) {
2994 p->t38.state = T38_LOCAL_DIRECT;
2995 if (option_debug)
2996 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
3001 res = 0;
3002 ast_set_flag(&p->flags[0], SIP_OUTGOING);
3004 if (p->options->transfer) {
3005 char buf[SIPBUFSIZE/2];
3007 if (referer) {
3008 if (sipdebug && option_debug > 2)
3009 ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->username, referer);
3010 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
3011 } else
3012 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
3013 ast_string_field_set(p, cid_name, buf);
3015 if (option_debug)
3016 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
3018 res = update_call_counter(p, INC_CALL_RINGING);
3019 if ( res != -1 ) {
3020 p->callingpres = ast->cid.cid_pres;
3021 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
3022 p->jointnoncodeccapability = p->noncodeccapability;
3024 /* If there are no audio formats left to offer, punt */
3025 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
3026 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
3027 res = -1;
3028 } else {
3029 p->t38.jointcapability = p->t38.capability;
3030 if (option_debug > 1)
3031 ast_log(LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
3032 xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
3033 if (xmitres == XMIT_ERROR)
3034 return -1; /* Transmission error */
3036 p->invitestate = INV_CALLING;
3038 /* Initialize auto-congest time */
3039 AST_SCHED_DEL(sched, p->initid);
3040 p->initid = ast_sched_add(sched, p->maxtime ? (p->maxtime * 4) : SIP_TRANS_TIMEOUT, auto_congest, p);
3043 return res;
3046 /*! \brief Destroy registry object
3047 Objects created with the register= statement in static configuration */
3048 static void sip_registry_destroy(struct sip_registry *reg)
3050 /* Really delete */
3051 if (option_debug > 2)
3052 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
3054 if (reg->call) {
3055 /* Clear registry before destroying to ensure
3056 we don't get reentered trying to grab the registry lock */
3057 reg->call->registry = NULL;
3058 if (option_debug > 2)
3059 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
3060 sip_destroy(reg->call);
3062 AST_SCHED_DEL(sched, reg->expire);
3063 AST_SCHED_DEL(sched, reg->timeout);
3064 ast_string_field_free_memory(reg);
3065 regobjs--;
3066 free(reg);
3070 /*! \brief Execute destruction of SIP dialog structure, release memory */
3071 static int __sip_destroy(struct sip_pvt *p, int lockowner)
3073 struct sip_pvt *cur, *prev = NULL;
3074 struct sip_pkt *cp;
3076 /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
3077 if (p->rtp && ast_rtp_get_bridged(p->rtp)) {
3078 ast_verbose("Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
3079 return -1;
3082 if (p->vrtp && ast_rtp_get_bridged(p->vrtp)) {
3083 ast_verbose("Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
3084 return -1;
3087 if (sip_debug_test_pvt(p) || option_debug > 2)
3088 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
3090 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
3091 update_call_counter(p, DEC_CALL_LIMIT);
3092 if (option_debug > 1)
3093 ast_log(LOG_DEBUG, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
3096 /* Unlink us from the owner if we have one */
3097 if (p->owner) {
3098 if (lockowner)
3099 ast_channel_lock(p->owner);
3100 if (option_debug)
3101 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
3102 p->owner->tech_pvt = NULL;
3103 /* Make sure that the channel knows its backend is going away */
3104 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
3105 if (lockowner)
3106 ast_channel_unlock(p->owner);
3107 /* Give the channel a chance to react before deallocation */
3108 usleep(1);
3111 /* Remove link from peer to subscription of MWI */
3112 if (p->relatedpeer && p->relatedpeer->mwipvt)
3113 p->relatedpeer->mwipvt = NULL;
3115 if (dumphistory)
3116 sip_dump_history(p);
3118 if (p->options)
3119 free(p->options);
3121 if (p->stateid > -1)
3122 ast_extension_state_del(p->stateid, NULL);
3123 AST_SCHED_DEL(sched, p->initid);
3124 AST_SCHED_DEL(sched, p->waitid);
3125 AST_SCHED_DEL(sched, p->autokillid);
3127 if (p->rtp) {
3128 ast_rtp_destroy(p->rtp);
3130 if (p->vrtp) {
3131 ast_rtp_destroy(p->vrtp);
3133 if (p->udptl)
3134 ast_udptl_destroy(p->udptl);
3135 if (p->refer)
3136 free(p->refer);
3137 if (p->route) {
3138 free_old_route(p->route);
3139 p->route = NULL;
3141 if (p->registry) {
3142 if (p->registry->call == p)
3143 p->registry->call = NULL;
3144 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
3147 /* Clear history */
3148 if (p->history) {
3149 struct sip_history *hist;
3150 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
3151 free(hist);
3152 p->history_entries--;
3154 free(p->history);
3155 p->history = NULL;
3158 for (prev = NULL, cur = iflist; cur; prev = cur, cur = cur->next) {
3159 if (cur == p) {
3160 UNLINK(cur, iflist, prev);
3161 break;
3164 if (!cur) {
3165 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
3166 return 0;
3169 /* remove all current packets in this dialog */
3170 while((cp = p->packets)) {
3171 p->packets = p->packets->next;
3172 AST_SCHED_DEL(sched, cp->retransid);
3173 free(cp);
3175 if (p->chanvars) {
3176 ast_variables_destroy(p->chanvars);
3177 p->chanvars = NULL;
3179 ast_mutex_destroy(&p->lock);
3181 ast_string_field_free_memory(p);
3183 free(p);
3184 return 0;
3187 /*! \brief update_call_counter: Handle call_limit for SIP users
3188 * Setting a call-limit will cause calls above the limit not to be accepted.
3190 * Remember that for a type=friend, there's one limit for the user and
3191 * another for the peer, not a combined call limit.
3192 * This will cause unexpected behaviour in subscriptions, since a "friend"
3193 * is *two* devices in Asterisk, not one.
3195 * Thought: For realtime, we should propably update storage with inuse counter...
3197 * \return 0 if call is ok (no call limit, below treshold)
3198 * -1 on rejection of call
3201 static int update_call_counter(struct sip_pvt *fup, int event)
3203 char name[256];
3204 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
3205 int outgoing = ast_test_flag(&fup->flags[1], SIP_PAGE2_OUTGOING_CALL);
3206 struct sip_user *u = NULL;
3207 struct sip_peer *p = NULL;
3209 if (option_debug > 2)
3210 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
3212 /* Test if we need to check call limits, in order to avoid
3213 realtime lookups if we do not need it */
3214 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
3215 return 0;
3217 ast_copy_string(name, fup->username, sizeof(name));
3219 /* Check the list of users only for incoming calls */
3220 if (global_limitonpeers == FALSE && !outgoing && (u = find_user(name, 1))) {
3221 inuse = &u->inUse;
3222 call_limit = &u->call_limit;
3223 inringing = NULL;
3224 } else if ( (p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, 1) ) ) { /* Try to find peer */
3225 inuse = &p->inUse;
3226 call_limit = &p->call_limit;
3227 inringing = &p->inRinging;
3228 ast_copy_string(name, fup->peername, sizeof(name));
3230 if (!p && !u) {
3231 if (option_debug > 1)
3232 ast_log(LOG_DEBUG, "%s is not a local device, no call limit\n", name);
3233 return 0;
3236 switch(event) {
3237 /* incoming and outgoing affects the inUse counter */
3238 case DEC_CALL_LIMIT:
3239 if ( *inuse > 0 ) {
3240 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
3241 (*inuse)--;
3242 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
3244 } else {
3245 *inuse = 0;
3247 if (inringing) {
3248 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3249 if (*inringing > 0)
3250 (*inringing)--;
3251 else if (!ast_test_flag(&p->flags[0], SIP_REALTIME) || ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS))
3252 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", fup->peername);
3253 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3256 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && global_notifyhold) {
3257 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
3258 sip_peer_hold(fup, 0);
3260 if (option_debug > 1 || sipdebug) {
3261 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
3263 break;
3265 case INC_CALL_RINGING:
3266 case INC_CALL_LIMIT:
3267 if (*call_limit > 0 ) {
3268 if (*inuse >= *call_limit) {
3269 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);
3270 if (u)
3271 ASTOBJ_UNREF(u, sip_destroy_user);
3272 else
3273 ASTOBJ_UNREF(p, sip_destroy_peer);
3274 return -1;
3277 if (inringing && (event == INC_CALL_RINGING)) {
3278 if (!ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3279 (*inringing)++;
3280 ast_set_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3283 /* Continue */
3284 (*inuse)++;
3285 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
3286 if (option_debug > 1 || sipdebug) {
3287 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
3289 break;
3291 case DEC_CALL_RINGING:
3292 if (inringing) {
3293 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3294 if (*inringing > 0)
3295 (*inringing)--;
3296 else if (!ast_test_flag(&p->flags[0], SIP_REALTIME) || ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS))
3297 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", p->name);
3298 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3301 break;
3303 default:
3304 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
3306 if (p) {
3307 ast_device_state_changed("SIP/%s", p->name);
3308 ASTOBJ_UNREF(p, sip_destroy_peer);
3309 } else /* u must be set */
3310 ASTOBJ_UNREF(u, sip_destroy_user);
3311 return 0;
3314 /*! \brief Destroy SIP call structure */
3315 static void sip_destroy(struct sip_pvt *p)
3317 ast_mutex_lock(&iflock);
3318 if (option_debug > 2)
3319 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
3320 __sip_destroy(p, 1);
3321 ast_mutex_unlock(&iflock);
3324 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
3325 static int hangup_sip2cause(int cause)
3327 /* Possible values taken from causes.h */
3329 switch(cause) {
3330 case 401: /* Unauthorized */
3331 return AST_CAUSE_CALL_REJECTED;
3332 case 403: /* Not found */
3333 return AST_CAUSE_CALL_REJECTED;
3334 case 404: /* Not found */
3335 return AST_CAUSE_UNALLOCATED;
3336 case 405: /* Method not allowed */
3337 return AST_CAUSE_INTERWORKING;
3338 case 407: /* Proxy authentication required */
3339 return AST_CAUSE_CALL_REJECTED;
3340 case 408: /* No reaction */
3341 return AST_CAUSE_NO_USER_RESPONSE;
3342 case 409: /* Conflict */
3343 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
3344 case 410: /* Gone */
3345 return AST_CAUSE_UNALLOCATED;
3346 case 411: /* Length required */
3347 return AST_CAUSE_INTERWORKING;
3348 case 413: /* Request entity too large */
3349 return AST_CAUSE_INTERWORKING;
3350 case 414: /* Request URI too large */
3351 return AST_CAUSE_INTERWORKING;
3352 case 415: /* Unsupported media type */
3353 return AST_CAUSE_INTERWORKING;
3354 case 420: /* Bad extension */
3355 return AST_CAUSE_NO_ROUTE_DESTINATION;
3356 case 480: /* No answer */
3357 return AST_CAUSE_NO_ANSWER;
3358 case 481: /* No answer */
3359 return AST_CAUSE_INTERWORKING;
3360 case 482: /* Loop detected */
3361 return AST_CAUSE_INTERWORKING;
3362 case 483: /* Too many hops */
3363 return AST_CAUSE_NO_ANSWER;
3364 case 484: /* Address incomplete */
3365 return AST_CAUSE_INVALID_NUMBER_FORMAT;
3366 case 485: /* Ambigous */
3367 return AST_CAUSE_UNALLOCATED;
3368 case 486: /* Busy everywhere */
3369 return AST_CAUSE_BUSY;
3370 case 487: /* Request terminated */
3371 return AST_CAUSE_INTERWORKING;
3372 case 488: /* No codecs approved */
3373 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3374 case 491: /* Request pending */
3375 return AST_CAUSE_INTERWORKING;
3376 case 493: /* Undecipherable */
3377 return AST_CAUSE_INTERWORKING;
3378 case 500: /* Server internal failure */
3379 return AST_CAUSE_FAILURE;
3380 case 501: /* Call rejected */
3381 return AST_CAUSE_FACILITY_REJECTED;
3382 case 502:
3383 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
3384 case 503: /* Service unavailable */
3385 return AST_CAUSE_CONGESTION;
3386 case 504: /* Gateway timeout */
3387 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
3388 case 505: /* SIP version not supported */
3389 return AST_CAUSE_INTERWORKING;
3390 case 600: /* Busy everywhere */
3391 return AST_CAUSE_USER_BUSY;
3392 case 603: /* Decline */
3393 return AST_CAUSE_CALL_REJECTED;
3394 case 604: /* Does not exist anywhere */
3395 return AST_CAUSE_UNALLOCATED;
3396 case 606: /* Not acceptable */
3397 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3398 default:
3399 return AST_CAUSE_NORMAL;
3401 /* Never reached */
3402 return 0;
3405 /*! \brief Convert Asterisk hangup causes to SIP codes
3406 \verbatim
3407 Possible values from causes.h
3408 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
3409 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
3411 In addition to these, a lot of PRI codes is defined in causes.h
3412 ...should we take care of them too ?
3414 Quote RFC 3398
3416 ISUP Cause value SIP response
3417 ---------------- ------------
3418 1 unallocated number 404 Not Found
3419 2 no route to network 404 Not found
3420 3 no route to destination 404 Not found
3421 16 normal call clearing --- (*)
3422 17 user busy 486 Busy here
3423 18 no user responding 408 Request Timeout
3424 19 no answer from the user 480 Temporarily unavailable
3425 20 subscriber absent 480 Temporarily unavailable
3426 21 call rejected 403 Forbidden (+)
3427 22 number changed (w/o diagnostic) 410 Gone
3428 22 number changed (w/ diagnostic) 301 Moved Permanently
3429 23 redirection to new destination 410 Gone
3430 26 non-selected user clearing 404 Not Found (=)
3431 27 destination out of order 502 Bad Gateway
3432 28 address incomplete 484 Address incomplete
3433 29 facility rejected 501 Not implemented
3434 31 normal unspecified 480 Temporarily unavailable
3435 \endverbatim
3437 static const char *hangup_cause2sip(int cause)
3439 switch (cause) {
3440 case AST_CAUSE_UNALLOCATED: /* 1 */
3441 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
3442 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
3443 return "404 Not Found";
3444 case AST_CAUSE_CONGESTION: /* 34 */
3445 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
3446 return "503 Service Unavailable";
3447 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
3448 return "408 Request Timeout";
3449 case AST_CAUSE_NO_ANSWER: /* 19 */
3450 return "480 Temporarily unavailable";
3451 case AST_CAUSE_CALL_REJECTED: /* 21 */
3452 return "403 Forbidden";
3453 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
3454 return "410 Gone";
3455 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
3456 return "480 Temporarily unavailable";
3457 case AST_CAUSE_INVALID_NUMBER_FORMAT:
3458 return "484 Address incomplete";
3459 case AST_CAUSE_USER_BUSY:
3460 return "486 Busy here";
3461 case AST_CAUSE_FAILURE:
3462 return "500 Server internal failure";
3463 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
3464 return "501 Not Implemented";
3465 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
3466 return "503 Service Unavailable";
3467 /* Used in chan_iax2 */
3468 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
3469 return "502 Bad Gateway";
3470 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
3471 return "488 Not Acceptable Here";
3473 case AST_CAUSE_NOTDEFINED:
3474 default:
3475 if (option_debug)
3476 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
3477 return NULL;
3480 /* Never reached */
3481 return 0;
3485 /*! \brief sip_hangup: Hangup SIP call
3486 * Part of PBX interface, called from ast_hangup */
3487 static int sip_hangup(struct ast_channel *ast)
3489 struct sip_pvt *p = ast->tech_pvt;
3490 int needcancel = FALSE;
3491 int needdestroy = 0;
3492 struct ast_channel *oldowner = ast;
3494 if (!p) {
3495 if (option_debug)
3496 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
3497 return 0;
3500 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
3501 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
3502 if (option_debug && sipdebug)
3503 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
3504 update_call_counter(p, DEC_CALL_LIMIT);
3506 if (option_debug >3)
3507 ast_log(LOG_DEBUG, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
3508 if (p->autokillid > -1 && sip_cancel_destroy(p))
3509 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
3510 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3511 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
3512 ast_clear_flag(&p->flags[0], SIP_NEEDDESTROY);
3513 p->owner->tech_pvt = NULL;
3514 p->owner = NULL; /* Owner will be gone after we return, so take it away */
3515 return 0;
3517 if (option_debug) {
3518 if (ast_test_flag(ast, AST_FLAG_ZOMBIE) && p->refer && option_debug)
3519 ast_log(LOG_DEBUG, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
3520 else {
3521 if (option_debug)
3522 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
3525 if (option_debug && ast_test_flag(ast, AST_FLAG_ZOMBIE))
3526 ast_log(LOG_DEBUG, "Hanging up zombie call. Be scared.\n");
3528 ast_mutex_lock(&p->lock);
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);
3535 /* Determine how to disconnect */
3536 if (p->owner != ast) {
3537 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
3538 ast_mutex_unlock(&p->lock);
3539 return 0;
3541 /* If the call is not UP, we need to send CANCEL instead of BYE */
3542 if (ast->_state == AST_STATE_RING || ast->_state == AST_STATE_RINGING || (p->invitestate < INV_COMPLETED && ast->_state != AST_STATE_UP)) {
3543 needcancel = TRUE;
3544 if (option_debug > 3)
3545 ast_log(LOG_DEBUG, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
3548 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
3550 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->owner->hangupcause) : "Unknown");
3552 /* Disconnect */
3553 if (p->vad)
3554 ast_dsp_free(p->vad);
3556 p->owner = NULL;
3557 ast->tech_pvt = NULL;
3559 ast_module_unref(ast_module_info->self);
3561 /* Do not destroy this pvt until we have timeout or
3562 get an answer to the BYE or INVITE/CANCEL
3563 If we get no answer during retransmit period, drop the call anyway.
3564 (Sorry, mother-in-law, you can't deny a hangup by sending
3565 603 declined to BYE...)
3567 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE))
3568 needdestroy = 1; /* Set destroy flag at end of this function */
3569 else if (p->invitestate != INV_CALLING)
3570 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3572 /* Start the process if it's not already started */
3573 if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
3574 if (needcancel) { /* Outgoing call, not up */
3575 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3576 /* stop retransmitting an INVITE that has not received a response */
3577 __sip_pretend_ack(p);
3578 p->invitestate = INV_CANCELLED;
3580 /* if we can't send right now, mark it pending */
3581 if (p->invitestate == INV_CALLING) {
3582 /* We can't send anything in CALLING state */
3583 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3584 /* 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. */
3585 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3586 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
3587 } else {
3588 /* Send a new request: CANCEL */
3589 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
3590 /* Actually don't destroy us yet, wait for the 487 on our original
3591 INVITE, but do set an autodestruct just in case we never get it. */
3592 needdestroy = 0;
3593 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3595 if ( p->initid != -1 ) {
3596 /* channel still up - reverse dec of inUse counter
3597 only if the channel is not auto-congested */
3598 update_call_counter(p, INC_CALL_LIMIT);
3600 } else { /* Incoming call, not up */
3601 const char *res;
3602 if (ast->hangupcause && (res = hangup_cause2sip(ast->hangupcause)))
3603 transmit_response_reliable(p, res, &p->initreq);
3604 else
3605 transmit_response_reliable(p, "603 Declined", &p->initreq);
3606 p->invitestate = INV_TERMINATED;
3608 } else { /* Call is in UP state, send BYE */
3609 if (!p->pendinginvite) {
3610 char *audioqos = "";
3611 char *videoqos = "";
3612 if (p->rtp)
3613 audioqos = ast_rtp_get_quality(p->rtp, NULL);
3614 if (p->vrtp)
3615 videoqos = ast_rtp_get_quality(p->vrtp, NULL);
3616 /* Send a hangup */
3617 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3619 /* Get RTCP quality before end of call */
3620 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
3621 if (p->rtp)
3622 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
3623 if (p->vrtp)
3624 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
3626 if (p->rtp && oldowner)
3627 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
3628 if (p->vrtp && oldowner)
3629 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
3630 } else {
3631 /* Note we will need a BYE when this all settles out
3632 but we can't send one while we have "INVITE" outstanding. */
3633 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3634 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
3635 AST_SCHED_DEL(sched, p->waitid);
3636 if (sip_cancel_destroy(p))
3637 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
3641 if (needdestroy)
3642 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
3643 ast_mutex_unlock(&p->lock);
3644 return 0;
3647 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
3648 static void try_suggested_sip_codec(struct sip_pvt *p)
3650 int fmt;
3651 const char *codec;
3653 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
3654 if (!codec)
3655 return;
3657 fmt = ast_getformatbyname(codec);
3658 if (fmt) {
3659 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
3660 if (p->jointcapability & fmt) {
3661 p->jointcapability &= fmt;
3662 p->capability &= fmt;
3663 } else
3664 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
3665 } else
3666 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
3667 return;
3670 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
3671 * Part of PBX interface */
3672 static int sip_answer(struct ast_channel *ast)
3674 int res = 0;
3675 struct sip_pvt *p = ast->tech_pvt;
3677 ast_mutex_lock(&p->lock);
3678 if (ast->_state != AST_STATE_UP) {
3679 try_suggested_sip_codec(p);
3681 ast_setstate(ast, AST_STATE_UP);
3682 if (option_debug)
3683 ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name);
3684 if (p->t38.state == T38_PEER_DIRECT) {
3685 p->t38.state = T38_ENABLED;
3686 if (option_debug > 1)
3687 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
3688 res = transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
3689 } else {
3690 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
3693 ast_mutex_unlock(&p->lock);
3694 return res;
3697 /*! \brief Send frame to media channel (rtp) */
3698 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
3700 struct sip_pvt *p = ast->tech_pvt;
3701 int res = 0;
3703 switch (frame->frametype) {
3704 case AST_FRAME_VOICE:
3705 if (!(frame->subclass & ast->nativeformats)) {
3706 char s1[512], s2[512], s3[512];
3707 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
3708 frame->subclass,
3709 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
3710 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
3711 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
3712 ast->readformat,
3713 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
3714 ast->writeformat);
3715 return 0;
3717 if (p) {
3718 ast_mutex_lock(&p->lock);
3719 if (p->rtp) {
3720 /* If channel is not up, activate early media session */
3721 if ((ast->_state != AST_STATE_UP) &&
3722 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3723 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3724 ast_rtp_new_source(p->rtp);
3725 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3726 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3728 p->lastrtptx = time(NULL);
3729 res = ast_rtp_write(p->rtp, frame);
3731 ast_mutex_unlock(&p->lock);
3733 break;
3734 case AST_FRAME_VIDEO:
3735 if (p) {
3736 ast_mutex_lock(&p->lock);
3737 if (p->vrtp) {
3738 /* Activate video early media */
3739 if ((ast->_state != AST_STATE_UP) &&
3740 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3741 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3742 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3743 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3745 p->lastrtptx = time(NULL);
3746 res = ast_rtp_write(p->vrtp, frame);
3748 ast_mutex_unlock(&p->lock);
3750 break;
3751 case AST_FRAME_IMAGE:
3752 return 0;
3753 break;
3754 case AST_FRAME_MODEM:
3755 if (p) {
3756 ast_mutex_lock(&p->lock);
3757 /* UDPTL requires two-way communication, so early media is not needed here.
3758 we simply forget the frames if we get modem frames before the bridge is up.
3759 Fax will re-transmit.
3761 if (p->udptl && ast->_state == AST_STATE_UP)
3762 res = ast_udptl_write(p->udptl, frame);
3763 ast_mutex_unlock(&p->lock);
3765 break;
3766 default:
3767 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
3768 return 0;
3771 return res;
3774 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
3775 Basically update any ->owner links */
3776 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
3778 int ret = -1;
3779 struct sip_pvt *p;
3781 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE) && option_debug)
3782 ast_log(LOG_DEBUG, "New channel is zombie\n");
3783 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE) && option_debug)
3784 ast_log(LOG_DEBUG, "Old channel is zombie\n");
3786 if (!newchan || !newchan->tech_pvt) {
3787 if (!newchan)
3788 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
3789 else
3790 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
3791 return -1;
3793 p = newchan->tech_pvt;
3795 if (!p) {
3796 ast_log(LOG_WARNING, "No pvt after masquerade. Strange things may happen\n");
3797 return -1;
3800 ast_mutex_lock(&p->lock);
3801 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
3802 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
3803 if (p->owner != oldchan)
3804 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
3805 else {
3806 p->owner = newchan;
3807 ret = 0;
3809 if (option_debug > 2)
3810 ast_log(LOG_DEBUG, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
3812 ast_mutex_unlock(&p->lock);
3813 return ret;
3816 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
3818 struct sip_pvt *p = ast->tech_pvt;
3819 int res = 0;
3821 ast_mutex_lock(&p->lock);
3822 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
3823 case SIP_DTMF_INBAND:
3824 res = -1; /* Tell Asterisk to generate inband indications */
3825 break;
3826 case SIP_DTMF_RFC2833:
3827 if (p->rtp)
3828 ast_rtp_senddigit_begin(p->rtp, digit);
3829 break;
3830 default:
3831 break;
3833 ast_mutex_unlock(&p->lock);
3835 return res;
3838 /*! \brief Send DTMF character on SIP channel
3839 within one call, we're able to transmit in many methods simultaneously */
3840 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
3842 struct sip_pvt *p = ast->tech_pvt;
3843 int res = 0;
3845 ast_mutex_lock(&p->lock);
3846 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
3847 case SIP_DTMF_INFO:
3848 transmit_info_with_digit(p, digit, duration);
3849 break;
3850 case SIP_DTMF_RFC2833:
3851 if (p->rtp)
3852 ast_rtp_senddigit_end(p->rtp, digit);
3853 break;
3854 case SIP_DTMF_INBAND:
3855 res = -1; /* Tell Asterisk to stop inband indications */
3856 break;
3858 ast_mutex_unlock(&p->lock);
3860 return res;
3863 /*! \brief Transfer SIP call */
3864 static int sip_transfer(struct ast_channel *ast, const char *dest)
3866 struct sip_pvt *p = ast->tech_pvt;
3867 int res;
3869 if (dest == NULL) /* functions below do not take a NULL */
3870 dest = "";
3871 ast_mutex_lock(&p->lock);
3872 if (ast->_state == AST_STATE_RING)
3873 res = sip_sipredirect(p, dest);
3874 else
3875 res = transmit_refer(p, dest);
3876 ast_mutex_unlock(&p->lock);
3877 return res;
3880 /*! \brief Play indication to user
3881 * With SIP a lot of indications is sent as messages, letting the device play
3882 the indication - busy signal, congestion etc
3883 \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
3885 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
3887 struct sip_pvt *p = ast->tech_pvt;
3888 int res = 0;
3890 ast_mutex_lock(&p->lock);
3891 switch(condition) {
3892 case AST_CONTROL_RINGING:
3893 if (ast->_state == AST_STATE_RING) {
3894 p->invitestate = INV_EARLY_MEDIA;
3895 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
3896 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
3897 /* Send 180 ringing if out-of-band seems reasonable */
3898 transmit_response(p, "180 Ringing", &p->initreq);
3899 ast_set_flag(&p->flags[0], SIP_RINGING);
3900 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
3901 break;
3902 } else {
3903 /* Well, if it's not reasonable, just send in-band */
3906 res = -1;
3907 break;
3908 case AST_CONTROL_BUSY:
3909 if (ast->_state != AST_STATE_UP) {
3910 transmit_response(p, "486 Busy Here", &p->initreq);
3911 p->invitestate = INV_COMPLETED;
3912 sip_alreadygone(p);
3913 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
3914 break;
3916 res = -1;
3917 break;
3918 case AST_CONTROL_CONGESTION:
3919 if (ast->_state != AST_STATE_UP) {
3920 transmit_response(p, "503 Service Unavailable", &p->initreq);
3921 p->invitestate = INV_COMPLETED;
3922 sip_alreadygone(p);
3923 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
3924 break;
3926 res = -1;
3927 break;
3928 case AST_CONTROL_PROCEEDING:
3929 if ((ast->_state != AST_STATE_UP) &&
3930 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3931 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3932 transmit_response(p, "100 Trying", &p->initreq);
3933 p->invitestate = INV_PROCEEDING;
3934 break;
3936 res = -1;
3937 break;
3938 case AST_CONTROL_PROGRESS:
3939 if ((ast->_state != AST_STATE_UP) &&
3940 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3941 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3942 p->invitestate = INV_EARLY_MEDIA;
3943 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3944 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3945 break;
3947 res = -1;
3948 break;
3949 case AST_CONTROL_HOLD:
3950 ast_rtp_new_source(p->rtp);
3951 ast_moh_start(ast, data, p->mohinterpret);
3952 break;
3953 case AST_CONTROL_UNHOLD:
3954 ast_rtp_new_source(p->rtp);
3955 ast_moh_stop(ast);
3956 break;
3957 case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
3958 if (p->vrtp && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
3959 transmit_info_with_vidupdate(p);
3960 /* ast_rtcp_send_h261fur(p->vrtp); */
3961 } else
3962 res = -1;
3963 break;
3964 case AST_CONTROL_SRCUPDATE:
3965 ast_rtp_new_source(p->rtp);
3966 break;
3967 case -1:
3968 res = -1;
3969 break;
3970 default:
3971 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
3972 res = -1;
3973 break;
3975 ast_mutex_unlock(&p->lock);
3976 return res;
3980 /*! \brief Initiate a call in the SIP channel
3981 called from sip_request_call (calls from the pbx ) for outbound channels
3982 and from handle_request_invite for inbound channels
3985 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
3987 struct ast_channel *tmp;
3988 struct ast_variable *v = NULL;
3989 int fmt;
3990 int what;
3991 int needvideo = 0, video = 0;
3992 char *decoded_exten;
3994 const char *my_name; /* pick a good name */
3996 if (title)
3997 my_name = title;
3998 else if ( (my_name = strchr(i->fromdomain,':')) )
3999 my_name++; /* skip ':' */
4000 else
4001 my_name = i->fromdomain;
4003 ast_mutex_unlock(&i->lock);
4004 /* Don't hold a sip pvt lock while we allocate a channel */
4005 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);
4008 if (!tmp) {
4009 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
4010 ast_mutex_lock(&i->lock);
4011 return NULL;
4013 ast_mutex_lock(&i->lock);
4015 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO)
4016 tmp->tech = &sip_tech_info;
4017 else
4018 tmp->tech = &sip_tech;
4020 /* Select our native format based on codec preference until we receive
4021 something from another device to the contrary. */
4022 if (i->jointcapability) { /* The joint capabilities of us and peer */
4023 what = i->jointcapability;
4024 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
4025 } else if (i->capability) { /* Our configured capability for this peer */
4026 what = i->capability;
4027 video = i->capability & AST_FORMAT_VIDEO_MASK;
4028 } else {
4029 what = global_capability; /* Global codec support */
4030 video = global_capability & AST_FORMAT_VIDEO_MASK;
4033 /* Set the native formats for audio and merge in video */
4034 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video;
4035 if (option_debug > 2) {
4036 char buf[SIPBUFSIZE];
4037 ast_log(LOG_DEBUG, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
4038 ast_log(LOG_DEBUG, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
4039 ast_log(LOG_DEBUG, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
4040 ast_log(LOG_DEBUG, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
4041 if (i->prefcodec)
4042 ast_log(LOG_DEBUG, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
4045 /* XXX Why are we choosing a codec from the native formats?? */
4046 fmt = ast_best_codec(tmp->nativeformats);
4048 /* If we have a prefcodec setting, we have an inbound channel that set a
4049 preferred format for this call. Otherwise, we check the jointcapability
4050 We also check for vrtp. If it's not there, we are not allowed do any video anyway.
4052 if (i->vrtp) {
4053 if (i->prefcodec)
4054 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK; /* Outbound call */
4055 else
4056 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK; /* Inbound call */
4059 if (option_debug > 2) {
4060 if (needvideo)
4061 ast_log(LOG_DEBUG, "This channel can handle video! HOLLYWOOD next!\n");
4062 else
4063 ast_log(LOG_DEBUG, "This channel will not be able to handle video.\n");
4068 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
4069 i->vad = ast_dsp_new();
4070 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
4071 if (global_relaxdtmf)
4072 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
4074 if (i->rtp) {
4075 tmp->fds[0] = ast_rtp_fd(i->rtp);
4076 tmp->fds[1] = ast_rtcp_fd(i->rtp);
4078 if (needvideo && i->vrtp) {
4079 tmp->fds[2] = ast_rtp_fd(i->vrtp);
4080 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
4082 if (i->udptl) {
4083 tmp->fds[5] = ast_udptl_fd(i->udptl);
4085 if (state == AST_STATE_RING)
4086 tmp->rings = 1;
4087 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
4088 tmp->writeformat = fmt;
4089 tmp->rawwriteformat = fmt;
4090 tmp->readformat = fmt;
4091 tmp->rawreadformat = fmt;
4092 tmp->tech_pvt = i;
4094 tmp->callgroup = i->callgroup;
4095 tmp->pickupgroup = i->pickupgroup;
4096 tmp->cid.cid_pres = i->callingpres;
4097 if (!ast_strlen_zero(i->accountcode))
4098 ast_string_field_set(tmp, accountcode, i->accountcode);
4099 if (i->amaflags)
4100 tmp->amaflags = i->amaflags;
4101 if (!ast_strlen_zero(i->language))
4102 ast_string_field_set(tmp, language, i->language);
4103 i->owner = tmp;
4104 ast_module_ref(ast_module_info->self);
4105 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
4106 /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
4107 * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
4108 * structure so that there aren't issues when forming URI's
4110 decoded_exten = ast_strdupa(i->exten);
4111 ast_uri_decode(decoded_exten);
4112 ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
4114 /* Don't use ast_set_callerid() here because it will
4115 * generate an unnecessary NewCallerID event */
4116 tmp->cid.cid_ani = ast_strdup(i->cid_num);
4117 if (!ast_strlen_zero(i->rdnis))
4118 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
4120 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
4121 tmp->cid.cid_dnid = ast_strdup(i->exten);
4123 tmp->priority = 1;
4124 if (!ast_strlen_zero(i->uri))
4125 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
4126 if (!ast_strlen_zero(i->domain))
4127 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
4128 if (!ast_strlen_zero(i->useragent))
4129 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
4130 if (!ast_strlen_zero(i->callid))
4131 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
4132 if (i->rtp)
4133 ast_jb_configure(tmp, &global_jbconf);
4135 /* If the INVITE contains T.38 SDP information set the proper channel variable so a created outgoing call will also have T.38 */
4136 if (i->udptl && i->t38.state == T38_PEER_DIRECT)
4137 pbx_builtin_setvar_helper(tmp, "_T38CALL", "1");
4139 /* Set channel variables for this call from configuration */
4140 for (v = i->chanvars ; v ; v = v->next)
4141 pbx_builtin_setvar_helper(tmp, v->name, v->value);
4143 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
4144 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
4145 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
4146 ast_hangup(tmp);
4147 tmp = NULL;
4150 if (!ast_test_flag(&i->flags[0], SIP_NO_HISTORY))
4151 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
4153 return tmp;
4156 /*! \brief Reads one line of SIP message body */
4157 static char *get_body_by_line(const char *line, const char *name, int nameLen)
4159 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=')
4160 return ast_skip_blanks(line + nameLen + 1);
4162 return "";
4165 /*! \brief Lookup 'name' in the SDP starting
4166 * at the 'start' line. Returns the matching line, and 'start'
4167 * is updated with the next line number.
4169 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
4171 int len = strlen(name);
4173 while (*start < req->sdp_end) {
4174 const char *r = get_body_by_line(req->line[(*start)++], name, len);
4175 if (r[0] != '\0')
4176 return r;
4179 return "";
4182 /*! \brief Get a line from an SDP message body */
4183 static const char *get_sdp(struct sip_request *req, const char *name)
4185 int dummy = 0;
4187 return get_sdp_iterate(&dummy, req, name);
4190 /*! \brief Get a specific line from the message body */
4191 static char *get_body(struct sip_request *req, char *name)
4193 int x;
4194 int len = strlen(name);
4195 char *r;
4197 for (x = 0; x < req->lines; x++) {
4198 r = get_body_by_line(req->line[x], name, len);
4199 if (r[0] != '\0')
4200 return r;
4203 return "";
4206 /*! \brief Find compressed SIP alias */
4207 static const char *find_alias(const char *name, const char *_default)
4209 /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
4210 static const struct cfalias {
4211 char * const fullname;
4212 char * const shortname;
4213 } aliases[] = {
4214 { "Content-Type", "c" },
4215 { "Content-Encoding", "e" },
4216 { "From", "f" },
4217 { "Call-ID", "i" },
4218 { "Contact", "m" },
4219 { "Content-Length", "l" },
4220 { "Subject", "s" },
4221 { "To", "t" },
4222 { "Supported", "k" },
4223 { "Refer-To", "r" },
4224 { "Referred-By", "b" },
4225 { "Allow-Events", "u" },
4226 { "Event", "o" },
4227 { "Via", "v" },
4228 { "Accept-Contact", "a" },
4229 { "Reject-Contact", "j" },
4230 { "Request-Disposition", "d" },
4231 { "Session-Expires", "x" },
4232 { "Identity", "y" },
4233 { "Identity-Info", "n" },
4235 int x;
4237 for (x=0; x<sizeof(aliases) / sizeof(aliases[0]); x++)
4238 if (!strcasecmp(aliases[x].fullname, name))
4239 return aliases[x].shortname;
4241 return _default;
4244 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
4246 int pass;
4249 * Technically you can place arbitrary whitespace both before and after the ':' in
4250 * a header, although RFC3261 clearly says you shouldn't before, and place just
4251 * one afterwards. If you shouldn't do it, what absolute idiot decided it was
4252 * a good idea to say you can do it, and if you can do it, why in the hell would.
4253 * you say you shouldn't.
4254 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
4255 * and we always allow spaces after that for compatibility.
4257 for (pass = 0; name && pass < 2;pass++) {
4258 int x, len = strlen(name);
4259 for (x=*start; x<req->headers; x++) {
4260 if (!strncasecmp(req->header[x], name, len)) {
4261 char *r = req->header[x] + len; /* skip name */
4262 if (pedanticsipchecking)
4263 r = ast_skip_blanks(r);
4265 if (*r == ':') {
4266 *start = x+1;
4267 return ast_skip_blanks(r+1);
4271 if (pass == 0) /* Try aliases */
4272 name = find_alias(name, NULL);
4275 /* Don't return NULL, so get_header is always a valid pointer */
4276 return "";
4279 /*! \brief Get header from SIP request */
4280 static const char *get_header(const struct sip_request *req, const char *name)
4282 int start = 0;
4283 return __get_header(req, name, &start);
4286 /*! \brief Read RTP from network */
4287 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
4289 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
4290 struct ast_frame *f;
4292 if (!p->rtp) {
4293 /* We have no RTP allocated for this channel */
4294 return &ast_null_frame;
4297 switch(ast->fdno) {
4298 case 0:
4299 f = ast_rtp_read(p->rtp); /* RTP Audio */
4300 break;
4301 case 1:
4302 f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
4303 break;
4304 case 2:
4305 f = ast_rtp_read(p->vrtp); /* RTP Video */
4306 break;
4307 case 3:
4308 f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
4309 break;
4310 case 5:
4311 f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
4312 break;
4313 default:
4314 f = &ast_null_frame;
4316 /* Don't forward RFC2833 if we're not supposed to */
4317 if (f && (f->frametype == AST_FRAME_DTMF) &&
4318 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833))
4319 return &ast_null_frame;
4321 /* We already hold the channel lock */
4322 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
4323 return f;
4325 if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
4326 if (!(f->subclass & p->jointcapability)) {
4327 if (option_debug) {
4328 ast_log(LOG_DEBUG, "Bogus frame of format '%s' received from '%s'!\n",
4329 ast_getformatname(f->subclass), p->owner->name);
4331 return &ast_null_frame;
4333 if (option_debug)
4334 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
4335 p->owner->nativeformats = (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
4336 ast_set_read_format(p->owner, p->owner->readformat);
4337 ast_set_write_format(p->owner, p->owner->writeformat);
4340 if (f && (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
4341 f = ast_dsp_process(p->owner, p->vad, f);
4342 if (f && f->frametype == AST_FRAME_DTMF) {
4343 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && f->subclass == 'f') {
4344 if (option_debug)
4345 ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
4346 *faxdetect = 1;
4347 } else if (option_debug) {
4348 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
4353 return f;
4356 /*! \brief Read SIP RTP from channel */
4357 static struct ast_frame *sip_read(struct ast_channel *ast)
4359 struct ast_frame *fr;
4360 struct sip_pvt *p = ast->tech_pvt;
4361 int faxdetected = FALSE;
4363 ast_mutex_lock(&p->lock);
4364 fr = sip_rtp_read(ast, p, &faxdetected);
4365 p->lastrtprx = time(NULL);
4367 /* If we are NOT bridged to another channel, and we have detected fax tone we issue T38 re-invite to a peer */
4368 /* 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 */
4369 if (faxdetected && ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && (p->t38.state == T38_DISABLED) && !(ast_bridged_channel(ast))) {
4370 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
4371 if (!p->pendinginvite) {
4372 if (option_debug > 2)
4373 ast_log(LOG_DEBUG, "Sending reinvite on SIP (%s) for T.38 negotiation.\n",ast->name);
4374 p->t38.state = T38_LOCAL_REINVITE;
4375 transmit_reinvite_with_t38_sdp(p);
4376 if (option_debug > 1)
4377 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, ast->name);
4379 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
4380 if (option_debug > 2)
4381 ast_log(LOG_DEBUG, "Deferring reinvite on SIP (%s) - it will be re-negotiated for T.38\n", ast->name);
4382 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
4386 /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
4387 if (fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
4388 fr = &ast_null_frame;
4391 ast_mutex_unlock(&p->lock);
4392 return fr;
4396 /*! \brief Generate 32 byte random string for callid's etc */
4397 static char *generate_random_string(char *buf, size_t size)
4399 long val[4];
4400 int x;
4402 for (x=0; x<4; x++)
4403 val[x] = ast_random();
4404 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
4406 return buf;
4409 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
4410 static void build_callid_pvt(struct sip_pvt *pvt)
4412 char buf[33];
4414 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip));
4416 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
4420 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
4421 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
4423 char buf[33];
4425 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
4427 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
4430 /*! \brief Make our SIP dialog tag */
4431 static void make_our_tag(char *tagbuf, size_t len)
4433 snprintf(tagbuf, len, "as%08lx", ast_random());
4436 /*! \brief Allocate SIP_PVT structure and set defaults */
4437 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
4438 int useglobal_nat, const int intended_method)
4440 struct sip_pvt *p;
4442 if (!(p = ast_calloc(1, sizeof(*p))))
4443 return NULL;
4445 if (ast_string_field_init(p, 512)) {
4446 free(p);
4447 return NULL;
4450 ast_mutex_init(&p->lock);
4452 p->method = intended_method;
4453 p->initid = -1;
4454 p->waitid = -1;
4455 p->autokillid = -1;
4456 p->subscribed = NONE;
4457 p->stateid = -1;
4458 p->prefs = default_prefs; /* Set default codecs for this call */
4460 if (intended_method != SIP_OPTIONS) /* Peerpoke has it's own system */
4461 p->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
4463 if (sin) {
4464 p->sa = *sin;
4465 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
4466 p->ourip = __ourip;
4467 } else
4468 p->ourip = __ourip;
4470 /* Copy global flags to this PVT at setup. */
4471 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
4472 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
4474 ast_set2_flag(&p->flags[0], !recordhistory, SIP_NO_HISTORY);
4476 p->branch = ast_random();
4477 make_our_tag(p->tag, sizeof(p->tag));
4478 p->ocseq = INITIAL_CSEQ;
4480 if (sip_methods[intended_method].need_rtp) {
4481 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
4482 /* If the global videosupport flag is on, we always create a RTP interface for video */
4483 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
4484 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
4485 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
4486 p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
4487 if (!p->rtp || (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)) {
4488 ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n",
4489 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video" : "", strerror(errno));
4490 ast_mutex_destroy(&p->lock);
4491 if (p->chanvars) {
4492 ast_variables_destroy(p->chanvars);
4493 p->chanvars = NULL;
4495 free(p);
4496 return NULL;
4498 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
4499 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
4500 ast_rtp_settos(p->rtp, global_tos_audio);
4501 ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
4502 ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
4503 ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
4504 if (p->vrtp) {
4505 ast_rtp_settos(p->vrtp, global_tos_video);
4506 ast_rtp_setdtmf(p->vrtp, 0);
4507 ast_rtp_setdtmfcompensate(p->vrtp, 0);
4508 ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
4509 ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
4510 ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
4512 if (p->udptl)
4513 ast_udptl_settos(p->udptl, global_tos_audio);
4514 p->maxcallbitrate = default_maxcallbitrate;
4517 if (useglobal_nat && sin) {
4518 /* Setup NAT structure according to global settings if we have an address */
4519 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
4520 p->recv = *sin;
4521 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
4524 if (p->method != SIP_REGISTER)
4525 ast_string_field_set(p, fromdomain, default_fromdomain);
4526 build_via(p);
4527 if (!callid)
4528 build_callid_pvt(p);
4529 else
4530 ast_string_field_set(p, callid, callid);
4531 /* Assign default music on hold class */
4532 ast_string_field_set(p, mohinterpret, default_mohinterpret);
4533 ast_string_field_set(p, mohsuggest, default_mohsuggest);
4534 p->capability = global_capability;
4535 p->allowtransfer = global_allowtransfer;
4536 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
4537 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
4538 p->noncodeccapability |= AST_RTP_DTMF;
4539 if (p->udptl) {
4540 p->t38.capability = global_t38_capability;
4541 if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY)
4542 p->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
4543 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_FEC)
4544 p->t38.capability |= T38FAX_UDP_EC_FEC;
4545 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_NONE)
4546 p->t38.capability |= T38FAX_UDP_EC_NONE;
4547 p->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
4548 p->t38.jointcapability = p->t38.capability;
4550 ast_string_field_set(p, context, default_context);
4552 /* Add to active dialog list */
4553 ast_mutex_lock(&iflock);
4554 p->next = iflist;
4555 iflist = p;
4556 ast_mutex_unlock(&iflock);
4557 if (option_debug)
4558 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");
4559 return p;
4562 /*! \brief Connect incoming SIP message to current dialog or create new dialog structure
4563 Called by handle_request, sipsock_read */
4564 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
4566 struct sip_pvt *p = NULL;
4567 char *tag = ""; /* note, tag is never NULL */
4568 char totag[128];
4569 char fromtag[128];
4570 const char *callid = get_header(req, "Call-ID");
4571 const char *from = get_header(req, "From");
4572 const char *to = get_header(req, "To");
4573 const char *cseq = get_header(req, "Cseq");
4575 /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
4576 /* get_header always returns non-NULL so we must use ast_strlen_zero() */
4577 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
4578 ast_strlen_zero(from) || ast_strlen_zero(cseq))
4579 return NULL; /* Invalid packet */
4581 if (pedanticsipchecking) {
4582 /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
4583 we need more to identify a branch - so we have to check branch, from
4584 and to tags to identify a call leg.
4585 For Asterisk to behave correctly, you need to turn on pedanticsipchecking
4586 in sip.conf
4588 if (gettag(req, "To", totag, sizeof(totag)))
4589 ast_set_flag(req, SIP_PKT_WITH_TOTAG); /* Used in handle_request/response */
4590 gettag(req, "From", fromtag, sizeof(fromtag));
4592 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
4594 if (option_debug > 4 )
4595 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);
4598 ast_mutex_lock(&iflock);
4599 for (p = iflist; p; p = p->next) {
4600 /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
4601 int found = FALSE;
4602 if (ast_strlen_zero(p->callid))
4603 continue;
4604 if (req->method == SIP_REGISTER)
4605 found = (!strcmp(p->callid, callid));
4606 else
4607 found = (!strcmp(p->callid, callid) &&
4608 (!pedanticsipchecking || ast_strlen_zero(tag) || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ;
4610 if (option_debug > 4)
4611 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);
4613 /* If we get a new request within an existing to-tag - check the to tag as well */
4614 if (pedanticsipchecking && found && req->method != SIP_RESPONSE) { /* SIP Request */
4615 if (p->tag[0] == '\0' && totag[0]) {
4616 /* We have no to tag, but they have. Wrong dialog */
4617 found = FALSE;
4618 } else if (totag[0]) { /* Both have tags, compare them */
4619 if (strcmp(totag, p->tag)) {
4620 found = FALSE; /* This is not our packet */
4623 if (!found && option_debug > 4)
4624 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);
4628 if (found) {
4629 /* Found the call */
4630 ast_mutex_lock(&p->lock);
4631 ast_mutex_unlock(&iflock);
4632 return p;
4635 ast_mutex_unlock(&iflock);
4637 /* See if the method is capable of creating a dialog */
4638 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
4639 if (intended_method == SIP_REFER) {
4640 /* We do support REFER, but not outside of a dialog yet */
4641 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
4642 } else if (intended_method == SIP_NOTIFY) {
4643 /* We do not support out-of-dialog NOTIFY either,
4644 like voicemail notification, so cancel that early */
4645 transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
4646 } else {
4647 /* Ok, time to create a new SIP dialog object, a pvt */
4648 if ((p = sip_alloc(callid, sin, 1, intended_method))) {
4649 /* Ok, we've created a dialog, let's go and process it */
4650 ast_mutex_lock(&p->lock);
4651 } else {
4652 /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
4653 getting a dialog from sip_alloc.
4655 Without a dialog we can't retransmit and handle ACKs and all that, but at least
4656 send an error message.
4658 Sorry, we apologize for the inconvienience
4660 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
4661 if (option_debug > 3)
4662 ast_log(LOG_DEBUG, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
4665 return p;
4666 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
4667 /* A method we do not support, let's take it on the volley */
4668 transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
4669 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
4670 /* This is a request outside of a dialog that we don't know about
4671 ...never reply to an ACK!
4673 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
4675 /* We do not respond to responses for dialogs that we don't know about, we just drop
4676 the session quickly */
4678 return p;
4681 /*! \brief Parse register=> line in sip.conf and add to registry */
4682 static int sip_register(char *value, int lineno)
4684 struct sip_registry *reg;
4685 int portnum = 0;
4686 char username[256] = "";
4687 char *hostname=NULL, *secret=NULL, *authuser=NULL;
4688 char *porta=NULL;
4689 char *contact=NULL;
4691 if (!value)
4692 return -1;
4693 ast_copy_string(username, value, sizeof(username));
4694 /* First split around the last '@' then parse the two components. */
4695 hostname = strrchr(username, '@'); /* allow @ in the first part */
4696 if (hostname)
4697 *hostname++ = '\0';
4698 if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
4699 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
4700 return -1;
4702 /* split user[:secret[:authuser]] */
4703 secret = strchr(username, ':');
4704 if (secret) {
4705 *secret++ = '\0';
4706 authuser = strchr(secret, ':');
4707 if (authuser)
4708 *authuser++ = '\0';
4710 /* split host[:port][/contact] */
4711 contact = strchr(hostname, '/');
4712 if (contact)
4713 *contact++ = '\0';
4714 if (ast_strlen_zero(contact))
4715 contact = "s";
4716 porta = strchr(hostname, ':');
4717 if (porta) {
4718 *porta++ = '\0';
4719 portnum = atoi(porta);
4720 if (portnum == 0) {
4721 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
4722 return -1;
4725 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
4726 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
4727 return -1;
4730 if (ast_string_field_init(reg, 256)) {
4731 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
4732 free(reg);
4733 return -1;
4736 regobjs++;
4737 ASTOBJ_INIT(reg);
4738 ast_string_field_set(reg, contact, contact);
4739 if (!ast_strlen_zero(username))
4740 ast_string_field_set(reg, username, username);
4741 if (hostname)
4742 ast_string_field_set(reg, hostname, hostname);
4743 if (authuser)
4744 ast_string_field_set(reg, authuser, authuser);
4745 if (secret)
4746 ast_string_field_set(reg, secret, secret);
4747 reg->expire = -1;
4748 reg->timeout = -1;
4749 reg->refresh = default_expiry;
4750 reg->portno = portnum;
4751 reg->callid_valid = FALSE;
4752 reg->ocseq = INITIAL_CSEQ;
4753 ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
4754 ASTOBJ_UNREF(reg,sip_registry_destroy);
4755 return 0;
4758 /*! \brief Parse multiline SIP headers into one header
4759 This is enabled if pedanticsipchecking is enabled */
4760 static int lws2sws(char *msgbuf, int len)
4762 int h = 0, t = 0;
4763 int lws = 0;
4765 for (; h < len;) {
4766 /* Eliminate all CRs */
4767 if (msgbuf[h] == '\r') {
4768 h++;
4769 continue;
4771 /* Check for end-of-line */
4772 if (msgbuf[h] == '\n') {
4773 /* Check for end-of-message */
4774 if (h + 1 == len)
4775 break;
4776 /* Check for a continuation line */
4777 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
4778 /* Merge continuation line */
4779 h++;
4780 continue;
4782 /* Propagate LF and start new line */
4783 msgbuf[t++] = msgbuf[h++];
4784 lws = 0;
4785 continue;
4787 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
4788 if (lws) {
4789 h++;
4790 continue;
4792 msgbuf[t++] = msgbuf[h++];
4793 lws = 1;
4794 continue;
4796 msgbuf[t++] = msgbuf[h++];
4797 if (lws)
4798 lws = 0;
4800 msgbuf[t] = '\0';
4801 return t;
4804 /*! \brief Parse a SIP message
4805 \note this function is used both on incoming and outgoing packets
4807 static void parse_request(struct sip_request *req)
4809 /* Divide fields by NULL's */
4810 char *c;
4811 int f = 0;
4813 c = req->data;
4815 /* First header starts immediately */
4816 req->header[f] = c;
4817 while(*c) {
4818 if (*c == '\n') {
4819 /* We've got a new header */
4820 *c = 0;
4822 if (sipdebug && option_debug > 3)
4823 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
4824 if (ast_strlen_zero(req->header[f])) {
4825 /* Line by itself means we're now in content */
4826 c++;
4827 break;
4829 if (f >= SIP_MAX_HEADERS - 1) {
4830 ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n");
4831 } else
4832 f++;
4833 req->header[f] = c + 1;
4834 } else if (*c == '\r') {
4835 /* Ignore but eliminate \r's */
4836 *c = 0;
4838 c++;
4840 /* Check for last header */
4841 if (!ast_strlen_zero(req->header[f])) {
4842 if (sipdebug && option_debug > 3)
4843 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
4844 f++;
4846 req->headers = f;
4847 /* Now we process any mime content */
4848 f = 0;
4849 req->line[f] = c;
4850 while(*c) {
4851 if (*c == '\n') {
4852 /* We've got a new line */
4853 *c = 0;
4854 if (sipdebug && option_debug > 3)
4855 ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
4856 if (f >= SIP_MAX_LINES - 1) {
4857 ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n");
4858 } else
4859 f++;
4860 req->line[f] = c + 1;
4861 } else if (*c == '\r') {
4862 /* Ignore and eliminate \r's */
4863 *c = 0;
4865 c++;
4867 /* Check for last line */
4868 if (!ast_strlen_zero(req->line[f]))
4869 f++;
4870 req->lines = f;
4871 if (*c)
4872 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
4873 /* Split up the first line parts */
4874 determine_firstline_parts(req);
4878 \brief Determine whether a SIP message contains an SDP in its body
4879 \param req the SIP request to process
4880 \return 1 if SDP found, 0 if not found
4882 Also updates req->sdp_start and req->sdp_end to indicate where the SDP
4883 lives in the message body.
4885 static int find_sdp(struct sip_request *req)
4887 const char *content_type;
4888 const char *content_length;
4889 const char *search;
4890 char *boundary;
4891 unsigned int x;
4892 int boundaryisquoted = FALSE;
4893 int found_application_sdp = FALSE;
4894 int found_end_of_headers = FALSE;
4896 content_length = get_header(req, "Content-Length");
4898 if (!ast_strlen_zero(content_length)) {
4899 if (sscanf(content_length, "%ud", &x) != 1) {
4900 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
4901 return 0;
4904 /* Content-Length of zero means there can't possibly be an
4905 SDP here, even if the Content-Type says there is */
4906 if (x == 0)
4907 return 0;
4910 content_type = get_header(req, "Content-Type");
4912 /* if the body contains only SDP, this is easy */
4913 if (!strcasecmp(content_type, "application/sdp")) {
4914 req->sdp_start = 0;
4915 req->sdp_end = req->lines;
4916 return req->lines ? 1 : 0;
4919 /* if it's not multipart/mixed, there cannot be an SDP */
4920 if (strncasecmp(content_type, "multipart/mixed", 15))
4921 return 0;
4923 /* if there is no boundary marker, it's invalid */
4924 if ((search = strcasestr(content_type, ";boundary=")))
4925 search += 10;
4926 else if ((search = strcasestr(content_type, "; boundary=")))
4927 search += 11;
4928 else
4929 return 0;
4931 if (ast_strlen_zero(search))
4932 return 0;
4934 /* If the boundary is quoted with ", remove quote */
4935 if (*search == '\"') {
4936 search++;
4937 boundaryisquoted = TRUE;
4940 /* make a duplicate of the string, with two extra characters
4941 at the beginning */
4942 boundary = ast_strdupa(search - 2);
4943 boundary[0] = boundary[1] = '-';
4944 /* Remove final quote */
4945 if (boundaryisquoted)
4946 boundary[strlen(boundary) - 1] = '\0';
4948 /* search for the boundary marker, the empty line delimiting headers from
4949 sdp part and the end boundry if it exists */
4951 for (x = 0; x < (req->lines ); x++) {
4952 if(!strncasecmp(req->line[x], boundary, strlen(boundary))){
4953 if(found_application_sdp && found_end_of_headers){
4954 req->sdp_end = x-1;
4955 return 1;
4957 found_application_sdp = FALSE;
4959 if(!strcasecmp(req->line[x], "Content-Type: application/sdp"))
4960 found_application_sdp = TRUE;
4962 if(strlen(req->line[x]) == 0 ){
4963 if(found_application_sdp && !found_end_of_headers){
4964 req->sdp_start = x;
4965 found_end_of_headers = TRUE;
4969 if(found_application_sdp && found_end_of_headers) {
4970 req->sdp_end = x;
4971 return TRUE;
4973 return FALSE;
4976 /*! \brief Change hold state for a call */
4977 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
4979 if (global_notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
4980 sip_peer_hold(dialog, holdstate);
4981 if (global_callevents)
4982 manager_event(EVENT_FLAG_CALL, holdstate ? "Hold" : "Unhold",
4983 "Channel: %s\r\n"
4984 "Uniqueid: %s\r\n",
4985 dialog->owner->name,
4986 dialog->owner->uniqueid);
4987 append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data);
4988 if (!holdstate) { /* Put off remote hold */
4989 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
4990 return;
4992 /* No address for RTP, we're on hold */
4994 if (sendonly == 1) /* One directional hold (sendonly/recvonly) */
4995 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
4996 else if (sendonly == 2) /* Inactive stream */
4997 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
4998 else
4999 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
5000 return;
5003 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
5004 If offer is rejected, we will not change any properties of the call
5005 Return 0 on success, a negative value on errors.
5006 Must be called after find_sdp().
5008 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
5010 const char *m; /* SDP media offer */
5011 const char *c;
5012 const char *a;
5013 char host[258];
5014 int len = -1;
5015 int portno = -1; /*!< RTP Audio port number */
5016 int vportno = -1; /*!< RTP Video port number */
5017 int udptlportno = -1;
5018 int peert38capability = 0;
5019 char s[256];
5020 int old = 0;
5022 /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
5023 int peercapability = 0, peernoncodeccapability = 0;
5024 int vpeercapability = 0, vpeernoncodeccapability = 0;
5025 struct sockaddr_in sin; /*!< media socket address */
5026 struct sockaddr_in vsin; /*!< Video socket address */
5028 const char *codecs;
5029 struct hostent *hp; /*!< RTP Audio host IP */
5030 struct hostent *vhp = NULL; /*!< RTP video host IP */
5031 struct ast_hostent audiohp;
5032 struct ast_hostent videohp;
5033 int codec;
5034 int destiterator = 0;
5035 int iterator;
5036 int sendonly = -1;
5037 int numberofports;
5038 struct ast_rtp *newaudiortp, *newvideortp; /* Buffers for codec handling */
5039 int newjointcapability; /* Negotiated capability */
5040 int newpeercapability;
5041 int newnoncodeccapability;
5042 int numberofmediastreams = 0;
5043 int debug = sip_debug_test_pvt(p);
5045 int found_rtpmap_codecs[SDP_MAX_RTPMAP_CODECS];
5046 int last_rtpmap_codec=0;
5048 if (!p->rtp) {
5049 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
5050 return -1;
5053 /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
5054 newaudiortp = alloca(ast_rtp_alloc_size());
5055 memset(newaudiortp, 0, ast_rtp_alloc_size());
5056 ast_rtp_new_init(newaudiortp);
5057 ast_rtp_pt_clear(newaudiortp);
5059 newvideortp = alloca(ast_rtp_alloc_size());
5060 memset(newvideortp, 0, ast_rtp_alloc_size());
5061 ast_rtp_new_init(newvideortp);
5062 ast_rtp_pt_clear(newvideortp);
5064 /* Update our last rtprx when we receive an SDP, too */
5065 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
5068 /* Try to find first media stream */
5069 m = get_sdp(req, "m");
5070 destiterator = req->sdp_start;
5071 c = get_sdp_iterate(&destiterator, req, "c");
5072 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
5073 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
5074 return -1;
5077 /* Check for IPv4 address (not IPv6 yet) */
5078 if (sscanf(c, "IN IP4 %256s", host) != 1) {
5079 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
5080 return -1;
5083 /* XXX This could block for a long time, and block the main thread! XXX */
5084 hp = ast_gethostbyname(host, &audiohp);
5085 if (!hp) {
5086 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
5087 return -1;
5089 vhp = hp; /* Copy to video address as default too */
5091 iterator = req->sdp_start;
5092 ast_set_flag(&p->flags[0], SIP_NOVIDEO);
5095 /* Find media streams in this SDP offer */
5096 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
5097 int x;
5098 int audio = FALSE;
5100 numberofports = 1;
5101 if ((sscanf(m, "audio %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
5102 (sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
5103 audio = TRUE;
5104 numberofmediastreams++;
5105 /* Found audio stream in this media definition */
5106 portno = x;
5107 /* Scan through the RTP payload types specified in a "m=" line: */
5108 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
5109 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
5110 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
5111 return -1;
5113 if (debug)
5114 ast_verbose("Found RTP audio format %d\n", codec);
5115 ast_rtp_set_m_type(newaudiortp, codec);
5117 } else if ((sscanf(m, "video %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
5118 (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
5119 /* If it is not audio - is it video ? */
5120 ast_clear_flag(&p->flags[0], SIP_NOVIDEO);
5121 numberofmediastreams++;
5122 vportno = x;
5123 /* Scan through the RTP payload types specified in a "m=" line: */
5124 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
5125 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
5126 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
5127 return -1;
5129 if (debug)
5130 ast_verbose("Found RTP video format %d\n", codec);
5131 ast_rtp_set_m_type(newvideortp, codec);
5133 } else if (p->udptl && ( (sscanf(m, "image %d udptl t38%n", &x, &len) == 1) ||
5134 (sscanf(m, "image %d UDPTL t38%n", &x, &len) == 1) )) {
5135 if (debug)
5136 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
5137 udptlportno = x;
5138 numberofmediastreams++;
5140 if (p->owner && p->lastinvite) {
5141 p->t38.state = T38_PEER_REINVITE; /* T38 Offered in re-invite from remote party */
5142 if (option_debug > 1)
5143 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>" );
5144 } else {
5145 p->t38.state = T38_PEER_DIRECT; /* T38 Offered directly from peer in first invite */
5146 if (option_debug > 1)
5147 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
5149 } else
5150 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
5151 if (numberofports > 1)
5152 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
5155 /* Check for Media-description-level-address for audio */
5156 c = get_sdp_iterate(&destiterator, req, "c");
5157 if (!ast_strlen_zero(c)) {
5158 if (sscanf(c, "IN IP4 %256s", host) != 1) {
5159 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
5160 } else {
5161 /* XXX This could block for a long time, and block the main thread! XXX */
5162 if (audio) {
5163 if ( !(hp = ast_gethostbyname(host, &audiohp))) {
5164 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in secondary c= line, '%s'\n", c);
5165 return -2;
5167 } else if (!(vhp = ast_gethostbyname(host, &videohp))) {
5168 ast_log(LOG_WARNING, "Unable to lookup RTP video host in secondary c= line, '%s'\n", c);
5169 return -2;
5175 if (portno == -1 && vportno == -1 && udptlportno == -1)
5176 /* No acceptable offer found in SDP - we have no ports */
5177 /* Do not change RTP or VRTP if this is a re-invite */
5178 return -2;
5180 if (numberofmediastreams > 2)
5181 /* We have too many fax, audio and/or video media streams, fail this offer */
5182 return -3;
5184 /* RTP addresses and ports for audio and video */
5185 sin.sin_family = AF_INET;
5186 vsin.sin_family = AF_INET;
5187 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
5188 if (vhp)
5189 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
5191 /* Setup UDPTL port number */
5192 if (p->udptl) {
5193 if (udptlportno > 0) {
5194 sin.sin_port = htons(udptlportno);
5195 ast_udptl_set_peer(p->udptl, &sin);
5196 if (debug)
5197 ast_log(LOG_DEBUG,"Peer T.38 UDPTL is at port %s:%d\n",ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
5198 } else {
5199 ast_udptl_stop(p->udptl);
5200 if (debug)
5201 ast_log(LOG_DEBUG, "Peer doesn't provide T.38 UDPTL\n");
5206 if (p->rtp) {
5207 if (portno > 0) {
5208 sin.sin_port = htons(portno);
5209 ast_rtp_set_peer(p->rtp, &sin);
5210 if (debug)
5211 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
5212 } else {
5213 if (udptlportno > 0) {
5214 if (debug)
5215 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session. Callid %s\n", p->callid);
5216 } else {
5217 ast_rtp_stop(p->rtp);
5218 if (debug)
5219 ast_verbose("Peer doesn't provide audio. Callid %s\n", p->callid);
5223 /* Setup video port number */
5224 if (vportno != -1)
5225 vsin.sin_port = htons(vportno);
5227 /* Next, scan through each "a=rtpmap:" line, noting each
5228 * specified RTP payload type (with corresponding MIME subtype):
5230 /* XXX This needs to be done per media stream, since it's media stream specific */
5231 iterator = req->sdp_start;
5232 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
5233 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
5234 if (option_debug > 1) {
5235 int breakout = FALSE;
5237 /* If we're debugging, check for unsupported sdp options */
5238 if (!strncasecmp(a, "rtcp:", (size_t) 5)) {
5239 if (debug)
5240 ast_verbose("Got unsupported a:rtcp in SDP offer \n");
5241 breakout = TRUE;
5242 } else if (!strncasecmp(a, "fmtp:", (size_t) 5)) {
5243 /* Format parameters: Not supported */
5244 /* Note: This is used for codec parameters, like bitrate for
5245 G722 and video formats for H263 and H264
5246 See RFC2327 for an example */
5247 if (debug)
5248 ast_verbose("Got unsupported a:fmtp in SDP offer \n");
5249 breakout = TRUE;
5250 } else if (!strncasecmp(a, "framerate:", (size_t) 10)) {
5251 /* Video stuff: Not supported */
5252 if (debug)
5253 ast_verbose("Got unsupported a:framerate in SDP offer \n");
5254 breakout = TRUE;
5255 } else if (!strncasecmp(a, "maxprate:", (size_t) 9)) {
5256 /* Video stuff: Not supported */
5257 if (debug)
5258 ast_verbose("Got unsupported a:maxprate in SDP offer \n");
5259 breakout = TRUE;
5260 } else if (!strncasecmp(a, "crypto:", (size_t) 7)) {
5261 /* SRTP stuff, not yet supported */
5262 if (debug)
5263 ast_verbose("Got unsupported a:crypto in SDP offer \n");
5264 breakout = TRUE;
5266 if (breakout) /* We have a match, skip to next header */
5267 continue;
5269 if (!strcasecmp(a, "sendonly")) {
5270 if (sendonly == -1)
5271 sendonly = 1;
5272 continue;
5273 } else if (!strcasecmp(a, "inactive")) {
5274 if (sendonly == -1)
5275 sendonly = 2;
5276 continue;
5277 } else if (!strcasecmp(a, "sendrecv")) {
5278 if (sendonly == -1)
5279 sendonly = 0;
5280 continue;
5281 } else if (strlen(a) > 5 && !strncasecmp(a, "ptime", 5)) {
5282 char *tmp = strrchr(a, ':');
5283 long int framing = 0;
5284 if (tmp) {
5285 tmp++;
5286 framing = strtol(tmp, NULL, 10);
5287 if (framing == LONG_MIN || framing == LONG_MAX) {
5288 framing = 0;
5289 if (option_debug)
5290 ast_log(LOG_DEBUG, "Can't read framing from SDP: %s\n", a);
5293 if (framing && last_rtpmap_codec) {
5294 if (p->autoframing) {
5295 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
5296 int codec_n;
5297 int format = 0;
5298 for (codec_n = 0; codec_n < last_rtpmap_codec; codec_n++) {
5299 format = ast_rtp_codec_getformat(found_rtpmap_codecs[codec_n]);
5300 if (!format) /* non-codec or not found */
5301 continue;
5302 if (option_debug)
5303 ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
5304 ast_codec_pref_setsize(pref, format, framing);
5306 ast_rtp_codec_setpref(p->rtp, pref);
5309 memset(&found_rtpmap_codecs, 0, sizeof(found_rtpmap_codecs));
5310 last_rtpmap_codec = 0;
5311 continue;
5312 } else if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) == 2) {
5313 /* We have a rtpmap to handle */
5314 int found = FALSE;
5315 /* We should propably check if this is an audio or video codec
5316 so we know where to look */
5318 if (last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
5319 /* Note: should really look at the 'freq' and '#chans' params too */
5320 if(ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
5321 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0) != -1) {
5322 if (debug)
5323 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
5324 found_rtpmap_codecs[last_rtpmap_codec] = codec;
5325 last_rtpmap_codec++;
5326 found = TRUE;
5328 } else if (p->vrtp) {
5329 if(ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0) != -1) {
5330 if (debug)
5331 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
5332 found_rtpmap_codecs[last_rtpmap_codec] = codec;
5333 last_rtpmap_codec++;
5334 found = TRUE;
5337 } else {
5338 if (debug)
5339 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
5342 if (!found) {
5343 /* Remove this codec since it's an unknown media type for us */
5344 /* XXX This is buggy since the media line for audio and video can have the
5345 same numbers. We need to check as described above, but for testing this works... */
5346 ast_rtp_unset_m_type(newaudiortp, codec);
5347 ast_rtp_unset_m_type(newvideortp, codec);
5348 if (debug)
5349 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
5354 if (udptlportno != -1) {
5355 int found = 0, x;
5357 old = 0;
5359 /* Scan trough the a= lines for T38 attributes and set apropriate fileds */
5360 iterator = req->sdp_start;
5361 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
5362 if ((sscanf(a, "T38FaxMaxBuffer:%d", &x) == 1)) {
5363 found = 1;
5364 if (option_debug > 2)
5365 ast_log(LOG_DEBUG, "MaxBufferSize:%d\n",x);
5366 } else if ((sscanf(a, "T38MaxBitRate:%d", &x) == 1)) {
5367 found = 1;
5368 if (option_debug > 2)
5369 ast_log(LOG_DEBUG,"T38MaxBitRate: %d\n",x);
5370 switch (x) {
5371 case 14400:
5372 peert38capability |= T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5373 break;
5374 case 12000:
5375 peert38capability |= T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5376 break;
5377 case 9600:
5378 peert38capability |= T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5379 break;
5380 case 7200:
5381 peert38capability |= T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5382 break;
5383 case 4800:
5384 peert38capability |= T38FAX_RATE_4800 | T38FAX_RATE_2400;
5385 break;
5386 case 2400:
5387 peert38capability |= T38FAX_RATE_2400;
5388 break;
5390 } else if ((sscanf(a, "T38FaxVersion:%d", &x) == 1)) {
5391 found = 1;
5392 if (option_debug > 2)
5393 ast_log(LOG_DEBUG, "FaxVersion: %d\n",x);
5394 if (x == 0)
5395 peert38capability |= T38FAX_VERSION_0;
5396 else if (x == 1)
5397 peert38capability |= T38FAX_VERSION_1;
5398 } else if ((sscanf(a, "T38FaxMaxDatagram:%d", &x) == 1)) {
5399 found = 1;
5400 if (option_debug > 2)
5401 ast_log(LOG_DEBUG, "FaxMaxDatagram: %d\n",x);
5402 ast_udptl_set_far_max_datagram(p->udptl, x);
5403 ast_udptl_set_local_max_datagram(p->udptl, x);
5404 } else if ((sscanf(a, "T38FaxFillBitRemoval:%d", &x) == 1)) {
5405 found = 1;
5406 if (option_debug > 2)
5407 ast_log(LOG_DEBUG, "FillBitRemoval: %d\n",x);
5408 if (x == 1)
5409 peert38capability |= T38FAX_FILL_BIT_REMOVAL;
5410 } else if ((sscanf(a, "T38FaxTranscodingMMR:%d", &x) == 1)) {
5411 found = 1;
5412 if (option_debug > 2)
5413 ast_log(LOG_DEBUG, "Transcoding MMR: %d\n",x);
5414 if (x == 1)
5415 peert38capability |= T38FAX_TRANSCODING_MMR;
5417 if ((sscanf(a, "T38FaxTranscodingJBIG:%d", &x) == 1)) {
5418 found = 1;
5419 if (option_debug > 2)
5420 ast_log(LOG_DEBUG, "Transcoding JBIG: %d\n",x);
5421 if (x == 1)
5422 peert38capability |= T38FAX_TRANSCODING_JBIG;
5423 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
5424 found = 1;
5425 if (option_debug > 2)
5426 ast_log(LOG_DEBUG, "RateManagement: %s\n", s);
5427 if (!strcasecmp(s, "localTCF"))
5428 peert38capability |= T38FAX_RATE_MANAGEMENT_LOCAL_TCF;
5429 else if (!strcasecmp(s, "transferredTCF"))
5430 peert38capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
5431 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
5432 found = 1;
5433 if (option_debug > 2)
5434 ast_log(LOG_DEBUG, "UDP EC: %s\n", s);
5435 if (!strcasecmp(s, "t38UDPRedundancy")) {
5436 peert38capability |= T38FAX_UDP_EC_REDUNDANCY;
5437 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
5438 } else if (!strcasecmp(s, "t38UDPFEC")) {
5439 peert38capability |= T38FAX_UDP_EC_FEC;
5440 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
5441 } else {
5442 peert38capability |= T38FAX_UDP_EC_NONE;
5443 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
5447 if (found) { /* Some cisco equipment returns nothing beside c= and m= lines in 200 OK T38 SDP */
5448 p->t38.peercapability = peert38capability;
5449 p->t38.jointcapability = (peert38capability & 255); /* Put everything beside supported speeds settings */
5450 peert38capability &= (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400);
5451 p->t38.jointcapability |= (peert38capability & p->t38.capability); /* Put the lower of our's and peer's speed */
5453 if (debug)
5454 ast_log(LOG_DEBUG, "Our T38 capability = (%d), peer T38 capability (%d), joint T38 capability (%d)\n",
5455 p->t38.capability,
5456 p->t38.peercapability,
5457 p->t38.jointcapability);
5458 } else {
5459 p->t38.state = T38_DISABLED;
5460 if (option_debug > 2)
5461 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
5464 /* Now gather all of the codecs that we are asked for: */
5465 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
5466 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
5468 newjointcapability = p->capability & (peercapability | vpeercapability);
5469 newpeercapability = (peercapability | vpeercapability);
5470 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
5473 if (debug) {
5474 /* shame on whoever coded this.... */
5475 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE];
5477 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
5478 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
5479 ast_getformatname_multiple(s2, SIPBUFSIZE, newpeercapability),
5480 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
5481 ast_getformatname_multiple(s4, SIPBUFSIZE, newjointcapability));
5483 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
5484 ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
5485 ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
5486 ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
5488 if (!newjointcapability) {
5489 /* If T.38 was not negotiated either, totally bail out... */
5490 if (!p->t38.jointcapability || !udptlportno) {
5491 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
5492 /* Do NOT Change current setting */
5493 return -1;
5494 } else {
5495 if (option_debug > 2)
5496 ast_log(LOG_DEBUG, "Have T.38 but no audio codecs, accepting offer anyway\n");
5497 return 0;
5501 /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
5502 they are acceptable */
5503 p->jointcapability = newjointcapability; /* Our joint codec profile for this call */
5504 p->peercapability = newpeercapability; /* The other sides capability in latest offer */
5505 p->jointnoncodeccapability = newnoncodeccapability; /* DTMF capabilities */
5507 ast_rtp_pt_copy(p->rtp, newaudiortp);
5508 if (p->vrtp)
5509 ast_rtp_pt_copy(p->vrtp, newvideortp);
5511 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
5512 ast_clear_flag(&p->flags[0], SIP_DTMF);
5513 if (newnoncodeccapability & AST_RTP_DTMF) {
5514 /* XXX Would it be reasonable to drop the DSP at this point? XXX */
5515 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
5516 /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
5517 ast_rtp_setdtmf(p->rtp, 1);
5518 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
5519 } else {
5520 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
5524 /* Setup audio port number */
5525 if (p->rtp && sin.sin_port) {
5526 ast_rtp_set_peer(p->rtp, &sin);
5527 if (debug)
5528 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
5531 /* Setup video port number */
5532 if (p->vrtp && vsin.sin_port) {
5533 ast_rtp_set_peer(p->vrtp, &vsin);
5534 if (debug)
5535 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
5538 /* Ok, we're going with this offer */
5539 if (option_debug > 1) {
5540 char buf[SIPBUFSIZE];
5541 ast_log(LOG_DEBUG, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
5544 if (!p->owner) /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
5545 return 0;
5547 if (option_debug > 3)
5548 ast_log(LOG_DEBUG, "We have an owner, now see if we need to change this call\n");
5550 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
5551 if (debug) {
5552 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
5553 ast_log(LOG_DEBUG, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
5554 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
5555 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
5557 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability);
5558 ast_set_read_format(p->owner, p->owner->readformat);
5559 ast_set_write_format(p->owner, p->owner->writeformat);
5562 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
5563 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
5564 /* Activate a re-invite */
5565 ast_queue_frame(p->owner, &ast_null_frame);
5566 } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
5567 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
5568 S_OR(p->mohsuggest, NULL),
5569 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
5570 if (sendonly)
5571 ast_rtp_stop(p->rtp);
5572 /* RTCP needs to go ahead, even if we're on hold!!! */
5573 /* Activate a re-invite */
5574 ast_queue_frame(p->owner, &ast_null_frame);
5577 /* Manager Hold and Unhold events must be generated, if necessary */
5578 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1))
5579 change_hold_state(p, req, FALSE, sendonly);
5580 else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1))
5581 change_hold_state(p, req, TRUE, sendonly);
5582 return 0;
5586 /*! \brief Add header to SIP message */
5587 static int add_header(struct sip_request *req, const char *var, const char *value)
5589 int maxlen = sizeof(req->data) - 4 - req->len; /* 4 bytes are for two \r\n ? */
5591 if (req->headers == SIP_MAX_HEADERS) {
5592 ast_log(LOG_WARNING, "Out of SIP header space\n");
5593 return -1;
5596 if (req->lines) {
5597 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
5598 return -1;
5601 if (maxlen <= 0) {
5602 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
5603 return -1;
5606 req->header[req->headers] = req->data + req->len;
5608 if (compactheaders)
5609 var = find_alias(var, var);
5611 snprintf(req->header[req->headers], maxlen, "%s: %s\r\n", var, value);
5612 req->len += strlen(req->header[req->headers]);
5613 req->headers++;
5615 return 0;
5618 /*! \brief Add 'Content-Length' header to SIP message */
5619 static int add_header_contentLength(struct sip_request *req, int len)
5621 char clen[10];
5623 snprintf(clen, sizeof(clen), "%d", len);
5624 return add_header(req, "Content-Length", clen);
5627 /*! \brief Add content (not header) to SIP message */
5628 static int add_line(struct sip_request *req, const char *line)
5630 if (req->lines == SIP_MAX_LINES) {
5631 ast_log(LOG_WARNING, "Out of SIP line space\n");
5632 return -1;
5634 if (!req->lines) {
5635 /* Add extra empty return */
5636 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
5637 req->len += strlen(req->data + req->len);
5639 if (req->len >= sizeof(req->data) - 4) {
5640 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
5641 return -1;
5643 req->line[req->lines] = req->data + req->len;
5644 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
5645 req->len += strlen(req->line[req->lines]);
5646 req->lines++;
5647 return 0;
5650 /*! \brief Copy one header field from one request to another */
5651 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
5653 const char *tmp = get_header(orig, field);
5655 if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
5656 return add_header(req, field, tmp);
5657 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
5658 return -1;
5661 /*! \brief Copy all headers from one request to another */
5662 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
5664 int start = 0;
5665 int copied = 0;
5666 for (;;) {
5667 const char *tmp = __get_header(orig, field, &start);
5669 if (ast_strlen_zero(tmp))
5670 break;
5671 /* Add what we're responding to */
5672 add_header(req, field, tmp);
5673 copied++;
5675 return copied ? 0 : -1;
5678 /*! \brief Copy SIP VIA Headers from the request to the response
5679 \note If the client indicates that it wishes to know the port we received from,
5680 it adds ;rport without an argument to the topmost via header. We need to
5681 add the port number (from our point of view) to that parameter.
5682 We always add ;received=<ip address> to the topmost via header.
5683 Received: RFC 3261, rport RFC 3581 */
5684 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
5686 int copied = 0;
5687 int start = 0;
5689 for (;;) {
5690 char new[512];
5691 const char *oh = __get_header(orig, field, &start);
5693 if (ast_strlen_zero(oh))
5694 break;
5696 if (!copied) { /* Only check for empty rport in topmost via header */
5697 char leftmost[512], *others, *rport;
5699 /* Only work on leftmost value */
5700 ast_copy_string(leftmost, oh, sizeof(leftmost));
5701 others = strchr(leftmost, ',');
5702 if (others)
5703 *others++ = '\0';
5705 /* Find ;rport; (empty request) */
5706 rport = strstr(leftmost, ";rport");
5707 if (rport && *(rport+6) == '=')
5708 rport = NULL; /* We already have a parameter to rport */
5710 /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting) */
5711 if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
5712 /* We need to add received port - rport */
5713 char *end;
5715 rport = strstr(leftmost, ";rport");
5717 if (rport) {
5718 end = strchr(rport + 1, ';');
5719 if (end)
5720 memmove(rport, end, strlen(end) + 1);
5721 else
5722 *rport = '\0';
5725 /* Add rport to first VIA header if requested */
5726 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
5727 leftmost, ast_inet_ntoa(p->recv.sin_addr),
5728 ntohs(p->recv.sin_port),
5729 others ? "," : "", others ? others : "");
5730 } else {
5731 /* We should *always* add a received to the topmost via */
5732 snprintf(new, sizeof(new), "%s;received=%s%s%s",
5733 leftmost, ast_inet_ntoa(p->recv.sin_addr),
5734 others ? "," : "", others ? others : "");
5736 oh = new; /* the header to copy */
5737 } /* else add the following via headers untouched */
5738 add_header(req, field, oh);
5739 copied++;
5741 if (!copied) {
5742 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
5743 return -1;
5745 return 0;
5748 /*! \brief Add route header into request per learned route */
5749 static void add_route(struct sip_request *req, struct sip_route *route)
5751 char r[SIPBUFSIZE*2], *p;
5752 int n, rem = sizeof(r);
5754 if (!route)
5755 return;
5757 p = r;
5758 for (;route ; route = route->next) {
5759 n = strlen(route->hop);
5760 if (rem < n+3) /* we need room for ",<route>" */
5761 break;
5762 if (p != r) { /* add a separator after fist route */
5763 *p++ = ',';
5764 --rem;
5766 *p++ = '<';
5767 ast_copy_string(p, route->hop, rem); /* cannot fail */
5768 p += n;
5769 *p++ = '>';
5770 rem -= (n+2);
5772 *p = '\0';
5773 add_header(req, "Route", r);
5776 /*! \brief Set destination from SIP URI */
5777 static void set_destination(struct sip_pvt *p, char *uri)
5779 char *h, *maddr, hostname[256];
5780 int port, hn;
5781 struct hostent *hp;
5782 struct ast_hostent ahp;
5783 int debug=sip_debug_test_pvt(p);
5785 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
5786 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
5788 if (debug)
5789 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
5791 /* Find and parse hostname */
5792 h = strchr(uri, '@');
5793 if (h)
5794 ++h;
5795 else {
5796 h = uri;
5797 if (strncasecmp(h, "sip:", 4) == 0)
5798 h += 4;
5799 else if (strncasecmp(h, "sips:", 5) == 0)
5800 h += 5;
5802 hn = strcspn(h, ":;>") + 1;
5803 if (hn > sizeof(hostname))
5804 hn = sizeof(hostname);
5805 ast_copy_string(hostname, h, hn);
5806 /* XXX bug here if string has been trimmed to sizeof(hostname) */
5807 h += hn - 1;
5809 /* Is "port" present? if not default to STANDARD_SIP_PORT */
5810 if (*h == ':') {
5811 /* Parse port */
5812 ++h;
5813 port = strtol(h, &h, 10);
5815 else
5816 port = STANDARD_SIP_PORT;
5818 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
5819 maddr = strstr(h, "maddr=");
5820 if (maddr) {
5821 maddr += 6;
5822 hn = strspn(maddr, "0123456789.") + 1;
5823 if (hn > sizeof(hostname))
5824 hn = sizeof(hostname);
5825 ast_copy_string(hostname, maddr, hn);
5828 hp = ast_gethostbyname(hostname, &ahp);
5829 if (hp == NULL) {
5830 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
5831 return;
5833 p->sa.sin_family = AF_INET;
5834 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
5835 p->sa.sin_port = htons(port);
5836 if (debug)
5837 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
5840 /*! \brief Initialize SIP response, based on SIP request */
5841 static int init_resp(struct sip_request *resp, const char *msg)
5843 /* Initialize a response */
5844 memset(resp, 0, sizeof(*resp));
5845 resp->method = SIP_RESPONSE;
5846 resp->header[0] = resp->data;
5847 snprintf(resp->header[0], sizeof(resp->data), "SIP/2.0 %s\r\n", msg);
5848 resp->len = strlen(resp->header[0]);
5849 resp->headers++;
5850 return 0;
5853 /*! \brief Initialize SIP request */
5854 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
5856 /* Initialize a request */
5857 memset(req, 0, sizeof(*req));
5858 req->method = sipmethod;
5859 req->header[0] = req->data;
5860 snprintf(req->header[0], sizeof(req->data), "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
5861 req->len = strlen(req->header[0]);
5862 req->headers++;
5863 return 0;
5867 /*! \brief Prepare SIP response packet */
5868 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
5870 char newto[256];
5871 const char *ot;
5873 init_resp(resp, msg);
5874 copy_via_headers(p, resp, req, "Via");
5875 if (msg[0] == '1' || msg[0] == '2')
5876 copy_all_header(resp, req, "Record-Route");
5877 copy_header(resp, req, "From");
5878 ot = get_header(req, "To");
5879 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
5880 /* Add the proper tag if we don't have it already. If they have specified
5881 their tag, use it. Otherwise, use our own tag */
5882 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
5883 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
5884 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
5885 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
5886 else
5887 ast_copy_string(newto, ot, sizeof(newto));
5888 ot = newto;
5890 add_header(resp, "To", ot);
5891 copy_header(resp, req, "Call-ID");
5892 copy_header(resp, req, "CSeq");
5893 if (!ast_strlen_zero(global_useragent))
5894 add_header(resp, "User-Agent", global_useragent);
5895 add_header(resp, "Allow", ALLOWED_METHODS);
5896 add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
5897 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
5898 /* For registration responses, we also need expiry and
5899 contact info */
5900 char tmp[256];
5902 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
5903 add_header(resp, "Expires", tmp);
5904 if (p->expiry) { /* Only add contact if we have an expiry time */
5905 char contact[SIPBUFSIZE];
5906 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
5907 add_header(resp, "Contact", contact); /* Not when we unregister */
5909 } else if (msg[0] != '4' && !ast_strlen_zero(p->our_contact)) {
5910 add_header(resp, "Contact", p->our_contact);
5912 return 0;
5915 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
5916 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
5918 struct sip_request *orig = &p->initreq;
5919 char stripped[80];
5920 char tmp[80];
5921 char newto[256];
5922 const char *c;
5923 const char *ot, *of;
5924 int is_strict = FALSE; /*!< Strict routing flag */
5926 memset(req, 0, sizeof(struct sip_request));
5928 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
5930 if (!seqno) {
5931 p->ocseq++;
5932 seqno = p->ocseq;
5935 if (newbranch) {
5936 p->branch ^= ast_random();
5937 build_via(p);
5940 /* Check for strict or loose router */
5941 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop,";lr") == NULL) {
5942 is_strict = TRUE;
5943 if (sipdebug)
5944 ast_log(LOG_DEBUG, "Strict routing enforced for session %s\n", p->callid);
5947 if (sipmethod == SIP_CANCEL)
5948 c = p->initreq.rlPart2; /* Use original URI */
5949 else if (sipmethod == SIP_ACK) {
5950 /* Use URI from Contact: in 200 OK (if INVITE)
5951 (we only have the contacturi on INVITEs) */
5952 if (!ast_strlen_zero(p->okcontacturi))
5953 c = is_strict ? p->route->hop : p->okcontacturi;
5954 else
5955 c = p->initreq.rlPart2;
5956 } else if (!ast_strlen_zero(p->okcontacturi))
5957 c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
5958 else if (!ast_strlen_zero(p->uri))
5959 c = p->uri;
5960 else {
5961 char *n;
5962 /* We have no URI, use To: or From: header as URI (depending on direction) */
5963 ast_copy_string(stripped, get_header(orig, (ast_test_flag(&p->flags[0], SIP_OUTGOING)) ? "To" : "From"),
5964 sizeof(stripped));
5965 n = get_in_brackets(stripped);
5966 c = strsep(&n, ";"); /* trim ; and beyond */
5968 init_req(req, sipmethod, c);
5970 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
5972 add_header(req, "Via", p->via);
5973 if (p->route) {
5974 set_destination(p, p->route->hop);
5975 add_route(req, is_strict ? p->route->next : p->route);
5978 ot = get_header(orig, "To");
5979 of = get_header(orig, "From");
5981 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
5982 as our original request, including tag (or presumably lack thereof) */
5983 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
5984 /* Add the proper tag if we don't have it already. If they have specified
5985 their tag, use it. Otherwise, use our own tag */
5986 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_strlen_zero(p->theirtag))
5987 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
5988 else if (!ast_test_flag(&p->flags[0], SIP_OUTGOING))
5989 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
5990 else
5991 snprintf(newto, sizeof(newto), "%s", ot);
5992 ot = newto;
5995 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
5996 add_header(req, "From", of);
5997 add_header(req, "To", ot);
5998 } else {
5999 add_header(req, "From", ot);
6000 add_header(req, "To", of);
6002 /* Do not add Contact for MESSAGE, BYE and Cancel requests */
6003 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
6004 add_header(req, "Contact", p->our_contact);
6006 copy_header(req, orig, "Call-ID");
6007 add_header(req, "CSeq", tmp);
6009 if (!ast_strlen_zero(global_useragent))
6010 add_header(req, "User-Agent", global_useragent);
6011 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
6013 if (!ast_strlen_zero(p->rpid))
6014 add_header(req, "Remote-Party-ID", p->rpid);
6016 return 0;
6019 /*! \brief Base transmit response function */
6020 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
6022 struct sip_request resp;
6023 int seqno = 0;
6025 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
6026 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
6027 return -1;
6029 respprep(&resp, p, msg, req);
6030 add_header_contentLength(&resp, 0);
6031 /* If we are cancelling an incoming invite for some reason, add information
6032 about the reason why we are doing this in clear text */
6033 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
6034 char buf[10];
6036 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
6037 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
6038 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
6040 return send_response(p, &resp, reliable, seqno);
6043 static void temp_pvt_cleanup(void *data)
6045 struct sip_pvt *p = data;
6047 ast_string_field_free_memory(p);
6049 free(data);
6052 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
6053 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)
6055 struct sip_pvt *p = NULL;
6057 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
6058 ast_log(LOG_NOTICE, "Failed to get temporary pvt\n");
6059 return -1;
6062 /* if the structure was just allocated, initialize it */
6063 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
6064 ast_set_flag(&p->flags[0], SIP_NO_HISTORY);
6065 if (ast_string_field_init(p, 512))
6066 return -1;
6069 /* Initialize the bare minimum */
6070 p->method = intended_method;
6072 if (sin) {
6073 p->sa = *sin;
6074 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
6075 p->ourip = __ourip;
6076 } else
6077 p->ourip = __ourip;
6079 p->branch = ast_random();
6080 make_our_tag(p->tag, sizeof(p->tag));
6081 p->ocseq = INITIAL_CSEQ;
6083 if (useglobal_nat && sin) {
6084 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
6085 p->recv = *sin;
6086 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
6088 check_via(p, req);
6090 ast_string_field_set(p, fromdomain, default_fromdomain);
6091 build_via(p);
6092 ast_string_field_set(p, callid, callid);
6094 /* Use this temporary pvt structure to send the message */
6095 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
6097 /* Free the string fields, but not the pool space */
6098 ast_string_field_reset_all(p);
6100 return 0;
6103 /*! \brief Transmit response, no retransmits */
6104 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
6106 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
6109 /*! \brief Transmit response, no retransmits */
6110 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
6112 struct sip_request resp;
6113 respprep(&resp, p, msg, req);
6114 append_date(&resp);
6115 add_header(&resp, "Unsupported", unsupported);
6116 add_header_contentLength(&resp, 0);
6117 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
6120 /*! \brief Transmit response, Make sure you get an ACK
6121 This is only used for responses to INVITEs, where we need to make sure we get an ACK
6123 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
6125 return __transmit_response(p, msg, req, XMIT_CRITICAL);
6128 /*! \brief Append date to SIP message */
6129 static void append_date(struct sip_request *req)
6131 char tmpdat[256];
6132 struct tm tm;
6133 time_t t = time(NULL);
6135 gmtime_r(&t, &tm);
6136 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
6137 add_header(req, "Date", tmpdat);
6140 /*! \brief Append date and content length before transmitting response */
6141 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
6143 struct sip_request resp;
6144 respprep(&resp, p, msg, req);
6145 append_date(&resp);
6146 add_header_contentLength(&resp, 0);
6147 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
6150 /*! \brief Append Accept header, content length before transmitting response */
6151 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
6153 struct sip_request resp;
6154 respprep(&resp, p, msg, req);
6155 add_header(&resp, "Accept", "application/sdp");
6156 add_header_contentLength(&resp, 0);
6157 return send_response(p, &resp, reliable, 0);
6160 /*! \brief Respond with authorization request */
6161 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)
6163 struct sip_request resp;
6164 char tmp[512];
6165 int seqno = 0;
6167 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
6168 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
6169 return -1;
6171 /* Stale means that they sent us correct authentication, but
6172 based it on an old challenge (nonce) */
6173 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
6174 respprep(&resp, p, msg, req);
6175 add_header(&resp, header, tmp);
6176 add_header_contentLength(&resp, 0);
6177 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
6178 return send_response(p, &resp, reliable, seqno);
6181 /*! \brief Add text body to SIP message */
6182 static int add_text(struct sip_request *req, const char *text)
6184 /* XXX Convert \n's to \r\n's XXX */
6185 add_header(req, "Content-Type", "text/plain");
6186 add_header_contentLength(req, strlen(text));
6187 add_line(req, text);
6188 return 0;
6191 /*! \brief Add DTMF INFO tone to sip message */
6192 /* Always adds default duration 250 ms, regardless of what came in over the line */
6193 static int add_digit(struct sip_request *req, char digit, unsigned int duration)
6195 char tmp[256];
6197 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
6198 add_header(req, "Content-Type", "application/dtmf-relay");
6199 add_header_contentLength(req, strlen(tmp));
6200 add_line(req, tmp);
6201 return 0;
6204 /*! \brief add XML encoded media control with update
6205 \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
6206 static int add_vidupdate(struct sip_request *req)
6208 const char *xml_is_a_huge_waste_of_space =
6209 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
6210 " <media_control>\r\n"
6211 " <vc_primitive>\r\n"
6212 " <to_encoder>\r\n"
6213 " <picture_fast_update>\r\n"
6214 " </picture_fast_update>\r\n"
6215 " </to_encoder>\r\n"
6216 " </vc_primitive>\r\n"
6217 " </media_control>\r\n";
6218 add_header(req, "Content-Type", "application/media_control+xml");
6219 add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
6220 add_line(req, xml_is_a_huge_waste_of_space);
6221 return 0;
6224 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
6225 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
6226 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
6227 int debug, int *min_packet_size)
6229 int rtp_code;
6230 struct ast_format_list fmt;
6233 if (debug)
6234 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
6235 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
6236 return;
6238 if (p->rtp) {
6239 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
6240 fmt = ast_codec_pref_getsize(pref, codec);
6241 } 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 */
6242 return;
6243 ast_build_string(m_buf, m_size, " %d", rtp_code);
6244 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
6245 ast_rtp_lookup_mime_subtype(1, codec,
6246 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
6247 sample_rate);
6248 if (codec == AST_FORMAT_G729A) {
6249 /* Indicate that we don't support VAD (G.729 annex B) */
6250 ast_build_string(a_buf, a_size, "a=fmtp:%d annexb=no\r\n", rtp_code);
6251 } else if (codec == AST_FORMAT_G723_1) {
6252 /* Indicate that we don't support VAD (G.723.1 annex A) */
6253 ast_build_string(a_buf, a_size, "a=fmtp:%d annexa=no\r\n", rtp_code);
6254 } else if (codec == AST_FORMAT_ILBC) {
6255 /* Add information about us using only 20/30 ms packetization */
6256 ast_build_string(a_buf, a_size, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
6259 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
6260 *min_packet_size = fmt.cur_ms;
6262 /* Our first codec packetization processed cannot be less than zero */
6263 if ((*min_packet_size) == 0 && fmt.cur_ms)
6264 *min_packet_size = fmt.cur_ms;
6267 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
6268 static int t38_get_rate(int t38cap)
6270 int maxrate = (t38cap & (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400));
6272 if (maxrate & T38FAX_RATE_14400) {
6273 if (option_debug > 1)
6274 ast_log(LOG_DEBUG, "T38MaxFaxRate 14400 found\n");
6275 return 14400;
6276 } else if (maxrate & T38FAX_RATE_12000) {
6277 if (option_debug > 1)
6278 ast_log(LOG_DEBUG, "T38MaxFaxRate 12000 found\n");
6279 return 12000;
6280 } else if (maxrate & T38FAX_RATE_9600) {
6281 if (option_debug > 1)
6282 ast_log(LOG_DEBUG, "T38MaxFaxRate 9600 found\n");
6283 return 9600;
6284 } else if (maxrate & T38FAX_RATE_7200) {
6285 if (option_debug > 1)
6286 ast_log(LOG_DEBUG, "T38MaxFaxRate 7200 found\n");
6287 return 7200;
6288 } else if (maxrate & T38FAX_RATE_4800) {
6289 if (option_debug > 1)
6290 ast_log(LOG_DEBUG, "T38MaxFaxRate 4800 found\n");
6291 return 4800;
6292 } else if (maxrate & T38FAX_RATE_2400) {
6293 if (option_debug > 1)
6294 ast_log(LOG_DEBUG, "T38MaxFaxRate 2400 found\n");
6295 return 2400;
6296 } else {
6297 if (option_debug > 1)
6298 ast_log(LOG_DEBUG, "Strange, T38MaxFaxRate NOT found in peers T38 SDP.\n");
6299 return 0;
6303 /*! \brief Add T.38 Session Description Protocol message */
6304 static int add_t38_sdp(struct sip_request *resp, struct sip_pvt *p)
6306 int len = 0;
6307 int x = 0;
6308 struct sockaddr_in udptlsin;
6309 char v[256] = "";
6310 char s[256] = "";
6311 char o[256] = "";
6312 char c[256] = "";
6313 char t[256] = "";
6314 char m_modem[256];
6315 char a_modem[1024];
6316 char *m_modem_next = m_modem;
6317 size_t m_modem_left = sizeof(m_modem);
6318 char *a_modem_next = a_modem;
6319 size_t a_modem_left = sizeof(a_modem);
6320 struct sockaddr_in udptldest = { 0, };
6321 int debug;
6323 debug = sip_debug_test_pvt(p);
6324 len = 0;
6325 if (!p->udptl) {
6326 ast_log(LOG_WARNING, "No way to add SDP without an UDPTL structure\n");
6327 return -1;
6330 if (!p->sessionid) {
6331 p->sessionid = getpid();
6332 p->sessionversion = p->sessionid;
6333 } else
6334 p->sessionversion++;
6336 /* Our T.38 end is */
6337 ast_udptl_get_us(p->udptl, &udptlsin);
6339 /* Determine T.38 UDPTL destination */
6340 if (p->udptlredirip.sin_addr.s_addr) {
6341 udptldest.sin_port = p->udptlredirip.sin_port;
6342 udptldest.sin_addr = p->udptlredirip.sin_addr;
6343 } else {
6344 udptldest.sin_addr = p->ourip;
6345 udptldest.sin_port = udptlsin.sin_port;
6348 if (debug)
6349 ast_log(LOG_DEBUG, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(udptlsin.sin_port));
6351 /* We break with the "recommendation" and send our IP, in order that our
6352 peer doesn't have to ast_gethostbyname() us */
6354 if (debug) {
6355 ast_log(LOG_DEBUG, "Our T38 capability (%d), peer T38 capability (%d), joint capability (%d)\n",
6356 p->t38.capability,
6357 p->t38.peercapability,
6358 p->t38.jointcapability);
6360 snprintf(v, sizeof(v), "v=0\r\n");
6361 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(udptldest.sin_addr));
6362 snprintf(s, sizeof(s), "s=session\r\n");
6363 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(udptldest.sin_addr));
6364 snprintf(t, sizeof(t), "t=0 0\r\n");
6365 ast_build_string(&m_modem_next, &m_modem_left, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
6367 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_0)
6368 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:0\r\n");
6369 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_1)
6370 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:1\r\n");
6371 if ((x = t38_get_rate(p->t38.jointcapability)))
6372 ast_build_string(&a_modem_next, &a_modem_left, "a=T38MaxBitRate:%d\r\n",x);
6373 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxFillBitRemoval:%d\r\n", (p->t38.jointcapability & T38FAX_FILL_BIT_REMOVAL) ? 1 : 0);
6374 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingMMR:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_MMR) ? 1 : 0);
6375 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingJBIG:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_JBIG) ? 1 : 0);
6376 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxRateManagement:%s\r\n", (p->t38.jointcapability & T38FAX_RATE_MANAGEMENT_LOCAL_TCF) ? "localTCF" : "transferredTCF");
6377 x = ast_udptl_get_local_max_datagram(p->udptl);
6378 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxBuffer:%d\r\n",x);
6379 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxDatagram:%d\r\n",x);
6380 if (p->t38.jointcapability != T38FAX_UDP_EC_NONE)
6381 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxUdpEC:%s\r\n", (p->t38.jointcapability & T38FAX_UDP_EC_REDUNDANCY) ? "t38UDPRedundancy" : "t38UDPFEC");
6382 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m_modem) + strlen(a_modem);
6383 add_header(resp, "Content-Type", "application/sdp");
6384 add_header_contentLength(resp, len);
6385 add_line(resp, v);
6386 add_line(resp, o);
6387 add_line(resp, s);
6388 add_line(resp, c);
6389 add_line(resp, t);
6390 add_line(resp, m_modem);
6391 add_line(resp, a_modem);
6393 /* Update lastrtprx when we send our SDP */
6394 p->lastrtprx = p->lastrtptx = time(NULL);
6396 return 0;
6400 /*! \brief Add RFC 2833 DTMF offer to SDP */
6401 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
6402 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
6403 int debug)
6405 int rtp_code;
6407 if (debug)
6408 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
6409 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
6410 return;
6412 ast_build_string(m_buf, m_size, " %d", rtp_code);
6413 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
6414 ast_rtp_lookup_mime_subtype(0, format, 0),
6415 sample_rate);
6416 if (format == AST_RTP_DTMF)
6417 /* Indicate we support DTMF and FLASH... */
6418 ast_build_string(a_buf, a_size, "a=fmtp:%d 0-16\r\n", rtp_code);
6422 * \note G.722 actually is supposed to specified as 8 kHz, even though it is
6423 * really 16 kHz. Update this macro for other formats as they are added in
6424 * the future.
6426 #define SDP_SAMPLE_RATE(x) 8000
6428 /*! \brief Add Session Description Protocol message */
6429 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p)
6431 int len = 0;
6432 int alreadysent = 0;
6434 struct sockaddr_in sin;
6435 struct sockaddr_in vsin;
6436 struct sockaddr_in dest;
6437 struct sockaddr_in vdest = { 0, };
6439 /* SDP fields */
6440 char *version = "v=0\r\n"; /* Protocol version */
6441 char *subject = "s=session\r\n"; /* Subject of the session */
6442 char owner[256]; /* Session owner/creator */
6443 char connection[256]; /* Connection data */
6444 char *stime = "t=0 0\r\n"; /* Time the session is active */
6445 char bandwidth[256] = ""; /* Max bitrate */
6446 char *hold;
6447 char m_audio[256]; /* Media declaration line for audio */
6448 char m_video[256]; /* Media declaration line for video */
6449 char a_audio[1024]; /* Attributes for audio */
6450 char a_video[1024]; /* Attributes for video */
6451 char *m_audio_next = m_audio;
6452 char *m_video_next = m_video;
6453 size_t m_audio_left = sizeof(m_audio);
6454 size_t m_video_left = sizeof(m_video);
6455 char *a_audio_next = a_audio;
6456 char *a_video_next = a_video;
6457 size_t a_audio_left = sizeof(a_audio);
6458 size_t a_video_left = sizeof(a_video);
6460 int x;
6461 int capability;
6462 int needvideo = FALSE;
6463 int debug = sip_debug_test_pvt(p);
6464 int min_audio_packet_size = 0;
6465 int min_video_packet_size = 0;
6467 m_video[0] = '\0'; /* Reset the video media string if it's not needed */
6469 if (!p->rtp) {
6470 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
6471 return AST_FAILURE;
6474 /* Set RTP Session ID and version */
6475 if (!p->sessionid) {
6476 p->sessionid = getpid();
6477 p->sessionversion = p->sessionid;
6478 } else
6479 p->sessionversion++;
6481 /* Get our addresses */
6482 ast_rtp_get_us(p->rtp, &sin);
6483 if (p->vrtp)
6484 ast_rtp_get_us(p->vrtp, &vsin);
6486 /* Is this a re-invite to move the media out, then use the original offer from caller */
6487 if (p->redirip.sin_addr.s_addr) {
6488 dest.sin_port = p->redirip.sin_port;
6489 dest.sin_addr = p->redirip.sin_addr;
6490 } else {
6491 dest.sin_addr = p->ourip;
6492 dest.sin_port = sin.sin_port;
6495 capability = p->jointcapability;
6498 if (option_debug > 1) {
6499 char codecbuf[SIPBUFSIZE];
6500 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");
6501 ast_log(LOG_DEBUG, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
6504 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
6505 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_RTP)) {
6506 ast_build_string(&m_audio_next, &m_audio_left, " %d", 191);
6507 ast_build_string(&a_audio_next, &a_audio_left, "a=rtpmap:%d %s/%d\r\n", 191, "t38", 8000);
6509 #endif
6511 /* Check if we need video in this call */
6512 if ((capability & AST_FORMAT_VIDEO_MASK) && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
6513 if (p->vrtp) {
6514 needvideo = TRUE;
6515 if (option_debug > 1)
6516 ast_log(LOG_DEBUG, "This call needs video offers!\n");
6517 } else if (option_debug > 1)
6518 ast_log(LOG_DEBUG, "This call needs video offers, but there's no video support enabled!\n");
6522 /* Ok, we need video. Let's add what we need for video and set codecs.
6523 Video is handled differently than audio since we can not transcode. */
6524 if (needvideo) {
6525 /* Determine video destination */
6526 if (p->vredirip.sin_addr.s_addr) {
6527 vdest.sin_addr = p->vredirip.sin_addr;
6528 vdest.sin_port = p->vredirip.sin_port;
6529 } else {
6530 vdest.sin_addr = p->ourip;
6531 vdest.sin_port = vsin.sin_port;
6533 ast_build_string(&m_video_next, &m_video_left, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
6535 /* Build max bitrate string */
6536 if (p->maxcallbitrate)
6537 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
6538 if (debug)
6539 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(vsin.sin_port));
6542 if (debug)
6543 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(sin.sin_port));
6545 /* Start building generic SDP headers */
6547 /* We break with the "recommendation" and send our IP, in order that our
6548 peer doesn't have to ast_gethostbyname() us */
6550 snprintf(owner, sizeof(owner), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
6551 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
6552 ast_build_string(&m_audio_next, &m_audio_left, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
6554 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
6555 hold = "a=recvonly\r\n";
6556 else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
6557 hold = "a=inactive\r\n";
6558 else
6559 hold = "a=sendrecv\r\n";
6561 /* Now, start adding audio codecs. These are added in this order:
6562 - First what was requested by the calling channel
6563 - Then preferences in order from sip.conf device config for this peer/user
6564 - Then other codecs in capabilities, including video
6567 /* Prefer the audio codec we were requested to use, first, no matter what
6568 Note that p->prefcodec can include video codecs, so mask them out
6570 if (capability & p->prefcodec) {
6571 int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
6573 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
6574 &m_audio_next, &m_audio_left,
6575 &a_audio_next, &a_audio_left,
6576 debug, &min_audio_packet_size);
6577 alreadysent |= codec;
6580 /* Start by sending our preferred audio codecs */
6581 for (x = 0; x < 32; x++) {
6582 int codec;
6584 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
6585 break;
6587 if (!(capability & codec))
6588 continue;
6590 if (alreadysent & codec)
6591 continue;
6593 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
6594 &m_audio_next, &m_audio_left,
6595 &a_audio_next, &a_audio_left,
6596 debug, &min_audio_packet_size);
6597 alreadysent |= codec;
6600 /* Now send any other common audio and video codecs, and non-codec formats: */
6601 for (x = 1; x <= (needvideo ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
6602 if (!(capability & x)) /* Codec not requested */
6603 continue;
6605 if (alreadysent & x) /* Already added to SDP */
6606 continue;
6608 if (x <= AST_FORMAT_MAX_AUDIO)
6609 add_codec_to_sdp(p, x, SDP_SAMPLE_RATE(x),
6610 &m_audio_next, &m_audio_left,
6611 &a_audio_next, &a_audio_left,
6612 debug, &min_audio_packet_size);
6613 else
6614 add_codec_to_sdp(p, x, 90000,
6615 &m_video_next, &m_video_left,
6616 &a_video_next, &a_video_left,
6617 debug, &min_video_packet_size);
6620 /* Now add DTMF RFC2833 telephony-event as a codec */
6621 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
6622 if (!(p->jointnoncodeccapability & x))
6623 continue;
6625 add_noncodec_to_sdp(p, x, 8000,
6626 &m_audio_next, &m_audio_left,
6627 &a_audio_next, &a_audio_left,
6628 debug);
6631 if (option_debug > 2)
6632 ast_log(LOG_DEBUG, "-- Done with adding codecs to SDP\n");
6634 if (!p->owner || !ast_internal_timing_enabled(p->owner))
6635 ast_build_string(&a_audio_next, &a_audio_left, "a=silenceSupp:off - - - -\r\n");
6637 if (min_audio_packet_size)
6638 ast_build_string(&a_audio_next, &a_audio_left, "a=ptime:%d\r\n", min_audio_packet_size);
6640 if (min_video_packet_size)
6641 ast_build_string(&a_video_next, &a_video_left, "a=ptime:%d\r\n", min_video_packet_size);
6643 if ((m_audio_left < 2) || (m_video_left < 2) || (a_audio_left == 0) || (a_video_left == 0))
6644 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
6646 ast_build_string(&m_audio_next, &m_audio_left, "\r\n");
6647 if (needvideo)
6648 ast_build_string(&m_video_next, &m_video_left, "\r\n");
6650 len = strlen(version) + strlen(subject) + strlen(owner) + strlen(connection) + strlen(stime) + strlen(m_audio) + strlen(a_audio) + strlen(hold);
6651 if (needvideo) /* only if video response is appropriate */
6652 len += strlen(m_video) + strlen(a_video) + strlen(bandwidth) + strlen(hold);
6654 add_header(resp, "Content-Type", "application/sdp");
6655 add_header_contentLength(resp, len);
6656 add_line(resp, version);
6657 add_line(resp, owner);
6658 add_line(resp, subject);
6659 add_line(resp, connection);
6660 if (needvideo) /* only if video response is appropriate */
6661 add_line(resp, bandwidth);
6662 add_line(resp, stime);
6663 add_line(resp, m_audio);
6664 add_line(resp, a_audio);
6665 add_line(resp, hold);
6666 if (needvideo) { /* only if video response is appropriate */
6667 add_line(resp, m_video);
6668 add_line(resp, a_video);
6669 add_line(resp, hold); /* Repeat hold for the video stream */
6672 /* Update lastrtprx when we send our SDP */
6673 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
6675 if (option_debug > 2) {
6676 char buf[SIPBUFSIZE];
6677 ast_log(LOG_DEBUG, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
6680 return AST_SUCCESS;
6683 /*! \brief Used for 200 OK and 183 early media */
6684 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
6686 struct sip_request resp;
6687 int seqno;
6689 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
6690 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
6691 return -1;
6693 respprep(&resp, p, msg, req);
6694 if (p->udptl) {
6695 ast_udptl_offered_from_local(p->udptl, 0);
6696 add_t38_sdp(&resp, p);
6697 } else
6698 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
6699 if (retrans && !p->pendinginvite)
6700 p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
6701 return send_response(p, &resp, retrans, seqno);
6704 /*! \brief copy SIP request (mostly used to save request for responses) */
6705 static void copy_request(struct sip_request *dst, const struct sip_request *src)
6707 long offset;
6708 int x;
6709 offset = ((void *)dst) - ((void *)src);
6710 /* First copy stuff */
6711 memcpy(dst, src, sizeof(*dst));
6712 /* Now fix pointer arithmetic */
6713 for (x=0; x < src->headers; x++)
6714 dst->header[x] += offset;
6715 for (x=0; x < src->lines; x++)
6716 dst->line[x] += offset;
6717 dst->rlPart1 += offset;
6718 dst->rlPart2 += offset;
6721 /*! \brief Used for 200 OK and 183 early media
6722 \return Will return XMIT_ERROR for network errors.
6724 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
6726 struct sip_request resp;
6727 int seqno;
6728 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
6729 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
6730 return -1;
6732 respprep(&resp, p, msg, req);
6733 if (p->rtp) {
6734 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
6735 if (option_debug)
6736 ast_log(LOG_DEBUG, "Setting framing from config on incoming call\n");
6737 ast_rtp_codec_setpref(p->rtp, &p->prefs);
6739 try_suggested_sip_codec(p);
6740 add_sdp(&resp, p);
6741 } else
6742 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
6743 if (reliable && !p->pendinginvite)
6744 p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
6745 return send_response(p, &resp, reliable, seqno);
6748 /*! \brief Parse first line of incoming SIP request */
6749 static int determine_firstline_parts(struct sip_request *req)
6751 char *e = ast_skip_blanks(req->header[0]); /* there shouldn't be any */
6753 if (!*e)
6754 return -1;
6755 req->rlPart1 = e; /* method or protocol */
6756 e = ast_skip_nonblanks(e);
6757 if (*e)
6758 *e++ = '\0';
6759 /* Get URI or status code */
6760 e = ast_skip_blanks(e);
6761 if ( !*e )
6762 return -1;
6763 ast_trim_blanks(e);
6765 if (!strcasecmp(req->rlPart1, "SIP/2.0") ) { /* We have a response */
6766 if (strlen(e) < 3) /* status code is 3 digits */
6767 return -1;
6768 req->rlPart2 = e;
6769 } else { /* We have a request */
6770 if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
6771 ast_log(LOG_WARNING, "bogus uri in <> %s\n", e);
6772 e++;
6773 if (!*e)
6774 return -1;
6776 req->rlPart2 = e; /* URI */
6777 e = ast_skip_nonblanks(e);
6778 if (*e)
6779 *e++ = '\0';
6780 e = ast_skip_blanks(e);
6781 if (strcasecmp(e, "SIP/2.0") ) {
6782 ast_log(LOG_WARNING, "Bad request protocol %s\n", e);
6783 return -1;
6786 return 1;
6789 /*! \brief Transmit reinvite with SDP
6790 \note A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
6791 INVITE that opened the SIP dialogue
6792 We reinvite so that the audio stream (RTP) go directly between
6793 the SIP UAs. SIP Signalling stays with * in the path.
6795 static int transmit_reinvite_with_sdp(struct sip_pvt *p)
6797 struct sip_request req;
6799 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
6801 add_header(&req, "Allow", ALLOWED_METHODS);
6802 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6803 if (sipdebug)
6804 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
6805 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
6806 append_history(p, "ReInv", "Re-invite sent");
6807 add_sdp(&req, p);
6808 /* Use this as the basis */
6809 initialize_initreq(p, &req);
6810 p->lastinvite = p->ocseq;
6811 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Change direction of this dialog */
6812 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
6815 /*! \brief Transmit reinvite with T38 SDP
6816 We reinvite so that the T38 processing can take place.
6817 SIP Signalling stays with * in the path.
6819 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p)
6821 struct sip_request req;
6823 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
6825 add_header(&req, "Allow", ALLOWED_METHODS);
6826 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6827 if (sipdebug)
6828 add_header(&req, "X-asterisk-info", "SIP re-invite (T38 switchover)");
6829 ast_udptl_offered_from_local(p->udptl, 1);
6830 add_t38_sdp(&req, p);
6831 /* Use this as the basis */
6832 initialize_initreq(p, &req);
6833 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Change direction of this dialog */
6834 p->lastinvite = p->ocseq;
6835 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
6838 /*! \brief Check Contact: URI of SIP message */
6839 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
6841 char stripped[SIPBUFSIZE];
6842 char *c;
6844 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
6845 c = get_in_brackets(stripped);
6846 c = strsep(&c, ";"); /* trim ; and beyond */
6847 if (!ast_strlen_zero(c))
6848 ast_string_field_set(p, uri, c);
6851 /*! \brief Build contact header - the contact header we send out */
6852 static void build_contact(struct sip_pvt *p)
6854 /* Construct Contact: header */
6855 if (ourport != STANDARD_SIP_PORT)
6856 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);
6857 else
6858 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip));
6861 /*! \brief Build the Remote Party-ID & From using callingpres options */
6862 static void build_rpid(struct sip_pvt *p)
6864 int send_pres_tags = TRUE;
6865 const char *privacy=NULL;
6866 const char *screen=NULL;
6867 char buf[256];
6868 const char *clid = default_callerid;
6869 const char *clin = NULL;
6870 const char *fromdomain;
6872 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
6873 return;
6875 if (p->owner && p->owner->cid.cid_num)
6876 clid = p->owner->cid.cid_num;
6877 if (p->owner && p->owner->cid.cid_name)
6878 clin = p->owner->cid.cid_name;
6879 if (ast_strlen_zero(clin))
6880 clin = clid;
6882 switch (p->callingpres) {
6883 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
6884 privacy = "off";
6885 screen = "no";
6886 break;
6887 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
6888 privacy = "off";
6889 screen = "yes";
6890 break;
6891 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
6892 privacy = "off";
6893 screen = "no";
6894 break;
6895 case AST_PRES_ALLOWED_NETWORK_NUMBER:
6896 privacy = "off";
6897 screen = "yes";
6898 break;
6899 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
6900 privacy = "full";
6901 screen = "no";
6902 break;
6903 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
6904 privacy = "full";
6905 screen = "yes";
6906 break;
6907 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
6908 privacy = "full";
6909 screen = "no";
6910 break;
6911 case AST_PRES_PROHIB_NETWORK_NUMBER:
6912 privacy = "full";
6913 screen = "yes";
6914 break;
6915 case AST_PRES_NUMBER_NOT_AVAILABLE:
6916 send_pres_tags = FALSE;
6917 break;
6918 default:
6919 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
6920 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
6921 privacy = "full";
6922 else
6923 privacy = "off";
6924 screen = "no";
6925 break;
6928 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip));
6930 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
6931 if (send_pres_tags)
6932 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
6933 ast_string_field_set(p, rpid, buf);
6935 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
6936 S_OR(p->fromuser, clid),
6937 fromdomain, p->tag);
6940 /*! \brief Initiate new SIP request to peer/user */
6941 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
6943 char invite_buf[256] = "";
6944 char *invite = invite_buf;
6945 size_t invite_max = sizeof(invite_buf);
6946 char from[256];
6947 char to[256];
6948 char tmp[SIPBUFSIZE/2];
6949 char tmp2[SIPBUFSIZE/2];
6950 const char *l = NULL, *n = NULL;
6951 const char *urioptions = "";
6953 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
6954 const char *s = p->username; /* being a string field, cannot be NULL */
6956 /* Test p->username against allowed characters in AST_DIGIT_ANY
6957 If it matches the allowed characters list, then sipuser = ";user=phone"
6958 If not, then sipuser = ""
6960 /* + is allowed in first position in a tel: uri */
6961 if (*s == '+')
6962 s++;
6963 for (; *s; s++) {
6964 if (!strchr(AST_DIGIT_ANYNUM, *s) )
6965 break;
6967 /* If we have only digits, add ;user=phone to the uri */
6968 if (*s)
6969 urioptions = ";user=phone";
6973 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
6975 if (p->owner) {
6976 l = p->owner->cid.cid_num;
6977 n = p->owner->cid.cid_name;
6979 /* if we are not sending RPID and user wants his callerid restricted */
6980 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
6981 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
6982 l = CALLERID_UNKNOWN;
6983 n = l;
6985 if (ast_strlen_zero(l))
6986 l = default_callerid;
6987 if (ast_strlen_zero(n))
6988 n = l;
6989 /* Allow user to be overridden */
6990 if (!ast_strlen_zero(p->fromuser))
6991 l = p->fromuser;
6992 else /* Save for any further attempts */
6993 ast_string_field_set(p, fromuser, l);
6995 /* Allow user to be overridden */
6996 if (!ast_strlen_zero(p->fromname))
6997 n = p->fromname;
6998 else /* Save for any further attempts */
6999 ast_string_field_set(p, fromname, n);
7001 if (pedanticsipchecking) {
7002 ast_uri_encode(n, tmp, sizeof(tmp), 0);
7003 n = tmp;
7004 ast_uri_encode(l, tmp2, sizeof(tmp2), 0);
7005 l = tmp2;
7008 if (ourport != STANDARD_SIP_PORT && ast_strlen_zero(p->fromdomain))
7009 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);
7010 else
7011 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)), p->tag);
7013 /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
7014 if (!ast_strlen_zero(p->fullcontact)) {
7015 /* If we have full contact, trust it */
7016 ast_build_string(&invite, &invite_max, "%s", p->fullcontact);
7017 } else {
7018 /* Otherwise, use the username while waiting for registration */
7019 ast_build_string(&invite, &invite_max, "sip:");
7020 if (!ast_strlen_zero(p->username)) {
7021 n = p->username;
7022 if (pedanticsipchecking) {
7023 ast_uri_encode(n, tmp, sizeof(tmp), 0);
7024 n = tmp;
7026 ast_build_string(&invite, &invite_max, "%s@", n);
7028 ast_build_string(&invite, &invite_max, "%s", p->tohost);
7029 if (ntohs(p->sa.sin_port) != STANDARD_SIP_PORT)
7030 ast_build_string(&invite, &invite_max, ":%d", ntohs(p->sa.sin_port));
7031 ast_build_string(&invite, &invite_max, "%s", urioptions);
7034 /* If custom URI options have been provided, append them */
7035 if (p->options && !ast_strlen_zero(p->options->uri_options))
7036 ast_build_string(&invite, &invite_max, ";%s", p->options->uri_options);
7038 ast_string_field_set(p, uri, invite_buf);
7040 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
7041 /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
7042 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "" : "sip:"), p->uri, p->theirtag);
7043 } else if (p->options && p->options->vxml_url) {
7044 /* If there is a VXML URL append it to the SIP URL */
7045 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
7046 } else
7047 snprintf(to, sizeof(to), "<%s>", p->uri);
7049 init_req(req, sipmethod, p->uri);
7050 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
7052 add_header(req, "Via", p->via);
7053 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
7054 * OTOH, then we won't have anything in p->route anyway */
7055 /* Build Remote Party-ID and From */
7056 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
7057 build_rpid(p);
7058 add_header(req, "From", p->rpid_from);
7059 } else
7060 add_header(req, "From", from);
7061 add_header(req, "To", to);
7062 ast_string_field_set(p, exten, l);
7063 build_contact(p);
7064 add_header(req, "Contact", p->our_contact);
7065 add_header(req, "Call-ID", p->callid);
7066 add_header(req, "CSeq", tmp);
7067 if (!ast_strlen_zero(global_useragent))
7068 add_header(req, "User-Agent", global_useragent);
7069 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
7070 if (!ast_strlen_zero(p->rpid))
7071 add_header(req, "Remote-Party-ID", p->rpid);
7074 /*! \brief Build REFER/INVITE/OPTIONS message and transmit it */
7075 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
7077 struct sip_request req;
7079 req.method = sipmethod;
7080 if (init) { /* Seems like init always is 2 */
7081 /* Bump branch even on initial requests */
7082 p->branch ^= ast_random();
7083 build_via(p);
7084 if (init > 1)
7085 initreqprep(&req, p, sipmethod);
7086 else
7087 reqprep(&req, p, sipmethod, 0, 1);
7088 } else
7089 reqprep(&req, p, sipmethod, 0, 1);
7091 if (p->options && p->options->auth)
7092 add_header(&req, p->options->authheader, p->options->auth);
7093 append_date(&req);
7094 if (sipmethod == SIP_REFER) { /* Call transfer */
7095 if (p->refer) {
7096 char buf[SIPBUFSIZE];
7097 if (!ast_strlen_zero(p->refer->refer_to))
7098 add_header(&req, "Refer-To", p->refer->refer_to);
7099 if (!ast_strlen_zero(p->refer->referred_by)) {
7100 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
7101 add_header(&req, "Referred-By", buf);
7105 /* This new INVITE is part of an attended transfer. Make sure that the
7106 other end knows and replace the current call with this new call */
7107 if (p->options && p->options->replaces && !ast_strlen_zero(p->options->replaces)) {
7108 add_header(&req, "Replaces", p->options->replaces);
7109 add_header(&req, "Require", "replaces");
7112 add_header(&req, "Allow", ALLOWED_METHODS);
7113 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7114 if (p->options && p->options->addsipheaders && p->owner) {
7115 struct ast_channel *chan = p->owner; /* The owner channel */
7116 struct varshead *headp;
7118 ast_channel_lock(chan);
7120 headp = &chan->varshead;
7122 if (!headp)
7123 ast_log(LOG_WARNING,"No Headp for the channel...ooops!\n");
7124 else {
7125 const struct ast_var_t *current;
7126 AST_LIST_TRAVERSE(headp, current, entries) {
7127 /* SIPADDHEADER: Add SIP header to outgoing call */
7128 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
7129 char *content, *end;
7130 const char *header = ast_var_value(current);
7131 char *headdup = ast_strdupa(header);
7133 /* Strip of the starting " (if it's there) */
7134 if (*headdup == '"')
7135 headdup++;
7136 if ((content = strchr(headdup, ':'))) {
7137 *content++ = '\0';
7138 content = ast_skip_blanks(content); /* Skip white space */
7139 /* Strip the ending " (if it's there) */
7140 end = content + strlen(content) -1;
7141 if (*end == '"')
7142 *end = '\0';
7144 add_header(&req, headdup, content);
7145 if (sipdebug)
7146 ast_log(LOG_DEBUG, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
7152 ast_channel_unlock(chan);
7154 if (sdp) {
7155 if (p->udptl && (p->t38.state == T38_LOCAL_DIRECT || p->t38.state == T38_LOCAL_REINVITE)) {
7156 ast_udptl_offered_from_local(p->udptl, 1);
7157 if (option_debug)
7158 ast_log(LOG_DEBUG, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
7159 add_t38_sdp(&req, p);
7160 } else if (p->rtp)
7161 add_sdp(&req, p);
7162 } else {
7163 add_header_contentLength(&req, 0);
7166 if (!p->initreq.headers)
7167 initialize_initreq(p, &req);
7168 p->lastinvite = p->ocseq;
7169 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
7172 /*! \brief Used in the SUBSCRIBE notification subsystem */
7173 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
7175 char tmp[4000], from[256], to[256];
7176 char *t = tmp, *c, *mfrom, *mto;
7177 size_t maxbytes = sizeof(tmp);
7178 struct sip_request req;
7179 char hint[AST_MAX_EXTENSION];
7180 char *statestring = "terminated";
7181 const struct cfsubscription_types *subscriptiontype;
7182 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
7183 char *pidfstate = "--";
7184 char *pidfnote= "Ready";
7186 memset(from, 0, sizeof(from));
7187 memset(to, 0, sizeof(to));
7188 memset(tmp, 0, sizeof(tmp));
7190 switch (state) {
7191 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
7192 statestring = (global_notifyringing) ? "early" : "confirmed";
7193 local_state = NOTIFY_INUSE;
7194 pidfstate = "busy";
7195 pidfnote = "Ringing";
7196 break;
7197 case AST_EXTENSION_RINGING:
7198 statestring = "early";
7199 local_state = NOTIFY_INUSE;
7200 pidfstate = "busy";
7201 pidfnote = "Ringing";
7202 break;
7203 case AST_EXTENSION_INUSE:
7204 statestring = "confirmed";
7205 local_state = NOTIFY_INUSE;
7206 pidfstate = "busy";
7207 pidfnote = "On the phone";
7208 break;
7209 case AST_EXTENSION_BUSY:
7210 statestring = "confirmed";
7211 local_state = NOTIFY_CLOSED;
7212 pidfstate = "busy";
7213 pidfnote = "On the phone";
7214 break;
7215 case AST_EXTENSION_UNAVAILABLE:
7216 statestring = "terminated";
7217 local_state = NOTIFY_CLOSED;
7218 pidfstate = "away";
7219 pidfnote = "Unavailable";
7220 break;
7221 case AST_EXTENSION_ONHOLD:
7222 statestring = "confirmed";
7223 local_state = NOTIFY_CLOSED;
7224 pidfstate = "busy";
7225 pidfnote = "On Hold";
7226 break;
7227 case AST_EXTENSION_NOT_INUSE:
7228 default:
7229 /* Default setting */
7230 break;
7233 subscriptiontype = find_subscription_type(p->subscribed);
7235 /* Check which device/devices we are watching and if they are registered */
7236 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
7237 char *hint2 = hint, *individual_hint = NULL;
7238 int hint_count = 0, unavailable_count = 0;
7240 while ((individual_hint = strsep(&hint2, "&"))) {
7241 hint_count++;
7243 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
7244 unavailable_count++;
7247 /* If none of the hinted devices are registered, we will
7248 * override notification and show no availability.
7250 if (hint_count > 0 && hint_count == unavailable_count) {
7251 local_state = NOTIFY_CLOSED;
7252 pidfstate = "away";
7253 pidfnote = "Not online";
7257 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
7258 c = get_in_brackets(from);
7259 if (strncasecmp(c, "sip:", 4)) {
7260 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
7261 return -1;
7263 mfrom = strsep(&c, ";"); /* trim ; and beyond */
7265 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
7266 c = get_in_brackets(to);
7267 if (strncasecmp(c, "sip:", 4)) {
7268 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
7269 return -1;
7271 mto = strsep(&c, ";"); /* trim ; and beyond */
7273 reqprep(&req, p, SIP_NOTIFY, 0, 1);
7276 add_header(&req, "Event", subscriptiontype->event);
7277 add_header(&req, "Content-Type", subscriptiontype->mediatype);
7278 switch(state) {
7279 case AST_EXTENSION_DEACTIVATED:
7280 if (timeout)
7281 add_header(&req, "Subscription-State", "terminated;reason=timeout");
7282 else {
7283 add_header(&req, "Subscription-State", "terminated;reason=probation");
7284 add_header(&req, "Retry-After", "60");
7286 break;
7287 case AST_EXTENSION_REMOVED:
7288 add_header(&req, "Subscription-State", "terminated;reason=noresource");
7289 break;
7290 default:
7291 if (p->expiry)
7292 add_header(&req, "Subscription-State", "active");
7293 else /* Expired */
7294 add_header(&req, "Subscription-State", "terminated;reason=timeout");
7296 switch (p->subscribed) {
7297 case XPIDF_XML:
7298 case CPIM_PIDF_XML:
7299 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
7300 ast_build_string(&t, &maxbytes, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
7301 ast_build_string(&t, &maxbytes, "<presence>\n");
7302 ast_build_string(&t, &maxbytes, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
7303 ast_build_string(&t, &maxbytes, "<atom id=\"%s\">\n", p->exten);
7304 ast_build_string(&t, &maxbytes, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
7305 ast_build_string(&t, &maxbytes, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
7306 ast_build_string(&t, &maxbytes, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
7307 ast_build_string(&t, &maxbytes, "</address>\n</atom>\n</presence>\n");
7308 break;
7309 case PIDF_XML: /* Eyebeam supports this format */
7310 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
7311 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);
7312 ast_build_string(&t, &maxbytes, "<pp:person><status>\n");
7313 if (pidfstate[0] != '-')
7314 ast_build_string(&t, &maxbytes, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
7315 ast_build_string(&t, &maxbytes, "</status></pp:person>\n");
7316 ast_build_string(&t, &maxbytes, "<note>%s</note>\n", pidfnote); /* Note */
7317 ast_build_string(&t, &maxbytes, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
7318 ast_build_string(&t, &maxbytes, "<contact priority=\"1\">%s</contact>\n", mto);
7319 if (pidfstate[0] == 'b') /* Busy? Still open ... */
7320 ast_build_string(&t, &maxbytes, "<status><basic>open</basic></status>\n");
7321 else
7322 ast_build_string(&t, &maxbytes, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
7323 ast_build_string(&t, &maxbytes, "</tuple>\n</presence>\n");
7324 break;
7325 case DIALOG_INFO_XML: /* SNOM subscribes in this format */
7326 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
7327 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);
7328 if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
7329 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
7330 else
7331 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\">\n", p->exten);
7332 ast_build_string(&t, &maxbytes, "<state>%s</state>\n", statestring);
7333 if (state == AST_EXTENSION_ONHOLD) {
7334 ast_build_string(&t, &maxbytes, "<local>\n<target uri=\"%s\">\n"
7335 "<param pname=\"+sip.rendering\" pvalue=\"no\">\n"
7336 "</target>\n</local>\n", mto);
7338 ast_build_string(&t, &maxbytes, "</dialog>\n</dialog-info>\n");
7339 break;
7340 case NONE:
7341 default:
7342 break;
7345 if (t > tmp + sizeof(tmp))
7346 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
7348 add_header_contentLength(&req, strlen(tmp));
7349 add_line(&req, tmp);
7350 p->pendinginvite = p->ocseq; /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
7352 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7355 /*! \brief Notify user of messages waiting in voicemail
7356 \note - Notification only works for registered peers with mailbox= definitions
7357 in sip.conf
7358 - We use the SIP Event package message-summary
7359 MIME type defaults to "application/simple-message-summary";
7361 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
7363 struct sip_request req;
7364 char tmp[500];
7365 char *t = tmp;
7366 size_t maxbytes = sizeof(tmp);
7368 initreqprep(&req, p, SIP_NOTIFY);
7369 add_header(&req, "Event", "message-summary");
7370 add_header(&req, "Content-Type", default_notifymime);
7372 ast_build_string(&t, &maxbytes, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
7373 ast_build_string(&t, &maxbytes, "Message-Account: sip:%s@%s\r\n",
7374 S_OR(vmexten, default_vmexten), S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)));
7375 /* Cisco has a bug in the SIP stack where it can't accept the
7376 (0/0) notification. This can temporarily be disabled in
7377 sip.conf with the "buggymwi" option */
7378 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)"));
7380 if (p->subscribed) {
7381 if (p->expiry)
7382 add_header(&req, "Subscription-State", "active");
7383 else /* Expired */
7384 add_header(&req, "Subscription-State", "terminated;reason=timeout");
7387 if (t > tmp + sizeof(tmp))
7388 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
7390 add_header_contentLength(&req, strlen(tmp));
7391 add_line(&req, tmp);
7393 if (!p->initreq.headers)
7394 initialize_initreq(p, &req);
7395 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7398 /*! \brief Transmit SIP request unreliably (only used in sip_notify subsystem) */
7399 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req)
7401 if (!p->initreq.headers) /* Initialize first request before sending */
7402 initialize_initreq(p, req);
7403 return send_request(p, req, XMIT_UNRELIABLE, p->ocseq);
7406 /*! \brief Notify a transferring party of the status of transfer */
7407 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
7409 struct sip_request req;
7410 char tmp[SIPBUFSIZE/2];
7412 reqprep(&req, p, SIP_NOTIFY, 0, 1);
7413 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
7414 add_header(&req, "Event", tmp);
7415 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
7416 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
7417 add_header(&req, "Allow", ALLOWED_METHODS);
7418 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7420 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
7421 add_header_contentLength(&req, strlen(tmp));
7422 add_line(&req, tmp);
7424 if (!p->initreq.headers)
7425 initialize_initreq(p, &req);
7427 p->lastnoninvite = p->ocseq;
7429 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7432 /*! \brief Convert registration state status to string */
7433 static char *regstate2str(enum sipregistrystate regstate)
7435 switch(regstate) {
7436 case REG_STATE_FAILED:
7437 return "Failed";
7438 case REG_STATE_UNREGISTERED:
7439 return "Unregistered";
7440 case REG_STATE_REGSENT:
7441 return "Request Sent";
7442 case REG_STATE_AUTHSENT:
7443 return "Auth. Sent";
7444 case REG_STATE_REGISTERED:
7445 return "Registered";
7446 case REG_STATE_REJECTED:
7447 return "Rejected";
7448 case REG_STATE_TIMEOUT:
7449 return "Timeout";
7450 case REG_STATE_NOAUTH:
7451 return "No Authentication";
7452 default:
7453 return "Unknown";
7457 /*! \brief Update registration with SIP Proxy */
7458 static int sip_reregister(const void *data)
7460 /* if we are here, we know that we need to reregister. */
7461 struct sip_registry *r= ASTOBJ_REF((struct sip_registry *) data);
7463 /* if we couldn't get a reference to the registry object, punt */
7464 if (!r)
7465 return 0;
7467 if (r->call && !ast_test_flag(&r->call->flags[0], SIP_NO_HISTORY))
7468 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
7469 /* Since registry's are only added/removed by the the monitor thread, this
7470 may be overkill to reference/dereference at all here */
7471 if (sipdebug)
7472 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
7474 r->expire = -1;
7475 __sip_do_register(r);
7476 ASTOBJ_UNREF(r, sip_registry_destroy);
7477 return 0;
7480 /*! \brief Register with SIP proxy */
7481 static int __sip_do_register(struct sip_registry *r)
7483 int res;
7485 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
7486 return res;
7489 /*! \brief Registration timeout, register again */
7490 static int sip_reg_timeout(const void *data)
7493 /* if we are here, our registration timed out, so we'll just do it over */
7494 struct sip_registry *r = ASTOBJ_REF((struct sip_registry *) data);
7495 struct sip_pvt *p;
7496 int res;
7498 /* if we couldn't get a reference to the registry object, punt */
7499 if (!r)
7500 return 0;
7502 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
7503 if (r->call) {
7504 /* Unlink us, destroy old call. Locking is not relevant here because all this happens
7505 in the single SIP manager thread. */
7506 p = r->call;
7507 ast_mutex_lock(&p->lock);
7508 if (p->registry)
7509 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
7510 r->call = NULL;
7511 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
7512 /* Pretend to ACK anything just in case */
7513 __sip_pretend_ack(p);
7514 ast_mutex_unlock(&p->lock);
7516 /* If we have a limit, stop registration and give up */
7517 if (global_regattempts_max && (r->regattempts > global_regattempts_max)) {
7518 /* Ok, enough is enough. Don't try any more */
7519 /* We could add an external notification here...
7520 steal it from app_voicemail :-) */
7521 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
7522 r->regstate = REG_STATE_FAILED;
7523 } else {
7524 r->regstate = REG_STATE_UNREGISTERED;
7525 r->timeout = -1;
7526 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
7528 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));
7529 ASTOBJ_UNREF(r, sip_registry_destroy);
7530 return 0;
7533 /*! \brief Transmit register to SIP proxy or UA */
7534 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
7536 struct sip_request req;
7537 char from[256];
7538 char to[256];
7539 char tmp[80];
7540 char addr[80];
7541 struct sip_pvt *p;
7543 /* exit if we are already in process with this registrar ?*/
7544 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
7545 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
7546 return 0;
7549 if (r->call) { /* We have a registration */
7550 if (!auth) {
7551 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
7552 return 0;
7553 } else {
7554 p = r->call;
7555 make_our_tag(p->tag, sizeof(p->tag)); /* create a new local tag for every register attempt */
7556 ast_string_field_free(p, theirtag); /* forget their old tag, so we don't match tags when getting response */
7558 } else {
7559 /* Build callid for registration if we haven't registered before */
7560 if (!r->callid_valid) {
7561 build_callid_registry(r, __ourip, default_fromdomain);
7562 r->callid_valid = TRUE;
7564 /* Allocate SIP packet for registration */
7565 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER))) {
7566 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
7567 return 0;
7569 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
7570 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
7571 /* Find address to hostname */
7572 if (create_addr(p, r->hostname)) {
7573 /* we have what we hope is a temporary network error,
7574 * probably DNS. We need to reschedule a registration try */
7575 sip_destroy(p);
7577 if (r->timeout > -1)
7578 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
7579 else
7580 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);
7582 AST_SCHED_DEL(sched, r->timeout);
7583 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
7584 r->regattempts++;
7585 return 0;
7587 /* Copy back Call-ID in case create_addr changed it */
7588 ast_string_field_set(r, callid, p->callid);
7589 if (r->portno) {
7590 p->sa.sin_port = htons(r->portno);
7591 p->recv.sin_port = htons(r->portno);
7592 } else /* Set registry port to the port set from the peer definition/srv or default */
7593 r->portno = ntohs(p->sa.sin_port);
7594 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
7595 r->call=p; /* Save pointer to SIP packet */
7596 p->registry = ASTOBJ_REF(r); /* Add pointer to registry in packet */
7597 if (!ast_strlen_zero(r->secret)) /* Secret (password) */
7598 ast_string_field_set(p, peersecret, r->secret);
7599 if (!ast_strlen_zero(r->md5secret))
7600 ast_string_field_set(p, peermd5secret, r->md5secret);
7601 /* User name in this realm
7602 - if authuser is set, use that, otherwise use username */
7603 if (!ast_strlen_zero(r->authuser)) {
7604 ast_string_field_set(p, peername, r->authuser);
7605 ast_string_field_set(p, authname, r->authuser);
7606 } else if (!ast_strlen_zero(r->username)) {
7607 ast_string_field_set(p, peername, r->username);
7608 ast_string_field_set(p, authname, r->username);
7609 ast_string_field_set(p, fromuser, r->username);
7611 if (!ast_strlen_zero(r->username))
7612 ast_string_field_set(p, username, r->username);
7613 /* Save extension in packet */
7614 ast_string_field_set(p, exten, r->contact);
7617 check which address we should use in our contact header
7618 based on whether the remote host is on the external or
7619 internal network so we can register through nat
7621 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
7622 p->ourip = bindaddr.sin_addr;
7623 build_contact(p);
7626 /* set up a timeout */
7627 if (auth == NULL) {
7628 if (r->timeout > -1)
7629 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
7630 AST_SCHED_DEL(sched, r->timeout);
7631 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
7632 if (option_debug)
7633 ast_log(LOG_DEBUG, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
7636 if (strchr(r->username, '@')) {
7637 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
7638 if (!ast_strlen_zero(p->theirtag))
7639 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
7640 else
7641 snprintf(to, sizeof(to), "<sip:%s>", r->username);
7642 } else {
7643 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
7644 if (!ast_strlen_zero(p->theirtag))
7645 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
7646 else
7647 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
7650 /* Fromdomain is what we are registering to, regardless of actual
7651 host name from SRV */
7652 if (!ast_strlen_zero(p->fromdomain)) {
7653 if (r->portno && r->portno != STANDARD_SIP_PORT)
7654 snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
7655 else
7656 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
7657 } else {
7658 if (r->portno && r->portno != STANDARD_SIP_PORT)
7659 snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
7660 else
7661 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
7663 ast_string_field_set(p, uri, addr);
7665 p->branch ^= ast_random();
7667 init_req(&req, sipmethod, addr);
7669 /* Add to CSEQ */
7670 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
7671 p->ocseq = r->ocseq;
7673 build_via(p);
7674 add_header(&req, "Via", p->via);
7675 add_header(&req, "From", from);
7676 add_header(&req, "To", to);
7677 add_header(&req, "Call-ID", p->callid);
7678 add_header(&req, "CSeq", tmp);
7679 if (!ast_strlen_zero(global_useragent))
7680 add_header(&req, "User-Agent", global_useragent);
7681 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
7684 if (auth) /* Add auth header */
7685 add_header(&req, authheader, auth);
7686 else if (!ast_strlen_zero(r->nonce)) {
7687 char digest[1024];
7689 /* We have auth data to reuse, build a digest header! */
7690 if (sipdebug)
7691 ast_log(LOG_DEBUG, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
7692 ast_string_field_set(p, realm, r->realm);
7693 ast_string_field_set(p, nonce, r->nonce);
7694 ast_string_field_set(p, domain, r->domain);
7695 ast_string_field_set(p, opaque, r->opaque);
7696 ast_string_field_set(p, qop, r->qop);
7697 r->noncecount++;
7698 p->noncecount = r->noncecount;
7700 memset(digest,0,sizeof(digest));
7701 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
7702 add_header(&req, "Authorization", digest);
7703 else
7704 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
7708 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
7709 add_header(&req, "Expires", tmp);
7710 add_header(&req, "Contact", p->our_contact);
7711 add_header(&req, "Event", "registration");
7712 add_header_contentLength(&req, 0);
7714 initialize_initreq(p, &req);
7715 if (sip_debug_test_pvt(p))
7716 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
7717 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
7718 r->regattempts++; /* Another attempt */
7719 if (option_debug > 3)
7720 ast_verbose("REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
7721 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
7724 /*! \brief Transmit text with SIP MESSAGE method */
7725 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
7727 struct sip_request req;
7729 reqprep(&req, p, SIP_MESSAGE, 0, 1);
7730 add_text(&req, text);
7731 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7734 /*! \brief Allocate SIP refer structure */
7735 static int sip_refer_allocate(struct sip_pvt *p)
7737 p->refer = ast_calloc(1, sizeof(struct sip_refer));
7738 return p->refer ? 1 : 0;
7741 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
7742 \note this is currently broken as we have no way of telling the dialplan
7743 engine whether a transfer succeeds or fails.
7744 \todo Fix the transfer() dialplan function so that a transfer may fail
7746 static int transmit_refer(struct sip_pvt *p, const char *dest)
7748 struct sip_request req = {
7749 .headers = 0,
7751 char from[256];
7752 const char *of;
7753 char *c;
7754 char referto[256];
7755 char *ttag, *ftag;
7756 char *theirtag = ast_strdupa(p->theirtag);
7758 if (option_debug || sipdebug)
7759 ast_log(LOG_DEBUG, "SIP transfer of %s to %s\n", p->callid, dest);
7761 /* Are we transfering an inbound or outbound call ? */
7762 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
7763 of = get_header(&p->initreq, "To");
7764 ttag = theirtag;
7765 ftag = p->tag;
7766 } else {
7767 of = get_header(&p->initreq, "From");
7768 ftag = theirtag;
7769 ttag = p->tag;
7772 ast_copy_string(from, of, sizeof(from));
7773 of = get_in_brackets(from);
7774 ast_string_field_set(p, from, of);
7775 if (strncasecmp(of, "sip:", 4))
7776 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
7777 else
7778 of += 4;
7779 /* Get just the username part */
7780 if ((c = strchr(dest, '@')))
7781 c = NULL;
7782 else if ((c = strchr(of, '@')))
7783 *c++ = '\0';
7784 if (c)
7785 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
7786 else
7787 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
7789 /* save in case we get 407 challenge */
7790 sip_refer_allocate(p);
7791 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
7792 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
7793 p->refer->status = REFER_SENT; /* Set refer status */
7795 reqprep(&req, p, SIP_REFER, 0, 1);
7796 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
7798 add_header(&req, "Refer-To", referto);
7799 add_header(&req, "Allow", ALLOWED_METHODS);
7800 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7801 if (!ast_strlen_zero(p->our_contact))
7802 add_header(&req, "Referred-By", p->our_contact);
7804 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7805 /* We should propably wait for a NOTIFY here until we ack the transfer */
7806 /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
7808 /*! \todo In theory, we should hang around and wait for a reply, before
7809 returning to the dial plan here. Don't know really how that would
7810 affect the transfer() app or the pbx, but, well, to make this
7811 useful we should have a STATUS code on transfer().
7816 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
7817 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
7819 struct sip_request req;
7821 reqprep(&req, p, SIP_INFO, 0, 1);
7822 add_digit(&req, digit, duration);
7823 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7826 /*! \brief Send SIP INFO with video update request */
7827 static int transmit_info_with_vidupdate(struct sip_pvt *p)
7829 struct sip_request req;
7831 reqprep(&req, p, SIP_INFO, 0, 1);
7832 add_vidupdate(&req);
7833 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7836 /*! \brief Transmit generic SIP request
7837 returns XMIT_ERROR if transmit failed with a critical error (don't retry)
7839 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
7841 struct sip_request resp;
7843 if (sipmethod == SIP_ACK)
7844 p->invitestate = INV_CONFIRMED;
7846 reqprep(&resp, p, sipmethod, seqno, newbranch);
7847 add_header_contentLength(&resp, 0);
7848 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
7851 /*! \brief Transmit SIP request, auth added */
7852 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
7854 struct sip_request resp;
7856 reqprep(&resp, p, sipmethod, seqno, newbranch);
7857 if (!ast_strlen_zero(p->realm)) {
7858 char digest[1024];
7860 memset(digest, 0, sizeof(digest));
7861 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
7862 if (p->options && p->options->auth_type == PROXY_AUTH)
7863 add_header(&resp, "Proxy-Authorization", digest);
7864 else if (p->options && p->options->auth_type == WWW_AUTH)
7865 add_header(&resp, "Authorization", digest);
7866 else /* Default, to be backwards compatible (maybe being too careful, but leaving it for now) */
7867 add_header(&resp, "Proxy-Authorization", digest);
7868 } else
7869 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
7871 /* If we are hanging up and know a cause for that, send it in clear text to make
7872 debugging easier. */
7873 if (sipmethod == SIP_BYE && p->owner && p->owner->hangupcause) {
7874 char buf[10];
7876 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
7877 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
7878 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
7881 add_header_contentLength(&resp, 0);
7882 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
7885 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
7886 static void destroy_association(struct sip_peer *peer)
7888 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE)) {
7889 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
7890 ast_update_realtime("sippeers", "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "username", "", "regserver", "", NULL);
7891 else
7892 ast_db_del("SIP/Registry", peer->name);
7896 /*! \brief Expire registration of SIP peer */
7897 static int expire_register(const void *data)
7899 struct sip_peer *peer = (struct sip_peer *)data;
7901 if (!peer) /* Hmmm. We have no peer. Weird. */
7902 return 0;
7904 memset(&peer->addr, 0, sizeof(peer->addr));
7906 destroy_association(peer); /* remove registration data from storage */
7908 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
7909 register_peer_exten(peer, FALSE); /* Remove regexten */
7910 peer->expire = -1;
7911 ast_device_state_changed("SIP/%s", peer->name);
7913 /* Do we need to release this peer from memory?
7914 Only for realtime peers and autocreated peers
7916 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT) ||
7917 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
7918 peer = ASTOBJ_CONTAINER_UNLINK(&peerl, peer);
7919 ASTOBJ_UNREF(peer, sip_destroy_peer);
7922 ASTOBJ_UNREF(peer, sip_destroy_peer);
7924 return 0;
7927 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
7928 static int sip_poke_peer_s(const void *data)
7930 struct sip_peer *peer = (struct sip_peer *) data;
7932 peer->pokeexpire = -1;
7934 sip_poke_peer(peer);
7936 ASTOBJ_UNREF(peer, sip_destroy_peer);
7938 return 0;
7941 /*! \brief Get registration details from Asterisk DB */
7942 static void reg_source_db(struct sip_peer *peer)
7944 char data[256];
7945 struct in_addr in;
7946 int expiry;
7947 int port;
7948 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
7950 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
7951 return;
7952 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
7953 return;
7955 scan = data;
7956 addr = strsep(&scan, ":");
7957 port_str = strsep(&scan, ":");
7958 expiry_str = strsep(&scan, ":");
7959 username = strsep(&scan, ":");
7960 contact = scan; /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
7962 if (!inet_aton(addr, &in))
7963 return;
7965 if (port_str)
7966 port = atoi(port_str);
7967 else
7968 return;
7970 if (expiry_str)
7971 expiry = atoi(expiry_str);
7972 else
7973 return;
7975 if (username)
7976 ast_copy_string(peer->username, username, sizeof(peer->username));
7977 if (contact)
7978 ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
7980 if (option_debug > 1)
7981 ast_log(LOG_DEBUG, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
7982 peer->name, peer->username, ast_inet_ntoa(in), port, expiry);
7984 memset(&peer->addr, 0, sizeof(peer->addr));
7985 peer->addr.sin_family = AF_INET;
7986 peer->addr.sin_addr = in;
7987 peer->addr.sin_port = htons(port);
7988 if (sipsock < 0) {
7989 /* SIP isn't up yet, so schedule a poke only, pretty soon */
7990 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
7991 struct sip_peer *peer_ptr = peer;
7992 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
7994 peer->pokeexpire = ast_sched_add(sched, ast_random() % 5000 + 1, sip_poke_peer_s, ASTOBJ_REF(peer));
7995 if (peer->pokeexpire == -1) {
7996 struct sip_peer *peer_ptr = peer;
7997 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
7999 } else
8000 sip_poke_peer(peer);
8001 if (!AST_SCHED_DEL(sched, peer->expire)) {
8002 struct sip_peer *peer_ptr = peer;
8003 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8005 peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, ASTOBJ_REF(peer));
8006 if (peer->expire == -1) {
8007 struct sip_peer *peer_ptr = peer;
8008 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8010 register_peer_exten(peer, TRUE);
8013 /*! \brief Save contact header for 200 OK on INVITE */
8014 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
8016 char contact[SIPBUFSIZE];
8017 char *c;
8019 /* Look for brackets */
8020 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
8021 c = get_in_brackets(contact);
8023 /* Save full contact to call pvt for later bye or re-invite */
8024 ast_string_field_set(pvt, fullcontact, c);
8026 /* Save URI for later ACKs, BYE or RE-invites */
8027 ast_string_field_set(pvt, okcontacturi, c);
8029 /* We should return false for URI:s we can't handle,
8030 like sips:, tel:, mailto:,ldap: etc */
8031 return TRUE;
8034 /*! \brief Change the other partys IP address based on given contact */
8035 static int set_address_from_contact(struct sip_pvt *pvt)
8037 struct hostent *hp;
8038 struct ast_hostent ahp;
8039 int port;
8040 char *c, *host, *pt;
8041 char contact_buf[256];
8042 char *contact;
8044 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
8045 /* NAT: Don't trust the contact field. Just use what they came to us
8046 with. */
8047 pvt->sa = pvt->recv;
8048 return 0;
8051 /* Work on a copy */
8052 ast_copy_string(contact_buf, pvt->fullcontact, sizeof(contact_buf));
8053 contact = contact_buf;
8055 /* Make sure it's a SIP URL */
8056 if (strncasecmp(contact, "sip:", 4)) {
8057 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
8058 } else
8059 contact += 4;
8061 /* Ditch arguments */
8062 /* XXX this code is replicated also shortly below */
8064 /* Grab host */
8065 host = strchr(contact, '@');
8066 if (!host) { /* No username part */
8067 host = contact;
8068 c = NULL;
8069 } else {
8070 *host++ = '\0';
8072 pt = strchr(host, ':');
8073 if (pt) {
8074 *pt++ = '\0';
8075 port = atoi(pt);
8076 } else
8077 port = STANDARD_SIP_PORT;
8079 contact = strsep(&contact, ";"); /* trim ; and beyond in username part */
8080 host = strsep(&host, ";"); /* trim ; and beyond in host/domain part */
8082 /* XXX This could block for a long time XXX */
8083 /* We should only do this if it's a name, not an IP */
8084 hp = ast_gethostbyname(host, &ahp);
8085 if (!hp) {
8086 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
8087 return -1;
8089 pvt->sa.sin_family = AF_INET;
8090 memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
8091 pvt->sa.sin_port = htons(port);
8093 return 0;
8097 /*! \brief Parse contact header and save registration (peer registration) */
8098 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
8100 char contact[SIPBUFSIZE];
8101 char data[SIPBUFSIZE];
8102 const char *expires = get_header(req, "Expires");
8103 int expiry = atoi(expires);
8104 char *curi, *n, *pt;
8105 int port;
8106 const char *useragent;
8107 struct hostent *hp;
8108 struct ast_hostent ahp;
8109 struct sockaddr_in oldsin;
8111 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
8113 if (ast_strlen_zero(expires)) { /* No expires header */
8114 expires = strcasestr(contact, ";expires=");
8115 if (expires) {
8116 /* XXX bug here, we overwrite the string */
8117 expires = strsep((char **) &expires, ";"); /* trim ; and beyond */
8118 if (sscanf(expires + 9, "%d", &expiry) != 1)
8119 expiry = default_expiry;
8120 } else {
8121 /* Nothing has been specified */
8122 expiry = default_expiry;
8126 /* Look for brackets */
8127 curi = contact;
8128 if (strchr(contact, '<') == NULL) /* No <, check for ; and strip it */
8129 strsep(&curi, ";"); /* This is Header options, not URI options */
8130 curi = get_in_brackets(contact);
8132 /* if they did not specify Contact: or Expires:, they are querying
8133 what we currently have stored as their contact address, so return
8136 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
8137 /* If we have an active registration, tell them when the registration is going to expire */
8138 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
8139 pvt->expiry = ast_sched_when(sched, peer->expire);
8140 return PARSE_REGISTER_QUERY;
8141 } else if (!strcasecmp(curi, "*") || !expiry) { /* Unregister this peer */
8142 /* This means remove all registrations and return OK */
8143 memset(&peer->addr, 0, sizeof(peer->addr));
8144 if (!AST_SCHED_DEL(sched, peer->expire)) {
8145 struct sip_peer *peer_ptr = peer;
8146 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8149 destroy_association(peer);
8151 register_peer_exten(peer, 0); /* Add extension from regexten= setting in sip.conf */
8152 peer->fullcontact[0] = '\0';
8153 peer->useragent[0] = '\0';
8154 peer->sipoptions = 0;
8155 peer->lastms = 0;
8157 if (option_verbose > 2)
8158 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", peer->name);
8159 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
8160 return PARSE_REGISTER_UPDATE;
8163 /* Store whatever we got as a contact from the client */
8164 ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));
8166 /* For the 200 OK, we should use the received contact */
8167 ast_string_field_build(pvt, our_contact, "<%s>", curi);
8169 /* Make sure it's a SIP URL */
8170 if (strncasecmp(curi, "sip:", 4)) {
8171 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", curi);
8172 } else
8173 curi += 4;
8174 /* Ditch q */
8175 curi = strsep(&curi, ";");
8176 /* Grab host */
8177 n = strchr(curi, '@');
8178 if (!n) {
8179 n = curi;
8180 curi = NULL;
8181 } else
8182 *n++ = '\0';
8183 pt = strchr(n, ':');
8184 if (pt) {
8185 *pt++ = '\0';
8186 port = atoi(pt);
8187 } else
8188 port = STANDARD_SIP_PORT;
8189 oldsin = peer->addr;
8190 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
8191 /* XXX This could block for a long time XXX */
8192 hp = ast_gethostbyname(n, &ahp);
8193 if (!hp) {
8194 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
8195 return PARSE_REGISTER_FAILED;
8197 peer->addr.sin_family = AF_INET;
8198 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
8199 peer->addr.sin_port = htons(port);
8200 } else {
8201 /* Don't trust the contact field. Just use what they came to us
8202 with */
8203 peer->addr = pvt->recv;
8206 /* Save SIP options profile */
8207 peer->sipoptions = pvt->sipoptions;
8209 if (curi && ast_strlen_zero(peer->username))
8210 ast_copy_string(peer->username, curi, sizeof(peer->username));
8212 if (!AST_SCHED_DEL(sched, peer->expire)) {
8213 struct sip_peer *peer_ptr = peer;
8214 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8216 if (expiry > max_expiry)
8217 expiry = max_expiry;
8218 if (expiry < min_expiry)
8219 expiry = min_expiry;
8220 if (ast_test_flag(&peer->flags[0], SIP_REALTIME)) {
8221 peer->expire = -1;
8222 } else {
8223 peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, ASTOBJ_REF(peer));
8224 if (peer->expire == -1) {
8225 struct sip_peer *peer_ptr = peer;
8226 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8229 pvt->expiry = expiry;
8230 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);
8231 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
8232 ast_db_put("SIP/Registry", peer->name, data);
8233 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
8235 /* Is this a new IP address for us? */
8236 if (inaddrcmp(&peer->addr, &oldsin)) {
8237 sip_poke_peer(peer);
8238 if (option_verbose > 2)
8239 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);
8240 register_peer_exten(peer, 1);
8243 /* Save User agent */
8244 useragent = get_header(req, "User-Agent");
8245 if (strcasecmp(useragent, peer->useragent)) { /* XXX copy if they are different ? */
8246 ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
8247 if (option_verbose > 3)
8248 ast_verbose(VERBOSE_PREFIX_3 "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
8250 return PARSE_REGISTER_UPDATE;
8253 /*! \brief Remove route from route list */
8254 static void free_old_route(struct sip_route *route)
8256 struct sip_route *next;
8258 while (route) {
8259 next = route->next;
8260 free(route);
8261 route = next;
8265 /*! \brief List all routes - mostly for debugging */
8266 static void list_route(struct sip_route *route)
8268 if (!route)
8269 ast_verbose("list_route: no route\n");
8270 else {
8271 for (;route; route = route->next)
8272 ast_verbose("list_route: hop: <%s>\n", route->hop);
8276 /*! \brief Build route list from Record-Route header */
8277 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
8279 struct sip_route *thishop, *head, *tail;
8280 int start = 0;
8281 int len;
8282 const char *rr, *contact, *c;
8284 /* Once a persistant route is set, don't fool with it */
8285 if (p->route && p->route_persistant) {
8286 if (option_debug)
8287 ast_log(LOG_DEBUG, "build_route: Retaining previous route: <%s>\n", p->route->hop);
8288 return;
8291 if (p->route) {
8292 free_old_route(p->route);
8293 p->route = NULL;
8296 /* We only want to create the route set the first time this is called */
8297 p->route_persistant = 1;
8299 /* Build a tailq, then assign it to p->route when done.
8300 * If backwards, we add entries from the head so they end up
8301 * in reverse order. However, we do need to maintain a correct
8302 * tail pointer because the contact is always at the end.
8304 head = NULL;
8305 tail = head;
8306 /* 1st we pass through all the hops in any Record-Route headers */
8307 for (;;) {
8308 /* Each Record-Route header */
8309 rr = __get_header(req, "Record-Route", &start);
8310 if (*rr == '\0')
8311 break;
8312 for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
8313 ++rr;
8314 len = strcspn(rr, ">") + 1;
8315 /* Make a struct route */
8316 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
8317 /* ast_calloc is not needed because all fields are initialized in this block */
8318 ast_copy_string(thishop->hop, rr, len);
8319 if (option_debug > 1)
8320 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
8321 /* Link in */
8322 if (backwards) {
8323 /* Link in at head so they end up in reverse order */
8324 thishop->next = head;
8325 head = thishop;
8326 /* If this was the first then it'll be the tail */
8327 if (!tail)
8328 tail = thishop;
8329 } else {
8330 thishop->next = NULL;
8331 /* Link in at the end */
8332 if (tail)
8333 tail->next = thishop;
8334 else
8335 head = thishop;
8336 tail = thishop;
8342 /* Only append the contact if we are dealing with a strict router */
8343 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop,";lr") == NULL) ) {
8344 /* 2nd append the Contact: if there is one */
8345 /* Can be multiple Contact headers, comma separated values - we just take the first */
8346 contact = get_header(req, "Contact");
8347 if (!ast_strlen_zero(contact)) {
8348 if (option_debug > 1)
8349 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
8350 /* Look for <: delimited address */
8351 c = strchr(contact, '<');
8352 if (c) {
8353 /* Take to > */
8354 ++c;
8355 len = strcspn(c, ">") + 1;
8356 } else {
8357 /* No <> - just take the lot */
8358 c = contact;
8359 len = strlen(contact) + 1;
8361 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
8362 /* ast_calloc is not needed because all fields are initialized in this block */
8363 ast_copy_string(thishop->hop, c, len);
8364 thishop->next = NULL;
8365 /* Goes at the end */
8366 if (tail)
8367 tail->next = thishop;
8368 else
8369 head = thishop;
8374 /* Store as new route */
8375 p->route = head;
8377 /* For debugging dump what we ended up with */
8378 if (sip_debug_test_pvt(p))
8379 list_route(p->route);
8382 AST_THREADSTORAGE(check_auth_buf, check_auth_buf_init);
8383 #define CHECK_AUTH_BUF_INITLEN 256
8385 /*! \brief Check user authorization from peer definition
8386 Some actions, like REGISTER and INVITEs from peers require
8387 authentication (if peer have secret set)
8388 \return 0 on success, non-zero on error
8390 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
8391 const char *secret, const char *md5secret, int sipmethod,
8392 char *uri, enum xmittype reliable, int ignore)
8394 const char *response = "407 Proxy Authentication Required";
8395 const char *reqheader = "Proxy-Authorization";
8396 const char *respheader = "Proxy-Authenticate";
8397 const char *authtoken;
8398 char a1_hash[256];
8399 char resp_hash[256]="";
8400 char *c;
8401 int wrongnonce = FALSE;
8402 int good_response;
8403 const char *usednonce = p->randdata;
8404 struct ast_dynamic_str *buf;
8405 int res;
8407 /* table of recognised keywords, and their value in the digest */
8408 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
8409 struct x {
8410 const char *key;
8411 const char *s;
8412 } *i, keys[] = {
8413 [K_RESP] = { "response=", "" },
8414 [K_URI] = { "uri=", "" },
8415 [K_USER] = { "username=", "" },
8416 [K_NONCE] = { "nonce=", "" },
8417 [K_LAST] = { NULL, NULL}
8420 /* Always OK if no secret */
8421 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
8422 return AUTH_SUCCESSFUL;
8423 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
8424 /* On a REGISTER, we have to use 401 and its family of headers instead of 407 and its family
8425 of headers -- GO SIP! Whoo hoo! Two things that do the same thing but are used in
8426 different circumstances! What a surprise. */
8427 response = "401 Unauthorized";
8428 reqheader = "Authorization";
8429 respheader = "WWW-Authenticate";
8431 authtoken = get_header(req, reqheader);
8432 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
8433 /* This is a retransmitted invite/register/etc, don't reconstruct authentication
8434 information */
8435 if (!reliable) {
8436 /* Resend message if this was NOT a reliable delivery. Otherwise the
8437 retransmission should get it */
8438 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
8439 /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
8440 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8442 return AUTH_CHALLENGE_SENT;
8443 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
8444 /* We have no auth, so issue challenge and request authentication */
8445 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
8446 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
8447 /* Schedule auto destroy in 32 seconds */
8448 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8449 return AUTH_CHALLENGE_SENT;
8452 /* --- We have auth, so check it */
8454 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
8455 an example in the spec of just what it is you're doing a hash on. */
8457 if (!(buf = ast_dynamic_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
8458 return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
8460 /* Make a copy of the response and parse it */
8461 res = ast_dynamic_str_thread_set(&buf, 0, &check_auth_buf, "%s", authtoken);
8463 if (res == AST_DYNSTR_BUILD_FAILED)
8464 return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
8466 c = buf->str;
8468 while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
8469 for (i = keys; i->key != NULL; i++) {
8470 const char *separator = ","; /* default */
8472 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
8473 continue;
8474 /* Found. Skip keyword, take text in quotes or up to the separator. */
8475 c += strlen(i->key);
8476 if (*c == '"') { /* in quotes. Skip first and look for last */
8477 c++;
8478 separator = "\"";
8480 i->s = c;
8481 strsep(&c, separator);
8482 break;
8484 if (i->key == NULL) /* not found, jump after space or comma */
8485 strsep(&c, " ,");
8488 /* Verify that digest username matches the username we auth as */
8489 if (strcmp(username, keys[K_USER].s)) {
8490 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
8491 username, keys[K_USER].s);
8492 /* Oops, we're trying something here */
8493 return AUTH_USERNAME_MISMATCH;
8496 /* Verify nonce from request matches our nonce. If not, send 401 with new nonce */
8497 if (strcasecmp(p->randdata, keys[K_NONCE].s)) { /* XXX it was 'n'casecmp ? */
8498 wrongnonce = TRUE;
8499 usednonce = keys[K_NONCE].s;
8502 if (!ast_strlen_zero(md5secret))
8503 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
8504 else {
8505 char a1[256];
8506 snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
8507 ast_md5_hash(a1_hash, a1);
8510 /* compute the expected response to compare with what we received */
8512 char a2[256];
8513 char a2_hash[256];
8514 char resp[256];
8516 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
8517 S_OR(keys[K_URI].s, uri));
8518 ast_md5_hash(a2_hash, a2);
8519 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
8520 ast_md5_hash(resp_hash, resp);
8523 good_response = keys[K_RESP].s &&
8524 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
8525 if (wrongnonce) {
8526 if (good_response) {
8527 if (sipdebug)
8528 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
8529 /* We got working auth token, based on stale nonce . */
8530 ast_string_field_build(p, randdata, "%08lx", ast_random());
8531 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
8532 } else {
8533 /* Everything was wrong, so give the device one more try with a new challenge */
8534 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
8535 if (sipdebug)
8536 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
8537 ast_string_field_build(p, randdata, "%08lx", ast_random());
8538 } else {
8539 if (sipdebug)
8540 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
8542 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
8545 /* Schedule auto destroy in 32 seconds */
8546 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8547 return AUTH_CHALLENGE_SENT;
8549 if (good_response) {
8550 append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
8551 return AUTH_SUCCESSFUL;
8554 /* Ok, we have a bad username/secret pair */
8555 /* Tell the UAS not to re-send this authentication data, because
8556 it will continue to fail
8559 return AUTH_SECRET_FAILED;
8562 /*! \brief Change onhold state of a peer using a pvt structure */
8563 static void sip_peer_hold(struct sip_pvt *p, int hold)
8565 struct sip_peer *peer = find_peer(p->peername, NULL, 1);
8567 if (!peer)
8568 return;
8570 /* If they put someone on hold, increment the value... otherwise decrement it */
8571 if (hold)
8572 peer->onHold++;
8573 else
8574 peer->onHold--;
8576 /* Request device state update */
8577 ast_device_state_changed("SIP/%s", peer->name);
8579 return;
8582 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
8583 \note If you add an "hint" priority to the extension in the dial plan,
8584 you will get notifications on device state changes */
8585 static int cb_extensionstate(char *context, char* exten, int state, void *data)
8587 struct sip_pvt *p = data;
8589 ast_mutex_lock(&p->lock);
8591 switch(state) {
8592 case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
8593 case AST_EXTENSION_REMOVED: /* Extension is gone */
8594 if (p->autokillid > -1 && sip_cancel_destroy(p)) /* Remove subscription expiry for renewals */
8595 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
8596 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); /* Delete subscription in 32 secs */
8597 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);
8598 p->stateid = -1;
8599 p->subscribed = NONE;
8600 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
8601 break;
8602 default: /* Tell user */
8603 p->laststate = state;
8604 break;
8606 if (p->subscribed != NONE) { /* Only send state NOTIFY if we know the format */
8607 if (!p->pendinginvite) {
8608 transmit_state_notify(p, state, 1, FALSE);
8609 } else {
8610 /* We already have a NOTIFY sent that is not answered. Queue the state up.
8611 if many state changes happen meanwhile, we will only send a notification of the last one */
8612 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
8615 if (option_verbose > 1)
8616 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,
8617 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
8620 ast_mutex_unlock(&p->lock);
8622 return 0;
8625 /*! \brief Send a fake 401 Unauthorized response when the administrator
8626 wants to hide the names of local users/peers from fishers
8628 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable)
8630 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
8631 transmit_response_with_auth(p, "401 Unauthorized", req, p->randdata, reliable, "WWW-Authenticate", 0);
8634 /*! \brief Verify registration of user
8635 - Registration is done in several steps, first a REGISTER without auth
8636 to get a challenge (nonce) then a second one with auth
8637 - Registration requests are only matched with peers that are marked as "dynamic"
8639 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
8640 struct sip_request *req, char *uri)
8642 enum check_auth_result res = AUTH_NOT_FOUND;
8643 struct sip_peer *peer;
8644 char tmp[256];
8645 char *name, *c;
8646 char *t;
8647 char *domain;
8649 /* Terminate URI */
8650 t = uri;
8651 while(*t && (*t > 32) && (*t != ';'))
8652 t++;
8653 *t = '\0';
8655 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
8656 if (pedanticsipchecking)
8657 ast_uri_decode(tmp);
8659 c = get_in_brackets(tmp);
8660 c = strsep(&c, ";"); /* Ditch ;user=phone */
8662 if (!strncasecmp(c, "sip:", 4)) {
8663 name = c + 4;
8664 } else {
8665 name = c;
8666 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
8669 /* Strip off the domain name */
8670 if ((c = strchr(name, '@'))) {
8671 *c++ = '\0';
8672 domain = c;
8673 if ((c = strchr(domain, ':'))) /* Remove :port */
8674 *c = '\0';
8675 if (!AST_LIST_EMPTY(&domain_list)) {
8676 if (!check_sip_domain(domain, NULL, 0)) {
8677 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
8678 return AUTH_UNKNOWN_DOMAIN;
8683 ast_string_field_set(p, exten, name);
8684 build_contact(p);
8685 peer = find_peer(name, NULL, 1);
8686 if (!(peer && ast_apply_ha(peer->ha, sin))) {
8687 /* Peer fails ACL check */
8688 if (peer) {
8689 ASTOBJ_UNREF(peer, sip_destroy_peer);
8690 peer = NULL;
8691 res = AUTH_ACL_FAILED;
8692 } else
8693 res = AUTH_NOT_FOUND;
8695 if (peer) {
8696 /* Set Frame packetization */
8697 if (p->rtp) {
8698 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
8699 p->autoframing = peer->autoframing;
8701 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
8702 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
8703 res = AUTH_PEER_NOT_DYNAMIC;
8704 } else {
8705 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
8706 transmit_response(p, "100 Trying", req);
8707 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, ast_test_flag(req, SIP_PKT_IGNORE)))) {
8708 if (sip_cancel_destroy(p))
8709 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
8711 /* We have a succesful registration attemp with proper authentication,
8712 now, update the peer */
8713 switch (parse_register_contact(p, peer, req)) {
8714 case PARSE_REGISTER_FAILED:
8715 ast_log(LOG_WARNING, "Failed to parse contact info\n");
8716 transmit_response_with_date(p, "400 Bad Request", req);
8717 peer->lastmsgssent = -1;
8718 res = 0;
8719 break;
8720 case PARSE_REGISTER_QUERY:
8721 transmit_response_with_date(p, "200 OK", req);
8722 peer->lastmsgssent = -1;
8723 res = 0;
8724 break;
8725 case PARSE_REGISTER_UPDATE:
8726 update_peer(peer, p->expiry);
8727 /* Say OK and ask subsystem to retransmit msg counter */
8728 transmit_response_with_date(p, "200 OK", req);
8729 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
8730 peer->lastmsgssent = -1;
8731 res = 0;
8732 break;
8737 if (!peer && autocreatepeer) {
8738 /* Create peer if we have autocreate mode enabled */
8739 peer = temp_peer(name);
8740 if (peer) {
8741 ASTOBJ_CONTAINER_LINK(&peerl, peer);
8742 if (sip_cancel_destroy(p))
8743 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
8744 switch (parse_register_contact(p, peer, req)) {
8745 case PARSE_REGISTER_FAILED:
8746 ast_log(LOG_WARNING, "Failed to parse contact info\n");
8747 transmit_response_with_date(p, "400 Bad Request", req);
8748 peer->lastmsgssent = -1;
8749 res = 0;
8750 break;
8751 case PARSE_REGISTER_QUERY:
8752 transmit_response_with_date(p, "200 OK", req);
8753 peer->lastmsgssent = -1;
8754 res = 0;
8755 break;
8756 case PARSE_REGISTER_UPDATE:
8757 /* Say OK and ask subsystem to retransmit msg counter */
8758 transmit_response_with_date(p, "200 OK", req);
8759 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
8760 peer->lastmsgssent = -1;
8761 res = 0;
8762 break;
8766 if (!res) {
8767 ast_device_state_changed("SIP/%s", peer->name);
8769 if (res < 0) {
8770 switch (res) {
8771 case AUTH_SECRET_FAILED:
8772 /* Wrong password in authentication. Go away, don't try again until you fixed it */
8773 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
8774 break;
8775 case AUTH_USERNAME_MISMATCH:
8776 /* Username and digest username does not match.
8777 Asterisk uses the From: username for authentication. We need the
8778 users to use the same authentication user name until we support
8779 proper authentication by digest auth name */
8780 transmit_response(p, "403 Authentication user name does not match account name", &p->initreq);
8781 break;
8782 case AUTH_NOT_FOUND:
8783 case AUTH_PEER_NOT_DYNAMIC:
8784 case AUTH_ACL_FAILED:
8785 if (global_alwaysauthreject) {
8786 transmit_fake_auth_response(p, &p->initreq, 1);
8787 } else {
8788 /* URI not found */
8789 if (res == AUTH_PEER_NOT_DYNAMIC)
8790 transmit_response(p, "403 Forbidden", &p->initreq);
8791 else
8792 transmit_response(p, "404 Not found", &p->initreq);
8794 break;
8795 default:
8796 break;
8799 if (peer)
8800 ASTOBJ_UNREF(peer, sip_destroy_peer);
8802 return res;
8805 /*! \brief Get referring dnis */
8806 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
8808 char tmp[256], *c, *a;
8809 struct sip_request *req;
8811 req = oreq;
8812 if (!req)
8813 req = &p->initreq;
8814 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
8815 if (ast_strlen_zero(tmp))
8816 return 0;
8817 c = get_in_brackets(tmp);
8818 if (strncasecmp(c, "sip:", 4)) {
8819 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", c);
8820 return -1;
8822 c += 4;
8823 a = c;
8824 strsep(&a, "@;"); /* trim anything after @ or ; */
8825 if (sip_debug_test_pvt(p))
8826 ast_verbose("RDNIS is %s\n", c);
8827 ast_string_field_set(p, rdnis, c);
8829 return 0;
8832 /*! \brief Find out who the call is for
8833 We use the INVITE uri to find out
8835 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
8837 char tmp[256] = "", *uri, *a;
8838 char tmpf[256] = "", *from;
8839 struct sip_request *req;
8840 char *colon;
8842 req = oreq;
8843 if (!req)
8844 req = &p->initreq;
8846 /* Find the request URI */
8847 if (req->rlPart2)
8848 ast_copy_string(tmp, req->rlPart2, sizeof(tmp));
8850 if (pedanticsipchecking)
8851 ast_uri_decode(tmp);
8853 uri = get_in_brackets(tmp);
8855 if (strncasecmp(uri, "sip:", 4)) {
8856 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
8857 return -1;
8859 uri += 4;
8861 /* Now find the From: caller ID and name */
8862 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
8863 if (!ast_strlen_zero(tmpf)) {
8864 if (pedanticsipchecking)
8865 ast_uri_decode(tmpf);
8866 from = get_in_brackets(tmpf);
8867 } else {
8868 from = NULL;
8871 if (!ast_strlen_zero(from)) {
8872 if (strncasecmp(from, "sip:", 4)) {
8873 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
8874 return -1;
8876 from += 4;
8877 if ((a = strchr(from, '@')))
8878 *a++ = '\0';
8879 else
8880 a = from; /* just a domain */
8881 from = strsep(&from, ";"); /* Remove userinfo options */
8882 a = strsep(&a, ";"); /* Remove URI options */
8883 ast_string_field_set(p, fromdomain, a);
8886 /* Skip any options and find the domain */
8888 /* Get the target domain */
8889 if ((a = strchr(uri, '@'))) {
8890 *a++ = '\0';
8891 } else { /* No username part */
8892 a = uri;
8893 uri = "s"; /* Set extension to "s" */
8895 colon = strchr(a, ':'); /* Remove :port */
8896 if (colon)
8897 *colon = '\0';
8899 uri = strsep(&uri, ";"); /* Remove userinfo options */
8900 a = strsep(&a, ";"); /* Remove URI options */
8902 ast_string_field_set(p, domain, a);
8904 if (!AST_LIST_EMPTY(&domain_list)) {
8905 char domain_context[AST_MAX_EXTENSION];
8907 domain_context[0] = '\0';
8908 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
8909 if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
8910 if (option_debug)
8911 ast_log(LOG_DEBUG, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
8912 return -2;
8915 /* If we have a context defined, overwrite the original context */
8916 if (!ast_strlen_zero(domain_context))
8917 ast_string_field_set(p, context, domain_context);
8920 /* If the request coming in is a subscription and subscribecontext has been specified use it */
8921 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
8922 ast_string_field_set(p, context, p->subscribecontext);
8924 if (sip_debug_test_pvt(p))
8925 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
8927 /* If this is a subscription we actually just need to see if a hint exists for the extension */
8928 if (req->method == SIP_SUBSCRIBE) {
8929 char hint[AST_MAX_EXTENSION];
8930 return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
8931 } else {
8932 /* Check the dialplan for the username part of the request URI,
8933 the domain will be stored in the SIPDOMAIN variable
8934 Since extensions.conf can have unescaped characters, try matching a decoded
8935 uri in addition to the non-decoded uri
8936 Return 0 if we have a matching extension */
8937 char *decoded_uri = ast_strdupa(uri);
8938 ast_uri_decode(decoded_uri);
8939 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)) ||
8940 !strcmp(uri, ast_pickup_ext())) {
8941 if (!oreq)
8942 ast_string_field_set(p, exten, uri);
8943 return 0;
8947 /* Return 1 for pickup extension or overlap dialling support (if we support it) */
8948 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
8949 ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) ||
8950 !strncmp(uri, ast_pickup_ext(), strlen(uri))) {
8951 return 1;
8954 return -1;
8957 /*! \brief Lock interface lock and find matching pvt lock
8958 - Their tag is fromtag, our tag is to-tag
8959 - This means that in some transactions, totag needs to be their tag :-)
8960 depending upon the direction
8962 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
8964 struct sip_pvt *sip_pvt_ptr;
8966 ast_mutex_lock(&iflock);
8968 if (option_debug > 3 && totag)
8969 ast_log(LOG_DEBUG, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
8971 /* Search interfaces and find the match */
8972 for (sip_pvt_ptr = iflist; sip_pvt_ptr; sip_pvt_ptr = sip_pvt_ptr->next) {
8973 if (!strcmp(sip_pvt_ptr->callid, callid)) {
8974 int match = 1;
8975 char *ourtag = sip_pvt_ptr->tag;
8977 /* Go ahead and lock it (and its owner) before returning */
8978 ast_mutex_lock(&sip_pvt_ptr->lock);
8980 /* Check if tags match. If not, this is not the call we want
8981 (With a forking SIP proxy, several call legs share the
8982 call id, but have different tags)
8984 if (pedanticsipchecking && (strcmp(fromtag, sip_pvt_ptr->theirtag) || (!ast_strlen_zero(totag) && strcmp(totag, ourtag))))
8985 match = 0;
8987 if (!match) {
8988 ast_mutex_unlock(&sip_pvt_ptr->lock);
8989 continue;
8992 if (option_debug > 3 && totag)
8993 ast_log(LOG_DEBUG, "Matched %s call - their tag is %s Our tag is %s\n",
8994 ast_test_flag(&sip_pvt_ptr->flags[0], SIP_OUTGOING) ? "OUTGOING": "INCOMING",
8995 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
8997 /* deadlock avoidance... */
8998 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
8999 ast_mutex_unlock(&sip_pvt_ptr->lock);
9000 usleep(1);
9001 ast_mutex_lock(&sip_pvt_ptr->lock);
9003 break;
9006 ast_mutex_unlock(&iflock);
9007 if (option_debug > 3 && !sip_pvt_ptr)
9008 ast_log(LOG_DEBUG, "Found no match for callid %s to-tag %s from-tag %s\n", callid, totag, fromtag);
9009 return sip_pvt_ptr;
9012 /*! \brief Call transfer support (the REFER method)
9013 * Extracts Refer headers into pvt dialog structure */
9014 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
9017 const char *p_referred_by = NULL;
9018 char *h_refer_to = NULL;
9019 char *h_referred_by = NULL;
9020 char *refer_to;
9021 const char *p_refer_to;
9022 char *referred_by_uri = NULL;
9023 char *ptr;
9024 struct sip_request *req = NULL;
9025 const char *transfer_context = NULL;
9026 struct sip_refer *referdata;
9029 req = outgoing_req;
9030 referdata = transferer->refer;
9032 if (!req)
9033 req = &transferer->initreq;
9035 p_refer_to = get_header(req, "Refer-To");
9036 if (ast_strlen_zero(p_refer_to)) {
9037 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
9038 return -2; /* Syntax error */
9040 h_refer_to = ast_strdupa(p_refer_to);
9041 refer_to = get_in_brackets(h_refer_to);
9042 if (pedanticsipchecking)
9043 ast_uri_decode(refer_to);
9045 if (strncasecmp(refer_to, "sip:", 4)) {
9046 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
9047 return -3;
9049 refer_to += 4; /* Skip sip: */
9051 /* Get referred by header if it exists */
9052 p_referred_by = get_header(req, "Referred-By");
9053 if (!ast_strlen_zero(p_referred_by)) {
9054 char *lessthan;
9055 h_referred_by = ast_strdupa(p_referred_by);
9056 if (pedanticsipchecking)
9057 ast_uri_decode(h_referred_by);
9059 /* Store referrer's caller ID name */
9060 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
9061 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
9062 *(lessthan - 1) = '\0'; /* Space */
9065 referred_by_uri = get_in_brackets(h_referred_by);
9066 if(strncasecmp(referred_by_uri, "sip:", 4)) {
9067 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
9068 referred_by_uri = (char *) NULL;
9069 } else {
9070 referred_by_uri += 4; /* Skip sip: */
9074 /* Check for arguments in the refer_to header */
9075 if ((ptr = strchr(refer_to, '?'))) { /* Search for arguments */
9076 *ptr++ = '\0';
9077 if (!strncasecmp(ptr, "REPLACES=", 9)) {
9078 char *to = NULL, *from = NULL;
9080 /* This is an attended transfer */
9081 referdata->attendedtransfer = 1;
9082 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
9083 ast_uri_decode(referdata->replaces_callid);
9084 if ((ptr = strchr(referdata->replaces_callid, ';'))) /* Find options */ {
9085 *ptr++ = '\0';
9088 if (ptr) {
9089 /* Find the different tags before we destroy the string */
9090 to = strcasestr(ptr, "to-tag=");
9091 from = strcasestr(ptr, "from-tag=");
9094 /* Grab the to header */
9095 if (to) {
9096 ptr = to + 7;
9097 if ((to = strchr(ptr, '&')))
9098 *to = '\0';
9099 if ((to = strchr(ptr, ';')))
9100 *to = '\0';
9101 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
9104 if (from) {
9105 ptr = from + 9;
9106 if ((to = strchr(ptr, '&')))
9107 *to = '\0';
9108 if ((to = strchr(ptr, ';')))
9109 *to = '\0';
9110 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
9113 if (option_debug > 1) {
9114 if (!pedanticsipchecking)
9115 ast_log(LOG_DEBUG,"Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
9116 else
9117 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>" );
9122 if ((ptr = strchr(refer_to, '@'))) { /* Separate domain */
9123 char *urioption = NULL, *domain;
9124 *ptr++ = '\0';
9126 if ((urioption = strchr(ptr, ';'))) /* Separate urioptions */
9127 *urioption++ = '\0';
9129 domain = ptr;
9130 if ((ptr = strchr(domain, ':'))) /* Remove :port */
9131 *ptr = '\0';
9133 /* Save the domain for the dial plan */
9134 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
9135 if (urioption)
9136 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
9139 if ((ptr = strchr(refer_to, ';'))) /* Remove options */
9140 *ptr = '\0';
9141 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
9143 if (referred_by_uri) {
9144 if ((ptr = strchr(referred_by_uri, ';'))) /* Remove options */
9145 *ptr = '\0';
9146 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
9147 } else {
9148 referdata->referred_by[0] = '\0';
9151 /* Determine transfer context */
9152 if (transferer->owner) /* Mimic behaviour in res_features.c */
9153 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
9155 /* By default, use the context in the channel sending the REFER */
9156 if (ast_strlen_zero(transfer_context)) {
9157 transfer_context = S_OR(transferer->owner->macrocontext,
9158 S_OR(transferer->context, default_context));
9161 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
9163 /* Either an existing extension or the parking extension */
9164 if (ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
9165 if (sip_debug_test_pvt(transferer)) {
9166 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
9168 /* We are ready to transfer to the extension */
9169 return 0;
9171 if (sip_debug_test_pvt(transferer))
9172 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
9174 /* Failure, we can't find this extension */
9175 return -1;
9179 /*! \brief Call transfer support (old way, deprecated by the IETF)--*/
9180 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
9182 char tmp[256] = "", *c, *a;
9183 struct sip_request *req = oreq ? oreq : &p->initreq;
9184 struct sip_refer *referdata = NULL;
9185 const char *transfer_context = NULL;
9187 if (!p->refer && !sip_refer_allocate(p))
9188 return -1;
9190 referdata = p->refer;
9192 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
9193 c = get_in_brackets(tmp);
9195 if (pedanticsipchecking)
9196 ast_uri_decode(c);
9198 if (strncasecmp(c, "sip:", 4)) {
9199 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
9200 return -1;
9202 c += 4;
9203 if ((a = strchr(c, ';'))) /* Remove arguments */
9204 *a = '\0';
9206 if ((a = strchr(c, '@'))) { /* Separate Domain */
9207 *a++ = '\0';
9208 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
9211 if (sip_debug_test_pvt(p))
9212 ast_verbose("Looking for %s in %s\n", c, p->context);
9214 if (p->owner) /* Mimic behaviour in res_features.c */
9215 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
9217 /* By default, use the context in the channel sending the REFER */
9218 if (ast_strlen_zero(transfer_context)) {
9219 transfer_context = S_OR(p->owner->macrocontext,
9220 S_OR(p->context, default_context));
9222 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
9223 /* This is a blind transfer */
9224 if (option_debug)
9225 ast_log(LOG_DEBUG,"SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
9226 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
9227 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
9228 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
9229 referdata->refer_call = NULL;
9230 /* Set new context */
9231 ast_string_field_set(p, context, transfer_context);
9232 return 0;
9233 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
9234 return 1;
9237 return -1;
9239 /*! \brief check Via: header for hostname, port and rport request/answer */
9240 static void check_via(struct sip_pvt *p, const struct sip_request *req)
9242 char via[512];
9243 char *c, *pt;
9244 struct hostent *hp;
9245 struct ast_hostent ahp;
9247 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
9249 /* Work on the leftmost value of the topmost Via header */
9250 c = strchr(via, ',');
9251 if (c)
9252 *c = '\0';
9254 /* Check for rport */
9255 c = strstr(via, ";rport");
9256 if (c && (c[6] != '=')) /* rport query, not answer */
9257 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
9259 c = strchr(via, ';');
9260 if (c)
9261 *c = '\0';
9263 c = strchr(via, ' ');
9264 if (c) {
9265 *c = '\0';
9266 c = ast_skip_blanks(c+1);
9267 if (strcasecmp(via, "SIP/2.0/UDP")) {
9268 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
9269 return;
9271 pt = strchr(c, ':');
9272 if (pt)
9273 *pt++ = '\0'; /* remember port pointer */
9274 hp = ast_gethostbyname(c, &ahp);
9275 if (!hp) {
9276 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
9277 return;
9279 memset(&p->sa, 0, sizeof(p->sa));
9280 p->sa.sin_family = AF_INET;
9281 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
9282 p->sa.sin_port = htons(pt ? atoi(pt) : STANDARD_SIP_PORT);
9284 if (sip_debug_test_pvt(p)) {
9285 const struct sockaddr_in *dst = sip_real_dst(p);
9286 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
9291 /*! \brief Get caller id name from SIP headers */
9292 static char *get_calleridname(const char *input, char *output, size_t outputsize)
9294 const char *end = strchr(input,'<'); /* first_bracket */
9295 const char *tmp = strchr(input,'"'); /* first quote */
9296 int bytes = 0;
9297 int maxbytes = outputsize - 1;
9299 if (!end || end == input) /* we require a part in brackets */
9300 return NULL;
9302 end--; /* move just before "<" */
9304 if (tmp && tmp <= end) {
9305 /* The quote (tmp) precedes the bracket (end+1).
9306 * Find the matching quote and return the content.
9308 end = strchr(tmp+1, '"');
9309 if (!end)
9310 return NULL;
9311 bytes = (int) (end - tmp);
9312 /* protect the output buffer */
9313 if (bytes > maxbytes)
9314 bytes = maxbytes;
9315 ast_copy_string(output, tmp + 1, bytes);
9316 } else {
9317 /* No quoted string, or it is inside brackets. */
9318 /* clear the empty characters in the begining*/
9319 input = ast_skip_blanks(input);
9320 /* clear the empty characters in the end */
9321 while(*end && *end < 33 && end > input)
9322 end--;
9323 if (end >= input) {
9324 bytes = (int) (end - input) + 2;
9325 /* protect the output buffer */
9326 if (bytes > maxbytes)
9327 bytes = maxbytes;
9328 ast_copy_string(output, input, bytes);
9329 } else
9330 return NULL;
9332 return output;
9335 /*! \brief Get caller id number from Remote-Party-ID header field
9336 * Returns true if number should be restricted (privacy setting found)
9337 * output is set to NULL if no number found
9339 static int get_rpid_num(const char *input, char *output, int maxlen)
9341 char *start;
9342 char *end;
9344 start = strchr(input,':');
9345 if (!start) {
9346 output[0] = '\0';
9347 return 0;
9349 start++;
9351 /* we found "number" */
9352 ast_copy_string(output,start,maxlen);
9353 output[maxlen-1] = '\0';
9355 end = strchr(output,'@');
9356 if (end)
9357 *end = '\0';
9358 else
9359 output[0] = '\0';
9360 if (strstr(input,"privacy=full") || strstr(input,"privacy=uri"))
9361 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
9363 return 0;
9367 /*! \brief Check if matching user or peer is defined
9368 Match user on From: user name and peer on IP/port
9369 This is used on first invite (not re-invites) and subscribe requests
9370 \return 0 on success, non-zero on failure
9372 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
9373 int sipmethod, char *uri, enum xmittype reliable,
9374 struct sockaddr_in *sin, struct sip_peer **authpeer)
9376 struct sip_user *user = NULL;
9377 struct sip_peer *peer;
9378 char from[256], *c;
9379 char *of;
9380 char rpid_num[50];
9381 const char *rpid;
9382 enum check_auth_result res = AUTH_SUCCESSFUL;
9383 char *t;
9384 char calleridname[50];
9385 int debug=sip_debug_test_addr(sin);
9386 struct ast_variable *tmpvar = NULL, *v = NULL;
9387 char *uri2 = ast_strdupa(uri);
9389 /* Terminate URI */
9390 t = uri2;
9391 while (*t && *t > 32 && *t != ';')
9392 t++;
9393 *t = '\0';
9394 ast_copy_string(from, get_header(req, "From"), sizeof(from)); /* XXX bug in original code, overwrote string */
9395 if (pedanticsipchecking)
9396 ast_uri_decode(from);
9397 /* XXX here tries to map the username for invite things */
9398 memset(calleridname, 0, sizeof(calleridname));
9399 get_calleridname(from, calleridname, sizeof(calleridname));
9400 if (calleridname[0])
9401 ast_string_field_set(p, cid_name, calleridname);
9403 rpid = get_header(req, "Remote-Party-ID");
9404 memset(rpid_num, 0, sizeof(rpid_num));
9405 if (!ast_strlen_zero(rpid))
9406 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
9408 of = get_in_brackets(from);
9409 if (ast_strlen_zero(p->exten)) {
9410 t = uri2;
9411 if (!strncasecmp(t, "sip:", 4))
9412 t+= 4;
9413 ast_string_field_set(p, exten, t);
9414 t = strchr(p->exten, '@');
9415 if (t)
9416 *t = '\0';
9417 if (ast_strlen_zero(p->our_contact))
9418 build_contact(p);
9420 /* save the URI part of the From header */
9421 ast_string_field_set(p, from, of);
9422 if (strncasecmp(of, "sip:", 4)) {
9423 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
9424 } else
9425 of += 4;
9426 /* Get just the username part */
9427 if ((c = strchr(of, '@'))) {
9428 char *tmp;
9429 *c = '\0';
9430 if ((c = strchr(of, ':')))
9431 *c = '\0';
9432 tmp = ast_strdupa(of);
9433 /* We need to be able to handle auth-headers looking like
9434 <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
9436 tmp = strsep(&tmp, ";");
9437 if (ast_is_shrinkable_phonenumber(tmp))
9438 ast_shrink_phone_number(tmp);
9439 ast_string_field_set(p, cid_num, tmp);
9442 if (!authpeer) /* If we are looking for a peer, don't check the user objects (or realtime) */
9443 user = find_user(of, 1);
9445 /* Find user based on user name in the from header */
9446 if (user && ast_apply_ha(user->ha, sin)) {
9447 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
9448 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9449 /* copy channel vars */
9450 for (v = user->chanvars ; v ; v = v->next) {
9451 if ((tmpvar = ast_variable_new(v->name, v->value))) {
9452 tmpvar->next = p->chanvars;
9453 p->chanvars = tmpvar;
9456 p->prefs = user->prefs;
9457 /* Set Frame packetization */
9458 if (p->rtp) {
9459 ast_rtp_codec_setpref(p->rtp, &p->prefs);
9460 p->autoframing = user->autoframing;
9462 /* replace callerid if rpid found, and not restricted */
9463 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
9464 char *tmp;
9465 if (*calleridname)
9466 ast_string_field_set(p, cid_name, calleridname);
9467 tmp = ast_strdupa(rpid_num);
9468 if (ast_is_shrinkable_phonenumber(tmp))
9469 ast_shrink_phone_number(tmp);
9470 ast_string_field_set(p, cid_num, tmp);
9473 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE) );
9475 if (!(res = check_auth(p, req, user->name, user->secret, user->md5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
9476 if (sip_cancel_destroy(p))
9477 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
9478 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
9479 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9480 /* Copy SIP extensions profile from INVITE */
9481 if (p->sipoptions)
9482 user->sipoptions = p->sipoptions;
9484 /* If we have a call limit, set flag */
9485 if (user->call_limit)
9486 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
9487 if (!ast_strlen_zero(user->context))
9488 ast_string_field_set(p, context, user->context);
9489 if (!ast_strlen_zero(user->cid_num)) {
9490 char *tmp = ast_strdupa(user->cid_num);
9491 if (ast_is_shrinkable_phonenumber(tmp))
9492 ast_shrink_phone_number(tmp);
9493 ast_string_field_set(p, cid_num, tmp);
9495 if (!ast_strlen_zero(user->cid_name))
9496 ast_string_field_set(p, cid_name, user->cid_name);
9497 ast_string_field_set(p, username, user->name);
9498 ast_string_field_set(p, peername, user->name);
9499 ast_string_field_set(p, peersecret, user->secret);
9500 ast_string_field_set(p, peermd5secret, user->md5secret);
9501 ast_string_field_set(p, subscribecontext, user->subscribecontext);
9502 ast_string_field_set(p, accountcode, user->accountcode);
9503 ast_string_field_set(p, language, user->language);
9504 ast_string_field_set(p, mohsuggest, user->mohsuggest);
9505 ast_string_field_set(p, mohinterpret, user->mohinterpret);
9506 p->allowtransfer = user->allowtransfer;
9507 p->amaflags = user->amaflags;
9508 p->callgroup = user->callgroup;
9509 p->pickupgroup = user->pickupgroup;
9510 if (user->callingpres) /* User callingpres setting will override RPID header */
9511 p->callingpres = user->callingpres;
9513 /* Set default codec settings for this call */
9514 p->capability = user->capability; /* User codec choice */
9515 p->jointcapability = user->capability; /* Our codecs */
9516 if (p->peercapability) /* AND with peer's codecs */
9517 p->jointcapability &= p->peercapability;
9518 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
9519 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
9520 p->noncodeccapability |= AST_RTP_DTMF;
9521 else
9522 p->noncodeccapability &= ~AST_RTP_DTMF;
9523 p->jointnoncodeccapability = p->noncodeccapability;
9524 if (p->t38.peercapability)
9525 p->t38.jointcapability &= p->t38.peercapability;
9526 p->maxcallbitrate = user->maxcallbitrate;
9527 /* If we do not support video, remove video from call structure */
9528 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
9529 ast_rtp_destroy(p->vrtp);
9530 p->vrtp = NULL;
9533 if (user && debug)
9534 ast_verbose("Found user '%s'\n", user->name);
9535 } else {
9536 if (user) {
9537 if (!authpeer && debug)
9538 ast_verbose("Found user '%s', but fails host access\n", user->name);
9539 ASTOBJ_UNREF(user,sip_destroy_user);
9541 user = NULL;
9544 if (!user) {
9545 /* If we didn't find a user match, check for peers */
9546 if (sipmethod == SIP_SUBSCRIBE)
9547 /* For subscribes, match on peer name only */
9548 peer = find_peer(of, NULL, 1);
9549 else
9550 /* Look for peer based on the IP address we received data from */
9551 /* If peer is registered from this IP address or have this as a default
9552 IP address, this call is from the peer
9554 peer = find_peer(NULL, &p->recv, 1);
9556 if (peer) {
9557 /* Set Frame packetization */
9558 if (p->rtp) {
9559 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
9560 p->autoframing = peer->autoframing;
9562 if (debug)
9563 ast_verbose("Found peer '%s'\n", peer->name);
9565 /* Take the peer */
9566 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
9567 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9569 /* Copy SIP extensions profile to peer */
9570 if (p->sipoptions)
9571 peer->sipoptions = p->sipoptions;
9573 /* replace callerid if rpid found, and not restricted */
9574 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
9575 char *tmp = ast_strdupa(rpid_num);
9576 if (*calleridname)
9577 ast_string_field_set(p, cid_name, calleridname);
9578 if (ast_is_shrinkable_phonenumber(tmp))
9579 ast_shrink_phone_number(tmp);
9580 ast_string_field_set(p, cid_num, tmp);
9582 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
9584 ast_string_field_set(p, peersecret, peer->secret);
9585 ast_string_field_set(p, peermd5secret, peer->md5secret);
9586 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
9587 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
9588 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
9589 if (peer->callingpres) /* Peer calling pres setting will override RPID */
9590 p->callingpres = peer->callingpres;
9591 if (peer->maxms && peer->lastms)
9592 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
9593 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
9594 /* Pretend there is no required authentication */
9595 ast_string_field_free(p, peersecret);
9596 ast_string_field_free(p, peermd5secret);
9598 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
9599 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
9600 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9601 /* If we have a call limit, set flag */
9602 if (peer->call_limit)
9603 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
9604 ast_string_field_set(p, peername, peer->name);
9605 ast_string_field_set(p, authname, peer->name);
9607 /* copy channel vars */
9608 for (v = peer->chanvars ; v ; v = v->next) {
9609 if ((tmpvar = ast_variable_new(v->name, v->value))) {
9610 tmpvar->next = p->chanvars;
9611 p->chanvars = tmpvar;
9614 if (authpeer) {
9615 (*authpeer) = ASTOBJ_REF(peer); /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
9618 if (!ast_strlen_zero(peer->username)) {
9619 ast_string_field_set(p, username, peer->username);
9620 /* Use the default username for authentication on outbound calls */
9621 /* XXX this takes the name from the caller... can we override ? */
9622 ast_string_field_set(p, authname, peer->username);
9624 if (!ast_strlen_zero(peer->cid_num)) {
9625 char *tmp = ast_strdupa(peer->cid_num);
9626 if (ast_is_shrinkable_phonenumber(tmp))
9627 ast_shrink_phone_number(tmp);
9628 ast_string_field_set(p, cid_num, tmp);
9630 if (!ast_strlen_zero(peer->cid_name))
9631 ast_string_field_set(p, cid_name, peer->cid_name);
9632 ast_string_field_set(p, fullcontact, peer->fullcontact);
9633 if (!ast_strlen_zero(peer->context))
9634 ast_string_field_set(p, context, peer->context);
9635 ast_string_field_set(p, peersecret, peer->secret);
9636 ast_string_field_set(p, peermd5secret, peer->md5secret);
9637 ast_string_field_set(p, language, peer->language);
9638 ast_string_field_set(p, accountcode, peer->accountcode);
9639 p->amaflags = peer->amaflags;
9640 p->callgroup = peer->callgroup;
9641 p->pickupgroup = peer->pickupgroup;
9642 p->capability = peer->capability;
9643 p->prefs = peer->prefs;
9644 p->jointcapability = peer->capability;
9645 if (p->peercapability)
9646 p->jointcapability &= p->peercapability;
9647 p->maxcallbitrate = peer->maxcallbitrate;
9648 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
9649 ast_rtp_destroy(p->vrtp);
9650 p->vrtp = NULL;
9652 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
9653 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
9654 p->noncodeccapability |= AST_RTP_DTMF;
9655 else
9656 p->noncodeccapability &= ~AST_RTP_DTMF;
9657 p->jointnoncodeccapability = p->noncodeccapability;
9658 if (p->t38.peercapability)
9659 p->t38.jointcapability &= p->t38.peercapability;
9661 ASTOBJ_UNREF(peer, sip_destroy_peer);
9662 } else {
9663 if (debug)
9664 ast_verbose("Found no matching peer or user for '%s:%d'\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
9666 /* do we allow guests? */
9667 if (!global_allowguest) {
9668 if (global_alwaysauthreject)
9669 res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
9670 else
9671 res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
9672 } else if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
9673 char *tmp = ast_strdupa(rpid_num);
9674 if (*calleridname)
9675 ast_string_field_set(p, cid_name, calleridname);
9676 if (ast_is_shrinkable_phonenumber(tmp))
9677 ast_shrink_phone_number(tmp);
9678 ast_string_field_set(p, cid_num, tmp);
9684 if (user)
9685 ASTOBJ_UNREF(user, sip_destroy_user);
9686 return res;
9689 /*! \brief Find user
9690 If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
9692 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
9694 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
9697 /*! \brief Get text out of a SIP MESSAGE packet */
9698 static int get_msg_text(char *buf, int len, struct sip_request *req)
9700 int x;
9701 int y;
9703 buf[0] = '\0';
9704 y = len - strlen(buf) - 5;
9705 if (y < 0)
9706 y = 0;
9707 for (x=0;x<req->lines;x++) {
9708 strncat(buf, req->line[x], y); /* safe */
9709 y -= strlen(req->line[x]) + 1;
9710 if (y < 0)
9711 y = 0;
9712 if (y != 0)
9713 strcat(buf, "\n"); /* safe */
9715 return 0;
9719 /*! \brief Receive SIP MESSAGE method messages
9720 \note We only handle messages within current calls currently
9721 Reference: RFC 3428 */
9722 static void receive_message(struct sip_pvt *p, struct sip_request *req)
9724 char buf[1024];
9725 struct ast_frame f;
9726 const char *content_type = get_header(req, "Content-Type");
9728 if (strcmp(content_type, "text/plain")) { /* No text/plain attachment */
9729 transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
9730 if (!p->owner)
9731 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
9732 return;
9735 if (get_msg_text(buf, sizeof(buf), req)) {
9736 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
9737 transmit_response(p, "202 Accepted", req);
9738 if (!p->owner)
9739 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
9740 return;
9743 if (p->owner) {
9744 if (sip_debug_test_pvt(p))
9745 ast_verbose("Message received: '%s'\n", buf);
9746 memset(&f, 0, sizeof(f));
9747 f.frametype = AST_FRAME_TEXT;
9748 f.subclass = 0;
9749 f.offset = 0;
9750 f.data = buf;
9751 f.datalen = strlen(buf);
9752 ast_queue_frame(p->owner, &f);
9753 transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
9754 } else { /* Message outside of a call, we do not support that */
9755 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);
9756 transmit_response(p, "405 Method Not Allowed", req); /* Good enough, or? */
9757 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
9759 return;
9762 /*! \brief CLI Command to show calls within limits set by call_limit */
9763 static int sip_show_inuse(int fd, int argc, char *argv[])
9765 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
9766 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
9767 char ilimits[40];
9768 char iused[40];
9769 int showall = FALSE;
9771 if (argc < 3)
9772 return RESULT_SHOWUSAGE;
9774 if (argc == 4 && !strcmp(argv[3],"all"))
9775 showall = TRUE;
9777 ast_cli(fd, FORMAT, "* User name", "In use", "Limit");
9778 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
9779 ASTOBJ_RDLOCK(iterator);
9780 if (iterator->call_limit)
9781 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
9782 else
9783 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
9784 snprintf(iused, sizeof(iused), "%d", iterator->inUse);
9785 if (showall || iterator->call_limit)
9786 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
9787 ASTOBJ_UNLOCK(iterator);
9788 } while (0) );
9790 ast_cli(fd, FORMAT, "* Peer name", "In use", "Limit");
9792 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
9793 ASTOBJ_RDLOCK(iterator);
9794 if (iterator->call_limit)
9795 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
9796 else
9797 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
9798 snprintf(iused, sizeof(iused), "%d/%d", iterator->inUse, iterator->inRinging);
9799 if (showall || iterator->call_limit)
9800 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
9801 ASTOBJ_UNLOCK(iterator);
9802 } while (0) );
9804 return RESULT_SUCCESS;
9805 #undef FORMAT
9806 #undef FORMAT2
9809 /*! \brief Convert transfer mode to text string */
9810 static char *transfermode2str(enum transfermodes mode)
9812 if (mode == TRANSFER_OPENFORALL)
9813 return "open";
9814 else if (mode == TRANSFER_CLOSED)
9815 return "closed";
9816 return "strict";
9819 /*! \brief Convert NAT setting to text string */
9820 static char *nat2str(int nat)
9822 switch(nat) {
9823 case SIP_NAT_NEVER:
9824 return "No";
9825 case SIP_NAT_ROUTE:
9826 return "Route";
9827 case SIP_NAT_ALWAYS:
9828 return "Always";
9829 case SIP_NAT_RFC3581:
9830 return "RFC3581";
9831 default:
9832 return "Unknown";
9836 /*! \brief Report Peer status in character string
9837 * \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
9839 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
9841 int res = 0;
9842 if (peer->maxms) {
9843 if (peer->lastms < 0) {
9844 ast_copy_string(status, "UNREACHABLE", statuslen);
9845 } else if (peer->lastms > peer->maxms) {
9846 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
9847 res = 1;
9848 } else if (peer->lastms) {
9849 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
9850 res = 1;
9851 } else {
9852 ast_copy_string(status, "UNKNOWN", statuslen);
9854 } else {
9855 ast_copy_string(status, "Unmonitored", statuslen);
9856 /* Checking if port is 0 */
9857 res = -1;
9859 return res;
9862 /*! \brief CLI Command 'SIP Show Users' */
9863 static int sip_show_users(int fd, int argc, char *argv[])
9865 regex_t regexbuf;
9866 int havepattern = FALSE;
9868 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
9870 switch (argc) {
9871 case 5:
9872 if (!strcasecmp(argv[3], "like")) {
9873 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
9874 return RESULT_SHOWUSAGE;
9875 havepattern = TRUE;
9876 } else
9877 return RESULT_SHOWUSAGE;
9878 case 3:
9879 break;
9880 default:
9881 return RESULT_SHOWUSAGE;
9884 ast_cli(fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
9885 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
9886 ASTOBJ_RDLOCK(iterator);
9888 if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
9889 ASTOBJ_UNLOCK(iterator);
9890 continue;
9893 ast_cli(fd, FORMAT, iterator->name,
9894 iterator->secret,
9895 iterator->accountcode,
9896 iterator->context,
9897 iterator->ha ? "Yes" : "No",
9898 nat2str(ast_test_flag(&iterator->flags[0], SIP_NAT)));
9899 ASTOBJ_UNLOCK(iterator);
9900 } while (0)
9903 if (havepattern)
9904 regfree(&regexbuf);
9906 return RESULT_SUCCESS;
9907 #undef FORMAT
9910 static char mandescr_show_peers[] =
9911 "Description: Lists SIP peers in text format with details on current status.\n"
9912 "Variables: \n"
9913 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
9915 /*! \brief Show SIP peers in the manager API */
9916 /* Inspired from chan_iax2 */
9917 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
9919 const char *id = astman_get_header(m,"ActionID");
9920 const char *a[] = {"sip", "show", "peers"};
9921 char idtext[256] = "";
9922 int total = 0;
9924 if (!ast_strlen_zero(id))
9925 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
9927 astman_send_ack(s, m, "Peer status list will follow");
9928 /* List the peers in separate manager events */
9929 _sip_show_peers(-1, &total, s, m, 3, a);
9930 /* Send final confirmation */
9931 astman_append(s,
9932 "Event: PeerlistComplete\r\n"
9933 "ListItems: %d\r\n"
9934 "%s"
9935 "\r\n", total, idtext);
9936 return 0;
9939 /*! \brief CLI Show Peers command */
9940 static int sip_show_peers(int fd, int argc, char *argv[])
9942 return _sip_show_peers(fd, NULL, NULL, NULL, argc, (const char **) argv);
9945 /*! \brief _sip_show_peers: Execute sip show peers command */
9946 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
9948 regex_t regexbuf;
9949 int havepattern = FALSE;
9951 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %-10s\n"
9952 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %-10s\n"
9954 char name[256];
9955 int total_peers = 0;
9956 int peers_mon_online = 0;
9957 int peers_mon_offline = 0;
9958 int peers_unmon_offline = 0;
9959 int peers_unmon_online = 0;
9960 const char *id;
9961 char idtext[256] = "";
9962 int realtimepeers;
9964 realtimepeers = ast_check_realtime("sippeers");
9966 if (s) { /* Manager - get ActionID */
9967 id = astman_get_header(m,"ActionID");
9968 if (!ast_strlen_zero(id))
9969 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
9972 switch (argc) {
9973 case 5:
9974 if (!strcasecmp(argv[3], "like")) {
9975 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
9976 return RESULT_SHOWUSAGE;
9977 havepattern = TRUE;
9978 } else
9979 return RESULT_SHOWUSAGE;
9980 case 3:
9981 break;
9982 default:
9983 return RESULT_SHOWUSAGE;
9986 if (!s) /* Normal list */
9987 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
9989 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
9990 char status[20] = "";
9991 char srch[2000];
9992 char pstatus;
9994 ASTOBJ_RDLOCK(iterator);
9996 if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
9997 ASTOBJ_UNLOCK(iterator);
9998 continue;
10001 if (!ast_strlen_zero(iterator->username) && !s)
10002 snprintf(name, sizeof(name), "%s/%s", iterator->name, iterator->username);
10003 else
10004 ast_copy_string(name, iterator->name, sizeof(name));
10006 pstatus = peer_status(iterator, status, sizeof(status));
10007 if (pstatus == 1)
10008 peers_mon_online++;
10009 else if (pstatus == 0)
10010 peers_mon_offline++;
10011 else {
10012 if (iterator->addr.sin_port == 0)
10013 peers_unmon_offline++;
10014 else
10015 peers_unmon_online++;
10018 snprintf(srch, sizeof(srch), FORMAT, name,
10019 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
10020 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ", /* Dynamic or not? */
10021 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
10022 iterator->ha ? " A " : " ", /* permit/deny */
10023 ntohs(iterator->addr.sin_port), status,
10024 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
10026 if (!s) {/* Normal CLI list */
10027 ast_cli(fd, FORMAT, name,
10028 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
10029 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ", /* Dynamic or not? */
10030 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
10031 iterator->ha ? " A " : " ", /* permit/deny */
10033 ntohs(iterator->addr.sin_port), status,
10034 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
10035 } else { /* Manager format */
10036 /* The names here need to be the same as other channels */
10037 astman_append(s,
10038 "Event: PeerEntry\r\n%s"
10039 "Channeltype: SIP\r\n"
10040 "ObjectName: %s\r\n"
10041 "ChanObjectType: peer\r\n" /* "peer" or "user" */
10042 "IPaddress: %s\r\n"
10043 "IPport: %d\r\n"
10044 "Dynamic: %s\r\n"
10045 "Natsupport: %s\r\n"
10046 "VideoSupport: %s\r\n"
10047 "ACL: %s\r\n"
10048 "Status: %s\r\n"
10049 "RealtimeDevice: %s\r\n\r\n",
10050 idtext,
10051 iterator->name,
10052 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "-none-",
10053 ntohs(iterator->addr.sin_port),
10054 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no", /* Dynamic or not? */
10055 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? "yes" : "no", /* NAT=yes? */
10056 ast_test_flag(&iterator->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no", /* VIDEOSUPPORT=yes? */
10057 iterator->ha ? "yes" : "no", /* permit/deny */
10058 status,
10059 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "yes":"no") : "no");
10062 ASTOBJ_UNLOCK(iterator);
10064 total_peers++;
10065 } while(0) );
10067 if (!s)
10068 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
10069 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
10071 if (havepattern)
10072 regfree(&regexbuf);
10074 if (total)
10075 *total = total_peers;
10078 return RESULT_SUCCESS;
10079 #undef FORMAT
10080 #undef FORMAT2
10083 /*! \brief List all allocated SIP Objects (realtime or static) */
10084 static int sip_show_objects(int fd, int argc, char *argv[])
10086 char tmp[256];
10087 if (argc != 3)
10088 return RESULT_SHOWUSAGE;
10089 ast_cli(fd, "-= User objects: %d static, %d realtime =-\n\n", suserobjs, ruserobjs);
10090 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &userl);
10091 ast_cli(fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
10092 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &peerl);
10093 ast_cli(fd, "-= Registry objects: %d =-\n\n", regobjs);
10094 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &regl);
10095 return RESULT_SUCCESS;
10097 /*! \brief Print call group and pickup group */
10098 static void print_group(int fd, ast_group_t group, int crlf)
10100 char buf[256];
10101 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
10104 /*! \brief Convert DTMF mode to printable string */
10105 static const char *dtmfmode2str(int mode)
10107 switch (mode) {
10108 case SIP_DTMF_RFC2833:
10109 return "rfc2833";
10110 case SIP_DTMF_INFO:
10111 return "info";
10112 case SIP_DTMF_INBAND:
10113 return "inband";
10114 case SIP_DTMF_AUTO:
10115 return "auto";
10117 return "<error>";
10120 /*! \brief Convert Insecure setting to printable string */
10121 static const char *insecure2str(int port, int invite)
10123 if (port && invite)
10124 return "port,invite";
10125 else if (port)
10126 return "port";
10127 else if (invite)
10128 return "invite";
10129 else
10130 return "no";
10133 /*! \brief Destroy disused contexts between reloads
10134 Only used in reload_config so the code for regcontext doesn't get ugly
10136 static void cleanup_stale_contexts(char *new, char *old)
10138 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
10140 while ((oldcontext = strsep(&old, "&"))) {
10141 stalecontext = '\0';
10142 ast_copy_string(newlist, new, sizeof(newlist));
10143 stringp = newlist;
10144 while ((newcontext = strsep(&stringp, "&"))) {
10145 if (strcmp(newcontext, oldcontext) == 0) {
10146 /* This is not the context you're looking for */
10147 stalecontext = '\0';
10148 break;
10149 } else if (strcmp(newcontext, oldcontext)) {
10150 stalecontext = oldcontext;
10154 if (stalecontext)
10155 ast_context_destroy(ast_context_find(stalecontext), "SIP");
10159 /*! \brief Remove temporary realtime objects from memory (CLI) */
10160 static int sip_prune_realtime(int fd, int argc, char *argv[])
10162 struct sip_peer *peer;
10163 struct sip_user *user;
10164 int pruneuser = FALSE;
10165 int prunepeer = FALSE;
10166 int multi = FALSE;
10167 char *name = NULL;
10168 regex_t regexbuf;
10170 switch (argc) {
10171 case 4:
10172 if (!strcasecmp(argv[3], "user"))
10173 return RESULT_SHOWUSAGE;
10174 if (!strcasecmp(argv[3], "peer"))
10175 return RESULT_SHOWUSAGE;
10176 if (!strcasecmp(argv[3], "like"))
10177 return RESULT_SHOWUSAGE;
10178 if (!strcasecmp(argv[3], "all")) {
10179 multi = TRUE;
10180 pruneuser = prunepeer = TRUE;
10181 } else {
10182 pruneuser = prunepeer = TRUE;
10183 name = argv[3];
10185 break;
10186 case 5:
10187 if (!strcasecmp(argv[4], "like"))
10188 return RESULT_SHOWUSAGE;
10189 if (!strcasecmp(argv[3], "all"))
10190 return RESULT_SHOWUSAGE;
10191 if (!strcasecmp(argv[3], "like")) {
10192 multi = TRUE;
10193 name = argv[4];
10194 pruneuser = prunepeer = TRUE;
10195 } else if (!strcasecmp(argv[3], "user")) {
10196 pruneuser = TRUE;
10197 if (!strcasecmp(argv[4], "all"))
10198 multi = TRUE;
10199 else
10200 name = argv[4];
10201 } else if (!strcasecmp(argv[3], "peer")) {
10202 prunepeer = TRUE;
10203 if (!strcasecmp(argv[4], "all"))
10204 multi = TRUE;
10205 else
10206 name = argv[4];
10207 } else
10208 return RESULT_SHOWUSAGE;
10209 break;
10210 case 6:
10211 if (strcasecmp(argv[4], "like"))
10212 return RESULT_SHOWUSAGE;
10213 if (!strcasecmp(argv[3], "user")) {
10214 pruneuser = TRUE;
10215 name = argv[5];
10216 } else if (!strcasecmp(argv[3], "peer")) {
10217 prunepeer = TRUE;
10218 name = argv[5];
10219 } else
10220 return RESULT_SHOWUSAGE;
10221 break;
10222 default:
10223 return RESULT_SHOWUSAGE;
10226 if (multi && name) {
10227 if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
10228 return RESULT_SHOWUSAGE;
10231 if (multi) {
10232 if (prunepeer) {
10233 int pruned = 0;
10235 ASTOBJ_CONTAINER_WRLOCK(&peerl);
10236 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
10237 ASTOBJ_RDLOCK(iterator);
10238 if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
10239 ASTOBJ_UNLOCK(iterator);
10240 continue;
10242 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10243 ASTOBJ_MARK(iterator);
10244 pruned++;
10246 ASTOBJ_UNLOCK(iterator);
10247 } while (0) );
10248 if (pruned) {
10249 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
10250 ast_cli(fd, "%d peers pruned.\n", pruned);
10251 } else
10252 ast_cli(fd, "No peers found to prune.\n");
10253 ASTOBJ_CONTAINER_UNLOCK(&peerl);
10255 if (pruneuser) {
10256 int pruned = 0;
10258 ASTOBJ_CONTAINER_WRLOCK(&userl);
10259 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
10260 ASTOBJ_RDLOCK(iterator);
10261 if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
10262 ASTOBJ_UNLOCK(iterator);
10263 continue;
10265 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10266 ASTOBJ_MARK(iterator);
10267 pruned++;
10269 ASTOBJ_UNLOCK(iterator);
10270 } while (0) );
10271 if (pruned) {
10272 ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, sip_destroy_user);
10273 ast_cli(fd, "%d users pruned.\n", pruned);
10274 } else
10275 ast_cli(fd, "No users found to prune.\n");
10276 ASTOBJ_CONTAINER_UNLOCK(&userl);
10278 } else {
10279 if (prunepeer) {
10280 if ((peer = ASTOBJ_CONTAINER_FIND_UNLINK(&peerl, name))) {
10281 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10282 ast_cli(fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
10283 ASTOBJ_CONTAINER_LINK(&peerl, peer);
10284 } else
10285 ast_cli(fd, "Peer '%s' pruned.\n", name);
10286 ASTOBJ_UNREF(peer, sip_destroy_peer);
10287 } else
10288 ast_cli(fd, "Peer '%s' not found.\n", name);
10290 if (pruneuser) {
10291 if ((user = ASTOBJ_CONTAINER_FIND_UNLINK(&userl, name))) {
10292 if (!ast_test_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10293 ast_cli(fd, "User '%s' is not a Realtime user, cannot be pruned.\n", name);
10294 ASTOBJ_CONTAINER_LINK(&userl, user);
10295 } else
10296 ast_cli(fd, "User '%s' pruned.\n", name);
10297 ASTOBJ_UNREF(user, sip_destroy_user);
10298 } else
10299 ast_cli(fd, "User '%s' not found.\n", name);
10303 return RESULT_SUCCESS;
10306 /*! \brief Print codec list from preference to CLI/manager */
10307 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
10309 int x, codec;
10311 for(x = 0; x < 32 ; x++) {
10312 codec = ast_codec_pref_index(pref, x);
10313 if (!codec)
10314 break;
10315 ast_cli(fd, "%s", ast_getformatname(codec));
10316 ast_cli(fd, ":%d", pref->framing[x]);
10317 if (x < 31 && ast_codec_pref_index(pref, x + 1))
10318 ast_cli(fd, ",");
10320 if (!x)
10321 ast_cli(fd, "none");
10324 /*! \brief Print domain mode to cli */
10325 static const char *domain_mode_to_text(const enum domain_mode mode)
10327 switch (mode) {
10328 case SIP_DOMAIN_AUTO:
10329 return "[Automatic]";
10330 case SIP_DOMAIN_CONFIG:
10331 return "[Configured]";
10334 return "";
10337 /*! \brief CLI command to list local domains */
10338 static int sip_show_domains(int fd, int argc, char *argv[])
10340 struct domain *d;
10341 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
10343 if (AST_LIST_EMPTY(&domain_list)) {
10344 ast_cli(fd, "SIP Domain support not enabled.\n\n");
10345 return RESULT_SUCCESS;
10346 } else {
10347 ast_cli(fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
10348 AST_LIST_LOCK(&domain_list);
10349 AST_LIST_TRAVERSE(&domain_list, d, list)
10350 ast_cli(fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
10351 domain_mode_to_text(d->mode));
10352 AST_LIST_UNLOCK(&domain_list);
10353 ast_cli(fd, "\n");
10354 return RESULT_SUCCESS;
10357 #undef FORMAT
10359 static char mandescr_show_peer[] =
10360 "Description: Show one SIP peer with details on current status.\n"
10361 "Variables: \n"
10362 " Peer: <name> The peer name you want to check.\n"
10363 " ActionID: <id> Optional action ID for this AMI transaction.\n";
10365 /*! \brief Show SIP peers in the manager API */
10366 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
10368 const char *a[4];
10369 const char *peer;
10370 int ret;
10372 peer = astman_get_header(m,"Peer");
10373 if (ast_strlen_zero(peer)) {
10374 astman_send_error(s, m, "Peer: <name> missing.\n");
10375 return 0;
10377 a[0] = "sip";
10378 a[1] = "show";
10379 a[2] = "peer";
10380 a[3] = peer;
10382 ret = _sip_show_peer(1, -1, s, m, 4, a);
10383 astman_append(s, "\r\n\r\n" );
10384 return ret;
10389 /*! \brief Show one peer in detail */
10390 static int sip_show_peer(int fd, int argc, char *argv[])
10392 return _sip_show_peer(0, fd, NULL, NULL, argc, (const char **) argv);
10395 /*! \brief Show one peer in detail (main function) */
10396 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
10398 char status[30] = "";
10399 char cbuf[256];
10400 struct sip_peer *peer;
10401 char codec_buf[512];
10402 struct ast_codec_pref *pref;
10403 struct ast_variable *v;
10404 struct sip_auth *auth;
10405 int x = 0, codec = 0, load_realtime;
10406 int realtimepeers;
10408 realtimepeers = ast_check_realtime("sippeers");
10410 if (argc < 4)
10411 return RESULT_SHOWUSAGE;
10413 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
10414 peer = find_peer(argv[3], NULL, load_realtime);
10415 if (s) { /* Manager */
10416 if (peer) {
10417 const char *id = astman_get_header(m,"ActionID");
10419 astman_append(s, "Response: Success\r\n");
10420 if (!ast_strlen_zero(id))
10421 astman_append(s, "ActionID: %s\r\n",id);
10422 } else {
10423 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.\n", argv[3]);
10424 astman_send_error(s, m, cbuf);
10425 return 0;
10428 if (peer && type==0 ) { /* Normal listing */
10429 ast_cli(fd,"\n\n");
10430 ast_cli(fd, " * Name : %s\n", peer->name);
10431 if (realtimepeers) { /* Realtime is enabled */
10432 ast_cli(fd, " Realtime peer: %s\n", ast_test_flag(&peer->flags[0], SIP_REALTIME) ? "Yes, cached" : "No");
10434 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
10435 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
10436 for (auth = peer->auth; auth; auth = auth->next) {
10437 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
10438 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
10440 ast_cli(fd, " Context : %s\n", peer->context);
10441 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
10442 ast_cli(fd, " Language : %s\n", peer->language);
10443 if (!ast_strlen_zero(peer->accountcode))
10444 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
10445 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
10446 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
10447 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
10448 if (!ast_strlen_zero(peer->fromuser))
10449 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
10450 if (!ast_strlen_zero(peer->fromdomain))
10451 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
10452 ast_cli(fd, " Callgroup : ");
10453 print_group(fd, peer->callgroup, 0);
10454 ast_cli(fd, " Pickupgroup : ");
10455 print_group(fd, peer->pickupgroup, 0);
10456 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
10457 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
10458 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
10459 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
10460 ast_cli(fd, " Dynamic : %s\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Yes":"No"));
10461 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
10462 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
10463 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
10464 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)));
10465 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
10466 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
10467 ast_cli(fd, " T38 pt UDPTL : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL)?"Yes":"No");
10468 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10469 ast_cli(fd, " T38 pt RTP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_RTP)?"Yes":"No");
10470 ast_cli(fd, " T38 pt TCP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_TCP)?"Yes":"No");
10471 #endif
10472 ast_cli(fd, " CanReinvite : %s\n", ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Yes":"No");
10473 ast_cli(fd, " PromiscRedir : %s\n", ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Yes":"No");
10474 ast_cli(fd, " User=Phone : %s\n", ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Yes":"No");
10475 ast_cli(fd, " Video Support: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Yes":"No");
10476 ast_cli(fd, " Trust RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_TRUSTRPID) ? "Yes" : "No");
10477 ast_cli(fd, " Send RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_SENDRPID) ? "Yes" : "No");
10478 ast_cli(fd, " Subscriptions: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
10479 ast_cli(fd, " Overlap dial : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
10481 /* - is enumerated */
10482 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
10483 ast_cli(fd, " LastMsg : %d\n", peer->lastmsg);
10484 ast_cli(fd, " ToHost : %s\n", peer->tohost);
10485 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));
10486 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
10487 if (!ast_strlen_zero(global_regcontext))
10488 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
10489 ast_cli(fd, " Def. Username: %s\n", peer->username);
10490 ast_cli(fd, " SIP Options : ");
10491 if (peer->sipoptions) {
10492 int lastoption = -1;
10493 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
10494 if (sip_options[x].id != lastoption) {
10495 if (peer->sipoptions & sip_options[x].id)
10496 ast_cli(fd, "%s ", sip_options[x].text);
10497 lastoption = x;
10500 } else
10501 ast_cli(fd, "(none)");
10503 ast_cli(fd, "\n");
10504 ast_cli(fd, " Codecs : ");
10505 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
10506 ast_cli(fd, "%s\n", codec_buf);
10507 ast_cli(fd, " Codec Order : (");
10508 print_codec_to_cli(fd, &peer->prefs);
10509 ast_cli(fd, ")\n");
10511 ast_cli(fd, " Auto-Framing: %s \n", peer->autoframing ? "Yes" : "No");
10512 ast_cli(fd, " Status : ");
10513 peer_status(peer, status, sizeof(status));
10514 ast_cli(fd, "%s\n",status);
10515 ast_cli(fd, " Useragent : %s\n", peer->useragent);
10516 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
10517 if (peer->chanvars) {
10518 ast_cli(fd, " Variables :\n");
10519 for (v = peer->chanvars ; v ; v = v->next)
10520 ast_cli(fd, " %s = %s\n", v->name, v->value);
10522 ast_cli(fd,"\n");
10523 ASTOBJ_UNREF(peer,sip_destroy_peer);
10524 } else if (peer && type == 1) { /* manager listing */
10525 char buf[256];
10526 astman_append(s, "Channeltype: SIP\r\n");
10527 astman_append(s, "ObjectName: %s\r\n", peer->name);
10528 astman_append(s, "ChanObjectType: peer\r\n");
10529 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
10530 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
10531 astman_append(s, "Context: %s\r\n", peer->context);
10532 astman_append(s, "Language: %s\r\n", peer->language);
10533 if (!ast_strlen_zero(peer->accountcode))
10534 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
10535 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
10536 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
10537 if (!ast_strlen_zero(peer->fromuser))
10538 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
10539 if (!ast_strlen_zero(peer->fromdomain))
10540 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
10541 astman_append(s, "Callgroup: ");
10542 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->callgroup));
10543 astman_append(s, "Pickupgroup: ");
10544 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->pickupgroup));
10545 astman_append(s, "VoiceMailbox: %s\r\n", peer->mailbox);
10546 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
10547 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
10548 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
10549 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
10550 astman_append(s, "Dynamic: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Y":"N"));
10551 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
10552 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched,peer->expire));
10553 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)));
10554 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
10555 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
10556 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
10557 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
10558 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
10559 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
10561 /* - is enumerated */
10562 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
10563 astman_append(s, "SIPLastMsg: %d\r\n", peer->lastmsg);
10564 astman_append(s, "ToHost: %s\r\n", peer->tohost);
10565 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));
10566 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));
10567 astman_append(s, "Default-Username: %s\r\n", peer->username);
10568 if (!ast_strlen_zero(global_regcontext))
10569 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
10570 astman_append(s, "Codecs: ");
10571 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
10572 astman_append(s, "%s\r\n", codec_buf);
10573 astman_append(s, "CodecOrder: ");
10574 pref = &peer->prefs;
10575 for(x = 0; x < 32 ; x++) {
10576 codec = ast_codec_pref_index(pref,x);
10577 if (!codec)
10578 break;
10579 astman_append(s, "%s", ast_getformatname(codec));
10580 if (x < 31 && ast_codec_pref_index(pref,x+1))
10581 astman_append(s, ",");
10584 astman_append(s, "\r\n");
10585 astman_append(s, "Status: ");
10586 peer_status(peer, status, sizeof(status));
10587 astman_append(s, "%s\r\n", status);
10588 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
10589 astman_append(s, "Reg-Contact : %s\r\n", peer->fullcontact);
10590 if (peer->chanvars) {
10591 for (v = peer->chanvars ; v ; v = v->next) {
10592 astman_append(s, "ChanVariable:\n");
10593 astman_append(s, " %s,%s\r\n", v->name, v->value);
10597 ASTOBJ_UNREF(peer,sip_destroy_peer);
10599 } else {
10600 ast_cli(fd,"Peer %s not found.\n", argv[3]);
10601 ast_cli(fd,"\n");
10604 return RESULT_SUCCESS;
10607 /*! \brief Show one user in detail */
10608 static int sip_show_user(int fd, int argc, char *argv[])
10610 char cbuf[256];
10611 struct sip_user *user;
10612 struct ast_variable *v;
10613 int load_realtime;
10615 if (argc < 4)
10616 return RESULT_SHOWUSAGE;
10618 /* Load from realtime storage? */
10619 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
10621 user = find_user(argv[3], load_realtime);
10622 if (user) {
10623 ast_cli(fd,"\n\n");
10624 ast_cli(fd, " * Name : %s\n", user->name);
10625 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
10626 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
10627 ast_cli(fd, " Context : %s\n", user->context);
10628 ast_cli(fd, " Language : %s\n", user->language);
10629 if (!ast_strlen_zero(user->accountcode))
10630 ast_cli(fd, " Accountcode : %s\n", user->accountcode);
10631 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
10632 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
10633 ast_cli(fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
10634 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
10635 ast_cli(fd, " Call limit : %d\n", user->call_limit);
10636 ast_cli(fd, " Callgroup : ");
10637 print_group(fd, user->callgroup, 0);
10638 ast_cli(fd, " Pickupgroup : ");
10639 print_group(fd, user->pickupgroup, 0);
10640 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
10641 ast_cli(fd, " ACL : %s\n", (user->ha?"Yes":"No"));
10642 ast_cli(fd, " Codec Order : (");
10643 print_codec_to_cli(fd, &user->prefs);
10644 ast_cli(fd, ")\n");
10646 ast_cli(fd, " Auto-Framing: %s \n", user->autoframing ? "Yes" : "No");
10647 if (user->chanvars) {
10648 ast_cli(fd, " Variables :\n");
10649 for (v = user->chanvars ; v ; v = v->next)
10650 ast_cli(fd, " %s = %s\n", v->name, v->value);
10652 ast_cli(fd,"\n");
10653 ASTOBJ_UNREF(user,sip_destroy_user);
10654 } else {
10655 ast_cli(fd,"User %s not found.\n", argv[3]);
10656 ast_cli(fd,"\n");
10659 return RESULT_SUCCESS;
10662 /*! \brief Show SIP Registry (registrations with other SIP proxies */
10663 static int sip_show_registry(int fd, int argc, char *argv[])
10665 #define FORMAT2 "%-30.30s %-12.12s %8.8s %-20.20s %-25.25s\n"
10666 #define FORMAT "%-30.30s %-12.12s %8d %-20.20s %-25.25s\n"
10667 char host[80];
10668 char tmpdat[256];
10669 struct tm tm;
10672 if (argc != 3)
10673 return RESULT_SHOWUSAGE;
10674 ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State", "Reg.Time");
10675 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
10676 ASTOBJ_RDLOCK(iterator);
10677 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
10678 if (iterator->regtime) {
10679 ast_localtime(&iterator->regtime, &tm, NULL);
10680 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
10681 } else {
10682 tmpdat[0] = 0;
10684 ast_cli(fd, FORMAT, host, iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
10685 ASTOBJ_UNLOCK(iterator);
10686 } while(0));
10687 return RESULT_SUCCESS;
10688 #undef FORMAT
10689 #undef FORMAT2
10692 /*! \brief List global settings for the SIP channel */
10693 static int sip_show_settings(int fd, int argc, char *argv[])
10695 int realtimepeers;
10696 int realtimeusers;
10697 char codec_buf[SIPBUFSIZE];
10699 realtimepeers = ast_check_realtime("sippeers");
10700 realtimeusers = ast_check_realtime("sipusers");
10702 if (argc != 3)
10703 return RESULT_SHOWUSAGE;
10704 ast_cli(fd, "\n\nGlobal Settings:\n");
10705 ast_cli(fd, "----------------\n");
10706 ast_cli(fd, " SIP Port: %d\n", ntohs(bindaddr.sin_port));
10707 ast_cli(fd, " Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
10708 ast_cli(fd, " Videosupport: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "Yes" : "No");
10709 ast_cli(fd, " AutoCreatePeer: %s\n", autocreatepeer ? "Yes" : "No");
10710 ast_cli(fd, " Allow unknown access: %s\n", global_allowguest ? "Yes" : "No");
10711 ast_cli(fd, " Allow subscriptions: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
10712 ast_cli(fd, " Allow overlap dialing: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
10713 ast_cli(fd, " Promsic. redir: %s\n", ast_test_flag(&global_flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
10714 ast_cli(fd, " SIP domain support: %s\n", AST_LIST_EMPTY(&domain_list) ? "No" : "Yes");
10715 ast_cli(fd, " Call to non-local dom.: %s\n", allow_external_domains ? "Yes" : "No");
10716 ast_cli(fd, " URI user is phone no: %s\n", ast_test_flag(&global_flags[0], SIP_USEREQPHONE) ? "Yes" : "No");
10717 ast_cli(fd, " Our auth realm %s\n", global_realm);
10718 ast_cli(fd, " Realm. auth: %s\n", authl ? "Yes": "No");
10719 ast_cli(fd, " Always auth rejects: %s\n", global_alwaysauthreject ? "Yes" : "No");
10720 ast_cli(fd, " Call limit peers only: %s\n", global_limitonpeers ? "Yes" : "No");
10721 ast_cli(fd, " Direct RTP setup: %s\n", global_directrtpsetup ? "Yes" : "No");
10722 ast_cli(fd, " User Agent: %s\n", global_useragent);
10723 ast_cli(fd, " MWI checking interval: %d secs\n", global_mwitime);
10724 ast_cli(fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
10725 ast_cli(fd, " Caller ID: %s\n", default_callerid);
10726 ast_cli(fd, " From: Domain: %s\n", default_fromdomain);
10727 ast_cli(fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
10728 ast_cli(fd, " Call Events: %s\n", global_callevents ? "On" : "Off");
10729 ast_cli(fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
10730 ast_cli(fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
10731 ast_cli(fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
10732 ast_cli(fd, " T38 fax pt UDPTL: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_UDPTL) ? "Yes" : "No");
10733 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10734 ast_cli(fd, " T38 fax pt RTP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_RTP) ? "Yes" : "No");
10735 ast_cli(fd, " T38 fax pt TCP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_TCP) ? "Yes" : "No");
10736 #endif
10737 ast_cli(fd, " RFC2833 Compensation: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE) ? "Yes" : "No");
10738 if (!realtimepeers && !realtimeusers)
10739 ast_cli(fd, " SIP realtime: Disabled\n" );
10740 else
10741 ast_cli(fd, " SIP realtime: Enabled\n" );
10743 ast_cli(fd, "\nGlobal Signalling Settings:\n");
10744 ast_cli(fd, "---------------------------\n");
10745 ast_cli(fd, " Codecs: ");
10746 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
10747 ast_cli(fd, "%s\n", codec_buf);
10748 ast_cli(fd, " Codec Order: ");
10749 print_codec_to_cli(fd, &default_prefs);
10750 ast_cli(fd, "\n");
10751 ast_cli(fd, " T1 minimum: %d\n", global_t1min);
10752 ast_cli(fd, " Relax DTMF: %s\n", global_relaxdtmf ? "Yes" : "No");
10753 ast_cli(fd, " Compact SIP headers: %s\n", compactheaders ? "Yes" : "No");
10754 ast_cli(fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
10755 ast_cli(fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
10756 ast_cli(fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
10757 ast_cli(fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
10758 ast_cli(fd, " DNS SRV lookup: %s\n", srvlookup ? "Yes" : "No");
10759 ast_cli(fd, " Pedantic SIP support: %s\n", pedanticsipchecking ? "Yes" : "No");
10760 ast_cli(fd, " Reg. min duration %d secs\n", min_expiry);
10761 ast_cli(fd, " Reg. max duration: %d secs\n", max_expiry);
10762 ast_cli(fd, " Reg. default duration: %d secs\n", default_expiry);
10763 ast_cli(fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
10764 ast_cli(fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
10765 ast_cli(fd, " Notify ringing state: %s\n", global_notifyringing ? "Yes" : "No");
10766 ast_cli(fd, " Notify hold state: %s\n", global_notifyhold ? "Yes" : "No");
10767 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(global_allowtransfer));
10768 ast_cli(fd, " Max Call Bitrate: %d kbps\r\n", default_maxcallbitrate);
10769 ast_cli(fd, " Auto-Framing: %s \r\n", global_autoframing ? "Yes" : "No");
10770 ast_cli(fd, "\nDefault Settings:\n");
10771 ast_cli(fd, "-----------------\n");
10772 ast_cli(fd, " Context: %s\n", default_context);
10773 ast_cli(fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
10774 ast_cli(fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
10775 ast_cli(fd, " Qualify: %d\n", default_qualify);
10776 ast_cli(fd, " Use ClientCode: %s\n", ast_test_flag(&global_flags[0], SIP_USECLIENTCODE) ? "Yes" : "No");
10777 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" );
10778 ast_cli(fd, " Language: %s\n", S_OR(default_language, "(Defaults to English)"));
10779 ast_cli(fd, " MOH Interpret: %s\n", default_mohinterpret);
10780 ast_cli(fd, " MOH Suggest: %s\n", default_mohsuggest);
10781 ast_cli(fd, " Voice Mail Extension: %s\n", default_vmexten);
10784 if (realtimepeers || realtimeusers) {
10785 ast_cli(fd, "\nRealtime SIP Settings:\n");
10786 ast_cli(fd, "----------------------\n");
10787 ast_cli(fd, " Realtime Peers: %s\n", realtimepeers ? "Yes" : "No");
10788 ast_cli(fd, " Realtime Users: %s\n", realtimeusers ? "Yes" : "No");
10789 ast_cli(fd, " Cache Friends: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? "Yes" : "No");
10790 ast_cli(fd, " Update: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) ? "Yes" : "No");
10791 ast_cli(fd, " Ignore Reg. Expire: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) ? "Yes" : "No");
10792 ast_cli(fd, " Save sys. name: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME) ? "Yes" : "No");
10793 ast_cli(fd, " Auto Clear: %d\n", global_rtautoclear);
10795 ast_cli(fd, "\n----\n");
10796 return RESULT_SUCCESS;
10799 /*! \brief Show subscription type in string format */
10800 static const char *subscription_type2str(enum subscriptiontype subtype)
10802 int i;
10804 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10805 if (subscription_types[i].type == subtype) {
10806 return subscription_types[i].text;
10809 return subscription_types[0].text;
10812 /*! \brief Find subscription type in array */
10813 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
10815 int i;
10817 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10818 if (subscription_types[i].type == subtype) {
10819 return &subscription_types[i];
10822 return &subscription_types[0];
10825 /*! \brief Show active SIP channels */
10826 static int sip_show_channels(int fd, int argc, char *argv[])
10828 return __sip_show_channels(fd, argc, argv, 0);
10831 /*! \brief Show active SIP subscriptions */
10832 static int sip_show_subscriptions(int fd, int argc, char *argv[])
10834 return __sip_show_channels(fd, argc, argv, 1);
10837 /*! \brief SIP show channels CLI (main function) */
10838 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions)
10840 #define FORMAT3 "%-15.15s %-10.10s %-11.11s %-15.15s %-13.13s %-15.15s %-10.10s\n"
10841 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-15.15s %-7.7s %-15.15s\n"
10842 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s\n"
10843 struct sip_pvt *cur;
10844 int numchans = 0;
10845 char *referstatus = NULL;
10847 if (argc != 3)
10848 return RESULT_SHOWUSAGE;
10849 ast_mutex_lock(&iflock);
10850 cur = iflist;
10851 if (!subscriptions)
10852 ast_cli(fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Seq (Tx/Rx)", "Format", "Hold", "Last Message");
10853 else
10854 ast_cli(fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox");
10855 for (; cur; cur = cur->next) {
10856 referstatus = "";
10857 if (cur->refer) { /* SIP transfer in progress */
10858 referstatus = referstatus2str(cur->refer->status);
10860 if (cur->subscribed == NONE && !subscriptions) {
10861 char formatbuf[SIPBUFSIZE/2];
10862 ast_cli(fd, FORMAT, ast_inet_ntoa(cur->sa.sin_addr),
10863 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10864 cur->callid,
10865 cur->ocseq, cur->icseq,
10866 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
10867 ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD) ? "Yes" : "No",
10868 ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY) ? "(d)" : "",
10869 cur->lastmsg ,
10870 referstatus
10872 numchans++;
10874 if (cur->subscribed != NONE && subscriptions) {
10875 ast_cli(fd, FORMAT3, ast_inet_ntoa(cur->sa.sin_addr),
10876 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10877 cur->callid,
10878 /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
10879 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
10880 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
10881 subscription_type2str(cur->subscribed),
10882 cur->subscribed == MWI_NOTIFICATION ? (cur->relatedpeer ? cur->relatedpeer->mailbox : "<none>") : "<none>"
10884 numchans++;
10887 ast_mutex_unlock(&iflock);
10888 if (!subscriptions)
10889 ast_cli(fd, "%d active SIP channel%s\n", numchans, (numchans != 1) ? "s" : "");
10890 else
10891 ast_cli(fd, "%d active SIP subscription%s\n", numchans, (numchans != 1) ? "s" : "");
10892 return RESULT_SUCCESS;
10893 #undef FORMAT
10894 #undef FORMAT2
10895 #undef FORMAT3
10898 /*! \brief Support routine for 'sip show channel' CLI */
10899 static char *complete_sipch(const char *line, const char *word, int pos, int state)
10901 int which=0;
10902 struct sip_pvt *cur;
10903 char *c = NULL;
10904 int wordlen = strlen(word);
10906 if (pos != 3) {
10907 return NULL;
10910 ast_mutex_lock(&iflock);
10911 for (cur = iflist; cur; cur = cur->next) {
10912 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
10913 c = ast_strdup(cur->callid);
10914 break;
10917 ast_mutex_unlock(&iflock);
10918 return c;
10921 /*! \brief Do completion on peer name */
10922 static char *complete_sip_peer(const char *word, int state, int flags2)
10924 char *result = NULL;
10925 int wordlen = strlen(word);
10926 int which = 0;
10928 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !result, do {
10929 /* locking of the object is not required because only the name and flags are being compared */
10930 if (!strncasecmp(word, iterator->name, wordlen) &&
10931 (!flags2 || ast_test_flag(&iterator->flags[1], flags2)) &&
10932 ++which > state)
10933 result = ast_strdup(iterator->name);
10934 } while(0) );
10935 return result;
10938 /*! \brief Support routine for 'sip show peer' CLI */
10939 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
10941 if (pos == 3)
10942 return complete_sip_peer(word, state, 0);
10944 return NULL;
10947 /*! \brief Support routine for 'sip debug peer' CLI */
10948 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state)
10950 if (pos == 3)
10951 return complete_sip_peer(word, state, 0);
10953 return NULL;
10956 /*! \brief Do completion on user name */
10957 static char *complete_sip_user(const char *word, int state, int flags2)
10959 char *result = NULL;
10960 int wordlen = strlen(word);
10961 int which = 0;
10963 ASTOBJ_CONTAINER_TRAVERSE(&userl, !result, do {
10964 /* locking of the object is not required because only the name and flags are being compared */
10965 if (!strncasecmp(word, iterator->name, wordlen)) {
10966 if (flags2 && !ast_test_flag(&iterator->flags[1], flags2))
10967 continue;
10968 if (++which > state) {
10969 result = ast_strdup(iterator->name);
10972 } while(0) );
10973 return result;
10976 /*! \brief Support routine for 'sip show user' CLI */
10977 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
10979 if (pos == 3)
10980 return complete_sip_user(word, state, 0);
10982 return NULL;
10985 /*! \brief Support routine for 'sip notify' CLI */
10986 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
10988 char *c = NULL;
10990 if (pos == 2) {
10991 int which = 0;
10992 char *cat = NULL;
10993 int wordlen = strlen(word);
10995 /* do completion for notify type */
10997 if (!notify_types)
10998 return NULL;
11000 while ( (cat = ast_category_browse(notify_types, cat)) ) {
11001 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
11002 c = ast_strdup(cat);
11003 break;
11006 return c;
11009 if (pos > 2)
11010 return complete_sip_peer(word, state, 0);
11012 return NULL;
11015 /*! \brief Support routine for 'sip prune realtime peer' CLI */
11016 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state)
11018 if (pos == 4)
11019 return complete_sip_peer(word, state, SIP_PAGE2_RTCACHEFRIENDS);
11020 return NULL;
11023 /*! \brief Support routine for 'sip prune realtime user' CLI */
11024 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state)
11026 if (pos == 4)
11027 return complete_sip_user(word, state, SIP_PAGE2_RTCACHEFRIENDS);
11029 return NULL;
11032 /*! \brief Show details of one active dialog */
11033 static int sip_show_channel(int fd, int argc, char *argv[])
11035 struct sip_pvt *cur;
11036 size_t len;
11037 int found = 0;
11039 if (argc != 4)
11040 return RESULT_SHOWUSAGE;
11041 len = strlen(argv[3]);
11042 ast_mutex_lock(&iflock);
11043 for (cur = iflist; cur; cur = cur->next) {
11044 if (!strncasecmp(cur->callid, argv[3], len)) {
11045 char formatbuf[SIPBUFSIZE/2];
11046 ast_cli(fd,"\n");
11047 if (cur->subscribed != NONE)
11048 ast_cli(fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
11049 else
11050 ast_cli(fd, " * SIP Call\n");
11051 ast_cli(fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
11052 ast_cli(fd, " Call-ID: %s\n", cur->callid);
11053 ast_cli(fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
11054 ast_cli(fd, " Our Codec Capability: %d\n", cur->capability);
11055 ast_cli(fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
11056 ast_cli(fd, " Their Codec Capability: %d\n", cur->peercapability);
11057 ast_cli(fd, " Joint Codec Capability: %d\n", cur->jointcapability);
11058 ast_cli(fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
11059 ast_cli(fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
11060 ast_cli(fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
11061 ast_cli(fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
11062 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
11063 ast_cli(fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
11064 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)" );
11065 ast_cli(fd, " Our Tag: %s\n", cur->tag);
11066 ast_cli(fd, " Their Tag: %s\n", cur->theirtag);
11067 ast_cli(fd, " SIP User agent: %s\n", cur->useragent);
11068 if (!ast_strlen_zero(cur->username))
11069 ast_cli(fd, " Username: %s\n", cur->username);
11070 if (!ast_strlen_zero(cur->peername))
11071 ast_cli(fd, " Peername: %s\n", cur->peername);
11072 if (!ast_strlen_zero(cur->uri))
11073 ast_cli(fd, " Original uri: %s\n", cur->uri);
11074 if (!ast_strlen_zero(cur->cid_num))
11075 ast_cli(fd, " Caller-ID: %s\n", cur->cid_num);
11076 ast_cli(fd, " Need Destroy: %d\n", ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY));
11077 ast_cli(fd, " Last Message: %s\n", cur->lastmsg);
11078 ast_cli(fd, " Promiscuous Redir: %s\n", ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
11079 ast_cli(fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
11080 ast_cli(fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
11081 ast_cli(fd, " SIP Options: ");
11082 if (cur->sipoptions) {
11083 int x;
11084 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
11085 if (cur->sipoptions & sip_options[x].id)
11086 ast_cli(fd, "%s ", sip_options[x].text);
11088 } else
11089 ast_cli(fd, "(none)\n");
11090 ast_cli(fd, "\n\n");
11091 found++;
11094 ast_mutex_unlock(&iflock);
11095 if (!found)
11096 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
11097 return RESULT_SUCCESS;
11100 /*! \brief Show history details of one dialog */
11101 static int sip_show_history(int fd, int argc, char *argv[])
11103 struct sip_pvt *cur;
11104 size_t len;
11105 int found = 0;
11107 if (argc != 4)
11108 return RESULT_SHOWUSAGE;
11109 if (!recordhistory)
11110 ast_cli(fd, "\n***Note: History recording is currently DISABLED. Use 'sip history' to ENABLE.\n");
11111 len = strlen(argv[3]);
11112 ast_mutex_lock(&iflock);
11113 for (cur = iflist; cur; cur = cur->next) {
11114 if (!strncasecmp(cur->callid, argv[3], len)) {
11115 struct sip_history *hist;
11116 int x = 0;
11118 ast_cli(fd,"\n");
11119 if (cur->subscribed != NONE)
11120 ast_cli(fd, " * Subscription\n");
11121 else
11122 ast_cli(fd, " * SIP Call\n");
11123 if (cur->history)
11124 AST_LIST_TRAVERSE(cur->history, hist, list)
11125 ast_cli(fd, "%d. %s\n", ++x, hist->event);
11126 if (x == 0)
11127 ast_cli(fd, "Call '%s' has no history\n", cur->callid);
11128 found++;
11131 ast_mutex_unlock(&iflock);
11132 if (!found)
11133 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
11134 return RESULT_SUCCESS;
11137 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
11138 static void sip_dump_history(struct sip_pvt *dialog)
11140 int x = 0;
11141 struct sip_history *hist;
11142 static int errmsg = 0;
11144 if (!dialog)
11145 return;
11147 if (!option_debug && !sipdebug) {
11148 if (!errmsg) {
11149 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
11150 errmsg = 1;
11152 return;
11155 ast_log(LOG_DEBUG, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
11156 if (dialog->subscribed)
11157 ast_log(LOG_DEBUG, " * Subscription\n");
11158 else
11159 ast_log(LOG_DEBUG, " * SIP Call\n");
11160 if (dialog->history)
11161 AST_LIST_TRAVERSE(dialog->history, hist, list)
11162 ast_log(LOG_DEBUG, " %-3.3d. %s\n", ++x, hist->event);
11163 if (!x)
11164 ast_log(LOG_DEBUG, "Call '%s' has no history\n", dialog->callid);
11165 ast_log(LOG_DEBUG, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
11169 /*! \brief Receive SIP INFO Message
11170 \note Doesn't read the duration of the DTMF signal */
11171 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
11173 char buf[1024];
11174 unsigned int event;
11175 const char *c = get_header(req, "Content-Type");
11177 /* Need to check the media/type */
11178 if (!strcasecmp(c, "application/dtmf-relay") ||
11179 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
11180 unsigned int duration = 0;
11182 /* Try getting the "signal=" part */
11183 if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
11184 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
11185 transmit_response(p, "200 OK", req); /* Should return error */
11186 return;
11187 } else {
11188 ast_copy_string(buf, c, sizeof(buf));
11191 if (!ast_strlen_zero((c = get_body(req, "Duration"))))
11192 duration = atoi(c);
11193 if (!duration)
11194 duration = 100; /* 100 ms */
11196 if (!p->owner) { /* not a PBX call */
11197 transmit_response(p, "481 Call leg/transaction does not exist", req);
11198 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11199 return;
11202 if (ast_strlen_zero(buf)) {
11203 transmit_response(p, "200 OK", req);
11204 return;
11207 if (buf[0] == '*')
11208 event = 10;
11209 else if (buf[0] == '#')
11210 event = 11;
11211 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
11212 event = 12 + buf[0] - 'A';
11213 else
11214 event = atoi(buf);
11215 if (event == 16) {
11216 /* send a FLASH event */
11217 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
11218 ast_queue_frame(p->owner, &f);
11219 if (sipdebug)
11220 ast_verbose("* DTMF-relay event received: FLASH\n");
11221 } else {
11222 /* send a DTMF event */
11223 struct ast_frame f = { AST_FRAME_DTMF, };
11224 if (event < 10) {
11225 f.subclass = '0' + event;
11226 } else if (event < 11) {
11227 f.subclass = '*';
11228 } else if (event < 12) {
11229 f.subclass = '#';
11230 } else if (event < 16) {
11231 f.subclass = 'A' + (event - 12);
11233 f.len = duration;
11234 ast_queue_frame(p->owner, &f);
11235 if (sipdebug)
11236 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
11238 transmit_response(p, "200 OK", req);
11239 return;
11240 } else if (!strcasecmp(c, "application/media_control+xml")) {
11241 /* Eh, we'll just assume it's a fast picture update for now */
11242 if (p->owner)
11243 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
11244 transmit_response(p, "200 OK", req);
11245 return;
11246 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
11247 /* Client code (from SNOM phone) */
11248 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
11249 if (p->owner && p->owner->cdr)
11250 ast_cdr_setuserfield(p->owner, c);
11251 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
11252 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
11253 transmit_response(p, "200 OK", req);
11254 } else {
11255 transmit_response(p, "403 Unauthorized", req);
11257 return;
11258 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
11259 /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
11260 transmit_response(p, "200 OK", req);
11261 return;
11264 /* Other type of INFO message, not really understood by Asterisk */
11265 /* if (get_msg_text(buf, sizeof(buf), req)) { */
11267 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
11268 transmit_response(p, "415 Unsupported media type", req);
11269 return;
11272 /*! \brief Enable SIP Debugging in CLI */
11273 static int sip_do_debug_ip(int fd, int argc, char *argv[])
11275 struct hostent *hp;
11276 struct ast_hostent ahp;
11277 int port = 0;
11278 char *p, *arg;
11280 /* sip set debug ip <ip> */
11281 if (argc != 5)
11282 return RESULT_SHOWUSAGE;
11283 p = arg = argv[4];
11284 strsep(&p, ":");
11285 if (p)
11286 port = atoi(p);
11287 hp = ast_gethostbyname(arg, &ahp);
11288 if (hp == NULL)
11289 return RESULT_SHOWUSAGE;
11291 debugaddr.sin_family = AF_INET;
11292 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
11293 debugaddr.sin_port = htons(port);
11294 if (port == 0)
11295 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
11296 else
11297 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
11299 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11301 return RESULT_SUCCESS;
11304 /*! \brief sip_do_debug_peer: Turn on SIP debugging with peer mask */
11305 static int sip_do_debug_peer(int fd, int argc, char *argv[])
11307 struct sip_peer *peer;
11308 if (argc != 5)
11309 return RESULT_SHOWUSAGE;
11310 peer = find_peer(argv[4], NULL, 1);
11311 if (peer) {
11312 if (peer->addr.sin_addr.s_addr) {
11313 debugaddr.sin_family = AF_INET;
11314 debugaddr.sin_addr = peer->addr.sin_addr;
11315 debugaddr.sin_port = peer->addr.sin_port;
11316 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
11317 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11318 } else
11319 ast_cli(fd, "Unable to get IP address of peer '%s'\n", argv[4]);
11320 ASTOBJ_UNREF(peer,sip_destroy_peer);
11321 } else
11322 ast_cli(fd, "No such peer '%s'\n", argv[4]);
11323 return RESULT_SUCCESS;
11326 /*! \brief Turn on SIP debugging (CLI command) */
11327 static int sip_do_debug(int fd, int argc, char *argv[])
11329 int oldsipdebug = sipdebug_console;
11330 if (argc != 3) {
11331 if (argc != 5)
11332 return RESULT_SHOWUSAGE;
11333 else if (strcmp(argv[3], "ip") == 0)
11334 return sip_do_debug_ip(fd, argc, argv);
11335 else if (strcmp(argv[3], "peer") == 0)
11336 return sip_do_debug_peer(fd, argc, argv);
11337 else
11338 return RESULT_SHOWUSAGE;
11340 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11341 memset(&debugaddr, 0, sizeof(debugaddr));
11342 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
11343 return RESULT_SUCCESS;
11346 static int sip_do_debug_deprecated(int fd, int argc, char *argv[])
11348 int oldsipdebug = sipdebug_console;
11349 char *newargv[6] = { "sip", "set", "debug", NULL };
11350 if (argc != 2) {
11351 if (argc != 4)
11352 return RESULT_SHOWUSAGE;
11353 else if (strcmp(argv[2], "ip") == 0) {
11354 newargv[3] = argv[2];
11355 newargv[4] = argv[3];
11356 return sip_do_debug_ip(fd, argc + 1, newargv);
11357 } else if (strcmp(argv[2], "peer") == 0) {
11358 newargv[3] = argv[2];
11359 newargv[4] = argv[3];
11360 return sip_do_debug_peer(fd, argc + 1, newargv);
11361 } else
11362 return RESULT_SHOWUSAGE;
11364 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11365 memset(&debugaddr, 0, sizeof(debugaddr));
11366 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
11367 return RESULT_SUCCESS;
11370 /*! \brief Cli command to send SIP notify to peer */
11371 static int sip_notify(int fd, int argc, char *argv[])
11373 struct ast_variable *varlist;
11374 int i;
11376 if (argc < 4)
11377 return RESULT_SHOWUSAGE;
11379 if (!notify_types) {
11380 ast_cli(fd, "No %s file found, or no types listed there\n", notify_config);
11381 return RESULT_FAILURE;
11384 varlist = ast_variable_browse(notify_types, argv[2]);
11386 if (!varlist) {
11387 ast_cli(fd, "Unable to find notify type '%s'\n", argv[2]);
11388 return RESULT_FAILURE;
11391 for (i = 3; i < argc; i++) {
11392 struct sip_pvt *p;
11393 struct sip_request req;
11394 struct ast_variable *var;
11396 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY))) {
11397 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
11398 return RESULT_FAILURE;
11401 if (create_addr(p, argv[i])) {
11402 /* Maybe they're not registered, etc. */
11403 sip_destroy(p);
11404 ast_cli(fd, "Could not create address for '%s'\n", argv[i]);
11405 continue;
11408 initreqprep(&req, p, SIP_NOTIFY);
11410 for (var = varlist; var; var = var->next)
11411 add_header(&req, var->name, ast_unescape_semicolon(var->value));
11413 /* Recalculate our side, and recalculate Call ID */
11414 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
11415 p->ourip = __ourip;
11416 build_via(p);
11417 build_callid_pvt(p);
11418 ast_cli(fd, "Sending NOTIFY of type '%s' to '%s'\n", argv[2], argv[i]);
11419 transmit_sip_request(p, &req);
11420 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11423 return RESULT_SUCCESS;
11426 /*! \brief Disable SIP Debugging in CLI */
11427 static int sip_no_debug(int fd, int argc, char *argv[])
11429 if (argc != 4)
11430 return RESULT_SHOWUSAGE;
11431 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11432 ast_cli(fd, "SIP Debugging Disabled\n");
11433 return RESULT_SUCCESS;
11436 static int sip_no_debug_deprecated(int fd, int argc, char *argv[])
11438 if (argc != 3)
11439 return RESULT_SHOWUSAGE;
11440 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11441 ast_cli(fd, "SIP Debugging Disabled\n");
11442 return RESULT_SUCCESS;
11445 /*! \brief Enable SIP History logging (CLI) */
11446 static int sip_do_history(int fd, int argc, char *argv[])
11448 if (argc != 2) {
11449 return RESULT_SHOWUSAGE;
11451 recordhistory = TRUE;
11452 ast_cli(fd, "SIP History Recording Enabled (use 'sip show history')\n");
11453 return RESULT_SUCCESS;
11456 /*! \brief Disable SIP History logging (CLI) */
11457 static int sip_no_history(int fd, int argc, char *argv[])
11459 if (argc != 3) {
11460 return RESULT_SHOWUSAGE;
11462 recordhistory = FALSE;
11463 ast_cli(fd, "SIP History Recording Disabled\n");
11464 return RESULT_SUCCESS;
11467 /*! \brief Authenticate for outbound registration */
11468 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader)
11470 char digest[1024];
11471 p->authtries++;
11472 memset(digest,0,sizeof(digest));
11473 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
11474 /* There's nothing to use for authentication */
11475 /* No digest challenge in request */
11476 if (sip_debug_test_pvt(p) && p->registry)
11477 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
11478 /* No old challenge */
11479 return -1;
11481 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
11482 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
11483 if (sip_debug_test_pvt(p) && p->registry)
11484 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
11485 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
11488 /*! \brief Add authentication on outbound SIP packet */
11489 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init)
11491 char digest[1024];
11493 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
11494 return -2;
11496 p->authtries++;
11497 if (option_debug > 1)
11498 ast_log(LOG_DEBUG, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
11499 memset(digest, 0, sizeof(digest));
11500 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
11501 /* No way to authenticate */
11502 return -1;
11504 /* Now we have a reply digest */
11505 p->options->auth = digest;
11506 p->options->authheader = respheader;
11507 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
11510 /*! \brief reply to authentication for outbound registrations
11511 \return Returns -1 if we have no auth
11512 \note This is used for register= servers in sip.conf, SIP proxies we register
11513 with for receiving calls from. */
11514 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
11516 char tmp[512];
11517 char *c;
11518 char oldnonce[256];
11520 /* table of recognised keywords, and places where they should be copied */
11521 const struct x {
11522 const char *key;
11523 int field_index;
11524 } *i, keys[] = {
11525 { "realm=", ast_string_field_index(p, realm) },
11526 { "nonce=", ast_string_field_index(p, nonce) },
11527 { "opaque=", ast_string_field_index(p, opaque) },
11528 { "qop=", ast_string_field_index(p, qop) },
11529 { "domain=", ast_string_field_index(p, domain) },
11530 { NULL, 0 },
11533 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
11534 if (ast_strlen_zero(tmp))
11535 return -1;
11536 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
11537 ast_log(LOG_WARNING, "missing Digest.\n");
11538 return -1;
11540 c = tmp + strlen("Digest ");
11541 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
11542 while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
11543 for (i = keys; i->key != NULL; i++) {
11544 char *src, *separator;
11545 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
11546 continue;
11547 /* Found. Skip keyword, take text in quotes or up to the separator. */
11548 c += strlen(i->key);
11549 if (*c == '"') {
11550 src = ++c;
11551 separator = "\"";
11552 } else {
11553 src = c;
11554 separator = ",";
11556 strsep(&c, separator); /* clear separator and move ptr */
11557 ast_string_field_index_set(p, i->field_index, src);
11558 break;
11560 if (i->key == NULL) /* not found, try ',' */
11561 strsep(&c, ",");
11563 /* Reset nonce count */
11564 if (strcmp(p->nonce, oldnonce))
11565 p->noncecount = 0;
11567 /* Save auth data for following registrations */
11568 if (p->registry) {
11569 struct sip_registry *r = p->registry;
11571 if (strcmp(r->nonce, p->nonce)) {
11572 ast_string_field_set(r, realm, p->realm);
11573 ast_string_field_set(r, nonce, p->nonce);
11574 ast_string_field_set(r, domain, p->domain);
11575 ast_string_field_set(r, opaque, p->opaque);
11576 ast_string_field_set(r, qop, p->qop);
11577 r->noncecount = 0;
11580 return build_reply_digest(p, sipmethod, digest, digest_len);
11583 /*! \brief Build reply digest
11584 \return Returns -1 if we have no auth
11585 \note Build digest challenge for authentication of peers (for registration)
11586 and users (for calls). Also used for authentication of CANCEL and BYE
11588 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
11590 char a1[256];
11591 char a2[256];
11592 char a1_hash[256];
11593 char a2_hash[256];
11594 char resp[256];
11595 char resp_hash[256];
11596 char uri[256];
11597 char cnonce[80];
11598 const char *username;
11599 const char *secret;
11600 const char *md5secret;
11601 struct sip_auth *auth = NULL; /* Realm authentication */
11603 if (!ast_strlen_zero(p->domain))
11604 ast_copy_string(uri, p->domain, sizeof(uri));
11605 else if (!ast_strlen_zero(p->uri))
11606 ast_copy_string(uri, p->uri, sizeof(uri));
11607 else
11608 snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, ast_inet_ntoa(p->sa.sin_addr));
11610 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
11612 /* Check if we have separate auth credentials */
11613 if ((auth = find_realm_authentication(authl, p->realm))) {
11614 ast_log(LOG_WARNING, "use realm [%s] from peer [%s][%s]\n",
11615 auth->username, p->peername, p->username);
11616 username = auth->username;
11617 secret = auth->secret;
11618 md5secret = auth->md5secret;
11619 if (sipdebug)
11620 ast_log(LOG_DEBUG,"Using realm %s authentication for call %s\n", p->realm, p->callid);
11621 } else {
11622 /* No authentication, use peer or register= config */
11623 username = p->authname;
11624 secret = p->peersecret;
11625 md5secret = p->peermd5secret;
11627 if (ast_strlen_zero(username)) /* We have no authentication */
11628 return -1;
11630 /* Calculate SIP digest response */
11631 snprintf(a1,sizeof(a1),"%s:%s:%s", username, p->realm, secret);
11632 snprintf(a2,sizeof(a2),"%s:%s", sip_methods[method].text, uri);
11633 if (!ast_strlen_zero(md5secret))
11634 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
11635 else
11636 ast_md5_hash(a1_hash,a1);
11637 ast_md5_hash(a2_hash,a2);
11639 p->noncecount++;
11640 if (!ast_strlen_zero(p->qop))
11641 snprintf(resp,sizeof(resp),"%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
11642 else
11643 snprintf(resp,sizeof(resp),"%s:%s:%s", a1_hash, p->nonce, a2_hash);
11644 ast_md5_hash(resp_hash, resp);
11645 /* XXX We hard code our qop to "auth" for now. XXX */
11646 if (!ast_strlen_zero(p->qop))
11647 snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\", opaque=\"%s\", qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, p->opaque, cnonce, p->noncecount);
11648 else
11649 snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\", opaque=\"%s\"", username, p->realm, uri, p->nonce, resp_hash, p->opaque);
11651 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
11653 return 0;
11656 static char show_domains_usage[] =
11657 "Usage: sip show domains\n"
11658 " Lists all configured SIP local domains.\n"
11659 " Asterisk only responds to SIP messages to local domains.\n";
11661 static char notify_usage[] =
11662 "Usage: sip notify <type> <peer> [<peer>...]\n"
11663 " Send a NOTIFY message to a SIP peer or peers\n"
11664 " Message types are defined in sip_notify.conf\n";
11666 static char show_users_usage[] =
11667 "Usage: sip show users [like <pattern>]\n"
11668 " Lists all known SIP users.\n"
11669 " Optional regular expression pattern is used to filter the user list.\n";
11671 static char show_user_usage[] =
11672 "Usage: sip show user <name> [load]\n"
11673 " Shows all details on one SIP user and the current status.\n"
11674 " Option \"load\" forces lookup of peer in realtime storage.\n";
11676 static char show_inuse_usage[] =
11677 "Usage: sip show inuse [all]\n"
11678 " List all SIP users and peers usage counters and limits.\n"
11679 " Add option \"all\" to show all devices, not only those with a limit.\n";
11681 static char show_channels_usage[] =
11682 "Usage: sip show channels\n"
11683 " Lists all currently active SIP channels.\n";
11685 static char show_channel_usage[] =
11686 "Usage: sip show channel <channel>\n"
11687 " Provides detailed status on a given SIP channel.\n";
11689 static char show_history_usage[] =
11690 "Usage: sip show history <channel>\n"
11691 " Provides detailed dialog history on a given SIP channel.\n";
11693 static char show_peers_usage[] =
11694 "Usage: sip show peers [like <pattern>]\n"
11695 " Lists all known SIP peers.\n"
11696 " Optional regular expression pattern is used to filter the peer list.\n";
11698 static char show_peer_usage[] =
11699 "Usage: sip show peer <name> [load]\n"
11700 " Shows all details on one SIP peer and the current status.\n"
11701 " Option \"load\" forces lookup of peer in realtime storage.\n";
11703 static char prune_realtime_usage[] =
11704 "Usage: sip prune realtime [peer|user] [<name>|all|like <pattern>]\n"
11705 " Prunes object(s) from the cache.\n"
11706 " Optional regular expression pattern is used to filter the objects.\n";
11708 static char show_reg_usage[] =
11709 "Usage: sip show registry\n"
11710 " Lists all registration requests and status.\n";
11712 static char debug_usage[] =
11713 "Usage: sip set debug\n"
11714 " Enables dumping of SIP packets for debugging purposes\n\n"
11715 " sip set debug ip <host[:PORT]>\n"
11716 " Enables dumping of SIP packets to and from host.\n\n"
11717 " sip set debug peer <peername>\n"
11718 " Enables dumping of SIP packets to and from host.\n"
11719 " Require peer to be registered.\n";
11721 static char no_debug_usage[] =
11722 "Usage: sip set debug off\n"
11723 " Disables dumping of SIP packets for debugging purposes\n";
11725 static char no_history_usage[] =
11726 "Usage: sip history off\n"
11727 " Disables recording of SIP dialog history for debugging purposes\n";
11729 static char history_usage[] =
11730 "Usage: sip history\n"
11731 " Enables recording of SIP dialog history for debugging purposes.\n"
11732 "Use 'sip show history' to view the history of a call number.\n";
11734 static char sip_reload_usage[] =
11735 "Usage: sip reload\n"
11736 " Reloads SIP configuration from sip.conf\n";
11738 static char show_subscriptions_usage[] =
11739 "Usage: sip show subscriptions\n"
11740 " Lists active SIP subscriptions for extension states\n";
11742 static char show_objects_usage[] =
11743 "Usage: sip show objects\n"
11744 " Lists status of known SIP objects\n";
11746 static char show_settings_usage[] =
11747 "Usage: sip show settings\n"
11748 " Provides detailed list of the configuration of the SIP channel.\n";
11750 /*! \brief Read SIP header (dialplan function) */
11751 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len)
11753 struct sip_pvt *p;
11754 const char *content = NULL;
11755 AST_DECLARE_APP_ARGS(args,
11756 AST_APP_ARG(header);
11757 AST_APP_ARG(number);
11759 int i, number, start = 0;
11761 if (ast_strlen_zero(data)) {
11762 ast_log(LOG_WARNING, "This function requires a header name.\n");
11763 return -1;
11766 ast_channel_lock(chan);
11767 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
11768 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
11769 ast_channel_unlock(chan);
11770 return -1;
11773 AST_STANDARD_APP_ARGS(args, data);
11774 if (!args.number) {
11775 number = 1;
11776 } else {
11777 sscanf(args.number, "%d", &number);
11778 if (number < 1)
11779 number = 1;
11782 p = chan->tech_pvt;
11784 /* If there is no private structure, this channel is no longer alive */
11785 if (!p) {
11786 ast_channel_unlock(chan);
11787 return -1;
11790 for (i = 0; i < number; i++)
11791 content = __get_header(&p->initreq, args.header, &start);
11793 if (ast_strlen_zero(content)) {
11794 ast_channel_unlock(chan);
11795 return -1;
11798 ast_copy_string(buf, content, len);
11799 ast_channel_unlock(chan);
11801 return 0;
11804 static struct ast_custom_function sip_header_function = {
11805 .name = "SIP_HEADER",
11806 .synopsis = "Gets the specified SIP header",
11807 .syntax = "SIP_HEADER(<name>[,<number>])",
11808 .desc = "Since there are several headers (such as Via) which can occur multiple\n"
11809 "times, SIP_HEADER takes an optional second argument to specify which header with\n"
11810 "that name to retrieve. Headers start at offset 1.\n",
11811 .read = func_header_read,
11814 /*! \brief Dial plan function to check if domain is local */
11815 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11817 if (ast_strlen_zero(data)) {
11818 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
11819 return -1;
11821 if (check_sip_domain(data, NULL, 0))
11822 ast_copy_string(buf, data, len);
11823 else
11824 buf[0] = '\0';
11825 return 0;
11828 static struct ast_custom_function checksipdomain_function = {
11829 .name = "CHECKSIPDOMAIN",
11830 .synopsis = "Checks if domain is a local domain",
11831 .syntax = "CHECKSIPDOMAIN(<domain|IP>)",
11832 .read = func_check_sipdomain,
11833 .desc = "This function checks if the domain in the argument is configured\n"
11834 "as a local SIP domain that this Asterisk server is configured to handle.\n"
11835 "Returns the domain name if it is locally handled, otherwise an empty string.\n"
11836 "Check the domain= configuration in sip.conf\n",
11839 /*! \brief ${SIPPEER()} Dialplan function - reads peer data */
11840 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11842 struct sip_peer *peer;
11843 char *colname;
11845 if ((colname = strchr(data, ':'))) /*! \todo Will be deprecated after 1.4 */
11846 *colname++ = '\0';
11847 else if ((colname = strchr(data, '|')))
11848 *colname++ = '\0';
11849 else
11850 colname = "ip";
11852 if (!(peer = find_peer(data, NULL, 1)))
11853 return -1;
11855 if (!strcasecmp(colname, "ip")) {
11856 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
11857 } else if (!strcasecmp(colname, "status")) {
11858 peer_status(peer, buf, len);
11859 } else if (!strcasecmp(colname, "language")) {
11860 ast_copy_string(buf, peer->language, len);
11861 } else if (!strcasecmp(colname, "regexten")) {
11862 ast_copy_string(buf, peer->regexten, len);
11863 } else if (!strcasecmp(colname, "limit")) {
11864 snprintf(buf, len, "%d", peer->call_limit);
11865 } else if (!strcasecmp(colname, "curcalls")) {
11866 snprintf(buf, len, "%d", peer->inUse);
11867 } else if (!strcasecmp(colname, "accountcode")) {
11868 ast_copy_string(buf, peer->accountcode, len);
11869 } else if (!strcasecmp(colname, "useragent")) {
11870 ast_copy_string(buf, peer->useragent, len);
11871 } else if (!strcasecmp(colname, "mailbox")) {
11872 ast_copy_string(buf, peer->mailbox, len);
11873 } else if (!strcasecmp(colname, "context")) {
11874 ast_copy_string(buf, peer->context, len);
11875 } else if (!strcasecmp(colname, "expire")) {
11876 snprintf(buf, len, "%d", peer->expire);
11877 } else if (!strcasecmp(colname, "dynamic")) {
11878 ast_copy_string(buf, (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no"), len);
11879 } else if (!strcasecmp(colname, "callerid_name")) {
11880 ast_copy_string(buf, peer->cid_name, len);
11881 } else if (!strcasecmp(colname, "callerid_num")) {
11882 ast_copy_string(buf, peer->cid_num, len);
11883 } else if (!strcasecmp(colname, "codecs")) {
11884 ast_getformatname_multiple(buf, len -1, peer->capability);
11885 } else if (!strncasecmp(colname, "codec[", 6)) {
11886 char *codecnum;
11887 int index = 0, codec = 0;
11889 codecnum = colname + 6; /* move past the '[' */
11890 codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
11891 index = atoi(codecnum);
11892 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
11893 ast_copy_string(buf, ast_getformatname(codec), len);
11897 ASTOBJ_UNREF(peer, sip_destroy_peer);
11899 return 0;
11902 /*! \brief Structure to declare a dialplan function: SIPPEER */
11903 struct ast_custom_function sippeer_function = {
11904 .name = "SIPPEER",
11905 .synopsis = "Gets SIP peer information",
11906 .syntax = "SIPPEER(<peername>[|item])",
11907 .read = function_sippeer,
11908 .desc = "Valid items are:\n"
11909 "- ip (default) The IP address.\n"
11910 "- mailbox The configured mailbox.\n"
11911 "- context The configured context.\n"
11912 "- expire The epoch time of the next expire.\n"
11913 "- dynamic Is it dynamic? (yes/no).\n"
11914 "- callerid_name The configured Caller ID name.\n"
11915 "- callerid_num The configured Caller ID number.\n"
11916 "- codecs The configured codecs.\n"
11917 "- status Status (if qualify=yes).\n"
11918 "- regexten Registration extension\n"
11919 "- limit Call limit (call-limit)\n"
11920 "- curcalls Current amount of calls \n"
11921 " Only available if call-limit is set\n"
11922 "- language Default language for peer\n"
11923 "- accountcode Account code for this peer\n"
11924 "- useragent Current user agent id for peer\n"
11925 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
11926 "\n"
11929 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
11930 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11932 struct sip_pvt *p;
11934 *buf = 0;
11936 if (!data) {
11937 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
11938 return -1;
11941 ast_channel_lock(chan);
11942 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
11943 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
11944 ast_channel_unlock(chan);
11945 return -1;
11948 p = chan->tech_pvt;
11950 /* If there is no private structure, this channel is no longer alive */
11951 if (!p) {
11952 ast_channel_unlock(chan);
11953 return -1;
11956 if (!strcasecmp(data, "peerip")) {
11957 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
11958 } else if (!strcasecmp(data, "recvip")) {
11959 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
11960 } else if (!strcasecmp(data, "from")) {
11961 ast_copy_string(buf, p->from, len);
11962 } else if (!strcasecmp(data, "uri")) {
11963 ast_copy_string(buf, p->uri, len);
11964 } else if (!strcasecmp(data, "useragent")) {
11965 ast_copy_string(buf, p->useragent, len);
11966 } else if (!strcasecmp(data, "peername")) {
11967 ast_copy_string(buf, p->peername, len);
11968 } else if (!strcasecmp(data, "t38passthrough")) {
11969 if (p->t38.state == T38_DISABLED)
11970 ast_copy_string(buf, "0", sizeof("0"));
11971 else /* T38 is offered or enabled in this call */
11972 ast_copy_string(buf, "1", sizeof("1"));
11973 } else {
11974 ast_channel_unlock(chan);
11975 return -1;
11977 ast_channel_unlock(chan);
11979 return 0;
11982 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
11983 static struct ast_custom_function sipchaninfo_function = {
11984 .name = "SIPCHANINFO",
11985 .synopsis = "Gets the specified SIP parameter from the current channel",
11986 .syntax = "SIPCHANINFO(item)",
11987 .read = function_sipchaninfo_read,
11988 .desc = "Valid items are:\n"
11989 "- peerip The IP address of the peer.\n"
11990 "- recvip The source IP address of the peer.\n"
11991 "- from The URI from the From: header.\n"
11992 "- uri The URI from the Contact: header.\n"
11993 "- useragent The useragent.\n"
11994 "- peername The name of the peer.\n"
11995 "- t38passthrough 1 if T38 is offered or enabled in this channel, otherwise 0\n"
11998 /*! \brief Parse 302 Moved temporalily response */
11999 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
12001 char tmp[SIPBUFSIZE];
12002 char *s, *e, *uri, *t;
12003 char *domain;
12005 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
12006 if ((t = strchr(tmp, ',')))
12007 *t = '\0';
12008 s = get_in_brackets(tmp);
12009 uri = ast_strdupa(s);
12010 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
12011 if (!strncasecmp(s, "sip:", 4))
12012 s += 4;
12013 e = strchr(s, ';');
12014 if (e)
12015 *e = '\0';
12016 if (option_debug)
12017 ast_log(LOG_DEBUG, "Found promiscuous redirection to 'SIP/%s'\n", s);
12018 if (p->owner)
12019 ast_string_field_build(p->owner, call_forward, "SIP/%s", s);
12020 } else {
12021 e = strchr(tmp, '@');
12022 if (e) {
12023 *e++ = '\0';
12024 domain = e;
12025 } else {
12026 /* No username part */
12027 domain = tmp;
12029 e = strchr(s, ';'); /* Strip of parameters in the username part */
12030 if (e)
12031 *e = '\0';
12032 e = strchr(domain, ';'); /* Strip of parameters in the domain part */
12033 if (e)
12034 *e = '\0';
12036 if (!strncasecmp(s, "sip:", 4))
12037 s += 4;
12038 if (option_debug > 1)
12039 ast_log(LOG_DEBUG, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
12040 if (p->owner) {
12041 pbx_builtin_setvar_helper(p->owner, "SIPREDIRECTURI", uri);
12042 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
12043 ast_string_field_set(p->owner, call_forward, s);
12048 /*! \brief Check pending actions on SIP call */
12049 static void check_pendings(struct sip_pvt *p)
12051 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
12052 /* if we can't BYE, then this is really a pending CANCEL */
12053 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
12054 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
12055 /* Actually don't destroy us yet, wait for the 487 on our original
12056 INVITE, but do set an autodestruct just in case we never get it. */
12057 else {
12058 /* We have a pending outbound invite, don't send someting
12059 new in-transaction */
12060 if (p->pendinginvite)
12061 return;
12063 /* Perhaps there is an SD change INVITE outstanding */
12064 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
12066 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
12067 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12068 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
12069 /* if we can't REINVITE, hold it for later */
12070 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
12071 if (option_debug)
12072 ast_log(LOG_DEBUG, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
12073 } else {
12074 if (option_debug)
12075 ast_log(LOG_DEBUG, "Sending pending reinvite on '%s'\n", p->callid);
12076 /* Didn't get to reinvite yet, so do it now */
12077 transmit_reinvite_with_sdp(p);
12078 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
12083 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
12084 to avoid race conditions between asterisk servers.
12085 Called from the scheduler.
12087 static int sip_reinvite_retry(const void *data)
12089 struct sip_pvt *p = (struct sip_pvt *) data;
12091 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
12092 p->waitid = -1;
12093 return 0;
12097 /*! \brief Handle SIP response to INVITE dialogue */
12098 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
12100 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
12101 int res = 0;
12102 int xmitres = 0;
12103 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
12104 struct ast_channel *bridgepeer = NULL;
12106 if (option_debug > 3) {
12107 if (reinvite)
12108 ast_log(LOG_DEBUG, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
12109 else
12110 ast_log(LOG_DEBUG, "SIP response %d to standard invite\n", resp);
12113 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) { /* This call is already gone */
12114 if (option_debug)
12115 ast_log(LOG_DEBUG, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
12116 return;
12119 /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
12120 /* Don't auto congest anymore since we've gotten something useful back */
12121 AST_SCHED_DEL(sched, p->initid);
12123 /* RFC3261 says we must treat every 1xx response (but not 100)
12124 that we don't recognize as if it was 183.
12126 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
12127 resp = 183;
12129 /* Any response between 100 and 199 is PROCEEDING */
12130 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
12131 p->invitestate = INV_PROCEEDING;
12133 /* Final response, not 200 ? */
12134 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
12135 p->invitestate = INV_COMPLETED;
12138 switch (resp) {
12139 case 100: /* Trying */
12140 case 101: /* Dialog establishment */
12141 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12142 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12143 check_pendings(p);
12144 break;
12146 case 180: /* 180 Ringing */
12147 case 182: /* 182 Queued */
12148 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12149 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12150 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12151 ast_queue_control(p->owner, AST_CONTROL_RINGING);
12152 if (p->owner->_state != AST_STATE_UP) {
12153 ast_setstate(p->owner, AST_STATE_RINGING);
12156 if (find_sdp(req)) {
12157 if (p->invitestate != INV_CANCELLED)
12158 p->invitestate = INV_EARLY_MEDIA;
12159 res = process_sdp(p, req);
12160 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12161 /* Queue a progress frame only if we have SDP in 180 or 182 */
12162 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
12165 check_pendings(p);
12166 break;
12168 case 183: /* Session progress */
12169 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12170 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12171 /* Ignore 183 Session progress without SDP */
12172 if (find_sdp(req)) {
12173 if (p->invitestate != INV_CANCELLED)
12174 p->invitestate = INV_EARLY_MEDIA;
12175 res = process_sdp(p, req);
12176 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12177 /* Queue a progress frame */
12178 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
12181 check_pendings(p);
12182 break;
12184 case 200: /* 200 OK on invite - someone's answering our call */
12185 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12186 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12187 p->authtries = 0;
12188 if (find_sdp(req)) {
12189 if ((res = process_sdp(p, req)) && !ast_test_flag(req, SIP_PKT_IGNORE))
12190 if (!reinvite)
12191 /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
12192 /* For re-invites, we try to recover */
12193 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12196 /* Parse contact header for continued conversation */
12197 /* When we get 200 OK, we know which device (and IP) to contact for this call */
12198 /* This is important when we have a SIP proxy between us and the phone */
12199 if (outgoing) {
12200 update_call_counter(p, DEC_CALL_RINGING);
12201 parse_ok_contact(p, req);
12202 if(set_address_from_contact(p)) {
12203 /* Bad contact - we don't know how to reach this device */
12204 /* We need to ACK, but then send a bye */
12205 /* OEJ: Possible issue that may need a check:
12206 If we have a proxy route between us and the device,
12207 should we care about resolving the contact
12208 or should we just send it?
12210 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12211 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12214 /* Save Record-Route for any later requests we make on this dialogue */
12215 if (!reinvite)
12216 build_route(p, req, 1);
12219 if (p->owner && (p->owner->_state == AST_STATE_UP) && (bridgepeer = ast_bridged_channel(p->owner))) { /* if this is a re-invite */
12220 struct sip_pvt *bridgepvt = NULL;
12222 if (!bridgepeer->tech) {
12223 ast_log(LOG_WARNING, "Ooooh.. no tech! That's REALLY bad\n");
12224 break;
12226 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
12227 bridgepvt = (struct sip_pvt*)(bridgepeer->tech_pvt);
12228 if (bridgepvt->udptl) {
12229 if (p->t38.state == T38_PEER_REINVITE) {
12230 sip_handle_t38_reinvite(bridgepeer, p, 0);
12231 ast_rtp_set_rtptimers_onhold(p->rtp);
12232 if (p->vrtp)
12233 ast_rtp_set_rtptimers_onhold(p->vrtp); /* Turn off RTP timers while we send fax */
12234 } else if (p->t38.state == T38_DISABLED && bridgepeer && (bridgepvt->t38.state == T38_ENABLED)) {
12235 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
12236 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
12237 /* XXXX Should we really destroy this session here, without any response at all??? */
12238 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12240 } else {
12241 if (option_debug > 1)
12242 ast_log(LOG_DEBUG, "Strange... The other side of the bridge does not have a udptl struct\n");
12243 ast_mutex_lock(&bridgepvt->lock);
12244 bridgepvt->t38.state = T38_DISABLED;
12245 ast_mutex_unlock(&bridgepvt->lock);
12246 if (option_debug)
12247 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->tech->type);
12248 p->t38.state = T38_DISABLED;
12249 if (option_debug > 1)
12250 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12252 } else {
12253 /* Other side is not a SIP channel */
12254 if (option_debug > 1)
12255 ast_log(LOG_DEBUG, "Strange... The other side of the bridge is not a SIP channel\n");
12256 p->t38.state = T38_DISABLED;
12257 if (option_debug > 1)
12258 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12261 if ((p->t38.state == T38_LOCAL_REINVITE) || (p->t38.state == T38_LOCAL_DIRECT)) {
12262 /* If there was T38 reinvite and we are supposed to answer with 200 OK than this should set us to T38 negotiated mode */
12263 p->t38.state = T38_ENABLED;
12264 if (option_debug)
12265 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12268 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12269 if (!reinvite) {
12270 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
12271 } else { /* RE-invite */
12272 ast_queue_frame(p->owner, &ast_null_frame);
12274 } else {
12275 /* It's possible we're getting an 200 OK after we've tried to disconnect
12276 by sending CANCEL */
12277 /* First send ACK, then send bye */
12278 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12279 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12281 /* If I understand this right, the branch is different for a non-200 ACK only */
12282 p->invitestate = INV_TERMINATED;
12283 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
12284 check_pendings(p);
12285 break;
12286 case 407: /* Proxy authentication */
12287 case 401: /* Www auth */
12288 /* First we ACK */
12289 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12290 if (p->options)
12291 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
12293 /* Then we AUTH */
12294 ast_string_field_free(p, theirtag); /* forget their old tag, so we don't match tags when getting response */
12295 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
12296 char *authenticate = (resp == 401 ? "WWW-Authenticate" : "Proxy-Authenticate");
12297 char *authorization = (resp == 401 ? "Authorization" : "Proxy-Authorization");
12298 if (p->authtries < MAX_AUTHTRIES)
12299 p->invitestate = INV_CALLING;
12300 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, authenticate, authorization, SIP_INVITE, 1)) {
12301 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
12302 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12303 sip_alreadygone(p);
12304 if (p->owner)
12305 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12308 break;
12310 case 403: /* Forbidden */
12311 /* First we ACK */
12312 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12313 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
12314 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner)
12315 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12316 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12317 sip_alreadygone(p);
12318 break;
12320 case 404: /* Not found */
12321 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12322 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12323 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12324 sip_alreadygone(p);
12325 break;
12327 case 408: /* Request timeout */
12328 case 481: /* Call leg does not exist */
12329 /* Could be REFER caused INVITE with replaces */
12330 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
12331 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12332 if (p->owner)
12333 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12334 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12335 break;
12336 case 487: /* Cancelled transaction */
12337 /* We have sent CANCEL on an outbound INVITE
12338 This transaction is already scheduled to be killed by sip_hangup().
12340 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12341 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE)) {
12342 ast_queue_hangup(p->owner);
12343 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
12344 } else if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
12345 update_call_counter(p, DEC_CALL_LIMIT);
12346 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
12347 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12348 sip_alreadygone(p);
12350 break;
12351 case 488: /* Not acceptable here */
12352 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12353 if (reinvite && p->udptl) {
12354 /* If this is a T.38 call, we should go back to
12355 audio. If this is an audio call - something went
12356 terribly wrong since we don't renegotiate codecs,
12357 only IP/port .
12359 p->t38.state = T38_DISABLED;
12360 /* Try to reset RTP timers */
12361 ast_rtp_set_rtptimers_onhold(p->rtp);
12362 ast_log(LOG_ERROR, "Got error on T.38 re-invite. Bad configuration. Peer needs to have T.38 disabled.\n");
12364 /*! \bug Is there any way we can go back to the audio call on both
12365 sides here?
12367 /* While figuring that out, hangup the call */
12368 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12369 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12370 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12371 } else if (p->udptl && p->t38.state == T38_LOCAL_DIRECT) {
12372 /* We tried to send T.38 out in an initial INVITE and the remote side rejected it,
12373 right now we can't fall back to audio so totally abort.
12375 p->t38.state = T38_DISABLED;
12376 /* Try to reset RTP timers */
12377 ast_rtp_set_rtptimers_onhold(p->rtp);
12378 ast_log(LOG_ERROR, "Got error on T.38 initial invite. Bailing out.\n");
12380 /* The dialog is now terminated */
12381 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12382 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12383 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12384 sip_alreadygone(p);
12385 } else {
12386 /* We can't set up this call, so give up */
12387 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12388 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12389 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12390 /* If there's no dialog to end, then mark p as already gone */
12391 if (!reinvite)
12392 sip_alreadygone(p);
12394 break;
12395 case 491: /* Pending */
12396 /* we really should have to wait a while, then retransmit
12397 * We should support the retry-after at some point
12398 * At this point, we treat this as a congestion if the call is not in UP state
12400 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12401 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE)) {
12402 if (p->owner->_state != AST_STATE_UP) {
12403 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12404 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12405 } else {
12406 /* This is a re-invite that failed.
12407 * Reset the flag after a while
12409 int wait = 3 + ast_random() % 5;
12410 p->waitid = ast_sched_add(sched, wait, sip_reinvite_retry, p);
12411 if (option_debug > 2)
12412 ast_log(LOG_DEBUG, "Reinvite race. Waiting %d secs before retry\n", wait);
12415 break;
12417 case 501: /* Not implemented */
12418 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12419 if (p->owner)
12420 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12421 break;
12423 if (xmitres == XMIT_ERROR)
12424 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
12427 /* \brief Handle SIP response in REFER transaction
12428 We've sent a REFER, now handle responses to it
12430 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
12432 char *auth = "Proxy-Authenticate";
12433 char *auth2 = "Proxy-Authorization";
12435 /* If no refer structure exists, then do nothing */
12436 if (!p->refer)
12437 return;
12439 switch (resp) {
12440 case 202: /* Transfer accepted */
12441 /* We need to do something here */
12442 /* The transferee is now sending INVITE to target */
12443 p->refer->status = REFER_ACCEPTED;
12444 /* Now wait for next message */
12445 if (option_debug > 2)
12446 ast_log(LOG_DEBUG, "Got 202 accepted on transfer\n");
12447 /* We should hang along, waiting for NOTIFY's here */
12448 break;
12450 case 401: /* Not www-authorized on SIP method */
12451 case 407: /* Proxy auth */
12452 if (ast_strlen_zero(p->authname)) {
12453 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
12454 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12455 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12457 if (resp == 401) {
12458 auth = "WWW-Authenticate";
12459 auth2 = "Authorization";
12461 if ((p->authtries > 1) || do_proxy_auth(p, req, auth, auth2, SIP_REFER, 0)) {
12462 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
12463 p->refer->status = REFER_NOAUTH;
12464 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12466 break;
12467 case 481: /* Call leg does not exist */
12469 /* A transfer with Replaces did not work */
12470 /* OEJ: We should Set flag, cancel the REFER, go back
12471 to original call - but right now we can't */
12472 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
12473 if (p->owner)
12474 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12475 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12476 break;
12478 case 500: /* Server error */
12479 case 501: /* Method not implemented */
12480 /* Return to the current call onhold */
12481 /* Status flag needed to be reset */
12482 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
12483 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12484 p->refer->status = REFER_FAILED;
12485 break;
12486 case 603: /* Transfer declined */
12487 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
12488 p->refer->status = REFER_FAILED;
12489 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12490 break;
12494 /*! \brief Handle responses on REGISTER to services */
12495 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
12497 int expires, expires_ms;
12498 struct sip_registry *r;
12499 r=p->registry;
12501 switch (resp) {
12502 case 401: /* Unauthorized */
12503 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "WWW-Authenticate", "Authorization")) {
12504 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
12505 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12507 break;
12508 case 403: /* Forbidden */
12509 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
12510 if (global_regattempts_max)
12511 p->registry->regattempts = global_regattempts_max+1;
12512 AST_SCHED_DEL(sched, r->timeout);
12513 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12514 break;
12515 case 404: /* Not found */
12516 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username,p->registry->hostname);
12517 if (global_regattempts_max)
12518 p->registry->regattempts = global_regattempts_max+1;
12519 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12520 r->call = NULL;
12521 AST_SCHED_DEL(sched, r->timeout);
12522 break;
12523 case 407: /* Proxy auth */
12524 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization")) {
12525 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
12526 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12528 break;
12529 case 408: /* Request timeout */
12530 if (global_regattempts_max)
12531 p->registry->regattempts = global_regattempts_max+1;
12532 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12533 r->call = NULL;
12534 AST_SCHED_DEL(sched, r->timeout);
12535 break;
12536 case 479: /* SER: Not able to process the URI - address is wrong in register*/
12537 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username,p->registry->hostname);
12538 if (global_regattempts_max)
12539 p->registry->regattempts = global_regattempts_max+1;
12540 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12541 r->call = NULL;
12542 AST_SCHED_DEL(sched, r->timeout);
12543 break;
12544 case 200: /* 200 OK */
12545 if (!r) {
12546 ast_log(LOG_WARNING, "Got 200 OK on REGISTER that isn't a register\n");
12547 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12548 return 0;
12551 r->regstate = REG_STATE_REGISTERED;
12552 r->regtime = time(NULL); /* Reset time of last succesful registration */
12553 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
12554 r->regattempts = 0;
12555 if (option_debug)
12556 ast_log(LOG_DEBUG, "Registration successful\n");
12557 if (r->timeout > -1) {
12558 if (option_debug)
12559 ast_log(LOG_DEBUG, "Cancelling timeout %d\n", r->timeout);
12561 AST_SCHED_DEL(sched, r->timeout);
12562 r->call = NULL;
12563 p->registry = NULL;
12564 /* Let this one hang around until we have all the responses */
12565 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12566 /* ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); */
12568 /* set us up for re-registering */
12569 /* figure out how long we got registered for */
12570 AST_SCHED_DEL(sched, r->expire);
12571 /* according to section 6.13 of RFC, contact headers override
12572 expires headers, so check those first */
12573 expires = 0;
12575 /* XXX todo: try to save the extra call */
12576 if (!ast_strlen_zero(get_header(req, "Contact"))) {
12577 const char *contact = NULL;
12578 const char *tmptmp = NULL;
12579 int start = 0;
12580 for(;;) {
12581 contact = __get_header(req, "Contact", &start);
12582 /* this loop ensures we get a contact header about our register request */
12583 if(!ast_strlen_zero(contact)) {
12584 if( (tmptmp=strstr(contact, p->our_contact))) {
12585 contact=tmptmp;
12586 break;
12588 } else
12589 break;
12591 tmptmp = strcasestr(contact, "expires=");
12592 if (tmptmp) {
12593 if (sscanf(tmptmp + 8, "%d;", &expires) != 1)
12594 expires = 0;
12598 if (!expires)
12599 expires=atoi(get_header(req, "expires"));
12600 if (!expires)
12601 expires=default_expiry;
12603 expires_ms = expires * 1000;
12604 if (expires <= EXPIRY_GUARD_LIMIT)
12605 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT),EXPIRY_GUARD_MIN);
12606 else
12607 expires_ms -= EXPIRY_GUARD_SECS * 1000;
12608 if (sipdebug)
12609 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
12611 r->refresh= (int) expires_ms / 1000;
12613 /* Schedule re-registration before we expire */
12614 AST_SCHED_DEL(sched, r->expire);
12615 r->expire = ast_sched_add(sched, expires_ms, sip_reregister, r);
12616 ASTOBJ_UNREF(r, sip_registry_destroy);
12618 return 1;
12621 /*! \brief Handle qualification responses (OPTIONS) */
12622 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
12624 struct sip_peer *peer = p->relatedpeer;
12625 int statechanged, is_reachable, was_reachable;
12626 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
12629 * Compute the response time to a ping (goes in peer->lastms.)
12630 * -1 means did not respond, 0 means unknown,
12631 * 1..maxms is a valid response, >maxms means late response.
12633 if (pingtime < 1) /* zero = unknown, so round up to 1 */
12634 pingtime = 1;
12636 /* Now determine new state and whether it has changed.
12637 * Use some helper variables to simplify the writing
12638 * of the expressions.
12640 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
12641 is_reachable = pingtime <= peer->maxms;
12642 statechanged = peer->lastms == 0 /* yes, unknown before */
12643 || was_reachable != is_reachable;
12645 peer->lastms = pingtime;
12646 peer->call = NULL;
12647 if (statechanged) {
12648 const char *s = is_reachable ? "Reachable" : "Lagged";
12650 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
12651 peer->name, s, pingtime, peer->maxms);
12652 ast_device_state_changed("SIP/%s", peer->name);
12653 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
12654 "Peer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
12655 peer->name, s, pingtime);
12658 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
12659 struct sip_peer *peer_ptr = peer;
12660 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
12663 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12665 /* Try again eventually */
12666 peer->pokeexpire = ast_sched_add(sched,
12667 is_reachable ? DEFAULT_FREQ_OK : DEFAULT_FREQ_NOTOK,
12668 sip_poke_peer_s, ASTOBJ_REF(peer));
12669 if (peer->pokeexpire == -1) {
12670 ASTOBJ_UNREF(peer, sip_destroy_peer);
12674 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
12675 static void stop_media_flows(struct sip_pvt *p)
12677 /* Immediately stop RTP, VRTP and UDPTL as applicable */
12678 if (p->rtp)
12679 ast_rtp_stop(p->rtp);
12680 if (p->vrtp)
12681 ast_rtp_stop(p->vrtp);
12682 if (p->udptl)
12683 ast_udptl_stop(p->udptl);
12686 /*! \brief Handle SIP response in dialogue */
12687 /* XXX only called by handle_request */
12688 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
12690 struct ast_channel *owner;
12691 int sipmethod;
12692 int res = 1;
12693 const char *c = get_header(req, "Cseq");
12694 const char *msg = strchr(c, ' ');
12696 if (!msg)
12697 msg = "";
12698 else
12699 msg++;
12700 sipmethod = find_sip_method(msg);
12702 owner = p->owner;
12703 if (owner)
12704 owner->hangupcause = hangup_sip2cause(resp);
12706 /* Acknowledge whatever it is destined for */
12707 if ((resp >= 100) && (resp <= 199))
12708 __sip_semi_ack(p, seqno, 0, sipmethod);
12709 else
12710 __sip_ack(p, seqno, 0, sipmethod);
12712 /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
12713 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite)
12714 p->pendinginvite = 0;
12716 /* Get their tag if we haven't already */
12717 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
12718 char tag[128];
12720 gettag(req, "To", tag, sizeof(tag));
12721 ast_string_field_set(p, theirtag, tag);
12723 if (p->relatedpeer && p->method == SIP_OPTIONS) {
12724 /* We don't really care what the response is, just that it replied back.
12725 Well, as long as it's not a 100 response... since we might
12726 need to hang around for something more "definitive" */
12727 if (resp != 100)
12728 handle_response_peerpoke(p, resp, req);
12729 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12730 switch(resp) {
12731 case 100: /* 100 Trying */
12732 case 101: /* 101 Dialog establishment */
12733 if (sipmethod == SIP_INVITE)
12734 handle_response_invite(p, resp, rest, req, seqno);
12735 break;
12736 case 183: /* 183 Session Progress */
12737 if (sipmethod == SIP_INVITE)
12738 handle_response_invite(p, resp, rest, req, seqno);
12739 break;
12740 case 180: /* 180 Ringing */
12741 if (sipmethod == SIP_INVITE)
12742 handle_response_invite(p, resp, rest, req, seqno);
12743 break;
12744 case 182: /* 182 Queued */
12745 if (sipmethod == SIP_INVITE)
12746 handle_response_invite(p, resp, rest, req, seqno);
12747 break;
12748 case 200: /* 200 OK */
12749 p->authtries = 0; /* Reset authentication counter */
12750 if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
12751 /* We successfully transmitted a message
12752 or a video update request in INFO */
12753 /* Nothing happens here - the message is inside a dialog */
12754 } else if (sipmethod == SIP_INVITE) {
12755 handle_response_invite(p, resp, rest, req, seqno);
12756 } else if (sipmethod == SIP_NOTIFY) {
12757 /* They got the notify, this is the end */
12758 if (p->owner) {
12759 if (!p->refer) {
12760 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
12761 ast_queue_hangup(p->owner);
12762 } else if (option_debug > 3)
12763 ast_log(LOG_DEBUG, "Got OK on REFER Notify message\n");
12764 } else {
12765 if (p->subscribed == NONE)
12766 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12767 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
12768 /* Ready to send the next state we have on queue */
12769 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
12770 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
12773 } else if (sipmethod == SIP_REGISTER)
12774 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12775 else if (sipmethod == SIP_BYE) /* Ok, we're ready to go */
12776 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12777 break;
12778 case 202: /* Transfer accepted */
12779 if (sipmethod == SIP_REFER)
12780 handle_response_refer(p, resp, rest, req, seqno);
12781 break;
12782 case 401: /* Not www-authorized on SIP method */
12783 if (sipmethod == SIP_INVITE)
12784 handle_response_invite(p, resp, rest, req, seqno);
12785 else if (sipmethod == SIP_REFER)
12786 handle_response_refer(p, resp, rest, req, seqno);
12787 else if (p->registry && sipmethod == SIP_REGISTER)
12788 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12789 else if (sipmethod == SIP_BYE) {
12790 if (ast_strlen_zero(p->authname)) {
12791 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12792 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12793 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12794 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "WWW-Authenticate", "Authorization", sipmethod, 0)) {
12795 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
12796 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12797 /* We fail to auth bye on our own call, but still needs to tear down the call.
12798 Life, they call it. */
12800 } else {
12801 ast_log(LOG_WARNING, "Got authentication request (401) on unknown %s to '%s'\n", sip_methods[sipmethod].text, get_header(req, "To"));
12802 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12804 break;
12805 case 403: /* Forbidden - we failed authentication */
12806 if (sipmethod == SIP_INVITE)
12807 handle_response_invite(p, resp, rest, req, seqno);
12808 else if (p->registry && sipmethod == SIP_REGISTER)
12809 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12810 else {
12811 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
12812 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12814 break;
12815 case 404: /* Not found */
12816 if (p->registry && sipmethod == SIP_REGISTER)
12817 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12818 else if (sipmethod == SIP_INVITE)
12819 handle_response_invite(p, resp, rest, req, seqno);
12820 else if (owner)
12821 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12822 break;
12823 case 407: /* Proxy auth required */
12824 if (sipmethod == SIP_INVITE)
12825 handle_response_invite(p, resp, rest, req, seqno);
12826 else if (sipmethod == SIP_REFER)
12827 handle_response_refer(p, resp, rest, req, seqno);
12828 else if (p->registry && sipmethod == SIP_REGISTER)
12829 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12830 else if (sipmethod == SIP_BYE) {
12831 if (ast_strlen_zero(p->authname)) {
12832 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12833 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12834 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12835 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", sipmethod, 0)) {
12836 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
12837 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12839 } else /* We can't handle this, giving up in a bad way */
12840 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12842 break;
12843 case 408: /* Request timeout - terminate dialog */
12844 if (sipmethod == SIP_INVITE)
12845 handle_response_invite(p, resp, rest, req, seqno);
12846 else if (sipmethod == SIP_REGISTER)
12847 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12848 else if (sipmethod == SIP_BYE) {
12849 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12850 if (option_debug)
12851 ast_log(LOG_DEBUG, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
12852 } else {
12853 if (owner)
12854 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12855 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12857 break;
12858 case 481: /* Call leg does not exist */
12859 if (sipmethod == SIP_INVITE) {
12860 handle_response_invite(p, resp, rest, req, seqno);
12861 } else if (sipmethod == SIP_REFER) {
12862 handle_response_refer(p, resp, rest, req, seqno);
12863 } else if (sipmethod == SIP_BYE) {
12864 /* The other side has no transaction to bye,
12865 just assume it's all right then */
12866 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12867 } else if (sipmethod == SIP_CANCEL) {
12868 /* The other side has no transaction to cancel,
12869 just assume it's all right then */
12870 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12871 } else {
12872 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12873 /* Guessing that this is not an important request */
12875 break;
12876 case 487:
12877 if (sipmethod == SIP_INVITE)
12878 handle_response_invite(p, resp, rest, req, seqno);
12879 break;
12880 case 488: /* Not acceptable here - codec error */
12881 if (sipmethod == SIP_INVITE)
12882 handle_response_invite(p, resp, rest, req, seqno);
12883 break;
12884 case 491: /* Pending */
12885 if (sipmethod == SIP_INVITE)
12886 handle_response_invite(p, resp, rest, req, seqno);
12887 else {
12888 if (option_debug)
12889 ast_log(LOG_DEBUG, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
12890 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12892 break;
12893 case 501: /* Not Implemented */
12894 if (sipmethod == SIP_INVITE)
12895 handle_response_invite(p, resp, rest, req, seqno);
12896 else if (sipmethod == SIP_REFER)
12897 handle_response_refer(p, resp, rest, req, seqno);
12898 else
12899 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
12900 break;
12901 case 603: /* Declined transfer */
12902 if (sipmethod == SIP_REFER) {
12903 handle_response_refer(p, resp, rest, req, seqno);
12904 break;
12906 /* Fallthrough */
12907 default:
12908 if ((resp >= 300) && (resp < 700)) {
12909 /* Fatal response */
12910 if ((option_verbose > 2) && (resp != 487))
12911 ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
12913 if (sipmethod == SIP_INVITE)
12914 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
12916 /* XXX Locking issues?? XXX */
12917 switch(resp) {
12918 case 300: /* Multiple Choices */
12919 case 301: /* Moved permenantly */
12920 case 302: /* Moved temporarily */
12921 case 305: /* Use Proxy */
12922 parse_moved_contact(p, req);
12923 /* Fall through */
12924 case 486: /* Busy here */
12925 case 600: /* Busy everywhere */
12926 case 603: /* Decline */
12927 if (p->owner)
12928 ast_queue_control(p->owner, AST_CONTROL_BUSY);
12929 break;
12930 case 482: /*
12931 \note SIP is incapable of performing a hairpin call, which
12932 is yet another failure of not having a layer 2 (again, YAY
12933 IETF for thinking ahead). So we treat this as a call
12934 forward and hope we end up at the right place... */
12935 if (option_debug)
12936 ast_log(LOG_DEBUG, "Hairpin detected, setting up call forward for what it's worth\n");
12937 if (p->owner)
12938 ast_string_field_build(p->owner, call_forward,
12939 "Local/%s@%s", p->username, p->context);
12940 /* Fall through */
12941 case 480: /* Temporarily Unavailable */
12942 case 404: /* Not Found */
12943 case 410: /* Gone */
12944 case 400: /* Bad Request */
12945 case 500: /* Server error */
12946 if (sipmethod == SIP_REFER) {
12947 handle_response_refer(p, resp, rest, req, seqno);
12948 break;
12950 /* Fall through */
12951 case 503: /* Service Unavailable */
12952 case 504: /* Server Timeout */
12953 if (owner)
12954 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12955 break;
12956 default:
12957 /* Send hangup */
12958 if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
12959 ast_queue_hangup(p->owner);
12960 break;
12962 /* ACK on invite */
12963 if (sipmethod == SIP_INVITE)
12964 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12965 if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
12966 sip_alreadygone(p);
12967 if (!p->owner)
12968 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12969 } else if ((resp >= 100) && (resp < 200)) {
12970 if (sipmethod == SIP_INVITE) {
12971 if (!ast_test_flag(req, SIP_PKT_IGNORE) && sip_cancel_destroy(p))
12972 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12973 if (find_sdp(req))
12974 process_sdp(p, req);
12975 if (p->owner) {
12976 /* Queue a progress frame */
12977 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
12980 } else
12981 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));
12983 } else {
12984 /* Responses to OUTGOING SIP requests on INCOMING calls
12985 get handled here. As well as out-of-call message responses */
12986 if (ast_test_flag(req, SIP_PKT_DEBUG))
12987 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
12989 if (sipmethod == SIP_INVITE && resp == 200) {
12990 /* Tags in early session is replaced by the tag in 200 OK, which is
12991 the final reply to our INVITE */
12992 char tag[128];
12994 gettag(req, "To", tag, sizeof(tag));
12995 ast_string_field_set(p, theirtag, tag);
12998 switch(resp) {
12999 case 200:
13000 if (sipmethod == SIP_INVITE) {
13001 handle_response_invite(p, resp, rest, req, seqno);
13002 } else if (sipmethod == SIP_CANCEL) {
13003 if (option_debug)
13004 ast_log(LOG_DEBUG, "Got 200 OK on CANCEL\n");
13006 /* Wait for 487, then destroy */
13007 } else if (sipmethod == SIP_NOTIFY) {
13008 /* They got the notify, this is the end */
13009 if (p->owner) {
13010 if (p->refer) {
13011 if (option_debug)
13012 ast_log(LOG_DEBUG, "Got 200 OK on NOTIFY for transfer\n");
13013 } else
13014 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
13015 /* ast_queue_hangup(p->owner); Disabled */
13016 } else {
13017 if (!p->subscribed && !p->refer)
13018 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13019 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
13020 /* Ready to send the next state we have on queue */
13021 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
13022 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
13025 } else if (sipmethod == SIP_BYE)
13026 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13027 else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO)
13028 /* We successfully transmitted a message or
13029 a video update request in INFO */
13031 else if (sipmethod == SIP_BYE)
13032 /* Ok, we're ready to go */
13033 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13034 break;
13035 case 202: /* Transfer accepted */
13036 if (sipmethod == SIP_REFER)
13037 handle_response_refer(p, resp, rest, req, seqno);
13038 break;
13039 case 401: /* www-auth */
13040 case 407:
13041 if (sipmethod == SIP_REFER)
13042 handle_response_refer(p, resp, rest, req, seqno);
13043 else if (sipmethod == SIP_INVITE)
13044 handle_response_invite(p, resp, rest, req, seqno);
13045 else if (sipmethod == SIP_BYE) {
13046 char *auth, *auth2;
13048 auth = (resp == 407 ? "Proxy-Authenticate" : "WWW-Authenticate");
13049 auth2 = (resp == 407 ? "Proxy-Authorization" : "Authorization");
13050 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, auth, auth2, sipmethod, 0)) {
13051 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
13052 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13055 break;
13056 case 481: /* Call leg does not exist */
13057 if (sipmethod == SIP_INVITE) {
13058 /* Re-invite failed */
13059 handle_response_invite(p, resp, rest, req, seqno);
13060 } else if (sipmethod == SIP_BYE) {
13061 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13062 } else if (sipdebug) {
13063 ast_log (LOG_DEBUG, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
13065 break;
13066 case 501: /* Not Implemented */
13067 if (sipmethod == SIP_INVITE)
13068 handle_response_invite(p, resp, rest, req, seqno);
13069 else if (sipmethod == SIP_REFER)
13070 handle_response_refer(p, resp, rest, req, seqno);
13071 break;
13072 case 603: /* Declined transfer */
13073 if (sipmethod == SIP_REFER) {
13074 handle_response_refer(p, resp, rest, req, seqno);
13075 break;
13077 /* Fallthrough */
13078 default: /* Errors without handlers */
13079 if ((resp >= 100) && (resp < 200)) {
13080 if (sipmethod == SIP_INVITE) { /* re-invite */
13081 if (!ast_test_flag(req, SIP_PKT_IGNORE) && sip_cancel_destroy(p))
13082 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13085 if ((resp >= 300) && (resp < 700)) {
13086 if ((option_verbose > 2) && (resp != 487))
13087 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));
13088 switch(resp) {
13089 case 488: /* Not acceptable here - codec error */
13090 case 603: /* Decline */
13091 case 500: /* Server error */
13092 case 503: /* Service Unavailable */
13093 case 504: /* Server timeout */
13095 /* re-invite failed */
13096 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
13097 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13098 break;
13101 break;
13107 /*! \brief Park SIP call support function
13108 Starts in a new thread, then parks the call
13109 XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
13110 audio can't be heard before hangup
13112 static void *sip_park_thread(void *stuff)
13114 struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
13115 struct sip_dual *d;
13116 struct sip_request req;
13117 int ext;
13118 int res;
13120 d = stuff;
13121 transferee = d->chan1;
13122 transferer = d->chan2;
13123 copy_request(&req, &d->req);
13124 free(d);
13126 if (!transferee || !transferer) {
13127 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
13128 return NULL;
13130 if (option_debug > 3)
13131 ast_log(LOG_DEBUG, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
13133 ast_channel_lock(transferee);
13134 if (ast_do_masquerade(transferee)) {
13135 ast_log(LOG_WARNING, "Masquerade failed.\n");
13136 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
13137 ast_channel_unlock(transferee);
13138 return NULL;
13140 ast_channel_unlock(transferee);
13142 res = ast_park_call(transferee, transferer, 0, &ext);
13145 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
13146 if (!res) {
13147 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
13148 } else {
13149 /* Then tell the transferer what happened */
13150 sprintf(buf, "Call parked on extension '%d'", ext);
13151 transmit_message_with_text(transferer->tech_pvt, buf);
13153 #endif
13155 /* Any way back to the current call??? */
13156 /* Transmit response to the REFER request */
13157 transmit_response(transferer->tech_pvt, "202 Accepted", &req);
13158 if (!res) {
13159 /* Transfer succeeded */
13160 append_history(transferer->tech_pvt, "SIPpark","Parked call on %d", ext);
13161 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
13162 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
13163 ast_hangup(transferer); /* This will cause a BYE */
13164 if (option_debug)
13165 ast_log(LOG_DEBUG, "SIP Call parked on extension '%d'\n", ext);
13166 } else {
13167 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
13168 append_history(transferer->tech_pvt, "SIPpark","Parking failed\n");
13169 if (option_debug)
13170 ast_log(LOG_DEBUG, "SIP Call parked failed \n");
13171 /* Do not hangup call */
13173 return NULL;
13176 /*! \brief Park a call using the subsystem in res_features.c
13177 This is executed in a separate thread
13179 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
13181 struct sip_dual *d;
13182 struct ast_channel *transferee, *transferer;
13183 /* Chan2m: The transferer, chan1m: The transferee */
13184 pthread_t th;
13186 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
13187 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
13188 if ((!transferer) || (!transferee)) {
13189 if (transferee) {
13190 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13191 ast_hangup(transferee);
13193 if (transferer) {
13194 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13195 ast_hangup(transferer);
13197 return -1;
13200 /* Make formats okay */
13201 transferee->readformat = chan1->readformat;
13202 transferee->writeformat = chan1->writeformat;
13204 /* Prepare for taking over the channel */
13205 ast_channel_masquerade(transferee, chan1);
13207 /* Setup the extensions and such */
13208 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
13209 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
13210 transferee->priority = chan1->priority;
13212 /* We make a clone of the peer channel too, so we can play
13213 back the announcement */
13215 /* Make formats okay */
13216 transferer->readformat = chan2->readformat;
13217 transferer->writeformat = chan2->writeformat;
13219 /* Prepare for taking over the channel. Go ahead and grab this channel
13220 * lock here to avoid a deadlock with callbacks into the channel driver
13221 * that hold the channel lock and want the pvt lock. */
13222 while (ast_channel_trylock(chan2)) {
13223 struct sip_pvt *pvt = chan2->tech_pvt;
13224 ast_mutex_unlock(&pvt->lock);
13225 usleep(1);
13226 ast_mutex_lock(&pvt->lock);
13228 ast_channel_masquerade(transferer, chan2);
13229 ast_channel_unlock(chan2);
13231 /* Setup the extensions and such */
13232 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
13233 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
13234 transferer->priority = chan2->priority;
13236 ast_channel_lock(transferer);
13237 if (ast_do_masquerade(transferer)) {
13238 ast_log(LOG_WARNING, "Masquerade failed :(\n");
13239 ast_channel_unlock(transferer);
13240 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13241 ast_hangup(transferer);
13242 return -1;
13244 ast_channel_unlock(transferer);
13245 if (!transferer || !transferee) {
13246 if (!transferer) {
13247 if (option_debug)
13248 ast_log(LOG_DEBUG, "No transferer channel, giving up parking\n");
13250 if (!transferee) {
13251 if (option_debug)
13252 ast_log(LOG_DEBUG, "No transferee channel, giving up parking\n");
13254 return -1;
13256 if ((d = ast_calloc(1, sizeof(*d)))) {
13257 pthread_attr_t attr;
13259 pthread_attr_init(&attr);
13260 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
13262 /* Save original request for followup */
13263 copy_request(&d->req, req);
13264 d->chan1 = transferee; /* Transferee */
13265 d->chan2 = transferer; /* Transferer */
13266 d->seqno = seqno;
13267 if (ast_pthread_create_background(&th, &attr, sip_park_thread, d) < 0) {
13268 /* Could not start thread */
13269 free(d); /* We don't need it anymore. If thread is created, d will be free'd
13270 by sip_park_thread() */
13271 pthread_attr_destroy(&attr);
13272 return 0;
13274 pthread_attr_destroy(&attr);
13276 return -1;
13279 /*! \brief Turn off generator data
13280 XXX Does this function belong in the SIP channel?
13282 static void ast_quiet_chan(struct ast_channel *chan)
13284 if (chan && chan->_state == AST_STATE_UP) {
13285 if (ast_test_flag(chan, AST_FLAG_MOH))
13286 ast_moh_stop(chan);
13287 else if (chan->generatordata)
13288 ast_deactivate_generator(chan);
13292 /*! \brief Attempt transfer of SIP call
13293 This fix for attended transfers on a local PBX */
13294 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
13296 int res = 0;
13297 struct ast_channel *peera = NULL,
13298 *peerb = NULL,
13299 *peerc = NULL,
13300 *peerd = NULL;
13303 /* We will try to connect the transferee with the target and hangup
13304 all channels to the transferer */
13305 if (option_debug > 3) {
13306 ast_log(LOG_DEBUG, "Sip transfer:--------------------\n");
13307 if (transferer->chan1)
13308 ast_log(LOG_DEBUG, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
13309 else
13310 ast_log(LOG_DEBUG, "-- No transferer first channel - odd??? \n");
13311 if (target->chan1)
13312 ast_log(LOG_DEBUG, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
13313 else
13314 ast_log(LOG_DEBUG, "-- No target first channel ---\n");
13315 if (transferer->chan2)
13316 ast_log(LOG_DEBUG, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
13317 else
13318 ast_log(LOG_DEBUG, "-- No bridged call to transferee\n");
13319 if (target->chan2)
13320 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)");
13321 else
13322 ast_log(LOG_DEBUG, "-- No target second channel ---\n");
13323 ast_log(LOG_DEBUG, "-- END Sip transfer:--------------------\n");
13325 if (transferer->chan2) { /* We have a bridge on the transferer's channel */
13326 peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
13327 peerb = target->chan1; /* Transferer - PBX -> target channel - This will get lost in masq */
13328 peerc = transferer->chan2; /* Asterisk to Transferee */
13329 peerd = target->chan2; /* Asterisk to Target */
13330 if (option_debug > 2)
13331 ast_log(LOG_DEBUG, "SIP transfer: Four channels to handle\n");
13332 } else if (target->chan2) { /* Transferer has no bridge (IVR), but transferee */
13333 peera = target->chan1; /* Transferer to PBX -> target channel */
13334 peerb = transferer->chan1; /* Transferer to IVR*/
13335 peerc = target->chan2; /* Asterisk to Target */
13336 peerd = transferer->chan2; /* Nothing */
13337 if (option_debug > 2)
13338 ast_log(LOG_DEBUG, "SIP transfer: Three channels to handle\n");
13341 if (peera && peerb && peerc && (peerb != peerc)) {
13342 ast_quiet_chan(peera); /* Stop generators */
13343 ast_quiet_chan(peerb);
13344 ast_quiet_chan(peerc);
13345 if (peerd)
13346 ast_quiet_chan(peerd);
13348 /* Fix CDRs so they're attached to the remaining channel */
13349 if (peera->cdr && peerb->cdr)
13350 peerb->cdr = ast_cdr_append(peerb->cdr, peera->cdr);
13351 else if (peera->cdr)
13352 peerb->cdr = peera->cdr;
13353 peera->cdr = NULL;
13355 if (peerb->cdr && peerc->cdr)
13356 peerb->cdr = ast_cdr_append(peerb->cdr, peerc->cdr);
13357 else if (peerc->cdr)
13358 peerb->cdr = peerc->cdr;
13359 peerc->cdr = NULL;
13361 if (option_debug > 3)
13362 ast_log(LOG_DEBUG, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
13363 if (ast_channel_masquerade(peerb, peerc)) {
13364 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
13365 res = -1;
13366 } else
13367 ast_log(LOG_DEBUG, "SIP transfer: Succeeded to masquerade channels.\n");
13368 return res;
13369 } else {
13370 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
13371 if (transferer->chan1)
13372 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
13373 if (target->chan1)
13374 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
13375 return -2;
13377 return 0;
13380 /*! \brief Get tag from packet
13382 * \return Returns the pointer to the provided tag buffer,
13383 * or NULL if the tag was not found.
13385 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
13387 const char *thetag;
13389 if (!tagbuf)
13390 return NULL;
13391 tagbuf[0] = '\0'; /* reset the buffer */
13392 thetag = get_header(req, header);
13393 thetag = strcasestr(thetag, ";tag=");
13394 if (thetag) {
13395 thetag += 5;
13396 ast_copy_string(tagbuf, thetag, tagbufsize);
13397 return strsep(&tagbuf, ";");
13399 return NULL;
13402 /*! \brief Handle incoming notifications */
13403 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
13405 /* This is mostly a skeleton for future improvements */
13406 /* Mostly created to return proper answers on notifications on outbound REFER's */
13407 int res = 0;
13408 const char *event = get_header(req, "Event");
13409 char *eventid = NULL;
13410 char *sep;
13412 if( (sep = strchr(event, ';')) ) { /* XXX bug here - overwriting string ? */
13413 *sep++ = '\0';
13414 eventid = sep;
13417 if (option_debug > 1 && sipdebug)
13418 ast_log(LOG_DEBUG, "Got NOTIFY Event: %s\n", event);
13420 if (strcmp(event, "refer")) {
13421 /* We don't understand this event. */
13422 /* Here's room to implement incoming voicemail notifications :-) */
13423 transmit_response(p, "489 Bad event", req);
13424 res = -1;
13425 } else {
13426 /* Save nesting depth for now, since there might be other events we will
13427 support in the future */
13429 /* Handle REFER notifications */
13431 char buf[1024];
13432 char *cmd, *code;
13433 int respcode;
13434 int success = TRUE;
13436 /* EventID for each transfer... EventID is basically the REFER cseq
13438 We are getting notifications on a call that we transfered
13439 We should hangup when we are getting a 200 OK in a sipfrag
13440 Check if we have an owner of this event */
13442 /* Check the content type */
13443 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
13444 /* We need a sipfrag */
13445 transmit_response(p, "400 Bad request", req);
13446 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13447 return -1;
13450 /* Get the text of the attachment */
13451 if (get_msg_text(buf, sizeof(buf), req)) {
13452 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
13453 transmit_response(p, "400 Bad request", req);
13454 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13455 return -1;
13459 From the RFC...
13460 A minimal, but complete, implementation can respond with a single
13461 NOTIFY containing either the body:
13462 SIP/2.0 100 Trying
13464 if the subscription is pending, the body:
13465 SIP/2.0 200 OK
13466 if the reference was successful, the body:
13467 SIP/2.0 503 Service Unavailable
13468 if the reference failed, or the body:
13469 SIP/2.0 603 Declined
13471 if the REFER request was accepted before approval to follow the
13472 reference could be obtained and that approval was subsequently denied
13473 (see Section 2.4.7).
13475 If there are several REFERs in the same dialog, we need to
13476 match the ID of the event header...
13478 if (option_debug > 2)
13479 ast_log(LOG_DEBUG, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
13480 cmd = ast_skip_blanks(buf);
13481 code = cmd;
13482 /* We are at SIP/2.0 */
13483 while(*code && (*code > 32)) { /* Search white space */
13484 code++;
13486 *code++ = '\0';
13487 code = ast_skip_blanks(code);
13488 sep = code;
13489 sep++;
13490 while(*sep && (*sep > 32)) { /* Search white space */
13491 sep++;
13493 *sep++ = '\0'; /* Response string */
13494 respcode = atoi(code);
13495 switch (respcode) {
13496 case 100: /* Trying: */
13497 case 101: /* dialog establishment */
13498 /* Don't do anything yet */
13499 break;
13500 case 183: /* Ringing: */
13501 /* Don't do anything yet */
13502 break;
13503 case 200: /* OK: The new call is up, hangup this call */
13504 /* Hangup the call that we are replacing */
13505 break;
13506 case 301: /* Moved permenantly */
13507 case 302: /* Moved temporarily */
13508 /* Do we get the header in the packet in this case? */
13509 success = FALSE;
13510 break;
13511 case 503: /* Service Unavailable: The new call failed */
13512 /* Cancel transfer, continue the call */
13513 success = FALSE;
13514 break;
13515 case 603: /* Declined: Not accepted */
13516 /* Cancel transfer, continue the current call */
13517 success = FALSE;
13518 break;
13520 if (!success) {
13521 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
13524 /* Confirm that we received this packet */
13525 transmit_response(p, "200 OK", req);
13528 if (!p->lastinvite)
13529 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13531 return res;
13534 /*! \brief Handle incoming OPTIONS request */
13535 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
13537 int res;
13539 res = get_destination(p, req);
13540 build_contact(p);
13542 /* XXX Should we authenticate OPTIONS? XXX */
13544 if (ast_strlen_zero(p->context))
13545 ast_string_field_set(p, context, default_context);
13547 if (ast_shutting_down())
13548 transmit_response_with_allow(p, "503 Unavailable", req, 0);
13549 else if (res < 0)
13550 transmit_response_with_allow(p, "404 Not Found", req, 0);
13551 else
13552 transmit_response_with_allow(p, "200 OK", req, 0);
13554 /* Destroy if this OPTIONS was the opening request, but not if
13555 it's in the middle of a normal call flow. */
13556 if (!p->lastinvite)
13557 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13559 return res;
13562 /*! \brief Handle the transfer part of INVITE with a replaces: header,
13563 meaning a target pickup or an attended transfer */
13564 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin)
13566 struct ast_frame *f;
13567 int earlyreplace = 0;
13568 int oneleggedreplace = 0; /* Call with no bridge, propably IVR or voice message */
13569 struct ast_channel *c = p->owner; /* Our incoming call */
13570 struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
13571 struct ast_channel *targetcall; /* The bridge to the take-over target */
13573 /* Check if we're in ring state */
13574 if (replacecall->_state == AST_STATE_RING)
13575 earlyreplace = 1;
13577 /* Check if we have a bridge */
13578 if (!(targetcall = ast_bridged_channel(replacecall))) {
13579 /* We have no bridge */
13580 if (!earlyreplace) {
13581 if (option_debug > 1)
13582 ast_log(LOG_DEBUG, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
13583 oneleggedreplace = 1;
13586 if (option_debug > 3 && targetcall && targetcall->_state == AST_STATE_RINGING)
13587 ast_log(LOG_DEBUG, "SIP transfer: Target channel is in ringing state\n");
13589 if (option_debug > 3) {
13590 if (targetcall)
13591 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);
13592 else
13593 ast_log(LOG_DEBUG, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
13596 if (ignore) {
13597 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
13598 /* We should answer something here. If we are here, the
13599 call we are replacing exists, so an accepted
13600 can't harm */
13601 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
13602 /* Do something more clever here */
13603 ast_channel_unlock(c);
13604 ast_mutex_unlock(&p->refer->refer_call->lock);
13605 return 1;
13607 if (!c) {
13608 /* What to do if no channel ??? */
13609 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
13610 transmit_response_reliable(p, "503 Service Unavailable", req);
13611 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
13612 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13613 ast_mutex_unlock(&p->refer->refer_call->lock);
13614 return 1;
13616 append_history(p, "Xfer", "INVITE/Replace received");
13617 /* We have three channels to play with
13618 channel c: New incoming call
13619 targetcall: Call from PBX to target
13620 p->refer->refer_call: SIP pvt dialog from transferer to pbx.
13621 replacecall: The owner of the previous
13622 We need to masq C into refer_call to connect to
13623 targetcall;
13624 If we are talking to internal audio stream, target call is null.
13627 /* Fake call progress */
13628 transmit_response(p, "100 Trying", req);
13629 ast_setstate(c, AST_STATE_RING);
13631 /* Masquerade the new call into the referred call to connect to target call
13632 Targetcall is not touched by the masq */
13634 /* Answer the incoming call and set channel to UP state */
13635 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
13637 ast_setstate(c, AST_STATE_UP);
13639 /* Stop music on hold and other generators */
13640 ast_quiet_chan(replacecall);
13641 ast_quiet_chan(targetcall);
13642 if (option_debug > 3)
13643 ast_log(LOG_DEBUG, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
13644 /* Unlock clone, but not original (replacecall) */
13645 if (!oneleggedreplace)
13646 ast_channel_unlock(c);
13648 /* Unlock PVT */
13649 ast_mutex_unlock(&p->refer->refer_call->lock);
13651 /* Make sure that the masq does not free our PVT for the old call */
13652 if (! earlyreplace && ! oneleggedreplace )
13653 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
13655 /* Prepare the masquerade - if this does not happen, we will be gone */
13656 if(ast_channel_masquerade(replacecall, c))
13657 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
13658 else if (option_debug > 3)
13659 ast_log(LOG_DEBUG, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
13661 /* The masquerade will happen as soon as someone reads a frame from the channel */
13663 /* C should now be in place of replacecall */
13664 /* ast_read needs to lock channel */
13665 ast_channel_unlock(c);
13667 if (earlyreplace || oneleggedreplace ) {
13668 /* Force the masq to happen */
13669 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
13670 ast_frfree(f);
13671 f = NULL;
13672 if (option_debug > 3)
13673 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from RING channel!\n");
13674 } else {
13675 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from RING channel \n");
13677 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13678 if (!oneleggedreplace)
13679 ast_channel_unlock(replacecall);
13680 } else { /* Bridged call, UP channel */
13681 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
13682 /* Masq ok */
13683 ast_frfree(f);
13684 f = NULL;
13685 if (option_debug > 2)
13686 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from channel! Masq done.\n");
13687 } else {
13688 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from channel. Transfer failed\n");
13690 ast_channel_unlock(replacecall);
13692 ast_mutex_unlock(&p->refer->refer_call->lock);
13694 ast_setstate(c, AST_STATE_DOWN);
13695 if (option_debug > 3) {
13696 struct ast_channel *test;
13697 ast_log(LOG_DEBUG, "After transfer:----------------------------\n");
13698 ast_log(LOG_DEBUG, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
13699 if (replacecall)
13700 ast_log(LOG_DEBUG, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
13701 if (p->owner) {
13702 ast_log(LOG_DEBUG, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
13703 test = ast_bridged_channel(p->owner);
13704 if (test)
13705 ast_log(LOG_DEBUG, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
13706 else
13707 ast_log(LOG_DEBUG, " -- No call bridged to C->owner \n");
13708 } else
13709 ast_log(LOG_DEBUG, " -- No channel yet \n");
13710 ast_log(LOG_DEBUG, "End After transfer:----------------------------\n");
13713 ast_channel_unlock(p->owner); /* Unlock new owner */
13714 if (!oneleggedreplace)
13715 ast_mutex_unlock(&p->lock); /* Unlock SIP structure */
13717 /* The call should be down with no ast_channel, so hang it up */
13718 c->tech_pvt = NULL;
13719 ast_hangup(c);
13720 return 0;
13724 /*! \brief Handle incoming INVITE request
13725 \note If the INVITE has a Replaces header, it is part of an
13726 * attended transfer. If so, we do not go through the dial
13727 * plan but tries to find the active call and masquerade
13728 * into it
13730 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)
13732 int res = 1;
13733 int gotdest;
13734 const char *p_replaces;
13735 char *replace_id = NULL;
13736 const char *required;
13737 unsigned int required_profile = 0;
13738 struct ast_channel *c = NULL; /* New channel */
13739 int reinvite = 0;
13741 /* Find out what they support */
13742 if (!p->sipoptions) {
13743 const char *supported = get_header(req, "Supported");
13744 if (!ast_strlen_zero(supported))
13745 parse_sip_options(p, supported);
13748 /* Find out what they require */
13749 required = get_header(req, "Require");
13750 if (!ast_strlen_zero(required)) {
13751 required_profile = parse_sip_options(NULL, required);
13752 if (required_profile && required_profile != SIP_OPT_REPLACES) {
13753 /* At this point we only support REPLACES */
13754 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
13755 ast_log(LOG_WARNING,"Received SIP INVITE with unsupported required extension: %s\n", required);
13756 p->invitestate = INV_COMPLETED;
13757 if (!p->lastinvite)
13758 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13759 return -1;
13763 /* Check if this is a loop */
13764 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->owner->_state != AST_STATE_UP)) {
13765 /* This is a call to ourself. Send ourselves an error code and stop
13766 processing immediately, as SIP really has no good mechanism for
13767 being able to call yourself */
13768 /* If pedantic is on, we need to check the tags. If they're different, this is
13769 in fact a forked call through a SIP proxy somewhere. */
13770 transmit_response(p, "482 Loop Detected", req);
13771 p->invitestate = INV_COMPLETED;
13772 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13773 return 0;
13776 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->pendinginvite) {
13777 /* We already have a pending invite. Sorry. You are on hold. */
13778 transmit_response(p, "491 Request Pending", req);
13779 if (option_debug)
13780 ast_log(LOG_DEBUG, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
13781 /* Don't destroy dialog here */
13782 return 0;
13785 p_replaces = get_header(req, "Replaces");
13786 if (!ast_strlen_zero(p_replaces)) {
13787 /* We have a replaces header */
13788 char *ptr;
13789 char *fromtag = NULL;
13790 char *totag = NULL;
13791 char *start, *to;
13792 int error = 0;
13794 if (p->owner) {
13795 if (option_debug > 2)
13796 ast_log(LOG_DEBUG, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
13797 transmit_response(p, "400 Bad request", req); /* The best way to not not accept the transfer */
13798 /* Do not destroy existing call */
13799 return -1;
13802 if (sipdebug && option_debug > 2)
13803 ast_log(LOG_DEBUG, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
13804 /* Create a buffer we can manipulate */
13805 replace_id = ast_strdupa(p_replaces);
13806 ast_uri_decode(replace_id);
13808 if (!p->refer && !sip_refer_allocate(p)) {
13809 transmit_response(p, "500 Server Internal Error", req);
13810 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
13811 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13812 p->invitestate = INV_COMPLETED;
13813 return -1;
13816 /* Todo: (When we find phones that support this)
13817 if the replaces header contains ";early-only"
13818 we can only replace the call in early
13819 stage, not after it's up.
13821 If it's not in early mode, 486 Busy.
13824 /* Skip leading whitespace */
13825 replace_id = ast_skip_blanks(replace_id);
13827 start = replace_id;
13828 while ( (ptr = strsep(&start, ";")) ) {
13829 ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
13830 if ( (to = strcasestr(ptr, "to-tag=") ) )
13831 totag = to + 7; /* skip the keyword */
13832 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
13833 fromtag = to + 9; /* skip the keyword */
13834 fromtag = strsep(&fromtag, "&"); /* trim what ? */
13838 if (sipdebug && option_debug > 3)
13839 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>");
13842 /* Try to find call that we are replacing
13843 If we have a Replaces header, we need to cancel that call if we succeed with this call
13845 if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
13846 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
13847 transmit_response(p, "481 Call Leg Does Not Exist (Replaces)", req);
13848 error = 1;
13851 /* At this point, bot the pvt and the owner of the call to be replaced is locked */
13853 /* The matched call is the call from the transferer to Asterisk .
13854 We want to bridge the bridged part of the call to the
13855 incoming invite, thus taking over the refered call */
13857 if (p->refer->refer_call == p) {
13858 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
13859 p->refer->refer_call = NULL;
13860 transmit_response(p, "400 Bad request", req); /* The best way to not not accept the transfer */
13861 error = 1;
13864 if (!error && !p->refer->refer_call->owner) {
13865 /* Oops, someting wrong anyway, no owner, no call */
13866 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
13867 /* Check for better return code */
13868 transmit_response(p, "481 Call Leg Does Not Exist (Replace)", req);
13869 error = 1;
13872 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 ) {
13873 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
13874 transmit_response(p, "603 Declined (Replaces)", req);
13875 error = 1;
13878 if (error) { /* Give up this dialog */
13879 append_history(p, "Xfer", "INVITE/Replace Failed.");
13880 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13881 ast_mutex_unlock(&p->lock);
13882 if (p->refer->refer_call) {
13883 ast_mutex_unlock(&p->refer->refer_call->lock);
13884 ast_channel_unlock(p->refer->refer_call->owner);
13886 p->invitestate = INV_COMPLETED;
13887 return -1;
13892 /* Check if this is an INVITE that sets up a new dialog or
13893 a re-invite in an existing dialog */
13895 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
13896 int newcall = (p->initreq.headers ? TRUE : FALSE);
13898 if (sip_cancel_destroy(p))
13899 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13900 /* This also counts as a pending invite */
13901 p->pendinginvite = seqno;
13902 check_via(p, req);
13904 copy_request(&p->initreq, req); /* Save this INVITE as the transaction basis */
13905 if (!p->owner) { /* Not a re-invite */
13906 if (debug)
13907 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
13908 if (newcall)
13909 append_history(p, "Invite", "New call: %s", p->callid);
13910 parse_ok_contact(p, req);
13911 } else { /* Re-invite on existing call */
13912 ast_clear_flag(&p->flags[0], SIP_OUTGOING); /* This is now an inbound dialog */
13913 /* Handle SDP here if we already have an owner */
13914 if (find_sdp(req)) {
13915 if (process_sdp(p, req)) {
13916 transmit_response(p, "488 Not acceptable here", req);
13917 if (!p->lastinvite)
13918 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13919 return -1;
13921 } else {
13922 p->jointcapability = p->capability;
13923 if (option_debug > 2)
13924 ast_log(LOG_DEBUG, "Hm.... No sdp for the moment\n");
13925 /* Some devices signal they want to be put off hold by sending a re-invite
13926 *without* an SDP, which is supposed to mean "Go back to your state"
13927 and since they put os on remote hold, we go back to off hold */
13928 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
13929 change_hold_state(p, req, FALSE, 0);
13931 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) /* This is a response, note what it was for */
13932 append_history(p, "ReInv", "Re-invite received");
13934 } else if (debug)
13935 ast_verbose("Ignoring this INVITE request\n");
13938 if (!p->lastinvite && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner) {
13939 /* This is a new invite */
13940 /* Handle authentication if this is our first invite */
13941 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
13942 if (res == AUTH_CHALLENGE_SENT) {
13943 p->invitestate = INV_COMPLETED; /* Needs to restart in another INVITE transaction */
13944 return 0;
13946 if (res < 0) { /* Something failed in authentication */
13947 if (res == AUTH_FAKE_AUTH) {
13948 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
13949 transmit_fake_auth_response(p, req, 1);
13950 } else {
13951 ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
13952 transmit_response_reliable(p, "403 Forbidden", req);
13954 p->invitestate = INV_COMPLETED;
13955 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13956 ast_string_field_free(p, theirtag);
13957 return 0;
13960 /* We have a succesful authentication, process the SDP portion if there is one */
13961 if (find_sdp(req)) {
13962 if (process_sdp(p, req)) {
13963 /* Unacceptable codecs */
13964 transmit_response_reliable(p, "488 Not acceptable here", req);
13965 p->invitestate = INV_COMPLETED;
13966 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13967 if (option_debug)
13968 ast_log(LOG_DEBUG, "No compatible codecs for this SIP call.\n");
13969 return -1;
13971 } else { /* No SDP in invite, call control session */
13972 p->jointcapability = p->capability;
13973 if (option_debug > 1)
13974 ast_log(LOG_DEBUG, "No SDP in Invite, third party call control\n");
13977 /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
13978 /* This seems redundant ... see !p-owner above */
13979 if (p->owner)
13980 ast_queue_frame(p->owner, &ast_null_frame);
13983 /* Initialize the context if it hasn't been already */
13984 if (ast_strlen_zero(p->context))
13985 ast_string_field_set(p, context, default_context);
13988 /* Check number of concurrent calls -vs- incoming limit HERE */
13989 if (option_debug)
13990 ast_log(LOG_DEBUG, "Checking SIP call limits for device %s\n", p->username);
13991 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
13992 if (res < 0) {
13993 ast_log(LOG_NOTICE, "Failed to place call for user %s, too many calls\n", p->username);
13994 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
13995 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13996 p->invitestate = INV_COMPLETED;
13998 return 0;
14000 gotdest = get_destination(p, NULL); /* Get destination right away */
14001 get_rdnis(p, NULL); /* Get redirect information */
14002 extract_uri(p, req); /* Get the Contact URI */
14003 build_contact(p); /* Build our contact header */
14005 if (p->rtp) {
14006 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
14007 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
14010 if (!replace_id && gotdest) { /* No matching extension found */
14011 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
14012 transmit_response_reliable(p, "484 Address Incomplete", req);
14013 else {
14014 transmit_response_reliable(p, "404 Not Found", req);
14015 ast_log(LOG_NOTICE, "Call from '%s' to extension"
14016 " '%s' rejected because extension not found.\n",
14017 S_OR(p->username, p->peername), p->exten);
14019 p->invitestate = INV_COMPLETED;
14020 update_call_counter(p, DEC_CALL_LIMIT);
14021 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14022 return 0;
14023 } else {
14024 /* If no extension was specified, use the s one */
14025 /* Basically for calling to IP/Host name only */
14026 if (ast_strlen_zero(p->exten))
14027 ast_string_field_set(p, exten, "s");
14028 /* Initialize our tag */
14030 make_our_tag(p->tag, sizeof(p->tag));
14031 /* First invitation - create the channel */
14032 c = sip_new(p, AST_STATE_DOWN, S_OR(p->username, NULL));
14033 *recount = 1;
14035 /* Save Record-Route for any later requests we make on this dialogue */
14036 build_route(p, req, 0);
14038 if (c) {
14039 /* Pre-lock the call */
14040 ast_channel_lock(c);
14043 } else {
14044 if (option_debug > 1 && sipdebug) {
14045 if (!ast_test_flag(req, SIP_PKT_IGNORE))
14046 ast_log(LOG_DEBUG, "Got a SIP re-invite for call %s\n", p->callid);
14047 else
14048 ast_log(LOG_DEBUG, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
14050 reinvite = 1;
14051 c = p->owner;
14054 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
14055 p->lastinvite = seqno;
14057 if (replace_id) { /* Attended transfer or call pickup - we're the target */
14058 /* Go and take over the target call */
14059 if (sipdebug && option_debug > 3)
14060 ast_log(LOG_DEBUG, "Sending this call to the invite/replcaes handler %s\n", p->callid);
14061 return handle_invite_replaces(p, req, debug, ast_test_flag(req, SIP_PKT_IGNORE), seqno, sin);
14065 if (c) { /* We have a call -either a new call or an old one (RE-INVITE) */
14066 switch(c->_state) {
14067 case AST_STATE_DOWN:
14068 if (option_debug > 1)
14069 ast_log(LOG_DEBUG, "%s: New call is still down.... Trying... \n", c->name);
14070 transmit_response(p, "100 Trying", req);
14071 p->invitestate = INV_PROCEEDING;
14072 ast_setstate(c, AST_STATE_RING);
14073 if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
14074 enum ast_pbx_result res;
14076 res = ast_pbx_start(c);
14078 switch(res) {
14079 case AST_PBX_FAILED:
14080 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
14081 p->invitestate = INV_COMPLETED;
14082 if (ast_test_flag(req, SIP_PKT_IGNORE))
14083 transmit_response(p, "503 Unavailable", req);
14084 else
14085 transmit_response_reliable(p, "503 Unavailable", req);
14086 break;
14087 case AST_PBX_CALL_LIMIT:
14088 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
14089 p->invitestate = INV_COMPLETED;
14090 if (ast_test_flag(req, SIP_PKT_IGNORE))
14091 transmit_response(p, "480 Temporarily Unavailable", req);
14092 else
14093 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
14094 break;
14095 case AST_PBX_SUCCESS:
14096 /* nothing to do */
14097 break;
14100 if (res) {
14102 /* Unlock locks so ast_hangup can do its magic */
14103 ast_mutex_unlock(&c->lock);
14104 ast_mutex_unlock(&p->lock);
14105 ast_hangup(c);
14106 ast_mutex_lock(&p->lock);
14107 c = NULL;
14109 } else { /* Pickup call in call group */
14110 ast_channel_unlock(c);
14111 *nounlock = 1;
14112 if (ast_pickup_call(c)) {
14113 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
14114 if (ast_test_flag(req, SIP_PKT_IGNORE))
14115 transmit_response(p, "503 Unavailable", req); /* OEJ - Right answer? */
14116 else
14117 transmit_response_reliable(p, "503 Unavailable", req);
14118 sip_alreadygone(p);
14119 /* Unlock locks so ast_hangup can do its magic */
14120 ast_mutex_unlock(&p->lock);
14121 c->hangupcause = AST_CAUSE_CALL_REJECTED;
14122 } else {
14123 ast_mutex_unlock(&p->lock);
14124 ast_setstate(c, AST_STATE_DOWN);
14125 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
14127 p->invitestate = INV_COMPLETED;
14128 ast_hangup(c);
14129 ast_mutex_lock(&p->lock);
14130 c = NULL;
14132 break;
14133 case AST_STATE_RING:
14134 transmit_response(p, "100 Trying", req);
14135 p->invitestate = INV_PROCEEDING;
14136 break;
14137 case AST_STATE_RINGING:
14138 transmit_response(p, "180 Ringing", req);
14139 p->invitestate = INV_PROCEEDING;
14140 break;
14141 case AST_STATE_UP:
14142 if (option_debug > 1)
14143 ast_log(LOG_DEBUG, "%s: This call is UP.... \n", c->name);
14145 transmit_response(p, "100 Trying", req);
14147 if (p->t38.state == T38_PEER_REINVITE) {
14148 struct ast_channel *bridgepeer = NULL;
14149 struct sip_pvt *bridgepvt = NULL;
14151 if ((bridgepeer = ast_bridged_channel(p->owner))) {
14152 /* 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*/
14153 /*! XXX: we should also check here does the other side supports t38 at all !!! XXX */
14154 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
14155 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
14156 if (bridgepvt->t38.state == T38_DISABLED) {
14157 if (bridgepvt->udptl) { /* If everything is OK with other side's udptl struct */
14158 /* Send re-invite to the bridged channel */
14159 sip_handle_t38_reinvite(bridgepeer, p, 1);
14160 } else { /* Something is wrong with peers udptl struct */
14161 ast_log(LOG_WARNING, "Strange... The other side of the bridge don't have udptl struct\n");
14162 ast_mutex_lock(&bridgepvt->lock);
14163 bridgepvt->t38.state = T38_DISABLED;
14164 ast_mutex_unlock(&bridgepvt->lock);
14165 if (option_debug > 1)
14166 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->name);
14167 if (ast_test_flag(req, SIP_PKT_IGNORE))
14168 transmit_response(p, "488 Not acceptable here", req);
14169 else
14170 transmit_response_reliable(p, "488 Not acceptable here", req);
14173 } else {
14174 /* The other side is already setup for T.38 most likely so we need to acknowledge this too */
14175 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
14176 p->t38.state = T38_ENABLED;
14177 if (option_debug)
14178 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14180 } else {
14181 /* Other side is not a SIP channel */
14182 if (ast_test_flag(req, SIP_PKT_IGNORE))
14183 transmit_response(p, "488 Not acceptable here", req);
14184 else
14185 transmit_response_reliable(p, "488 Not acceptable here", req);
14186 p->t38.state = T38_DISABLED;
14187 if (option_debug > 1)
14188 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14190 if (!p->lastinvite) /* Only destroy if this is *not* a re-invite */
14191 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14193 } else {
14194 /* we are not bridged in a call */
14195 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
14196 p->t38.state = T38_ENABLED;
14197 if (option_debug)
14198 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14200 } else if (p->t38.state == T38_DISABLED) { /* Channel doesn't have T38 offered or enabled */
14201 int sendok = TRUE;
14203 /* If we are bridged to a channel that has T38 enabled than this is a case of RTP re-invite after T38 session */
14204 /* so handle it here (re-invite other party to RTP) */
14205 struct ast_channel *bridgepeer = NULL;
14206 struct sip_pvt *bridgepvt = NULL;
14207 if ((bridgepeer = ast_bridged_channel(p->owner))) {
14208 if ((bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) && !ast_check_hangup(bridgepeer)) {
14209 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
14210 /* Does the bridged peer have T38 ? */
14211 if (bridgepvt->t38.state == T38_ENABLED) {
14212 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
14213 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
14214 if (ast_test_flag(req, SIP_PKT_IGNORE))
14215 transmit_response(p, "488 Not Acceptable Here (unsupported)", req);
14216 else
14217 transmit_response_reliable(p, "488 Not Acceptable Here (unsupported)", req);
14218 sendok = FALSE;
14220 /* No bridged peer with T38 enabled*/
14223 /* Respond to normal re-invite */
14224 if (sendok)
14225 /* If this is not a re-invite or something to ignore - it's critical */
14226 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (ast_test_flag(req, SIP_PKT_IGNORE) ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
14228 p->invitestate = INV_TERMINATED;
14229 break;
14230 default:
14231 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
14232 transmit_response(p, "100 Trying", req);
14233 break;
14235 } else {
14236 if (p && (p->autokillid == -1)) {
14237 const char *msg;
14239 if (!p->jointcapability)
14240 msg = "488 Not Acceptable Here (codec error)";
14241 else {
14242 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
14243 msg = "503 Unavailable";
14245 if (ast_test_flag(req, SIP_PKT_IGNORE))
14246 transmit_response(p, msg, req);
14247 else
14248 transmit_response_reliable(p, msg, req);
14249 p->invitestate = INV_COMPLETED;
14250 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14253 return res;
14256 /*! \brief Find all call legs and bridge transferee with target
14257 * called from handle_request_refer */
14258 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
14260 struct sip_dual target; /* Chan 1: Call from tranferer to Asterisk */
14261 /* Chan 2: Call from Asterisk to target */
14262 int res = 0;
14263 struct sip_pvt *targetcall_pvt;
14265 /* Check if the call ID of the replaces header does exist locally */
14266 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
14267 transferer->refer->replaces_callid_fromtag))) {
14268 if (transferer->refer->localtransfer) {
14269 /* We did not find the refered call. Sorry, can't accept then */
14270 transmit_response(transferer, "202 Accepted", req);
14271 /* Let's fake a response from someone else in order
14272 to follow the standard */
14273 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
14274 append_history(transferer, "Xfer", "Refer failed");
14275 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
14276 transferer->refer->status = REFER_FAILED;
14277 return -1;
14279 /* Fall through for remote transfers that we did not find locally */
14280 if (option_debug > 2)
14281 ast_log(LOG_DEBUG, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
14282 return 0;
14285 /* Ok, we can accept this transfer */
14286 transmit_response(transferer, "202 Accepted", req);
14287 append_history(transferer, "Xfer", "Refer accepted");
14288 if (!targetcall_pvt->owner) { /* No active channel */
14289 if (option_debug > 3)
14290 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No owner of target call\n");
14291 /* Cancel transfer */
14292 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
14293 append_history(transferer, "Xfer", "Refer failed");
14294 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
14295 transferer->refer->status = REFER_FAILED;
14296 ast_mutex_unlock(&targetcall_pvt->lock);
14297 ast_channel_unlock(current->chan1);
14298 return -1;
14301 /* We have a channel, find the bridge */
14302 target.chan1 = targetcall_pvt->owner; /* Transferer to Asterisk */
14303 target.chan2 = ast_bridged_channel(targetcall_pvt->owner); /* Asterisk to target */
14305 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
14306 /* Wrong state of new channel */
14307 if (option_debug > 3) {
14308 if (target.chan2)
14309 ast_log(LOG_DEBUG, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
14310 else if (target.chan1->_state != AST_STATE_RING)
14311 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No target channel\n");
14312 else
14313 ast_log(LOG_DEBUG, "SIP attended transfer: Attempting transfer in ringing state\n");
14317 /* Transfer */
14318 if (option_debug > 3 && sipdebug) {
14319 if (current->chan2) /* We have two bridges */
14320 ast_log(LOG_DEBUG, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
14321 else /* One bridge, propably transfer of IVR/voicemail etc */
14322 ast_log(LOG_DEBUG, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
14325 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
14327 /* Perform the transfer */
14328 res = attempt_transfer(current, &target);
14329 ast_mutex_unlock(&targetcall_pvt->lock);
14330 if (res) {
14331 /* Failed transfer */
14332 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
14333 append_history(transferer, "Xfer", "Refer failed");
14334 transferer->refer->status = REFER_FAILED;
14335 if (targetcall_pvt->owner)
14336 ast_channel_unlock(targetcall_pvt->owner);
14337 /* Right now, we have to hangup, sorry. Bridge is destroyed */
14338 if (res != -2)
14339 ast_hangup(transferer->owner);
14340 else
14341 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
14342 } else {
14343 /* Transfer succeeded! */
14345 /* Tell transferer that we're done. */
14346 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
14347 append_history(transferer, "Xfer", "Refer succeeded");
14348 transferer->refer->status = REFER_200OK;
14349 if (targetcall_pvt->owner) {
14350 if (option_debug)
14351 ast_log(LOG_DEBUG, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
14352 ast_channel_unlock(targetcall_pvt->owner);
14355 return 1;
14359 /*! \brief Handle incoming REFER request */
14360 /*! \page SIP_REFER SIP transfer Support (REFER)
14362 REFER is used for call transfer in SIP. We get a REFER
14363 to place a new call with an INVITE somwhere and then
14364 keep the transferor up-to-date of the transfer. If the
14365 transfer fails, get back on line with the orginal call.
14367 - REFER can be sent outside or inside of a dialog.
14368 Asterisk only accepts REFER inside of a dialog.
14370 - If we get a replaces header, it is an attended transfer
14372 \par Blind transfers
14373 The transferor provides the transferee
14374 with the transfer targets contact. The signalling between
14375 transferer or transferee should not be cancelled, so the
14376 call is recoverable if the transfer target can not be reached
14377 by the transferee.
14379 In this case, Asterisk receives a TRANSFER from
14380 the transferor, thus is the transferee. We should
14381 try to set up a call to the contact provided
14382 and if that fails, re-connect the current session.
14383 If the new call is set up, we issue a hangup.
14384 In this scenario, we are following section 5.2
14385 in the SIP CC Transfer draft. (Transfer without
14386 a GRUU)
14388 \par Transfer with consultation hold
14389 In this case, the transferor
14390 talks to the transfer target before the transfer takes place.
14391 This is implemented with SIP hold and transfer.
14392 Note: The invite From: string could indicate a transfer.
14393 (Section 6. Transfer with consultation hold)
14394 The transferor places the transferee on hold, starts a call
14395 with the transfer target to alert them to the impending
14396 transfer, terminates the connection with the target, then
14397 proceeds with the transfer (as in Blind transfer above)
14399 \par Attended transfer
14400 The transferor places the transferee
14401 on hold, calls the transfer target to alert them,
14402 places the target on hold, then proceeds with the transfer
14403 using a Replaces header field in the Refer-to header. This
14404 will force the transfee to send an Invite to the target,
14405 with a replaces header that instructs the target to
14406 hangup the call between the transferor and the target.
14407 In this case, the Refer/to: uses the AOR address. (The same
14408 URI that the transferee used to establish the session with
14409 the transfer target (To: ). The Require: replaces header should
14410 be in the INVITE to avoid the wrong UA in a forked SIP proxy
14411 scenario to answer and have no call to replace with.
14413 The referred-by header is *NOT* required, but if we get it,
14414 can be copied into the INVITE to the transfer target to
14415 inform the target about the transferor
14417 "Any REFER request has to be appropriately authenticated.".
14419 We can't destroy dialogs, since we want the call to continue.
14422 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock)
14424 struct sip_dual current; /* Chan1: Call between asterisk and transferer */
14425 /* Chan2: Call between asterisk and transferee */
14427 int res = 0;
14429 if (ast_test_flag(req, SIP_PKT_DEBUG))
14430 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");
14432 if (!p->owner) {
14433 /* This is a REFER outside of an existing SIP dialog */
14434 /* We can't handle that, so decline it */
14435 if (option_debug > 2)
14436 ast_log(LOG_DEBUG, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
14437 transmit_response(p, "603 Declined (No dialog)", req);
14438 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
14439 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
14440 sip_alreadygone(p);
14441 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14443 return 0;
14447 /* Check if transfer is allowed from this device */
14448 if (p->allowtransfer == TRANSFER_CLOSED ) {
14449 /* Transfer not allowed, decline */
14450 transmit_response(p, "603 Declined (policy)", req);
14451 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
14452 /* Do not destroy SIP session */
14453 return 0;
14456 if(!ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
14457 /* Already have a pending REFER */
14458 transmit_response(p, "491 Request pending", req);
14459 append_history(p, "Xfer", "Refer failed. Request pending.");
14460 return 0;
14463 /* Allocate memory for call transfer data */
14464 if (!p->refer && !sip_refer_allocate(p)) {
14465 transmit_response(p, "500 Internal Server Error", req);
14466 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
14467 return -3;
14470 res = get_refer_info(p, req); /* Extract headers */
14472 p->refer->status = REFER_SENT;
14474 if (res != 0) {
14475 switch (res) {
14476 case -2: /* Syntax error */
14477 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
14478 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
14479 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14480 ast_log(LOG_DEBUG, "SIP transfer to black hole can't be handled (no refer-to: )\n");
14481 break;
14482 case -3:
14483 transmit_response(p, "603 Declined (Non sip: uri)", req);
14484 append_history(p, "Xfer", "Refer failed. Non SIP uri");
14485 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14486 ast_log(LOG_DEBUG, "SIP transfer to non-SIP uri denied\n");
14487 break;
14488 default:
14489 /* Refer-to extension not found, fake a failed transfer */
14490 transmit_response(p, "202 Accepted", req);
14491 append_history(p, "Xfer", "Refer failed. Bad extension.");
14492 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
14493 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14494 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14495 ast_log(LOG_DEBUG, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
14496 break;
14498 return 0;
14500 if (ast_strlen_zero(p->context))
14501 ast_string_field_set(p, context, default_context);
14503 /* If we do not support SIP domains, all transfers are local */
14504 if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
14505 p->refer->localtransfer = 1;
14506 if (sipdebug && option_debug > 2)
14507 ast_log(LOG_DEBUG, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
14508 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
14509 /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
14510 p->refer->localtransfer = 1;
14511 } else if (sipdebug && option_debug > 2)
14512 ast_log(LOG_DEBUG, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
14514 /* Is this a repeat of a current request? Ignore it */
14515 /* Don't know what else to do right now. */
14516 if (ignore)
14517 return res;
14519 /* If this is a blind transfer, we have the following
14520 channels to work with:
14521 - chan1, chan2: The current call between transferer and transferee (2 channels)
14522 - target_channel: A new call from the transferee to the target (1 channel)
14523 We need to stay tuned to what happens in order to be able
14524 to bring back the call to the transferer */
14526 /* If this is a attended transfer, we should have all call legs within reach:
14527 - chan1, chan2: The call between the transferer and transferee (2 channels)
14528 - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
14529 We want to bridge chan2 with targetcall_pvt!
14531 The replaces call id in the refer message points
14532 to the call leg between Asterisk and the transferer.
14533 So we need to connect the target and the transferee channel
14534 and hangup the two other channels silently
14536 If the target is non-local, the call ID could be on a remote
14537 machine and we need to send an INVITE with replaces to the
14538 target. We basically handle this as a blind transfer
14539 and let the sip_call function catch that we need replaces
14540 header in the INVITE.
14544 /* Get the transferer's channel */
14545 current.chan1 = p->owner;
14547 /* Find the other part of the bridge (2) - transferee */
14548 current.chan2 = ast_bridged_channel(current.chan1);
14550 if (sipdebug && option_debug > 2)
14551 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>");
14553 if (!current.chan2 && !p->refer->attendedtransfer) {
14554 /* No bridged channel, propably IVR or echo or similar... */
14555 /* Guess we should masquerade or something here */
14556 /* Until we figure it out, refuse transfer of such calls */
14557 if (sipdebug && option_debug > 2)
14558 ast_log(LOG_DEBUG,"Refused SIP transfer on non-bridged channel.\n");
14559 p->refer->status = REFER_FAILED;
14560 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
14561 transmit_response(p, "603 Declined", req);
14562 return -1;
14565 if (current.chan2) {
14566 if (sipdebug && option_debug > 3)
14567 ast_log(LOG_DEBUG, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
14569 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
14572 ast_set_flag(&p->flags[0], SIP_GOTREFER);
14574 /* Attended transfer: Find all call legs and bridge transferee with target*/
14575 if (p->refer->attendedtransfer) {
14576 if ((res = local_attended_transfer(p, &current, req, seqno)))
14577 return res; /* We're done with the transfer */
14578 /* Fall through for remote transfers that we did not find locally */
14579 if (sipdebug && option_debug > 3)
14580 ast_log(LOG_DEBUG, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
14581 /* Fallthrough if we can't find the call leg internally */
14585 /* Parking a call */
14586 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
14587 /* Must release c's lock now, because it will not longer be accessible after the transfer! */
14588 *nounlock = 1;
14589 ast_channel_unlock(current.chan1);
14590 copy_request(&current.req, req);
14591 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14592 p->refer->status = REFER_200OK;
14593 append_history(p, "Xfer", "REFER to call parking.");
14594 if (sipdebug && option_debug > 3)
14595 ast_log(LOG_DEBUG, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
14596 sip_park(current.chan2, current.chan1, req, seqno);
14597 return res;
14600 /* Blind transfers and remote attended xfers */
14601 transmit_response(p, "202 Accepted", req);
14603 if (current.chan1 && current.chan2) {
14604 if (option_debug > 2)
14605 ast_log(LOG_DEBUG, "chan1->name: %s\n", current.chan1->name);
14606 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
14608 if (current.chan2) {
14609 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
14610 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
14611 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
14612 /* One for the new channel */
14613 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
14614 /* Attended transfer to remote host, prepare headers for the INVITE */
14615 if (p->refer->referred_by)
14616 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
14618 /* Generate a Replaces string to be used in the INVITE during attended transfer */
14619 if (p->refer->replaces_callid && !ast_strlen_zero(p->refer->replaces_callid)) {
14620 char tempheader[SIPBUFSIZE];
14621 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
14622 p->refer->replaces_callid_totag ? ";to-tag=" : "",
14623 p->refer->replaces_callid_totag,
14624 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
14625 p->refer->replaces_callid_fromtag);
14626 if (current.chan2)
14627 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
14629 /* Must release lock now, because it will not longer
14630 be accessible after the transfer! */
14631 *nounlock = 1;
14632 ast_channel_unlock(current.chan1);
14634 /* Connect the call */
14636 /* FAKE ringing if not attended transfer */
14637 if (!p->refer->attendedtransfer)
14638 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
14640 /* For blind transfer, this will lead to a new call */
14641 /* For attended transfer to remote host, this will lead to
14642 a new SIP call with a replaces header, if the dial plan allows it
14644 if (!current.chan2) {
14645 /* We have no bridge, so we're talking with Asterisk somehow */
14646 /* We need to masquerade this call */
14647 /* What to do to fix this situation:
14648 * Set up the new call in a new channel
14649 * Let the new channel masq into this channel
14650 Please add that code here :-)
14652 p->refer->status = REFER_FAILED;
14653 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
14654 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14655 append_history(p, "Xfer", "Refer failed (only bridged calls).");
14656 return -1;
14658 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
14660 /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
14661 servers - generate an INVITE with Replaces. Either way, let the dial plan decided */
14662 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
14664 if (!res) {
14665 /* Success - we have a new channel */
14666 if (option_debug > 2)
14667 ast_log(LOG_DEBUG, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
14668 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
14669 if (p->refer->localtransfer)
14670 p->refer->status = REFER_200OK;
14671 if (p->owner)
14672 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
14673 append_history(p, "Xfer", "Refer succeeded.");
14674 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14675 /* Do not hangup call, the other side do that when we say 200 OK */
14676 /* We could possibly implement a timer here, auto congestion */
14677 res = 0;
14678 } else {
14679 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
14680 if (option_debug > 2)
14681 ast_log(LOG_DEBUG, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
14682 append_history(p, "Xfer", "Refer failed.");
14683 /* Failure of some kind */
14684 p->refer->status = REFER_FAILED;
14685 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
14686 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14687 res = -1;
14689 return res;
14692 /*! \brief Handle incoming CANCEL request */
14693 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
14696 check_via(p, req);
14697 sip_alreadygone(p);
14699 /* At this point, we could have cancelled the invite at the same time
14700 as the other side sends a CANCEL. Our final reply with error code
14701 might not have been received by the other side before the CANCEL
14702 was sent, so let's just give up retransmissions and waiting for
14703 ACK on our error code. The call is hanging up any way. */
14704 if (p->invitestate == INV_TERMINATED)
14705 __sip_pretend_ack(p);
14706 else
14707 p->invitestate = INV_CANCELLED;
14709 if (p->owner && p->owner->_state == AST_STATE_UP) {
14710 /* This call is up, cancel is ignored, we need a bye */
14711 transmit_response(p, "200 OK", req);
14712 if (option_debug)
14713 ast_log(LOG_DEBUG, "Got CANCEL on an answered call. Ignoring... \n");
14714 return 0;
14717 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
14718 update_call_counter(p, DEC_CALL_LIMIT);
14720 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
14721 if (p->owner)
14722 ast_queue_hangup(p->owner);
14723 else
14724 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14725 if (p->initreq.len > 0) {
14726 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
14727 transmit_response(p, "200 OK", req);
14728 return 1;
14729 } else {
14730 transmit_response(p, "481 Call Leg Does Not Exist", req);
14731 return 0;
14735 static int acf_channel_read(struct ast_channel *chan, char *funcname, char *preparse, char *buf, size_t buflen)
14737 struct ast_rtp_quality qos;
14738 struct sip_pvt *p = chan->tech_pvt;
14739 char *all = "", *parse = ast_strdupa(preparse);
14740 AST_DECLARE_APP_ARGS(args,
14741 AST_APP_ARG(param);
14742 AST_APP_ARG(type);
14743 AST_APP_ARG(field);
14745 AST_STANDARD_APP_ARGS(args, parse);
14747 /* Sanity check */
14748 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
14749 ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
14750 return 0;
14753 if (strcasecmp(args.param, "rtpqos"))
14754 return 0;
14756 /* Default arguments of audio,all */
14757 if (ast_strlen_zero(args.type))
14758 args.type = "audio";
14759 if (ast_strlen_zero(args.field))
14760 args.field = "all";
14762 memset(buf, 0, buflen);
14763 memset(&qos, 0, sizeof(qos));
14765 if (strcasecmp(args.type, "AUDIO") == 0) {
14766 all = ast_rtp_get_quality(p->rtp, &qos);
14767 } else if (strcasecmp(args.type, "VIDEO") == 0) {
14768 all = ast_rtp_get_quality(p->vrtp, &qos);
14771 if (strcasecmp(args.field, "local_ssrc") == 0)
14772 snprintf(buf, buflen, "%u", qos.local_ssrc);
14773 else if (strcasecmp(args.field, "local_lostpackets") == 0)
14774 snprintf(buf, buflen, "%u", qos.local_lostpackets);
14775 else if (strcasecmp(args.field, "local_jitter") == 0)
14776 snprintf(buf, buflen, "%.0lf", qos.local_jitter * 1000.0);
14777 else if (strcasecmp(args.field, "local_count") == 0)
14778 snprintf(buf, buflen, "%u", qos.local_count);
14779 else if (strcasecmp(args.field, "remote_ssrc") == 0)
14780 snprintf(buf, buflen, "%u", qos.remote_ssrc);
14781 else if (strcasecmp(args.field, "remote_lostpackets") == 0)
14782 snprintf(buf, buflen, "%u", qos.remote_lostpackets);
14783 else if (strcasecmp(args.field, "remote_jitter") == 0)
14784 snprintf(buf, buflen, "%.0lf", qos.remote_jitter * 1000.0);
14785 else if (strcasecmp(args.field, "remote_count") == 0)
14786 snprintf(buf, buflen, "%u", qos.remote_count);
14787 else if (strcasecmp(args.field, "rtt") == 0)
14788 snprintf(buf, buflen, "%.0lf", qos.rtt * 1000.0);
14789 else if (strcasecmp(args.field, "all") == 0)
14790 ast_copy_string(buf, all, buflen);
14791 else {
14792 ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
14793 return -1;
14795 return 0;
14798 /*! \brief Handle incoming BYE request */
14799 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
14801 struct ast_channel *c=NULL;
14802 int res;
14803 struct ast_channel *bridged_to;
14805 /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
14806 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner)
14807 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
14809 p->invitestate = INV_TERMINATED;
14811 copy_request(&p->initreq, req);
14812 check_via(p, req);
14813 sip_alreadygone(p);
14815 /* Get RTCP quality before end of call */
14816 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY) || p->owner) {
14817 char *audioqos, *videoqos;
14818 if (p->rtp) {
14819 audioqos = ast_rtp_get_quality(p->rtp, NULL);
14820 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
14821 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
14822 if (p->owner)
14823 pbx_builtin_setvar_helper(p->owner, "RTPAUDIOQOS", audioqos);
14825 if (p->vrtp) {
14826 videoqos = ast_rtp_get_quality(p->vrtp, NULL);
14827 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
14828 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
14829 if (p->owner)
14830 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
14834 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
14836 if (!ast_strlen_zero(get_header(req, "Also"))) {
14837 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
14838 ast_inet_ntoa(p->recv.sin_addr));
14839 if (ast_strlen_zero(p->context))
14840 ast_string_field_set(p, context, default_context);
14841 res = get_also_info(p, req);
14842 if (!res) {
14843 c = p->owner;
14844 if (c) {
14845 bridged_to = ast_bridged_channel(c);
14846 if (bridged_to) {
14847 /* Don't actually hangup here... */
14848 ast_queue_control(c, AST_CONTROL_UNHOLD);
14849 ast_async_goto(bridged_to, p->context, p->refer->refer_to,1);
14850 } else
14851 ast_queue_hangup(p->owner);
14853 } else {
14854 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
14855 if (p->owner)
14856 ast_queue_hangup(p->owner);
14858 } else if (p->owner) {
14859 ast_queue_hangup(p->owner);
14860 if (option_debug > 2)
14861 ast_log(LOG_DEBUG, "Received bye, issuing owner hangup\n");
14862 } else {
14863 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14864 if (option_debug > 2)
14865 ast_log(LOG_DEBUG, "Received bye, no owner, selfdestruct soon.\n");
14867 transmit_response(p, "200 OK", req);
14869 return 1;
14872 /*! \brief Handle incoming MESSAGE request */
14873 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
14875 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
14876 if (ast_test_flag(req, SIP_PKT_DEBUG))
14877 ast_verbose("Receiving message!\n");
14878 receive_message(p, req);
14879 } else
14880 transmit_response(p, "202 Accepted", req);
14881 return 1;
14884 /*! \brief Handle incoming SUBSCRIBE request */
14885 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
14887 int gotdest;
14888 int res = 0;
14889 int firststate = AST_EXTENSION_REMOVED;
14890 struct sip_peer *authpeer = NULL;
14891 const char *eventheader = get_header(req, "Event"); /* Get Event package name */
14892 const char *accept = get_header(req, "Accept");
14893 int resubscribe = (p->subscribed != NONE);
14894 char *temp, *event;
14896 if (p->initreq.headers) {
14897 /* We already have a dialog */
14898 if (p->initreq.method != SIP_SUBSCRIBE) {
14899 /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
14900 /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
14901 transmit_response(p, "403 Forbidden (within dialog)", req);
14902 /* Do not destroy session, since we will break the call if we do */
14903 if (option_debug)
14904 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);
14905 return 0;
14906 } else if (ast_test_flag(req, SIP_PKT_DEBUG)) {
14907 if (option_debug) {
14908 if (resubscribe)
14909 ast_log(LOG_DEBUG, "Got a re-subscribe on existing subscription %s\n", p->callid);
14910 else
14911 ast_log(LOG_DEBUG, "Got a new subscription %s (possibly with auth)\n", p->callid);
14916 /* Check if we have a global disallow setting on subscriptions.
14917 if so, we don't have to check peer/user settings after auth, which saves a lot of processing
14919 if (!global_allowsubscribe) {
14920 transmit_response(p, "403 Forbidden (policy)", req);
14921 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14922 return 0;
14925 if (!ast_test_flag(req, SIP_PKT_IGNORE) && !resubscribe) { /* Set up dialog, new subscription */
14926 const char *to = get_header(req, "To");
14927 char totag[128];
14929 /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
14930 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
14931 if (ast_test_flag(req, SIP_PKT_DEBUG))
14932 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
14933 transmit_response(p, "481 Subscription does not exist", req);
14934 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14935 return 0;
14938 /* Use this as the basis */
14939 if (ast_test_flag(req, SIP_PKT_DEBUG))
14940 ast_verbose("Creating new subscription\n");
14942 copy_request(&p->initreq, req);
14943 check_via(p, req);
14944 } else if (ast_test_flag(req, SIP_PKT_DEBUG) && ast_test_flag(req, SIP_PKT_IGNORE))
14945 ast_verbose("Ignoring this SUBSCRIBE request\n");
14947 /* Find parameters to Event: header value and remove them for now */
14948 if (ast_strlen_zero(eventheader)) {
14949 transmit_response(p, "489 Bad Event", req);
14950 if (option_debug > 1)
14951 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: <none>\n");
14952 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14953 return 0;
14956 if ( (strchr(eventheader, ';'))) {
14957 event = ast_strdupa(eventheader); /* Since eventheader is a const, we can't change it */
14958 temp = strchr(event, ';');
14959 *temp = '\0'; /* Remove any options for now */
14960 /* We might need to use them later :-) */
14961 } else
14962 event = (char *) eventheader; /* XXX is this legal ? */
14964 /* Handle authentication */
14965 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
14966 /* if an authentication response was sent, we are done here */
14967 if (res == AUTH_CHALLENGE_SENT) {
14968 if (authpeer)
14969 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14970 return 0;
14972 if (res < 0) {
14973 if (res == AUTH_FAKE_AUTH) {
14974 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
14975 transmit_fake_auth_response(p, req, 1);
14976 } else {
14977 ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
14978 transmit_response_reliable(p, "403 Forbidden", req);
14980 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14981 if (authpeer)
14982 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14983 return 0;
14986 /* Check if this user/peer is allowed to subscribe at all */
14987 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
14988 transmit_response(p, "403 Forbidden (policy)", req);
14989 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14990 if (authpeer)
14991 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14992 return 0;
14995 /* Get destination right away */
14996 gotdest = get_destination(p, NULL);
14998 /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
14999 parse_ok_contact(p, req);
15001 build_contact(p);
15002 if (strcmp(event, "message-summary") && gotdest) {
15003 transmit_response(p, "404 Not Found", req);
15004 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15005 if (authpeer)
15006 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15007 return 0;
15010 /* Initialize tag for new subscriptions */
15011 if (ast_strlen_zero(p->tag))
15012 make_our_tag(p->tag, sizeof(p->tag));
15014 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
15015 if (authpeer) /* No need for authpeer here */
15016 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15018 /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
15019 /* Polycom phones only handle xpidf+xml, even if they say they can
15020 handle pidf+xml as well
15022 if (strstr(p->useragent, "Polycom")) {
15023 p->subscribed = XPIDF_XML;
15024 } else if (strstr(accept, "application/pidf+xml")) {
15025 p->subscribed = PIDF_XML; /* RFC 3863 format */
15026 } else if (strstr(accept, "application/dialog-info+xml")) {
15027 p->subscribed = DIALOG_INFO_XML;
15028 /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
15029 } else if (strstr(accept, "application/cpim-pidf+xml")) {
15030 p->subscribed = CPIM_PIDF_XML; /* RFC 3863 format */
15031 } else if (strstr(accept, "application/xpidf+xml")) {
15032 p->subscribed = XPIDF_XML; /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
15033 } else if (ast_strlen_zero(accept)) {
15034 if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
15035 transmit_response(p, "489 Bad Event", req);
15037 ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
15038 p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
15039 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15040 return 0;
15042 /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
15043 so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
15044 } else {
15045 /* Can't find a format for events that we know about */
15046 char mybuf[200];
15047 snprintf(mybuf,sizeof(mybuf),"489 Bad Event (format %s)", accept);
15048 transmit_response(p, mybuf, req);
15050 ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
15051 accept, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
15052 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15053 return 0;
15055 } else if (!strcmp(event, "message-summary")) {
15056 if (!ast_strlen_zero(accept) && strcmp(accept, "application/simple-message-summary")) {
15057 /* Format requested that we do not support */
15058 transmit_response(p, "406 Not Acceptable", req);
15059 if (option_debug > 1)
15060 ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", accept);
15061 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15062 if (authpeer) /* No need for authpeer here */
15063 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15064 return 0;
15066 /* Looks like they actually want a mailbox status
15067 This version of Asterisk supports mailbox subscriptions
15068 The subscribed URI needs to exist in the dial plan
15069 In most devices, this is configurable to the voicemailmain extension you use
15071 if (!authpeer || ast_strlen_zero(authpeer->mailbox)) {
15072 transmit_response(p, "404 Not found (no mailbox)", req);
15073 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15074 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
15075 if (authpeer) /* No need for authpeer here */
15076 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15077 return 0;
15080 p->subscribed = MWI_NOTIFICATION;
15081 if (authpeer->mwipvt && authpeer->mwipvt != p) /* Destroy old PVT if this is a new one */
15082 /* We only allow one subscription per peer */
15083 sip_destroy(authpeer->mwipvt);
15084 authpeer->mwipvt = p; /* Link from peer to pvt */
15085 p->relatedpeer = authpeer; /* Link from pvt to peer */
15086 } else { /* At this point, Asterisk does not understand the specified event */
15087 transmit_response(p, "489 Bad Event", req);
15088 if (option_debug > 1)
15089 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: %s\n", event);
15090 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15091 if (authpeer) /* No need for authpeer here */
15092 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15093 return 0;
15096 if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
15097 if (p->stateid > -1)
15098 ast_extension_state_del(p->stateid, cb_extensionstate);
15099 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, p);
15102 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
15103 p->lastinvite = seqno;
15104 if (p && !ast_test_flag(&p->flags[0], SIP_NEEDDESTROY)) {
15105 p->expiry = atoi(get_header(req, "Expires"));
15107 /* check if the requested expiry-time is within the approved limits from sip.conf */
15108 if (p->expiry > max_expiry)
15109 p->expiry = max_expiry;
15110 if (p->expiry < min_expiry && p->expiry > 0)
15111 p->expiry = min_expiry;
15113 if (sipdebug || option_debug > 1) {
15114 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
15115 ast_log(LOG_DEBUG, "Adding subscription for mailbox notification - peer %s Mailbox %s\n", p->relatedpeer->name, p->relatedpeer->mailbox);
15116 else
15117 ast_log(LOG_DEBUG, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
15119 if (p->autokillid > -1 && sip_cancel_destroy(p)) /* Remove subscription expiry for renewals */
15120 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15121 if (p->expiry > 0)
15122 sip_scheddestroy(p, (p->expiry + 10) * 1000); /* Set timer for destruction of call at expiration */
15124 if (p->subscribed == MWI_NOTIFICATION) {
15125 transmit_response(p, "200 OK", req);
15126 if (p->relatedpeer) { /* Send first notification */
15127 ASTOBJ_WRLOCK(p->relatedpeer);
15128 sip_send_mwi_to_peer(p->relatedpeer);
15129 ASTOBJ_UNLOCK(p->relatedpeer);
15131 } else {
15132 struct sip_pvt *p_old;
15134 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
15136 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));
15137 transmit_response(p, "404 Not found", req);
15138 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15139 return 0;
15142 transmit_response(p, "200 OK", req);
15143 transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
15144 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
15145 /* hide the 'complete' exten/context in the refer_to field for later display */
15146 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
15148 /* remove any old subscription from this peer for the same exten/context,
15149 as the peer has obviously forgotten about it and it's wasteful to wait
15150 for it to expire and send NOTIFY messages to the peer only to have them
15151 ignored (or generate errors)
15153 ast_mutex_lock(&iflock);
15154 for (p_old = iflist; p_old; p_old = p_old->next) {
15155 if (p_old == p)
15156 continue;
15157 if (p_old->initreq.method != SIP_SUBSCRIBE)
15158 continue;
15159 if (p_old->subscribed == NONE)
15160 continue;
15161 ast_mutex_lock(&p_old->lock);
15162 if (!strcmp(p_old->username, p->username)) {
15163 if (!strcmp(p_old->exten, p->exten) &&
15164 !strcmp(p_old->context, p->context)) {
15165 ast_set_flag(&p_old->flags[0], SIP_NEEDDESTROY);
15166 ast_mutex_unlock(&p_old->lock);
15167 break;
15170 ast_mutex_unlock(&p_old->lock);
15172 ast_mutex_unlock(&iflock);
15174 if (!p->expiry)
15175 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15177 return 1;
15180 /*! \brief Handle incoming REGISTER request */
15181 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
15183 enum check_auth_result res;
15185 /* Use this as the basis */
15186 if (ast_test_flag(req, SIP_PKT_DEBUG))
15187 ast_verbose("Using latest REGISTER request as basis request\n");
15188 copy_request(&p->initreq, req);
15189 check_via(p, req);
15190 if ((res = register_verify(p, sin, req, e)) < 0) {
15191 const char *reason;
15193 switch (res) {
15194 case AUTH_SECRET_FAILED:
15195 reason = "Wrong password";
15196 break;
15197 case AUTH_USERNAME_MISMATCH:
15198 reason = "Username/auth name mismatch";
15199 break;
15200 case AUTH_NOT_FOUND:
15201 reason = "No matching peer found";
15202 break;
15203 case AUTH_UNKNOWN_DOMAIN:
15204 reason = "Not a local domain";
15205 break;
15206 case AUTH_PEER_NOT_DYNAMIC:
15207 reason = "Peer is not supposed to register";
15208 break;
15209 case AUTH_ACL_FAILED:
15210 reason = "Device does not match ACL";
15211 break;
15212 default:
15213 reason = "Unknown failure";
15214 break;
15216 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
15217 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
15218 reason);
15219 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
15220 } else
15221 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
15223 if (res < 1) {
15224 /* Destroy the session, but keep us around for just a bit in case they don't
15225 get our 200 OK */
15226 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15228 return res;
15231 /*! \brief Handle incoming SIP requests (methods)
15232 \note This is where all incoming requests go first */
15233 /* called with p and p->owner locked */
15234 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
15236 /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
15237 relatively static */
15238 const char *cmd;
15239 const char *cseq;
15240 const char *useragent;
15241 int seqno;
15242 int len;
15243 int ignore = FALSE;
15244 int respid;
15245 int res = 0;
15246 int debug = sip_debug_test_pvt(p);
15247 char *e;
15248 int error = 0;
15250 /* Get Method and Cseq */
15251 cseq = get_header(req, "Cseq");
15252 cmd = req->header[0];
15254 /* Must have Cseq */
15255 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
15256 ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
15257 error = 1;
15259 if (!error && sscanf(cseq, "%d%n", &seqno, &len) != 1) {
15260 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
15261 error = 1;
15263 if (error) {
15264 if (!p->initreq.headers) /* New call */
15265 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); /* Make sure we destroy this dialog */
15266 return -1;
15268 /* Get the command XXX */
15270 cmd = req->rlPart1;
15271 e = req->rlPart2;
15273 /* Save useragent of the client */
15274 useragent = get_header(req, "User-Agent");
15275 if (!ast_strlen_zero(useragent))
15276 ast_string_field_set(p, useragent, useragent);
15278 /* Find out SIP method for incoming request */
15279 if (req->method == SIP_RESPONSE) { /* Response to our request */
15280 /* Response to our request -- Do some sanity checks */
15281 if (!p->initreq.headers) {
15282 if (option_debug)
15283 ast_log(LOG_DEBUG, "That's odd... Got a response on a call we dont know about. Cseq %d Cmd %s\n", seqno, cmd);
15284 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15285 return 0;
15286 } else if (p->ocseq && (p->ocseq < seqno) && (seqno != p->lastnoninvite)) {
15287 if (option_debug)
15288 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
15289 return -1;
15290 } else if (p->ocseq && (p->ocseq != seqno) && (seqno != p->lastnoninvite)) {
15291 /* ignore means "don't do anything with it" but still have to
15292 respond appropriately */
15293 ignore = TRUE;
15294 ast_set_flag(req, SIP_PKT_IGNORE);
15295 ast_set_flag(req, SIP_PKT_IGNORE_RESP);
15296 append_history(p, "Ignore", "Ignoring this retransmit\n");
15297 } else if (e) {
15298 e = ast_skip_blanks(e);
15299 if (sscanf(e, "%d %n", &respid, &len) != 1) {
15300 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
15301 } else {
15302 if (respid <= 0) {
15303 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
15304 return 0;
15306 /* More SIP ridiculousness, we have to ignore bogus contacts in 100 etc responses */
15307 if ((respid == 200) || ((respid >= 300) && (respid <= 399)))
15308 extract_uri(p, req);
15309 handle_response(p, respid, e + len, req, ignore, seqno);
15312 return 0;
15315 /* New SIP request coming in
15316 (could be new request in existing SIP dialog as well...)
15319 p->method = req->method; /* Find out which SIP method they are using */
15320 if (option_debug > 3)
15321 ast_log(LOG_DEBUG, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
15323 if (p->icseq && (p->icseq > seqno) ) {
15324 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
15325 if (option_debug > 2)
15326 ast_log(LOG_DEBUG, "Got CANCEL or ACK on INVITE with transactions in between.\n");
15327 } else {
15328 if (option_debug)
15329 ast_log(LOG_DEBUG, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
15330 if (req->method != SIP_ACK)
15331 transmit_response(p, "503 Server error", req); /* We must respond according to RFC 3261 sec 12.2 */
15332 return -1;
15334 } else if (p->icseq &&
15335 p->icseq == seqno &&
15336 req->method != SIP_ACK &&
15337 (p->method != SIP_CANCEL || ast_test_flag(&p->flags[0], SIP_ALREADYGONE))) {
15338 /* ignore means "don't do anything with it" but still have to
15339 respond appropriately. We do this if we receive a repeat of
15340 the last sequence number */
15341 ignore = 2;
15342 ast_set_flag(req, SIP_PKT_IGNORE);
15343 ast_set_flag(req, SIP_PKT_IGNORE_REQ);
15344 if (option_debug > 2)
15345 ast_log(LOG_DEBUG, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
15348 if (seqno >= p->icseq)
15349 /* Next should follow monotonically (but not necessarily
15350 incrementally -- thanks again to the genius authors of SIP --
15351 increasing */
15352 p->icseq = seqno;
15354 /* Find their tag if we haven't got it */
15355 if (ast_strlen_zero(p->theirtag)) {
15356 char tag[128];
15358 gettag(req, "From", tag, sizeof(tag));
15359 ast_string_field_set(p, theirtag, tag);
15361 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
15363 if (pedanticsipchecking) {
15364 /* If this is a request packet without a from tag, it's not
15365 correct according to RFC 3261 */
15366 /* Check if this a new request in a new dialog with a totag already attached to it,
15367 RFC 3261 - section 12.2 - and we don't want to mess with recovery */
15368 if (!p->initreq.headers && ast_test_flag(req, SIP_PKT_WITH_TOTAG)) {
15369 /* If this is a first request and it got a to-tag, it is not for us */
15370 if (!ast_test_flag(req, SIP_PKT_IGNORE) && req->method == SIP_INVITE) {
15371 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
15372 /* Will cease to exist after ACK */
15373 } else if (req->method != SIP_ACK) {
15374 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
15375 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15377 return res;
15381 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
15382 transmit_response(p, "400 Bad request", req);
15383 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15384 return -1;
15387 /* Handle various incoming SIP methods in requests */
15388 switch (p->method) {
15389 case SIP_OPTIONS:
15390 res = handle_request_options(p, req);
15391 break;
15392 case SIP_INVITE:
15393 res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
15394 break;
15395 case SIP_REFER:
15396 res = handle_request_refer(p, req, debug, ignore, seqno, nounlock);
15397 break;
15398 case SIP_CANCEL:
15399 res = handle_request_cancel(p, req);
15400 break;
15401 case SIP_BYE:
15402 res = handle_request_bye(p, req);
15403 break;
15404 case SIP_MESSAGE:
15405 res = handle_request_message(p, req);
15406 break;
15407 case SIP_SUBSCRIBE:
15408 res = handle_request_subscribe(p, req, sin, seqno, e);
15409 break;
15410 case SIP_REGISTER:
15411 res = handle_request_register(p, req, sin, e);
15412 break;
15413 case SIP_INFO:
15414 if (ast_test_flag(req, SIP_PKT_DEBUG))
15415 ast_verbose("Receiving INFO!\n");
15416 if (!ignore)
15417 handle_request_info(p, req);
15418 else /* if ignoring, transmit response */
15419 transmit_response(p, "200 OK", req);
15420 break;
15421 case SIP_NOTIFY:
15422 res = handle_request_notify(p, req, sin, seqno, e);
15423 break;
15424 case SIP_ACK:
15425 /* Make sure we don't ignore this */
15426 if (seqno == p->pendinginvite) {
15427 p->invitestate = INV_TERMINATED;
15428 p->pendinginvite = 0;
15429 __sip_ack(p, seqno, FLAG_RESPONSE, 0);
15430 if (find_sdp(req)) {
15431 if (process_sdp(p, req))
15432 return -1;
15434 check_pendings(p);
15436 /* Got an ACK that we did not match. Ignore silently */
15437 if (!p->lastinvite && ast_strlen_zero(p->randdata))
15438 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15439 break;
15440 default:
15441 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
15442 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
15443 cmd, ast_inet_ntoa(p->sa.sin_addr));
15444 /* If this is some new method, and we don't have a call, destroy it now */
15445 if (!p->initreq.headers)
15446 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15447 break;
15449 return res;
15452 /*! \brief Read data from SIP socket
15453 \note sipsock_read locks the owner channel while we are processing the SIP message
15454 \return 1 on error, 0 on success
15455 \note Successful messages is connected to SIP call and forwarded to handle_request()
15457 static int sipsock_read(int *id, int fd, short events, void *ignore)
15459 struct sip_request req;
15460 struct sockaddr_in sin = { 0, };
15461 struct sip_pvt *p;
15462 int res;
15463 socklen_t len = sizeof(sin);
15464 int nounlock;
15465 int recount = 0;
15466 int lockretry;
15468 memset(&req, 0, sizeof(req));
15469 res = recvfrom(sipsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
15470 if (res < 0) {
15471 #if !defined(__FreeBSD__)
15472 if (errno == EAGAIN)
15473 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
15474 else
15475 #endif
15476 if (errno != ECONNREFUSED)
15477 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
15478 return 1;
15480 if (option_debug && res == sizeof(req.data) - 1)
15481 ast_log(LOG_DEBUG, "Received packet exceeds buffer. Data is possibly lost\n");
15483 req.data[res] = '\0';
15484 req.len = res;
15485 if(sip_debug_test_addr(&sin)) /* Set the debug flag early on packet level */
15486 ast_set_flag(&req, SIP_PKT_DEBUG);
15487 if (pedanticsipchecking)
15488 req.len = lws2sws(req.data, req.len); /* Fix multiline headers */
15489 if (ast_test_flag(&req, SIP_PKT_DEBUG))
15490 ast_verbose("\n<--- SIP read from %s:%d --->\n%s\n<------------->\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), req.data);
15492 parse_request(&req);
15493 req.method = find_sip_method(req.rlPart1);
15495 if (ast_test_flag(&req, SIP_PKT_DEBUG))
15496 ast_verbose("--- (%d headers %d lines)%s ---\n", req.headers, req.lines, (req.headers + req.lines == 0) ? " Nat keepalive" : "");
15498 if (req.headers < 2) /* Must have at least two headers */
15499 return 1;
15501 /* Process request, with netlock held, and with usual deadlock avoidance */
15502 for (lockretry = 100; lockretry > 0; lockretry--) {
15503 ast_mutex_lock(&netlock);
15505 /* Find the active SIP dialog or create a new one */
15506 p = find_call(&req, &sin, req.method); /* returns p locked */
15507 if (p == NULL) {
15508 if (option_debug)
15509 ast_log(LOG_DEBUG, "Invalid SIP message - rejected , no callid, len %d\n", req.len);
15510 ast_mutex_unlock(&netlock);
15511 return 1;
15513 /* Go ahead and lock the owner if it has one -- we may need it */
15514 /* becaues this is deadlock-prone, we need to try and unlock if failed */
15515 if (!p->owner || !ast_channel_trylock(p->owner))
15516 break; /* locking succeeded */
15517 if (option_debug)
15518 ast_log(LOG_DEBUG, "Failed to grab owner channel lock, trying again. (SIP call %s)\n", p->callid);
15519 ast_mutex_unlock(&p->lock);
15520 ast_mutex_unlock(&netlock);
15521 /* Sleep for a very short amount of time */
15522 usleep(1);
15524 p->recv = sin;
15526 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) /* This is a request or response, note what it was for */
15527 append_history(p, "Rx", "%s / %s / %s", req.data, get_header(&req, "CSeq"), req.rlPart2);
15529 if (!lockretry) {
15530 if (p->owner)
15531 ast_log(LOG_ERROR, "We could NOT get the channel lock for %s! \n", S_OR(p->owner->name, "- no channel name ??? - "));
15532 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
15533 if (req.method != SIP_ACK)
15534 transmit_response(p, "503 Server error", &req); /* We must respond according to RFC 3261 sec 12.2 */
15535 /* XXX We could add retry-after to make sure they come back */
15536 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
15537 return 1;
15539 nounlock = 0;
15540 if (handle_request(p, &req, &sin, &recount, &nounlock) == -1) {
15541 /* Request failed */
15542 if (option_debug)
15543 ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
15546 if (p->owner && !nounlock)
15547 ast_channel_unlock(p->owner);
15548 ast_mutex_unlock(&p->lock);
15549 ast_mutex_unlock(&netlock);
15550 if (recount)
15551 ast_update_use_count();
15553 return 1;
15556 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
15557 static int sip_send_mwi_to_peer(struct sip_peer *peer)
15559 /* Called with peerl lock, but releases it */
15560 struct sip_pvt *p;
15561 int newmsgs, oldmsgs;
15563 /* Do we have an IP address? If not, skip this peer */
15564 if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr)
15565 return 0;
15567 /* Check for messages */
15568 ast_app_inboxcount(peer->mailbox, &newmsgs, &oldmsgs);
15570 peer->lastmsgcheck = time(NULL);
15572 /* Return now if it's the same thing we told them last time */
15573 if (((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)) == peer->lastmsgssent) {
15574 return 0;
15578 peer->lastmsgssent = ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs));
15580 if (peer->mwipvt) {
15581 /* Base message on subscription */
15582 p = peer->mwipvt;
15583 } else {
15584 /* Build temporary dialog for this message */
15585 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY)))
15586 return -1;
15587 if (create_addr_from_peer(p, peer)) {
15588 /* Maybe they're not registered, etc. */
15589 sip_destroy(p);
15590 return 0;
15592 /* Recalculate our side, and recalculate Call ID */
15593 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
15594 p->ourip = __ourip;
15595 build_via(p);
15596 build_callid_pvt(p);
15597 /* Destroy this session after 32 secs */
15598 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15600 /* Send MWI */
15601 ast_set_flag(&p->flags[0], SIP_OUTGOING);
15602 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
15603 return 0;
15606 /*! \brief Check whether peer needs a new MWI notification check */
15607 static int does_peer_need_mwi(struct sip_peer *peer)
15609 time_t t = time(NULL);
15611 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
15612 !peer->mwipvt) { /* We don't have a subscription */
15613 peer->lastmsgcheck = t; /* Reset timer */
15614 return FALSE;
15617 if (!ast_strlen_zero(peer->mailbox) && (t - peer->lastmsgcheck) > global_mwitime)
15618 return TRUE;
15620 return FALSE;
15624 /*! \brief The SIP monitoring thread
15625 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
15626 (and thus do not have a separate thread) indefinitely
15628 static void *do_monitor(void *data)
15630 int res;
15631 struct sip_pvt *sip;
15632 struct sip_peer *peer = NULL;
15633 time_t t;
15634 int fastrestart = FALSE;
15635 int lastpeernum = -1;
15636 int curpeernum;
15637 int reloading;
15639 /* Add an I/O event to our SIP UDP socket */
15640 if (sipsock > -1)
15641 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
15643 /* From here on out, we die whenever asked */
15644 for(;;) {
15645 /* Check for a reload request */
15646 ast_mutex_lock(&sip_reload_lock);
15647 reloading = sip_reloading;
15648 sip_reloading = FALSE;
15649 ast_mutex_unlock(&sip_reload_lock);
15650 if (reloading) {
15651 if (option_verbose > 0)
15652 ast_verbose(VERBOSE_PREFIX_1 "Reloading SIP\n");
15653 sip_do_reload(sip_reloadreason);
15655 /* Change the I/O fd of our UDP socket */
15656 if (sipsock > -1) {
15657 if (sipsock_read_id)
15658 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
15659 else
15660 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
15661 } else if (sipsock_read_id) {
15662 ast_io_remove(io, sipsock_read_id);
15663 sipsock_read_id = NULL;
15666 restartsearch:
15667 /* Check for interfaces needing to be killed */
15668 ast_mutex_lock(&iflock);
15669 t = time(NULL);
15670 /* don't scan the interface list if it hasn't been a reasonable period
15671 of time since the last time we did it (when MWI is being sent, we can
15672 get back to this point every millisecond or less)
15674 for (sip = iflist; !fastrestart && sip; sip = sip->next) {
15675 /*! \note If we can't get a lock on an interface, skip it and come
15676 * back later. Note that there is the possibility of a deadlock with
15677 * sip_hangup otherwise, because sip_hangup is called with the channel
15678 * locked first, and the iface lock is attempted second.
15680 if (ast_mutex_trylock(&sip->lock))
15681 continue;
15683 /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
15684 if (sip->rtp && sip->owner &&
15685 (sip->owner->_state == AST_STATE_UP) &&
15686 !sip->redirip.sin_addr.s_addr &&
15687 sip->t38.state != T38_ENABLED) {
15688 if (sip->lastrtptx &&
15689 ast_rtp_get_rtpkeepalive(sip->rtp) &&
15690 (t > sip->lastrtptx + ast_rtp_get_rtpkeepalive(sip->rtp))) {
15691 /* Need to send an empty RTP packet */
15692 sip->lastrtptx = time(NULL);
15693 ast_rtp_sendcng(sip->rtp, 0);
15695 if (sip->lastrtprx &&
15696 (ast_rtp_get_rtptimeout(sip->rtp) || ast_rtp_get_rtpholdtimeout(sip->rtp)) &&
15697 (t > sip->lastrtprx + ast_rtp_get_rtptimeout(sip->rtp))) {
15698 /* Might be a timeout now -- see if we're on hold */
15699 struct sockaddr_in sin;
15700 ast_rtp_get_peer(sip->rtp, &sin);
15701 if (sin.sin_addr.s_addr ||
15702 (ast_rtp_get_rtpholdtimeout(sip->rtp) &&
15703 (t > sip->lastrtprx + ast_rtp_get_rtpholdtimeout(sip->rtp)))) {
15704 /* Needs a hangup */
15705 if (ast_rtp_get_rtptimeout(sip->rtp)) {
15706 while (sip->owner && ast_channel_trylock(sip->owner)) {
15707 ast_mutex_unlock(&sip->lock);
15708 usleep(1);
15709 ast_mutex_lock(&sip->lock);
15711 if (sip->owner) {
15712 ast_log(LOG_NOTICE,
15713 "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
15714 sip->owner->name,
15715 (long) (t - sip->lastrtprx));
15716 /* Issue a softhangup */
15717 ast_softhangup_nolock(sip->owner, AST_SOFTHANGUP_DEV);
15718 ast_channel_unlock(sip->owner);
15719 /* forget the timeouts for this call, since a hangup
15720 has already been requested and we don't want to
15721 repeatedly request hangups
15723 ast_rtp_set_rtptimeout(sip->rtp, 0);
15724 ast_rtp_set_rtpholdtimeout(sip->rtp, 0);
15725 if (sip->vrtp) {
15726 ast_rtp_set_rtptimeout(sip->vrtp, 0);
15727 ast_rtp_set_rtpholdtimeout(sip->vrtp, 0);
15734 /* If we have sessions that needs to be destroyed, do it now */
15735 if (ast_test_flag(&sip->flags[0], SIP_NEEDDESTROY) && !sip->packets &&
15736 !sip->owner) {
15737 ast_mutex_unlock(&sip->lock);
15738 __sip_destroy(sip, 1);
15739 ast_mutex_unlock(&iflock);
15740 usleep(1);
15741 goto restartsearch;
15743 ast_mutex_unlock(&sip->lock);
15745 ast_mutex_unlock(&iflock);
15747 pthread_testcancel();
15748 /* Wait for sched or io */
15749 res = ast_sched_wait(sched);
15750 if ((res < 0) || (res > 1000))
15751 res = 1000;
15752 /* If we might need to send more mailboxes, don't wait long at all.*/
15753 if (fastrestart)
15754 res = 1;
15755 res = ast_io_wait(io, res);
15756 if (option_debug && res > 20)
15757 ast_log(LOG_DEBUG, "chan_sip: ast_io_wait ran %d all at once\n", res);
15758 ast_mutex_lock(&monlock);
15759 if (res >= 0) {
15760 res = ast_sched_runq(sched);
15761 if (option_debug && res >= 20)
15762 ast_log(LOG_DEBUG, "chan_sip: ast_sched_runq ran %d all at once\n", res);
15765 /* Send MWI notifications to peers - static and cached realtime peers */
15766 t = time(NULL);
15767 fastrestart = FALSE;
15768 curpeernum = 0;
15769 peer = NULL;
15770 /* Find next peer that needs mwi */
15771 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !peer, do {
15772 if ((curpeernum > lastpeernum) && does_peer_need_mwi(iterator)) {
15773 fastrestart = TRUE;
15774 lastpeernum = curpeernum;
15775 peer = ASTOBJ_REF(iterator);
15777 curpeernum++;
15778 } while (0)
15780 /* Send MWI to the peer */
15781 if (peer) {
15782 ASTOBJ_WRLOCK(peer);
15783 sip_send_mwi_to_peer(peer);
15784 ASTOBJ_UNLOCK(peer);
15785 ASTOBJ_UNREF(peer,sip_destroy_peer);
15786 } else {
15787 /* Reset where we come from */
15788 lastpeernum = -1;
15790 ast_mutex_unlock(&monlock);
15792 /* Never reached */
15793 return NULL;
15797 /*! \brief Start the channel monitor thread */
15798 static int restart_monitor(void)
15800 /* If we're supposed to be stopped -- stay stopped */
15801 if (monitor_thread == AST_PTHREADT_STOP)
15802 return 0;
15803 ast_mutex_lock(&monlock);
15804 if (monitor_thread == pthread_self()) {
15805 ast_mutex_unlock(&monlock);
15806 ast_log(LOG_WARNING, "Cannot kill myself\n");
15807 return -1;
15809 if (monitor_thread != AST_PTHREADT_NULL) {
15810 /* Wake up the thread */
15811 pthread_kill(monitor_thread, SIGURG);
15812 } else {
15813 /* Start a new monitor */
15814 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
15815 ast_mutex_unlock(&monlock);
15816 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
15817 return -1;
15820 ast_mutex_unlock(&monlock);
15821 return 0;
15824 /*! \brief React to lack of answer to Qualify poke */
15825 static int sip_poke_noanswer(const void *data)
15827 struct sip_peer *peer = (struct sip_peer *)data;
15829 peer->pokeexpire = -1;
15830 if (peer->lastms > -1) {
15831 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
15832 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
15834 if (peer->call)
15835 sip_destroy(peer->call);
15836 peer->call = NULL;
15837 peer->lastms = -1;
15838 ast_device_state_changed("SIP/%s", peer->name);
15840 /* This function gets called one place outside of the scheduler ... */
15841 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
15842 struct sip_peer *peer_ptr = peer;
15843 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
15846 /* There is no need to ASTOBJ_REF() here. Just let the scheduled callback
15847 * inherit the reference that the current callback already has. */
15848 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
15849 if (peer->pokeexpire == -1) {
15850 ASTOBJ_UNREF(peer, sip_destroy_peer);
15853 return 0;
15856 /*! \brief Check availability of peer, also keep NAT open
15857 \note This is done with the interval in qualify= configuration option
15858 Default is 2 seconds */
15859 static int sip_poke_peer(struct sip_peer *peer)
15861 struct sip_pvt *p;
15862 int xmitres = 0;
15864 if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
15865 /* IF we have no IP, or this isn't to be monitored, return
15866 imeediately after clearing things out */
15867 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
15868 struct sip_peer *peer_ptr = peer;
15869 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
15871 peer->lastms = 0;
15872 peer->call = NULL;
15873 return 0;
15875 if (peer->call) {
15876 if (sipdebug)
15877 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
15878 sip_destroy(peer->call);
15880 if (!(p = peer->call = sip_alloc(NULL, NULL, 0, SIP_OPTIONS)))
15881 return -1;
15883 p->sa = peer->addr;
15884 p->recv = peer->addr;
15885 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
15886 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15888 /* Send OPTIONs to peer's fullcontact */
15889 if (!ast_strlen_zero(peer->fullcontact))
15890 ast_string_field_set(p, fullcontact, peer->fullcontact);
15892 if (!ast_strlen_zero(peer->tohost))
15893 ast_string_field_set(p, tohost, peer->tohost);
15894 else
15895 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
15897 /* Recalculate our side, and recalculate Call ID */
15898 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
15899 p->ourip = __ourip;
15900 build_via(p);
15901 build_callid_pvt(p);
15903 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
15904 struct sip_peer *peer_ptr = peer;
15905 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
15908 p->relatedpeer = peer;
15909 ast_set_flag(&p->flags[0], SIP_OUTGOING);
15910 #ifdef VOCAL_DATA_HACK
15911 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
15912 xmitres = transmit_invite(p, SIP_INVITE, 0, 2);
15913 #else
15914 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2);
15915 #endif
15916 gettimeofday(&peer->ps, NULL);
15917 if (xmitres == XMIT_ERROR) {
15918 sip_poke_noanswer(ASTOBJ_REF(peer)); /* Immediately unreachable, network problems */
15919 } else {
15920 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
15921 struct sip_peer *peer_ptr = peer;
15922 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
15924 peer->pokeexpire = ast_sched_add(sched, peer->maxms * 2, sip_poke_noanswer, ASTOBJ_REF(peer));
15925 if (peer->pokeexpire == -1) {
15926 struct sip_peer *peer_ptr = peer;
15927 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
15931 return 0;
15934 /*! \brief Part of PBX channel interface
15935 \note
15936 \par Return values:---
15938 If we have qualify on and the device is not reachable, regardless of registration
15939 state we return AST_DEVICE_UNAVAILABLE
15941 For peers with call limit:
15942 - not registered AST_DEVICE_UNAVAILABLE
15943 - registered, no call AST_DEVICE_NOT_INUSE
15944 - registered, active calls AST_DEVICE_INUSE
15945 - registered, call limit reached AST_DEVICE_BUSY
15946 - registered, onhold AST_DEVICE_ONHOLD
15947 - registered, ringing AST_DEVICE_RINGING
15949 For peers without call limit:
15950 - not registered AST_DEVICE_UNAVAILABLE
15951 - registered AST_DEVICE_NOT_INUSE
15952 - fixed IP (!dynamic) AST_DEVICE_NOT_INUSE
15954 Peers that does not have a known call and can't be reached by OPTIONS
15955 - unreachable AST_DEVICE_UNAVAILABLE
15957 If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
15958 out a state by walking the channel list.
15960 The queue system (\ref app_queue.c) treats a member as "active"
15961 if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
15963 When placing a call to the queue member, queue system sets a member to busy if
15964 != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
15967 static int sip_devicestate(void *data)
15969 char *host;
15970 char *tmp;
15972 struct hostent *hp;
15973 struct ast_hostent ahp;
15974 struct sip_peer *p;
15976 int res = AST_DEVICE_INVALID;
15978 /* make sure data is not null. Maybe unnecessary, but better be safe */
15979 host = ast_strdupa(data ? data : "");
15980 if ((tmp = strchr(host, '@')))
15981 host = tmp + 1;
15983 if (option_debug > 2)
15984 ast_log(LOG_DEBUG, "Checking device state for peer %s\n", host);
15986 if ((p = find_peer(host, NULL, 1))) {
15987 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
15988 /* we have an address for the peer */
15990 /* Check status in this order
15991 - Hold
15992 - Ringing
15993 - Busy (enforced only by call limit)
15994 - Inuse (we have a call)
15995 - Unreachable (qualify)
15996 If we don't find any of these state, report AST_DEVICE_NOT_INUSE
15997 for registered devices */
15999 if (p->onHold)
16000 /* First check for hold or ring states */
16001 res = AST_DEVICE_ONHOLD;
16002 else if (p->inRinging) {
16003 if (p->inRinging == p->inUse)
16004 res = AST_DEVICE_RINGING;
16005 else
16006 res = AST_DEVICE_RINGINUSE;
16007 } else if (p->call_limit && (p->inUse == p->call_limit))
16008 /* check call limit */
16009 res = AST_DEVICE_BUSY;
16010 else if (p->call_limit && p->inUse)
16011 /* Not busy, but we do have a call */
16012 res = AST_DEVICE_INUSE;
16013 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
16014 /* We don't have a call. Are we reachable at all? Requires qualify= */
16015 res = AST_DEVICE_UNAVAILABLE;
16016 else /* Default reply if we're registered and have no other data */
16017 res = AST_DEVICE_NOT_INUSE;
16018 } else {
16019 /* there is no address, it's unavailable */
16020 res = AST_DEVICE_UNAVAILABLE;
16022 ASTOBJ_UNREF(p,sip_destroy_peer);
16023 } else {
16024 char *port = strchr(host, ':');
16025 if (port)
16026 *port = '\0';
16027 hp = ast_gethostbyname(host, &ahp);
16028 if (hp)
16029 res = AST_DEVICE_UNKNOWN;
16032 return res;
16035 /*! \brief PBX interface function -build SIP pvt structure
16036 SIP calls initiated by the PBX arrive here */
16037 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
16039 int oldformat;
16040 struct sip_pvt *p;
16041 struct ast_channel *tmpc = NULL;
16042 char *ext, *host;
16043 char tmp[256];
16044 char *dest = data;
16046 oldformat = format;
16047 if (!(format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1))) {
16048 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));
16049 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL; /* Can't find codec to connect to host */
16050 return NULL;
16052 if (option_debug)
16053 ast_log(LOG_DEBUG, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
16055 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE))) {
16056 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", (char *)data);
16057 *cause = AST_CAUSE_SWITCH_CONGESTION;
16058 return NULL;
16061 ast_set_flag(&p->flags[1], SIP_PAGE2_OUTGOING_CALL);
16063 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
16064 sip_destroy(p);
16065 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
16066 *cause = AST_CAUSE_SWITCH_CONGESTION;
16067 return NULL;
16070 ast_copy_string(tmp, dest, sizeof(tmp));
16071 host = strchr(tmp, '@');
16072 if (host) {
16073 *host++ = '\0';
16074 ext = tmp;
16075 } else {
16076 ext = strchr(tmp, '/');
16077 if (ext)
16078 *ext++ = '\0';
16079 host = tmp;
16082 if (create_addr(p, host)) {
16083 *cause = AST_CAUSE_UNREGISTERED;
16084 if (option_debug > 2)
16085 ast_log(LOG_DEBUG, "Cant create SIP call - target device not registred\n");
16086 sip_destroy(p);
16087 return NULL;
16089 if (ast_strlen_zero(p->peername) && ext)
16090 ast_string_field_set(p, peername, ext);
16091 /* Recalculate our side, and recalculate Call ID */
16092 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
16093 p->ourip = __ourip;
16094 build_via(p);
16095 build_callid_pvt(p);
16097 /* We have an extension to call, don't use the full contact here */
16098 /* This to enable dialing registered peers with extension dialling,
16099 like SIP/peername/extension
16100 SIP/peername will still use the full contact */
16101 if (ext) {
16102 ast_string_field_set(p, username, ext);
16103 ast_string_field_free(p, fullcontact);
16105 #if 0
16106 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
16107 #endif
16108 p->prefcodec = oldformat; /* Format for this call */
16109 ast_mutex_lock(&p->lock);
16110 tmpc = sip_new(p, AST_STATE_DOWN, host); /* Place the call */
16111 ast_mutex_unlock(&p->lock);
16112 if (!tmpc)
16113 sip_destroy(p);
16114 ast_update_use_count();
16115 restart_monitor();
16116 return tmpc;
16120 * \brief Parse the "insecure" setting from sip.conf or from realtime.
16121 * \param flags a pointer to an ast_flags structure
16122 * \param value the value of the SIP insecure setting
16123 * \param lineno linenumber in sip.conf or -1 for realtime
16125 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno)
16127 static int dep_insecure_very = 0;
16128 static int dep_insecure_yes = 0;
16130 if (ast_strlen_zero(value))
16131 return;
16133 if (!strcasecmp(value, "very")) {
16134 ast_set_flag(flags, SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16135 if(!dep_insecure_very) {
16136 if(lineno != -1)
16137 ast_log(LOG_WARNING, "insecure=very at line %d is deprecated; use insecure=port,invite instead\n", lineno);
16138 else
16139 ast_log(LOG_WARNING, "insecure=very is deprecated; use insecure=port,invite instead\n");
16140 dep_insecure_very = 1;
16143 else if (ast_true(value)) {
16144 ast_set_flag(flags, SIP_INSECURE_PORT);
16145 if(!dep_insecure_yes) {
16146 if(lineno != -1)
16147 ast_log(LOG_WARNING, "insecure=%s at line %d is deprecated; use insecure=port instead\n", value, lineno);
16148 else
16149 ast_log(LOG_WARNING, "insecure=%s is deprecated; use insecure=port instead\n", value);
16150 dep_insecure_yes = 1;
16153 else if (!ast_false(value)) {
16154 char buf[64];
16155 char *word, *next;
16156 ast_copy_string(buf, value, sizeof(buf));
16157 next = buf;
16158 while ((word = strsep(&next, ","))) {
16159 if (!strcasecmp(word, "port"))
16160 ast_set_flag(flags, SIP_INSECURE_PORT);
16161 else if (!strcasecmp(word, "invite"))
16162 ast_set_flag(flags, SIP_INSECURE_INVITE);
16163 else
16164 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
16170 \brief Handle flag-type options common to configuration of devices - users and peers
16171 \param flags array of two struct ast_flags
16172 \param mask array of two struct ast_flags
16173 \param v linked list of config variables to process
16174 \returns non-zero if any config options were handled, zero otherwise
16176 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
16178 int res = 1;
16180 if (!strcasecmp(v->name, "trustrpid")) {
16181 ast_set_flag(&mask[0], SIP_TRUSTRPID);
16182 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
16183 } else if (!strcasecmp(v->name, "sendrpid")) {
16184 ast_set_flag(&mask[0], SIP_SENDRPID);
16185 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
16186 } else if (!strcasecmp(v->name, "g726nonstandard")) {
16187 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
16188 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
16189 } else if (!strcasecmp(v->name, "useclientcode")) {
16190 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
16191 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
16192 } else if (!strcasecmp(v->name, "dtmfmode")) {
16193 ast_set_flag(&mask[0], SIP_DTMF);
16194 ast_clear_flag(&flags[0], SIP_DTMF);
16195 if (!strcasecmp(v->value, "inband"))
16196 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
16197 else if (!strcasecmp(v->value, "rfc2833"))
16198 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
16199 else if (!strcasecmp(v->value, "info"))
16200 ast_set_flag(&flags[0], SIP_DTMF_INFO);
16201 else if (!strcasecmp(v->value, "auto"))
16202 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
16203 else {
16204 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
16205 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
16207 } else if (!strcasecmp(v->name, "nat")) {
16208 ast_set_flag(&mask[0], SIP_NAT);
16209 ast_clear_flag(&flags[0], SIP_NAT);
16210 if (!strcasecmp(v->value, "never"))
16211 ast_set_flag(&flags[0], SIP_NAT_NEVER);
16212 else if (!strcasecmp(v->value, "route"))
16213 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
16214 else if (ast_true(v->value))
16215 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
16216 else
16217 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
16218 } else if (!strcasecmp(v->name, "canreinvite")) {
16219 ast_set_flag(&mask[0], SIP_REINVITE);
16220 ast_clear_flag(&flags[0], SIP_REINVITE);
16221 if(ast_true(v->value)) {
16222 ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
16223 } else if (!ast_false(v->value)) {
16224 char buf[64];
16225 char *word, *next = buf;
16227 ast_copy_string(buf, v->value, sizeof(buf));
16228 while ((word = strsep(&next, ","))) {
16229 if(!strcasecmp(word, "update")) {
16230 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
16231 } else if(!strcasecmp(word, "nonat")) {
16232 ast_set_flag(&flags[0], SIP_CAN_REINVITE);
16233 ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
16234 } else {
16235 ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
16239 } else if (!strcasecmp(v->name, "insecure")) {
16240 ast_set_flag(&mask[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16241 ast_clear_flag(&flags[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16242 set_insecure_flags(flags, v->value, v->lineno);
16243 } else if (!strcasecmp(v->name, "progressinband")) {
16244 ast_set_flag(&mask[0], SIP_PROG_INBAND);
16245 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
16246 if (ast_true(v->value))
16247 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
16248 else if (strcasecmp(v->value, "never"))
16249 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
16250 } else if (!strcasecmp(v->name, "promiscredir")) {
16251 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
16252 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
16253 } else if (!strcasecmp(v->name, "videosupport")) {
16254 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
16255 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
16256 } else if (!strcasecmp(v->name, "allowoverlap")) {
16257 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
16258 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
16259 } else if (!strcasecmp(v->name, "allowsubscribe")) {
16260 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
16261 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
16262 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
16263 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_UDPTL);
16264 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_UDPTL);
16265 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
16266 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
16267 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_RTP);
16268 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_RTP);
16269 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
16270 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_TCP);
16271 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_TCP);
16272 #endif
16273 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
16274 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
16275 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
16276 } else if (!strcasecmp(v->name, "buggymwi")) {
16277 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
16278 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
16279 } else
16280 res = 0;
16282 return res;
16285 /*! \brief Add SIP domain to list of domains we are responsible for */
16286 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
16288 struct domain *d;
16290 if (ast_strlen_zero(domain)) {
16291 ast_log(LOG_WARNING, "Zero length domain.\n");
16292 return 1;
16295 if (!(d = ast_calloc(1, sizeof(*d))))
16296 return 0;
16298 ast_copy_string(d->domain, domain, sizeof(d->domain));
16300 if (!ast_strlen_zero(context))
16301 ast_copy_string(d->context, context, sizeof(d->context));
16303 d->mode = mode;
16305 AST_LIST_LOCK(&domain_list);
16306 AST_LIST_INSERT_TAIL(&domain_list, d, list);
16307 AST_LIST_UNLOCK(&domain_list);
16309 if (sipdebug)
16310 ast_log(LOG_DEBUG, "Added local SIP domain '%s'\n", domain);
16312 return 1;
16315 /*! \brief check_sip_domain: Check if domain part of uri is local to our server */
16316 static int check_sip_domain(const char *domain, char *context, size_t len)
16318 struct domain *d;
16319 int result = 0;
16321 AST_LIST_LOCK(&domain_list);
16322 AST_LIST_TRAVERSE(&domain_list, d, list) {
16323 if (strcasecmp(d->domain, domain))
16324 continue;
16326 if (len && !ast_strlen_zero(d->context))
16327 ast_copy_string(context, d->context, len);
16329 result = 1;
16330 break;
16332 AST_LIST_UNLOCK(&domain_list);
16334 return result;
16337 /*! \brief Clear our domain list (at reload) */
16338 static void clear_sip_domains(void)
16340 struct domain *d;
16342 AST_LIST_LOCK(&domain_list);
16343 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
16344 free(d);
16345 AST_LIST_UNLOCK(&domain_list);
16349 /*! \brief Add realm authentication in list */
16350 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno)
16352 char authcopy[256];
16353 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
16354 char *stringp;
16355 struct sip_auth *a, *b, *auth;
16357 if (ast_strlen_zero(configuration))
16358 return authlist;
16360 if (option_debug)
16361 ast_log(LOG_DEBUG, "Auth config :: %s\n", configuration);
16363 ast_copy_string(authcopy, configuration, sizeof(authcopy));
16364 stringp = authcopy;
16366 username = stringp;
16367 realm = strrchr(stringp, '@');
16368 if (realm)
16369 *realm++ = '\0';
16370 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
16371 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
16372 return authlist;
16374 stringp = username;
16375 username = strsep(&stringp, ":");
16376 if (username) {
16377 secret = strsep(&stringp, ":");
16378 if (!secret) {
16379 stringp = username;
16380 md5secret = strsep(&stringp,"#");
16383 if (!(auth = ast_calloc(1, sizeof(*auth))))
16384 return authlist;
16386 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
16387 ast_copy_string(auth->username, username, sizeof(auth->username));
16388 if (secret)
16389 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
16390 if (md5secret)
16391 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
16393 /* find the end of the list */
16394 for (b = NULL, a = authlist; a ; b = a, a = a->next)
16396 if (b)
16397 b->next = auth; /* Add structure add end of list */
16398 else
16399 authlist = auth;
16401 if (option_verbose > 2)
16402 ast_verbose("Added authentication for realm %s\n", realm);
16404 return authlist;
16408 /*! \brief Clear realm authentication list (at reload) */
16409 static int clear_realm_authentication(struct sip_auth *authlist)
16411 struct sip_auth *a = authlist;
16412 struct sip_auth *b;
16414 while (a) {
16415 b = a;
16416 a = a->next;
16417 free(b);
16420 return 1;
16423 /*! \brief Find authentication for a specific realm */
16424 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
16426 struct sip_auth *a;
16428 for (a = authlist; a; a = a->next) {
16429 if (!strcasecmp(a->realm, realm))
16430 break;
16433 return a;
16436 /*! \brief Initiate a SIP user structure from configuration (configuration or realtime) */
16437 static struct sip_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
16439 struct sip_user *user;
16440 int format;
16441 struct ast_ha *oldha = NULL;
16442 char *varname = NULL, *varval = NULL;
16443 struct ast_variable *tmpvar = NULL;
16444 struct ast_flags userflags[2] = {{(0)}};
16445 struct ast_flags mask[2] = {{(0)}};
16448 if (!(user = ast_calloc(1, sizeof(*user))))
16449 return NULL;
16451 suserobjs++;
16452 ASTOBJ_INIT(user);
16453 ast_copy_string(user->name, name, sizeof(user->name));
16454 oldha = user->ha;
16455 user->ha = NULL;
16456 ast_copy_flags(&user->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
16457 ast_copy_flags(&user->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16458 user->capability = global_capability;
16459 user->allowtransfer = global_allowtransfer;
16460 user->maxcallbitrate = default_maxcallbitrate;
16461 user->autoframing = global_autoframing;
16462 user->prefs = default_prefs;
16463 /* set default context */
16464 strcpy(user->context, default_context);
16465 strcpy(user->language, default_language);
16466 strcpy(user->mohinterpret, default_mohinterpret);
16467 strcpy(user->mohsuggest, default_mohsuggest);
16468 /* First we walk through the v parameters list and then the alt parameters list */
16469 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
16470 if (handle_common_options(&userflags[0], &mask[0], v))
16471 continue;
16473 if (!strcasecmp(v->name, "context")) {
16474 ast_copy_string(user->context, v->value, sizeof(user->context));
16475 } else if (!strcasecmp(v->name, "subscribecontext")) {
16476 ast_copy_string(user->subscribecontext, v->value, sizeof(user->subscribecontext));
16477 } else if (!strcasecmp(v->name, "setvar")) {
16478 varname = ast_strdupa(v->value);
16479 if ((varval = strchr(varname,'='))) {
16480 *varval++ = '\0';
16481 if ((tmpvar = ast_variable_new(varname, varval))) {
16482 tmpvar->next = user->chanvars;
16483 user->chanvars = tmpvar;
16486 } else if (!strcasecmp(v->name, "permit") ||
16487 !strcasecmp(v->name, "deny")) {
16488 user->ha = ast_append_ha(v->name, v->value, user->ha);
16489 } else if (!strcasecmp(v->name, "allowtransfer")) {
16490 user->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
16491 } else if (!strcasecmp(v->name, "secret")) {
16492 ast_copy_string(user->secret, v->value, sizeof(user->secret));
16493 } else if (!strcasecmp(v->name, "md5secret")) {
16494 ast_copy_string(user->md5secret, v->value, sizeof(user->md5secret));
16495 } else if (!strcasecmp(v->name, "callerid")) {
16496 ast_callerid_split(v->value, user->cid_name, sizeof(user->cid_name), user->cid_num, sizeof(user->cid_num));
16497 } else if (!strcasecmp(v->name, "fullname")) {
16498 ast_copy_string(user->cid_name, v->value, sizeof(user->cid_name));
16499 } else if (!strcasecmp(v->name, "cid_number")) {
16500 ast_copy_string(user->cid_num, v->value, sizeof(user->cid_num));
16501 } else if (!strcasecmp(v->name, "callgroup")) {
16502 user->callgroup = ast_get_group(v->value);
16503 } else if (!strcasecmp(v->name, "pickupgroup")) {
16504 user->pickupgroup = ast_get_group(v->value);
16505 } else if (!strcasecmp(v->name, "language")) {
16506 ast_copy_string(user->language, v->value, sizeof(user->language));
16507 } else if (!strcasecmp(v->name, "mohinterpret")
16508 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
16509 ast_copy_string(user->mohinterpret, v->value, sizeof(user->mohinterpret));
16510 } else if (!strcasecmp(v->name, "mohsuggest")) {
16511 ast_copy_string(user->mohsuggest, v->value, sizeof(user->mohsuggest));
16512 } else if (!strcasecmp(v->name, "accountcode")) {
16513 ast_copy_string(user->accountcode, v->value, sizeof(user->accountcode));
16514 } else if (!strcasecmp(v->name, "call-limit")) {
16515 user->call_limit = atoi(v->value);
16516 if (user->call_limit < 0)
16517 user->call_limit = 0;
16518 } else if (!strcasecmp(v->name, "amaflags")) {
16519 format = ast_cdr_amaflags2int(v->value);
16520 if (format < 0) {
16521 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
16522 } else {
16523 user->amaflags = format;
16525 } else if (!strcasecmp(v->name, "allow")) {
16526 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
16527 } else if (!strcasecmp(v->name, "disallow")) {
16528 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 0);
16529 } else if (!strcasecmp(v->name, "autoframing")) {
16530 user->autoframing = ast_true(v->value);
16531 } else if (!strcasecmp(v->name, "callingpres")) {
16532 user->callingpres = ast_parse_caller_presentation(v->value);
16533 if (user->callingpres == -1)
16534 user->callingpres = atoi(v->value);
16535 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
16536 user->maxcallbitrate = atoi(v->value);
16537 if (user->maxcallbitrate < 0)
16538 user->maxcallbitrate = default_maxcallbitrate;
16540 /* We can't just report unknown options here because this may be a
16541 * type=friend entry. All user options are valid for a peer, but not
16542 * the other way around. */
16544 ast_copy_flags(&user->flags[0], &userflags[0], mask[0].flags);
16545 ast_copy_flags(&user->flags[1], &userflags[1], mask[1].flags);
16546 if (ast_test_flag(&user->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
16547 global_allowsubscribe = TRUE; /* No global ban any more */
16548 ast_free_ha(oldha);
16549 return user;
16552 /*! \brief Set peer defaults before configuring specific configurations */
16553 static void set_peer_defaults(struct sip_peer *peer)
16555 if (peer->expire == 0) {
16556 /* Don't reset expire or port time during reload
16557 if we have an active registration
16559 peer->expire = -1;
16560 peer->pokeexpire = -1;
16561 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
16563 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
16564 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16565 strcpy(peer->context, default_context);
16566 strcpy(peer->subscribecontext, default_subscribecontext);
16567 strcpy(peer->language, default_language);
16568 strcpy(peer->mohinterpret, default_mohinterpret);
16569 strcpy(peer->mohsuggest, default_mohsuggest);
16570 peer->addr.sin_family = AF_INET;
16571 peer->defaddr.sin_family = AF_INET;
16572 peer->capability = global_capability;
16573 peer->maxcallbitrate = default_maxcallbitrate;
16574 peer->rtptimeout = global_rtptimeout;
16575 peer->rtpholdtimeout = global_rtpholdtimeout;
16576 peer->rtpkeepalive = global_rtpkeepalive;
16577 peer->allowtransfer = global_allowtransfer;
16578 peer->autoframing = global_autoframing;
16579 strcpy(peer->vmexten, default_vmexten);
16580 peer->secret[0] = '\0';
16581 peer->md5secret[0] = '\0';
16582 peer->cid_num[0] = '\0';
16583 peer->cid_name[0] = '\0';
16584 peer->fromdomain[0] = '\0';
16585 peer->fromuser[0] = '\0';
16586 peer->regexten[0] = '\0';
16587 peer->mailbox[0] = '\0';
16588 peer->callgroup = 0;
16589 peer->pickupgroup = 0;
16590 peer->maxms = default_qualify;
16591 peer->prefs = default_prefs;
16594 /*! \brief Create temporary peer (used in autocreatepeer mode) */
16595 static struct sip_peer *temp_peer(const char *name)
16597 struct sip_peer *peer;
16599 if (!(peer = ast_calloc(1, sizeof(*peer))))
16600 return NULL;
16602 apeerobjs++;
16603 ASTOBJ_INIT(peer);
16604 set_peer_defaults(peer);
16606 ast_copy_string(peer->name, name, sizeof(peer->name));
16608 ast_set_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT);
16609 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
16610 peer->prefs = default_prefs;
16611 reg_source_db(peer);
16613 return peer;
16616 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
16617 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
16619 struct sip_peer *peer = NULL;
16620 struct ast_ha *oldha = NULL;
16621 int obproxyfound=0;
16622 int found=0;
16623 int firstpass=1;
16624 int format=0; /* Ama flags */
16625 time_t regseconds = 0;
16626 char *varname = NULL, *varval = NULL;
16627 struct ast_variable *tmpvar = NULL;
16628 struct ast_flags peerflags[2] = {{(0)}};
16629 struct ast_flags mask[2] = {{(0)}};
16632 if (!realtime)
16633 /* Note we do NOT use find_peer here, to avoid realtime recursion */
16634 /* We also use a case-sensitive comparison (unlike find_peer) so
16635 that case changes made to the peer name will be properly handled
16636 during reload
16638 peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);
16640 if (peer) {
16641 /* Already in the list, remove it and it will be added back (or FREE'd) */
16642 found = 1;
16643 if (!(peer->objflags & ASTOBJ_FLAG_MARKED))
16644 firstpass = 0;
16645 } else {
16646 if (!(peer = ast_calloc(1, sizeof(*peer))))
16647 return NULL;
16649 if (realtime)
16650 rpeerobjs++;
16651 else
16652 speerobjs++;
16653 ASTOBJ_INIT(peer);
16655 /* Note that our peer HAS had its reference count incrased */
16656 if (firstpass) {
16657 peer->lastmsgssent = -1;
16658 oldha = peer->ha;
16659 peer->ha = NULL;
16660 set_peer_defaults(peer); /* Set peer defaults */
16662 if (!found && name)
16663 ast_copy_string(peer->name, name, sizeof(peer->name));
16665 /* If we have channel variables, remove them (reload) */
16666 if (peer->chanvars) {
16667 ast_variables_destroy(peer->chanvars);
16668 peer->chanvars = NULL;
16669 /* XXX should unregister ? */
16672 /* If we have realm authentication information, remove them (reload) */
16673 clear_realm_authentication(peer->auth);
16674 peer->auth = NULL;
16676 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
16677 if (handle_common_options(&peerflags[0], &mask[0], v))
16678 continue;
16679 if (realtime && !strcasecmp(v->name, "regseconds")) {
16680 ast_get_time_t(v->value, &regseconds, 0, NULL);
16681 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
16682 inet_aton(v->value, &(peer->addr.sin_addr));
16683 } else if (realtime && !strcasecmp(v->name, "name"))
16684 ast_copy_string(peer->name, v->value, sizeof(peer->name));
16685 else if (realtime && !strcasecmp(v->name, "fullcontact")) {
16686 ast_copy_string(peer->fullcontact, v->value, sizeof(peer->fullcontact));
16687 ast_set_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT);
16688 } else if (!strcasecmp(v->name, "secret"))
16689 ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
16690 else if (!strcasecmp(v->name, "md5secret"))
16691 ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
16692 else if (!strcasecmp(v->name, "auth"))
16693 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
16694 else if (!strcasecmp(v->name, "callerid")) {
16695 ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
16696 } else if (!strcasecmp(v->name, "fullname")) {
16697 ast_copy_string(peer->cid_name, v->value, sizeof(peer->cid_name));
16698 } else if (!strcasecmp(v->name, "cid_number")) {
16699 ast_copy_string(peer->cid_num, v->value, sizeof(peer->cid_num));
16700 } else if (!strcasecmp(v->name, "context")) {
16701 ast_copy_string(peer->context, v->value, sizeof(peer->context));
16702 } else if (!strcasecmp(v->name, "subscribecontext")) {
16703 ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
16704 } else if (!strcasecmp(v->name, "fromdomain")) {
16705 ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
16706 } else if (!strcasecmp(v->name, "usereqphone")) {
16707 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
16708 } else if (!strcasecmp(v->name, "fromuser")) {
16709 ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
16710 } else if (!strcasecmp(v->name, "host") || !strcasecmp(v->name, "outboundproxy")) {
16711 if (!strcasecmp(v->value, "dynamic")) {
16712 if (!strcasecmp(v->name, "outboundproxy") || obproxyfound) {
16713 ast_log(LOG_WARNING, "You can't have a dynamic outbound proxy, you big silly head at line %d.\n", v->lineno);
16714 } else {
16715 /* They'll register with us */
16716 if (!found || !ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
16717 /* Initialize stuff if this is a new peer, or if it used to be
16718 * non-dynamic before the reload. */
16719 memset(&peer->addr.sin_addr, 0, 4);
16720 if (peer->addr.sin_port) {
16721 /* If we've already got a port, make it the default rather than absolute */
16722 peer->defaddr.sin_port = peer->addr.sin_port;
16723 peer->addr.sin_port = 0;
16726 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
16728 } else {
16729 /* Non-dynamic. Make sure we become that way if we're not */
16730 if (!AST_SCHED_DEL(sched, peer->expire)) {
16731 struct sip_peer *peer_ptr = peer;
16732 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
16734 ast_clear_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
16735 if (!obproxyfound || !strcasecmp(v->name, "outboundproxy")) {
16736 if (ast_get_ip_or_srv(&peer->addr, v->value, srvlookup ? "_sip._udp" : NULL)) {
16737 ASTOBJ_UNREF(peer, sip_destroy_peer);
16738 return NULL;
16741 if (!strcasecmp(v->name, "outboundproxy"))
16742 obproxyfound=1;
16743 else {
16744 ast_copy_string(peer->tohost, v->value, sizeof(peer->tohost));
16745 if (!peer->addr.sin_port)
16746 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
16749 } else if (!strcasecmp(v->name, "defaultip")) {
16750 if (ast_get_ip(&peer->defaddr, v->value)) {
16751 ASTOBJ_UNREF(peer, sip_destroy_peer);
16752 return NULL;
16754 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
16755 peer->ha = ast_append_ha(v->name, v->value, peer->ha);
16756 } else if (!strcasecmp(v->name, "port")) {
16757 if (!realtime && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC))
16758 peer->defaddr.sin_port = htons(atoi(v->value));
16759 else
16760 peer->addr.sin_port = htons(atoi(v->value));
16761 } else if (!strcasecmp(v->name, "callingpres")) {
16762 peer->callingpres = ast_parse_caller_presentation(v->value);
16763 if (peer->callingpres == -1)
16764 peer->callingpres = atoi(v->value);
16765 } else if (!strcasecmp(v->name, "username")) {
16766 ast_copy_string(peer->username, v->value, sizeof(peer->username));
16767 } else if (!strcasecmp(v->name, "language")) {
16768 ast_copy_string(peer->language, v->value, sizeof(peer->language));
16769 } else if (!strcasecmp(v->name, "regexten")) {
16770 ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
16771 } else if (!strcasecmp(v->name, "call-limit") || !strcasecmp(v->name, "incominglimit")) {
16772 peer->call_limit = atoi(v->value);
16773 if (peer->call_limit < 0)
16774 peer->call_limit = 0;
16775 } else if (!strcasecmp(v->name, "amaflags")) {
16776 format = ast_cdr_amaflags2int(v->value);
16777 if (format < 0) {
16778 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
16779 } else {
16780 peer->amaflags = format;
16782 } else if (!strcasecmp(v->name, "accountcode")) {
16783 ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
16784 } else if (!strcasecmp(v->name, "mohinterpret")
16785 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
16786 ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
16787 } else if (!strcasecmp(v->name, "mohsuggest")) {
16788 ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
16789 } else if (!strcasecmp(v->name, "mailbox")) {
16790 ast_copy_string(peer->mailbox, v->value, sizeof(peer->mailbox));
16791 } else if (!strcasecmp(v->name, "subscribemwi")) {
16792 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
16793 } else if (!strcasecmp(v->name, "vmexten")) {
16794 ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
16795 } else if (!strcasecmp(v->name, "callgroup")) {
16796 peer->callgroup = ast_get_group(v->value);
16797 } else if (!strcasecmp(v->name, "allowtransfer")) {
16798 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
16799 } else if (!strcasecmp(v->name, "pickupgroup")) {
16800 peer->pickupgroup = ast_get_group(v->value);
16801 } else if (!strcasecmp(v->name, "allow")) {
16802 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
16803 } else if (!strcasecmp(v->name, "disallow")) {
16804 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
16805 } else if (!strcasecmp(v->name, "autoframing")) {
16806 peer->autoframing = ast_true(v->value);
16807 } else if (!strcasecmp(v->name, "rtptimeout")) {
16808 if ((sscanf(v->value, "%d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
16809 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16810 peer->rtptimeout = global_rtptimeout;
16812 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
16813 if ((sscanf(v->value, "%d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
16814 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16815 peer->rtpholdtimeout = global_rtpholdtimeout;
16817 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
16818 if ((sscanf(v->value, "%d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
16819 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
16820 peer->rtpkeepalive = global_rtpkeepalive;
16822 } else if (!strcasecmp(v->name, "setvar")) {
16823 /* Set peer channel variable */
16824 varname = ast_strdupa(v->value);
16825 if ((varval = strchr(varname, '='))) {
16826 *varval++ = '\0';
16827 if ((tmpvar = ast_variable_new(varname, varval))) {
16828 tmpvar->next = peer->chanvars;
16829 peer->chanvars = tmpvar;
16832 } else if (!strcasecmp(v->name, "qualify")) {
16833 if (!strcasecmp(v->value, "no")) {
16834 peer->maxms = 0;
16835 } else if (!strcasecmp(v->value, "yes")) {
16836 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
16837 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
16838 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);
16839 peer->maxms = 0;
16841 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
16842 peer->maxcallbitrate = atoi(v->value);
16843 if (peer->maxcallbitrate < 0)
16844 peer->maxcallbitrate = default_maxcallbitrate;
16847 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && realtime) {
16848 time_t nowtime = time(NULL);
16850 if ((nowtime - regseconds) > 0) {
16851 destroy_association(peer);
16852 memset(&peer->addr, 0, sizeof(peer->addr));
16853 if (option_debug)
16854 ast_log(LOG_DEBUG, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
16857 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
16858 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
16859 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
16860 global_allowsubscribe = TRUE; /* No global ban any more */
16861 if (!found && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && !ast_test_flag(&peer->flags[0], SIP_REALTIME))
16862 reg_source_db(peer);
16863 ASTOBJ_UNMARK(peer);
16864 ast_free_ha(oldha);
16865 return peer;
16868 /*! \brief Re-read SIP.conf config file
16869 \note This function reloads all config data, except for
16870 active peers (with registrations). They will only
16871 change configuration data at restart, not at reload.
16872 SIP debug and recordhistory state will not change
16874 static int reload_config(enum channelreloadreason reason)
16876 struct ast_config *cfg, *ucfg;
16877 struct ast_variable *v;
16878 struct sip_peer *peer;
16879 struct sip_user *user;
16880 struct ast_hostent ahp;
16881 char *cat, *stringp, *context, *oldregcontext;
16882 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
16883 struct hostent *hp;
16884 int format;
16885 struct ast_flags dummy[2];
16886 int auto_sip_domains = FALSE;
16887 struct sockaddr_in old_bindaddr = bindaddr;
16888 int registry_count = 0, peer_count = 0, user_count = 0;
16889 unsigned int temp_tos = 0;
16890 struct ast_flags debugflag = {0};
16892 cfg = ast_config_load(config);
16894 /* We *must* have a config file otherwise stop immediately */
16895 if (!cfg) {
16896 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
16897 return -1;
16900 if (option_debug > 3)
16901 ast_log(LOG_DEBUG, "--------------- SIP reload started\n");
16903 clear_realm_authentication(authl);
16904 clear_sip_domains();
16905 authl = NULL;
16907 /* First, destroy all outstanding registry calls */
16908 /* This is needed, since otherwise active registry entries will not be destroyed */
16909 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
16910 ASTOBJ_RDLOCK(iterator);
16911 if (iterator->call) {
16912 if (option_debug > 2)
16913 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
16914 /* This will also remove references to the registry */
16915 sip_destroy(iterator->call);
16917 ASTOBJ_UNLOCK(iterator);
16919 } while(0));
16921 /* Then, actually destroy users and registry */
16922 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
16923 if (option_debug > 3)
16924 ast_log(LOG_DEBUG, "--------------- Done destroying user list\n");
16925 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
16926 if (option_debug > 3)
16927 ast_log(LOG_DEBUG, "--------------- Done destroying registry list\n");
16928 ASTOBJ_CONTAINER_MARKALL(&peerl);
16930 /* Initialize copy of current global_regcontext for later use in removing stale contexts */
16931 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
16932 oldregcontext = oldcontexts;
16934 /* Clear all flags before setting default values */
16935 /* Preserve debugging settings for console */
16936 ast_copy_flags(&debugflag, &global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
16937 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
16938 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
16939 ast_copy_flags(&global_flags[1], &debugflag, SIP_PAGE2_DEBUG_CONSOLE);
16941 /* Reset IP addresses */
16942 memset(&bindaddr, 0, sizeof(bindaddr));
16943 ast_free_ha(localaddr);
16944 memset(&localaddr, 0, sizeof(localaddr));
16945 memset(&externip, 0, sizeof(externip));
16946 memset(&default_prefs, 0 , sizeof(default_prefs));
16947 outboundproxyip.sin_port = htons(STANDARD_SIP_PORT);
16948 outboundproxyip.sin_family = AF_INET; /* Type of address: IPv4 */
16949 ourport = STANDARD_SIP_PORT;
16950 srvlookup = DEFAULT_SRVLOOKUP;
16951 global_tos_sip = DEFAULT_TOS_SIP;
16952 global_tos_audio = DEFAULT_TOS_AUDIO;
16953 global_tos_video = DEFAULT_TOS_VIDEO;
16954 externhost[0] = '\0'; /* External host name (for behind NAT DynDNS support) */
16955 externexpire = 0; /* Expiration for DNS re-issuing */
16956 externrefresh = 10;
16957 memset(&outboundproxyip, 0, sizeof(outboundproxyip));
16959 /* Reset channel settings to default before re-configuring */
16960 allow_external_domains = DEFAULT_ALLOW_EXT_DOM; /* Allow external invites */
16961 global_regcontext[0] = '\0';
16962 expiry = DEFAULT_EXPIRY;
16963 global_notifyringing = DEFAULT_NOTIFYRINGING;
16964 global_limitonpeers = FALSE;
16965 global_directrtpsetup = FALSE; /* Experimental feature, disabled by default */
16966 global_notifyhold = FALSE;
16967 global_alwaysauthreject = 0;
16968 global_allowsubscribe = FALSE;
16969 ast_copy_string(global_useragent, DEFAULT_USERAGENT, sizeof(global_useragent));
16970 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
16971 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME))
16972 ast_copy_string(global_realm, DEFAULT_REALM, sizeof(global_realm));
16973 else
16974 ast_copy_string(global_realm, ast_config_AST_SYSTEM_NAME, sizeof(global_realm));
16975 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
16976 compactheaders = DEFAULT_COMPACTHEADERS;
16977 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
16978 global_regattempts_max = 0;
16979 pedanticsipchecking = DEFAULT_PEDANTIC;
16980 global_mwitime = DEFAULT_MWITIME;
16981 autocreatepeer = DEFAULT_AUTOCREATEPEER;
16982 global_autoframing = 0;
16983 global_allowguest = DEFAULT_ALLOWGUEST;
16984 global_rtptimeout = 0;
16985 global_rtpholdtimeout = 0;
16986 global_rtpkeepalive = 0;
16987 global_allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
16988 global_rtautoclear = 120;
16989 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE); /* Default for peers, users: TRUE */
16990 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP); /* Default for peers, users: TRUE */
16991 ast_set_flag(&global_flags[1], SIP_PAGE2_RTUPDATE);
16993 /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for peers and users */
16994 ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
16995 default_subscribecontext[0] = '\0';
16996 default_language[0] = '\0';
16997 default_fromdomain[0] = '\0';
16998 default_qualify = DEFAULT_QUALIFY;
16999 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
17000 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
17001 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
17002 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
17003 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833); /*!< Default DTMF setting: RFC2833 */
17004 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581); /*!< NAT support if requested by device with rport */
17005 ast_set_flag(&global_flags[0], SIP_CAN_REINVITE); /*!< Allow re-invites */
17007 /* Debugging settings, always default to off */
17008 dumphistory = FALSE;
17009 recordhistory = FALSE;
17010 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
17012 /* Misc settings for the channel */
17013 global_relaxdtmf = FALSE;
17014 global_callevents = FALSE;
17015 global_t1min = DEFAULT_T1MIN;
17017 global_matchexterniplocally = FALSE;
17019 /* Copy the default jb config over global_jbconf */
17020 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
17022 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT);
17024 /* Read the [general] config section of sip.conf (or from realtime config) */
17025 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
17026 if (handle_common_options(&global_flags[0], &dummy[0], v))
17027 continue;
17028 /* handle jb conf */
17029 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
17030 continue;
17032 /* Create the interface list */
17033 if (!strcasecmp(v->name, "context")) {
17034 ast_copy_string(default_context, v->value, sizeof(default_context));
17035 } else if (!strcasecmp(v->name, "subscribecontext")) {
17036 ast_copy_string(default_subscribecontext, v->value, sizeof(default_subscribecontext));
17037 } else if (!strcasecmp(v->name, "allowguest")) {
17038 global_allowguest = ast_true(v->value) ? 1 : 0;
17039 } else if (!strcasecmp(v->name, "realm")) {
17040 ast_copy_string(global_realm, v->value, sizeof(global_realm));
17041 } else if (!strcasecmp(v->name, "useragent")) {
17042 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
17043 if (option_debug)
17044 ast_log(LOG_DEBUG, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
17045 } else if (!strcasecmp(v->name, "allowtransfer")) {
17046 global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
17047 } else if (!strcasecmp(v->name, "rtcachefriends")) {
17048 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
17049 } else if (!strcasecmp(v->name, "rtsavesysname")) {
17050 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTSAVE_SYSNAME);
17051 } else if (!strcasecmp(v->name, "rtupdate")) {
17052 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTUPDATE);
17053 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
17054 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_IGNOREREGEXPIRE);
17055 } else if (!strcasecmp(v->name, "t1min")) {
17056 global_t1min = atoi(v->value);
17057 } else if (!strcasecmp(v->name, "rtautoclear")) {
17058 int i = atoi(v->value);
17059 if (i > 0)
17060 global_rtautoclear = i;
17061 else
17062 i = 0;
17063 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
17064 } else if (!strcasecmp(v->name, "usereqphone")) {
17065 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
17066 } else if (!strcasecmp(v->name, "relaxdtmf")) {
17067 global_relaxdtmf = ast_true(v->value);
17068 } else if (!strcasecmp(v->name, "checkmwi")) {
17069 if ((sscanf(v->value, "%d", &global_mwitime) != 1) || (global_mwitime < 0)) {
17070 ast_log(LOG_WARNING, "'%s' is not a valid MWI time setting at line %d. Using default (10).\n", v->value, v->lineno);
17071 global_mwitime = DEFAULT_MWITIME;
17073 } else if (!strcasecmp(v->name, "vmexten")) {
17074 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
17075 } else if (!strcasecmp(v->name, "rtptimeout")) {
17076 if ((sscanf(v->value, "%d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
17077 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
17078 global_rtptimeout = 0;
17080 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
17081 if ((sscanf(v->value, "%d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
17082 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
17083 global_rtpholdtimeout = 0;
17085 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
17086 if ((sscanf(v->value, "%d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
17087 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
17088 global_rtpkeepalive = 0;
17090 } else if (!strcasecmp(v->name, "compactheaders")) {
17091 compactheaders = ast_true(v->value);
17092 } else if (!strcasecmp(v->name, "notifymimetype")) {
17093 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
17094 } else if (!strncasecmp(v->name, "limitonpeer", 11)) {
17095 global_limitonpeers = ast_true(v->value);
17096 } else if (!strcasecmp(v->name, "directrtpsetup")) {
17097 global_directrtpsetup = ast_true(v->value);
17098 } else if (!strcasecmp(v->name, "notifyringing")) {
17099 global_notifyringing = ast_true(v->value);
17100 } else if (!strcasecmp(v->name, "notifyhold")) {
17101 global_notifyhold = ast_true(v->value);
17102 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
17103 global_alwaysauthreject = ast_true(v->value);
17104 } else if (!strcasecmp(v->name, "mohinterpret")
17105 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
17106 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
17107 } else if (!strcasecmp(v->name, "mohsuggest")) {
17108 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
17109 } else if (!strcasecmp(v->name, "language")) {
17110 ast_copy_string(default_language, v->value, sizeof(default_language));
17111 } else if (!strcasecmp(v->name, "regcontext")) {
17112 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
17113 stringp = newcontexts;
17114 /* Let's remove any contexts that are no longer defined in regcontext */
17115 cleanup_stale_contexts(stringp, oldregcontext);
17116 /* Create contexts if they don't exist already */
17117 while ((context = strsep(&stringp, "&"))) {
17118 if (!ast_context_find(context))
17119 ast_context_create(NULL, context,"SIP");
17121 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
17122 } else if (!strcasecmp(v->name, "callerid")) {
17123 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
17124 } else if (!strcasecmp(v->name, "fromdomain")) {
17125 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
17126 } else if (!strcasecmp(v->name, "outboundproxy")) {
17127 if (ast_get_ip_or_srv(&outboundproxyip, v->value, srvlookup ? "_sip._udp" : NULL) < 0)
17128 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", v->value);
17129 } else if (!strcasecmp(v->name, "outboundproxyport")) {
17130 /* Port needs to be after IP */
17131 sscanf(v->value, "%d", &format);
17132 outboundproxyip.sin_port = htons(format);
17133 } else if (!strcasecmp(v->name, "autocreatepeer")) {
17134 autocreatepeer = ast_true(v->value);
17135 } else if (!strcasecmp(v->name, "srvlookup")) {
17136 srvlookup = ast_true(v->value);
17137 } else if (!strcasecmp(v->name, "pedantic")) {
17138 pedanticsipchecking = ast_true(v->value);
17139 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
17140 max_expiry = atoi(v->value);
17141 if (max_expiry < 1)
17142 max_expiry = DEFAULT_MAX_EXPIRY;
17143 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
17144 min_expiry = atoi(v->value);
17145 if (min_expiry < 1)
17146 min_expiry = DEFAULT_MIN_EXPIRY;
17147 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
17148 default_expiry = atoi(v->value);
17149 if (default_expiry < 1)
17150 default_expiry = DEFAULT_DEFAULT_EXPIRY;
17151 } else if (!strcasecmp(v->name, "sipdebug")) { /* XXX maybe ast_set2_flags ? */
17152 if (ast_true(v->value))
17153 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
17154 } else if (!strcasecmp(v->name, "dumphistory")) {
17155 dumphistory = ast_true(v->value);
17156 } else if (!strcasecmp(v->name, "recordhistory")) {
17157 recordhistory = ast_true(v->value);
17158 } else if (!strcasecmp(v->name, "registertimeout")) {
17159 global_reg_timeout = atoi(v->value);
17160 if (global_reg_timeout < 1)
17161 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
17162 } else if (!strcasecmp(v->name, "registerattempts")) {
17163 global_regattempts_max = atoi(v->value);
17164 } else if (!strcasecmp(v->name, "bindaddr")) {
17165 if (!(hp = ast_gethostbyname(v->value, &ahp))) {
17166 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
17167 } else {
17168 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
17170 } else if (!strcasecmp(v->name, "localnet")) {
17171 struct ast_ha *na;
17172 if (!(na = ast_append_ha("d", v->value, localaddr)))
17173 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
17174 else
17175 localaddr = na;
17176 } else if (!strcasecmp(v->name, "localmask")) {
17177 ast_log(LOG_WARNING, "Use of localmask is no long supported -- use localnet with mask syntax\n");
17178 } else if (!strcasecmp(v->name, "externip")) {
17179 if (!(hp = ast_gethostbyname(v->value, &ahp)))
17180 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
17181 else
17182 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
17183 externexpire = 0;
17184 } else if (!strcasecmp(v->name, "externhost")) {
17185 ast_copy_string(externhost, v->value, sizeof(externhost));
17186 if (!(hp = ast_gethostbyname(externhost, &ahp)))
17187 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
17188 else
17189 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
17190 externexpire = time(NULL);
17191 } else if (!strcasecmp(v->name, "externrefresh")) {
17192 if (sscanf(v->value, "%d", &externrefresh) != 1) {
17193 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
17194 externrefresh = 10;
17196 } else if (!strcasecmp(v->name, "allow")) {
17197 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 1);
17198 } else if (!strcasecmp(v->name, "disallow")) {
17199 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 0);
17200 } else if (!strcasecmp(v->name, "autoframing")) {
17201 global_autoframing = ast_true(v->value);
17202 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
17203 allow_external_domains = ast_true(v->value);
17204 } else if (!strcasecmp(v->name, "autodomain")) {
17205 auto_sip_domains = ast_true(v->value);
17206 } else if (!strcasecmp(v->name, "domain")) {
17207 char *domain = ast_strdupa(v->value);
17208 char *context = strchr(domain, ',');
17210 if (context)
17211 *context++ = '\0';
17213 if (option_debug && ast_strlen_zero(context))
17214 ast_log(LOG_DEBUG, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
17215 if (ast_strlen_zero(domain))
17216 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
17217 else
17218 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, context ? ast_strip(context) : "");
17219 } else if (!strcasecmp(v->name, "register")) {
17220 if (sip_register(v->value, v->lineno) == 0)
17221 registry_count++;
17222 } else if (!strcasecmp(v->name, "tos")) {
17223 if (!ast_str2tos(v->value, &temp_tos)) {
17224 global_tos_sip = temp_tos;
17225 global_tos_audio = temp_tos;
17226 global_tos_video = temp_tos;
17227 ast_log(LOG_WARNING, "tos value at line %d is deprecated. See doc/ip-tos.txt for more information.\n", v->lineno);
17228 } else
17229 ast_log(LOG_WARNING, "Invalid tos value at line %d, See doc/ip-tos.txt for more information.\n", v->lineno);
17230 } else if (!strcasecmp(v->name, "tos_sip")) {
17231 if (ast_str2tos(v->value, &global_tos_sip))
17232 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, recommended value is 'cs3'. See doc/ip-tos.txt.\n", v->lineno);
17233 } else if (!strcasecmp(v->name, "tos_audio")) {
17234 if (ast_str2tos(v->value, &global_tos_audio))
17235 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, recommended value is 'ef'. See doc/ip-tos.txt.\n", v->lineno);
17236 } else if (!strcasecmp(v->name, "tos_video")) {
17237 if (ast_str2tos(v->value, &global_tos_video))
17238 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, recommended value is 'af41'. See doc/ip-tos.txt.\n", v->lineno);
17239 } else if (!strcasecmp(v->name, "bindport")) {
17240 if (sscanf(v->value, "%d", &ourport) == 1) {
17241 bindaddr.sin_port = htons(ourport);
17242 } else {
17243 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
17245 } else if (!strcasecmp(v->name, "qualify")) {
17246 if (!strcasecmp(v->value, "no")) {
17247 default_qualify = 0;
17248 } else if (!strcasecmp(v->value, "yes")) {
17249 default_qualify = DEFAULT_MAXMS;
17250 } else if (sscanf(v->value, "%d", &default_qualify) != 1) {
17251 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
17252 default_qualify = 0;
17254 } else if (!strcasecmp(v->name, "callevents")) {
17255 global_callevents = ast_true(v->value);
17256 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
17257 default_maxcallbitrate = atoi(v->value);
17258 if (default_maxcallbitrate < 0)
17259 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
17260 } else if (!strcasecmp(v->name, "matchexterniplocally")) {
17261 global_matchexterniplocally = ast_true(v->value);
17265 if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
17266 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
17267 allow_external_domains = 1;
17270 /* Build list of authentication to various SIP realms, i.e. service providers */
17271 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
17272 /* Format for authentication is auth = username:password@realm */
17273 if (!strcasecmp(v->name, "auth"))
17274 authl = add_realm_authentication(authl, v->value, v->lineno);
17277 ucfg = ast_config_load("users.conf");
17278 if (ucfg) {
17279 struct ast_variable *gen;
17280 int genhassip, genregistersip;
17281 const char *hassip, *registersip;
17283 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
17284 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
17285 gen = ast_variable_browse(ucfg, "general");
17286 cat = ast_category_browse(ucfg, NULL);
17287 while (cat) {
17288 if (strcasecmp(cat, "general")) {
17289 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
17290 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
17291 if (ast_true(hassip) || (!hassip && genhassip)) {
17292 user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
17293 if (user) {
17294 ASTOBJ_CONTAINER_LINK(&userl,user);
17295 ASTOBJ_UNREF(user, sip_destroy_user);
17296 user_count++;
17298 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
17299 if (peer) {
17300 ast_device_state_changed("SIP/%s", peer->name);
17301 ASTOBJ_CONTAINER_LINK(&peerl,peer);
17302 ASTOBJ_UNREF(peer, sip_destroy_peer);
17303 peer_count++;
17306 if (ast_true(registersip) || (!registersip && genregistersip)) {
17307 char tmp[256];
17308 const char *host = ast_variable_retrieve(ucfg, cat, "host");
17309 const char *username = ast_variable_retrieve(ucfg, cat, "username");
17310 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
17311 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
17312 if (!host)
17313 host = ast_variable_retrieve(ucfg, "general", "host");
17314 if (!username)
17315 username = ast_variable_retrieve(ucfg, "general", "username");
17316 if (!secret)
17317 secret = ast_variable_retrieve(ucfg, "general", "secret");
17318 if (!contact)
17319 contact = "s";
17320 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
17321 if (!ast_strlen_zero(secret))
17322 snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
17323 else
17324 snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
17325 if (sip_register(tmp, 0) == 0)
17326 registry_count++;
17330 cat = ast_category_browse(ucfg, cat);
17332 ast_config_destroy(ucfg);
17336 /* Load peers, users and friends */
17337 cat = NULL;
17338 while ( (cat = ast_category_browse(cfg, cat)) ) {
17339 const char *utype;
17340 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
17341 continue;
17342 utype = ast_variable_retrieve(cfg, cat, "type");
17343 if (!utype) {
17344 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
17345 continue;
17346 } else {
17347 int is_user = 0, is_peer = 0;
17348 if (!strcasecmp(utype, "user"))
17349 is_user = 1;
17350 else if (!strcasecmp(utype, "friend"))
17351 is_user = is_peer = 1;
17352 else if (!strcasecmp(utype, "peer"))
17353 is_peer = 1;
17354 else {
17355 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
17356 continue;
17358 if (is_user) {
17359 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
17360 if (user) {
17361 ASTOBJ_CONTAINER_LINK(&userl,user);
17362 ASTOBJ_UNREF(user, sip_destroy_user);
17363 user_count++;
17366 if (is_peer) {
17367 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
17368 if (peer) {
17369 ASTOBJ_CONTAINER_LINK(&peerl,peer);
17370 ASTOBJ_UNREF(peer, sip_destroy_peer);
17371 peer_count++;
17376 if (ast_find_ourip(&__ourip, bindaddr)) {
17377 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
17378 ast_config_destroy(cfg);
17379 return 0;
17381 if (!ntohs(bindaddr.sin_port))
17382 bindaddr.sin_port = ntohs(STANDARD_SIP_PORT);
17383 bindaddr.sin_family = AF_INET;
17384 ast_mutex_lock(&netlock);
17385 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
17386 close(sipsock);
17387 sipsock = -1;
17389 if (sipsock < 0) {
17390 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
17391 if (sipsock < 0) {
17392 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
17393 ast_config_destroy(cfg);
17394 return -1;
17395 } else {
17396 /* Allow SIP clients on the same host to access us: */
17397 const int reuseFlag = 1;
17399 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
17400 (const char*)&reuseFlag,
17401 sizeof reuseFlag);
17403 ast_enable_packet_fragmentation(sipsock);
17405 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
17406 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
17407 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
17408 strerror(errno));
17409 close(sipsock);
17410 sipsock = -1;
17411 } else {
17412 if (option_verbose > 1) {
17413 ast_verbose(VERBOSE_PREFIX_2 "SIP Listening on %s:%d\n",
17414 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
17415 ast_verbose(VERBOSE_PREFIX_2 "Using SIP TOS: %s\n", ast_tos2str(global_tos_sip));
17417 if (setsockopt(sipsock, IPPROTO_IP, IP_TOS, &global_tos_sip, sizeof(global_tos_sip)))
17418 ast_log(LOG_WARNING, "Unable to set SIP TOS to %s\n", ast_tos2str(global_tos_sip));
17422 ast_mutex_unlock(&netlock);
17424 /* Add default domains - host name, IP address and IP:port */
17425 /* Only do this if user added any sip domain with "localdomains" */
17426 /* In order to *not* break backwards compatibility */
17427 /* Some phones address us at IP only, some with additional port number */
17428 if (auto_sip_domains) {
17429 char temp[MAXHOSTNAMELEN];
17431 /* First our default IP address */
17432 if (bindaddr.sin_addr.s_addr)
17433 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
17434 else
17435 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
17437 /* Our extern IP address, if configured */
17438 if (externip.sin_addr.s_addr)
17439 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
17441 /* Extern host name (NAT traversal support) */
17442 if (!ast_strlen_zero(externhost))
17443 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
17445 /* Our host name */
17446 if (!gethostname(temp, sizeof(temp)))
17447 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
17450 /* Release configuration from memory */
17451 ast_config_destroy(cfg);
17453 /* Load the list of manual NOTIFY types to support */
17454 if (notify_types)
17455 ast_config_destroy(notify_types);
17456 notify_types = ast_config_load(notify_config);
17458 /* Done, tell the manager */
17459 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);
17461 return 0;
17464 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
17466 struct sip_pvt *p;
17467 struct ast_udptl *udptl = NULL;
17469 p = chan->tech_pvt;
17470 if (!p)
17471 return NULL;
17473 ast_mutex_lock(&p->lock);
17474 if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
17475 udptl = p->udptl;
17476 ast_mutex_unlock(&p->lock);
17477 return udptl;
17480 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
17482 struct sip_pvt *p;
17484 p = chan->tech_pvt;
17485 if (!p)
17486 return -1;
17487 ast_mutex_lock(&p->lock);
17488 if (udptl)
17489 ast_udptl_get_peer(udptl, &p->udptlredirip);
17490 else
17491 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
17492 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
17493 if (!p->pendinginvite) {
17494 if (option_debug > 2) {
17495 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);
17497 transmit_reinvite_with_t38_sdp(p);
17498 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17499 if (option_debug > 2) {
17500 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);
17502 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17505 /* Reset lastrtprx timer */
17506 p->lastrtprx = p->lastrtptx = time(NULL);
17507 ast_mutex_unlock(&p->lock);
17508 return 0;
17511 /*! \brief Handle T38 reinvite
17512 \todo Make sure we don't destroy the call if we can't handle the re-invite.
17513 Nothing should be changed until we have processed the SDP and know that we
17514 can handle it.
17516 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite)
17518 struct sip_pvt *p;
17519 int flag = 0;
17521 p = chan->tech_pvt;
17522 if (!p || !pvt->udptl)
17523 return -1;
17525 /* Setup everything on the other side like offered/responded from first side */
17526 ast_mutex_lock(&p->lock);
17528 /*! \todo check if this is not set earlier when setting up the PVT. If not
17529 maybe it should move there. */
17530 p->t38.jointcapability = p->t38.peercapability = pvt->t38.jointcapability;
17532 ast_udptl_set_far_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
17533 ast_udptl_set_local_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
17534 ast_udptl_set_error_correction_scheme(p->udptl, ast_udptl_get_error_correction_scheme(pvt->udptl));
17536 if (reinvite) { /* If we are handling sending re-invite to the other side of the bridge */
17537 /*! \note The SIP_CAN_REINVITE flag is for RTP media redirects,
17538 not really T38 re-invites which are different. In this
17539 case it's used properly, to see if we can reinvite over
17540 NAT
17542 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
17543 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
17544 flag =1;
17545 } else {
17546 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
17548 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
17549 if (!p->pendinginvite) {
17550 if (option_debug > 2) {
17551 if (flag)
17552 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));
17553 else
17554 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));
17556 transmit_reinvite_with_t38_sdp(p);
17557 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17558 if (option_debug > 2) {
17559 if (flag)
17560 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));
17561 else
17562 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));
17564 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17567 /* Reset lastrtprx timer */
17568 p->lastrtprx = p->lastrtptx = time(NULL);
17569 ast_mutex_unlock(&p->lock);
17570 return 0;
17571 } else { /* If we are handling sending 200 OK to the other side of the bridge */
17572 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
17573 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
17574 flag = 1;
17575 } else {
17576 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
17578 if (option_debug > 2) {
17579 if (flag)
17580 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));
17581 else
17582 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));
17584 pvt->t38.state = T38_ENABLED;
17585 p->t38.state = T38_ENABLED;
17586 if (option_debug > 1) {
17587 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", pvt->t38.state, pvt->owner ? pvt->owner->name : "<none>");
17588 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
17590 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
17591 p->lastrtprx = p->lastrtptx = time(NULL);
17592 ast_mutex_unlock(&p->lock);
17593 return 0;
17598 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
17599 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
17601 struct sip_pvt *p = NULL;
17602 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
17604 if (!(p = chan->tech_pvt))
17605 return AST_RTP_GET_FAILED;
17607 ast_mutex_lock(&p->lock);
17608 if (!(p->rtp)) {
17609 ast_mutex_unlock(&p->lock);
17610 return AST_RTP_GET_FAILED;
17613 *rtp = p->rtp;
17615 if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT))
17616 res = AST_RTP_TRY_PARTIAL;
17617 else if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
17618 res = AST_RTP_TRY_NATIVE;
17619 else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
17620 res = AST_RTP_GET_FAILED;
17622 ast_mutex_unlock(&p->lock);
17624 return res;
17627 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
17628 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
17630 struct sip_pvt *p = NULL;
17631 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
17633 if (!(p = chan->tech_pvt))
17634 return AST_RTP_GET_FAILED;
17636 ast_mutex_lock(&p->lock);
17637 if (!(p->vrtp)) {
17638 ast_mutex_unlock(&p->lock);
17639 return AST_RTP_GET_FAILED;
17642 *rtp = p->vrtp;
17644 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
17645 res = AST_RTP_TRY_NATIVE;
17647 ast_mutex_unlock(&p->lock);
17649 return res;
17652 /*! \brief Set the RTP peer for this call */
17653 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
17655 struct sip_pvt *p;
17656 int changed = 0;
17658 p = chan->tech_pvt;
17659 if (!p)
17660 return -1;
17662 /* Disable early RTP bridge */
17663 if (chan->_state != AST_STATE_UP && !global_directrtpsetup) /* We are in early state */
17664 return 0;
17666 ast_mutex_lock(&p->lock);
17667 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) {
17668 /* If we're destroyed, don't bother */
17669 ast_mutex_unlock(&p->lock);
17670 return 0;
17673 /* if this peer cannot handle reinvites of the media stream to devices
17674 that are known to be behind a NAT, then stop the process now
17676 if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
17677 ast_mutex_unlock(&p->lock);
17678 return 0;
17681 if (rtp) {
17682 changed |= ast_rtp_get_peer(rtp, &p->redirip);
17683 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
17684 memset(&p->redirip, 0, sizeof(p->redirip));
17685 changed = 1;
17687 if (vrtp) {
17688 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
17689 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
17690 memset(&p->vredirip, 0, sizeof(p->vredirip));
17691 changed = 1;
17693 if (codecs) {
17694 if ((p->redircodecs != codecs)) {
17695 p->redircodecs = codecs;
17696 changed = 1;
17698 if ((p->capability & codecs) != p->capability) {
17699 p->jointcapability &= codecs;
17700 p->capability &= codecs;
17701 changed = 1;
17704 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
17705 if (chan->_state != AST_STATE_UP) { /* We are in early state */
17706 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
17707 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
17708 if (option_debug)
17709 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));
17710 } else if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
17711 if (option_debug > 2) {
17712 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));
17714 transmit_reinvite_with_sdp(p);
17715 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17716 if (option_debug > 2) {
17717 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));
17719 /* We have a pending Invite. Send re-invite when we're done with the invite */
17720 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17723 /* Reset lastrtprx timer */
17724 p->lastrtprx = p->lastrtptx = time(NULL);
17725 ast_mutex_unlock(&p->lock);
17726 return 0;
17729 static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
17730 static char *descrip_dtmfmode = "SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
17731 static char *app_dtmfmode = "SIPDtmfMode";
17733 static char *app_sipaddheader = "SIPAddHeader";
17734 static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
17736 static char *descrip_sipaddheader = ""
17737 " SIPAddHeader(Header: Content)\n"
17738 "Adds a header to a SIP call placed with DIAL.\n"
17739 "Remember to user the X-header if you are adding non-standard SIP\n"
17740 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
17741 "Adding the wrong headers may jeopardize the SIP dialog.\n"
17742 "Always returns 0\n";
17745 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
17746 static int sip_dtmfmode(struct ast_channel *chan, void *data)
17748 struct sip_pvt *p;
17749 char *mode;
17750 if (data)
17751 mode = (char *)data;
17752 else {
17753 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
17754 return 0;
17756 ast_channel_lock(chan);
17757 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
17758 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
17759 ast_channel_unlock(chan);
17760 return 0;
17762 p = chan->tech_pvt;
17763 if (!p) {
17764 ast_channel_unlock(chan);
17765 return 0;
17767 ast_mutex_lock(&p->lock);
17768 if (!strcasecmp(mode,"info")) {
17769 ast_clear_flag(&p->flags[0], SIP_DTMF);
17770 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
17771 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
17772 } else if (!strcasecmp(mode,"rfc2833")) {
17773 ast_clear_flag(&p->flags[0], SIP_DTMF);
17774 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
17775 p->jointnoncodeccapability |= AST_RTP_DTMF;
17776 } else if (!strcasecmp(mode,"inband")) {
17777 ast_clear_flag(&p->flags[0], SIP_DTMF);
17778 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
17779 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
17780 } else
17781 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n",mode);
17782 if (p->rtp)
17783 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
17784 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
17785 if (!p->vad) {
17786 p->vad = ast_dsp_new();
17787 ast_dsp_set_features(p->vad, DSP_FEATURE_DTMF_DETECT);
17789 } else {
17790 if (p->vad) {
17791 ast_dsp_free(p->vad);
17792 p->vad = NULL;
17795 ast_mutex_unlock(&p->lock);
17796 ast_channel_unlock(chan);
17797 return 0;
17800 /*! \brief Add a SIP header to an outbound INVITE */
17801 static int sip_addheader(struct ast_channel *chan, void *data)
17803 int no = 0;
17804 int ok = FALSE;
17805 char varbuf[30];
17806 char *inbuf = (char *) data;
17808 if (ast_strlen_zero(inbuf)) {
17809 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
17810 return 0;
17812 ast_channel_lock(chan);
17814 /* Check for headers */
17815 while (!ok && no <= 50) {
17816 no++;
17817 snprintf(varbuf, sizeof(varbuf), "_SIPADDHEADER%.2d", no);
17819 /* Compare without the leading underscore */
17820 if( (pbx_builtin_getvar_helper(chan, (const char *) varbuf + 1) == (const char *) NULL) )
17821 ok = TRUE;
17823 if (ok) {
17824 pbx_builtin_setvar_helper (chan, varbuf, inbuf);
17825 if (sipdebug)
17826 ast_log(LOG_DEBUG,"SIP Header added \"%s\" as %s\n", inbuf, varbuf);
17827 } else {
17828 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
17830 ast_channel_unlock(chan);
17831 return 0;
17834 /*! \brief Transfer call before connect with a 302 redirect
17835 \note Called by the transfer() dialplan application through the sip_transfer()
17836 pbx interface function if the call is in ringing state
17837 \todo Fix this function so that we wait for reply to the REFER and
17838 react to errors, denials or other issues the other end might have.
17840 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
17842 char *cdest;
17843 char *extension, *host, *port;
17844 char tmp[80];
17846 cdest = ast_strdupa(dest);
17848 extension = strsep(&cdest, "@");
17849 host = strsep(&cdest, ":");
17850 port = strsep(&cdest, ":");
17851 if (ast_strlen_zero(extension)) {
17852 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
17853 return 0;
17856 /* we'll issue the redirect message here */
17857 if (!host) {
17858 char *localtmp;
17859 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
17860 if (ast_strlen_zero(tmp)) {
17861 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
17862 return 0;
17864 if ((localtmp = strcasestr(tmp, "sip:")) && (localtmp = strchr(localtmp, '@'))) {
17865 char lhost[80], lport[80];
17866 memset(lhost, 0, sizeof(lhost));
17867 memset(lport, 0, sizeof(lport));
17868 localtmp++;
17869 /* This is okey because lhost and lport are as big as tmp */
17870 sscanf(localtmp, "%[^<>:; ]:%[^<>:; ]", lhost, lport);
17871 if (ast_strlen_zero(lhost)) {
17872 ast_log(LOG_ERROR, "Can't find the host address\n");
17873 return 0;
17875 host = ast_strdupa(lhost);
17876 if (!ast_strlen_zero(lport)) {
17877 port = ast_strdupa(lport);
17882 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
17883 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
17885 sip_scheddestroy(p, SIP_TRANS_TIMEOUT); /* Make sure we stop send this reply. */
17886 sip_alreadygone(p);
17887 return 0;
17890 /*! \brief Return SIP UA's codec (part of the RTP interface) */
17891 static int sip_get_codec(struct ast_channel *chan)
17893 struct sip_pvt *p = chan->tech_pvt;
17894 return p->peercapability ? p->peercapability : p->capability;
17897 /*! \brief Send a poke to all known peers
17898 Space them out 100 ms apart
17899 XXX We might have a cool algorithm for this or use random - any suggestions?
17901 static void sip_poke_all_peers(void)
17903 int ms = 0;
17905 if (!speerobjs) /* No peers, just give up */
17906 return;
17908 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
17909 ASTOBJ_WRLOCK(iterator);
17910 if (!AST_SCHED_DEL(sched, iterator->pokeexpire)) {
17911 struct sip_peer *peer_ptr = iterator;
17912 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
17914 ms += 100;
17915 iterator->pokeexpire = ast_sched_add(sched, ms, sip_poke_peer_s, ASTOBJ_REF(iterator));
17916 if (iterator->pokeexpire == -1) {
17917 struct sip_peer *peer_ptr = iterator;
17918 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
17920 ASTOBJ_UNLOCK(iterator);
17921 } while (0)
17925 /*! \brief Send all known registrations */
17926 static void sip_send_all_registers(void)
17928 int ms;
17929 int regspacing;
17930 if (!regobjs)
17931 return;
17932 regspacing = default_expiry * 1000/regobjs;
17933 if (regspacing > 100)
17934 regspacing = 100;
17935 ms = regspacing;
17936 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
17937 ASTOBJ_WRLOCK(iterator);
17938 AST_SCHED_DEL(sched, iterator->expire);
17939 ms += regspacing;
17940 iterator->expire = ast_sched_add(sched, ms, sip_reregister, iterator);
17941 ASTOBJ_UNLOCK(iterator);
17942 } while (0)
17946 /*! \brief Reload module */
17947 static int sip_do_reload(enum channelreloadreason reason)
17949 reload_config(reason);
17951 /* Prune peers who still are supposed to be deleted */
17952 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
17953 if (option_debug > 3)
17954 ast_log(LOG_DEBUG, "--------------- Done destroying pruned peers\n");
17956 /* Send qualify (OPTIONS) to all peers */
17957 sip_poke_all_peers();
17959 /* Register with all services */
17960 sip_send_all_registers();
17962 if (option_debug > 3)
17963 ast_log(LOG_DEBUG, "--------------- SIP reload done\n");
17965 return 0;
17968 /*! \brief Force reload of module from cli */
17969 static int sip_reload(int fd, int argc, char *argv[])
17971 ast_mutex_lock(&sip_reload_lock);
17972 if (sip_reloading)
17973 ast_verbose("Previous SIP reload not yet done\n");
17974 else {
17975 sip_reloading = TRUE;
17976 if (fd)
17977 sip_reloadreason = CHANNEL_CLI_RELOAD;
17978 else
17979 sip_reloadreason = CHANNEL_MODULE_RELOAD;
17981 ast_mutex_unlock(&sip_reload_lock);
17982 restart_monitor();
17984 return 0;
17987 /*! \brief Part of Asterisk module interface */
17988 static int reload(void)
17990 return sip_reload(0, 0, NULL);
17993 static struct ast_cli_entry cli_sip_debug_deprecated =
17994 { { "sip", "debug", NULL },
17995 sip_do_debug_deprecated, "Enable SIP debugging",
17996 debug_usage };
17998 static struct ast_cli_entry cli_sip_no_debug_deprecated =
17999 { { "sip", "no", "debug", NULL },
18000 sip_no_debug_deprecated, "Disable SIP debugging",
18001 debug_usage };
18003 static struct ast_cli_entry cli_sip[] = {
18004 { { "sip", "show", "channels", NULL },
18005 sip_show_channels, "List active SIP channels",
18006 show_channels_usage },
18008 { { "sip", "show", "domains", NULL },
18009 sip_show_domains, "List our local SIP domains.",
18010 show_domains_usage },
18012 { { "sip", "show", "inuse", NULL },
18013 sip_show_inuse, "List all inuse/limits",
18014 show_inuse_usage },
18016 { { "sip", "show", "objects", NULL },
18017 sip_show_objects, "List all SIP object allocations",
18018 show_objects_usage },
18020 { { "sip", "show", "peers", NULL },
18021 sip_show_peers, "List defined SIP peers",
18022 show_peers_usage },
18024 { { "sip", "show", "registry", NULL },
18025 sip_show_registry, "List SIP registration status",
18026 show_reg_usage },
18028 { { "sip", "show", "settings", NULL },
18029 sip_show_settings, "Show SIP global settings",
18030 show_settings_usage },
18032 { { "sip", "show", "subscriptions", NULL },
18033 sip_show_subscriptions, "List active SIP subscriptions",
18034 show_subscriptions_usage },
18036 { { "sip", "show", "users", NULL },
18037 sip_show_users, "List defined SIP users",
18038 show_users_usage },
18040 { { "sip", "notify", NULL },
18041 sip_notify, "Send a notify packet to a SIP peer",
18042 notify_usage, complete_sipnotify },
18044 { { "sip", "show", "channel", NULL },
18045 sip_show_channel, "Show detailed SIP channel info",
18046 show_channel_usage, complete_sipch },
18048 { { "sip", "show", "history", NULL },
18049 sip_show_history, "Show SIP dialog history",
18050 show_history_usage, complete_sipch },
18052 { { "sip", "show", "peer", NULL },
18053 sip_show_peer, "Show details on specific SIP peer",
18054 show_peer_usage, complete_sip_show_peer },
18056 { { "sip", "show", "user", NULL },
18057 sip_show_user, "Show details on specific SIP user",
18058 show_user_usage, complete_sip_show_user },
18060 { { "sip", "prune", "realtime", NULL },
18061 sip_prune_realtime, "Prune cached Realtime object(s)",
18062 prune_realtime_usage },
18064 { { "sip", "prune", "realtime", "peer", NULL },
18065 sip_prune_realtime, "Prune cached Realtime peer(s)",
18066 prune_realtime_usage, complete_sip_prune_realtime_peer },
18068 { { "sip", "prune", "realtime", "user", NULL },
18069 sip_prune_realtime, "Prune cached Realtime user(s)",
18070 prune_realtime_usage, complete_sip_prune_realtime_user },
18072 { { "sip", "set", "debug", NULL },
18073 sip_do_debug, "Enable SIP debugging",
18074 debug_usage, NULL, &cli_sip_debug_deprecated },
18076 { { "sip", "set", "debug", "ip", NULL },
18077 sip_do_debug, "Enable SIP debugging on IP",
18078 debug_usage },
18080 { { "sip", "set", "debug", "peer", NULL },
18081 sip_do_debug, "Enable SIP debugging on Peername",
18082 debug_usage, complete_sip_debug_peer },
18084 { { "sip", "set", "debug", "off", NULL },
18085 sip_no_debug, "Disable SIP debugging",
18086 no_debug_usage, NULL, &cli_sip_no_debug_deprecated },
18088 { { "sip", "history", NULL },
18089 sip_do_history, "Enable SIP history",
18090 history_usage },
18092 { { "sip", "history", "off", NULL },
18093 sip_no_history, "Disable SIP history",
18094 no_history_usage },
18096 { { "sip", "reload", NULL },
18097 sip_reload, "Reload SIP configuration",
18098 sip_reload_usage },
18101 /*! \brief PBX load module - initialization */
18102 static int load_module(void)
18104 ASTOBJ_CONTAINER_INIT(&userl); /* User object list */
18105 ASTOBJ_CONTAINER_INIT(&peerl); /* Peer object list */
18106 ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list */
18108 if (!(sched = sched_context_create())) {
18109 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
18110 return AST_MODULE_LOAD_FAILURE;
18113 if (!(io = io_context_create())) {
18114 ast_log(LOG_ERROR, "Unable to create I/O context\n");
18115 sched_context_destroy(sched);
18116 return AST_MODULE_LOAD_FAILURE;
18119 sip_reloadreason = CHANNEL_MODULE_LOAD;
18121 if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
18122 return AST_MODULE_LOAD_DECLINE;
18124 /* Make sure we can register our sip channel type */
18125 if (ast_channel_register(&sip_tech)) {
18126 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
18127 io_context_destroy(io);
18128 sched_context_destroy(sched);
18129 return AST_MODULE_LOAD_FAILURE;
18132 /* Register all CLI functions for SIP */
18133 ast_cli_register_multiple(cli_sip, sizeof(cli_sip)/ sizeof(struct ast_cli_entry));
18135 /* Tell the RTP subdriver that we're here */
18136 ast_rtp_proto_register(&sip_rtp);
18138 /* Tell the UDPTL subdriver that we're here */
18139 ast_udptl_proto_register(&sip_udptl);
18141 /* Register dialplan applications */
18142 ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
18143 ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
18145 /* Register dialplan functions */
18146 ast_custom_function_register(&sip_header_function);
18147 ast_custom_function_register(&sippeer_function);
18148 ast_custom_function_register(&sipchaninfo_function);
18149 ast_custom_function_register(&checksipdomain_function);
18151 /* Register manager commands */
18152 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM, manager_sip_show_peers,
18153 "List SIP peers (text format)", mandescr_show_peers);
18154 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM, manager_sip_show_peer,
18155 "Show SIP peer (text format)", mandescr_show_peer);
18157 sip_poke_all_peers();
18158 sip_send_all_registers();
18160 /* And start the monitor for the first time */
18161 restart_monitor();
18163 return AST_MODULE_LOAD_SUCCESS;
18166 /*! \brief PBX unload module API */
18167 static int unload_module(void)
18169 struct sip_pvt *p, *pl;
18171 /* First, take us out of the channel type list */
18172 ast_channel_unregister(&sip_tech);
18174 /* Unregister dial plan functions */
18175 ast_custom_function_unregister(&sipchaninfo_function);
18176 ast_custom_function_unregister(&sippeer_function);
18177 ast_custom_function_unregister(&sip_header_function);
18178 ast_custom_function_unregister(&checksipdomain_function);
18180 /* Unregister dial plan applications */
18181 ast_unregister_application(app_dtmfmode);
18182 ast_unregister_application(app_sipaddheader);
18184 /* Unregister CLI commands */
18185 ast_cli_unregister_multiple(cli_sip, sizeof(cli_sip) / sizeof(struct ast_cli_entry));
18187 /* Disconnect from the RTP subsystem */
18188 ast_rtp_proto_unregister(&sip_rtp);
18190 /* Disconnect from UDPTL */
18191 ast_udptl_proto_unregister(&sip_udptl);
18193 /* Unregister AMI actions */
18194 ast_manager_unregister("SIPpeers");
18195 ast_manager_unregister("SIPshowpeer");
18197 ast_mutex_lock(&iflock);
18198 /* Hangup all interfaces if they have an owner */
18199 for (p = iflist; p ; p = p->next) {
18200 if (p->owner)
18201 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
18203 ast_mutex_unlock(&iflock);
18205 ast_mutex_lock(&monlock);
18206 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
18207 pthread_cancel(monitor_thread);
18208 pthread_kill(monitor_thread, SIGURG);
18209 pthread_join(monitor_thread, NULL);
18211 monitor_thread = AST_PTHREADT_STOP;
18212 ast_mutex_unlock(&monlock);
18214 restartdestroy:
18215 ast_mutex_lock(&iflock);
18216 /* Destroy all the interfaces and free their memory */
18217 p = iflist;
18218 while (p) {
18219 pl = p;
18220 p = p->next;
18221 if (__sip_destroy(pl, TRUE) < 0) {
18222 /* Something is still bridged, let it react to getting a hangup */
18223 iflist = p;
18224 ast_mutex_unlock(&iflock);
18225 usleep(1);
18226 goto restartdestroy;
18229 iflist = NULL;
18230 ast_mutex_unlock(&iflock);
18232 /* Free memory for local network address mask */
18233 ast_free_ha(localaddr);
18235 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
18236 ASTOBJ_CONTAINER_DESTROY(&userl);
18237 ASTOBJ_CONTAINER_DESTROYALL(&peerl, sip_destroy_peer);
18238 ASTOBJ_CONTAINER_DESTROY(&peerl);
18239 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
18240 ASTOBJ_CONTAINER_DESTROY(&regl);
18242 clear_realm_authentication(authl);
18243 clear_sip_domains();
18244 close(sipsock);
18245 sched_context_destroy(sched);
18247 return 0;
18250 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
18251 .load = load_module,
18252 .unload = unload_module,
18253 .reload = reload,