Use autotagged externals
[asterisk-bristuff.git] / channels / chan_sip.c
blob9b185a0715a5b0376531506669e10b309edc5d95
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
19 /*!
20 * \file
21 * \brief Implementation of Session Initiation Protocol
23 * \author Mark Spencer <markster@digium.com>
25 * See Also:
26 * \arg \ref AstCREDITS
28 * Implementation of RFC 3261 - without S/MIME, TCP and TLS support
29 * Configuration file \link Config_sip sip.conf \endlink
32 * \todo SIP over TCP
33 * \todo SIP over TLS
34 * \todo Better support of forking
35 * \todo VIA branch tag transaction checking
36 * \todo Transaction support
38 * \ingroup channel_drivers
40 * \par Overview of the handling of SIP sessions
41 * The SIP channel handles several types of SIP sessions, or dialogs,
42 * not all of them being "telephone calls".
43 * - Incoming calls that will be sent to the PBX core
44 * - Outgoing calls, generated by the PBX
45 * - SIP subscriptions and notifications of states and voicemail messages
46 * - SIP registrations, both inbound and outbound
47 * - SIP peer management (peerpoke, OPTIONS)
48 * - SIP text messages
50 * In the SIP channel, there's a list of active SIP dialogs, which includes
51 * all of these when they are active. "sip show channels" in the CLI will
52 * show most of these, excluding subscriptions which are shown by
53 * "sip show subscriptions"
55 * \par incoming packets
56 * Incoming packets are received in the monitoring thread, then handled by
57 * sipsock_read(). This function parses the packet and matches an existing
58 * dialog or starts a new SIP dialog.
60 * sipsock_read sends the packet to handle_request(), that parses a bit more.
61 * if it's a response to an outbound request, it's sent to handle_response().
62 * If it is a request, handle_request sends it to one of a list of functions
63 * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
64 * sipsock_read locks the ast_channel if it exists (an active call) and
65 * unlocks it after we have processed the SIP message.
67 * A new INVITE is sent to handle_request_invite(), that will end up
68 * starting a new channel in the PBX, the new channel after that executing
69 * in a separate channel thread. This is an incoming "call".
70 * When the call is answered, either by a bridged channel or the PBX itself
71 * the sip_answer() function is called.
73 * The actual media - Video or Audio - is mostly handled by the RTP subsystem
74 * in rtp.c
76 * \par Outbound calls
77 * Outbound calls are set up by the PBX through the sip_request_call()
78 * function. After that, they are activated by sip_call().
80 * \par Hanging up
81 * The PBX issues a hangup on both incoming and outgoing calls through
82 * the sip_hangup() function
84 * \par Deprecated stuff
85 * This is deprecated and will be removed after the 1.4 release
86 * - the SIPUSERAGENT dialplan variable
87 * - the ALERT_INFO dialplan variable
90 /*** MODULEINFO
91 <depend>res_features</depend>
92 ***/
95 #include "asterisk.h"
97 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
99 #include <stdio.h>
100 #include <ctype.h>
101 #include <string.h>
102 #include <unistd.h>
103 #include <sys/socket.h>
104 #include <sys/ioctl.h>
105 #include <net/if.h>
106 #include <errno.h>
107 #include <stdlib.h>
108 #include <fcntl.h>
109 #include <netdb.h>
110 #include <signal.h>
111 #include <sys/signal.h>
112 #include <netinet/in.h>
113 #include <netinet/in_systm.h>
114 #include <arpa/inet.h>
115 #include <netinet/ip.h>
116 #include <regex.h>
118 #include "asterisk/lock.h"
119 #include "asterisk/channel.h"
120 #include "asterisk/config.h"
121 #include "asterisk/logger.h"
122 #include "asterisk/module.h"
123 #include "asterisk/pbx.h"
124 #include "asterisk/options.h"
125 #include "asterisk/sched.h"
126 #include "asterisk/io.h"
127 #include "asterisk/rtp.h"
128 #include "asterisk/udptl.h"
129 #include "asterisk/acl.h"
130 #include "asterisk/manager.h"
131 #include "asterisk/callerid.h"
132 #include "asterisk/cli.h"
133 #include "asterisk/app.h"
134 #include "asterisk/musiconhold.h"
135 #include "asterisk/dsp.h"
136 #include "asterisk/features.h"
137 #include "asterisk/srv.h"
138 #include "asterisk/astdb.h"
139 #include "asterisk/causes.h"
140 #include "asterisk/utils.h"
141 #include "asterisk/file.h"
142 #include "asterisk/astobj.h"
143 #include "asterisk/devicestate.h"
144 #include "asterisk/linkedlists.h"
145 #include "asterisk/stringfields.h"
146 #include "asterisk/monitor.h"
147 #include "asterisk/localtime.h"
148 #include "asterisk/abstract_jb.h"
149 #include "asterisk/compiler.h"
150 #include "asterisk/threadstorage.h"
151 #include "asterisk/translate.h"
153 #ifndef FALSE
154 #define FALSE 0
155 #endif
157 #ifndef TRUE
158 #define TRUE 1
159 #endif
161 #define SIPBUFSIZE 512
163 #define XMIT_ERROR -2
165 #define VIDEO_CODEC_MASK 0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
166 #ifndef IPTOS_MINCOST
167 #define IPTOS_MINCOST 0x02
168 #endif
170 /* #define VOCAL_DATA_HACK */
172 #define DEFAULT_DEFAULT_EXPIRY 120
173 #define DEFAULT_MIN_EXPIRY 60
174 #define DEFAULT_MAX_EXPIRY 3600
175 #define DEFAULT_REGISTRATION_TIMEOUT 20
176 #define DEFAULT_MAX_FORWARDS "70"
178 /* guard limit must be larger than guard secs */
179 /* guard min must be < 1000, and should be >= 250 */
180 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
181 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
182 EXPIRY_GUARD_SECS */
183 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
184 GUARD_PCT turns out to be lower than this, it
185 will use this time instead.
186 This is in milliseconds. */
187 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
188 below EXPIRY_GUARD_LIMIT */
189 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
191 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
192 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
193 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
194 static int expiry = DEFAULT_EXPIRY;
196 #ifndef MAX
197 #define MAX(a,b) ((a) > (b) ? (a) : (b))
198 #endif
200 #define CALLERID_UNKNOWN "Unknown"
202 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
203 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
204 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
206 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
207 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
208 #define SIP_TRANS_TIMEOUT 32000 /*!< SIP request timeout (rfc 3261) 64*T1
209 \todo Use known T1 for timeout (peerpoke)
211 #define DEFAULT_TRANS_TIMEOUT -1 /* Use default SIP transaction timeout */
212 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
214 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
215 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
216 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
218 #define SDP_MAX_RTPMAP_CODECS 32 /*!< Maximum number of codecs allowed in received SDP */
220 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
222 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
223 static struct ast_jb_conf default_jbconf =
225 .flags = 0,
226 .max_size = -1,
227 .resync_threshold = -1,
228 .impl = ""
230 static struct ast_jb_conf global_jbconf;
232 static const char config[] = "sip.conf";
233 static const char notify_config[] = "sip_notify.conf";
235 #define RTP 1
236 #define NO_RTP 0
238 /*! \brief Authorization scheme for call transfers
239 \note Not a bitfield flag, since there are plans for other modes,
240 like "only allow transfers for authenticated devices" */
241 enum transfermodes {
242 TRANSFER_OPENFORALL, /*!< Allow all SIP transfers */
243 TRANSFER_CLOSED, /*!< Allow no SIP transfers */
247 enum sip_result {
248 AST_SUCCESS = 0,
249 AST_FAILURE = -1,
252 /*! \brief States for the INVITE transaction, not the dialog
253 \note this is for the INVITE that sets up the dialog
255 enum invitestates {
256 INV_NONE = 0, /*!< No state at all, maybe not an INVITE dialog */
257 INV_CALLING = 1, /*!< Invite sent, no answer */
258 INV_PROCEEDING = 2, /*!< We got/sent 1xx message */
259 INV_EARLY_MEDIA = 3, /*!< We got 18x message with to-tag back */
260 INV_COMPLETED = 4, /*!< Got final response with error. Wait for ACK, then CONFIRMED */
261 INV_CONFIRMED = 5, /*!< Confirmed response - we've got an ack (Incoming calls only) */
262 INV_TERMINATED = 6, /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done
263 The only way out of this is a BYE from one side */
264 INV_CANCELLED = 7, /*!< Transaction cancelled by client or server in non-terminated state */
267 /* Do _NOT_ make any changes to this enum, or the array following it;
268 if you think you are doing the right thing, you are probably
269 not doing the right thing. If you think there are changes
270 needed, get someone else to review them first _before_
271 submitting a patch. If these two lists do not match properly
272 bad things will happen.
275 enum xmittype {
276 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
277 If it fails, it's critical and will cause a teardown of the session */
278 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
279 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
282 enum parse_register_result {
283 PARSE_REGISTER_FAILED,
284 PARSE_REGISTER_UPDATE,
285 PARSE_REGISTER_QUERY,
288 enum subscriptiontype {
289 NONE = 0,
290 XPIDF_XML,
291 DIALOG_INFO_XML,
292 CPIM_PIDF_XML,
293 PIDF_XML,
294 MWI_NOTIFICATION
297 static const struct cfsubscription_types {
298 enum subscriptiontype type;
299 const char * const event;
300 const char * const mediatype;
301 const char * const text;
302 } subscription_types[] = {
303 { NONE, "-", "unknown", "unknown" },
304 /* RFC 4235: SIP Dialog event package */
305 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
306 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
307 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
308 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
309 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
312 /*! \brief SIP Request methods known by Asterisk */
313 enum sipmethod {
314 SIP_UNKNOWN, /* Unknown response */
315 SIP_RESPONSE, /* Not request, response to outbound request */
316 SIP_REGISTER,
317 SIP_OPTIONS,
318 SIP_NOTIFY,
319 SIP_INVITE,
320 SIP_ACK,
321 SIP_PRACK, /* Not supported at all */
322 SIP_BYE,
323 SIP_REFER,
324 SIP_SUBSCRIBE,
325 SIP_MESSAGE,
326 SIP_UPDATE, /* We can send UPDATE; but not accept it */
327 SIP_INFO,
328 SIP_CANCEL,
329 SIP_PUBLISH, /* Not supported at all */
330 SIP_PING, /* Not supported at all, no standard but still implemented out there */
333 /*! \brief Authentication types - proxy or www authentication
334 \note Endpoints, like Asterisk, should always use WWW authentication to
335 allow multiple authentications in the same call - to the proxy and
336 to the end point.
338 enum sip_auth_type {
339 PROXY_AUTH,
340 WWW_AUTH,
343 /*! \brief Authentication result from check_auth* functions */
344 enum check_auth_result {
345 AUTH_SUCCESSFUL = 0,
346 AUTH_CHALLENGE_SENT = 1,
347 AUTH_SECRET_FAILED = -1,
348 AUTH_USERNAME_MISMATCH = -2,
349 AUTH_NOT_FOUND = -3,
350 AUTH_FAKE_AUTH = -4,
351 AUTH_UNKNOWN_DOMAIN = -5,
352 AUTH_PEER_NOT_DYNAMIC = -6,
353 AUTH_ACL_FAILED = -7,
356 /*! \brief States for outbound registrations (with register= lines in sip.conf */
357 enum sipregistrystate {
358 REG_STATE_UNREGISTERED = 0, /*!< We are not registred */
359 REG_STATE_REGSENT, /*!< Registration request sent */
360 REG_STATE_AUTHSENT, /*!< We have tried to authenticate */
361 REG_STATE_REGISTERED, /*!< Registred and done */
362 REG_STATE_REJECTED, /*!< Registration rejected */
363 REG_STATE_TIMEOUT, /*!< Registration timed out */
364 REG_STATE_NOAUTH, /*!< We have no accepted credentials */
365 REG_STATE_FAILED, /*!< Registration failed after several tries */
368 #define CAN_NOT_CREATE_DIALOG 0
369 #define CAN_CREATE_DIALOG 1
370 #define CAN_CREATE_DIALOG_UNSUPPORTED_METHOD 2
372 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
373 static const struct cfsip_methods {
374 enum sipmethod id;
375 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
376 char * const text;
377 int can_create;
378 } sip_methods[] = {
379 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
380 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
381 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
382 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
383 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
384 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
385 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
386 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
387 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
388 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
389 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
390 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
391 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
392 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
393 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
394 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
395 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
398 /*! Define SIP option tags, used in Require: and Supported: headers
399 We need to be aware of these properties in the phones to use
400 the replace: header. We should not do that without knowing
401 that the other end supports it...
402 This is nothing we can configure, we learn by the dialog
403 Supported: header on the REGISTER (peer) or the INVITE
404 (other devices)
405 We are not using many of these today, but will in the future.
406 This is documented in RFC 3261
408 #define SUPPORTED 1
409 #define NOT_SUPPORTED 0
411 #define SIP_OPT_REPLACES (1 << 0)
412 #define SIP_OPT_100REL (1 << 1)
413 #define SIP_OPT_TIMER (1 << 2)
414 #define SIP_OPT_EARLY_SESSION (1 << 3)
415 #define SIP_OPT_JOIN (1 << 4)
416 #define SIP_OPT_PATH (1 << 5)
417 #define SIP_OPT_PREF (1 << 6)
418 #define SIP_OPT_PRECONDITION (1 << 7)
419 #define SIP_OPT_PRIVACY (1 << 8)
420 #define SIP_OPT_SDP_ANAT (1 << 9)
421 #define SIP_OPT_SEC_AGREE (1 << 10)
422 #define SIP_OPT_EVENTLIST (1 << 11)
423 #define SIP_OPT_GRUU (1 << 12)
424 #define SIP_OPT_TARGET_DIALOG (1 << 13)
425 #define SIP_OPT_NOREFERSUB (1 << 14)
426 #define SIP_OPT_HISTINFO (1 << 15)
427 #define SIP_OPT_RESPRIORITY (1 << 16)
429 /*! \brief List of well-known SIP options. If we get this in a require,
430 we should check the list and answer accordingly. */
431 static const struct cfsip_options {
432 int id; /*!< Bitmap ID */
433 int supported; /*!< Supported by Asterisk ? */
434 char * const text; /*!< Text id, as in standard */
435 } sip_options[] = { /* XXX used in 3 places */
436 /* RFC3891: Replaces: header for transfer */
437 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
438 /* One version of Polycom firmware has the wrong label */
439 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
440 /* RFC3262: PRACK 100% reliability */
441 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
442 /* RFC4028: SIP Session Timers */
443 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
444 /* RFC3959: SIP Early session support */
445 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
446 /* RFC3911: SIP Join header support */
447 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
448 /* RFC3327: Path support */
449 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
450 /* RFC3840: Callee preferences */
451 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
452 /* RFC3312: Precondition support */
453 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
454 /* RFC3323: Privacy with proxies*/
455 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
456 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
457 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
458 /* RFC3329: Security agreement mechanism */
459 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
460 /* SIMPLE events: RFC4662 */
461 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
462 /* GRUU: Globally Routable User Agent URI's */
463 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
464 /* RFC4538: Target-dialog */
465 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
466 /* Disable the REFER subscription, RFC 4488 */
467 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
468 /* ietf-sip-history-info-06.txt */
469 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
470 /* ietf-sip-resource-priority-10.txt */
471 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
475 /*! \brief SIP Methods we support */
476 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
478 /*! \brief SIP Extensions we support */
479 #define SUPPORTED_EXTENSIONS "replaces"
481 /*! \brief Standard SIP port from RFC 3261. DO NOT CHANGE THIS */
482 #define STANDARD_SIP_PORT 5060
483 /* Note: in many SIP headers, absence of a port number implies port 5060,
484 * and this is why we cannot change the above constant.
485 * There is a limited number of places in asterisk where we could,
486 * in principle, use a different "default" port number, but
487 * we do not support this feature at the moment.
490 /* Default values, set and reset in reload_config before reading configuration */
491 /* These are default values in the source. There are other recommended values in the
492 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
493 yet encouraging new behaviour on new installations
495 #define DEFAULT_CONTEXT "default"
496 #define DEFAULT_MOHINTERPRET "default"
497 #define DEFAULT_MOHSUGGEST ""
498 #define DEFAULT_VMEXTEN "asterisk"
499 #define DEFAULT_CALLERID "asterisk"
500 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
501 #define DEFAULT_MWITIME 10
502 #define DEFAULT_ALLOWGUEST TRUE
503 #define DEFAULT_SRVLOOKUP TRUE /*!< Recommended setting is ON */
504 #define DEFAULT_COMPACTHEADERS FALSE
505 #define DEFAULT_TOS_SIP 0 /*!< Call signalling packets should be marked as DSCP CS3, but the default is 0 to be compatible with previous versions. */
506 #define DEFAULT_TOS_AUDIO 0 /*!< Audio packets should be marked as DSCP EF (Expedited Forwarding), but the default is 0 to be compatible with previous versions. */
507 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
508 #define DEFAULT_ALLOW_EXT_DOM TRUE
509 #define DEFAULT_REALM "asterisk"
510 #define DEFAULT_NOTIFYRINGING TRUE
511 #define DEFAULT_PEDANTIC FALSE
512 #define DEFAULT_AUTOCREATEPEER FALSE
513 #define DEFAULT_QUALIFY FALSE
514 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
515 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
516 #ifndef DEFAULT_USERAGENT
517 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
518 #endif
521 /* Default setttings are used as a channel setting and as a default when
522 configuring devices */
523 static char default_context[AST_MAX_CONTEXT];
524 static char default_subscribecontext[AST_MAX_CONTEXT];
525 static char default_language[MAX_LANGUAGE];
526 static char default_callerid[AST_MAX_EXTENSION];
527 static char default_fromdomain[AST_MAX_EXTENSION];
528 static char default_notifymime[AST_MAX_EXTENSION];
529 static int default_qualify; /*!< Default Qualify= setting */
530 static char default_vmexten[AST_MAX_EXTENSION];
531 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
532 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
533 * a bridged channel on hold */
534 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
535 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
537 /* Global settings only apply to the channel */
538 static int global_directrtpsetup; /*!< Enable support for Direct RTP setup (no re-invites) */
539 static int global_limitonpeers; /*!< Match call limit on peers only */
540 static int global_rtautoclear;
541 static int global_notifyringing; /*!< Send notifications on ringing */
542 static int global_notifyhold; /*!< Send notifications on hold */
543 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
544 static int srvlookup; /*!< SRV Lookup on or off. Default is on */
545 static int pedanticsipchecking; /*!< Extra checking ? Default off */
546 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
547 static int global_relaxdtmf; /*!< Relax DTMF */
548 static int global_rtptimeout; /*!< Time out call if no RTP */
549 static int global_rtpholdtimeout;
550 static int global_rtpkeepalive; /*!< Send RTP keepalives */
551 static int global_reg_timeout;
552 static int global_regattempts_max; /*!< Registration attempts before giving up */
553 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
554 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
555 the global setting is in globals_flags[1] */
556 static int global_mwitime; /*!< Time between MWI checks for peers */
557 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
558 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
559 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
560 static int compactheaders; /*!< send compact sip headers */
561 static int recordhistory; /*!< Record SIP history. Off by default */
562 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
563 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
564 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
565 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
566 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
567 static int global_callevents; /*!< Whether we send manager events or not */
568 static int global_t1min; /*!< T1 roundtrip time minimum */
569 static int global_autoframing; /*!< Turn autoframing on or off. */
570 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
572 static int global_matchexterniplocally; /*!< Match externip/externhost setting against localnet setting */
574 /*! \brief Codecs that we support by default: */
575 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
577 /* Object counters */
578 static int suserobjs = 0; /*!< Static users */
579 static int ruserobjs = 0; /*!< Realtime users */
580 static int speerobjs = 0; /*!< Statis peers */
581 static int rpeerobjs = 0; /*!< Realtime peers */
582 static int apeerobjs = 0; /*!< Autocreated peer objects */
583 static int regobjs = 0; /*!< Registry objects */
585 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
587 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
588 AST_MUTEX_DEFINE_STATIC(iflock);
590 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
591 when it's doing something critical. */
592 AST_MUTEX_DEFINE_STATIC(netlock);
594 AST_MUTEX_DEFINE_STATIC(monlock);
596 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
598 /*! \brief This is the thread for the monitor which checks for input on the channels
599 which are not currently in use. */
600 static pthread_t monitor_thread = AST_PTHREADT_NULL;
602 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
603 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
605 static struct sched_context *sched; /*!< The scheduling context */
606 static struct io_context *io; /*!< The IO context */
607 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
609 #define DEC_CALL_LIMIT 0
610 #define INC_CALL_LIMIT 1
611 #define DEC_CALL_RINGING 2
612 #define INC_CALL_RINGING 3
614 /*! \brief sip_request: The data grabbed from the UDP socket */
615 struct sip_request {
616 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
617 char *rlPart2; /*!< The Request URI or Response Status */
618 int len; /*!< Length */
619 int headers; /*!< # of SIP Headers */
620 int method; /*!< Method of this request */
621 int lines; /*!< Body Content */
622 unsigned int flags; /*!< SIP_PKT Flags for this packet */
623 char *header[SIP_MAX_HEADERS];
624 char *line[SIP_MAX_LINES];
625 char data[SIP_MAX_PACKET];
626 unsigned int sdp_start; /*!< the line number where the SDP begins */
627 unsigned int sdp_end; /*!< the line number where the SDP ends */
631 * A sip packet is stored into the data[] buffer, with the header followed
632 * by an empty line and the body of the message.
633 * On outgoing packets, data is accumulated in data[] with len reflecting
634 * the next available byte, headers and lines count the number of lines
635 * in both parts. There are no '\0' in data[0..len-1].
637 * On received packet, the input read from the socket is copied into data[],
638 * len is set and the string is NUL-terminated. Then a parser fills up
639 * the other fields -header[] and line[] to point to the lines of the
640 * message, rlPart1 and rlPart2 parse the first lnie as below:
642 * Requests have in the first line METHOD URI SIP/2.0
643 * rlPart1 = method; rlPart2 = uri;
644 * Responses have in the first line SIP/2.0 code description
645 * rlPart1 = SIP/2.0; rlPart2 = code + description;
649 /*! \brief structure used in transfers */
650 struct sip_dual {
651 struct ast_channel *chan1; /*!< First channel involved */
652 struct ast_channel *chan2; /*!< Second channel involved */
653 struct sip_request req; /*!< Request that caused the transfer (REFER) */
654 int seqno; /*!< Sequence number */
657 struct sip_pkt;
659 /*! \brief Parameters to the transmit_invite function */
660 struct sip_invite_param {
661 const char *distinctive_ring; /*!< Distinctive ring header */
662 int addsipheaders; /*!< Add extra SIP headers */
663 const char *uri_options; /*!< URI options to add to the URI */
664 const char *vxml_url; /*!< VXML url for Cisco phones */
665 char *auth; /*!< Authentication */
666 char *authheader; /*!< Auth header */
667 enum sip_auth_type auth_type; /*!< Authentication type */
668 const char *replaces; /*!< Replaces header for call transfers */
669 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
672 /*! \brief Structure to save routing information for a SIP session */
673 struct sip_route {
674 struct sip_route *next;
675 char hop[0];
678 /*! \brief Modes for SIP domain handling in the PBX */
679 enum domain_mode {
680 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
681 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
684 /*! \brief Domain data structure.
685 \note In the future, we will connect this to a configuration tree specific
686 for this domain
688 struct domain {
689 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
690 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
691 enum domain_mode mode; /*!< How did we find this domain? */
692 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
695 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
698 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
699 struct sip_history {
700 AST_LIST_ENTRY(sip_history) list;
701 char event[0]; /* actually more, depending on needs */
704 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
706 /*! \brief sip_auth: Credentials for authentication to other SIP services */
707 struct sip_auth {
708 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
709 char username[256]; /*!< Username */
710 char secret[256]; /*!< Secret */
711 char md5secret[256]; /*!< MD5Secret */
712 struct sip_auth *next; /*!< Next auth structure in list */
715 /*--- Various flags for the flags field in the pvt structure */
716 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
717 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed by the monitor thread */
718 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
719 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
720 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
721 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
722 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
723 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
724 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
725 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
726 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
727 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
728 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
729 #define SIP_OUTGOING (1 << 13) /*!< Direction of the last transaction in this dialog */
730 #define SIP_FREE_BIT (1 << 14) /*!< ---- */
731 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 15) /*!< Do not hangup at first ast_hangup */
732 #define SIP_DTMF (3 << 16) /*!< DTMF Support: four settings, uses two bits */
733 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DTMF Support: RTP DTMF - "rfc2833" */
734 #define SIP_DTMF_INBAND (1 << 16) /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
735 #define SIP_DTMF_INFO (2 << 16) /*!< DTMF Support: SIP Info messages - "info" */
736 #define SIP_DTMF_AUTO (3 << 16) /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
737 /* NAT settings */
738 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
739 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
740 #define SIP_NAT_RFC3581 (1 << 18) /*!< NAT RFC3581 */
741 #define SIP_NAT_ROUTE (2 << 18) /*!< NAT Only ROUTE */
742 #define SIP_NAT_ALWAYS (3 << 18) /*!< NAT Both ROUTE and RFC3581 */
743 /* re-INVITE related settings */
744 #define SIP_REINVITE (7 << 20) /*!< three bits used */
745 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
746 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< allow media reinvite when new peer is behind NAT */
747 #define SIP_REINVITE_UPDATE (4 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
748 /* "insecure" settings */
749 #define SIP_INSECURE_PORT (1 << 23) /*!< don't require matching port for incoming requests */
750 #define SIP_INSECURE_INVITE (1 << 24) /*!< don't require authentication for incoming INVITEs */
751 /* Sending PROGRESS in-band settings */
752 #define SIP_PROG_INBAND (3 << 25) /*!< three settings, uses two bits */
753 #define SIP_PROG_INBAND_NEVER (0 << 25)
754 #define SIP_PROG_INBAND_NO (1 << 25)
755 #define SIP_PROG_INBAND_YES (2 << 25)
756 #define SIP_NO_HISTORY (1 << 27) /*!< Suppress recording request/response history */
757 #define SIP_CALL_LIMIT (1 << 28) /*!< Call limit enforced for this call */
758 #define SIP_SENDRPID (1 << 29) /*!< Remote Party-ID Support */
759 #define SIP_INC_COUNT (1 << 30) /*!< Did this connection increment the counter of in-use calls? */
760 #define SIP_G726_NONSTANDARD (1 << 31) /*!< Use non-standard packing for G726-32 data */
762 #define SIP_FLAGS_TO_COPY \
763 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
764 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
765 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
767 /*--- a new page of flags (for flags[1] */
768 /* realtime flags */
769 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
770 #define SIP_PAGE2_RTUPDATE (1 << 1)
771 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
772 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
773 #define SIP_PAGE2_RTSAVE_SYSNAME (1 << 5)
774 /* Space for addition of other realtime flags in the future */
775 #define SIP_PAGE2_STATECHANGEQUEUE (1 << 9) /*!< D: Unsent state pending change exists */
776 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 10)
777 #define SIP_PAGE2_DEBUG (3 << 11)
778 #define SIP_PAGE2_DEBUG_CONFIG (1 << 11)
779 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 12)
780 #define SIP_PAGE2_DYNAMIC (1 << 13) /*!< Dynamic Peers register with Asterisk */
781 #define SIP_PAGE2_SELFDESTRUCT (1 << 14) /*!< Automatic peers need to destruct themselves */
782 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15)
783 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< Allow subscriptions from this peer? */
784 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< Allow overlap dialing ? */
785 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< Only issue MWI notification if subscribed to */
786 #define SIP_PAGE2_INC_RINGING (1 << 19) /*!< Did this connection increment the counter of in-use calls? */
787 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< T38 Fax Passthrough Support */
788 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< 20: T38 Fax Passthrough Support */
789 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< 21: T38 Fax Passthrough Support (not implemented) */
790 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< 22: T38 Fax Passthrough Support (not implemented) */
791 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< Call states */
792 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23) /*!< 23: Active hold */
793 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23) /*!< 23: One directional hold */
794 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23) /*!< 23: Inactive hold */
795 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25) /*!< 25: ???? */
796 #define SIP_PAGE2_BUGGY_MWI (1 << 26) /*!< 26: Buggy CISCO MWI fix */
797 #define SIP_PAGE2_OUTGOING_CALL (1 << 27) /*!< 27: Is this an outgoing call? */
798 #define SIP_PAGE2_UDPTL_DESTINATION (1 << 28) /*!< 28: Use source IP of RTP as destination if NAT is enabled */
799 #define SIP_PAGE2_DIALOG_ESTABLISHED (1 << 29) /*!< 29: Has a dialog been established? */
801 #define SIP_PAGE2_FLAGS_TO_COPY \
802 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
803 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_UDPTL_DESTINATION)
805 /* SIP packet flags */
806 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
807 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
808 #define SIP_PKT_IGNORE (1 << 2) /*!< This is a re-transmit, ignore it */
809 #define SIP_PKT_IGNORE_RESP (1 << 3) /*!< Resp ignore - ??? */
810 #define SIP_PKT_IGNORE_REQ (1 << 4) /*!< Req ignore - ??? */
812 /* T.38 set of flags */
813 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
814 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
815 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
816 /* Rate management */
817 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
818 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
819 /* UDP Error correction */
820 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
821 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
822 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
823 /* T38 Spec version */
824 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
825 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
826 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
827 /* Maximum Fax Rate */
828 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
829 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
830 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
831 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
832 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
833 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
835 /*!< This is default: NO MMR and JBIG trancoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
836 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
838 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
839 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
840 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
842 /*! \brief T38 States for a call */
843 enum t38state {
844 T38_DISABLED = 0, /*!< Not enabled */
845 T38_LOCAL_DIRECT, /*!< Offered from local */
846 T38_LOCAL_REINVITE, /*!< Offered from local - REINVITE */
847 T38_PEER_DIRECT, /*!< Offered from peer */
848 T38_PEER_REINVITE, /*!< Offered from peer - REINVITE */
849 T38_ENABLED /*!< Negotiated (enabled) */
852 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
853 struct t38properties {
854 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
855 int capability; /*!< Our T38 capability */
856 int peercapability; /*!< Peers T38 capability */
857 int jointcapability; /*!< Supported T38 capability at both ends */
858 enum t38state state; /*!< T.38 state */
861 /*! \brief Parameters to know status of transfer */
862 enum referstatus {
863 REFER_IDLE, /*!< No REFER is in progress */
864 REFER_SENT, /*!< Sent REFER to transferee */
865 REFER_RECEIVED, /*!< Received REFER from transferer */
866 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING */
867 REFER_ACCEPTED, /*!< Accepted by transferee */
868 REFER_RINGING, /*!< Target Ringing */
869 REFER_200OK, /*!< Answered by transfer target */
870 REFER_FAILED, /*!< REFER declined - go on */
871 REFER_NOAUTH /*!< We had no auth for REFER */
874 static const struct c_referstatusstring {
875 enum referstatus status;
876 char *text;
877 } referstatusstrings[] = {
878 { REFER_IDLE, "<none>" },
879 { REFER_SENT, "Request sent" },
880 { REFER_RECEIVED, "Request received" },
881 { REFER_ACCEPTED, "Accepted" },
882 { REFER_RINGING, "Target ringing" },
883 { REFER_200OK, "Done" },
884 { REFER_FAILED, "Failed" },
885 { REFER_NOAUTH, "Failed - auth failure" }
888 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed */
889 /* OEJ: Should be moved to string fields */
890 struct sip_refer {
891 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
892 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
893 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
894 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
895 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
896 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
897 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
898 char replaces_callid[SIPBUFSIZE]; /*!< Replace info: callid */
899 char replaces_callid_totag[SIPBUFSIZE/2]; /*!< Replace info: to-tag */
900 char replaces_callid_fromtag[SIPBUFSIZE/2]; /*!< Replace info: from-tag */
901 struct sip_pvt *refer_call; /*!< Call we are referring */
902 int attendedtransfer; /*!< Attended or blind transfer? */
903 int localtransfer; /*!< Transfer to local domain? */
904 enum referstatus status; /*!< REFER status */
907 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
908 static struct sip_pvt {
909 ast_mutex_t lock; /*!< Dialog private lock */
910 int method; /*!< SIP method that opened this dialog */
911 enum invitestates invitestate; /*!< The state of the INVITE transaction only */
912 AST_DECLARE_STRING_FIELDS(
913 AST_STRING_FIELD(callid); /*!< Global CallID */
914 AST_STRING_FIELD(randdata); /*!< Random data */
915 AST_STRING_FIELD(accountcode); /*!< Account code */
916 AST_STRING_FIELD(realm); /*!< Authorization realm */
917 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
918 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
919 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
920 AST_STRING_FIELD(domain); /*!< Authorization domain */
921 AST_STRING_FIELD(from); /*!< The From: header */
922 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
923 AST_STRING_FIELD(exten); /*!< Extension where to start */
924 AST_STRING_FIELD(context); /*!< Context for this call */
925 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
926 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
927 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
928 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
929 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
930 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
931 AST_STRING_FIELD(language); /*!< Default language for this call */
932 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
933 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
934 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
935 AST_STRING_FIELD(theirtag); /*!< Their tag */
936 AST_STRING_FIELD(username); /*!< [user] name */
937 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
938 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
939 AST_STRING_FIELD(uri); /*!< Original requested URI */
940 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
941 AST_STRING_FIELD(peersecret); /*!< Password */
942 AST_STRING_FIELD(peermd5secret);
943 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
944 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
945 AST_STRING_FIELD(via); /*!< Via: header */
946 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
947 AST_STRING_FIELD(our_contact); /*!< Our contact header */
948 AST_STRING_FIELD(rpid); /*!< Our RPID header */
949 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
951 unsigned int ocseq; /*!< Current outgoing seqno */
952 unsigned int icseq; /*!< Current incoming seqno */
953 ast_group_t callgroup; /*!< Call group */
954 ast_group_t pickupgroup; /*!< Pickup group */
955 int lastinvite; /*!< Last Cseq of invite */
956 int lastnoninvite; /*!< Last Cseq of non-invite */
957 struct ast_flags flags[2]; /*!< SIP_ flags */
958 int timer_t1; /*!< SIP timer T1, ms rtt */
959 unsigned int sipoptions; /*!< Supported SIP options on the other end */
960 struct ast_codec_pref prefs; /*!< codec prefs */
961 int capability; /*!< Special capability (codec) */
962 int jointcapability; /*!< Supported capability at both ends (codecs) */
963 int peercapability; /*!< Supported peer capability */
964 int prefcodec; /*!< Preferred codec (outbound only) */
965 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
966 int jointnoncodeccapability; /*!< Joint Non codec capability */
967 int redircodecs; /*!< Redirect codecs */
968 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
969 struct t38properties t38; /*!< T38 settings */
970 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
971 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
972 int callingpres; /*!< Calling presentation */
973 int authtries; /*!< Times we've tried to authenticate */
974 int expiry; /*!< How long we take to expire */
975 long branch; /*!< The branch identifier of this session */
976 char tag[11]; /*!< Our tag for this session */
977 int sessionid; /*!< SDP Session ID */
978 int sessionversion; /*!< SDP Session Version */
979 struct sockaddr_in sa; /*!< Our peer */
980 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
981 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
982 time_t lastrtprx; /*!< Last RTP received */
983 time_t lastrtptx; /*!< Last RTP sent */
984 int rtptimeout; /*!< RTP timeout time */
985 struct sockaddr_in recv; /*!< Received as */
986 struct in_addr ourip; /*!< Our IP */
987 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
988 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
989 int route_persistant; /*!< Is this the "real" route? */
990 struct sip_auth *peerauth; /*!< Realm authentication */
991 int noncecount; /*!< Nonce-count */
992 char lastmsg[256]; /*!< Last Message sent/received */
993 int amaflags; /*!< AMA Flags */
994 int pendinginvite; /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
995 struct sip_request initreq; /*!< Request that opened the latest transaction
996 within this SIP dialog */
998 int maxtime; /*!< Max time for first response */
999 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
1000 int waitid; /*!< Wait ID for scheduler after 491 or other delays */
1001 int autokillid; /*!< Auto-kill ID (scheduler) */
1002 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
1003 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
1004 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
1005 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
1006 int laststate; /*!< SUBSCRIBE: Last known extension state */
1007 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
1009 struct ast_dsp *vad; /*!< Voice Activation Detection dsp */
1011 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
1012 Used in peerpoke, mwi subscriptions */
1013 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
1014 struct ast_rtp *rtp; /*!< RTP Session */
1015 struct ast_rtp *vrtp; /*!< Video RTP session */
1016 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
1017 struct sip_history_head *history; /*!< History of this SIP dialog */
1018 size_t history_entries; /*!< Number of entires in the history */
1019 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1020 struct sip_pvt *next; /*!< Next dialog in chain */
1021 struct sip_invite_param *options; /*!< Options for INVITE */
1022 int autoframing;
1023 } *iflist = NULL;
1025 /*! Max entires in the history list for a sip_pvt */
1026 #define MAX_HISTORY_ENTRIES 50
1028 #define FLAG_RESPONSE (1 << 0)
1029 #define FLAG_FATAL (1 << 1)
1031 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */
1032 struct sip_pkt {
1033 struct sip_pkt *next; /*!< Next packet in linked list */
1034 int retrans; /*!< Retransmission number */
1035 int method; /*!< SIP method for this packet */
1036 int seqno; /*!< Sequence number */
1037 unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */
1038 struct sip_pvt *owner; /*!< Owner AST call */
1039 int retransid; /*!< Retransmission ID */
1040 int timer_a; /*!< SIP timer A, retransmission timer */
1041 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
1042 int packetlen; /*!< Length of packet */
1043 char data[0];
1046 /*! \brief Structure for SIP user data. User's place calls to us */
1047 struct sip_user {
1048 /* Users who can access various contexts */
1049 ASTOBJ_COMPONENTS(struct sip_user);
1050 char secret[80]; /*!< Password */
1051 char md5secret[80]; /*!< Password in md5 */
1052 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1053 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
1054 char cid_num[80]; /*!< Caller ID num */
1055 char cid_name[80]; /*!< Caller ID name */
1056 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
1057 char language[MAX_LANGUAGE]; /*!< Default language for this user */
1058 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1059 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1060 char useragent[256]; /*!< User agent in SIP request */
1061 struct ast_codec_pref prefs; /*!< codec prefs */
1062 ast_group_t callgroup; /*!< Call group */
1063 ast_group_t pickupgroup; /*!< Pickup Group */
1064 unsigned int sipoptions; /*!< Supported SIP options */
1065 struct ast_flags flags[2]; /*!< SIP_ flags */
1066 int amaflags; /*!< AMA flags for billing */
1067 int callingpres; /*!< Calling id presentation */
1068 int capability; /*!< Codec capability */
1069 int inUse; /*!< Number of calls in use */
1070 int call_limit; /*!< Limit of concurrent calls */
1071 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1072 struct ast_ha *ha; /*!< ACL setting */
1073 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1074 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1075 int autoframing;
1078 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1079 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1080 struct sip_peer {
1081 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
1082 /*!< peer->name is the unique name of this object */
1083 char secret[80]; /*!< Password */
1084 char md5secret[80]; /*!< Password in MD5 */
1085 struct sip_auth *auth; /*!< Realm authentication list */
1086 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1087 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1088 char username[80]; /*!< Temporary username until registration */
1089 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1090 int amaflags; /*!< AMA Flags (for billing) */
1091 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1092 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1093 char fromuser[80]; /*!< From: user when calling this peer */
1094 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1095 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1096 char cid_num[80]; /*!< Caller ID num */
1097 char cid_name[80]; /*!< Caller ID name */
1098 int callingpres; /*!< Calling id presentation */
1099 int inUse; /*!< Number of calls in use */
1100 int inRinging; /*!< Number of calls ringing */
1101 int onHold; /*!< Peer has someone on hold */
1102 int call_limit; /*!< Limit of concurrent calls */
1103 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1104 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1105 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
1106 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1107 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1108 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1109 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1110 struct ast_codec_pref prefs; /*!< codec prefs */
1111 int lastmsgssent;
1112 time_t lastmsgcheck; /*!< Last time we checked for MWI */
1113 unsigned int sipoptions; /*!< Supported SIP options */
1114 struct ast_flags flags[2]; /*!< SIP_ flags */
1115 int expire; /*!< When to expire this peer registration */
1116 int capability; /*!< Codec capability */
1117 int rtptimeout; /*!< RTP timeout */
1118 int rtpholdtimeout; /*!< RTP Hold Timeout */
1119 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1120 ast_group_t callgroup; /*!< Call group */
1121 ast_group_t pickupgroup; /*!< Pickup group */
1122 struct sockaddr_in addr; /*!< IP address of peer */
1123 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1125 /* Qualification */
1126 struct sip_pvt *call; /*!< Call pointer */
1127 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1128 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1129 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1130 struct timeval ps; /*!< Ping send time */
1132 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1133 struct ast_ha *ha; /*!< Access control list */
1134 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1135 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1136 int lastmsg;
1137 int autoframing;
1142 /*! \brief Registrations with other SIP proxies */
1143 struct sip_registry {
1144 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1145 AST_DECLARE_STRING_FIELDS(
1146 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1147 AST_STRING_FIELD(realm); /*!< Authorization realm */
1148 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1149 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1150 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1151 AST_STRING_FIELD(domain); /*!< Authorization domain */
1152 AST_STRING_FIELD(username); /*!< Who we are registering as */
1153 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1154 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1155 AST_STRING_FIELD(secret); /*!< Password in clear text */
1156 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1157 AST_STRING_FIELD(contact); /*!< Contact extension */
1158 AST_STRING_FIELD(random);
1160 int portno; /*!< Optional port override */
1161 int expire; /*!< Sched ID of expiration */
1162 int regattempts; /*!< Number of attempts (since the last success) */
1163 int timeout; /*!< sched id of sip_reg_timeout */
1164 int refresh; /*!< How often to refresh */
1165 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1166 enum sipregistrystate regstate; /*!< Registration state (see above) */
1167 time_t regtime; /*!< Last succesful registration time */
1168 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1169 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1170 struct sockaddr_in us; /*!< Who the server thinks we are */
1171 int noncecount; /*!< Nonce-count */
1172 char lastmsg[256]; /*!< Last Message sent/received */
1175 /* --- Linked lists of various objects --------*/
1177 /*! \brief The user list: Users and friends */
1178 static struct ast_user_list {
1179 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1180 } userl;
1182 /*! \brief The peer list: Peers and Friends */
1183 static struct ast_peer_list {
1184 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1185 } peerl;
1187 /*! \brief The register list: Other SIP proxys we register with and place calls to */
1188 static struct ast_register_list {
1189 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1190 int recheck;
1191 } regl;
1193 static void temp_pvt_cleanup(void *);
1195 /*! \brief A per-thread temporary pvt structure */
1196 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1198 #ifdef LOW_MEMORY
1199 static void ts_ast_rtp_destroy(void *);
1201 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, ts_audio_rtp_init, ts_ast_rtp_destroy);
1202 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, ts_video_rtp_init, ts_ast_rtp_destroy);
1203 #endif
1205 /*! \todo Move the sip_auth list to AST_LIST */
1206 static struct sip_auth *authl = NULL; /*!< Authentication list for realm authentication */
1209 /* --- Sockets and networking --------------*/
1210 static int sipsock = -1; /*!< Main socket for SIP network communication */
1211 static struct sockaddr_in bindaddr = { 0, }; /*!< The address we bind to */
1212 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1213 static char externhost[MAXHOSTNAMELEN]; /*!< External host name (possibly with dynamic DNS and DHCP */
1214 static time_t externexpire = 0; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1215 static int externrefresh = 10;
1216 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1217 static struct in_addr __ourip;
1218 static struct sockaddr_in outboundproxyip;
1219 static int ourport;
1220 static struct sockaddr_in debugaddr;
1222 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1224 /*---------------------------- Forward declarations of functions in chan_sip.c */
1225 /*! \note This is added to help splitting up chan_sip.c into several files
1226 in coming releases */
1228 /*--- PBX interface functions */
1229 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1230 static int sip_devicestate(void *data);
1231 static int sip_sendtext(struct ast_channel *ast, const char *text);
1232 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1233 static int sip_hangup(struct ast_channel *ast);
1234 static int sip_answer(struct ast_channel *ast);
1235 static struct ast_frame *sip_read(struct ast_channel *ast);
1236 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1237 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1238 static int sip_transfer(struct ast_channel *ast, const char *dest);
1239 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1240 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1241 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1243 /*--- Transmitting responses and requests */
1244 static int sipsock_read(int *id, int fd, short events, void *ignore);
1245 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
1246 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
1247 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1248 static int retrans_pkt(const void *data);
1249 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
1250 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);
1251 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1252 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1253 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1254 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1255 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1256 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);
1257 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1258 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1259 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1260 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1261 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1262 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
1263 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1264 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1265 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1266 static int transmit_refer(struct sip_pvt *p, const char *dest);
1267 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1268 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1269 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1270 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1271 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1272 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1273 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1274 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1275 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1276 static int does_peer_need_mwi(struct sip_peer *peer);
1278 /*--- Dialog management */
1279 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1280 int useglobal_nat, const int intended_method);
1281 static int __sip_autodestruct(const void *data);
1282 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1283 static int sip_cancel_destroy(struct sip_pvt *p);
1284 static void sip_destroy(struct sip_pvt *p);
1285 static int __sip_destroy(struct sip_pvt *p, int lockowner);
1286 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1287 static void __sip_pretend_ack(struct sip_pvt *p);
1288 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1289 static int auto_congest(const void *nothing);
1290 static int update_call_counter(struct sip_pvt *fup, int event);
1291 static int hangup_sip2cause(int cause);
1292 static const char *hangup_cause2sip(int cause);
1293 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1294 static void free_old_route(struct sip_route *route);
1295 static void list_route(struct sip_route *route);
1296 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1297 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1298 struct sip_request *req, char *uri);
1299 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1300 static void check_pendings(struct sip_pvt *p);
1301 static void *sip_park_thread(void *stuff);
1302 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1303 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1305 /*--- Codec handling / SDP */
1306 static void try_suggested_sip_codec(struct sip_pvt *p);
1307 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1308 static const char *get_sdp(struct sip_request *req, const char *name);
1309 static int find_sdp(struct sip_request *req);
1310 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
1311 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1312 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1313 int debug, int *min_packet_size);
1314 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1315 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1316 int debug);
1317 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p);
1318 static void stop_media_flows(struct sip_pvt *p);
1320 /*--- Authentication stuff */
1321 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1322 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1323 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1324 const char *secret, const char *md5secret, int sipmethod,
1325 char *uri, enum xmittype reliable, int ignore);
1326 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1327 int sipmethod, char *uri, enum xmittype reliable,
1328 struct sockaddr_in *sin, struct sip_peer **authpeer);
1329 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1331 /*--- Domain handling */
1332 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1333 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1334 static void clear_sip_domains(void);
1336 /*--- SIP realm authentication */
1337 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
1338 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1339 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1341 /*--- Misc functions */
1342 static int sip_do_reload(enum channelreloadreason reason);
1343 static int reload_config(enum channelreloadreason reason);
1344 static int expire_register(const void *data);
1345 static void *do_monitor(void *data);
1346 static int restart_monitor(void);
1347 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1348 static int sip_addrcmp(char *name, struct sockaddr_in *sin); /* Support for peer matching */
1349 static int sip_refer_allocate(struct sip_pvt *p);
1350 static void ast_quiet_chan(struct ast_channel *chan);
1351 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1353 /*--- Device monitoring and Device/extension state handling */
1354 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1355 static int sip_devicestate(void *data);
1356 static int sip_poke_noanswer(const void *data);
1357 static int sip_poke_peer(struct sip_peer *peer);
1358 static void sip_poke_all_peers(void);
1359 static void sip_peer_hold(struct sip_pvt *p, int hold);
1361 /*--- Applications, functions, CLI and manager command helpers */
1362 static const char *sip_nat_mode(const struct sip_pvt *p);
1363 static int sip_show_inuse(int fd, int argc, char *argv[]);
1364 static char *transfermode2str(enum transfermodes mode) attribute_const;
1365 static char *nat2str(int nat) attribute_const;
1366 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1367 static int sip_show_users(int fd, int argc, char *argv[]);
1368 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1369 static int sip_show_peers(int fd, int argc, char *argv[]);
1370 static int sip_show_objects(int fd, int argc, char *argv[]);
1371 static void print_group(int fd, ast_group_t group, int crlf);
1372 static const char *dtmfmode2str(int mode) attribute_const;
1373 static const char *insecure2str(int port, int invite) attribute_const;
1374 static void cleanup_stale_contexts(char *new, char *old);
1375 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1376 static const char *domain_mode_to_text(const enum domain_mode mode);
1377 static int sip_show_domains(int fd, int argc, char *argv[]);
1378 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1379 static int sip_show_peer(int fd, int argc, char *argv[]);
1380 static int sip_show_user(int fd, int argc, char *argv[]);
1381 static int sip_show_registry(int fd, int argc, char *argv[]);
1382 static int sip_show_settings(int fd, int argc, char *argv[]);
1383 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1384 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1385 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1386 static int sip_show_channels(int fd, int argc, char *argv[]);
1387 static int sip_show_subscriptions(int fd, int argc, char *argv[]);
1388 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1389 static char *complete_sipch(const char *line, const char *word, int pos, int state);
1390 static char *complete_sip_peer(const char *word, int state, int flags2);
1391 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1392 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state);
1393 static char *complete_sip_user(const char *word, int state, int flags2);
1394 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
1395 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1396 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state);
1397 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state);
1398 static int sip_show_channel(int fd, int argc, char *argv[]);
1399 static int sip_show_history(int fd, int argc, char *argv[]);
1400 static int sip_do_debug_ip(int fd, int argc, char *argv[]);
1401 static int sip_do_debug_peer(int fd, int argc, char *argv[]);
1402 static int sip_do_debug(int fd, int argc, char *argv[]);
1403 static int sip_no_debug(int fd, int argc, char *argv[]);
1404 static int sip_notify(int fd, int argc, char *argv[]);
1405 static int sip_do_history(int fd, int argc, char *argv[]);
1406 static int sip_no_history(int fd, int argc, char *argv[]);
1407 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
1408 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1409 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1410 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1411 static int sip_dtmfmode(struct ast_channel *chan, void *data);
1412 static int sip_addheader(struct ast_channel *chan, void *data);
1413 static int sip_do_reload(enum channelreloadreason reason);
1414 static int sip_reload(int fd, int argc, char *argv[]);
1415 static int acf_channel_read(struct ast_channel *chan, char *funcname, char *preparse, char *buf, size_t buflen);
1417 /*--- Debugging
1418 Functions for enabling debug per IP or fully, or enabling history logging for
1419 a SIP dialog
1421 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1422 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1423 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1424 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1425 static void sip_dump_history(struct sip_pvt *dialog);
1427 /*--- Device object handling */
1428 static struct sip_peer *temp_peer(const char *name);
1429 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1430 static struct sip_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1431 static int update_call_counter(struct sip_pvt *fup, int event);
1432 static void sip_destroy_peer(struct sip_peer *peer);
1433 static void sip_destroy_user(struct sip_user *user);
1434 static int sip_poke_peer(struct sip_peer *peer);
1435 static int sip_poke_peer_s(const void *data);
1436 static void set_peer_defaults(struct sip_peer *peer);
1437 static struct sip_peer *temp_peer(const char *name);
1438 static void register_peer_exten(struct sip_peer *peer, int onoff);
1439 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int devstate_only);
1440 static struct sip_user *find_user(const char *name, int realtime);
1441 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1442 static int expire_register(const void *data);
1443 static void reg_source_db(struct sip_peer *peer);
1444 static void destroy_association(struct sip_peer *peer);
1445 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1447 /* Realtime device support */
1448 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
1449 static struct sip_user *realtime_user(const char *username);
1450 static void update_peer(struct sip_peer *p, int expiry);
1451 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
1452 static int sip_prune_realtime(int fd, int argc, char *argv[]);
1454 /*--- Internal UA client handling (outbound registrations) */
1455 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
1456 static void sip_registry_destroy(struct sip_registry *reg);
1457 static int sip_register(char *value, int lineno);
1458 static char *regstate2str(enum sipregistrystate regstate) attribute_const;
1459 static int sip_reregister(const void *data);
1460 static int __sip_do_register(struct sip_registry *r);
1461 static int sip_reg_timeout(const void *data);
1462 static void sip_send_all_registers(void);
1464 /*--- Parsing SIP requests and responses */
1465 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1466 static int determine_firstline_parts(struct sip_request *req);
1467 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1468 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1469 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1470 static int find_sip_method(const char *msg);
1471 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1472 static int parse_request(struct sip_request *req);
1473 static const char *get_header(const struct sip_request *req, const char *name);
1474 static char *referstatus2str(enum referstatus rstatus) attribute_pure;
1475 static int method_match(enum sipmethod id, const char *name);
1476 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1477 static char *get_in_brackets(char *tmp);
1478 static const char *find_alias(const char *name, const char *_default);
1479 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1480 static int lws2sws(char *msgbuf, int len);
1481 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1482 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1483 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1484 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1485 static int set_address_from_contact(struct sip_pvt *pvt);
1486 static void check_via(struct sip_pvt *p, const struct sip_request *req);
1487 static char *get_calleridname(const char *input, char *output, size_t outputsize);
1488 static int get_rpid_num(const char *input, char *output, int maxlen);
1489 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
1490 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1491 static int get_msg_text(char *buf, int len, struct sip_request *req);
1492 static void free_old_route(struct sip_route *route);
1493 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1495 /*--- Constructing requests and responses */
1496 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1497 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1498 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1499 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1500 static int init_resp(struct sip_request *resp, const char *msg);
1501 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1502 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1503 static void build_via(struct sip_pvt *p);
1504 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1505 static int create_addr(struct sip_pvt *dialog, const char *opeer);
1506 static char *generate_random_string(char *buf, size_t size);
1507 static void build_callid_pvt(struct sip_pvt *pvt);
1508 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1509 static void make_our_tag(char *tagbuf, size_t len);
1510 static int add_header(struct sip_request *req, const char *var, const char *value);
1511 static int add_header_contentLength(struct sip_request *req, int len);
1512 static int add_line(struct sip_request *req, const char *line);
1513 static int add_text(struct sip_request *req, const char *text);
1514 static int add_digit(struct sip_request *req, char digit, unsigned int duration);
1515 static int add_vidupdate(struct sip_request *req);
1516 static void add_route(struct sip_request *req, struct sip_route *route);
1517 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1518 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1519 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1520 static void set_destination(struct sip_pvt *p, char *uri);
1521 static void append_date(struct sip_request *req);
1522 static void build_contact(struct sip_pvt *p);
1523 static void build_rpid(struct sip_pvt *p);
1525 /*------Request handling functions */
1526 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1527 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);
1528 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock);
1529 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1530 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1531 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1532 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1533 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1534 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1535 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1536 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1537 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1538 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
1540 /*------Response handling functions */
1541 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1542 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1543 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
1544 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
1546 /*----- RTP interface functions */
1547 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
1548 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1549 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1550 static int sip_get_codec(struct ast_channel *chan);
1551 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
1553 /*------ T38 Support --------- */
1554 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite); /*!< T38 negotiation helper function */
1555 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1556 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p);
1557 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1558 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1560 /*! \brief Definition of this channel for PBX channel registration */
1561 static const struct ast_channel_tech sip_tech = {
1562 .type = "SIP",
1563 .description = "Session Initiation Protocol (SIP)",
1564 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1565 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1566 .requester = sip_request_call,
1567 .devicestate = sip_devicestate,
1568 .call = sip_call,
1569 .hangup = sip_hangup,
1570 .answer = sip_answer,
1571 .read = sip_read,
1572 .write = sip_write,
1573 .write_video = sip_write,
1574 .indicate = sip_indicate,
1575 .transfer = sip_transfer,
1576 .fixup = sip_fixup,
1577 .send_digit_begin = sip_senddigit_begin,
1578 .send_digit_end = sip_senddigit_end,
1579 .bridge = ast_rtp_bridge,
1580 .send_text = sip_sendtext,
1581 .func_channel_read = acf_channel_read,
1584 /*! \brief This version of the sip channel tech has no send_digit_begin
1585 * callback. This is for use with channels using SIP INFO DTMF so that
1586 * the core knows that the channel doesn't want DTMF BEGIN frames. */
1587 static const struct ast_channel_tech sip_tech_info = {
1588 .type = "SIP",
1589 .description = "Session Initiation Protocol (SIP)",
1590 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1591 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1592 .requester = sip_request_call,
1593 .devicestate = sip_devicestate,
1594 .call = sip_call,
1595 .hangup = sip_hangup,
1596 .answer = sip_answer,
1597 .read = sip_read,
1598 .write = sip_write,
1599 .write_video = sip_write,
1600 .indicate = sip_indicate,
1601 .transfer = sip_transfer,
1602 .fixup = sip_fixup,
1603 .send_digit_end = sip_senddigit_end,
1604 .bridge = ast_rtp_bridge,
1605 .send_text = sip_sendtext,
1606 .func_channel_read = acf_channel_read,
1609 /**--- some list management macros. **/
1611 #define UNLINK(element, head, prev) do { \
1612 if (prev) \
1613 (prev)->next = (element)->next; \
1614 else \
1615 (head) = (element)->next; \
1616 } while (0)
1618 /*! \brief Interface structure with callbacks used to connect to RTP module */
1619 static struct ast_rtp_protocol sip_rtp = {
1620 type: "SIP",
1621 get_rtp_info: sip_get_rtp_peer,
1622 get_vrtp_info: sip_get_vrtp_peer,
1623 set_rtp_peer: sip_set_rtp_peer,
1624 get_codec: sip_get_codec,
1627 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1628 static struct ast_udptl_protocol sip_udptl = {
1629 type: "SIP",
1630 get_udptl_info: sip_get_udptl_peer,
1631 set_udptl_peer: sip_set_udptl_peer,
1634 /*! \brief Convert transfer status to string */
1635 static char *referstatus2str(enum referstatus rstatus)
1637 int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
1638 int x;
1640 for (x = 0; x < i; x++) {
1641 if (referstatusstrings[x].status == rstatus)
1642 return (char *) referstatusstrings[x].text;
1644 return "";
1647 /*! \brief Initialize the initital request packet in the pvt structure.
1648 This packet is used for creating replies and future requests in
1649 a dialog */
1650 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
1652 if (p->initreq.headers && option_debug) {
1653 ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
1655 /* Use this as the basis */
1656 copy_request(&p->initreq, req);
1657 parse_request(&p->initreq);
1658 if (ast_test_flag(req, SIP_PKT_DEBUG))
1659 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
1662 static void sip_alreadygone(struct sip_pvt *dialog)
1664 if (option_debug > 2)
1665 ast_log(LOG_DEBUG, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
1666 ast_set_flag(&dialog->flags[0], SIP_ALREADYGONE);
1670 /*! \brief returns true if 'name' (with optional trailing whitespace)
1671 * matches the sip method 'id'.
1672 * Strictly speaking, SIP methods are case SENSITIVE, but we do
1673 * a case-insensitive comparison to be more tolerant.
1674 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1676 static int method_match(enum sipmethod id, const char *name)
1678 int len = strlen(sip_methods[id].text);
1679 int l_name = name ? strlen(name) : 0;
1680 /* true if the string is long enough, and ends with whitespace, and matches */
1681 return (l_name >= len && name[len] < 33 &&
1682 !strncasecmp(sip_methods[id].text, name, len));
1685 /*! \brief find_sip_method: Find SIP method from header */
1686 static int find_sip_method(const char *msg)
1688 int i, res = 0;
1690 if (ast_strlen_zero(msg))
1691 return 0;
1692 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
1693 if (method_match(i, msg))
1694 res = sip_methods[i].id;
1696 return res;
1699 /*! \brief Parse supported header in incoming packet */
1700 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
1702 char *next, *sep;
1703 char *temp;
1704 unsigned int profile = 0;
1705 int i, found;
1707 if (ast_strlen_zero(supported) )
1708 return 0;
1709 temp = ast_strdupa(supported);
1711 if (option_debug > 2 && sipdebug)
1712 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1714 for (next = temp; next; next = sep) {
1715 found = FALSE;
1716 if ( (sep = strchr(next, ',')) != NULL)
1717 *sep++ = '\0';
1718 next = ast_skip_blanks(next);
1719 if (option_debug > 2 && sipdebug)
1720 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1721 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
1722 if (!strcasecmp(next, sip_options[i].text)) {
1723 profile |= sip_options[i].id;
1724 found = TRUE;
1725 if (option_debug > 2 && sipdebug)
1726 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1727 break;
1730 if (!found && option_debug > 2 && sipdebug) {
1731 if (!strncasecmp(next, "x-", 2))
1732 ast_log(LOG_DEBUG, "Found private SIP option, not supported: %s\n", next);
1733 else
1734 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1738 if (pvt)
1739 pvt->sipoptions = profile;
1740 return profile;
1743 /*! \brief See if we pass debug IP filter */
1744 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
1746 if (!sipdebug)
1747 return 0;
1748 if (debugaddr.sin_addr.s_addr) {
1749 if (((ntohs(debugaddr.sin_port) != 0)
1750 && (debugaddr.sin_port != addr->sin_port))
1751 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1752 return 0;
1754 return 1;
1757 /*! \brief The real destination address for a write */
1758 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
1760 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
1763 /*! \brief Display SIP nat mode */
1764 static const char *sip_nat_mode(const struct sip_pvt *p)
1766 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
1769 /*! \brief Test PVT for debugging output */
1770 static inline int sip_debug_test_pvt(struct sip_pvt *p)
1772 if (!sipdebug)
1773 return 0;
1774 return sip_debug_test_addr(sip_real_dst(p));
1777 /*! \brief Transmit SIP message */
1778 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1780 int res;
1781 const struct sockaddr_in *dst = sip_real_dst(p);
1782 res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
1784 if (res == -1) {
1785 switch (errno) {
1786 case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
1787 case EHOSTUNREACH: /* Host can't be reached */
1788 case ENETDOWN: /* Inteface down */
1789 case ENETUNREACH: /* Network failure */
1790 case ECONNREFUSED: /* ICMP port unreachable */
1791 res = XMIT_ERROR; /* Don't bother with trying to transmit again */
1794 if (res != len)
1795 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));
1796 return res;
1800 /*! \brief Build a Via header for a request */
1801 static void build_via(struct sip_pvt *p)
1803 /* Work around buggy UNIDEN UIP200 firmware */
1804 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1806 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1807 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1808 ast_inet_ntoa(p->ourip), ourport, p->branch, rport);
1811 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1813 * Using the localaddr structure built up with localnet statements in sip.conf
1814 * apply it to their address to see if we need to substitute our
1815 * externip or can get away with our internal bindaddr
1817 static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1819 struct sockaddr_in theirs, ours;
1821 /* Get our local information */
1822 ast_ouraddrfor(them, us);
1823 theirs.sin_addr = *them;
1824 ours.sin_addr = *us;
1826 if (localaddr && externip.sin_addr.s_addr &&
1827 (ast_apply_ha(localaddr, &theirs)) &&
1828 (!global_matchexterniplocally || !ast_apply_ha(localaddr, &ours))) {
1829 if (externexpire && time(NULL) >= externexpire) {
1830 struct ast_hostent ahp;
1831 struct hostent *hp;
1833 externexpire = time(NULL) + externrefresh;
1834 if ((hp = ast_gethostbyname(externhost, &ahp))) {
1835 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1836 } else
1837 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1839 *us = externip.sin_addr;
1840 if (option_debug) {
1841 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n",
1842 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
1844 } else if (bindaddr.sin_addr.s_addr)
1845 *us = bindaddr.sin_addr;
1846 return AST_SUCCESS;
1849 /*! \brief Append to SIP dialog history
1850 \return Always returns 0 */
1851 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1853 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1854 __attribute__ ((format (printf, 2, 3)));
1856 /*! \brief Append to SIP dialog history with arg list */
1857 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1859 char buf[80], *c = buf; /* max history length */
1860 struct sip_history *hist;
1861 int l;
1863 vsnprintf(buf, sizeof(buf), fmt, ap);
1864 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1865 l = strlen(buf) + 1;
1866 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1867 return;
1868 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1869 free(hist);
1870 return;
1872 memcpy(hist->event, buf, l);
1873 if (p->history_entries == MAX_HISTORY_ENTRIES) {
1874 struct sip_history *oldest;
1875 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
1876 p->history_entries--;
1877 free(oldest);
1879 AST_LIST_INSERT_TAIL(p->history, hist, list);
1880 p->history_entries++;
1883 /*! \brief Append to SIP dialog history with arg list */
1884 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1886 va_list ap;
1888 if (!p)
1889 return;
1891 if (ast_test_flag(&p->flags[0], SIP_NO_HISTORY)
1892 && !recordhistory && !dumphistory) {
1893 return;
1896 va_start(ap, fmt);
1897 append_history_va(p, fmt, ap);
1898 va_end(ap);
1900 return;
1903 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
1904 static int retrans_pkt(const void *data)
1906 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
1907 int reschedule = DEFAULT_RETRANS;
1908 int xmitres = 0;
1910 /* Lock channel PVT */
1911 ast_mutex_lock(&pkt->owner->lock);
1913 if (pkt->retrans < MAX_RETRANS) {
1914 pkt->retrans++;
1915 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
1916 if (sipdebug && option_debug > 3)
1917 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);
1918 } else {
1919 int siptimer_a;
1921 if (sipdebug && option_debug > 3)
1922 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1923 if (!pkt->timer_a)
1924 pkt->timer_a = 2 ;
1925 else
1926 pkt->timer_a = 2 * pkt->timer_a;
1928 /* For non-invites, a maximum of 4 secs */
1929 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
1930 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1931 siptimer_a = 4000;
1933 /* Reschedule re-transmit */
1934 reschedule = siptimer_a;
1935 if (option_debug > 3)
1936 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);
1939 if (sip_debug_test_pvt(pkt->owner)) {
1940 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
1941 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
1942 pkt->retrans, sip_nat_mode(pkt->owner),
1943 ast_inet_ntoa(dst->sin_addr),
1944 ntohs(dst->sin_port), pkt->data);
1947 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1948 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1949 ast_mutex_unlock(&pkt->owner->lock);
1950 if (xmitres == XMIT_ERROR)
1951 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
1952 else
1953 return reschedule;
1955 /* Too many retries */
1956 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
1957 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1958 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n", pkt->owner->callid, pkt->seqno, (ast_test_flag(pkt, FLAG_FATAL)) ? "Critical" : "Non-critical", (ast_test_flag(pkt, FLAG_RESPONSE)) ? "Response" : "Request");
1959 } else if ((pkt->method == SIP_OPTIONS) && sipdebug) {
1960 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
1962 if (xmitres == XMIT_ERROR) {
1963 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission of transaction in call id %s \n", pkt->owner->callid);
1964 append_history(pkt->owner, "XmitErr", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1965 } else
1966 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1968 pkt->retransid = -1;
1970 if (ast_test_flag(pkt, FLAG_FATAL)) {
1971 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
1972 DEADLOCK_AVOIDANCE(&pkt->owner->lock); /* SIP_PVT, not channel */
1975 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
1976 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
1978 if (pkt->owner->owner) {
1979 sip_alreadygone(pkt->owner);
1980 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
1981 ast_queue_hangup(pkt->owner->owner);
1982 ast_channel_unlock(pkt->owner->owner);
1983 } else {
1984 /* If no channel owner, destroy now */
1986 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
1987 if (pkt->method != SIP_OPTIONS) {
1988 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
1989 sip_alreadygone(pkt->owner);
1990 if (option_debug)
1991 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
1996 if (pkt->method == SIP_BYE) {
1997 /* We're not getting answers on SIP BYE's. Tear down the call anyway. */
1998 if (pkt->owner->owner)
1999 ast_channel_unlock(pkt->owner->owner);
2000 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
2001 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
2004 /* In any case, go ahead and remove the packet */
2005 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
2006 if (cur == pkt)
2007 break;
2009 if (cur) {
2010 if (prev)
2011 prev->next = cur->next;
2012 else
2013 pkt->owner->packets = cur->next;
2014 ast_mutex_unlock(&pkt->owner->lock);
2015 free(cur);
2016 pkt = NULL;
2017 } else
2018 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
2019 if (pkt)
2020 ast_mutex_unlock(&pkt->owner->lock);
2021 return 0;
2024 /*! \brief Transmit packet with retransmits
2025 \return 0 on success, -1 on failure to allocate packet
2027 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
2029 struct sip_pkt *pkt;
2030 int siptimer_a = DEFAULT_RETRANS;
2031 int xmitres = 0;
2033 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
2034 return AST_FAILURE;
2035 memcpy(pkt->data, data, len);
2036 pkt->method = sipmethod;
2037 pkt->packetlen = len;
2038 pkt->next = p->packets;
2039 pkt->owner = p;
2040 pkt->seqno = seqno;
2041 if (resp)
2042 ast_set_flag(pkt, FLAG_RESPONSE);
2043 pkt->data[len] = '\0';
2044 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
2045 pkt->retransid = -1;
2046 if (fatal)
2047 ast_set_flag(pkt, FLAG_FATAL);
2048 if (pkt->timer_t1)
2049 siptimer_a = pkt->timer_t1 * 2;
2051 if (option_debug > 3 && sipdebug)
2052 ast_log(LOG_DEBUG, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
2053 pkt->retransid = -1;
2054 pkt->next = p->packets;
2055 p->packets = pkt;
2056 if (sipmethod == SIP_INVITE) {
2057 /* Note this is a pending invite */
2058 p->pendinginvite = seqno;
2061 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
2063 if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
2064 append_history(pkt->owner, "XmitErr", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
2065 return AST_FAILURE;
2066 } else {
2067 /* Schedule retransmission */
2068 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
2069 return AST_SUCCESS;
2073 /*! \brief Kill a SIP dialog (called by scheduler) */
2074 static int __sip_autodestruct(const void *data)
2076 struct sip_pvt *p = (struct sip_pvt *)data;
2078 /* If this is a subscription, tell the phone that we got a timeout */
2079 if (p->subscribed) {
2080 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */
2081 p->subscribed = NONE;
2082 append_history(p, "Subscribestatus", "timeout");
2083 if (option_debug > 2)
2084 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
2085 return 10000; /* Reschedule this destruction so that we know that it's gone */
2088 /* If there are packets still waiting for delivery, delay the destruction */
2089 if (p->packets) {
2090 if (option_debug > 2)
2091 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
2092 append_history(p, "ReliableXmit", "timeout");
2093 return 10000;
2096 /* If we're destroying a subscription, dereference peer object too */
2097 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
2098 ASTOBJ_UNREF(p->relatedpeer,sip_destroy_peer);
2100 /* Reset schedule ID */
2101 p->autokillid = -1;
2103 if (option_debug)
2104 ast_log(LOG_DEBUG, "Auto destroying SIP dialog '%s'\n", p->callid);
2105 append_history(p, "AutoDestroy", "%s", p->callid);
2106 if (p->owner) {
2107 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
2108 ast_queue_hangup(p->owner);
2109 } else if (p->refer && !ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) {
2110 if (option_debug > 2)
2111 ast_log(LOG_DEBUG, "Finally hanging up channel after transfer: %s\n", p->callid);
2112 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2113 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
2114 } else
2115 sip_destroy(p);
2116 return 0;
2119 /*! \brief Schedule destruction of SIP dialog */
2120 static void sip_scheddestroy(struct sip_pvt *p, int ms)
2122 if (ms < 0) {
2123 if (p->timer_t1 == 0)
2124 p->timer_t1 = 500; /* Set timer T1 if not set (RFC 3261) */
2125 ms = p->timer_t1 * 64;
2127 if (sip_debug_test_pvt(p))
2128 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
2129 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
2130 append_history(p, "SchedDestroy", "%d ms", ms);
2132 AST_SCHED_DEL(sched, p->autokillid);
2133 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
2136 /*! \brief Cancel destruction of SIP dialog */
2137 static int sip_cancel_destroy(struct sip_pvt *p)
2139 int res = 0;
2140 if (p->autokillid > -1) {
2141 if (!(res = ast_sched_del(sched, p->autokillid))) {
2142 append_history(p, "CancelDestroy", "");
2143 p->autokillid = -1;
2146 return res;
2149 /*! \brief Acknowledges receipt of a packet and stops retransmission
2150 * called with p locked*/
2151 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2153 struct sip_pkt *cur, *prev = NULL;
2155 /* Just in case... */
2156 char *msg;
2157 int res = FALSE;
2159 msg = sip_methods[sipmethod].text;
2161 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
2162 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
2163 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
2164 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
2165 if (!resp && (seqno == p->pendinginvite)) {
2166 if (option_debug)
2167 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
2168 p->pendinginvite = 0;
2170 /* this is our baby */
2171 res = TRUE;
2172 UNLINK(cur, p->packets, prev);
2173 if (cur->retransid > -1) {
2174 if (sipdebug && option_debug > 3)
2175 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
2177 /* This odd section is designed to thwart a
2178 * race condition in the packet scheduler. There are
2179 * two conditions under which deleting the packet from the
2180 * scheduler can fail.
2182 * 1. The packet has been removed from the scheduler because retransmission
2183 * is being attempted. The problem is that if the packet is currently attempting
2184 * retransmission and we are at this point in the code, then that MUST mean
2185 * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
2186 * lock temporarily to allow retransmission.
2188 * 2. The packet has reached its maximum number of retransmissions and has
2189 * been permanently removed from the packet scheduler. If this is the case, then
2190 * the packet's retransid will be set to -1. The atomicity of the setting and checking
2191 * of the retransid to -1 is ensured since in both cases p's lock is held.
2193 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
2194 DEADLOCK_AVOIDANCE(&p->lock);
2196 free(cur);
2197 break;
2200 if (option_debug)
2201 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");
2204 /*! \brief Pretend to ack all packets
2205 * called with p locked */
2206 static void __sip_pretend_ack(struct sip_pvt *p)
2208 struct sip_pkt *cur = NULL;
2210 while (p->packets) {
2211 int method;
2212 if (cur == p->packets) {
2213 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
2214 return;
2216 cur = p->packets;
2217 method = (cur->method) ? cur->method : find_sip_method(cur->data);
2218 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method);
2222 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2223 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2225 struct sip_pkt *cur;
2226 int res = -1;
2228 for (cur = p->packets; cur; cur = cur->next) {
2229 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
2230 (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
2231 /* this is our baby */
2232 if (cur->retransid > -1) {
2233 if (option_debug > 3 && sipdebug)
2234 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
2236 AST_SCHED_DEL(sched, cur->retransid);
2237 res = 0;
2238 break;
2241 if (option_debug)
2242 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");
2243 return res;
2247 /*! \brief Copy SIP request, parse it */
2248 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2250 memset(dst, 0, sizeof(*dst));
2251 memcpy(dst->data, src->data, sizeof(dst->data));
2252 dst->len = src->len;
2253 parse_request(dst);
2256 /*! \brief add a blank line if no body */
2257 static void add_blank(struct sip_request *req)
2259 if (!req->lines) {
2260 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2261 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2262 req->len += strlen(req->data + req->len);
2266 /*! \brief Transmit response on SIP request*/
2267 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2269 int res;
2271 add_blank(req);
2272 if (sip_debug_test_pvt(p)) {
2273 const struct sockaddr_in *dst = sip_real_dst(p);
2275 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
2276 reliable ? "Reliably " : "", sip_nat_mode(p),
2277 ast_inet_ntoa(dst->sin_addr),
2278 ntohs(dst->sin_port), req->data);
2280 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2281 struct sip_request tmp;
2282 parse_copy(&tmp, req);
2283 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
2284 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
2286 res = (reliable) ?
2287 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2288 __sip_xmit(p, req->data, req->len);
2289 if (res > 0)
2290 return 0;
2291 return res;
2294 /*! \brief Send SIP Request to the other part of the dialogue */
2295 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2297 int res;
2299 add_blank(req);
2300 if (sip_debug_test_pvt(p)) {
2301 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
2302 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);
2303 else
2304 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);
2306 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2307 struct sip_request tmp;
2308 parse_copy(&tmp, req);
2309 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
2311 res = (reliable) ?
2312 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2313 __sip_xmit(p, req->data, req->len);
2314 return res;
2317 /*! \brief Locate closing quote in a string, skipping escaped quotes.
2318 * optionally with a limit on the search.
2319 * start must be past the first quote.
2321 static const char *find_closing_quote(const char *start, const char *lim)
2323 char last_char = '\0';
2324 const char *s;
2325 for (s = start; *s && s != lim; last_char = *s++) {
2326 if (*s == '"' && last_char != '\\')
2327 break;
2329 return s;
2332 /*! \brief Pick out text in brackets from character string
2333 \return pointer to terminated stripped string
2334 \param tmp input string that will be modified
2335 Examples:
2337 "foo" <bar> valid input, returns bar
2338 foo returns the whole string
2339 < "foo ... > returns the string between brackets
2340 < "foo... bogus (missing closing bracket), returns the whole string
2341 XXX maybe should still skip the opening bracket
2343 static char *get_in_brackets(char *tmp)
2345 const char *parse = tmp;
2346 char *first_bracket;
2349 * Skip any quoted text until we find the part in brackets.
2350 * On any error give up and return the full string.
2352 while ( (first_bracket = strchr(parse, '<')) ) {
2353 char *first_quote = strchr(parse, '"');
2355 if (!first_quote || first_quote > first_bracket)
2356 break; /* no need to look at quoted part */
2357 /* the bracket is within quotes, so ignore it */
2358 parse = find_closing_quote(first_quote + 1, NULL);
2359 if (!*parse) { /* not found, return full string ? */
2360 /* XXX or be robust and return in-bracket part ? */
2361 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
2362 break;
2364 parse++;
2366 if (first_bracket) {
2367 char *second_bracket = strchr(first_bracket + 1, '>');
2368 if (second_bracket) {
2369 *second_bracket = '\0';
2370 tmp = first_bracket + 1;
2371 } else {
2372 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
2375 return tmp;
2378 /*! \brief Send SIP MESSAGE text within a call
2379 Called from PBX core sendtext() application */
2380 static int sip_sendtext(struct ast_channel *ast, const char *text)
2382 struct sip_pvt *p = ast->tech_pvt;
2383 int debug = sip_debug_test_pvt(p);
2385 if (debug)
2386 ast_verbose("Sending text %s on %s\n", text, ast->name);
2387 if (!p)
2388 return -1;
2389 if (ast_strlen_zero(text))
2390 return 0;
2391 if (debug)
2392 ast_verbose("Really sending text %s on %s\n", text, ast->name);
2393 transmit_message_with_text(p, text);
2394 return 0;
2397 /*! \brief Update peer object in realtime storage
2398 If the Asterisk system name is set in asterisk.conf, we will use
2399 that name and store that in the "regserver" field in the sippeers
2400 table to facilitate multi-server setups.
2402 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
2404 char port[10];
2405 char ipaddr[INET_ADDRSTRLEN];
2406 char regseconds[20];
2408 char *sysname = ast_config_AST_SYSTEM_NAME;
2409 char *syslabel = NULL;
2411 time_t nowtime = time(NULL) + expirey;
2412 const char *fc = fullcontact ? "fullcontact" : NULL;
2414 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
2415 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2416 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2418 if (ast_strlen_zero(sysname)) /* No system name, disable this */
2419 sysname = NULL;
2420 else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME))
2421 syslabel = "regserver";
2423 if (fc)
2424 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2425 "port", port, "regseconds", regseconds,
2426 "username", username, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
2427 else
2428 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2429 "port", port, "regseconds", regseconds,
2430 "username", username, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
2433 /*! \brief Automatically add peer extension to dial plan */
2434 static void register_peer_exten(struct sip_peer *peer, int onoff)
2436 char multi[256];
2437 char *stringp, *ext, *context;
2439 /* XXX note that global_regcontext is both a global 'enable' flag and
2440 * the name of the global regexten context, if not specified
2441 * individually.
2443 if (ast_strlen_zero(global_regcontext))
2444 return;
2446 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
2447 stringp = multi;
2448 while ((ext = strsep(&stringp, "&"))) {
2449 if ((context = strchr(ext, '@'))) {
2450 *context++ = '\0'; /* split ext@context */
2451 if (!ast_context_find(context)) {
2452 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
2453 continue;
2455 } else {
2456 context = global_regcontext;
2458 if (onoff)
2459 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2460 ast_strdup(peer->name), ast_free, "SIP");
2461 else
2462 ast_context_remove_extension(context, ext, 1, NULL);
2466 /*! \brief Destroy peer object from memory */
2467 static void sip_destroy_peer(struct sip_peer *peer)
2469 if (option_debug > 2)
2470 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
2472 /* Delete it, it needs to disappear */
2473 if (peer->call)
2474 sip_destroy(peer->call);
2476 if (peer->mwipvt) /* We have an active subscription, delete it */
2477 sip_destroy(peer->mwipvt);
2479 if (peer->chanvars) {
2480 ast_variables_destroy(peer->chanvars);
2481 peer->chanvars = NULL;
2484 register_peer_exten(peer, FALSE);
2485 ast_free_ha(peer->ha);
2486 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
2487 apeerobjs--;
2488 else if (ast_test_flag(&peer->flags[0], SIP_REALTIME))
2489 rpeerobjs--;
2490 else
2491 speerobjs--;
2492 clear_realm_authentication(peer->auth);
2493 peer->auth = NULL;
2494 free(peer);
2497 /*! \brief Update peer data in database (if used) */
2498 static void update_peer(struct sip_peer *p, int expiry)
2500 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2501 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
2502 (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
2503 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
2508 /*! \brief realtime_peer: Get peer from realtime storage
2509 * Checks the "sippeers" realtime family from extconfig.conf
2510 * \todo Consider adding check of port address when matching here to follow the same
2511 * algorithm as for static peers. Will we break anything by adding that?
2513 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
2515 struct sip_peer *peer=NULL;
2516 struct ast_variable *var = NULL;
2517 struct ast_config *peerlist = NULL;
2518 struct ast_variable *tmp;
2519 struct ast_flags flags = {0};
2520 const char *iabuf = NULL;
2521 char portstring[6]; /*up to five digits plus null terminator*/
2522 const char *insecure;
2523 char *cat = NULL;
2524 unsigned short portnum;
2526 /* First check on peer name */
2527 if (newpeername) {
2528 var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", NULL);
2529 if (!var && sin)
2530 var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), NULL);
2531 if (!var) {
2532 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
2533 /*!\note
2534 * If this one loaded something, then we need to ensure that the host
2535 * field matched. The only reason why we can't have this as a criteria
2536 * is because we only have the IP address and the host field might be
2537 * set as a name (and the reverse PTR might not match).
2539 if (var && sin) {
2540 for (tmp = var; tmp; tmp = tmp->next) {
2541 if (!strcasecmp(tmp->name, "host")) {
2542 struct hostent *hp;
2543 struct ast_hostent ahp;
2544 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
2545 /* No match */
2546 ast_variables_destroy(var);
2547 var = NULL;
2549 break;
2556 if (!var && sin) { /* Then check on IP address */
2557 iabuf = ast_inet_ntoa(sin->sin_addr);
2558 portnum = ntohs(sin->sin_port);
2559 sprintf(portstring, "%d", portnum);
2560 var = ast_load_realtime("sippeers", "host", iabuf, "port", portstring, NULL); /* First check for fixed IP hosts */
2561 if (!var)
2562 var = ast_load_realtime("sippeers", "ipaddr", iabuf, "port", portstring, NULL); /* Then check for registered hosts */
2563 if (!var) {
2564 peerlist = ast_load_realtime_multientry("sippeers", "host", iabuf, NULL); /*No exact match, see if port is insecure, try host match first*/
2565 if(peerlist){
2566 while((cat = ast_category_browse(peerlist, cat)))
2568 insecure = ast_variable_retrieve(peerlist, cat, "insecure");
2569 set_insecure_flags(&flags, insecure, -1);
2570 if(ast_test_flag(&flags, SIP_INSECURE_PORT)) {
2571 var = ast_category_root(peerlist, cat);
2572 break;
2576 if(!var) {
2577 ast_config_destroy(peerlist);
2578 peerlist = NULL; /*for safety's sake*/
2579 cat = NULL;
2580 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", iabuf, NULL); /*No exact match, see if port is insecure, now try ip address match*/
2581 if(peerlist) {
2582 while((cat = ast_category_browse(peerlist, cat)))
2584 insecure = ast_variable_retrieve(peerlist, cat, "insecure");
2585 set_insecure_flags(&flags, insecure, -1);
2586 if(ast_test_flag(&flags, SIP_INSECURE_PORT)) {
2587 var = ast_category_root(peerlist, cat);
2588 break;
2596 if (!var) {
2597 if(peerlist)
2598 ast_config_destroy(peerlist);
2599 return NULL;
2602 for (tmp = var; tmp; tmp = tmp->next) {
2603 /* If this is type=user, then skip this object. */
2604 if (!strcasecmp(tmp->name, "type") &&
2605 !strcasecmp(tmp->value, "user")) {
2606 ast_variables_destroy(var);
2607 return NULL;
2608 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
2609 newpeername = tmp->value;
2613 if (!newpeername) { /* Did not find peer in realtime */
2614 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
2615 if(peerlist)
2616 ast_config_destroy(peerlist);
2617 else
2618 ast_variables_destroy(var);
2619 return NULL;
2622 /* Peer found in realtime, now build it in memory */
2623 peer = build_peer(newpeername, var, NULL, 1);
2624 if (!peer) {
2625 if(peerlist)
2626 ast_config_destroy(peerlist);
2627 else
2628 ast_variables_destroy(var);
2629 return NULL;
2632 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
2633 /* Cache peer */
2634 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
2635 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
2636 if (!AST_SCHED_DEL(sched, peer->expire)) {
2637 struct sip_peer *peer_ptr = peer;
2638 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
2640 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, ASTOBJ_REF(peer));
2641 if (peer->expire == -1) {
2642 struct sip_peer *peer_ptr = peer;
2643 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
2646 ASTOBJ_CONTAINER_LINK(&peerl,peer);
2648 ast_set_flag(&peer->flags[0], SIP_REALTIME);
2649 if(peerlist)
2650 ast_config_destroy(peerlist);
2651 else
2652 ast_variables_destroy(var);
2653 return peer;
2656 /*! \brief Support routine for find_peer */
2657 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
2659 /* We know name is the first field, so we can cast */
2660 struct sip_peer *p = (struct sip_peer *) name;
2661 return !(!inaddrcmp(&p->addr, sin) ||
2662 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
2663 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
2666 /*! \brief Locate peer by name or ip address
2667 * This is used on incoming SIP message to find matching peer on ip
2668 or outgoing message to find matching peer on name */
2669 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int devstate_only)
2671 struct sip_peer *p = NULL;
2673 if (peer)
2674 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
2675 else
2676 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
2678 if (!p && (realtime || devstate_only))
2679 p = realtime_peer(peer, sin, devstate_only);
2681 return p;
2684 /*! \brief Remove user object from in-memory storage */
2685 static void sip_destroy_user(struct sip_user *user)
2687 if (option_debug > 2)
2688 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
2689 ast_free_ha(user->ha);
2690 if (user->chanvars) {
2691 ast_variables_destroy(user->chanvars);
2692 user->chanvars = NULL;
2694 if (ast_test_flag(&user->flags[0], SIP_REALTIME))
2695 ruserobjs--;
2696 else
2697 suserobjs--;
2698 free(user);
2701 /*! \brief Load user from realtime storage
2702 * Loads user from "sipusers" category in realtime (extconfig.conf)
2703 * Users are matched on From: user name (the domain in skipped) */
2704 static struct sip_user *realtime_user(const char *username)
2706 struct ast_variable *var;
2707 struct ast_variable *tmp;
2708 struct sip_user *user = NULL;
2710 var = ast_load_realtime("sipusers", "name", username, NULL);
2712 if (!var)
2713 return NULL;
2715 for (tmp = var; tmp; tmp = tmp->next) {
2716 if (!strcasecmp(tmp->name, "type") &&
2717 !strcasecmp(tmp->value, "peer")) {
2718 ast_variables_destroy(var);
2719 return NULL;
2723 user = build_user(username, var, NULL, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2725 if (!user) { /* No user found */
2726 ast_variables_destroy(var);
2727 return NULL;
2730 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2731 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2732 suserobjs++;
2733 ASTOBJ_CONTAINER_LINK(&userl,user);
2734 } else {
2735 /* Move counter from s to r... */
2736 suserobjs--;
2737 ruserobjs++;
2739 ast_set_flag(&user->flags[0], SIP_REALTIME);
2740 ast_variables_destroy(var);
2741 return user;
2744 /*! \brief Locate user by name
2745 * Locates user by name (From: sip uri user name part) first
2746 * from in-memory list (static configuration) then from
2747 * realtime storage (defined in extconfig.conf) */
2748 static struct sip_user *find_user(const char *name, int realtime)
2750 struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
2751 if (!u && realtime)
2752 u = realtime_user(name);
2753 return u;
2756 /*! \brief Set nat mode on the various data sockets */
2757 static void do_setnat(struct sip_pvt *p, int natflags)
2759 const char *mode = natflags ? "On" : "Off";
2761 if (p->rtp) {
2762 if (option_debug)
2763 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", mode);
2764 ast_rtp_setnat(p->rtp, natflags);
2766 if (p->vrtp) {
2767 if (option_debug)
2768 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", mode);
2769 ast_rtp_setnat(p->vrtp, natflags);
2771 if (p->udptl) {
2772 if (option_debug)
2773 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", mode);
2774 ast_udptl_setnat(p->udptl, natflags);
2778 /*! \brief Create address structure from peer reference.
2779 * return -1 on error, 0 on success.
2781 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
2783 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
2784 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
2785 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
2786 dialog->recv = dialog->sa;
2787 } else
2788 return -1;
2790 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
2791 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
2792 dialog->capability = peer->capability;
2793 if ((!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(dialog->capability & AST_FORMAT_VIDEO_MASK)) && dialog->vrtp) {
2794 ast_rtp_destroy(dialog->vrtp);
2795 dialog->vrtp = NULL;
2797 dialog->prefs = peer->prefs;
2798 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
2799 dialog->t38.capability = global_t38_capability;
2800 if (dialog->udptl) {
2801 if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_FEC )
2802 dialog->t38.capability |= T38FAX_UDP_EC_FEC;
2803 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
2804 dialog->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
2805 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_NONE )
2806 dialog->t38.capability |= T38FAX_UDP_EC_NONE;
2807 dialog->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
2808 if (option_debug > 1)
2809 ast_log(LOG_DEBUG,"Our T38 capability (%d)\n", dialog->t38.capability);
2811 dialog->t38.jointcapability = dialog->t38.capability;
2812 } else if (dialog->udptl) {
2813 ast_udptl_destroy(dialog->udptl);
2814 dialog->udptl = NULL;
2816 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE );
2818 if (dialog->rtp) {
2819 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
2820 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
2821 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
2822 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
2823 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
2824 /* Set Frame packetization */
2825 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
2826 dialog->autoframing = peer->autoframing;
2828 if (dialog->vrtp) {
2829 ast_rtp_setdtmf(dialog->vrtp, 0);
2830 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
2831 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
2832 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
2833 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
2836 ast_string_field_set(dialog, peername, peer->name);
2837 ast_string_field_set(dialog, authname, peer->username);
2838 ast_string_field_set(dialog, username, peer->username);
2839 ast_string_field_set(dialog, peersecret, peer->secret);
2840 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
2841 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
2842 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
2843 ast_string_field_set(dialog, tohost, peer->tohost);
2844 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
2845 if (!dialog->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
2846 char *tmpcall;
2847 char *c;
2848 tmpcall = ast_strdupa(dialog->callid);
2849 c = strchr(tmpcall, '@');
2850 if (c) {
2851 *c = '\0';
2852 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
2855 if (ast_strlen_zero(dialog->tohost))
2856 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
2857 if (!ast_strlen_zero(peer->fromdomain))
2858 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
2859 if (!ast_strlen_zero(peer->fromuser))
2860 ast_string_field_set(dialog, fromuser, peer->fromuser);
2861 if (!ast_strlen_zero(peer->language))
2862 ast_string_field_set(dialog, language, peer->language);
2863 dialog->maxtime = peer->maxms;
2864 dialog->callgroup = peer->callgroup;
2865 dialog->pickupgroup = peer->pickupgroup;
2866 dialog->peerauth = peer->auth;
2867 dialog->allowtransfer = peer->allowtransfer;
2868 /* Set timer T1 to RTT for this peer (if known by qualify=) */
2869 /* Minimum is settable or default to 100 ms */
2870 if (peer->maxms && peer->lastms)
2871 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
2872 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
2873 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
2874 dialog->noncodeccapability |= AST_RTP_DTMF;
2875 else
2876 dialog->noncodeccapability &= ~AST_RTP_DTMF;
2877 dialog->jointnoncodeccapability = dialog->noncodeccapability;
2878 ast_string_field_set(dialog, context, peer->context);
2879 dialog->rtptimeout = peer->rtptimeout;
2880 if (peer->call_limit)
2881 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
2882 dialog->maxcallbitrate = peer->maxcallbitrate;
2884 return 0;
2887 /*! \brief create address structure from peer name
2888 * Or, if peer not found, find it in the global DNS
2889 * returns TRUE (-1) on failure, FALSE on success */
2890 static int create_addr(struct sip_pvt *dialog, const char *opeer)
2892 struct hostent *hp;
2893 struct ast_hostent ahp;
2894 struct sip_peer *p;
2895 char *port;
2896 int portno;
2897 char host[MAXHOSTNAMELEN], *hostn;
2898 char peer[256];
2900 ast_copy_string(peer, opeer, sizeof(peer));
2901 port = strchr(peer, ':');
2902 if (port)
2903 *port++ = '\0';
2904 dialog->sa.sin_family = AF_INET;
2905 dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
2906 p = find_peer(peer, NULL, 1, 0);
2908 if (p) {
2909 int res = create_addr_from_peer(dialog, p);
2910 if (port) {
2911 portno = atoi(port);
2912 dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
2914 ASTOBJ_UNREF(p, sip_destroy_peer);
2915 return res;
2917 hostn = peer;
2918 portno = port ? atoi(port) : STANDARD_SIP_PORT;
2919 if (srvlookup) {
2920 char service[MAXHOSTNAMELEN];
2921 int tportno;
2922 int ret;
2924 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
2925 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
2926 if (ret > 0) {
2927 hostn = host;
2928 portno = tportno;
2931 hp = ast_gethostbyname(hostn, &ahp);
2932 if (!hp) {
2933 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2934 return -1;
2936 ast_string_field_set(dialog, tohost, peer);
2937 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
2938 dialog->sa.sin_port = htons(portno);
2939 dialog->recv = dialog->sa;
2940 return 0;
2943 /*! \brief Scheduled congestion on a call */
2944 static int auto_congest(const void *nothing)
2946 struct sip_pvt *p = (struct sip_pvt *)nothing;
2948 ast_mutex_lock(&p->lock);
2949 p->initid = -1;
2950 if (p->owner) {
2951 /* XXX fails on possible deadlock */
2952 if (!ast_channel_trylock(p->owner)) {
2953 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
2954 append_history(p, "Cong", "Auto-congesting (timer)");
2955 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
2956 ast_channel_unlock(p->owner);
2959 ast_mutex_unlock(&p->lock);
2960 return 0;
2964 /*! \brief Initiate SIP call from PBX
2965 * used from the dial() application */
2966 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2968 int res, xmitres = 0;
2969 struct sip_pvt *p;
2970 struct varshead *headp;
2971 struct ast_var_t *current;
2972 const char *referer = NULL; /* SIP refererer */
2974 p = ast->tech_pvt;
2975 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2976 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2977 return -1;
2980 /* Check whether there is vxml_url, distinctive ring variables */
2981 headp=&ast->varshead;
2982 AST_LIST_TRAVERSE(headp,current,entries) {
2983 /* Check whether there is a VXML_URL variable */
2984 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2985 p->options->vxml_url = ast_var_value(current);
2986 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
2987 p->options->uri_options = ast_var_value(current);
2988 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
2989 /* Check whether there is a ALERT_INFO variable */
2990 p->options->distinctive_ring = ast_var_value(current);
2991 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2992 /* Check whether there is a variable with a name starting with SIPADDHEADER */
2993 p->options->addsipheaders = 1;
2994 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
2995 /* This is a transfered call */
2996 p->options->transfer = 1;
2997 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
2998 /* This is the referer */
2999 referer = ast_var_value(current);
3000 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
3001 /* We're replacing a call. */
3002 p->options->replaces = ast_var_value(current);
3003 } else if (!strcasecmp(ast_var_name(current), "T38CALL")) {
3004 p->t38.state = T38_LOCAL_DIRECT;
3005 if (option_debug)
3006 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
3011 res = 0;
3012 ast_set_flag(&p->flags[0], SIP_OUTGOING);
3014 if (p->options->transfer) {
3015 char buf[SIPBUFSIZE/2];
3017 if (referer) {
3018 if (sipdebug && option_debug > 2)
3019 ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->username, referer);
3020 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
3021 } else
3022 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
3023 ast_string_field_set(p, cid_name, buf);
3025 if (option_debug)
3026 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
3028 res = update_call_counter(p, INC_CALL_RINGING);
3029 if ( res != -1 ) {
3030 p->callingpres = ast->cid.cid_pres;
3031 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
3032 p->jointnoncodeccapability = p->noncodeccapability;
3034 /* If there are no audio formats left to offer, punt */
3035 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
3036 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
3037 res = -1;
3038 } else {
3039 p->t38.jointcapability = p->t38.capability;
3040 if (option_debug > 1)
3041 ast_log(LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
3042 xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
3043 if (xmitres == XMIT_ERROR)
3044 return -1; /* Transmission error */
3046 p->invitestate = INV_CALLING;
3048 /* Initialize auto-congest time */
3049 AST_SCHED_DEL(sched, p->initid);
3050 p->initid = ast_sched_add(sched, p->maxtime ? (p->maxtime * 4) : SIP_TRANS_TIMEOUT, auto_congest, p);
3053 return res;
3056 /*! \brief Destroy registry object
3057 Objects created with the register= statement in static configuration */
3058 static void sip_registry_destroy(struct sip_registry *reg)
3060 /* Really delete */
3061 if (option_debug > 2)
3062 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
3064 if (reg->call) {
3065 /* Clear registry before destroying to ensure
3066 we don't get reentered trying to grab the registry lock */
3067 reg->call->registry = NULL;
3068 if (option_debug > 2)
3069 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
3070 sip_destroy(reg->call);
3072 AST_SCHED_DEL(sched, reg->expire);
3073 AST_SCHED_DEL(sched, reg->timeout);
3074 ast_string_field_free_memory(reg);
3075 regobjs--;
3076 free(reg);
3080 /*! \brief Execute destruction of SIP dialog structure, release memory */
3081 static int __sip_destroy(struct sip_pvt *p, int lockowner)
3083 struct sip_pvt *cur, *prev = NULL;
3084 struct sip_pkt *cp;
3086 /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
3087 if (p->rtp && ast_rtp_get_bridged(p->rtp)) {
3088 ast_verbose("Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
3089 return -1;
3092 if (p->vrtp && ast_rtp_get_bridged(p->vrtp)) {
3093 ast_verbose("Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
3094 return -1;
3097 if (sip_debug_test_pvt(p) || option_debug > 2)
3098 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
3100 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
3101 update_call_counter(p, DEC_CALL_LIMIT);
3102 if (option_debug > 1)
3103 ast_log(LOG_DEBUG, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
3106 /* Unlink us from the owner if we have one */
3107 if (p->owner) {
3108 if (lockowner)
3109 ast_channel_lock(p->owner);
3110 if (option_debug)
3111 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
3112 p->owner->tech_pvt = NULL;
3113 /* Make sure that the channel knows its backend is going away */
3114 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
3115 if (lockowner)
3116 ast_channel_unlock(p->owner);
3117 /* Give the channel a chance to react before deallocation */
3118 usleep(1);
3121 /* Remove link from peer to subscription of MWI */
3122 if (p->relatedpeer) {
3123 if (p->relatedpeer->mwipvt == p) {
3124 p->relatedpeer->mwipvt = NULL;
3126 ASTOBJ_UNREF(p->relatedpeer, sip_destroy_peer);
3129 if (dumphistory)
3130 sip_dump_history(p);
3132 if (p->options)
3133 free(p->options);
3135 if (p->stateid > -1)
3136 ast_extension_state_del(p->stateid, NULL);
3137 AST_SCHED_DEL(sched, p->initid);
3138 AST_SCHED_DEL(sched, p->waitid);
3139 AST_SCHED_DEL(sched, p->autokillid);
3141 if (p->rtp) {
3142 ast_rtp_destroy(p->rtp);
3144 if (p->vrtp) {
3145 ast_rtp_destroy(p->vrtp);
3147 if (p->udptl)
3148 ast_udptl_destroy(p->udptl);
3149 if (p->refer)
3150 free(p->refer);
3151 if (p->route) {
3152 free_old_route(p->route);
3153 p->route = NULL;
3155 if (p->registry) {
3156 if (p->registry->call == p)
3157 p->registry->call = NULL;
3158 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
3161 /* Clear history */
3162 if (p->history) {
3163 struct sip_history *hist;
3164 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
3165 free(hist);
3166 p->history_entries--;
3168 free(p->history);
3169 p->history = NULL;
3172 for (prev = NULL, cur = iflist; cur; prev = cur, cur = cur->next) {
3173 if (cur == p) {
3174 UNLINK(cur, iflist, prev);
3175 break;
3178 if (!cur) {
3179 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
3180 return 0;
3183 /* remove all current packets in this dialog */
3184 while((cp = p->packets)) {
3185 p->packets = p->packets->next;
3186 AST_SCHED_DEL(sched, cp->retransid);
3187 free(cp);
3189 if (p->chanvars) {
3190 ast_variables_destroy(p->chanvars);
3191 p->chanvars = NULL;
3193 ast_mutex_destroy(&p->lock);
3195 ast_string_field_free_memory(p);
3197 free(p);
3198 return 0;
3201 /*! \brief update_call_counter: Handle call_limit for SIP users
3202 * Setting a call-limit will cause calls above the limit not to be accepted.
3204 * Remember that for a type=friend, there's one limit for the user and
3205 * another for the peer, not a combined call limit.
3206 * This will cause unexpected behaviour in subscriptions, since a "friend"
3207 * is *two* devices in Asterisk, not one.
3209 * Thought: For realtime, we should propably update storage with inuse counter...
3211 * \return 0 if call is ok (no call limit, below treshold)
3212 * -1 on rejection of call
3215 static int update_call_counter(struct sip_pvt *fup, int event)
3217 char name[256];
3218 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
3219 int outgoing = ast_test_flag(&fup->flags[1], SIP_PAGE2_OUTGOING_CALL);
3220 struct sip_user *u = NULL;
3221 struct sip_peer *p = NULL;
3223 if (option_debug > 2)
3224 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
3226 /* Test if we need to check call limits, in order to avoid
3227 realtime lookups if we do not need it */
3228 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
3229 return 0;
3231 ast_copy_string(name, fup->username, sizeof(name));
3233 /* Check the list of users only for incoming calls */
3234 if (global_limitonpeers == FALSE && !outgoing && (u = find_user(name, 1))) {
3235 inuse = &u->inUse;
3236 call_limit = &u->call_limit;
3237 inringing = NULL;
3238 } else if ( (p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, 1, 0) ) ) { /* Try to find peer */
3239 inuse = &p->inUse;
3240 call_limit = &p->call_limit;
3241 inringing = &p->inRinging;
3242 ast_copy_string(name, fup->peername, sizeof(name));
3244 if (!p && !u) {
3245 if (option_debug > 1)
3246 ast_log(LOG_DEBUG, "%s is not a local device, no call limit\n", name);
3247 return 0;
3250 switch(event) {
3251 /* incoming and outgoing affects the inUse counter */
3252 case DEC_CALL_LIMIT:
3253 if ( *inuse > 0 ) {
3254 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
3255 (*inuse)--;
3256 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
3258 } else {
3259 *inuse = 0;
3261 if (inringing) {
3262 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3263 if (*inringing > 0)
3264 (*inringing)--;
3265 else if (!ast_test_flag(&p->flags[0], SIP_REALTIME) || ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS))
3266 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", fup->peername);
3267 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3270 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && global_notifyhold) {
3271 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
3272 sip_peer_hold(fup, 0);
3274 if (option_debug > 1 || sipdebug) {
3275 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
3277 break;
3279 case INC_CALL_RINGING:
3280 case INC_CALL_LIMIT:
3281 if (*call_limit > 0 ) {
3282 if (*inuse >= *call_limit) {
3283 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);
3284 if (u)
3285 ASTOBJ_UNREF(u, sip_destroy_user);
3286 else
3287 ASTOBJ_UNREF(p, sip_destroy_peer);
3288 return -1;
3291 if (inringing && (event == INC_CALL_RINGING)) {
3292 if (!ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3293 (*inringing)++;
3294 ast_set_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3297 /* Continue */
3298 (*inuse)++;
3299 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
3300 if (option_debug > 1 || sipdebug) {
3301 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
3303 break;
3305 case DEC_CALL_RINGING:
3306 if (inringing) {
3307 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3308 if (*inringing > 0)
3309 (*inringing)--;
3310 else if (!ast_test_flag(&p->flags[0], SIP_REALTIME) || ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS))
3311 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", p->name);
3312 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3315 break;
3317 default:
3318 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
3320 if (p) {
3321 ast_device_state_changed("SIP/%s", p->name);
3322 ASTOBJ_UNREF(p, sip_destroy_peer);
3323 } else /* u must be set */
3324 ASTOBJ_UNREF(u, sip_destroy_user);
3325 return 0;
3328 /*! \brief Destroy SIP call structure */
3329 static void sip_destroy(struct sip_pvt *p)
3331 ast_mutex_lock(&iflock);
3332 if (option_debug > 2)
3333 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
3334 __sip_destroy(p, 1);
3335 ast_mutex_unlock(&iflock);
3338 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
3339 static int hangup_sip2cause(int cause)
3341 /* Possible values taken from causes.h */
3343 switch(cause) {
3344 case 401: /* Unauthorized */
3345 return AST_CAUSE_CALL_REJECTED;
3346 case 403: /* Not found */
3347 return AST_CAUSE_CALL_REJECTED;
3348 case 404: /* Not found */
3349 return AST_CAUSE_UNALLOCATED;
3350 case 405: /* Method not allowed */
3351 return AST_CAUSE_INTERWORKING;
3352 case 407: /* Proxy authentication required */
3353 return AST_CAUSE_CALL_REJECTED;
3354 case 408: /* No reaction */
3355 return AST_CAUSE_NO_USER_RESPONSE;
3356 case 409: /* Conflict */
3357 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
3358 case 410: /* Gone */
3359 return AST_CAUSE_UNALLOCATED;
3360 case 411: /* Length required */
3361 return AST_CAUSE_INTERWORKING;
3362 case 413: /* Request entity too large */
3363 return AST_CAUSE_INTERWORKING;
3364 case 414: /* Request URI too large */
3365 return AST_CAUSE_INTERWORKING;
3366 case 415: /* Unsupported media type */
3367 return AST_CAUSE_INTERWORKING;
3368 case 420: /* Bad extension */
3369 return AST_CAUSE_NO_ROUTE_DESTINATION;
3370 case 480: /* No answer */
3371 return AST_CAUSE_NO_ANSWER;
3372 case 481: /* No answer */
3373 return AST_CAUSE_INTERWORKING;
3374 case 482: /* Loop detected */
3375 return AST_CAUSE_INTERWORKING;
3376 case 483: /* Too many hops */
3377 return AST_CAUSE_NO_ANSWER;
3378 case 484: /* Address incomplete */
3379 return AST_CAUSE_INVALID_NUMBER_FORMAT;
3380 case 485: /* Ambigous */
3381 return AST_CAUSE_UNALLOCATED;
3382 case 486: /* Busy everywhere */
3383 return AST_CAUSE_BUSY;
3384 case 487: /* Request terminated */
3385 return AST_CAUSE_INTERWORKING;
3386 case 488: /* No codecs approved */
3387 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3388 case 491: /* Request pending */
3389 return AST_CAUSE_INTERWORKING;
3390 case 493: /* Undecipherable */
3391 return AST_CAUSE_INTERWORKING;
3392 case 500: /* Server internal failure */
3393 return AST_CAUSE_FAILURE;
3394 case 501: /* Call rejected */
3395 return AST_CAUSE_FACILITY_REJECTED;
3396 case 502:
3397 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
3398 case 503: /* Service unavailable */
3399 return AST_CAUSE_CONGESTION;
3400 case 504: /* Gateway timeout */
3401 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
3402 case 505: /* SIP version not supported */
3403 return AST_CAUSE_INTERWORKING;
3404 case 600: /* Busy everywhere */
3405 return AST_CAUSE_USER_BUSY;
3406 case 603: /* Decline */
3407 return AST_CAUSE_CALL_REJECTED;
3408 case 604: /* Does not exist anywhere */
3409 return AST_CAUSE_UNALLOCATED;
3410 case 606: /* Not acceptable */
3411 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3412 default:
3413 return AST_CAUSE_NORMAL;
3415 /* Never reached */
3416 return 0;
3419 /*! \brief Convert Asterisk hangup causes to SIP codes
3420 \verbatim
3421 Possible values from causes.h
3422 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
3423 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
3425 In addition to these, a lot of PRI codes is defined in causes.h
3426 ...should we take care of them too ?
3428 Quote RFC 3398
3430 ISUP Cause value SIP response
3431 ---------------- ------------
3432 1 unallocated number 404 Not Found
3433 2 no route to network 404 Not found
3434 3 no route to destination 404 Not found
3435 16 normal call clearing --- (*)
3436 17 user busy 486 Busy here
3437 18 no user responding 408 Request Timeout
3438 19 no answer from the user 480 Temporarily unavailable
3439 20 subscriber absent 480 Temporarily unavailable
3440 21 call rejected 403 Forbidden (+)
3441 22 number changed (w/o diagnostic) 410 Gone
3442 22 number changed (w/ diagnostic) 301 Moved Permanently
3443 23 redirection to new destination 410 Gone
3444 26 non-selected user clearing 404 Not Found (=)
3445 27 destination out of order 502 Bad Gateway
3446 28 address incomplete 484 Address incomplete
3447 29 facility rejected 501 Not implemented
3448 31 normal unspecified 480 Temporarily unavailable
3449 \endverbatim
3451 static const char *hangup_cause2sip(int cause)
3453 switch (cause) {
3454 case AST_CAUSE_UNALLOCATED: /* 1 */
3455 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
3456 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
3457 return "404 Not Found";
3458 case AST_CAUSE_CONGESTION: /* 34 */
3459 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
3460 return "503 Service Unavailable";
3461 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
3462 return "408 Request Timeout";
3463 case AST_CAUSE_NO_ANSWER: /* 19 */
3464 case AST_CAUSE_UNREGISTERED: /* 20 */
3465 return "480 Temporarily unavailable";
3466 case AST_CAUSE_CALL_REJECTED: /* 21 */
3467 return "403 Forbidden";
3468 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
3469 return "410 Gone";
3470 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
3471 return "480 Temporarily unavailable";
3472 case AST_CAUSE_INVALID_NUMBER_FORMAT:
3473 return "484 Address incomplete";
3474 case AST_CAUSE_USER_BUSY:
3475 return "486 Busy here";
3476 case AST_CAUSE_FAILURE:
3477 return "500 Server internal failure";
3478 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
3479 return "501 Not Implemented";
3480 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
3481 return "503 Service Unavailable";
3482 /* Used in chan_iax2 */
3483 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
3484 return "502 Bad Gateway";
3485 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
3486 return "488 Not Acceptable Here";
3488 case AST_CAUSE_NOTDEFINED:
3489 default:
3490 if (option_debug)
3491 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
3492 return NULL;
3495 /* Never reached */
3496 return 0;
3500 /*! \brief sip_hangup: Hangup SIP call
3501 * Part of PBX interface, called from ast_hangup */
3502 static int sip_hangup(struct ast_channel *ast)
3504 struct sip_pvt *p = ast->tech_pvt;
3505 int needcancel = FALSE;
3506 int needdestroy = 0;
3507 struct ast_channel *oldowner = ast;
3509 if (!p) {
3510 if (option_debug)
3511 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
3512 return 0;
3515 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
3516 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
3517 if (option_debug && sipdebug)
3518 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
3519 update_call_counter(p, DEC_CALL_LIMIT);
3521 if (option_debug >3)
3522 ast_log(LOG_DEBUG, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
3523 if (p->autokillid > -1 && sip_cancel_destroy(p))
3524 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
3525 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3526 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
3527 ast_clear_flag(&p->flags[0], SIP_NEEDDESTROY);
3528 p->owner->tech_pvt = NULL;
3529 p->owner = NULL; /* Owner will be gone after we return, so take it away */
3530 return 0;
3532 if (option_debug) {
3533 if (ast_test_flag(ast, AST_FLAG_ZOMBIE) && p->refer && option_debug)
3534 ast_log(LOG_DEBUG, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
3535 else {
3536 if (option_debug)
3537 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
3540 if (option_debug && ast_test_flag(ast, AST_FLAG_ZOMBIE))
3541 ast_log(LOG_DEBUG, "Hanging up zombie call. Be scared.\n");
3543 ast_mutex_lock(&p->lock);
3544 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
3545 if (option_debug && sipdebug)
3546 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
3547 update_call_counter(p, DEC_CALL_LIMIT);
3550 /* Determine how to disconnect */
3551 if (p->owner != ast) {
3552 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
3553 ast_mutex_unlock(&p->lock);
3554 return 0;
3556 /* If the call is not UP, we need to send CANCEL instead of BYE */
3557 if (ast->_state == AST_STATE_RING || ast->_state == AST_STATE_RINGING || (p->invitestate < INV_COMPLETED && ast->_state != AST_STATE_UP)) {
3558 needcancel = TRUE;
3559 if (option_debug > 3)
3560 ast_log(LOG_DEBUG, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
3563 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
3565 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->owner->hangupcause) : "Unknown");
3567 /* Disconnect */
3568 if (p->vad)
3569 ast_dsp_free(p->vad);
3571 p->owner = NULL;
3572 ast->tech_pvt = NULL;
3574 ast_module_unref(ast_module_info->self);
3576 /* Do not destroy this pvt until we have timeout or
3577 get an answer to the BYE or INVITE/CANCEL
3578 If we get no answer during retransmit period, drop the call anyway.
3579 (Sorry, mother-in-law, you can't deny a hangup by sending
3580 603 declined to BYE...)
3582 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE))
3583 needdestroy = 1; /* Set destroy flag at end of this function */
3584 else if (p->invitestate != INV_CALLING)
3585 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3587 /* Start the process if it's not already started */
3588 if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
3589 if (needcancel) { /* Outgoing call, not up */
3590 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3591 /* stop retransmitting an INVITE that has not received a response */
3592 __sip_pretend_ack(p);
3593 p->invitestate = INV_CANCELLED;
3595 /* if we can't send right now, mark it pending */
3596 if (p->invitestate == INV_CALLING) {
3597 /* We can't send anything in CALLING state */
3598 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3599 /* 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. */
3600 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3601 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
3602 } else {
3603 /* Send a new request: CANCEL */
3604 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
3605 /* Actually don't destroy us yet, wait for the 487 on our original
3606 INVITE, but do set an autodestruct just in case we never get it. */
3607 needdestroy = 0;
3608 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3610 if ( p->initid != -1 ) {
3611 /* channel still up - reverse dec of inUse counter
3612 only if the channel is not auto-congested */
3613 update_call_counter(p, INC_CALL_LIMIT);
3615 } else { /* Incoming call, not up */
3616 const char *res;
3617 if (ast->hangupcause && (res = hangup_cause2sip(ast->hangupcause)))
3618 transmit_response_reliable(p, res, &p->initreq);
3619 else
3620 transmit_response_reliable(p, "603 Declined", &p->initreq);
3621 p->invitestate = INV_TERMINATED;
3623 } else { /* Call is in UP state, send BYE */
3624 if (!p->pendinginvite) {
3625 char *audioqos = "";
3626 char *videoqos = "";
3627 if (p->rtp)
3628 audioqos = ast_rtp_get_quality(p->rtp, NULL);
3629 if (p->vrtp)
3630 videoqos = ast_rtp_get_quality(p->vrtp, NULL);
3631 /* Send a hangup */
3632 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3634 /* Get RTCP quality before end of call */
3635 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
3636 if (p->rtp)
3637 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
3638 if (p->vrtp)
3639 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
3641 if (p->rtp && oldowner)
3642 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
3643 if (p->vrtp && oldowner)
3644 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
3645 } else {
3646 /* Note we will need a BYE when this all settles out
3647 but we can't send one while we have "INVITE" outstanding. */
3648 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3649 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
3650 AST_SCHED_DEL(sched, p->waitid);
3651 if (sip_cancel_destroy(p))
3652 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
3656 if (needdestroy)
3657 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
3658 ast_mutex_unlock(&p->lock);
3659 return 0;
3662 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
3663 static void try_suggested_sip_codec(struct sip_pvt *p)
3665 int fmt;
3666 const char *codec;
3668 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
3669 if (!codec)
3670 return;
3672 fmt = ast_getformatbyname(codec);
3673 if (fmt) {
3674 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
3675 if (p->jointcapability & fmt) {
3676 p->jointcapability &= fmt;
3677 p->capability &= fmt;
3678 } else
3679 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
3680 } else
3681 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
3682 return;
3685 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
3686 * Part of PBX interface */
3687 static int sip_answer(struct ast_channel *ast)
3689 int res = 0;
3690 struct sip_pvt *p = ast->tech_pvt;
3692 ast_mutex_lock(&p->lock);
3693 if (ast->_state != AST_STATE_UP) {
3694 try_suggested_sip_codec(p);
3696 ast_setstate(ast, AST_STATE_UP);
3697 if (option_debug)
3698 ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name);
3699 if (p->t38.state == T38_PEER_DIRECT) {
3700 p->t38.state = T38_ENABLED;
3701 if (option_debug > 1)
3702 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
3703 res = transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
3704 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
3705 } else {
3706 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
3707 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
3710 ast_mutex_unlock(&p->lock);
3711 return res;
3714 /*! \brief Send frame to media channel (rtp) */
3715 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
3717 struct sip_pvt *p = ast->tech_pvt;
3718 int res = 0;
3720 switch (frame->frametype) {
3721 case AST_FRAME_VOICE:
3722 if (!(frame->subclass & ast->nativeformats)) {
3723 char s1[512], s2[512], s3[512];
3724 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
3725 frame->subclass,
3726 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
3727 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
3728 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
3729 ast->readformat,
3730 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
3731 ast->writeformat);
3732 return 0;
3734 if (p) {
3735 ast_mutex_lock(&p->lock);
3736 if (p->rtp) {
3737 /* If channel is not up, activate early media session */
3738 if ((ast->_state != AST_STATE_UP) &&
3739 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3740 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3741 ast_rtp_new_source(p->rtp);
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->rtp, frame);
3748 ast_mutex_unlock(&p->lock);
3750 break;
3751 case AST_FRAME_VIDEO:
3752 if (p) {
3753 ast_mutex_lock(&p->lock);
3754 if (p->vrtp) {
3755 /* Activate video early media */
3756 if ((ast->_state != AST_STATE_UP) &&
3757 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3758 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3759 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3760 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3762 p->lastrtptx = time(NULL);
3763 res = ast_rtp_write(p->vrtp, frame);
3765 ast_mutex_unlock(&p->lock);
3767 break;
3768 case AST_FRAME_IMAGE:
3769 return 0;
3770 break;
3771 case AST_FRAME_MODEM:
3772 if (p) {
3773 ast_mutex_lock(&p->lock);
3774 /* UDPTL requires two-way communication, so early media is not needed here.
3775 we simply forget the frames if we get modem frames before the bridge is up.
3776 Fax will re-transmit.
3778 if (p->udptl && ast->_state == AST_STATE_UP)
3779 res = ast_udptl_write(p->udptl, frame);
3780 ast_mutex_unlock(&p->lock);
3782 break;
3783 default:
3784 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
3785 return 0;
3788 return res;
3791 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
3792 Basically update any ->owner links */
3793 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
3795 int ret = -1;
3796 struct sip_pvt *p;
3798 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE) && option_debug)
3799 ast_log(LOG_DEBUG, "New channel is zombie\n");
3800 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE) && option_debug)
3801 ast_log(LOG_DEBUG, "Old channel is zombie\n");
3803 if (!newchan || !newchan->tech_pvt) {
3804 if (!newchan)
3805 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
3806 else
3807 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
3808 return -1;
3810 p = newchan->tech_pvt;
3812 if (!p) {
3813 ast_log(LOG_WARNING, "No pvt after masquerade. Strange things may happen\n");
3814 return -1;
3817 ast_mutex_lock(&p->lock);
3818 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
3819 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
3820 if (p->owner != oldchan)
3821 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
3822 else {
3823 p->owner = newchan;
3824 /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
3825 RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
3826 able to do this if the masquerade happens before the bridge breaks (e.g., AMI
3827 redirect of both channels). Note that a channel can not be masqueraded *into*
3828 a native bridge. So there is no danger that this breaks a native bridge that
3829 should stay up. */
3830 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0);
3831 ret = 0;
3833 if (option_debug > 2)
3834 ast_log(LOG_DEBUG, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
3836 ast_mutex_unlock(&p->lock);
3837 return ret;
3840 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
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_INBAND:
3848 res = -1; /* Tell Asterisk to generate inband indications */
3849 break;
3850 case SIP_DTMF_RFC2833:
3851 if (p->rtp)
3852 ast_rtp_senddigit_begin(p->rtp, digit);
3853 break;
3854 default:
3855 break;
3857 ast_mutex_unlock(&p->lock);
3859 return res;
3862 /*! \brief Send DTMF character on SIP channel
3863 within one call, we're able to transmit in many methods simultaneously */
3864 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
3866 struct sip_pvt *p = ast->tech_pvt;
3867 int res = 0;
3869 ast_mutex_lock(&p->lock);
3870 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
3871 case SIP_DTMF_INFO:
3872 transmit_info_with_digit(p, digit, duration);
3873 break;
3874 case SIP_DTMF_RFC2833:
3875 if (p->rtp)
3876 ast_rtp_senddigit_end(p->rtp, digit);
3877 break;
3878 case SIP_DTMF_INBAND:
3879 res = -1; /* Tell Asterisk to stop inband indications */
3880 break;
3882 ast_mutex_unlock(&p->lock);
3884 return res;
3887 /*! \brief Transfer SIP call */
3888 static int sip_transfer(struct ast_channel *ast, const char *dest)
3890 struct sip_pvt *p = ast->tech_pvt;
3891 int res;
3893 if (dest == NULL) /* functions below do not take a NULL */
3894 dest = "";
3895 ast_mutex_lock(&p->lock);
3896 if (ast->_state == AST_STATE_RING)
3897 res = sip_sipredirect(p, dest);
3898 else
3899 res = transmit_refer(p, dest);
3900 ast_mutex_unlock(&p->lock);
3901 return res;
3904 /*! \brief Play indication to user
3905 * With SIP a lot of indications is sent as messages, letting the device play
3906 the indication - busy signal, congestion etc
3907 \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
3909 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
3911 struct sip_pvt *p = ast->tech_pvt;
3912 int res = 0;
3914 ast_mutex_lock(&p->lock);
3915 switch(condition) {
3916 case AST_CONTROL_RINGING:
3917 if (ast->_state == AST_STATE_RING) {
3918 p->invitestate = INV_EARLY_MEDIA;
3919 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
3920 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
3921 /* Send 180 ringing if out-of-band seems reasonable */
3922 transmit_response(p, "180 Ringing", &p->initreq);
3923 ast_set_flag(&p->flags[0], SIP_RINGING);
3924 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
3925 break;
3926 } else {
3927 /* Well, if it's not reasonable, just send in-band */
3930 res = -1;
3931 break;
3932 case AST_CONTROL_BUSY:
3933 if (ast->_state != AST_STATE_UP) {
3934 transmit_response_reliable(p, "486 Busy Here", &p->initreq);
3935 p->invitestate = INV_COMPLETED;
3936 sip_alreadygone(p);
3937 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
3938 break;
3940 res = -1;
3941 break;
3942 case AST_CONTROL_CONGESTION:
3943 if (ast->_state != AST_STATE_UP) {
3944 transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
3945 p->invitestate = INV_COMPLETED;
3946 sip_alreadygone(p);
3947 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
3948 break;
3950 res = -1;
3951 break;
3952 case AST_CONTROL_PROCEEDING:
3953 if ((ast->_state != AST_STATE_UP) &&
3954 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3955 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3956 transmit_response(p, "100 Trying", &p->initreq);
3957 p->invitestate = INV_PROCEEDING;
3958 break;
3960 res = -1;
3961 break;
3962 case AST_CONTROL_PROGRESS:
3963 if ((ast->_state != AST_STATE_UP) &&
3964 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3965 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3966 p->invitestate = INV_EARLY_MEDIA;
3967 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3968 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3969 break;
3971 res = -1;
3972 break;
3973 case AST_CONTROL_HOLD:
3974 ast_rtp_new_source(p->rtp);
3975 ast_moh_start(ast, data, p->mohinterpret);
3976 break;
3977 case AST_CONTROL_UNHOLD:
3978 ast_rtp_new_source(p->rtp);
3979 ast_moh_stop(ast);
3980 break;
3981 case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
3982 if (p->vrtp && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
3983 transmit_info_with_vidupdate(p);
3984 /* ast_rtcp_send_h261fur(p->vrtp); */
3985 } else
3986 res = -1;
3987 break;
3988 case AST_CONTROL_SRCUPDATE:
3989 ast_rtp_new_source(p->rtp);
3990 break;
3991 case -1:
3992 res = -1;
3993 break;
3994 default:
3995 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
3996 res = -1;
3997 break;
3999 ast_mutex_unlock(&p->lock);
4000 return res;
4004 /*! \brief Initiate a call in the SIP channel
4005 called from sip_request_call (calls from the pbx ) for outbound channels
4006 and from handle_request_invite for inbound channels
4009 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
4011 struct ast_channel *tmp;
4012 struct ast_variable *v = NULL;
4013 int fmt;
4014 int what;
4015 int needvideo = 0, video = 0;
4016 char *decoded_exten;
4018 const char *my_name; /* pick a good name */
4020 if (title)
4021 my_name = title;
4022 else if ( (my_name = strchr(i->fromdomain,':')) )
4023 my_name++; /* skip ':' */
4024 else
4025 my_name = i->fromdomain;
4027 ast_mutex_unlock(&i->lock);
4028 /* Don't hold a sip pvt lock while we allocate a channel */
4029 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);
4032 if (!tmp) {
4033 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
4034 ast_mutex_lock(&i->lock);
4035 return NULL;
4037 ast_mutex_lock(&i->lock);
4039 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO)
4040 tmp->tech = &sip_tech_info;
4041 else
4042 tmp->tech = &sip_tech;
4044 /* Select our native format based on codec preference until we receive
4045 something from another device to the contrary. */
4046 if (i->jointcapability) { /* The joint capabilities of us and peer */
4047 what = i->jointcapability;
4048 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
4049 } else if (i->capability) { /* Our configured capability for this peer */
4050 what = i->capability;
4051 video = i->capability & AST_FORMAT_VIDEO_MASK;
4052 } else {
4053 what = global_capability; /* Global codec support */
4054 video = global_capability & AST_FORMAT_VIDEO_MASK;
4057 /* Set the native formats for audio and merge in video */
4058 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video;
4059 if (option_debug > 2) {
4060 char buf[SIPBUFSIZE];
4061 ast_log(LOG_DEBUG, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
4062 ast_log(LOG_DEBUG, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
4063 ast_log(LOG_DEBUG, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
4064 ast_log(LOG_DEBUG, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
4065 if (i->prefcodec)
4066 ast_log(LOG_DEBUG, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
4069 /* XXX Why are we choosing a codec from the native formats?? */
4070 fmt = ast_best_codec(tmp->nativeformats);
4072 /* If we have a prefcodec setting, we have an inbound channel that set a
4073 preferred format for this call. Otherwise, we check the jointcapability
4074 We also check for vrtp. If it's not there, we are not allowed do any video anyway.
4076 if (i->vrtp) {
4077 if (i->prefcodec)
4078 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK; /* Outbound call */
4079 else
4080 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK; /* Inbound call */
4083 if (option_debug > 2) {
4084 if (needvideo)
4085 ast_log(LOG_DEBUG, "This channel can handle video! HOLLYWOOD next!\n");
4086 else
4087 ast_log(LOG_DEBUG, "This channel will not be able to handle video.\n");
4092 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
4093 i->vad = ast_dsp_new();
4094 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
4095 if (global_relaxdtmf)
4096 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
4098 if (i->rtp) {
4099 tmp->fds[0] = ast_rtp_fd(i->rtp);
4100 tmp->fds[1] = ast_rtcp_fd(i->rtp);
4102 if (needvideo && i->vrtp) {
4103 tmp->fds[2] = ast_rtp_fd(i->vrtp);
4104 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
4106 if (i->udptl) {
4107 tmp->fds[5] = ast_udptl_fd(i->udptl);
4109 if (state == AST_STATE_RING)
4110 tmp->rings = 1;
4111 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
4112 tmp->writeformat = fmt;
4113 tmp->rawwriteformat = fmt;
4114 tmp->readformat = fmt;
4115 tmp->rawreadformat = fmt;
4116 tmp->tech_pvt = i;
4118 tmp->callgroup = i->callgroup;
4119 tmp->pickupgroup = i->pickupgroup;
4120 tmp->cid.cid_pres = i->callingpres;
4121 if (!ast_strlen_zero(i->accountcode))
4122 ast_string_field_set(tmp, accountcode, i->accountcode);
4123 if (i->amaflags)
4124 tmp->amaflags = i->amaflags;
4125 if (!ast_strlen_zero(i->language))
4126 ast_string_field_set(tmp, language, i->language);
4127 i->owner = tmp;
4128 ast_module_ref(ast_module_info->self);
4129 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
4130 /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
4131 * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
4132 * structure so that there aren't issues when forming URI's
4134 decoded_exten = ast_strdupa(i->exten);
4135 ast_uri_decode(decoded_exten);
4136 ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
4138 /* Don't use ast_set_callerid() here because it will
4139 * generate an unnecessary NewCallerID event */
4140 tmp->cid.cid_ani = ast_strdup(i->cid_num);
4141 if (!ast_strlen_zero(i->rdnis))
4142 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
4144 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
4145 tmp->cid.cid_dnid = ast_strdup(i->exten);
4147 tmp->priority = 1;
4148 if (!ast_strlen_zero(i->uri))
4149 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
4150 if (!ast_strlen_zero(i->domain))
4151 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
4152 if (!ast_strlen_zero(i->useragent))
4153 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
4154 if (!ast_strlen_zero(i->callid))
4155 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
4156 if (i->rtp)
4157 ast_jb_configure(tmp, &global_jbconf);
4159 /* If the INVITE contains T.38 SDP information set the proper channel variable so a created outgoing call will also have T.38 */
4160 if (i->udptl && i->t38.state == T38_PEER_DIRECT)
4161 pbx_builtin_setvar_helper(tmp, "_T38CALL", "1");
4163 /* Set channel variables for this call from configuration */
4164 for (v = i->chanvars ; v ; v = v->next)
4165 pbx_builtin_setvar_helper(tmp, v->name, v->value);
4167 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
4168 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
4169 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
4170 ast_hangup(tmp);
4171 tmp = NULL;
4174 if (!ast_test_flag(&i->flags[0], SIP_NO_HISTORY))
4175 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
4177 return tmp;
4180 /*! \brief Reads one line of SIP message body */
4181 static char *get_body_by_line(const char *line, const char *name, int nameLen)
4183 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=')
4184 return ast_skip_blanks(line + nameLen + 1);
4186 return "";
4189 /*! \brief Lookup 'name' in the SDP starting
4190 * at the 'start' line. Returns the matching line, and 'start'
4191 * is updated with the next line number.
4193 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
4195 int len = strlen(name);
4197 while (*start < req->sdp_end) {
4198 const char *r = get_body_by_line(req->line[(*start)++], name, len);
4199 if (r[0] != '\0')
4200 return r;
4203 return "";
4206 /*! \brief Get a line from an SDP message body */
4207 static const char *get_sdp(struct sip_request *req, const char *name)
4209 int dummy = 0;
4211 return get_sdp_iterate(&dummy, req, name);
4214 /*! \brief Get a specific line from the message body */
4215 static char *get_body(struct sip_request *req, char *name)
4217 int x;
4218 int len = strlen(name);
4219 char *r;
4221 for (x = 0; x < req->lines; x++) {
4222 r = get_body_by_line(req->line[x], name, len);
4223 if (r[0] != '\0')
4224 return r;
4227 return "";
4230 /*! \brief Find compressed SIP alias */
4231 static const char *find_alias(const char *name, const char *_default)
4233 /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
4234 static const struct cfalias {
4235 char * const fullname;
4236 char * const shortname;
4237 } aliases[] = {
4238 { "Content-Type", "c" },
4239 { "Content-Encoding", "e" },
4240 { "From", "f" },
4241 { "Call-ID", "i" },
4242 { "Contact", "m" },
4243 { "Content-Length", "l" },
4244 { "Subject", "s" },
4245 { "To", "t" },
4246 { "Supported", "k" },
4247 { "Refer-To", "r" },
4248 { "Referred-By", "b" },
4249 { "Allow-Events", "u" },
4250 { "Event", "o" },
4251 { "Via", "v" },
4252 { "Accept-Contact", "a" },
4253 { "Reject-Contact", "j" },
4254 { "Request-Disposition", "d" },
4255 { "Session-Expires", "x" },
4256 { "Identity", "y" },
4257 { "Identity-Info", "n" },
4259 int x;
4261 for (x=0; x<sizeof(aliases) / sizeof(aliases[0]); x++)
4262 if (!strcasecmp(aliases[x].fullname, name))
4263 return aliases[x].shortname;
4265 return _default;
4268 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
4270 int pass;
4273 * Technically you can place arbitrary whitespace both before and after the ':' in
4274 * a header, although RFC3261 clearly says you shouldn't before, and place just
4275 * one afterwards. If you shouldn't do it, what absolute idiot decided it was
4276 * a good idea to say you can do it, and if you can do it, why in the hell would.
4277 * you say you shouldn't.
4278 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
4279 * and we always allow spaces after that for compatibility.
4281 for (pass = 0; name && pass < 2;pass++) {
4282 int x, len = strlen(name);
4283 for (x=*start; x<req->headers; x++) {
4284 if (!strncasecmp(req->header[x], name, len)) {
4285 char *r = req->header[x] + len; /* skip name */
4286 if (pedanticsipchecking)
4287 r = ast_skip_blanks(r);
4289 if (*r == ':') {
4290 *start = x+1;
4291 return ast_skip_blanks(r+1);
4295 if (pass == 0) /* Try aliases */
4296 name = find_alias(name, NULL);
4299 /* Don't return NULL, so get_header is always a valid pointer */
4300 return "";
4303 /*! \brief Get header from SIP request */
4304 static const char *get_header(const struct sip_request *req, const char *name)
4306 int start = 0;
4307 return __get_header(req, name, &start);
4310 /*! \brief Read RTP from network */
4311 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
4313 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
4314 struct ast_frame *f;
4316 if (!p->rtp) {
4317 /* We have no RTP allocated for this channel */
4318 return &ast_null_frame;
4321 switch(ast->fdno) {
4322 case 0:
4323 f = ast_rtp_read(p->rtp); /* RTP Audio */
4324 break;
4325 case 1:
4326 f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
4327 break;
4328 case 2:
4329 f = ast_rtp_read(p->vrtp); /* RTP Video */
4330 break;
4331 case 3:
4332 f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
4333 break;
4334 case 5:
4335 f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
4336 break;
4337 default:
4338 f = &ast_null_frame;
4340 /* Don't forward RFC2833 if we're not supposed to */
4341 if (f && (f->frametype == AST_FRAME_DTMF) &&
4342 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833))
4343 return &ast_null_frame;
4345 /* We already hold the channel lock */
4346 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
4347 return f;
4349 if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
4350 if (!(f->subclass & p->jointcapability)) {
4351 if (option_debug) {
4352 ast_log(LOG_DEBUG, "Bogus frame of format '%s' received from '%s'!\n",
4353 ast_getformatname(f->subclass), p->owner->name);
4355 return &ast_null_frame;
4357 if (option_debug)
4358 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
4359 p->owner->nativeformats = (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
4360 ast_set_read_format(p->owner, p->owner->readformat);
4361 ast_set_write_format(p->owner, p->owner->writeformat);
4364 if (f && (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
4365 f = ast_dsp_process(p->owner, p->vad, f);
4366 if (f && f->frametype == AST_FRAME_DTMF) {
4367 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && f->subclass == 'f') {
4368 if (option_debug)
4369 ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
4370 *faxdetect = 1;
4371 } else if (option_debug) {
4372 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
4377 return f;
4380 /*! \brief Read SIP RTP from channel */
4381 static struct ast_frame *sip_read(struct ast_channel *ast)
4383 struct ast_frame *fr;
4384 struct sip_pvt *p = ast->tech_pvt;
4385 int faxdetected = FALSE;
4387 ast_mutex_lock(&p->lock);
4388 fr = sip_rtp_read(ast, p, &faxdetected);
4389 p->lastrtprx = time(NULL);
4391 /* If we are NOT bridged to another channel, and we have detected fax tone we issue T38 re-invite to a peer */
4392 /* 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 */
4393 if (faxdetected && ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && (p->t38.state == T38_DISABLED) && !(ast_bridged_channel(ast))) {
4394 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
4395 if (!p->pendinginvite) {
4396 if (option_debug > 2)
4397 ast_log(LOG_DEBUG, "Sending reinvite on SIP (%s) for T.38 negotiation.\n",ast->name);
4398 p->t38.state = T38_LOCAL_REINVITE;
4399 transmit_reinvite_with_t38_sdp(p);
4400 if (option_debug > 1)
4401 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, ast->name);
4403 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
4404 if (option_debug > 2)
4405 ast_log(LOG_DEBUG, "Deferring reinvite on SIP (%s) - it will be re-negotiated for T.38\n", ast->name);
4406 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
4410 /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
4411 if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
4412 fr = &ast_null_frame;
4415 ast_mutex_unlock(&p->lock);
4416 return fr;
4420 /*! \brief Generate 32 byte random string for callid's etc */
4421 static char *generate_random_string(char *buf, size_t size)
4423 long val[4];
4424 int x;
4426 for (x=0; x<4; x++)
4427 val[x] = ast_random();
4428 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
4430 return buf;
4433 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
4434 static void build_callid_pvt(struct sip_pvt *pvt)
4436 char buf[33];
4438 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip));
4440 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
4444 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
4445 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
4447 char buf[33];
4449 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
4451 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
4454 /*! \brief Make our SIP dialog tag */
4455 static void make_our_tag(char *tagbuf, size_t len)
4457 snprintf(tagbuf, len, "as%08lx", ast_random());
4460 /*! \brief Allocate SIP_PVT structure and set defaults */
4461 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
4462 int useglobal_nat, const int intended_method)
4464 struct sip_pvt *p;
4466 if (!(p = ast_calloc(1, sizeof(*p))))
4467 return NULL;
4469 if (ast_string_field_init(p, 512)) {
4470 free(p);
4471 return NULL;
4474 ast_mutex_init(&p->lock);
4476 p->method = intended_method;
4477 p->initid = -1;
4478 p->waitid = -1;
4479 p->autokillid = -1;
4480 p->subscribed = NONE;
4481 p->stateid = -1;
4482 p->prefs = default_prefs; /* Set default codecs for this call */
4484 if (intended_method != SIP_OPTIONS) /* Peerpoke has it's own system */
4485 p->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
4487 if (sin) {
4488 p->sa = *sin;
4489 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
4490 p->ourip = __ourip;
4491 } else
4492 p->ourip = __ourip;
4494 /* Copy global flags to this PVT at setup. */
4495 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
4496 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
4498 ast_set2_flag(&p->flags[0], !recordhistory, SIP_NO_HISTORY);
4500 p->branch = ast_random();
4501 make_our_tag(p->tag, sizeof(p->tag));
4502 p->ocseq = INITIAL_CSEQ;
4504 if (sip_methods[intended_method].need_rtp) {
4505 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
4506 /* If the global videosupport flag is on, we always create a RTP interface for video */
4507 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
4508 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
4509 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
4510 p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
4511 if (!p->rtp || (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)) {
4512 ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n",
4513 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video" : "", strerror(errno));
4514 ast_mutex_destroy(&p->lock);
4515 if (p->chanvars) {
4516 ast_variables_destroy(p->chanvars);
4517 p->chanvars = NULL;
4519 free(p);
4520 return NULL;
4522 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
4523 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
4524 ast_rtp_settos(p->rtp, global_tos_audio);
4525 ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
4526 ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
4527 ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
4528 if (p->vrtp) {
4529 ast_rtp_settos(p->vrtp, global_tos_video);
4530 ast_rtp_setdtmf(p->vrtp, 0);
4531 ast_rtp_setdtmfcompensate(p->vrtp, 0);
4532 ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
4533 ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
4534 ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
4536 if (p->udptl)
4537 ast_udptl_settos(p->udptl, global_tos_audio);
4538 p->maxcallbitrate = default_maxcallbitrate;
4539 p->autoframing = global_autoframing;
4540 ast_rtp_codec_setpref(p->rtp, &p->prefs);
4543 if (useglobal_nat && sin) {
4544 /* Setup NAT structure according to global settings if we have an address */
4545 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
4546 p->recv = *sin;
4547 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
4550 if (p->method != SIP_REGISTER)
4551 ast_string_field_set(p, fromdomain, default_fromdomain);
4552 build_via(p);
4553 if (!callid)
4554 build_callid_pvt(p);
4555 else
4556 ast_string_field_set(p, callid, callid);
4557 /* Assign default music on hold class */
4558 ast_string_field_set(p, mohinterpret, default_mohinterpret);
4559 ast_string_field_set(p, mohsuggest, default_mohsuggest);
4560 p->capability = global_capability;
4561 p->allowtransfer = global_allowtransfer;
4562 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
4563 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
4564 p->noncodeccapability |= AST_RTP_DTMF;
4565 if (p->udptl) {
4566 p->t38.capability = global_t38_capability;
4567 if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY)
4568 p->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
4569 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_FEC)
4570 p->t38.capability |= T38FAX_UDP_EC_FEC;
4571 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_NONE)
4572 p->t38.capability |= T38FAX_UDP_EC_NONE;
4573 p->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
4574 p->t38.jointcapability = p->t38.capability;
4576 ast_string_field_set(p, context, default_context);
4578 /* Add to active dialog list */
4579 ast_mutex_lock(&iflock);
4580 p->next = iflist;
4581 iflist = p;
4582 ast_mutex_unlock(&iflock);
4583 if (option_debug)
4584 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");
4585 return p;
4588 /*! \brief Connect incoming SIP message to current dialog or create new dialog structure
4589 Called by handle_request, sipsock_read */
4590 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
4592 struct sip_pvt *p = NULL;
4593 char *tag = ""; /* note, tag is never NULL */
4594 char totag[128];
4595 char fromtag[128];
4596 const char *callid = get_header(req, "Call-ID");
4597 const char *from = get_header(req, "From");
4598 const char *to = get_header(req, "To");
4599 const char *cseq = get_header(req, "Cseq");
4601 /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
4602 /* get_header always returns non-NULL so we must use ast_strlen_zero() */
4603 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
4604 ast_strlen_zero(from) || ast_strlen_zero(cseq))
4605 return NULL; /* Invalid packet */
4607 if (pedanticsipchecking) {
4608 /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
4609 we need more to identify a branch - so we have to check branch, from
4610 and to tags to identify a call leg.
4611 For Asterisk to behave correctly, you need to turn on pedanticsipchecking
4612 in sip.conf
4614 if (gettag(req, "To", totag, sizeof(totag)))
4615 ast_set_flag(req, SIP_PKT_WITH_TOTAG); /* Used in handle_request/response */
4616 gettag(req, "From", fromtag, sizeof(fromtag));
4618 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
4620 if (option_debug > 4 )
4621 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);
4624 ast_mutex_lock(&iflock);
4625 for (p = iflist; p; p = p->next) {
4626 /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
4627 int found = FALSE;
4628 if (ast_strlen_zero(p->callid))
4629 continue;
4630 if (req->method == SIP_REGISTER)
4631 found = (!strcmp(p->callid, callid));
4632 else {
4633 found = !strcmp(p->callid, callid);
4634 if (pedanticsipchecking && found) {
4635 found = ast_strlen_zero(tag) || ast_strlen_zero(p->theirtag) || !ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED) || !strcmp(p->theirtag, tag);
4639 if (option_debug > 4)
4640 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);
4642 /* If we get a new request within an existing to-tag - check the to tag as well */
4643 if (pedanticsipchecking && found && req->method != SIP_RESPONSE) { /* SIP Request */
4644 if (p->tag[0] == '\0' && totag[0]) {
4645 /* We have no to tag, but they have. Wrong dialog */
4646 found = FALSE;
4647 } else if (totag[0]) { /* Both have tags, compare them */
4648 if (strcmp(totag, p->tag)) {
4649 found = FALSE; /* This is not our packet */
4652 if (!found && option_debug > 4)
4653 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);
4655 if (found) {
4656 /* Found the call */
4657 ast_mutex_lock(&p->lock);
4658 ast_mutex_unlock(&iflock);
4659 return p;
4662 ast_mutex_unlock(&iflock);
4664 /* See if the method is capable of creating a dialog */
4665 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
4666 if (intended_method == SIP_REFER) {
4667 /* We do support REFER, but not outside of a dialog yet */
4668 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
4669 } else if (intended_method == SIP_NOTIFY) {
4670 /* We do not support out-of-dialog NOTIFY either,
4671 like voicemail notification, so cancel that early */
4672 transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
4673 } else {
4674 /* Ok, time to create a new SIP dialog object, a pvt */
4675 if ((p = sip_alloc(callid, sin, 1, intended_method))) {
4676 /* Ok, we've created a dialog, let's go and process it */
4677 ast_mutex_lock(&p->lock);
4678 } else {
4679 /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
4680 getting a dialog from sip_alloc.
4682 Without a dialog we can't retransmit and handle ACKs and all that, but at least
4683 send an error message.
4685 Sorry, we apologize for the inconvienience
4687 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
4688 if (option_debug > 3)
4689 ast_log(LOG_DEBUG, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
4692 return p;
4693 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
4694 /* A method we do not support, let's take it on the volley */
4695 transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
4696 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
4697 /* This is a request outside of a dialog that we don't know about
4698 ...never reply to an ACK!
4700 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
4702 /* We do not respond to responses for dialogs that we don't know about, we just drop
4703 the session quickly */
4705 return p;
4708 /*! \brief Parse register=> line in sip.conf and add to registry */
4709 static int sip_register(char *value, int lineno)
4711 struct sip_registry *reg;
4712 int portnum = 0;
4713 char username[256] = "";
4714 char *hostname=NULL, *secret=NULL, *authuser=NULL;
4715 char *porta=NULL;
4716 char *contact=NULL;
4718 if (!value)
4719 return -1;
4720 ast_copy_string(username, value, sizeof(username));
4721 /* First split around the last '@' then parse the two components. */
4722 hostname = strrchr(username, '@'); /* allow @ in the first part */
4723 if (hostname)
4724 *hostname++ = '\0';
4725 if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
4726 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
4727 return -1;
4729 /* split user[:secret[:authuser]] */
4730 secret = strchr(username, ':');
4731 if (secret) {
4732 *secret++ = '\0';
4733 authuser = strchr(secret, ':');
4734 if (authuser)
4735 *authuser++ = '\0';
4737 /* split host[:port][/contact] */
4738 contact = strchr(hostname, '/');
4739 if (contact)
4740 *contact++ = '\0';
4741 if (ast_strlen_zero(contact))
4742 contact = "s";
4743 porta = strchr(hostname, ':');
4744 if (porta) {
4745 *porta++ = '\0';
4746 portnum = atoi(porta);
4747 if (portnum == 0) {
4748 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
4749 return -1;
4752 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
4753 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
4754 return -1;
4757 if (ast_string_field_init(reg, 256)) {
4758 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
4759 free(reg);
4760 return -1;
4763 regobjs++;
4764 ASTOBJ_INIT(reg);
4765 ast_string_field_set(reg, contact, contact);
4766 if (!ast_strlen_zero(username))
4767 ast_string_field_set(reg, username, username);
4768 if (hostname)
4769 ast_string_field_set(reg, hostname, hostname);
4770 if (authuser)
4771 ast_string_field_set(reg, authuser, authuser);
4772 if (secret)
4773 ast_string_field_set(reg, secret, secret);
4774 reg->expire = -1;
4775 reg->timeout = -1;
4776 reg->refresh = default_expiry;
4777 reg->portno = portnum;
4778 reg->callid_valid = FALSE;
4779 reg->ocseq = INITIAL_CSEQ;
4780 ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
4781 ASTOBJ_UNREF(reg,sip_registry_destroy);
4782 return 0;
4785 /*! \brief Parse multiline SIP headers into one header
4786 This is enabled if pedanticsipchecking is enabled */
4787 static int lws2sws(char *msgbuf, int len)
4789 int h = 0, t = 0;
4790 int lws = 0;
4792 for (; h < len;) {
4793 /* Eliminate all CRs */
4794 if (msgbuf[h] == '\r') {
4795 h++;
4796 continue;
4798 /* Check for end-of-line */
4799 if (msgbuf[h] == '\n') {
4800 /* Check for end-of-message */
4801 if (h + 1 == len)
4802 break;
4803 /* Check for a continuation line */
4804 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
4805 /* Merge continuation line */
4806 h++;
4807 continue;
4809 /* Propagate LF and start new line */
4810 msgbuf[t++] = msgbuf[h++];
4811 lws = 0;
4812 continue;
4814 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
4815 if (lws) {
4816 h++;
4817 continue;
4819 msgbuf[t++] = msgbuf[h++];
4820 lws = 1;
4821 continue;
4823 msgbuf[t++] = msgbuf[h++];
4824 if (lws)
4825 lws = 0;
4827 msgbuf[t] = '\0';
4828 return t;
4831 /*! \brief Parse a SIP message
4832 \note this function is used both on incoming and outgoing packets
4834 static int parse_request(struct sip_request *req)
4836 /* Divide fields by NULL's */
4837 char *c;
4838 int f = 0;
4840 c = req->data;
4842 /* First header starts immediately */
4843 req->header[f] = c;
4844 while(*c) {
4845 if (*c == '\n') {
4846 /* We've got a new header */
4847 *c = 0;
4849 if (sipdebug && option_debug > 3)
4850 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
4851 if (ast_strlen_zero(req->header[f])) {
4852 /* Line by itself means we're now in content */
4853 c++;
4854 break;
4856 if (f >= SIP_MAX_HEADERS - 1) {
4857 ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n");
4858 } else
4859 f++;
4860 req->header[f] = c + 1;
4861 } else if (*c == '\r') {
4862 /* Ignore but eliminate \r's */
4863 *c = 0;
4865 c++;
4867 /* Check for last header */
4868 if (!ast_strlen_zero(req->header[f])) {
4869 if (sipdebug && option_debug > 3)
4870 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
4871 f++;
4873 req->headers = f;
4874 /* Now we process any mime content */
4875 f = 0;
4876 req->line[f] = c;
4877 while(*c) {
4878 if (*c == '\n') {
4879 /* We've got a new line */
4880 *c = 0;
4881 if (sipdebug && option_debug > 3)
4882 ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
4883 if (f >= SIP_MAX_LINES - 1) {
4884 ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n");
4885 } else
4886 f++;
4887 req->line[f] = c + 1;
4888 } else if (*c == '\r') {
4889 /* Ignore and eliminate \r's */
4890 *c = 0;
4892 c++;
4894 /* Check for last line */
4895 if (!ast_strlen_zero(req->line[f]))
4896 f++;
4897 req->lines = f;
4898 if (*c)
4899 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
4900 /* Split up the first line parts */
4901 return determine_firstline_parts(req);
4905 \brief Determine whether a SIP message contains an SDP in its body
4906 \param req the SIP request to process
4907 \return 1 if SDP found, 0 if not found
4909 Also updates req->sdp_start and req->sdp_end to indicate where the SDP
4910 lives in the message body.
4912 static int find_sdp(struct sip_request *req)
4914 const char *content_type;
4915 const char *content_length;
4916 const char *search;
4917 char *boundary;
4918 unsigned int x;
4919 int boundaryisquoted = FALSE;
4920 int found_application_sdp = FALSE;
4921 int found_end_of_headers = FALSE;
4923 content_length = get_header(req, "Content-Length");
4925 if (!ast_strlen_zero(content_length)) {
4926 if (sscanf(content_length, "%ud", &x) != 1) {
4927 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
4928 return 0;
4931 /* Content-Length of zero means there can't possibly be an
4932 SDP here, even if the Content-Type says there is */
4933 if (x == 0)
4934 return 0;
4937 content_type = get_header(req, "Content-Type");
4939 /* if the body contains only SDP, this is easy */
4940 if (!strncasecmp(content_type, "application/sdp", 15)) {
4941 req->sdp_start = 0;
4942 req->sdp_end = req->lines;
4943 return req->lines ? 1 : 0;
4946 /* if it's not multipart/mixed, there cannot be an SDP */
4947 if (strncasecmp(content_type, "multipart/mixed", 15))
4948 return 0;
4950 /* if there is no boundary marker, it's invalid */
4951 if ((search = strcasestr(content_type, ";boundary=")))
4952 search += 10;
4953 else if ((search = strcasestr(content_type, "; boundary=")))
4954 search += 11;
4955 else
4956 return 0;
4958 if (ast_strlen_zero(search))
4959 return 0;
4961 /* If the boundary is quoted with ", remove quote */
4962 if (*search == '\"') {
4963 search++;
4964 boundaryisquoted = TRUE;
4967 /* make a duplicate of the string, with two extra characters
4968 at the beginning */
4969 boundary = ast_strdupa(search - 2);
4970 boundary[0] = boundary[1] = '-';
4971 /* Remove final quote */
4972 if (boundaryisquoted)
4973 boundary[strlen(boundary) - 1] = '\0';
4975 /* search for the boundary marker, the empty line delimiting headers from
4976 sdp part and the end boundry if it exists */
4978 for (x = 0; x < (req->lines ); x++) {
4979 if(!strncasecmp(req->line[x], boundary, strlen(boundary))){
4980 if(found_application_sdp && found_end_of_headers){
4981 req->sdp_end = x-1;
4982 return 1;
4984 found_application_sdp = FALSE;
4986 if(!strcasecmp(req->line[x], "Content-Type: application/sdp"))
4987 found_application_sdp = TRUE;
4989 if(strlen(req->line[x]) == 0 ){
4990 if(found_application_sdp && !found_end_of_headers){
4991 req->sdp_start = x;
4992 found_end_of_headers = TRUE;
4996 if(found_application_sdp && found_end_of_headers) {
4997 req->sdp_end = x;
4998 return TRUE;
5000 return FALSE;
5003 /*! \brief Change hold state for a call */
5004 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
5006 if (global_notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
5007 sip_peer_hold(dialog, holdstate);
5008 if (global_callevents)
5009 manager_event(EVENT_FLAG_CALL, holdstate ? "Hold" : "Unhold",
5010 "Channel: %s\r\n"
5011 "Uniqueid: %s\r\n",
5012 dialog->owner->name,
5013 dialog->owner->uniqueid);
5014 append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data);
5015 if (!holdstate) { /* Put off remote hold */
5016 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
5017 return;
5019 /* No address for RTP, we're on hold */
5021 if (sendonly == 1) /* One directional hold (sendonly/recvonly) */
5022 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
5023 else if (sendonly == 2) /* Inactive stream */
5024 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
5025 else
5026 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
5027 return;
5030 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
5031 If offer is rejected, we will not change any properties of the call
5032 Return 0 on success, a negative value on errors.
5033 Must be called after find_sdp().
5035 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
5037 const char *m; /* SDP media offer */
5038 const char *c;
5039 const char *a;
5040 char host[258];
5041 int len = -1;
5042 int portno = -1; /*!< RTP Audio port number */
5043 int vportno = -1; /*!< RTP Video port number */
5044 int udptlportno = -1;
5045 int peert38capability = 0;
5046 char s[256];
5047 int old = 0;
5049 /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
5050 int peercapability = 0, peernoncodeccapability = 0;
5051 int vpeercapability = 0, vpeernoncodeccapability = 0;
5052 struct sockaddr_in sin; /*!< media socket address */
5053 struct sockaddr_in vsin; /*!< Video socket address */
5055 const char *codecs;
5056 struct hostent *hp; /*!< RTP Audio host IP */
5057 struct hostent *vhp = NULL; /*!< RTP video host IP */
5058 struct ast_hostent audiohp;
5059 struct ast_hostent videohp;
5060 int codec;
5061 int destiterator = 0;
5062 int iterator;
5063 int sendonly = -1;
5064 int numberofports;
5065 struct ast_rtp *newaudiortp, *newvideortp; /* Buffers for codec handling */
5066 int newjointcapability; /* Negotiated capability */
5067 int newpeercapability;
5068 int newnoncodeccapability;
5069 int numberofmediastreams = 0;
5070 int debug = sip_debug_test_pvt(p);
5072 int found_rtpmap_codecs[SDP_MAX_RTPMAP_CODECS];
5073 int last_rtpmap_codec=0;
5075 if (!p->rtp) {
5076 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
5077 return -1;
5080 /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
5081 #ifdef LOW_MEMORY
5082 newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
5083 #else
5084 newaudiortp = alloca(ast_rtp_alloc_size());
5085 #endif
5086 memset(newaudiortp, 0, ast_rtp_alloc_size());
5087 ast_rtp_new_init(newaudiortp);
5088 ast_rtp_pt_clear(newaudiortp);
5090 #ifdef LOW_MEMORY
5091 newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
5092 #else
5093 newvideortp = alloca(ast_rtp_alloc_size());
5094 #endif
5095 memset(newvideortp, 0, ast_rtp_alloc_size());
5096 ast_rtp_new_init(newvideortp);
5097 ast_rtp_pt_clear(newvideortp);
5099 /* Update our last rtprx when we receive an SDP, too */
5100 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
5103 /* Try to find first media stream */
5104 m = get_sdp(req, "m");
5105 destiterator = req->sdp_start;
5106 c = get_sdp_iterate(&destiterator, req, "c");
5107 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
5108 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
5109 return -1;
5112 /* Check for IPv4 address (not IPv6 yet) */
5113 if (sscanf(c, "IN IP4 %256s", host) != 1) {
5114 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
5115 return -1;
5118 /* XXX This could block for a long time, and block the main thread! XXX */
5119 hp = ast_gethostbyname(host, &audiohp);
5120 if (!hp) {
5121 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
5122 return -1;
5124 vhp = hp; /* Copy to video address as default too */
5126 iterator = req->sdp_start;
5127 ast_set_flag(&p->flags[0], SIP_NOVIDEO);
5130 /* Find media streams in this SDP offer */
5131 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
5132 int x;
5133 int audio = FALSE;
5135 numberofports = 1;
5136 if ((sscanf(m, "audio %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
5137 (sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
5138 audio = TRUE;
5139 numberofmediastreams++;
5140 /* Found audio stream in this media definition */
5141 portno = x;
5142 /* Scan through the RTP payload types specified in a "m=" line: */
5143 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
5144 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
5145 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
5146 return -1;
5148 if (debug)
5149 ast_verbose("Found RTP audio format %d\n", codec);
5150 ast_rtp_set_m_type(newaudiortp, codec);
5152 } else if ((sscanf(m, "video %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
5153 (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
5154 /* If it is not audio - is it video ? */
5155 ast_clear_flag(&p->flags[0], SIP_NOVIDEO);
5156 numberofmediastreams++;
5157 vportno = x;
5158 /* Scan through the RTP payload types specified in a "m=" line: */
5159 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
5160 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
5161 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
5162 return -1;
5164 if (debug)
5165 ast_verbose("Found RTP video format %d\n", codec);
5166 ast_rtp_set_m_type(newvideortp, codec);
5168 } else if (p->udptl && ( (sscanf(m, "image %d udptl t38%n", &x, &len) == 1) ||
5169 (sscanf(m, "image %d UDPTL t38%n", &x, &len) == 1) )) {
5170 if (debug)
5171 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
5172 udptlportno = x;
5173 numberofmediastreams++;
5175 if (p->owner && p->lastinvite) {
5176 p->t38.state = T38_PEER_REINVITE; /* T38 Offered in re-invite from remote party */
5177 if (option_debug > 1)
5178 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>" );
5179 } else {
5180 p->t38.state = T38_PEER_DIRECT; /* T38 Offered directly from peer in first invite */
5181 if (option_debug > 1)
5182 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
5184 } else
5185 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
5186 if (numberofports > 1)
5187 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
5190 /* Check for Media-description-level-address for audio */
5191 c = get_sdp_iterate(&destiterator, req, "c");
5192 if (!ast_strlen_zero(c)) {
5193 if (sscanf(c, "IN IP4 %256s", host) != 1) {
5194 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
5195 } else {
5196 /* XXX This could block for a long time, and block the main thread! XXX */
5197 if (audio) {
5198 if ( !(hp = ast_gethostbyname(host, &audiohp))) {
5199 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in secondary c= line, '%s'\n", c);
5200 return -2;
5202 } else if (!(vhp = ast_gethostbyname(host, &videohp))) {
5203 ast_log(LOG_WARNING, "Unable to lookup RTP video host in secondary c= line, '%s'\n", c);
5204 return -2;
5210 if (portno == -1 && vportno == -1 && udptlportno == -1)
5211 /* No acceptable offer found in SDP - we have no ports */
5212 /* Do not change RTP or VRTP if this is a re-invite */
5213 return -2;
5215 if (numberofmediastreams > 2)
5216 /* We have too many fax, audio and/or video media streams, fail this offer */
5217 return -3;
5219 /* RTP addresses and ports for audio and video */
5220 sin.sin_family = AF_INET;
5221 vsin.sin_family = AF_INET;
5222 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
5223 if (vhp)
5224 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
5226 /* Setup UDPTL port number */
5227 if (p->udptl) {
5228 if (udptlportno > 0) {
5229 sin.sin_port = htons(udptlportno);
5230 if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
5231 struct sockaddr_in peer;
5232 ast_rtp_get_peer(p->rtp, &peer);
5233 if (peer.sin_addr.s_addr) {
5234 memcpy(&sin.sin_addr, &peer.sin_addr, sizeof(&sin.sin_addr));
5235 if (debug) {
5236 ast_log(LOG_DEBUG, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_inet_ntoa(sin.sin_addr));
5240 ast_udptl_set_peer(p->udptl, &sin);
5241 if (debug)
5242 ast_log(LOG_DEBUG,"Peer T.38 UDPTL is at port %s:%d\n",ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
5243 } else {
5244 ast_udptl_stop(p->udptl);
5245 if (debug)
5246 ast_log(LOG_DEBUG, "Peer doesn't provide T.38 UDPTL\n");
5251 if (p->rtp) {
5252 if (portno > 0) {
5253 sin.sin_port = htons(portno);
5254 ast_rtp_set_peer(p->rtp, &sin);
5255 if (debug)
5256 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
5257 } else {
5258 if (udptlportno > 0) {
5259 if (debug)
5260 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session. Callid %s\n", p->callid);
5261 } else {
5262 ast_rtp_stop(p->rtp);
5263 if (debug)
5264 ast_verbose("Peer doesn't provide audio. Callid %s\n", p->callid);
5268 /* Setup video port number */
5269 if (vportno != -1)
5270 vsin.sin_port = htons(vportno);
5272 /* Next, scan through each "a=rtpmap:" line, noting each
5273 * specified RTP payload type (with corresponding MIME subtype):
5275 /* XXX This needs to be done per media stream, since it's media stream specific */
5276 iterator = req->sdp_start;
5277 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
5278 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
5279 if (option_debug > 1) {
5280 int breakout = FALSE;
5282 /* If we're debugging, check for unsupported sdp options */
5283 if (!strncasecmp(a, "rtcp:", (size_t) 5)) {
5284 if (debug)
5285 ast_verbose("Got unsupported a:rtcp in SDP offer \n");
5286 breakout = TRUE;
5287 } else if (!strncasecmp(a, "fmtp:", (size_t) 5)) {
5288 /* Format parameters: Not supported */
5289 /* Note: This is used for codec parameters, like bitrate for
5290 G722 and video formats for H263 and H264
5291 See RFC2327 for an example */
5292 if (debug)
5293 ast_verbose("Got unsupported a:fmtp in SDP offer \n");
5294 breakout = TRUE;
5295 } else if (!strncasecmp(a, "framerate:", (size_t) 10)) {
5296 /* Video stuff: Not supported */
5297 if (debug)
5298 ast_verbose("Got unsupported a:framerate in SDP offer \n");
5299 breakout = TRUE;
5300 } else if (!strncasecmp(a, "maxprate:", (size_t) 9)) {
5301 /* Video stuff: Not supported */
5302 if (debug)
5303 ast_verbose("Got unsupported a:maxprate in SDP offer \n");
5304 breakout = TRUE;
5305 } else if (!strncasecmp(a, "crypto:", (size_t) 7)) {
5306 /* SRTP stuff, not yet supported */
5307 if (debug)
5308 ast_verbose("Got unsupported a:crypto in SDP offer \n");
5309 breakout = TRUE;
5311 if (breakout) /* We have a match, skip to next header */
5312 continue;
5314 if (!strcasecmp(a, "sendonly")) {
5315 if (sendonly == -1)
5316 sendonly = 1;
5317 continue;
5318 } else if (!strcasecmp(a, "inactive")) {
5319 if (sendonly == -1)
5320 sendonly = 2;
5321 continue;
5322 } else if (!strcasecmp(a, "sendrecv")) {
5323 if (sendonly == -1)
5324 sendonly = 0;
5325 continue;
5326 } else if (strlen(a) > 5 && !strncasecmp(a, "ptime", 5)) {
5327 char *tmp = strrchr(a, ':');
5328 long int framing = 0;
5329 if (tmp) {
5330 tmp++;
5331 framing = strtol(tmp, NULL, 10);
5332 if (framing == LONG_MIN || framing == LONG_MAX) {
5333 framing = 0;
5334 if (option_debug)
5335 ast_log(LOG_DEBUG, "Can't read framing from SDP: %s\n", a);
5338 if (framing && p->autoframing) {
5339 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
5340 int codec_n;
5341 int format = 0;
5342 for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
5343 format = ast_rtp_codec_getformat(codec_n);
5344 if (!format) /* non-codec or not found */
5345 continue;
5346 if (option_debug)
5347 ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
5348 ast_codec_pref_setsize(pref, format, framing);
5350 ast_rtp_codec_setpref(p->rtp, pref);
5352 continue;
5353 } else if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) == 2) {
5354 /* We have a rtpmap to handle */
5355 int found = FALSE;
5356 /* We should propably check if this is an audio or video codec
5357 so we know where to look */
5359 if (last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
5360 /* Note: should really look at the 'freq' and '#chans' params too */
5361 if(ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
5362 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0) != -1) {
5363 if (debug)
5364 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
5365 found_rtpmap_codecs[last_rtpmap_codec] = codec;
5366 last_rtpmap_codec++;
5367 found = TRUE;
5369 } else if (p->vrtp) {
5370 if(ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0) != -1) {
5371 if (debug)
5372 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
5373 found_rtpmap_codecs[last_rtpmap_codec] = codec;
5374 last_rtpmap_codec++;
5375 found = TRUE;
5378 } else {
5379 if (debug)
5380 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
5383 if (!found) {
5384 /* Remove this codec since it's an unknown media type for us */
5385 /* XXX This is buggy since the media line for audio and video can have the
5386 same numbers. We need to check as described above, but for testing this works... */
5387 ast_rtp_unset_m_type(newaudiortp, codec);
5388 ast_rtp_unset_m_type(newvideortp, codec);
5389 if (debug)
5390 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
5395 if (udptlportno != -1) {
5396 int found = 0, x;
5398 old = 0;
5400 /* Scan trough the a= lines for T38 attributes and set apropriate fileds */
5401 iterator = req->sdp_start;
5402 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
5403 if ((sscanf(a, "T38FaxMaxBuffer:%d", &x) == 1)) {
5404 found = 1;
5405 if (option_debug > 2)
5406 ast_log(LOG_DEBUG, "MaxBufferSize:%d\n",x);
5407 } else if ((sscanf(a, "T38MaxBitRate:%d", &x) == 1)) {
5408 found = 1;
5409 if (option_debug > 2)
5410 ast_log(LOG_DEBUG,"T38MaxBitRate: %d\n",x);
5411 switch (x) {
5412 case 14400:
5413 peert38capability |= T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5414 break;
5415 case 12000:
5416 peert38capability |= T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5417 break;
5418 case 9600:
5419 peert38capability |= T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5420 break;
5421 case 7200:
5422 peert38capability |= T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5423 break;
5424 case 4800:
5425 peert38capability |= T38FAX_RATE_4800 | T38FAX_RATE_2400;
5426 break;
5427 case 2400:
5428 peert38capability |= T38FAX_RATE_2400;
5429 break;
5431 } else if ((sscanf(a, "T38FaxVersion:%d", &x) == 1)) {
5432 found = 1;
5433 if (option_debug > 2)
5434 ast_log(LOG_DEBUG, "FaxVersion: %d\n",x);
5435 if (x == 0)
5436 peert38capability |= T38FAX_VERSION_0;
5437 else if (x == 1)
5438 peert38capability |= T38FAX_VERSION_1;
5439 } else if ((sscanf(a, "T38FaxMaxDatagram:%d", &x) == 1)) {
5440 found = 1;
5441 if (option_debug > 2)
5442 ast_log(LOG_DEBUG, "FaxMaxDatagram: %d\n",x);
5443 ast_udptl_set_far_max_datagram(p->udptl, x);
5444 ast_udptl_set_local_max_datagram(p->udptl, x);
5445 } else if ((sscanf(a, "T38FaxFillBitRemoval:%d", &x) == 1)) {
5446 found = 1;
5447 if (option_debug > 2)
5448 ast_log(LOG_DEBUG, "FillBitRemoval: %d\n",x);
5449 if (x == 1)
5450 peert38capability |= T38FAX_FILL_BIT_REMOVAL;
5451 } else if ((sscanf(a, "T38FaxTranscodingMMR:%d", &x) == 1)) {
5452 found = 1;
5453 if (option_debug > 2)
5454 ast_log(LOG_DEBUG, "Transcoding MMR: %d\n",x);
5455 if (x == 1)
5456 peert38capability |= T38FAX_TRANSCODING_MMR;
5458 if ((sscanf(a, "T38FaxTranscodingJBIG:%d", &x) == 1)) {
5459 found = 1;
5460 if (option_debug > 2)
5461 ast_log(LOG_DEBUG, "Transcoding JBIG: %d\n",x);
5462 if (x == 1)
5463 peert38capability |= T38FAX_TRANSCODING_JBIG;
5464 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
5465 found = 1;
5466 if (option_debug > 2)
5467 ast_log(LOG_DEBUG, "RateManagement: %s\n", s);
5468 if (!strcasecmp(s, "localTCF"))
5469 peert38capability |= T38FAX_RATE_MANAGEMENT_LOCAL_TCF;
5470 else if (!strcasecmp(s, "transferredTCF"))
5471 peert38capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
5472 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
5473 found = 1;
5474 if (option_debug > 2)
5475 ast_log(LOG_DEBUG, "UDP EC: %s\n", s);
5476 if (!strcasecmp(s, "t38UDPRedundancy")) {
5477 peert38capability |= T38FAX_UDP_EC_REDUNDANCY;
5478 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
5479 } else if (!strcasecmp(s, "t38UDPFEC")) {
5480 peert38capability |= T38FAX_UDP_EC_FEC;
5481 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
5482 } else {
5483 peert38capability |= T38FAX_UDP_EC_NONE;
5484 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
5488 if (found) { /* Some cisco equipment returns nothing beside c= and m= lines in 200 OK T38 SDP */
5489 p->t38.peercapability = peert38capability;
5490 p->t38.jointcapability = (peert38capability & 255); /* Put everything beside supported speeds settings */
5491 peert38capability &= (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400);
5492 p->t38.jointcapability |= (peert38capability & p->t38.capability); /* Put the lower of our's and peer's speed */
5494 if (debug)
5495 ast_log(LOG_DEBUG, "Our T38 capability = (%d), peer T38 capability (%d), joint T38 capability (%d)\n",
5496 p->t38.capability,
5497 p->t38.peercapability,
5498 p->t38.jointcapability);
5499 } else {
5500 p->t38.state = T38_DISABLED;
5501 if (option_debug > 2)
5502 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
5505 /* Now gather all of the codecs that we are asked for: */
5506 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
5507 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
5509 newjointcapability = p->capability & (peercapability | vpeercapability);
5510 newpeercapability = (peercapability | vpeercapability);
5511 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
5514 if (debug) {
5515 /* shame on whoever coded this.... */
5516 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE];
5518 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
5519 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
5520 ast_getformatname_multiple(s2, SIPBUFSIZE, newpeercapability),
5521 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
5522 ast_getformatname_multiple(s4, SIPBUFSIZE, newjointcapability));
5524 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
5525 ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
5526 ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
5527 ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
5529 if (!newjointcapability) {
5530 /* If T.38 was not negotiated either, totally bail out... */
5531 if (!p->t38.jointcapability || !udptlportno) {
5532 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
5533 /* Do NOT Change current setting */
5534 return -1;
5535 } else {
5536 if (option_debug > 2)
5537 ast_log(LOG_DEBUG, "Have T.38 but no audio codecs, accepting offer anyway\n");
5538 return 0;
5542 /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
5543 they are acceptable */
5544 p->jointcapability = newjointcapability; /* Our joint codec profile for this call */
5545 p->peercapability = newpeercapability; /* The other sides capability in latest offer */
5546 p->jointnoncodeccapability = newnoncodeccapability; /* DTMF capabilities */
5548 ast_rtp_pt_copy(p->rtp, newaudiortp);
5549 if (p->vrtp)
5550 ast_rtp_pt_copy(p->vrtp, newvideortp);
5552 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
5553 ast_clear_flag(&p->flags[0], SIP_DTMF);
5554 if (newnoncodeccapability & AST_RTP_DTMF) {
5555 /* XXX Would it be reasonable to drop the DSP at this point? XXX */
5556 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
5557 /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
5558 ast_rtp_setdtmf(p->rtp, 1);
5559 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
5560 } else {
5561 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
5565 /* Setup audio port number */
5566 if (p->rtp && sin.sin_port) {
5567 ast_rtp_set_peer(p->rtp, &sin);
5568 if (debug)
5569 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
5572 /* Setup video port number */
5573 if (p->vrtp && vsin.sin_port) {
5574 ast_rtp_set_peer(p->vrtp, &vsin);
5575 if (debug)
5576 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
5579 /* Ok, we're going with this offer */
5580 if (option_debug > 1) {
5581 char buf[SIPBUFSIZE];
5582 ast_log(LOG_DEBUG, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
5585 if (!p->owner) /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
5586 return 0;
5588 if (option_debug > 3)
5589 ast_log(LOG_DEBUG, "We have an owner, now see if we need to change this call\n");
5591 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
5592 if (debug) {
5593 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
5594 ast_log(LOG_DEBUG, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
5595 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
5596 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
5598 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability);
5599 ast_set_read_format(p->owner, p->owner->readformat);
5600 ast_set_write_format(p->owner, p->owner->writeformat);
5603 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
5604 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
5605 /* Activate a re-invite */
5606 ast_queue_frame(p->owner, &ast_null_frame);
5607 } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
5608 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
5609 S_OR(p->mohsuggest, NULL),
5610 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
5611 if (sendonly)
5612 ast_rtp_stop(p->rtp);
5613 /* RTCP needs to go ahead, even if we're on hold!!! */
5614 /* Activate a re-invite */
5615 ast_queue_frame(p->owner, &ast_null_frame);
5618 /* Manager Hold and Unhold events must be generated, if necessary */
5619 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1))
5620 change_hold_state(p, req, FALSE, sendonly);
5621 else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1))
5622 change_hold_state(p, req, TRUE, sendonly);
5623 return 0;
5626 #ifdef LOW_MEMORY
5627 static void ts_ast_rtp_destroy(void *data)
5629 struct ast_rtp *tmp = data;
5630 ast_rtp_destroy(tmp);
5632 #endif
5634 /*! \brief Add header to SIP message */
5635 static int add_header(struct sip_request *req, const char *var, const char *value)
5637 int maxlen = sizeof(req->data) - 4 - req->len; /* 4 bytes are for two \r\n ? */
5639 if (req->headers == SIP_MAX_HEADERS) {
5640 ast_log(LOG_WARNING, "Out of SIP header space\n");
5641 return -1;
5644 if (req->lines) {
5645 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
5646 return -1;
5649 if (maxlen <= 0) {
5650 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
5651 return -1;
5654 req->header[req->headers] = req->data + req->len;
5656 if (compactheaders)
5657 var = find_alias(var, var);
5659 snprintf(req->header[req->headers], maxlen, "%s: %s\r\n", var, value);
5660 req->len += strlen(req->header[req->headers]);
5661 req->headers++;
5663 return 0;
5666 /*! \brief Add 'Content-Length' header to SIP message */
5667 static int add_header_contentLength(struct sip_request *req, int len)
5669 char clen[10];
5671 snprintf(clen, sizeof(clen), "%d", len);
5672 return add_header(req, "Content-Length", clen);
5675 /*! \brief Add content (not header) to SIP message */
5676 static int add_line(struct sip_request *req, const char *line)
5678 if (req->lines == SIP_MAX_LINES) {
5679 ast_log(LOG_WARNING, "Out of SIP line space\n");
5680 return -1;
5682 if (!req->lines) {
5683 /* Add extra empty return */
5684 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
5685 req->len += strlen(req->data + req->len);
5687 if (req->len >= sizeof(req->data) - 4) {
5688 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
5689 return -1;
5691 req->line[req->lines] = req->data + req->len;
5692 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
5693 req->len += strlen(req->line[req->lines]);
5694 req->lines++;
5695 return 0;
5698 /*! \brief Copy one header field from one request to another */
5699 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
5701 const char *tmp = get_header(orig, field);
5703 if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
5704 return add_header(req, field, tmp);
5705 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
5706 return -1;
5709 /*! \brief Copy all headers from one request to another */
5710 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
5712 int start = 0;
5713 int copied = 0;
5714 for (;;) {
5715 const char *tmp = __get_header(orig, field, &start);
5717 if (ast_strlen_zero(tmp))
5718 break;
5719 /* Add what we're responding to */
5720 add_header(req, field, tmp);
5721 copied++;
5723 return copied ? 0 : -1;
5726 /*! \brief Copy SIP VIA Headers from the request to the response
5727 \note If the client indicates that it wishes to know the port we received from,
5728 it adds ;rport without an argument to the topmost via header. We need to
5729 add the port number (from our point of view) to that parameter.
5730 We always add ;received=<ip address> to the topmost via header.
5731 Received: RFC 3261, rport RFC 3581 */
5732 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
5734 int copied = 0;
5735 int start = 0;
5737 for (;;) {
5738 char new[512];
5739 const char *oh = __get_header(orig, field, &start);
5741 if (ast_strlen_zero(oh))
5742 break;
5744 if (!copied) { /* Only check for empty rport in topmost via header */
5745 char leftmost[512], *others, *rport;
5747 /* Only work on leftmost value */
5748 ast_copy_string(leftmost, oh, sizeof(leftmost));
5749 others = strchr(leftmost, ',');
5750 if (others)
5751 *others++ = '\0';
5753 /* Find ;rport; (empty request) */
5754 rport = strstr(leftmost, ";rport");
5755 if (rport && *(rport+6) == '=')
5756 rport = NULL; /* We already have a parameter to rport */
5758 /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting) */
5759 if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
5760 /* We need to add received port - rport */
5761 char *end;
5763 rport = strstr(leftmost, ";rport");
5765 if (rport) {
5766 end = strchr(rport + 1, ';');
5767 if (end)
5768 memmove(rport, end, strlen(end) + 1);
5769 else
5770 *rport = '\0';
5773 /* Add rport to first VIA header if requested */
5774 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
5775 leftmost, ast_inet_ntoa(p->recv.sin_addr),
5776 ntohs(p->recv.sin_port),
5777 others ? "," : "", others ? others : "");
5778 } else {
5779 /* We should *always* add a received to the topmost via */
5780 snprintf(new, sizeof(new), "%s;received=%s%s%s",
5781 leftmost, ast_inet_ntoa(p->recv.sin_addr),
5782 others ? "," : "", others ? others : "");
5784 oh = new; /* the header to copy */
5785 } /* else add the following via headers untouched */
5786 add_header(req, field, oh);
5787 copied++;
5789 if (!copied) {
5790 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
5791 return -1;
5793 return 0;
5796 /*! \brief Add route header into request per learned route */
5797 static void add_route(struct sip_request *req, struct sip_route *route)
5799 char r[SIPBUFSIZE*2], *p;
5800 int n, rem = sizeof(r);
5802 if (!route)
5803 return;
5805 p = r;
5806 for (;route ; route = route->next) {
5807 n = strlen(route->hop);
5808 if (rem < n+3) /* we need room for ",<route>" */
5809 break;
5810 if (p != r) { /* add a separator after fist route */
5811 *p++ = ',';
5812 --rem;
5814 *p++ = '<';
5815 ast_copy_string(p, route->hop, rem); /* cannot fail */
5816 p += n;
5817 *p++ = '>';
5818 rem -= (n+2);
5820 *p = '\0';
5821 add_header(req, "Route", r);
5824 /*! \brief Set destination from SIP URI */
5825 static void set_destination(struct sip_pvt *p, char *uri)
5827 char *h, *maddr, hostname[256];
5828 int port, hn;
5829 struct hostent *hp;
5830 struct ast_hostent ahp;
5831 int debug=sip_debug_test_pvt(p);
5833 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
5834 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
5836 if (debug)
5837 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
5839 /* Find and parse hostname */
5840 h = strchr(uri, '@');
5841 if (h)
5842 ++h;
5843 else {
5844 h = uri;
5845 if (strncasecmp(h, "sip:", 4) == 0)
5846 h += 4;
5847 else if (strncasecmp(h, "sips:", 5) == 0)
5848 h += 5;
5850 hn = strcspn(h, ":;>") + 1;
5851 if (hn > sizeof(hostname))
5852 hn = sizeof(hostname);
5853 ast_copy_string(hostname, h, hn);
5854 /* XXX bug here if string has been trimmed to sizeof(hostname) */
5855 h += hn - 1;
5857 /* Is "port" present? if not default to STANDARD_SIP_PORT */
5858 if (*h == ':') {
5859 /* Parse port */
5860 ++h;
5861 port = strtol(h, &h, 10);
5863 else
5864 port = STANDARD_SIP_PORT;
5866 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
5867 maddr = strstr(h, "maddr=");
5868 if (maddr) {
5869 maddr += 6;
5870 hn = strspn(maddr, "0123456789.") + 1;
5871 if (hn > sizeof(hostname))
5872 hn = sizeof(hostname);
5873 ast_copy_string(hostname, maddr, hn);
5876 hp = ast_gethostbyname(hostname, &ahp);
5877 if (hp == NULL) {
5878 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
5879 return;
5881 p->sa.sin_family = AF_INET;
5882 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
5883 p->sa.sin_port = htons(port);
5884 if (debug)
5885 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
5888 /*! \brief Initialize SIP response, based on SIP request */
5889 static int init_resp(struct sip_request *resp, const char *msg)
5891 /* Initialize a response */
5892 memset(resp, 0, sizeof(*resp));
5893 resp->method = SIP_RESPONSE;
5894 resp->header[0] = resp->data;
5895 snprintf(resp->header[0], sizeof(resp->data), "SIP/2.0 %s\r\n", msg);
5896 resp->len = strlen(resp->header[0]);
5897 resp->headers++;
5898 return 0;
5901 /*! \brief Initialize SIP request */
5902 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
5904 /* Initialize a request */
5905 memset(req, 0, sizeof(*req));
5906 req->method = sipmethod;
5907 req->header[0] = req->data;
5908 snprintf(req->header[0], sizeof(req->data), "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
5909 req->len = strlen(req->header[0]);
5910 req->headers++;
5911 return 0;
5915 /*! \brief Prepare SIP response packet */
5916 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
5918 char newto[256];
5919 const char *ot;
5921 init_resp(resp, msg);
5922 copy_via_headers(p, resp, req, "Via");
5923 if (msg[0] == '1' || msg[0] == '2')
5924 copy_all_header(resp, req, "Record-Route");
5925 copy_header(resp, req, "From");
5926 ot = get_header(req, "To");
5927 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
5928 /* Add the proper tag if we don't have it already. If they have specified
5929 their tag, use it. Otherwise, use our own tag */
5930 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
5931 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
5932 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
5933 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
5934 else
5935 ast_copy_string(newto, ot, sizeof(newto));
5936 ot = newto;
5938 add_header(resp, "To", ot);
5939 copy_header(resp, req, "Call-ID");
5940 copy_header(resp, req, "CSeq");
5941 if (!ast_strlen_zero(global_useragent))
5942 add_header(resp, "User-Agent", global_useragent);
5943 add_header(resp, "Allow", ALLOWED_METHODS);
5944 add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
5945 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
5946 /* For registration responses, we also need expiry and
5947 contact info */
5948 char tmp[256];
5950 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
5951 add_header(resp, "Expires", tmp);
5952 if (p->expiry) { /* Only add contact if we have an expiry time */
5953 char contact[SIPBUFSIZE];
5954 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
5955 add_header(resp, "Contact", contact); /* Not when we unregister */
5957 } else if (msg[0] != '4' && !ast_strlen_zero(p->our_contact)) {
5958 add_header(resp, "Contact", p->our_contact);
5960 return 0;
5963 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
5964 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
5966 struct sip_request *orig = &p->initreq;
5967 char stripped[80];
5968 char tmp[80];
5969 char newto[256];
5970 const char *c;
5971 const char *ot, *of;
5972 int is_strict = FALSE; /*!< Strict routing flag */
5974 memset(req, 0, sizeof(struct sip_request));
5976 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
5978 if (!seqno) {
5979 p->ocseq++;
5980 seqno = p->ocseq;
5983 if (newbranch) {
5984 p->branch ^= ast_random();
5985 build_via(p);
5988 /* Check for strict or loose router */
5989 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop,";lr") == NULL) {
5990 is_strict = TRUE;
5991 if (sipdebug)
5992 ast_log(LOG_DEBUG, "Strict routing enforced for session %s\n", p->callid);
5995 if (sipmethod == SIP_CANCEL)
5996 c = p->initreq.rlPart2; /* Use original URI */
5997 else if (sipmethod == SIP_ACK) {
5998 /* Use URI from Contact: in 200 OK (if INVITE)
5999 (we only have the contacturi on INVITEs) */
6000 if (!ast_strlen_zero(p->okcontacturi))
6001 c = is_strict ? p->route->hop : p->okcontacturi;
6002 else
6003 c = p->initreq.rlPart2;
6004 } else if (!ast_strlen_zero(p->okcontacturi))
6005 c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
6006 else if (!ast_strlen_zero(p->uri))
6007 c = p->uri;
6008 else {
6009 char *n;
6010 /* We have no URI, use To: or From: header as URI (depending on direction) */
6011 ast_copy_string(stripped, get_header(orig, (ast_test_flag(&p->flags[0], SIP_OUTGOING)) ? "To" : "From"),
6012 sizeof(stripped));
6013 n = get_in_brackets(stripped);
6014 c = strsep(&n, ";"); /* trim ; and beyond */
6016 init_req(req, sipmethod, c);
6018 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
6020 add_header(req, "Via", p->via);
6021 if (p->route) {
6022 set_destination(p, p->route->hop);
6023 add_route(req, is_strict ? p->route->next : p->route);
6026 ot = get_header(orig, "To");
6027 of = get_header(orig, "From");
6029 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
6030 as our original request, including tag (or presumably lack thereof) */
6031 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
6032 /* Add the proper tag if we don't have it already. If they have specified
6033 their tag, use it. Otherwise, use our own tag */
6034 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_strlen_zero(p->theirtag))
6035 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
6036 else if (!ast_test_flag(&p->flags[0], SIP_OUTGOING))
6037 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
6038 else
6039 snprintf(newto, sizeof(newto), "%s", ot);
6040 ot = newto;
6043 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
6044 add_header(req, "From", of);
6045 add_header(req, "To", ot);
6046 } else {
6047 add_header(req, "From", ot);
6048 add_header(req, "To", of);
6050 /* Do not add Contact for MESSAGE, BYE and Cancel requests */
6051 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
6052 add_header(req, "Contact", p->our_contact);
6054 copy_header(req, orig, "Call-ID");
6055 add_header(req, "CSeq", tmp);
6057 if (!ast_strlen_zero(global_useragent))
6058 add_header(req, "User-Agent", global_useragent);
6059 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
6061 if (!ast_strlen_zero(p->rpid))
6062 add_header(req, "Remote-Party-ID", p->rpid);
6064 return 0;
6067 /*! \brief Base transmit response function */
6068 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
6070 struct sip_request resp;
6071 int seqno = 0;
6073 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
6074 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
6075 return -1;
6077 respprep(&resp, p, msg, req);
6078 add_header_contentLength(&resp, 0);
6079 /* If we are cancelling an incoming invite for some reason, add information
6080 about the reason why we are doing this in clear text */
6081 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
6082 char buf[10];
6084 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
6085 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
6086 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
6088 return send_response(p, &resp, reliable, seqno);
6091 static void temp_pvt_cleanup(void *data)
6093 struct sip_pvt *p = data;
6095 ast_string_field_free_memory(p);
6097 free(data);
6100 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
6101 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)
6103 struct sip_pvt *p = NULL;
6105 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
6106 ast_log(LOG_NOTICE, "Failed to get temporary pvt\n");
6107 return -1;
6110 /* if the structure was just allocated, initialize it */
6111 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
6112 ast_set_flag(&p->flags[0], SIP_NO_HISTORY);
6113 if (ast_string_field_init(p, 512))
6114 return -1;
6117 /* Initialize the bare minimum */
6118 p->method = intended_method;
6120 if (sin) {
6121 p->sa = *sin;
6122 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
6123 p->ourip = __ourip;
6124 } else
6125 p->ourip = __ourip;
6127 p->branch = ast_random();
6128 make_our_tag(p->tag, sizeof(p->tag));
6129 p->ocseq = INITIAL_CSEQ;
6131 if (useglobal_nat && sin) {
6132 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
6133 p->recv = *sin;
6134 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
6136 check_via(p, req);
6138 ast_string_field_set(p, fromdomain, default_fromdomain);
6139 build_via(p);
6140 ast_string_field_set(p, callid, callid);
6142 /* Use this temporary pvt structure to send the message */
6143 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
6145 /* Free the string fields, but not the pool space */
6146 ast_string_field_reset_all(p);
6148 return 0;
6151 /*! \brief Transmit response, no retransmits */
6152 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
6154 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
6157 /*! \brief Transmit response, no retransmits */
6158 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
6160 struct sip_request resp;
6161 respprep(&resp, p, msg, req);
6162 append_date(&resp);
6163 add_header(&resp, "Unsupported", unsupported);
6164 add_header_contentLength(&resp, 0);
6165 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
6168 /*! \brief Transmit response, Make sure you get an ACK
6169 This is only used for responses to INVITEs, where we need to make sure we get an ACK
6171 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
6173 return __transmit_response(p, msg, req, XMIT_CRITICAL);
6176 /*! \brief Append date to SIP message */
6177 static void append_date(struct sip_request *req)
6179 char tmpdat[256];
6180 struct tm tm;
6181 time_t t = time(NULL);
6183 gmtime_r(&t, &tm);
6184 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
6185 add_header(req, "Date", tmpdat);
6188 /*! \brief Append date and content length before transmitting response */
6189 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
6191 struct sip_request resp;
6192 respprep(&resp, p, msg, req);
6193 append_date(&resp);
6194 add_header_contentLength(&resp, 0);
6195 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
6198 /*! \brief Append Accept header, content length before transmitting response */
6199 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
6201 struct sip_request resp;
6202 respprep(&resp, p, msg, req);
6203 add_header(&resp, "Accept", "application/sdp");
6204 add_header_contentLength(&resp, 0);
6205 return send_response(p, &resp, reliable, 0);
6208 /*! \brief Respond with authorization request */
6209 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)
6211 struct sip_request resp;
6212 char tmp[512];
6213 int seqno = 0;
6215 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
6216 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
6217 return -1;
6219 /* Stale means that they sent us correct authentication, but
6220 based it on an old challenge (nonce) */
6221 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
6222 respprep(&resp, p, msg, req);
6223 add_header(&resp, header, tmp);
6224 add_header_contentLength(&resp, 0);
6225 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
6226 return send_response(p, &resp, reliable, seqno);
6229 /*! \brief Add text body to SIP message */
6230 static int add_text(struct sip_request *req, const char *text)
6232 /* XXX Convert \n's to \r\n's XXX */
6233 add_header(req, "Content-Type", "text/plain");
6234 add_header_contentLength(req, strlen(text));
6235 add_line(req, text);
6236 return 0;
6239 /*! \brief Add DTMF INFO tone to sip message */
6240 /* Always adds default duration 250 ms, regardless of what came in over the line */
6241 static int add_digit(struct sip_request *req, char digit, unsigned int duration)
6243 char tmp[256];
6245 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
6246 add_header(req, "Content-Type", "application/dtmf-relay");
6247 add_header_contentLength(req, strlen(tmp));
6248 add_line(req, tmp);
6249 return 0;
6252 /*! \brief add XML encoded media control with update
6253 \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
6254 static int add_vidupdate(struct sip_request *req)
6256 const char *xml_is_a_huge_waste_of_space =
6257 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
6258 " <media_control>\r\n"
6259 " <vc_primitive>\r\n"
6260 " <to_encoder>\r\n"
6261 " <picture_fast_update>\r\n"
6262 " </picture_fast_update>\r\n"
6263 " </to_encoder>\r\n"
6264 " </vc_primitive>\r\n"
6265 " </media_control>\r\n";
6266 add_header(req, "Content-Type", "application/media_control+xml");
6267 add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
6268 add_line(req, xml_is_a_huge_waste_of_space);
6269 return 0;
6272 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
6273 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
6274 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
6275 int debug, int *min_packet_size)
6277 int rtp_code;
6278 struct ast_format_list fmt;
6281 if (debug)
6282 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
6283 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
6284 return;
6286 if (p->rtp) {
6287 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
6288 fmt = ast_codec_pref_getsize(pref, codec);
6289 } 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 */
6290 return;
6291 ast_build_string(m_buf, m_size, " %d", rtp_code);
6292 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
6293 ast_rtp_lookup_mime_subtype(1, codec,
6294 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
6295 sample_rate);
6296 if (codec == AST_FORMAT_G729A) {
6297 /* Indicate that we don't support VAD (G.729 annex B) */
6298 ast_build_string(a_buf, a_size, "a=fmtp:%d annexb=no\r\n", rtp_code);
6299 } else if (codec == AST_FORMAT_G723_1) {
6300 /* Indicate that we don't support VAD (G.723.1 annex A) */
6301 ast_build_string(a_buf, a_size, "a=fmtp:%d annexa=no\r\n", rtp_code);
6302 } else if (codec == AST_FORMAT_ILBC) {
6303 /* Add information about us using only 20/30 ms packetization */
6304 ast_build_string(a_buf, a_size, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
6307 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
6308 *min_packet_size = fmt.cur_ms;
6310 /* Our first codec packetization processed cannot be less than zero */
6311 if ((*min_packet_size) == 0 && fmt.cur_ms)
6312 *min_packet_size = fmt.cur_ms;
6315 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
6316 static int t38_get_rate(int t38cap)
6318 int maxrate = (t38cap & (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400));
6320 if (maxrate & T38FAX_RATE_14400) {
6321 if (option_debug > 1)
6322 ast_log(LOG_DEBUG, "T38MaxFaxRate 14400 found\n");
6323 return 14400;
6324 } else if (maxrate & T38FAX_RATE_12000) {
6325 if (option_debug > 1)
6326 ast_log(LOG_DEBUG, "T38MaxFaxRate 12000 found\n");
6327 return 12000;
6328 } else if (maxrate & T38FAX_RATE_9600) {
6329 if (option_debug > 1)
6330 ast_log(LOG_DEBUG, "T38MaxFaxRate 9600 found\n");
6331 return 9600;
6332 } else if (maxrate & T38FAX_RATE_7200) {
6333 if (option_debug > 1)
6334 ast_log(LOG_DEBUG, "T38MaxFaxRate 7200 found\n");
6335 return 7200;
6336 } else if (maxrate & T38FAX_RATE_4800) {
6337 if (option_debug > 1)
6338 ast_log(LOG_DEBUG, "T38MaxFaxRate 4800 found\n");
6339 return 4800;
6340 } else if (maxrate & T38FAX_RATE_2400) {
6341 if (option_debug > 1)
6342 ast_log(LOG_DEBUG, "T38MaxFaxRate 2400 found\n");
6343 return 2400;
6344 } else {
6345 if (option_debug > 1)
6346 ast_log(LOG_DEBUG, "Strange, T38MaxFaxRate NOT found in peers T38 SDP.\n");
6347 return 0;
6351 /*! \brief Add T.38 Session Description Protocol message */
6352 static int add_t38_sdp(struct sip_request *resp, struct sip_pvt *p)
6354 int len = 0;
6355 int x = 0;
6356 struct sockaddr_in udptlsin;
6357 char v[256] = "";
6358 char s[256] = "";
6359 char o[256] = "";
6360 char c[256] = "";
6361 char t[256] = "";
6362 char m_modem[256];
6363 char a_modem[1024];
6364 char *m_modem_next = m_modem;
6365 size_t m_modem_left = sizeof(m_modem);
6366 char *a_modem_next = a_modem;
6367 size_t a_modem_left = sizeof(a_modem);
6368 struct sockaddr_in udptldest = { 0, };
6369 int debug;
6371 debug = sip_debug_test_pvt(p);
6372 len = 0;
6373 if (!p->udptl) {
6374 ast_log(LOG_WARNING, "No way to add SDP without an UDPTL structure\n");
6375 return -1;
6378 if (!p->sessionid) {
6379 p->sessionid = getpid();
6380 p->sessionversion = p->sessionid;
6381 } else
6382 p->sessionversion++;
6384 /* Our T.38 end is */
6385 ast_udptl_get_us(p->udptl, &udptlsin);
6387 /* Determine T.38 UDPTL destination */
6388 if (p->udptlredirip.sin_addr.s_addr) {
6389 udptldest.sin_port = p->udptlredirip.sin_port;
6390 udptldest.sin_addr = p->udptlredirip.sin_addr;
6391 } else {
6392 udptldest.sin_addr = p->ourip;
6393 udptldest.sin_port = udptlsin.sin_port;
6396 if (debug)
6397 ast_log(LOG_DEBUG, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(udptlsin.sin_port));
6399 /* We break with the "recommendation" and send our IP, in order that our
6400 peer doesn't have to ast_gethostbyname() us */
6402 if (debug) {
6403 ast_log(LOG_DEBUG, "Our T38 capability (%d), peer T38 capability (%d), joint capability (%d)\n",
6404 p->t38.capability,
6405 p->t38.peercapability,
6406 p->t38.jointcapability);
6408 snprintf(v, sizeof(v), "v=0\r\n");
6409 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(udptldest.sin_addr));
6410 snprintf(s, sizeof(s), "s=session\r\n");
6411 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(udptldest.sin_addr));
6412 snprintf(t, sizeof(t), "t=0 0\r\n");
6413 ast_build_string(&m_modem_next, &m_modem_left, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
6415 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_0)
6416 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:0\r\n");
6417 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_1)
6418 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:1\r\n");
6419 if ((x = t38_get_rate(p->t38.jointcapability)))
6420 ast_build_string(&a_modem_next, &a_modem_left, "a=T38MaxBitRate:%d\r\n",x);
6421 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxFillBitRemoval:%d\r\n", (p->t38.jointcapability & T38FAX_FILL_BIT_REMOVAL) ? 1 : 0);
6422 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingMMR:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_MMR) ? 1 : 0);
6423 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingJBIG:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_JBIG) ? 1 : 0);
6424 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxRateManagement:%s\r\n", (p->t38.jointcapability & T38FAX_RATE_MANAGEMENT_LOCAL_TCF) ? "localTCF" : "transferredTCF");
6425 x = ast_udptl_get_local_max_datagram(p->udptl);
6426 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxBuffer:%d\r\n",x);
6427 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxDatagram:%d\r\n",x);
6428 if (p->t38.jointcapability != T38FAX_UDP_EC_NONE)
6429 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxUdpEC:%s\r\n", (p->t38.jointcapability & T38FAX_UDP_EC_REDUNDANCY) ? "t38UDPRedundancy" : "t38UDPFEC");
6430 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m_modem) + strlen(a_modem);
6431 add_header(resp, "Content-Type", "application/sdp");
6432 add_header_contentLength(resp, len);
6433 add_line(resp, v);
6434 add_line(resp, o);
6435 add_line(resp, s);
6436 add_line(resp, c);
6437 add_line(resp, t);
6438 add_line(resp, m_modem);
6439 add_line(resp, a_modem);
6441 /* Update lastrtprx when we send our SDP */
6442 p->lastrtprx = p->lastrtptx = time(NULL);
6444 return 0;
6448 /*! \brief Add RFC 2833 DTMF offer to SDP */
6449 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
6450 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
6451 int debug)
6453 int rtp_code;
6455 if (debug)
6456 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
6457 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
6458 return;
6460 ast_build_string(m_buf, m_size, " %d", rtp_code);
6461 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
6462 ast_rtp_lookup_mime_subtype(0, format, 0),
6463 sample_rate);
6464 if (format == AST_RTP_DTMF)
6465 /* Indicate we support DTMF and FLASH... */
6466 ast_build_string(a_buf, a_size, "a=fmtp:%d 0-16\r\n", rtp_code);
6470 * \note G.722 actually is supposed to specified as 8 kHz, even though it is
6471 * really 16 kHz. Update this macro for other formats as they are added in
6472 * the future.
6474 #define SDP_SAMPLE_RATE(x) 8000
6476 /*! \brief Add Session Description Protocol message */
6477 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p)
6479 int len = 0;
6480 int alreadysent = 0;
6482 struct sockaddr_in sin;
6483 struct sockaddr_in vsin;
6484 struct sockaddr_in dest;
6485 struct sockaddr_in vdest = { 0, };
6487 /* SDP fields */
6488 char *version = "v=0\r\n"; /* Protocol version */
6489 char *subject = "s=session\r\n"; /* Subject of the session */
6490 char owner[256]; /* Session owner/creator */
6491 char connection[256]; /* Connection data */
6492 char *stime = "t=0 0\r\n"; /* Time the session is active */
6493 char bandwidth[256] = ""; /* Max bitrate */
6494 char *hold;
6495 char m_audio[256]; /* Media declaration line for audio */
6496 char m_video[256]; /* Media declaration line for video */
6497 char a_audio[1024]; /* Attributes for audio */
6498 char a_video[1024]; /* Attributes for video */
6499 char *m_audio_next = m_audio;
6500 char *m_video_next = m_video;
6501 size_t m_audio_left = sizeof(m_audio);
6502 size_t m_video_left = sizeof(m_video);
6503 char *a_audio_next = a_audio;
6504 char *a_video_next = a_video;
6505 size_t a_audio_left = sizeof(a_audio);
6506 size_t a_video_left = sizeof(a_video);
6508 int x;
6509 int capability;
6510 int needvideo = FALSE;
6511 int debug = sip_debug_test_pvt(p);
6512 int min_audio_packet_size = 0;
6513 int min_video_packet_size = 0;
6515 m_video[0] = '\0'; /* Reset the video media string if it's not needed */
6517 if (!p->rtp) {
6518 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
6519 return AST_FAILURE;
6522 /* Set RTP Session ID and version */
6523 if (!p->sessionid) {
6524 p->sessionid = getpid();
6525 p->sessionversion = p->sessionid;
6526 } else
6527 p->sessionversion++;
6529 /* Get our addresses */
6530 ast_rtp_get_us(p->rtp, &sin);
6531 if (p->vrtp)
6532 ast_rtp_get_us(p->vrtp, &vsin);
6534 /* Is this a re-invite to move the media out, then use the original offer from caller */
6535 if (p->redirip.sin_addr.s_addr) {
6536 dest.sin_port = p->redirip.sin_port;
6537 dest.sin_addr = p->redirip.sin_addr;
6538 } else {
6539 dest.sin_addr = p->ourip;
6540 dest.sin_port = sin.sin_port;
6543 capability = p->jointcapability;
6546 if (option_debug > 1) {
6547 char codecbuf[SIPBUFSIZE];
6548 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");
6549 ast_log(LOG_DEBUG, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
6552 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
6553 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_RTP)) {
6554 ast_build_string(&m_audio_next, &m_audio_left, " %d", 191);
6555 ast_build_string(&a_audio_next, &a_audio_left, "a=rtpmap:%d %s/%d\r\n", 191, "t38", 8000);
6557 #endif
6559 /* Check if we need video in this call */
6560 if ((capability & AST_FORMAT_VIDEO_MASK) && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
6561 if (p->vrtp) {
6562 needvideo = TRUE;
6563 if (option_debug > 1)
6564 ast_log(LOG_DEBUG, "This call needs video offers!\n");
6565 } else if (option_debug > 1)
6566 ast_log(LOG_DEBUG, "This call needs video offers, but there's no video support enabled!\n");
6570 /* Ok, we need video. Let's add what we need for video and set codecs.
6571 Video is handled differently than audio since we can not transcode. */
6572 if (needvideo) {
6573 /* Determine video destination */
6574 if (p->vredirip.sin_addr.s_addr) {
6575 vdest.sin_addr = p->vredirip.sin_addr;
6576 vdest.sin_port = p->vredirip.sin_port;
6577 } else {
6578 vdest.sin_addr = p->ourip;
6579 vdest.sin_port = vsin.sin_port;
6581 ast_build_string(&m_video_next, &m_video_left, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
6583 /* Build max bitrate string */
6584 if (p->maxcallbitrate)
6585 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
6586 if (debug)
6587 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(vsin.sin_port));
6590 if (debug)
6591 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(sin.sin_port));
6593 /* Start building generic SDP headers */
6595 /* We break with the "recommendation" and send our IP, in order that our
6596 peer doesn't have to ast_gethostbyname() us */
6598 snprintf(owner, sizeof(owner), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
6599 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
6600 ast_build_string(&m_audio_next, &m_audio_left, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
6602 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
6603 hold = "a=recvonly\r\n";
6604 else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
6605 hold = "a=inactive\r\n";
6606 else
6607 hold = "a=sendrecv\r\n";
6609 /* Now, start adding audio codecs. These are added in this order:
6610 - First what was requested by the calling channel
6611 - Then preferences in order from sip.conf device config for this peer/user
6612 - Then other codecs in capabilities, including video
6615 /* Prefer the audio codec we were requested to use, first, no matter what
6616 Note that p->prefcodec can include video codecs, so mask them out
6618 if (capability & p->prefcodec) {
6619 int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
6621 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
6622 &m_audio_next, &m_audio_left,
6623 &a_audio_next, &a_audio_left,
6624 debug, &min_audio_packet_size);
6625 alreadysent |= codec;
6628 /* Start by sending our preferred audio codecs */
6629 for (x = 0; x < 32; x++) {
6630 int codec;
6632 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
6633 break;
6635 if (!(capability & codec))
6636 continue;
6638 if (alreadysent & codec)
6639 continue;
6641 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
6642 &m_audio_next, &m_audio_left,
6643 &a_audio_next, &a_audio_left,
6644 debug, &min_audio_packet_size);
6645 alreadysent |= codec;
6648 /* Now send any other common audio and video codecs, and non-codec formats: */
6649 for (x = 1; x <= (needvideo ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
6650 if (!(capability & x)) /* Codec not requested */
6651 continue;
6653 if (alreadysent & x) /* Already added to SDP */
6654 continue;
6656 if (x <= AST_FORMAT_MAX_AUDIO)
6657 add_codec_to_sdp(p, x, SDP_SAMPLE_RATE(x),
6658 &m_audio_next, &m_audio_left,
6659 &a_audio_next, &a_audio_left,
6660 debug, &min_audio_packet_size);
6661 else
6662 add_codec_to_sdp(p, x, 90000,
6663 &m_video_next, &m_video_left,
6664 &a_video_next, &a_video_left,
6665 debug, &min_video_packet_size);
6668 /* Now add DTMF RFC2833 telephony-event as a codec */
6669 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
6670 if (!(p->jointnoncodeccapability & x))
6671 continue;
6673 add_noncodec_to_sdp(p, x, 8000,
6674 &m_audio_next, &m_audio_left,
6675 &a_audio_next, &a_audio_left,
6676 debug);
6679 if (option_debug > 2)
6680 ast_log(LOG_DEBUG, "-- Done with adding codecs to SDP\n");
6682 if (!p->owner || !ast_internal_timing_enabled(p->owner))
6683 ast_build_string(&a_audio_next, &a_audio_left, "a=silenceSupp:off - - - -\r\n");
6685 if (min_audio_packet_size)
6686 ast_build_string(&a_audio_next, &a_audio_left, "a=ptime:%d\r\n", min_audio_packet_size);
6688 if (min_video_packet_size)
6689 ast_build_string(&a_video_next, &a_video_left, "a=ptime:%d\r\n", min_video_packet_size);
6691 if ((m_audio_left < 2) || (m_video_left < 2) || (a_audio_left == 0) || (a_video_left == 0))
6692 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
6694 ast_build_string(&m_audio_next, &m_audio_left, "\r\n");
6695 if (needvideo)
6696 ast_build_string(&m_video_next, &m_video_left, "\r\n");
6698 len = strlen(version) + strlen(subject) + strlen(owner) + strlen(connection) + strlen(stime) + strlen(m_audio) + strlen(a_audio) + strlen(hold);
6699 if (needvideo) /* only if video response is appropriate */
6700 len += strlen(m_video) + strlen(a_video) + strlen(bandwidth) + strlen(hold);
6702 add_header(resp, "Content-Type", "application/sdp");
6703 add_header_contentLength(resp, len);
6704 add_line(resp, version);
6705 add_line(resp, owner);
6706 add_line(resp, subject);
6707 add_line(resp, connection);
6708 if (needvideo) /* only if video response is appropriate */
6709 add_line(resp, bandwidth);
6710 add_line(resp, stime);
6711 add_line(resp, m_audio);
6712 add_line(resp, a_audio);
6713 add_line(resp, hold);
6714 if (needvideo) { /* only if video response is appropriate */
6715 add_line(resp, m_video);
6716 add_line(resp, a_video);
6717 add_line(resp, hold); /* Repeat hold for the video stream */
6720 /* Update lastrtprx when we send our SDP */
6721 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
6723 if (option_debug > 2) {
6724 char buf[SIPBUFSIZE];
6725 ast_log(LOG_DEBUG, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
6728 return AST_SUCCESS;
6731 /*! \brief Used for 200 OK and 183 early media */
6732 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
6734 struct sip_request resp;
6735 int seqno;
6737 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
6738 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
6739 return -1;
6741 respprep(&resp, p, msg, req);
6742 if (p->udptl) {
6743 ast_udptl_offered_from_local(p->udptl, 0);
6744 add_t38_sdp(&resp, p);
6745 } else
6746 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
6747 if (retrans && !p->pendinginvite)
6748 p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
6749 return send_response(p, &resp, retrans, seqno);
6752 /*! \brief copy SIP request (mostly used to save request for responses) */
6753 static void copy_request(struct sip_request *dst, const struct sip_request *src)
6755 long offset;
6756 int x;
6757 offset = ((void *)dst) - ((void *)src);
6758 /* First copy stuff */
6759 memcpy(dst, src, sizeof(*dst));
6760 /* Now fix pointer arithmetic */
6761 for (x=0; x < src->headers; x++)
6762 dst->header[x] += offset;
6763 for (x=0; x < src->lines; x++)
6764 dst->line[x] += offset;
6765 dst->rlPart1 += offset;
6766 dst->rlPart2 += offset;
6769 /*! \brief Used for 200 OK and 183 early media
6770 \return Will return XMIT_ERROR for network errors.
6772 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
6774 struct sip_request resp;
6775 int seqno;
6776 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
6777 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
6778 return -1;
6780 respprep(&resp, p, msg, req);
6781 if (p->rtp) {
6782 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
6783 if (option_debug)
6784 ast_log(LOG_DEBUG, "Setting framing from config on incoming call\n");
6785 ast_rtp_codec_setpref(p->rtp, &p->prefs);
6787 try_suggested_sip_codec(p);
6788 add_sdp(&resp, p);
6789 } else
6790 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
6791 if (reliable && !p->pendinginvite)
6792 p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
6793 return send_response(p, &resp, reliable, seqno);
6796 /*! \brief Parse first line of incoming SIP request */
6797 static int determine_firstline_parts(struct sip_request *req)
6799 char *e = ast_skip_blanks(req->header[0]); /* there shouldn't be any */
6801 if (!*e)
6802 return -1;
6803 req->rlPart1 = e; /* method or protocol */
6804 e = ast_skip_nonblanks(e);
6805 if (*e)
6806 *e++ = '\0';
6807 /* Get URI or status code */
6808 e = ast_skip_blanks(e);
6809 if ( !*e )
6810 return -1;
6811 ast_trim_blanks(e);
6813 if (!strcasecmp(req->rlPart1, "SIP/2.0") ) { /* We have a response */
6814 if (strlen(e) < 3) /* status code is 3 digits */
6815 return -1;
6816 req->rlPart2 = e;
6817 } else { /* We have a request */
6818 if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
6819 ast_log(LOG_WARNING, "bogus uri in <> %s\n", e);
6820 e++;
6821 if (!*e)
6822 return -1;
6824 req->rlPart2 = e; /* URI */
6825 e = ast_skip_nonblanks(e);
6826 if (*e)
6827 *e++ = '\0';
6828 e = ast_skip_blanks(e);
6829 if (strcasecmp(e, "SIP/2.0") ) {
6830 ast_log(LOG_WARNING, "Bad request protocol %s\n", e);
6831 return -1;
6834 return 1;
6837 /*! \brief Transmit reinvite with SDP
6838 \note A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
6839 INVITE that opened the SIP dialogue
6840 We reinvite so that the audio stream (RTP) go directly between
6841 the SIP UAs. SIP Signalling stays with * in the path.
6843 static int transmit_reinvite_with_sdp(struct sip_pvt *p)
6845 struct sip_request req;
6847 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
6849 add_header(&req, "Allow", ALLOWED_METHODS);
6850 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6851 if (sipdebug)
6852 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
6853 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
6854 append_history(p, "ReInv", "Re-invite sent");
6855 add_sdp(&req, p);
6856 /* Use this as the basis */
6857 initialize_initreq(p, &req);
6858 p->lastinvite = p->ocseq;
6859 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Change direction of this dialog */
6860 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
6863 /*! \brief Transmit reinvite with T38 SDP
6864 We reinvite so that the T38 processing can take place.
6865 SIP Signalling stays with * in the path.
6867 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p)
6869 struct sip_request req;
6871 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
6873 add_header(&req, "Allow", ALLOWED_METHODS);
6874 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6875 if (sipdebug)
6876 add_header(&req, "X-asterisk-info", "SIP re-invite (T38 switchover)");
6877 ast_udptl_offered_from_local(p->udptl, 1);
6878 add_t38_sdp(&req, p);
6879 /* Use this as the basis */
6880 initialize_initreq(p, &req);
6881 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Change direction of this dialog */
6882 p->lastinvite = p->ocseq;
6883 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
6886 /*! \brief Check Contact: URI of SIP message */
6887 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
6889 char stripped[SIPBUFSIZE];
6890 char *c;
6892 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
6893 c = get_in_brackets(stripped);
6894 c = strsep(&c, ";"); /* trim ; and beyond */
6895 if (!ast_strlen_zero(c))
6896 ast_string_field_set(p, uri, c);
6899 /*! \brief Build contact header - the contact header we send out */
6900 static void build_contact(struct sip_pvt *p)
6902 /* Construct Contact: header */
6903 if (ourport != STANDARD_SIP_PORT)
6904 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);
6905 else
6906 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip));
6909 /*! \brief Build the Remote Party-ID & From using callingpres options */
6910 static void build_rpid(struct sip_pvt *p)
6912 int send_pres_tags = TRUE;
6913 const char *privacy=NULL;
6914 const char *screen=NULL;
6915 char buf[256];
6916 const char *clid = default_callerid;
6917 const char *clin = NULL;
6918 const char *fromdomain;
6920 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
6921 return;
6923 if (p->owner && p->owner->cid.cid_num)
6924 clid = p->owner->cid.cid_num;
6925 if (p->owner && p->owner->cid.cid_name)
6926 clin = p->owner->cid.cid_name;
6927 if (ast_strlen_zero(clin))
6928 clin = clid;
6930 switch (p->callingpres) {
6931 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
6932 privacy = "off";
6933 screen = "no";
6934 break;
6935 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
6936 privacy = "off";
6937 screen = "yes";
6938 break;
6939 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
6940 privacy = "off";
6941 screen = "no";
6942 break;
6943 case AST_PRES_ALLOWED_NETWORK_NUMBER:
6944 privacy = "off";
6945 screen = "yes";
6946 break;
6947 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
6948 privacy = "full";
6949 screen = "no";
6950 break;
6951 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
6952 privacy = "full";
6953 screen = "yes";
6954 break;
6955 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
6956 privacy = "full";
6957 screen = "no";
6958 break;
6959 case AST_PRES_PROHIB_NETWORK_NUMBER:
6960 privacy = "full";
6961 screen = "yes";
6962 break;
6963 case AST_PRES_NUMBER_NOT_AVAILABLE:
6964 send_pres_tags = FALSE;
6965 break;
6966 default:
6967 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
6968 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
6969 privacy = "full";
6970 else
6971 privacy = "off";
6972 screen = "no";
6973 break;
6976 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip));
6978 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
6979 if (send_pres_tags)
6980 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
6981 ast_string_field_set(p, rpid, buf);
6983 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
6984 S_OR(p->fromuser, clid),
6985 fromdomain, p->tag);
6988 /*! \brief Initiate new SIP request to peer/user */
6989 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
6991 char invite_buf[256] = "";
6992 char *invite = invite_buf;
6993 size_t invite_max = sizeof(invite_buf);
6994 char from[256];
6995 char to[256];
6996 char tmp[SIPBUFSIZE/2];
6997 char tmp2[SIPBUFSIZE/2];
6998 const char *l = NULL, *n = NULL;
6999 const char *urioptions = "";
7001 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
7002 const char *s = p->username; /* being a string field, cannot be NULL */
7004 /* Test p->username against allowed characters in AST_DIGIT_ANY
7005 If it matches the allowed characters list, then sipuser = ";user=phone"
7006 If not, then sipuser = ""
7008 /* + is allowed in first position in a tel: uri */
7009 if (*s == '+')
7010 s++;
7011 for (; *s; s++) {
7012 if (!strchr(AST_DIGIT_ANYNUM, *s) )
7013 break;
7015 /* If we have only digits, add ;user=phone to the uri */
7016 if (*s)
7017 urioptions = ";user=phone";
7021 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
7023 if (p->owner) {
7024 l = p->owner->cid.cid_num;
7025 n = p->owner->cid.cid_name;
7027 /* if we are not sending RPID and user wants his callerid restricted */
7028 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
7029 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
7030 l = CALLERID_UNKNOWN;
7031 n = l;
7033 if (ast_strlen_zero(l))
7034 l = default_callerid;
7035 if (ast_strlen_zero(n))
7036 n = l;
7037 /* Allow user to be overridden */
7038 if (!ast_strlen_zero(p->fromuser))
7039 l = p->fromuser;
7040 else /* Save for any further attempts */
7041 ast_string_field_set(p, fromuser, l);
7043 /* Allow user to be overridden */
7044 if (!ast_strlen_zero(p->fromname))
7045 n = p->fromname;
7046 else /* Save for any further attempts */
7047 ast_string_field_set(p, fromname, n);
7049 if (pedanticsipchecking) {
7050 ast_uri_encode(n, tmp, sizeof(tmp), 0);
7051 n = tmp;
7052 ast_uri_encode(l, tmp2, sizeof(tmp2), 0);
7053 l = tmp2;
7056 if (ourport != STANDARD_SIP_PORT && ast_strlen_zero(p->fromdomain))
7057 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);
7058 else
7059 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)), p->tag);
7061 /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
7062 if (!ast_strlen_zero(p->fullcontact)) {
7063 /* If we have full contact, trust it */
7064 ast_build_string(&invite, &invite_max, "%s", p->fullcontact);
7065 } else {
7066 /* Otherwise, use the username while waiting for registration */
7067 ast_build_string(&invite, &invite_max, "sip:");
7068 if (!ast_strlen_zero(p->username)) {
7069 n = p->username;
7070 if (pedanticsipchecking) {
7071 ast_uri_encode(n, tmp, sizeof(tmp), 0);
7072 n = tmp;
7074 ast_build_string(&invite, &invite_max, "%s@", n);
7076 ast_build_string(&invite, &invite_max, "%s", p->tohost);
7077 if (ntohs(p->sa.sin_port) != STANDARD_SIP_PORT)
7078 ast_build_string(&invite, &invite_max, ":%d", ntohs(p->sa.sin_port));
7079 ast_build_string(&invite, &invite_max, "%s", urioptions);
7082 /* If custom URI options have been provided, append them */
7083 if (p->options && !ast_strlen_zero(p->options->uri_options))
7084 ast_build_string(&invite, &invite_max, ";%s", p->options->uri_options);
7086 ast_string_field_set(p, uri, invite_buf);
7088 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
7089 /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
7090 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "" : "sip:"), p->uri, p->theirtag);
7091 } else if (p->options && p->options->vxml_url) {
7092 /* If there is a VXML URL append it to the SIP URL */
7093 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
7094 } else
7095 snprintf(to, sizeof(to), "<%s>", p->uri);
7097 init_req(req, sipmethod, p->uri);
7098 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
7100 add_header(req, "Via", p->via);
7101 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
7102 * OTOH, then we won't have anything in p->route anyway */
7103 /* Build Remote Party-ID and From */
7104 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
7105 build_rpid(p);
7106 add_header(req, "From", p->rpid_from);
7107 } else
7108 add_header(req, "From", from);
7109 add_header(req, "To", to);
7110 ast_string_field_set(p, exten, l);
7111 build_contact(p);
7112 add_header(req, "Contact", p->our_contact);
7113 add_header(req, "Call-ID", p->callid);
7114 add_header(req, "CSeq", tmp);
7115 if (!ast_strlen_zero(global_useragent))
7116 add_header(req, "User-Agent", global_useragent);
7117 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
7118 if (!ast_strlen_zero(p->rpid))
7119 add_header(req, "Remote-Party-ID", p->rpid);
7122 /*! \brief Build REFER/INVITE/OPTIONS message and transmit it */
7123 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
7125 struct sip_request req;
7127 req.method = sipmethod;
7128 if (init) { /* Seems like init always is 2 */
7129 /* Bump branch even on initial requests */
7130 p->branch ^= ast_random();
7131 build_via(p);
7132 if (init > 1)
7133 initreqprep(&req, p, sipmethod);
7134 else
7135 reqprep(&req, p, sipmethod, 0, 1);
7136 } else
7137 reqprep(&req, p, sipmethod, 0, 1);
7139 if (p->options && p->options->auth)
7140 add_header(&req, p->options->authheader, p->options->auth);
7141 append_date(&req);
7142 if (sipmethod == SIP_REFER) { /* Call transfer */
7143 if (p->refer) {
7144 char buf[SIPBUFSIZE];
7145 if (!ast_strlen_zero(p->refer->refer_to))
7146 add_header(&req, "Refer-To", p->refer->refer_to);
7147 if (!ast_strlen_zero(p->refer->referred_by)) {
7148 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
7149 add_header(&req, "Referred-By", buf);
7153 /* This new INVITE is part of an attended transfer. Make sure that the
7154 other end knows and replace the current call with this new call */
7155 if (p->options && p->options->replaces && !ast_strlen_zero(p->options->replaces)) {
7156 add_header(&req, "Replaces", p->options->replaces);
7157 add_header(&req, "Require", "replaces");
7160 add_header(&req, "Allow", ALLOWED_METHODS);
7161 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7162 if (p->options && p->options->addsipheaders && p->owner) {
7163 struct ast_channel *chan = p->owner; /* The owner channel */
7164 struct varshead *headp;
7166 ast_channel_lock(chan);
7168 headp = &chan->varshead;
7170 if (!headp)
7171 ast_log(LOG_WARNING,"No Headp for the channel...ooops!\n");
7172 else {
7173 const struct ast_var_t *current;
7174 AST_LIST_TRAVERSE(headp, current, entries) {
7175 /* SIPADDHEADER: Add SIP header to outgoing call */
7176 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
7177 char *content, *end;
7178 const char *header = ast_var_value(current);
7179 char *headdup = ast_strdupa(header);
7181 /* Strip of the starting " (if it's there) */
7182 if (*headdup == '"')
7183 headdup++;
7184 if ((content = strchr(headdup, ':'))) {
7185 *content++ = '\0';
7186 content = ast_skip_blanks(content); /* Skip white space */
7187 /* Strip the ending " (if it's there) */
7188 end = content + strlen(content) -1;
7189 if (*end == '"')
7190 *end = '\0';
7192 add_header(&req, headdup, content);
7193 if (sipdebug)
7194 ast_log(LOG_DEBUG, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
7200 ast_channel_unlock(chan);
7202 if (sdp) {
7203 if (p->udptl && (p->t38.state == T38_LOCAL_DIRECT || p->t38.state == T38_LOCAL_REINVITE)) {
7204 ast_udptl_offered_from_local(p->udptl, 1);
7205 if (option_debug)
7206 ast_log(LOG_DEBUG, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
7207 add_t38_sdp(&req, p);
7208 } else if (p->rtp)
7209 add_sdp(&req, p);
7210 } else {
7211 add_header_contentLength(&req, 0);
7214 if (!p->initreq.headers || init > 2)
7215 initialize_initreq(p, &req);
7216 p->lastinvite = p->ocseq;
7217 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
7220 /*! \brief Used in the SUBSCRIBE notification subsystem */
7221 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
7223 char tmp[4000], from[256], to[256];
7224 char *t = tmp, *c, *mfrom, *mto;
7225 size_t maxbytes = sizeof(tmp);
7226 struct sip_request req;
7227 char hint[AST_MAX_EXTENSION];
7228 char *statestring = "terminated";
7229 const struct cfsubscription_types *subscriptiontype;
7230 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
7231 char *pidfstate = "--";
7232 char *pidfnote= "Ready";
7234 memset(from, 0, sizeof(from));
7235 memset(to, 0, sizeof(to));
7236 memset(tmp, 0, sizeof(tmp));
7238 switch (state) {
7239 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
7240 statestring = (global_notifyringing) ? "early" : "confirmed";
7241 local_state = NOTIFY_INUSE;
7242 pidfstate = "busy";
7243 pidfnote = "Ringing";
7244 break;
7245 case AST_EXTENSION_RINGING:
7246 statestring = "early";
7247 local_state = NOTIFY_INUSE;
7248 pidfstate = "busy";
7249 pidfnote = "Ringing";
7250 break;
7251 case AST_EXTENSION_INUSE:
7252 statestring = "confirmed";
7253 local_state = NOTIFY_INUSE;
7254 pidfstate = "busy";
7255 pidfnote = "On the phone";
7256 break;
7257 case AST_EXTENSION_BUSY:
7258 statestring = "confirmed";
7259 local_state = NOTIFY_CLOSED;
7260 pidfstate = "busy";
7261 pidfnote = "On the phone";
7262 break;
7263 case AST_EXTENSION_UNAVAILABLE:
7264 statestring = "terminated";
7265 local_state = NOTIFY_CLOSED;
7266 pidfstate = "away";
7267 pidfnote = "Unavailable";
7268 break;
7269 case AST_EXTENSION_ONHOLD:
7270 statestring = "confirmed";
7271 local_state = NOTIFY_CLOSED;
7272 pidfstate = "busy";
7273 pidfnote = "On Hold";
7274 break;
7275 case AST_EXTENSION_NOT_INUSE:
7276 default:
7277 /* Default setting */
7278 break;
7281 subscriptiontype = find_subscription_type(p->subscribed);
7283 /* Check which device/devices we are watching and if they are registered */
7284 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
7285 char *hint2 = hint, *individual_hint = NULL;
7286 int hint_count = 0, unavailable_count = 0;
7288 while ((individual_hint = strsep(&hint2, "&"))) {
7289 hint_count++;
7291 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
7292 unavailable_count++;
7295 /* If none of the hinted devices are registered, we will
7296 * override notification and show no availability.
7298 if (hint_count > 0 && hint_count == unavailable_count) {
7299 local_state = NOTIFY_CLOSED;
7300 pidfstate = "away";
7301 pidfnote = "Not online";
7305 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
7306 c = get_in_brackets(from);
7307 if (strncasecmp(c, "sip:", 4)) {
7308 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
7309 return -1;
7311 mfrom = strsep(&c, ";"); /* trim ; and beyond */
7313 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
7314 c = get_in_brackets(to);
7315 if (strncasecmp(c, "sip:", 4)) {
7316 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
7317 return -1;
7319 mto = strsep(&c, ";"); /* trim ; and beyond */
7321 reqprep(&req, p, SIP_NOTIFY, 0, 1);
7324 add_header(&req, "Event", subscriptiontype->event);
7325 add_header(&req, "Content-Type", subscriptiontype->mediatype);
7326 switch(state) {
7327 case AST_EXTENSION_DEACTIVATED:
7328 if (timeout)
7329 add_header(&req, "Subscription-State", "terminated;reason=timeout");
7330 else {
7331 add_header(&req, "Subscription-State", "terminated;reason=probation");
7332 add_header(&req, "Retry-After", "60");
7334 break;
7335 case AST_EXTENSION_REMOVED:
7336 add_header(&req, "Subscription-State", "terminated;reason=noresource");
7337 break;
7338 default:
7339 if (p->expiry)
7340 add_header(&req, "Subscription-State", "active");
7341 else /* Expired */
7342 add_header(&req, "Subscription-State", "terminated;reason=timeout");
7344 switch (p->subscribed) {
7345 case XPIDF_XML:
7346 case CPIM_PIDF_XML:
7347 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
7348 ast_build_string(&t, &maxbytes, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
7349 ast_build_string(&t, &maxbytes, "<presence>\n");
7350 ast_build_string(&t, &maxbytes, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
7351 ast_build_string(&t, &maxbytes, "<atom id=\"%s\">\n", p->exten);
7352 ast_build_string(&t, &maxbytes, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
7353 ast_build_string(&t, &maxbytes, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
7354 ast_build_string(&t, &maxbytes, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
7355 ast_build_string(&t, &maxbytes, "</address>\n</atom>\n</presence>\n");
7356 break;
7357 case PIDF_XML: /* Eyebeam supports this format */
7358 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
7359 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);
7360 ast_build_string(&t, &maxbytes, "<pp:person><status>\n");
7361 if (pidfstate[0] != '-')
7362 ast_build_string(&t, &maxbytes, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
7363 ast_build_string(&t, &maxbytes, "</status></pp:person>\n");
7364 ast_build_string(&t, &maxbytes, "<note>%s</note>\n", pidfnote); /* Note */
7365 ast_build_string(&t, &maxbytes, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
7366 ast_build_string(&t, &maxbytes, "<contact priority=\"1\">%s</contact>\n", mto);
7367 if (pidfstate[0] == 'b') /* Busy? Still open ... */
7368 ast_build_string(&t, &maxbytes, "<status><basic>open</basic></status>\n");
7369 else
7370 ast_build_string(&t, &maxbytes, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
7371 ast_build_string(&t, &maxbytes, "</tuple>\n</presence>\n");
7372 break;
7373 case DIALOG_INFO_XML: /* SNOM subscribes in this format */
7374 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
7375 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);
7376 if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
7377 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
7378 else
7379 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\">\n", p->exten);
7380 ast_build_string(&t, &maxbytes, "<state>%s</state>\n", statestring);
7381 if (state == AST_EXTENSION_ONHOLD) {
7382 ast_build_string(&t, &maxbytes, "<local>\n<target uri=\"%s\">\n"
7383 "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
7384 "</target>\n</local>\n", mto);
7386 ast_build_string(&t, &maxbytes, "</dialog>\n</dialog-info>\n");
7387 break;
7388 case NONE:
7389 default:
7390 break;
7393 if (t > tmp + sizeof(tmp))
7394 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
7396 add_header_contentLength(&req, strlen(tmp));
7397 add_line(&req, tmp);
7398 p->pendinginvite = p->ocseq; /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
7400 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7403 /*! \brief Notify user of messages waiting in voicemail
7404 \note - Notification only works for registered peers with mailbox= definitions
7405 in sip.conf
7406 - We use the SIP Event package message-summary
7407 MIME type defaults to "application/simple-message-summary";
7409 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
7411 struct sip_request req;
7412 char tmp[500];
7413 char *t = tmp;
7414 size_t maxbytes = sizeof(tmp);
7416 initreqprep(&req, p, SIP_NOTIFY);
7417 add_header(&req, "Event", "message-summary");
7418 add_header(&req, "Content-Type", default_notifymime);
7420 ast_build_string(&t, &maxbytes, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
7421 ast_build_string(&t, &maxbytes, "Message-Account: sip:%s@%s\r\n",
7422 S_OR(vmexten, default_vmexten), S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)));
7423 /* Cisco has a bug in the SIP stack where it can't accept the
7424 (0/0) notification. This can temporarily be disabled in
7425 sip.conf with the "buggymwi" option */
7426 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)"));
7428 if (p->subscribed) {
7429 if (p->expiry)
7430 add_header(&req, "Subscription-State", "active");
7431 else /* Expired */
7432 add_header(&req, "Subscription-State", "terminated;reason=timeout");
7435 if (t > tmp + sizeof(tmp))
7436 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
7438 add_header_contentLength(&req, strlen(tmp));
7439 add_line(&req, tmp);
7441 if (!p->initreq.headers)
7442 initialize_initreq(p, &req);
7443 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7446 /*! \brief Transmit SIP request unreliably (only used in sip_notify subsystem) */
7447 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req)
7449 if (!p->initreq.headers) /* Initialize first request before sending */
7450 initialize_initreq(p, req);
7451 return send_request(p, req, XMIT_UNRELIABLE, p->ocseq);
7454 /*! \brief Notify a transferring party of the status of transfer */
7455 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
7457 struct sip_request req;
7458 char tmp[SIPBUFSIZE/2];
7460 reqprep(&req, p, SIP_NOTIFY, 0, 1);
7461 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
7462 add_header(&req, "Event", tmp);
7463 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
7464 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
7465 add_header(&req, "Allow", ALLOWED_METHODS);
7466 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7468 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
7469 add_header_contentLength(&req, strlen(tmp));
7470 add_line(&req, tmp);
7472 if (!p->initreq.headers)
7473 initialize_initreq(p, &req);
7475 p->lastnoninvite = p->ocseq;
7477 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7480 /*! \brief Convert registration state status to string */
7481 static char *regstate2str(enum sipregistrystate regstate)
7483 switch(regstate) {
7484 case REG_STATE_FAILED:
7485 return "Failed";
7486 case REG_STATE_UNREGISTERED:
7487 return "Unregistered";
7488 case REG_STATE_REGSENT:
7489 return "Request Sent";
7490 case REG_STATE_AUTHSENT:
7491 return "Auth. Sent";
7492 case REG_STATE_REGISTERED:
7493 return "Registered";
7494 case REG_STATE_REJECTED:
7495 return "Rejected";
7496 case REG_STATE_TIMEOUT:
7497 return "Timeout";
7498 case REG_STATE_NOAUTH:
7499 return "No Authentication";
7500 default:
7501 return "Unknown";
7505 /*! \brief Update registration with SIP Proxy */
7506 static int sip_reregister(const void *data)
7508 /* if we are here, we know that we need to reregister. */
7509 struct sip_registry *r= ASTOBJ_REF((struct sip_registry *) data);
7511 /* if we couldn't get a reference to the registry object, punt */
7512 if (!r)
7513 return 0;
7515 if (r->call && !ast_test_flag(&r->call->flags[0], SIP_NO_HISTORY))
7516 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
7517 /* Since registry's are only added/removed by the the monitor thread, this
7518 may be overkill to reference/dereference at all here */
7519 if (sipdebug)
7520 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
7522 r->expire = -1;
7523 __sip_do_register(r);
7524 ASTOBJ_UNREF(r, sip_registry_destroy);
7525 return 0;
7528 /*! \brief Register with SIP proxy */
7529 static int __sip_do_register(struct sip_registry *r)
7531 int res;
7533 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
7534 return res;
7537 /*! \brief Registration timeout, register again */
7538 static int sip_reg_timeout(const void *data)
7541 /* if we are here, our registration timed out, so we'll just do it over */
7542 struct sip_registry *r = ASTOBJ_REF((struct sip_registry *) data);
7543 struct sip_pvt *p;
7544 int res;
7546 /* if we couldn't get a reference to the registry object, punt */
7547 if (!r)
7548 return 0;
7550 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
7551 if (r->call) {
7552 /* Unlink us, destroy old call. Locking is not relevant here because all this happens
7553 in the single SIP manager thread. */
7554 p = r->call;
7555 ast_mutex_lock(&p->lock);
7556 if (p->registry)
7557 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
7558 r->call = NULL;
7559 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
7560 /* Pretend to ACK anything just in case */
7561 __sip_pretend_ack(p);
7562 ast_mutex_unlock(&p->lock);
7564 /* If we have a limit, stop registration and give up */
7565 if (global_regattempts_max && (r->regattempts > global_regattempts_max)) {
7566 /* Ok, enough is enough. Don't try any more */
7567 /* We could add an external notification here...
7568 steal it from app_voicemail :-) */
7569 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
7570 r->regstate = REG_STATE_FAILED;
7571 } else {
7572 r->regstate = REG_STATE_UNREGISTERED;
7573 r->timeout = -1;
7574 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
7576 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));
7577 ASTOBJ_UNREF(r, sip_registry_destroy);
7578 return 0;
7581 /*! \brief Transmit register to SIP proxy or UA */
7582 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
7584 struct sip_request req;
7585 char from[256];
7586 char to[256];
7587 char tmp[80];
7588 char addr[80];
7589 struct sip_pvt *p;
7590 char *fromdomain;
7592 /* exit if we are already in process with this registrar ?*/
7593 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
7594 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
7595 return 0;
7598 if (r->call) { /* We have a registration */
7599 if (!auth) {
7600 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
7601 return 0;
7602 } else {
7603 p = r->call;
7604 make_our_tag(p->tag, sizeof(p->tag)); /* create a new local tag for every register attempt */
7605 ast_string_field_free(p, theirtag); /* forget their old tag, so we don't match tags when getting response */
7607 } else {
7608 /* Build callid for registration if we haven't registered before */
7609 if (!r->callid_valid) {
7610 build_callid_registry(r, __ourip, default_fromdomain);
7611 r->callid_valid = TRUE;
7613 /* Allocate SIP packet for registration */
7614 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER))) {
7615 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
7616 return 0;
7618 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
7619 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
7620 /* Find address to hostname */
7621 if (create_addr(p, r->hostname)) {
7622 /* we have what we hope is a temporary network error,
7623 * probably DNS. We need to reschedule a registration try */
7624 sip_destroy(p);
7626 if (r->timeout > -1)
7627 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
7628 else
7629 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);
7631 AST_SCHED_DEL(sched, r->timeout);
7632 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
7633 r->regattempts++;
7634 return 0;
7636 /* Copy back Call-ID in case create_addr changed it */
7637 ast_string_field_set(r, callid, p->callid);
7638 if (r->portno) {
7639 p->sa.sin_port = htons(r->portno);
7640 p->recv.sin_port = htons(r->portno);
7641 } else /* Set registry port to the port set from the peer definition/srv or default */
7642 r->portno = ntohs(p->sa.sin_port);
7643 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
7644 r->call=p; /* Save pointer to SIP packet */
7645 p->registry = ASTOBJ_REF(r); /* Add pointer to registry in packet */
7646 if (!ast_strlen_zero(r->secret)) /* Secret (password) */
7647 ast_string_field_set(p, peersecret, r->secret);
7648 if (!ast_strlen_zero(r->md5secret))
7649 ast_string_field_set(p, peermd5secret, r->md5secret);
7650 /* User name in this realm
7651 - if authuser is set, use that, otherwise use username */
7652 if (!ast_strlen_zero(r->authuser)) {
7653 ast_string_field_set(p, peername, r->authuser);
7654 ast_string_field_set(p, authname, r->authuser);
7655 } else if (!ast_strlen_zero(r->username)) {
7656 ast_string_field_set(p, peername, r->username);
7657 ast_string_field_set(p, authname, r->username);
7658 ast_string_field_set(p, fromuser, r->username);
7660 if (!ast_strlen_zero(r->username))
7661 ast_string_field_set(p, username, r->username);
7662 /* Save extension in packet */
7663 ast_string_field_set(p, exten, r->contact);
7666 check which address we should use in our contact header
7667 based on whether the remote host is on the external or
7668 internal network so we can register through nat
7670 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
7671 p->ourip = bindaddr.sin_addr;
7672 build_contact(p);
7675 /* set up a timeout */
7676 if (auth == NULL) {
7677 if (r->timeout > -1)
7678 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
7679 AST_SCHED_DEL(sched, r->timeout);
7680 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
7681 if (option_debug)
7682 ast_log(LOG_DEBUG, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
7685 if ((fromdomain = strchr(r->username, '@'))) {
7686 /* We have a domain in the username for registration */
7687 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
7688 if (!ast_strlen_zero(p->theirtag))
7689 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
7690 else
7691 snprintf(to, sizeof(to), "<sip:%s>", r->username);
7693 /* If the registration username contains '@', then the domain should be used as
7694 the equivalent of "fromdomain" for the registration */
7695 if (ast_strlen_zero(p->fromdomain)) {
7696 ast_string_field_set(p, fromdomain, ++fromdomain);
7698 } else {
7699 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
7700 if (!ast_strlen_zero(p->theirtag))
7701 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
7702 else
7703 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
7706 /* Fromdomain is what we are registering to, regardless of actual
7707 host name from SRV */
7708 if (!ast_strlen_zero(p->fromdomain)) {
7709 if (r->portno && r->portno != STANDARD_SIP_PORT)
7710 snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
7711 else
7712 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
7713 } else {
7714 if (r->portno && r->portno != STANDARD_SIP_PORT)
7715 snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
7716 else
7717 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
7719 ast_string_field_set(p, uri, addr);
7721 p->branch ^= ast_random();
7723 init_req(&req, sipmethod, addr);
7725 /* Add to CSEQ */
7726 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
7727 p->ocseq = r->ocseq;
7729 build_via(p);
7730 add_header(&req, "Via", p->via);
7731 add_header(&req, "From", from);
7732 add_header(&req, "To", to);
7733 add_header(&req, "Call-ID", p->callid);
7734 add_header(&req, "CSeq", tmp);
7735 if (!ast_strlen_zero(global_useragent))
7736 add_header(&req, "User-Agent", global_useragent);
7737 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
7740 if (auth) /* Add auth header */
7741 add_header(&req, authheader, auth);
7742 else if (!ast_strlen_zero(r->nonce)) {
7743 char digest[1024];
7745 /* We have auth data to reuse, build a digest header! */
7746 if (sipdebug)
7747 ast_log(LOG_DEBUG, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
7748 ast_string_field_set(p, realm, r->realm);
7749 ast_string_field_set(p, nonce, r->nonce);
7750 ast_string_field_set(p, domain, r->domain);
7751 ast_string_field_set(p, opaque, r->opaque);
7752 ast_string_field_set(p, qop, r->qop);
7753 r->noncecount++;
7754 p->noncecount = r->noncecount;
7756 memset(digest,0,sizeof(digest));
7757 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
7758 add_header(&req, "Authorization", digest);
7759 else
7760 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
7764 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
7765 add_header(&req, "Expires", tmp);
7766 add_header(&req, "Contact", p->our_contact);
7767 add_header(&req, "Event", "registration");
7768 add_header_contentLength(&req, 0);
7770 initialize_initreq(p, &req);
7771 if (sip_debug_test_pvt(p))
7772 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
7773 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
7774 r->regattempts++; /* Another attempt */
7775 if (option_debug > 3)
7776 ast_verbose("REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
7777 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
7780 /*! \brief Transmit text with SIP MESSAGE method */
7781 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
7783 struct sip_request req;
7785 reqprep(&req, p, SIP_MESSAGE, 0, 1);
7786 add_text(&req, text);
7787 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7790 /*! \brief Allocate SIP refer structure */
7791 static int sip_refer_allocate(struct sip_pvt *p)
7793 p->refer = ast_calloc(1, sizeof(struct sip_refer));
7794 return p->refer ? 1 : 0;
7797 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
7798 \note this is currently broken as we have no way of telling the dialplan
7799 engine whether a transfer succeeds or fails.
7800 \todo Fix the transfer() dialplan function so that a transfer may fail
7802 static int transmit_refer(struct sip_pvt *p, const char *dest)
7804 struct sip_request req = {
7805 .headers = 0,
7807 char from[256];
7808 const char *of;
7809 char *c;
7810 char referto[256];
7811 char *ttag, *ftag;
7812 char *theirtag = ast_strdupa(p->theirtag);
7814 if (option_debug || sipdebug)
7815 ast_log(LOG_DEBUG, "SIP transfer of %s to %s\n", p->callid, dest);
7817 /* Are we transfering an inbound or outbound call ? */
7818 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
7819 of = get_header(&p->initreq, "To");
7820 ttag = theirtag;
7821 ftag = p->tag;
7822 } else {
7823 of = get_header(&p->initreq, "From");
7824 ftag = theirtag;
7825 ttag = p->tag;
7828 ast_copy_string(from, of, sizeof(from));
7829 of = get_in_brackets(from);
7830 ast_string_field_set(p, from, of);
7831 if (strncasecmp(of, "sip:", 4))
7832 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
7833 else
7834 of += 4;
7835 /* Get just the username part */
7836 if ((c = strchr(dest, '@')))
7837 c = NULL;
7838 else if ((c = strchr(of, '@')))
7839 *c++ = '\0';
7840 if (c)
7841 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
7842 else
7843 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
7845 /* save in case we get 407 challenge */
7846 sip_refer_allocate(p);
7847 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
7848 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
7849 p->refer->status = REFER_SENT; /* Set refer status */
7851 reqprep(&req, p, SIP_REFER, 0, 1);
7853 add_header(&req, "Refer-To", referto);
7854 add_header(&req, "Allow", ALLOWED_METHODS);
7855 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7856 if (!ast_strlen_zero(p->our_contact))
7857 add_header(&req, "Referred-By", p->our_contact);
7859 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7860 /* We should propably wait for a NOTIFY here until we ack the transfer */
7861 /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
7863 /*! \todo In theory, we should hang around and wait for a reply, before
7864 returning to the dial plan here. Don't know really how that would
7865 affect the transfer() app or the pbx, but, well, to make this
7866 useful we should have a STATUS code on transfer().
7871 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
7872 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
7874 struct sip_request req;
7876 reqprep(&req, p, SIP_INFO, 0, 1);
7877 add_digit(&req, digit, duration);
7878 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7881 /*! \brief Send SIP INFO with video update request */
7882 static int transmit_info_with_vidupdate(struct sip_pvt *p)
7884 struct sip_request req;
7886 reqprep(&req, p, SIP_INFO, 0, 1);
7887 add_vidupdate(&req);
7888 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7891 /*! \brief Transmit generic SIP request
7892 returns XMIT_ERROR if transmit failed with a critical error (don't retry)
7894 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
7896 struct sip_request resp;
7898 if (sipmethod == SIP_ACK)
7899 p->invitestate = INV_CONFIRMED;
7901 reqprep(&resp, p, sipmethod, seqno, newbranch);
7902 add_header_contentLength(&resp, 0);
7903 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
7906 /*! \brief Transmit SIP request, auth added */
7907 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
7909 struct sip_request resp;
7911 reqprep(&resp, p, sipmethod, seqno, newbranch);
7912 if (!ast_strlen_zero(p->realm)) {
7913 char digest[1024];
7915 memset(digest, 0, sizeof(digest));
7916 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
7917 if (p->options && p->options->auth_type == PROXY_AUTH)
7918 add_header(&resp, "Proxy-Authorization", digest);
7919 else if (p->options && p->options->auth_type == WWW_AUTH)
7920 add_header(&resp, "Authorization", digest);
7921 else /* Default, to be backwards compatible (maybe being too careful, but leaving it for now) */
7922 add_header(&resp, "Proxy-Authorization", digest);
7923 } else
7924 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
7926 /* If we are hanging up and know a cause for that, send it in clear text to make
7927 debugging easier. */
7928 if (sipmethod == SIP_BYE && p->owner && p->owner->hangupcause) {
7929 char buf[10];
7931 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
7932 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
7933 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
7936 add_header_contentLength(&resp, 0);
7937 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
7940 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
7941 static void destroy_association(struct sip_peer *peer)
7943 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE)) {
7944 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
7945 ast_update_realtime("sippeers", "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "username", "", "regserver", "", NULL);
7946 else
7947 ast_db_del("SIP/Registry", peer->name);
7951 /*! \brief Expire registration of SIP peer */
7952 static int expire_register(const void *data)
7954 struct sip_peer *peer = (struct sip_peer *)data;
7956 if (!peer) /* Hmmm. We have no peer. Weird. */
7957 return 0;
7959 memset(&peer->addr, 0, sizeof(peer->addr));
7961 destroy_association(peer); /* remove registration data from storage */
7963 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
7964 register_peer_exten(peer, FALSE); /* Remove regexten */
7965 peer->expire = -1;
7966 ast_device_state_changed("SIP/%s", peer->name);
7968 /* Do we need to release this peer from memory?
7969 Only for realtime peers and autocreated peers
7971 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT) ||
7972 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
7973 struct sip_peer *peer_ptr = peer_ptr;
7974 peer_ptr = ASTOBJ_CONTAINER_UNLINK(&peerl, peer);
7975 if (peer_ptr) {
7976 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
7980 ASTOBJ_UNREF(peer, sip_destroy_peer);
7982 return 0;
7985 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
7986 static int sip_poke_peer_s(const void *data)
7988 struct sip_peer *peer = (struct sip_peer *) data;
7990 peer->pokeexpire = -1;
7992 sip_poke_peer(peer);
7994 ASTOBJ_UNREF(peer, sip_destroy_peer);
7996 return 0;
7999 /*! \brief Get registration details from Asterisk DB */
8000 static void reg_source_db(struct sip_peer *peer)
8002 char data[256];
8003 struct in_addr in;
8004 int expiry;
8005 int port;
8006 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
8008 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
8009 return;
8010 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
8011 return;
8013 scan = data;
8014 addr = strsep(&scan, ":");
8015 port_str = strsep(&scan, ":");
8016 expiry_str = strsep(&scan, ":");
8017 username = strsep(&scan, ":");
8018 contact = scan; /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
8020 if (!inet_aton(addr, &in))
8021 return;
8023 if (port_str)
8024 port = atoi(port_str);
8025 else
8026 return;
8028 if (expiry_str)
8029 expiry = atoi(expiry_str);
8030 else
8031 return;
8033 if (username)
8034 ast_copy_string(peer->username, username, sizeof(peer->username));
8035 if (contact)
8036 ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
8038 if (option_debug > 1)
8039 ast_log(LOG_DEBUG, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
8040 peer->name, peer->username, ast_inet_ntoa(in), port, expiry);
8042 memset(&peer->addr, 0, sizeof(peer->addr));
8043 peer->addr.sin_family = AF_INET;
8044 peer->addr.sin_addr = in;
8045 peer->addr.sin_port = htons(port);
8046 if (sipsock < 0) {
8047 /* SIP isn't up yet, so schedule a poke only, pretty soon */
8048 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
8049 struct sip_peer *peer_ptr = peer;
8050 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8052 peer->pokeexpire = ast_sched_add(sched, ast_random() % 5000 + 1, sip_poke_peer_s, ASTOBJ_REF(peer));
8053 if (peer->pokeexpire == -1) {
8054 struct sip_peer *peer_ptr = peer;
8055 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8057 } else
8058 sip_poke_peer(peer);
8059 if (!AST_SCHED_DEL(sched, peer->expire)) {
8060 struct sip_peer *peer_ptr = peer;
8061 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8063 peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, ASTOBJ_REF(peer));
8064 if (peer->expire == -1) {
8065 struct sip_peer *peer_ptr = peer;
8066 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8068 register_peer_exten(peer, TRUE);
8071 /*! \brief Save contact header for 200 OK on INVITE */
8072 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
8074 char contact[SIPBUFSIZE];
8075 char *c;
8077 /* Look for brackets */
8078 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
8079 c = get_in_brackets(contact);
8081 /* Save full contact to call pvt for later bye or re-invite */
8082 ast_string_field_set(pvt, fullcontact, c);
8084 /* Save URI for later ACKs, BYE or RE-invites */
8085 ast_string_field_set(pvt, okcontacturi, c);
8087 /* We should return false for URI:s we can't handle,
8088 like sips:, tel:, mailto:,ldap: etc */
8089 return TRUE;
8092 static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin)
8094 struct hostent *hp;
8095 struct ast_hostent ahp;
8096 int port;
8097 char *c, *host, *pt;
8098 char contact_buf[256];
8099 char *contact;
8101 /* Work on a copy */
8102 ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
8103 contact = contact_buf;
8105 /* Make sure it's a SIP URL */
8106 if (strncasecmp(contact, "sip:", 4)) {
8107 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
8108 } else
8109 contact += 4;
8111 /* Ditch arguments */
8112 /* XXX this code is replicated also shortly below */
8114 /* Grab host */
8115 host = strchr(contact, '@');
8116 if (!host) { /* No username part */
8117 host = contact;
8118 c = NULL;
8119 } else {
8120 *host++ = '\0';
8122 pt = strchr(host, ':');
8123 if (pt) {
8124 *pt++ = '\0';
8125 port = atoi(pt);
8126 } else
8127 port = STANDARD_SIP_PORT;
8129 contact = strsep(&contact, ";"); /* trim ; and beyond in username part */
8130 host = strsep(&host, ";"); /* trim ; and beyond in host/domain part */
8132 /* XXX This could block for a long time XXX */
8133 /* We should only do this if it's a name, not an IP */
8134 hp = ast_gethostbyname(host, &ahp);
8135 if (!hp) {
8136 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
8137 return -1;
8139 sin->sin_family = AF_INET;
8140 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
8141 sin->sin_port = htons(port);
8143 return 0;
8146 /*! \brief Change the other partys IP address based on given contact */
8147 static int set_address_from_contact(struct sip_pvt *pvt)
8149 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
8150 /* NAT: Don't trust the contact field. Just use what they came to us
8151 with. */
8152 pvt->sa = pvt->recv;
8153 return 0;
8156 return __set_address_from_contact(pvt->fullcontact, &pvt->sa);
8160 /*! \brief Parse contact header and save registration (peer registration) */
8161 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
8163 char contact[SIPBUFSIZE];
8164 char data[SIPBUFSIZE];
8165 const char *expires = get_header(req, "Expires");
8166 int expiry = atoi(expires);
8167 char *curi, *n, *pt;
8168 int port;
8169 const char *useragent;
8170 struct hostent *hp;
8171 struct ast_hostent ahp;
8172 struct sockaddr_in oldsin;
8174 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
8176 if (ast_strlen_zero(expires)) { /* No expires header */
8177 expires = strcasestr(contact, ";expires=");
8178 if (expires) {
8179 /* XXX bug here, we overwrite the string */
8180 expires = strsep((char **) &expires, ";"); /* trim ; and beyond */
8181 if (sscanf(expires + 9, "%d", &expiry) != 1)
8182 expiry = default_expiry;
8183 } else {
8184 /* Nothing has been specified */
8185 expiry = default_expiry;
8189 /* Look for brackets */
8190 curi = contact;
8191 if (strchr(contact, '<') == NULL) /* No <, check for ; and strip it */
8192 strsep(&curi, ";"); /* This is Header options, not URI options */
8193 curi = get_in_brackets(contact);
8195 /* if they did not specify Contact: or Expires:, they are querying
8196 what we currently have stored as their contact address, so return
8199 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
8200 /* If we have an active registration, tell them when the registration is going to expire */
8201 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
8202 pvt->expiry = ast_sched_when(sched, peer->expire);
8203 return PARSE_REGISTER_QUERY;
8204 } else if (!strcasecmp(curi, "*") || !expiry) { /* Unregister this peer */
8205 /* This means remove all registrations and return OK */
8206 memset(&peer->addr, 0, sizeof(peer->addr));
8207 if (!AST_SCHED_DEL(sched, peer->expire)) {
8208 struct sip_peer *peer_ptr = peer;
8209 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8212 destroy_association(peer);
8214 register_peer_exten(peer, 0); /* Add extension from regexten= setting in sip.conf */
8215 peer->fullcontact[0] = '\0';
8216 peer->useragent[0] = '\0';
8217 peer->sipoptions = 0;
8218 peer->lastms = 0;
8220 if (option_verbose > 2)
8221 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", peer->name);
8222 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
8223 return PARSE_REGISTER_UPDATE;
8226 /* Store whatever we got as a contact from the client */
8227 ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));
8229 /* For the 200 OK, we should use the received contact */
8230 ast_string_field_build(pvt, our_contact, "<%s>", curi);
8232 /* Make sure it's a SIP URL */
8233 if (strncasecmp(curi, "sip:", 4)) {
8234 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", curi);
8235 } else
8236 curi += 4;
8237 /* Ditch q */
8238 curi = strsep(&curi, ";");
8239 /* Grab host */
8240 n = strchr(curi, '@');
8241 if (!n) {
8242 n = curi;
8243 curi = NULL;
8244 } else
8245 *n++ = '\0';
8246 pt = strchr(n, ':');
8247 if (pt) {
8248 *pt++ = '\0';
8249 port = atoi(pt);
8250 } else
8251 port = STANDARD_SIP_PORT;
8252 oldsin = peer->addr;
8253 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
8254 /* XXX This could block for a long time XXX */
8255 hp = ast_gethostbyname(n, &ahp);
8256 if (!hp) {
8257 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
8258 return PARSE_REGISTER_FAILED;
8260 peer->addr.sin_family = AF_INET;
8261 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
8262 peer->addr.sin_port = htons(port);
8263 } else {
8264 /* Don't trust the contact field. Just use what they came to us
8265 with */
8266 peer->addr = pvt->recv;
8269 /* Save SIP options profile */
8270 peer->sipoptions = pvt->sipoptions;
8272 if (curi && ast_strlen_zero(peer->username))
8273 ast_copy_string(peer->username, curi, sizeof(peer->username));
8275 if (!AST_SCHED_DEL(sched, peer->expire)) {
8276 struct sip_peer *peer_ptr = peer;
8277 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8279 if (expiry > max_expiry)
8280 expiry = max_expiry;
8281 if (expiry < min_expiry)
8282 expiry = min_expiry;
8283 if (ast_test_flag(&peer->flags[0], SIP_REALTIME) && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
8284 peer->expire = -1;
8285 } else {
8286 peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, ASTOBJ_REF(peer));
8287 if (peer->expire == -1) {
8288 struct sip_peer *peer_ptr = peer;
8289 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8292 pvt->expiry = expiry;
8293 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);
8294 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
8295 ast_db_put("SIP/Registry", peer->name, data);
8296 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
8298 /* Is this a new IP address for us? */
8299 if (inaddrcmp(&peer->addr, &oldsin)) {
8300 sip_poke_peer(peer);
8301 if (option_verbose > 2)
8302 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);
8303 register_peer_exten(peer, 1);
8306 /* Save User agent */
8307 useragent = get_header(req, "User-Agent");
8308 if (strcasecmp(useragent, peer->useragent)) { /* XXX copy if they are different ? */
8309 ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
8310 if (option_verbose > 3)
8311 ast_verbose(VERBOSE_PREFIX_3 "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
8313 return PARSE_REGISTER_UPDATE;
8316 /*! \brief Remove route from route list */
8317 static void free_old_route(struct sip_route *route)
8319 struct sip_route *next;
8321 while (route) {
8322 next = route->next;
8323 free(route);
8324 route = next;
8328 /*! \brief List all routes - mostly for debugging */
8329 static void list_route(struct sip_route *route)
8331 if (!route)
8332 ast_verbose("list_route: no route\n");
8333 else {
8334 for (;route; route = route->next)
8335 ast_verbose("list_route: hop: <%s>\n", route->hop);
8339 /*! \brief Build route list from Record-Route header */
8340 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
8342 struct sip_route *thishop, *head, *tail;
8343 int start = 0;
8344 int len;
8345 const char *rr, *contact, *c;
8347 /* Once a persistant route is set, don't fool with it */
8348 if (p->route && p->route_persistant) {
8349 if (option_debug)
8350 ast_log(LOG_DEBUG, "build_route: Retaining previous route: <%s>\n", p->route->hop);
8351 return;
8354 if (p->route) {
8355 free_old_route(p->route);
8356 p->route = NULL;
8359 /* We only want to create the route set the first time this is called */
8360 p->route_persistant = 1;
8362 /* Build a tailq, then assign it to p->route when done.
8363 * If backwards, we add entries from the head so they end up
8364 * in reverse order. However, we do need to maintain a correct
8365 * tail pointer because the contact is always at the end.
8367 head = NULL;
8368 tail = head;
8369 /* 1st we pass through all the hops in any Record-Route headers */
8370 for (;;) {
8371 /* Each Record-Route header */
8372 rr = __get_header(req, "Record-Route", &start);
8373 if (*rr == '\0')
8374 break;
8375 for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
8376 ++rr;
8377 len = strcspn(rr, ">") + 1;
8378 /* Make a struct route */
8379 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
8380 /* ast_calloc is not needed because all fields are initialized in this block */
8381 ast_copy_string(thishop->hop, rr, len);
8382 if (option_debug > 1)
8383 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
8384 /* Link in */
8385 if (backwards) {
8386 /* Link in at head so they end up in reverse order */
8387 thishop->next = head;
8388 head = thishop;
8389 /* If this was the first then it'll be the tail */
8390 if (!tail)
8391 tail = thishop;
8392 } else {
8393 thishop->next = NULL;
8394 /* Link in at the end */
8395 if (tail)
8396 tail->next = thishop;
8397 else
8398 head = thishop;
8399 tail = thishop;
8405 /* Only append the contact if we are dealing with a strict router */
8406 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop,";lr") == NULL) ) {
8407 /* 2nd append the Contact: if there is one */
8408 /* Can be multiple Contact headers, comma separated values - we just take the first */
8409 contact = get_header(req, "Contact");
8410 if (!ast_strlen_zero(contact)) {
8411 if (option_debug > 1)
8412 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
8413 /* Look for <: delimited address */
8414 c = strchr(contact, '<');
8415 if (c) {
8416 /* Take to > */
8417 ++c;
8418 len = strcspn(c, ">") + 1;
8419 } else {
8420 /* No <> - just take the lot */
8421 c = contact;
8422 len = strlen(contact) + 1;
8424 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
8425 /* ast_calloc is not needed because all fields are initialized in this block */
8426 ast_copy_string(thishop->hop, c, len);
8427 thishop->next = NULL;
8428 /* Goes at the end */
8429 if (tail)
8430 tail->next = thishop;
8431 else
8432 head = thishop;
8437 /* Store as new route */
8438 p->route = head;
8440 /* For debugging dump what we ended up with */
8441 if (sip_debug_test_pvt(p))
8442 list_route(p->route);
8445 AST_THREADSTORAGE(check_auth_buf, check_auth_buf_init);
8446 #define CHECK_AUTH_BUF_INITLEN 256
8448 /*! \brief Check user authorization from peer definition
8449 Some actions, like REGISTER and INVITEs from peers require
8450 authentication (if peer have secret set)
8451 \return 0 on success, non-zero on error
8453 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
8454 const char *secret, const char *md5secret, int sipmethod,
8455 char *uri, enum xmittype reliable, int ignore)
8457 const char *response = "407 Proxy Authentication Required";
8458 const char *reqheader = "Proxy-Authorization";
8459 const char *respheader = "Proxy-Authenticate";
8460 const char *authtoken;
8461 char a1_hash[256];
8462 char resp_hash[256]="";
8463 char *c;
8464 int wrongnonce = FALSE;
8465 int good_response;
8466 const char *usednonce = p->randdata;
8467 struct ast_dynamic_str *buf;
8468 int res;
8470 /* table of recognised keywords, and their value in the digest */
8471 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
8472 struct x {
8473 const char *key;
8474 const char *s;
8475 } *i, keys[] = {
8476 [K_RESP] = { "response=", "" },
8477 [K_URI] = { "uri=", "" },
8478 [K_USER] = { "username=", "" },
8479 [K_NONCE] = { "nonce=", "" },
8480 [K_LAST] = { NULL, NULL}
8483 /* Always OK if no secret */
8484 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
8485 return AUTH_SUCCESSFUL;
8486 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
8487 /* On a REGISTER, we have to use 401 and its family of headers instead of 407 and its family
8488 of headers -- GO SIP! Whoo hoo! Two things that do the same thing but are used in
8489 different circumstances! What a surprise. */
8490 response = "401 Unauthorized";
8491 reqheader = "Authorization";
8492 respheader = "WWW-Authenticate";
8494 authtoken = get_header(req, reqheader);
8495 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
8496 /* This is a retransmitted invite/register/etc, don't reconstruct authentication
8497 information */
8498 if (!reliable) {
8499 /* Resend message if this was NOT a reliable delivery. Otherwise the
8500 retransmission should get it */
8501 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
8502 /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
8503 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8505 return AUTH_CHALLENGE_SENT;
8506 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
8507 /* We have no auth, so issue challenge and request authentication */
8508 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
8509 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
8510 /* Schedule auto destroy in 32 seconds */
8511 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8512 return AUTH_CHALLENGE_SENT;
8515 /* --- We have auth, so check it */
8517 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
8518 an example in the spec of just what it is you're doing a hash on. */
8520 if (!(buf = ast_dynamic_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
8521 return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
8523 /* Make a copy of the response and parse it */
8524 res = ast_dynamic_str_thread_set(&buf, 0, &check_auth_buf, "%s", authtoken);
8526 if (res == AST_DYNSTR_BUILD_FAILED)
8527 return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
8529 c = buf->str;
8531 while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
8532 for (i = keys; i->key != NULL; i++) {
8533 const char *separator = ","; /* default */
8535 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
8536 continue;
8537 /* Found. Skip keyword, take text in quotes or up to the separator. */
8538 c += strlen(i->key);
8539 if (*c == '"') { /* in quotes. Skip first and look for last */
8540 c++;
8541 separator = "\"";
8543 i->s = c;
8544 strsep(&c, separator);
8545 break;
8547 if (i->key == NULL) /* not found, jump after space or comma */
8548 strsep(&c, " ,");
8551 /* Verify that digest username matches the username we auth as */
8552 if (strcmp(username, keys[K_USER].s)) {
8553 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
8554 username, keys[K_USER].s);
8555 /* Oops, we're trying something here */
8556 return AUTH_USERNAME_MISMATCH;
8559 /* Verify nonce from request matches our nonce. If not, send 401 with new nonce */
8560 if (strcasecmp(p->randdata, keys[K_NONCE].s)) { /* XXX it was 'n'casecmp ? */
8561 wrongnonce = TRUE;
8562 usednonce = keys[K_NONCE].s;
8565 if (!ast_strlen_zero(md5secret))
8566 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
8567 else {
8568 char a1[256];
8569 snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
8570 ast_md5_hash(a1_hash, a1);
8573 /* compute the expected response to compare with what we received */
8575 char a2[256];
8576 char a2_hash[256];
8577 char resp[256];
8579 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
8580 S_OR(keys[K_URI].s, uri));
8581 ast_md5_hash(a2_hash, a2);
8582 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
8583 ast_md5_hash(resp_hash, resp);
8586 good_response = keys[K_RESP].s &&
8587 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
8588 if (wrongnonce) {
8589 if (good_response) {
8590 if (sipdebug)
8591 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
8592 /* We got working auth token, based on stale nonce . */
8593 ast_string_field_build(p, randdata, "%08lx", ast_random());
8594 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
8595 } else {
8596 /* Everything was wrong, so give the device one more try with a new challenge */
8597 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
8598 if (sipdebug)
8599 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
8600 ast_string_field_build(p, randdata, "%08lx", ast_random());
8601 } else {
8602 if (sipdebug)
8603 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
8605 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
8608 /* Schedule auto destroy in 32 seconds */
8609 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8610 return AUTH_CHALLENGE_SENT;
8612 if (good_response) {
8613 append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
8614 return AUTH_SUCCESSFUL;
8617 /* Ok, we have a bad username/secret pair */
8618 /* Tell the UAS not to re-send this authentication data, because
8619 it will continue to fail
8622 return AUTH_SECRET_FAILED;
8625 /*! \brief Change onhold state of a peer using a pvt structure */
8626 static void sip_peer_hold(struct sip_pvt *p, int hold)
8628 struct sip_peer *peer = find_peer(p->peername, NULL, 1, 0);
8630 if (!peer)
8631 return;
8633 /* If they put someone on hold, increment the value... otherwise decrement it */
8634 if (hold)
8635 peer->onHold++;
8636 else
8637 peer->onHold--;
8639 /* Request device state update */
8640 ast_device_state_changed("SIP/%s", peer->name);
8642 return;
8645 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
8646 \note If you add an "hint" priority to the extension in the dial plan,
8647 you will get notifications on device state changes */
8648 static int cb_extensionstate(char *context, char* exten, int state, void *data)
8650 struct sip_pvt *p = data;
8652 ast_mutex_lock(&p->lock);
8654 switch(state) {
8655 case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
8656 case AST_EXTENSION_REMOVED: /* Extension is gone */
8657 if (p->autokillid > -1 && sip_cancel_destroy(p)) /* Remove subscription expiry for renewals */
8658 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
8659 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); /* Delete subscription in 32 secs */
8660 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);
8661 p->stateid = -1;
8662 p->subscribed = NONE;
8663 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
8664 break;
8665 default: /* Tell user */
8666 p->laststate = state;
8667 break;
8669 if (p->subscribed != NONE) { /* Only send state NOTIFY if we know the format */
8670 if (!p->pendinginvite) {
8671 transmit_state_notify(p, state, 1, FALSE);
8672 } else {
8673 /* We already have a NOTIFY sent that is not answered. Queue the state up.
8674 if many state changes happen meanwhile, we will only send a notification of the last one */
8675 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
8678 if (option_verbose > 1)
8679 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,
8680 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
8683 ast_mutex_unlock(&p->lock);
8685 return 0;
8688 /*! \brief Send a fake 401 Unauthorized response when the administrator
8689 wants to hide the names of local users/peers from fishers
8691 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable)
8693 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
8694 transmit_response_with_auth(p, "401 Unauthorized", req, p->randdata, reliable, "WWW-Authenticate", 0);
8697 /*! \brief Verify registration of user
8698 - Registration is done in several steps, first a REGISTER without auth
8699 to get a challenge (nonce) then a second one with auth
8700 - Registration requests are only matched with peers that are marked as "dynamic"
8702 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
8703 struct sip_request *req, char *uri)
8705 enum check_auth_result res = AUTH_NOT_FOUND;
8706 struct sip_peer *peer;
8707 char tmp[256];
8708 char *name, *c;
8709 char *t;
8710 char *domain;
8712 /* Terminate URI */
8713 t = uri;
8714 while(*t && (*t > 32) && (*t != ';'))
8715 t++;
8716 *t = '\0';
8718 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
8719 if (pedanticsipchecking)
8720 ast_uri_decode(tmp);
8722 c = get_in_brackets(tmp);
8723 c = strsep(&c, ";"); /* Ditch ;user=phone */
8725 if (!strncasecmp(c, "sip:", 4)) {
8726 name = c + 4;
8727 } else {
8728 name = c;
8729 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
8732 /* Strip off the domain name */
8733 if ((c = strchr(name, '@'))) {
8734 *c++ = '\0';
8735 domain = c;
8736 if ((c = strchr(domain, ':'))) /* Remove :port */
8737 *c = '\0';
8738 if (!AST_LIST_EMPTY(&domain_list)) {
8739 if (!check_sip_domain(domain, NULL, 0)) {
8740 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
8741 return AUTH_UNKNOWN_DOMAIN;
8746 ast_string_field_set(p, exten, name);
8747 build_contact(p);
8748 peer = find_peer(name, NULL, 1, 0);
8749 if (!(peer && ast_apply_ha(peer->ha, sin))) {
8750 /* Peer fails ACL check */
8751 if (peer) {
8752 ASTOBJ_UNREF(peer, sip_destroy_peer);
8753 res = AUTH_ACL_FAILED;
8754 } else
8755 res = AUTH_NOT_FOUND;
8757 if (peer) {
8758 /* Set Frame packetization */
8759 if (p->rtp) {
8760 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
8761 p->autoframing = peer->autoframing;
8763 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
8764 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
8765 res = AUTH_PEER_NOT_DYNAMIC;
8766 } else {
8767 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
8768 transmit_response(p, "100 Trying", req);
8769 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, ast_test_flag(req, SIP_PKT_IGNORE)))) {
8770 if (sip_cancel_destroy(p))
8771 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
8773 /* We have a succesful registration attemp with proper authentication,
8774 now, update the peer */
8775 switch (parse_register_contact(p, peer, req)) {
8776 case PARSE_REGISTER_FAILED:
8777 ast_log(LOG_WARNING, "Failed to parse contact info\n");
8778 transmit_response_with_date(p, "400 Bad Request", req);
8779 peer->lastmsgssent = -1;
8780 res = 0;
8781 break;
8782 case PARSE_REGISTER_QUERY:
8783 transmit_response_with_date(p, "200 OK", req);
8784 peer->lastmsgssent = -1;
8785 res = 0;
8786 break;
8787 case PARSE_REGISTER_UPDATE:
8788 update_peer(peer, p->expiry);
8789 /* Say OK and ask subsystem to retransmit msg counter */
8790 transmit_response_with_date(p, "200 OK", req);
8791 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
8792 peer->lastmsgssent = -1;
8793 res = 0;
8794 break;
8799 if (!peer && autocreatepeer) {
8800 /* Create peer if we have autocreate mode enabled */
8801 peer = temp_peer(name);
8802 if (peer) {
8803 ASTOBJ_CONTAINER_LINK(&peerl, peer);
8804 if (sip_cancel_destroy(p))
8805 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
8806 switch (parse_register_contact(p, peer, req)) {
8807 case PARSE_REGISTER_FAILED:
8808 ast_log(LOG_WARNING, "Failed to parse contact info\n");
8809 transmit_response_with_date(p, "400 Bad Request", req);
8810 peer->lastmsgssent = -1;
8811 res = 0;
8812 break;
8813 case PARSE_REGISTER_QUERY:
8814 transmit_response_with_date(p, "200 OK", req);
8815 peer->lastmsgssent = -1;
8816 res = 0;
8817 break;
8818 case PARSE_REGISTER_UPDATE:
8819 /* Say OK and ask subsystem to retransmit msg counter */
8820 transmit_response_with_date(p, "200 OK", req);
8821 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
8822 peer->lastmsgssent = -1;
8823 res = 0;
8824 break;
8828 if (!res) {
8829 ast_device_state_changed("SIP/%s", peer->name);
8831 if (res < 0) {
8832 switch (res) {
8833 case AUTH_SECRET_FAILED:
8834 /* Wrong password in authentication. Go away, don't try again until you fixed it */
8835 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
8836 break;
8837 case AUTH_USERNAME_MISMATCH:
8838 /* Username and digest username does not match.
8839 Asterisk uses the From: username for authentication. We need the
8840 users to use the same authentication user name until we support
8841 proper authentication by digest auth name */
8842 transmit_response(p, "403 Authentication user name does not match account name", &p->initreq);
8843 break;
8844 case AUTH_NOT_FOUND:
8845 case AUTH_PEER_NOT_DYNAMIC:
8846 case AUTH_ACL_FAILED:
8847 if (global_alwaysauthreject) {
8848 transmit_fake_auth_response(p, &p->initreq, 1);
8849 } else {
8850 /* URI not found */
8851 if (res == AUTH_PEER_NOT_DYNAMIC)
8852 transmit_response(p, "403 Forbidden", &p->initreq);
8853 else
8854 transmit_response(p, "404 Not found", &p->initreq);
8856 break;
8857 default:
8858 break;
8861 if (peer)
8862 ASTOBJ_UNREF(peer, sip_destroy_peer);
8864 return res;
8867 /*! \brief Get referring dnis */
8868 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
8870 char tmp[256], *c, *a;
8871 struct sip_request *req;
8873 req = oreq;
8874 if (!req)
8875 req = &p->initreq;
8876 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
8877 if (ast_strlen_zero(tmp))
8878 return 0;
8879 c = get_in_brackets(tmp);
8880 if (strncasecmp(c, "sip:", 4)) {
8881 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", c);
8882 return -1;
8884 c += 4;
8885 a = c;
8886 strsep(&a, "@;"); /* trim anything after @ or ; */
8887 if (sip_debug_test_pvt(p))
8888 ast_verbose("RDNIS is %s\n", c);
8889 ast_string_field_set(p, rdnis, c);
8891 return 0;
8894 /*! \brief Find out who the call is for
8895 We use the INVITE uri to find out
8897 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
8899 char tmp[256] = "", *uri, *a;
8900 char tmpf[256] = "", *from;
8901 struct sip_request *req;
8902 char *colon;
8903 char *decoded_uri;
8905 req = oreq;
8906 if (!req)
8907 req = &p->initreq;
8909 /* Find the request URI */
8910 if (req->rlPart2)
8911 ast_copy_string(tmp, req->rlPart2, sizeof(tmp));
8913 if (pedanticsipchecking)
8914 ast_uri_decode(tmp);
8916 uri = get_in_brackets(tmp);
8918 if (strncasecmp(uri, "sip:", 4)) {
8919 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
8920 return -1;
8922 uri += 4;
8924 /* Now find the From: caller ID and name */
8925 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
8926 if (!ast_strlen_zero(tmpf)) {
8927 if (pedanticsipchecking)
8928 ast_uri_decode(tmpf);
8929 from = get_in_brackets(tmpf);
8930 } else {
8931 from = NULL;
8934 if (!ast_strlen_zero(from)) {
8935 if (strncasecmp(from, "sip:", 4)) {
8936 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
8937 return -1;
8939 from += 4;
8940 if ((a = strchr(from, '@')))
8941 *a++ = '\0';
8942 else
8943 a = from; /* just a domain */
8944 from = strsep(&from, ";"); /* Remove userinfo options */
8945 a = strsep(&a, ";"); /* Remove URI options */
8946 ast_string_field_set(p, fromdomain, a);
8949 /* Skip any options and find the domain */
8951 /* Get the target domain */
8952 if ((a = strchr(uri, '@'))) {
8953 *a++ = '\0';
8954 } else { /* No username part */
8955 a = uri;
8956 uri = "s"; /* Set extension to "s" */
8958 colon = strchr(a, ':'); /* Remove :port */
8959 if (colon)
8960 *colon = '\0';
8962 uri = strsep(&uri, ";"); /* Remove userinfo options */
8963 a = strsep(&a, ";"); /* Remove URI options */
8965 ast_string_field_set(p, domain, a);
8967 if (!AST_LIST_EMPTY(&domain_list)) {
8968 char domain_context[AST_MAX_EXTENSION];
8970 domain_context[0] = '\0';
8971 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
8972 if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
8973 if (option_debug)
8974 ast_log(LOG_DEBUG, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
8975 return -2;
8978 /* If we have a context defined, overwrite the original context */
8979 if (!ast_strlen_zero(domain_context))
8980 ast_string_field_set(p, context, domain_context);
8983 /* If the request coming in is a subscription and subscribecontext has been specified use it */
8984 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
8985 ast_string_field_set(p, context, p->subscribecontext);
8987 if (sip_debug_test_pvt(p))
8988 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
8990 /* If this is a subscription we actually just need to see if a hint exists for the extension */
8991 if (req->method == SIP_SUBSCRIBE) {
8992 char hint[AST_MAX_EXTENSION];
8993 return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
8994 } else {
8995 decoded_uri = ast_strdupa(uri);
8996 ast_uri_decode(decoded_uri);
8997 /* Check the dialplan for the username part of the request URI,
8998 the domain will be stored in the SIPDOMAIN variable
8999 Since extensions.conf can have unescaped characters, try matching a decoded
9000 uri in addition to the non-decoded uri
9001 Return 0 if we have a matching extension */
9002 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)) ||
9003 !strcmp(decoded_uri, ast_pickup_ext())) {
9004 if (!oreq)
9005 ast_string_field_set(p, exten, decoded_uri);
9006 return 0;
9010 /* Return 1 for pickup extension or overlap dialling support (if we support it) */
9011 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
9012 ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
9013 !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
9014 return 1;
9017 return -1;
9020 /*! \brief Lock interface lock and find matching pvt lock
9022 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
9024 struct sip_pvt *sip_pvt_ptr;
9026 ast_mutex_lock(&iflock);
9028 if (option_debug > 3 && totag)
9029 ast_log(LOG_DEBUG, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
9031 /* Search interfaces and find the match */
9032 for (sip_pvt_ptr = iflist; sip_pvt_ptr; sip_pvt_ptr = sip_pvt_ptr->next) {
9033 if (!strcmp(sip_pvt_ptr->callid, callid)) {
9034 int match = 1;
9036 /* Go ahead and lock it (and its owner) before returning */
9037 ast_mutex_lock(&sip_pvt_ptr->lock);
9039 /* Check if tags match. If not, this is not the call we want
9040 (With a forking SIP proxy, several call legs share the
9041 call id, but have different tags)
9043 if (pedanticsipchecking) {
9044 const char *pvt_fromtag, *pvt_totag;
9046 if (ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_OUTGOING_CALL)) {
9047 /* Outgoing call tags : from is "our", to is "their" */
9048 pvt_fromtag = sip_pvt_ptr->tag ;
9049 pvt_totag = sip_pvt_ptr->theirtag ;
9050 } else {
9051 /* Incoming call tags : from is "their", to is "our" */
9052 pvt_fromtag = sip_pvt_ptr->theirtag ;
9053 pvt_totag = sip_pvt_ptr->tag ;
9055 if (ast_strlen_zero(fromtag) || strcmp(fromtag, pvt_fromtag) || (!ast_strlen_zero(totag) && strcmp(totag, pvt_totag)))
9056 match = 0;
9059 if (!match) {
9060 ast_mutex_unlock(&sip_pvt_ptr->lock);
9061 continue;
9064 if (option_debug > 3 && totag)
9065 ast_log(LOG_DEBUG, "Matched %s call - their tag is %s Our tag is %s\n",
9066 ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_OUTGOING_CALL) ? "OUTGOING": "INCOMING",
9067 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
9069 /* deadlock avoidance... */
9070 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
9071 DEADLOCK_AVOIDANCE(&sip_pvt_ptr->lock);
9073 break;
9076 ast_mutex_unlock(&iflock);
9077 if (option_debug > 3 && !sip_pvt_ptr)
9078 ast_log(LOG_DEBUG, "Found no match for callid %s to-tag %s from-tag %s\n", callid, totag, fromtag);
9079 return sip_pvt_ptr;
9082 /*! \brief Call transfer support (the REFER method)
9083 * Extracts Refer headers into pvt dialog structure */
9084 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
9087 const char *p_referred_by = NULL;
9088 char *h_refer_to = NULL;
9089 char *h_referred_by = NULL;
9090 char *refer_to;
9091 const char *p_refer_to;
9092 char *referred_by_uri = NULL;
9093 char *ptr;
9094 struct sip_request *req = NULL;
9095 const char *transfer_context = NULL;
9096 struct sip_refer *referdata;
9099 req = outgoing_req;
9100 referdata = transferer->refer;
9102 if (!req)
9103 req = &transferer->initreq;
9105 p_refer_to = get_header(req, "Refer-To");
9106 if (ast_strlen_zero(p_refer_to)) {
9107 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
9108 return -2; /* Syntax error */
9110 h_refer_to = ast_strdupa(p_refer_to);
9111 refer_to = get_in_brackets(h_refer_to);
9112 if (pedanticsipchecking)
9113 ast_uri_decode(refer_to);
9115 if (strncasecmp(refer_to, "sip:", 4)) {
9116 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
9117 return -3;
9119 refer_to += 4; /* Skip sip: */
9121 /* Get referred by header if it exists */
9122 p_referred_by = get_header(req, "Referred-By");
9123 if (!ast_strlen_zero(p_referred_by)) {
9124 char *lessthan;
9125 h_referred_by = ast_strdupa(p_referred_by);
9126 if (pedanticsipchecking)
9127 ast_uri_decode(h_referred_by);
9129 /* Store referrer's caller ID name */
9130 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
9131 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
9132 *(lessthan - 1) = '\0'; /* Space */
9135 referred_by_uri = get_in_brackets(h_referred_by);
9136 if(strncasecmp(referred_by_uri, "sip:", 4)) {
9137 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
9138 referred_by_uri = (char *) NULL;
9139 } else {
9140 referred_by_uri += 4; /* Skip sip: */
9144 /* Check for arguments in the refer_to header */
9145 if ((ptr = strchr(refer_to, '?'))) { /* Search for arguments */
9146 *ptr++ = '\0';
9147 if (!strncasecmp(ptr, "REPLACES=", 9)) {
9148 char *to = NULL, *from = NULL;
9150 /* This is an attended transfer */
9151 referdata->attendedtransfer = 1;
9152 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
9153 ast_uri_decode(referdata->replaces_callid);
9154 if ((ptr = strchr(referdata->replaces_callid, ';'))) /* Find options */ {
9155 *ptr++ = '\0';
9158 if (ptr) {
9159 /* Find the different tags before we destroy the string */
9160 to = strcasestr(ptr, "to-tag=");
9161 from = strcasestr(ptr, "from-tag=");
9164 /* Grab the to header */
9165 if (to) {
9166 ptr = to + 7;
9167 if ((to = strchr(ptr, '&')))
9168 *to = '\0';
9169 if ((to = strchr(ptr, ';')))
9170 *to = '\0';
9171 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
9174 if (from) {
9175 ptr = from + 9;
9176 if ((to = strchr(ptr, '&')))
9177 *to = '\0';
9178 if ((to = strchr(ptr, ';')))
9179 *to = '\0';
9180 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
9183 if (option_debug > 1) {
9184 if (!pedanticsipchecking)
9185 ast_log(LOG_DEBUG,"Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
9186 else
9187 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>" );
9192 if ((ptr = strchr(refer_to, '@'))) { /* Separate domain */
9193 char *urioption = NULL, *domain;
9194 *ptr++ = '\0';
9196 if ((urioption = strchr(ptr, ';'))) /* Separate urioptions */
9197 *urioption++ = '\0';
9199 domain = ptr;
9200 if ((ptr = strchr(domain, ':'))) /* Remove :port */
9201 *ptr = '\0';
9203 /* Save the domain for the dial plan */
9204 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
9205 if (urioption)
9206 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
9209 if ((ptr = strchr(refer_to, ';'))) /* Remove options */
9210 *ptr = '\0';
9211 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
9213 if (referred_by_uri) {
9214 if ((ptr = strchr(referred_by_uri, ';'))) /* Remove options */
9215 *ptr = '\0';
9216 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
9217 } else {
9218 referdata->referred_by[0] = '\0';
9221 /* Determine transfer context */
9222 if (transferer->owner) /* Mimic behaviour in res_features.c */
9223 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
9225 /* By default, use the context in the channel sending the REFER */
9226 if (ast_strlen_zero(transfer_context)) {
9227 transfer_context = S_OR(transferer->owner->macrocontext,
9228 S_OR(transferer->context, default_context));
9231 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
9233 /* Either an existing extension or the parking extension */
9234 if (ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
9235 if (sip_debug_test_pvt(transferer)) {
9236 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
9238 /* We are ready to transfer to the extension */
9239 return 0;
9241 if (sip_debug_test_pvt(transferer))
9242 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
9244 /* Failure, we can't find this extension */
9245 return -1;
9249 /*! \brief Call transfer support (old way, deprecated by the IETF)--*/
9250 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
9252 char tmp[256] = "", *c, *a;
9253 struct sip_request *req = oreq ? oreq : &p->initreq;
9254 struct sip_refer *referdata = NULL;
9255 const char *transfer_context = NULL;
9257 if (!p->refer && !sip_refer_allocate(p))
9258 return -1;
9260 referdata = p->refer;
9262 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
9263 c = get_in_brackets(tmp);
9265 if (pedanticsipchecking)
9266 ast_uri_decode(c);
9268 if (strncasecmp(c, "sip:", 4)) {
9269 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
9270 return -1;
9272 c += 4;
9273 if ((a = strchr(c, ';'))) /* Remove arguments */
9274 *a = '\0';
9276 if ((a = strchr(c, '@'))) { /* Separate Domain */
9277 *a++ = '\0';
9278 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
9281 if (sip_debug_test_pvt(p))
9282 ast_verbose("Looking for %s in %s\n", c, p->context);
9284 if (p->owner) /* Mimic behaviour in res_features.c */
9285 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
9287 /* By default, use the context in the channel sending the REFER */
9288 if (ast_strlen_zero(transfer_context)) {
9289 transfer_context = S_OR(p->owner->macrocontext,
9290 S_OR(p->context, default_context));
9292 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
9293 /* This is a blind transfer */
9294 if (option_debug)
9295 ast_log(LOG_DEBUG,"SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
9296 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
9297 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
9298 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
9299 referdata->refer_call = NULL;
9300 /* Set new context */
9301 ast_string_field_set(p, context, transfer_context);
9302 return 0;
9303 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
9304 return 1;
9307 return -1;
9309 /*! \brief check Via: header for hostname, port and rport request/answer */
9310 static void check_via(struct sip_pvt *p, const struct sip_request *req)
9312 char via[512];
9313 char *c, *pt;
9314 struct hostent *hp;
9315 struct ast_hostent ahp;
9317 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
9319 /* Work on the leftmost value of the topmost Via header */
9320 c = strchr(via, ',');
9321 if (c)
9322 *c = '\0';
9324 /* Check for rport */
9325 c = strstr(via, ";rport");
9326 if (c && (c[6] != '=')) /* rport query, not answer */
9327 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
9329 c = strchr(via, ';');
9330 if (c)
9331 *c = '\0';
9333 c = strchr(via, ' ');
9334 if (c) {
9335 *c = '\0';
9336 c = ast_skip_blanks(c+1);
9337 if (strcasecmp(via, "SIP/2.0/UDP")) {
9338 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
9339 return;
9341 pt = strchr(c, ':');
9342 if (pt)
9343 *pt++ = '\0'; /* remember port pointer */
9344 hp = ast_gethostbyname(c, &ahp);
9345 if (!hp) {
9346 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
9347 return;
9349 memset(&p->sa, 0, sizeof(p->sa));
9350 p->sa.sin_family = AF_INET;
9351 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
9352 p->sa.sin_port = htons(pt ? atoi(pt) : STANDARD_SIP_PORT);
9354 if (sip_debug_test_pvt(p)) {
9355 const struct sockaddr_in *dst = sip_real_dst(p);
9356 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
9361 /*! \brief Get caller id name from SIP headers */
9362 static char *get_calleridname(const char *input, char *output, size_t outputsize)
9364 const char *end = strchr(input,'<'); /* first_bracket */
9365 const char *tmp = strchr(input,'"'); /* first quote */
9366 int bytes = 0;
9367 int maxbytes = outputsize - 1;
9369 if (!end || end == input) /* we require a part in brackets */
9370 return NULL;
9372 end--; /* move just before "<" */
9374 if (tmp && tmp <= end) {
9375 /* The quote (tmp) precedes the bracket (end+1).
9376 * Find the matching quote and return the content.
9378 end = strchr(tmp+1, '"');
9379 if (!end)
9380 return NULL;
9381 bytes = (int) (end - tmp);
9382 /* protect the output buffer */
9383 if (bytes > maxbytes)
9384 bytes = maxbytes;
9385 ast_copy_string(output, tmp + 1, bytes);
9386 } else {
9387 /* No quoted string, or it is inside brackets. */
9388 /* clear the empty characters in the begining*/
9389 input = ast_skip_blanks(input);
9390 /* clear the empty characters in the end */
9391 while(*end && *end < 33 && end > input)
9392 end--;
9393 if (end >= input) {
9394 bytes = (int) (end - input) + 2;
9395 /* protect the output buffer */
9396 if (bytes > maxbytes)
9397 bytes = maxbytes;
9398 ast_copy_string(output, input, bytes);
9399 } else
9400 return NULL;
9402 return output;
9405 /*! \brief Get caller id number from Remote-Party-ID header field
9406 * Returns true if number should be restricted (privacy setting found)
9407 * output is set to NULL if no number found
9409 static int get_rpid_num(const char *input, char *output, int maxlen)
9411 char *start;
9412 char *end;
9414 start = strchr(input,':');
9415 if (!start) {
9416 output[0] = '\0';
9417 return 0;
9419 start++;
9421 /* we found "number" */
9422 ast_copy_string(output,start,maxlen);
9423 output[maxlen-1] = '\0';
9425 end = strchr(output,'@');
9426 if (end)
9427 *end = '\0';
9428 else
9429 output[0] = '\0';
9430 if (strstr(input,"privacy=full") || strstr(input,"privacy=uri"))
9431 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
9433 return 0;
9437 /*! \brief Check if matching user or peer is defined
9438 Match user on From: user name and peer on IP/port
9439 This is used on first invite (not re-invites) and subscribe requests
9440 \return 0 on success, non-zero on failure
9442 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
9443 int sipmethod, char *uri, enum xmittype reliable,
9444 struct sockaddr_in *sin, struct sip_peer **authpeer)
9446 struct sip_user *user = NULL;
9447 struct sip_peer *peer;
9448 char from[256], *c;
9449 char *of;
9450 char rpid_num[50];
9451 const char *rpid;
9452 enum check_auth_result res = AUTH_SUCCESSFUL;
9453 char *t;
9454 char calleridname[50];
9455 int debug=sip_debug_test_addr(sin);
9456 struct ast_variable *tmpvar = NULL, *v = NULL;
9457 char *uri2 = ast_strdupa(uri);
9459 /* Terminate URI */
9460 t = uri2;
9461 while (*t && *t > 32 && *t != ';')
9462 t++;
9463 *t = '\0';
9464 ast_copy_string(from, get_header(req, "From"), sizeof(from)); /* XXX bug in original code, overwrote string */
9465 if (pedanticsipchecking)
9466 ast_uri_decode(from);
9467 /* XXX here tries to map the username for invite things */
9468 memset(calleridname, 0, sizeof(calleridname));
9469 get_calleridname(from, calleridname, sizeof(calleridname));
9470 if (calleridname[0])
9471 ast_string_field_set(p, cid_name, calleridname);
9473 rpid = get_header(req, "Remote-Party-ID");
9474 memset(rpid_num, 0, sizeof(rpid_num));
9475 if (!ast_strlen_zero(rpid))
9476 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
9478 of = get_in_brackets(from);
9479 if (ast_strlen_zero(p->exten)) {
9480 t = uri2;
9481 if (!strncasecmp(t, "sip:", 4))
9482 t+= 4;
9483 ast_string_field_set(p, exten, t);
9484 t = strchr(p->exten, '@');
9485 if (t)
9486 *t = '\0';
9487 if (ast_strlen_zero(p->our_contact))
9488 build_contact(p);
9490 /* save the URI part of the From header */
9491 ast_string_field_set(p, from, of);
9492 if (strncasecmp(of, "sip:", 4)) {
9493 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
9494 } else
9495 of += 4;
9496 /* Get just the username part */
9497 if ((c = strchr(of, '@'))) {
9498 char *tmp;
9499 *c = '\0';
9500 if ((c = strchr(of, ':')))
9501 *c = '\0';
9502 tmp = ast_strdupa(of);
9503 /* We need to be able to handle auth-headers looking like
9504 <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
9506 tmp = strsep(&tmp, ";");
9507 if (ast_is_shrinkable_phonenumber(tmp))
9508 ast_shrink_phone_number(tmp);
9509 ast_string_field_set(p, cid_num, tmp);
9512 if (!authpeer) /* If we are looking for a peer, don't check the user objects (or realtime) */
9513 user = find_user(of, 1);
9515 /* Find user based on user name in the from header */
9516 if (user && ast_apply_ha(user->ha, sin)) {
9517 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
9518 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9519 /* copy channel vars */
9520 for (v = user->chanvars ; v ; v = v->next) {
9521 if ((tmpvar = ast_variable_new(v->name, v->value))) {
9522 tmpvar->next = p->chanvars;
9523 p->chanvars = tmpvar;
9526 p->prefs = user->prefs;
9527 /* Set Frame packetization */
9528 if (p->rtp) {
9529 ast_rtp_codec_setpref(p->rtp, &p->prefs);
9530 p->autoframing = user->autoframing;
9532 /* replace callerid if rpid found, and not restricted */
9533 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
9534 char *tmp;
9535 if (*calleridname)
9536 ast_string_field_set(p, cid_name, calleridname);
9537 tmp = ast_strdupa(rpid_num);
9538 if (ast_is_shrinkable_phonenumber(tmp))
9539 ast_shrink_phone_number(tmp);
9540 ast_string_field_set(p, cid_num, tmp);
9543 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE) );
9545 if (!(res = check_auth(p, req, user->name, user->secret, user->md5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
9546 if (sip_cancel_destroy(p))
9547 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
9548 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
9549 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9550 /* Copy SIP extensions profile from INVITE */
9551 if (p->sipoptions)
9552 user->sipoptions = p->sipoptions;
9554 /* If we have a call limit, set flag */
9555 if (user->call_limit)
9556 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
9557 if (!ast_strlen_zero(user->context))
9558 ast_string_field_set(p, context, user->context);
9559 if (!ast_strlen_zero(user->cid_num)) {
9560 char *tmp = ast_strdupa(user->cid_num);
9561 if (ast_is_shrinkable_phonenumber(tmp))
9562 ast_shrink_phone_number(tmp);
9563 ast_string_field_set(p, cid_num, tmp);
9565 if (!ast_strlen_zero(user->cid_name))
9566 ast_string_field_set(p, cid_name, user->cid_name);
9567 ast_string_field_set(p, username, user->name);
9568 ast_string_field_set(p, peername, user->name);
9569 ast_string_field_set(p, peersecret, user->secret);
9570 ast_string_field_set(p, peermd5secret, user->md5secret);
9571 ast_string_field_set(p, subscribecontext, user->subscribecontext);
9572 ast_string_field_set(p, accountcode, user->accountcode);
9573 ast_string_field_set(p, language, user->language);
9574 ast_string_field_set(p, mohsuggest, user->mohsuggest);
9575 ast_string_field_set(p, mohinterpret, user->mohinterpret);
9576 p->allowtransfer = user->allowtransfer;
9577 p->amaflags = user->amaflags;
9578 p->callgroup = user->callgroup;
9579 p->pickupgroup = user->pickupgroup;
9580 if (user->callingpres) /* User callingpres setting will override RPID header */
9581 p->callingpres = user->callingpres;
9583 /* Set default codec settings for this call */
9584 p->capability = user->capability; /* User codec choice */
9585 p->jointcapability = user->capability; /* Our codecs */
9586 if (p->peercapability) /* AND with peer's codecs */
9587 p->jointcapability &= p->peercapability;
9588 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
9589 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
9590 p->noncodeccapability |= AST_RTP_DTMF;
9591 else
9592 p->noncodeccapability &= ~AST_RTP_DTMF;
9593 p->jointnoncodeccapability = p->noncodeccapability;
9594 if (p->t38.peercapability)
9595 p->t38.jointcapability &= p->t38.peercapability;
9596 p->maxcallbitrate = user->maxcallbitrate;
9597 /* If we do not support video, remove video from call structure */
9598 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
9599 ast_rtp_destroy(p->vrtp);
9600 p->vrtp = NULL;
9603 if (user && debug)
9604 ast_verbose("Found user '%s'\n", user->name);
9605 } else {
9606 if (user) {
9607 if (!authpeer && debug)
9608 ast_verbose("Found user '%s', but fails host access\n", user->name);
9609 ASTOBJ_UNREF(user,sip_destroy_user);
9611 user = NULL;
9614 if (!user) {
9615 /* If we didn't find a user match, check for peers */
9616 if (sipmethod == SIP_SUBSCRIBE)
9617 /* For subscribes, match on peer name only */
9618 peer = find_peer(of, NULL, 1, 0);
9619 else
9620 /* Look for peer based on the IP address we received data from */
9621 /* If peer is registered from this IP address or have this as a default
9622 IP address, this call is from the peer
9624 peer = find_peer(NULL, &p->recv, 1, 0);
9626 if (peer) {
9627 /* Set Frame packetization */
9628 if (p->rtp) {
9629 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
9630 p->autoframing = peer->autoframing;
9632 if (debug)
9633 ast_verbose("Found peer '%s'\n", peer->name);
9635 /* Take the peer */
9636 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
9637 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9639 /* Copy SIP extensions profile to peer */
9640 if (p->sipoptions)
9641 peer->sipoptions = p->sipoptions;
9643 /* replace callerid if rpid found, and not restricted */
9644 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
9645 char *tmp = ast_strdupa(rpid_num);
9646 if (*calleridname)
9647 ast_string_field_set(p, cid_name, calleridname);
9648 if (ast_is_shrinkable_phonenumber(tmp))
9649 ast_shrink_phone_number(tmp);
9650 ast_string_field_set(p, cid_num, tmp);
9652 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
9654 ast_string_field_set(p, peersecret, peer->secret);
9655 ast_string_field_set(p, peermd5secret, peer->md5secret);
9656 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
9657 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
9658 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
9659 if (peer->callingpres) /* Peer calling pres setting will override RPID */
9660 p->callingpres = peer->callingpres;
9661 if (peer->maxms && peer->lastms)
9662 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
9663 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
9664 /* Pretend there is no required authentication */
9665 ast_string_field_free(p, peersecret);
9666 ast_string_field_free(p, peermd5secret);
9668 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
9669 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
9670 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9671 /* If we have a call limit, set flag */
9672 if (peer->call_limit)
9673 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
9674 ast_string_field_set(p, peername, peer->name);
9675 ast_string_field_set(p, authname, peer->name);
9677 /* copy channel vars */
9678 for (v = peer->chanvars ; v ; v = v->next) {
9679 if ((tmpvar = ast_variable_new(v->name, v->value))) {
9680 tmpvar->next = p->chanvars;
9681 p->chanvars = tmpvar;
9684 if (authpeer) {
9685 (*authpeer) = ASTOBJ_REF(peer); /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
9688 if (!ast_strlen_zero(peer->username)) {
9689 ast_string_field_set(p, username, peer->username);
9690 /* Use the default username for authentication on outbound calls */
9691 /* XXX this takes the name from the caller... can we override ? */
9692 ast_string_field_set(p, authname, peer->username);
9694 if (!ast_strlen_zero(peer->cid_num)) {
9695 char *tmp = ast_strdupa(peer->cid_num);
9696 if (ast_is_shrinkable_phonenumber(tmp))
9697 ast_shrink_phone_number(tmp);
9698 ast_string_field_set(p, cid_num, tmp);
9700 if (!ast_strlen_zero(peer->cid_name))
9701 ast_string_field_set(p, cid_name, peer->cid_name);
9702 ast_string_field_set(p, fullcontact, peer->fullcontact);
9703 if (!ast_strlen_zero(peer->context))
9704 ast_string_field_set(p, context, peer->context);
9705 ast_string_field_set(p, peersecret, peer->secret);
9706 ast_string_field_set(p, peermd5secret, peer->md5secret);
9707 ast_string_field_set(p, language, peer->language);
9708 ast_string_field_set(p, accountcode, peer->accountcode);
9709 p->amaflags = peer->amaflags;
9710 p->callgroup = peer->callgroup;
9711 p->pickupgroup = peer->pickupgroup;
9712 p->capability = peer->capability;
9713 p->prefs = peer->prefs;
9714 p->jointcapability = peer->capability;
9715 if (p->peercapability)
9716 p->jointcapability &= p->peercapability;
9717 p->maxcallbitrate = peer->maxcallbitrate;
9718 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
9719 ast_rtp_destroy(p->vrtp);
9720 p->vrtp = NULL;
9722 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
9723 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
9724 p->noncodeccapability |= AST_RTP_DTMF;
9725 else
9726 p->noncodeccapability &= ~AST_RTP_DTMF;
9727 p->jointnoncodeccapability = p->noncodeccapability;
9728 if (p->t38.peercapability)
9729 p->t38.jointcapability &= p->t38.peercapability;
9731 ASTOBJ_UNREF(peer, sip_destroy_peer);
9732 } else {
9733 if (debug)
9734 ast_verbose("Found no matching peer or user for '%s:%d'\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
9736 /* do we allow guests? */
9737 if (!global_allowguest) {
9738 if (global_alwaysauthreject)
9739 res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
9740 else
9741 res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
9742 } else if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
9743 char *tmp = ast_strdupa(rpid_num);
9744 if (*calleridname)
9745 ast_string_field_set(p, cid_name, calleridname);
9746 if (ast_is_shrinkable_phonenumber(tmp))
9747 ast_shrink_phone_number(tmp);
9748 ast_string_field_set(p, cid_num, tmp);
9754 if (user)
9755 ASTOBJ_UNREF(user, sip_destroy_user);
9756 return res;
9759 /*! \brief Find user
9760 If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
9762 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
9764 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
9767 /*! \brief Get text out of a SIP MESSAGE packet */
9768 static int get_msg_text(char *buf, int len, struct sip_request *req)
9770 int x;
9771 int y;
9773 buf[0] = '\0';
9774 y = len - strlen(buf) - 5;
9775 if (y < 0)
9776 y = 0;
9777 for (x=0;x<req->lines;x++) {
9778 strncat(buf, req->line[x], y); /* safe */
9779 y -= strlen(req->line[x]) + 1;
9780 if (y < 0)
9781 y = 0;
9782 if (y != 0)
9783 strcat(buf, "\n"); /* safe */
9785 return 0;
9789 /*! \brief Receive SIP MESSAGE method messages
9790 \note We only handle messages within current calls currently
9791 Reference: RFC 3428 */
9792 static void receive_message(struct sip_pvt *p, struct sip_request *req)
9794 char buf[1024];
9795 struct ast_frame f;
9796 const char *content_type = get_header(req, "Content-Type");
9798 if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
9799 transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
9800 if (!p->owner)
9801 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
9802 return;
9805 if (get_msg_text(buf, sizeof(buf), req)) {
9806 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
9807 transmit_response(p, "202 Accepted", req);
9808 if (!p->owner)
9809 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
9810 return;
9813 if (p->owner) {
9814 if (sip_debug_test_pvt(p))
9815 ast_verbose("Message received: '%s'\n", buf);
9816 memset(&f, 0, sizeof(f));
9817 f.frametype = AST_FRAME_TEXT;
9818 f.subclass = 0;
9819 f.offset = 0;
9820 f.data = buf;
9821 f.datalen = strlen(buf);
9822 ast_queue_frame(p->owner, &f);
9823 transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
9824 } else { /* Message outside of a call, we do not support that */
9825 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);
9826 transmit_response(p, "405 Method Not Allowed", req); /* Good enough, or? */
9827 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
9829 return;
9832 /*! \brief CLI Command to show calls within limits set by call_limit */
9833 static int sip_show_inuse(int fd, int argc, char *argv[])
9835 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
9836 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
9837 char ilimits[40];
9838 char iused[40];
9839 int showall = FALSE;
9841 if (argc < 3)
9842 return RESULT_SHOWUSAGE;
9844 if (argc == 4 && !strcmp(argv[3],"all"))
9845 showall = TRUE;
9847 ast_cli(fd, FORMAT, "* User name", "In use", "Limit");
9848 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
9849 ASTOBJ_RDLOCK(iterator);
9850 if (iterator->call_limit)
9851 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
9852 else
9853 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
9854 snprintf(iused, sizeof(iused), "%d", iterator->inUse);
9855 if (showall || iterator->call_limit)
9856 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
9857 ASTOBJ_UNLOCK(iterator);
9858 } while (0) );
9860 ast_cli(fd, FORMAT, "* Peer name", "In use", "Limit");
9862 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
9863 ASTOBJ_RDLOCK(iterator);
9864 if (iterator->call_limit)
9865 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
9866 else
9867 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
9868 snprintf(iused, sizeof(iused), "%d/%d", iterator->inUse, iterator->inRinging);
9869 if (showall || iterator->call_limit)
9870 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
9871 ASTOBJ_UNLOCK(iterator);
9872 } while (0) );
9874 return RESULT_SUCCESS;
9875 #undef FORMAT
9876 #undef FORMAT2
9879 /*! \brief Convert transfer mode to text string */
9880 static char *transfermode2str(enum transfermodes mode)
9882 if (mode == TRANSFER_OPENFORALL)
9883 return "open";
9884 else if (mode == TRANSFER_CLOSED)
9885 return "closed";
9886 return "strict";
9889 /*! \brief Convert NAT setting to text string */
9890 static char *nat2str(int nat)
9892 switch(nat) {
9893 case SIP_NAT_NEVER:
9894 return "No";
9895 case SIP_NAT_ROUTE:
9896 return "Route";
9897 case SIP_NAT_ALWAYS:
9898 return "Always";
9899 case SIP_NAT_RFC3581:
9900 return "RFC3581";
9901 default:
9902 return "Unknown";
9906 /*! \brief Report Peer status in character string
9907 * \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
9909 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
9911 int res = 0;
9912 if (peer->maxms) {
9913 if (peer->lastms < 0) {
9914 ast_copy_string(status, "UNREACHABLE", statuslen);
9915 } else if (peer->lastms > peer->maxms) {
9916 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
9917 res = 1;
9918 } else if (peer->lastms) {
9919 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
9920 res = 1;
9921 } else {
9922 ast_copy_string(status, "UNKNOWN", statuslen);
9924 } else {
9925 ast_copy_string(status, "Unmonitored", statuslen);
9926 /* Checking if port is 0 */
9927 res = -1;
9929 return res;
9932 /*! \brief CLI Command 'SIP Show Users' */
9933 static int sip_show_users(int fd, int argc, char *argv[])
9935 regex_t regexbuf;
9936 int havepattern = FALSE;
9938 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
9940 switch (argc) {
9941 case 5:
9942 if (!strcasecmp(argv[3], "like")) {
9943 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
9944 return RESULT_SHOWUSAGE;
9945 havepattern = TRUE;
9946 } else
9947 return RESULT_SHOWUSAGE;
9948 case 3:
9949 break;
9950 default:
9951 return RESULT_SHOWUSAGE;
9954 ast_cli(fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
9955 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
9956 ASTOBJ_RDLOCK(iterator);
9958 if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
9959 ASTOBJ_UNLOCK(iterator);
9960 continue;
9963 ast_cli(fd, FORMAT, iterator->name,
9964 iterator->secret,
9965 iterator->accountcode,
9966 iterator->context,
9967 iterator->ha ? "Yes" : "No",
9968 nat2str(ast_test_flag(&iterator->flags[0], SIP_NAT)));
9969 ASTOBJ_UNLOCK(iterator);
9970 } while (0)
9973 if (havepattern)
9974 regfree(&regexbuf);
9976 return RESULT_SUCCESS;
9977 #undef FORMAT
9980 static char mandescr_show_peers[] =
9981 "Description: Lists SIP peers in text format with details on current status.\n"
9982 "Variables: \n"
9983 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
9985 /*! \brief Show SIP peers in the manager API */
9986 /* Inspired from chan_iax2 */
9987 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
9989 const char *id = astman_get_header(m,"ActionID");
9990 const char *a[] = {"sip", "show", "peers"};
9991 char idtext[256] = "";
9992 int total = 0;
9994 if (!ast_strlen_zero(id))
9995 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
9997 astman_send_ack(s, m, "Peer status list will follow");
9998 /* List the peers in separate manager events */
9999 _sip_show_peers(-1, &total, s, m, 3, a);
10000 /* Send final confirmation */
10001 astman_append(s,
10002 "Event: PeerlistComplete\r\n"
10003 "ListItems: %d\r\n"
10004 "%s"
10005 "\r\n", total, idtext);
10006 return 0;
10009 /*! \brief CLI Show Peers command */
10010 static int sip_show_peers(int fd, int argc, char *argv[])
10012 return _sip_show_peers(fd, NULL, NULL, NULL, argc, (const char **) argv);
10015 /*! \brief _sip_show_peers: Execute sip show peers command */
10016 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
10018 regex_t regexbuf;
10019 int havepattern = FALSE;
10021 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %-10s\n"
10022 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %-10s\n"
10024 char name[256];
10025 int total_peers = 0;
10026 int peers_mon_online = 0;
10027 int peers_mon_offline = 0;
10028 int peers_unmon_offline = 0;
10029 int peers_unmon_online = 0;
10030 const char *id;
10031 char idtext[256] = "";
10032 int realtimepeers;
10034 realtimepeers = ast_check_realtime("sippeers");
10036 if (s) { /* Manager - get ActionID */
10037 id = astman_get_header(m,"ActionID");
10038 if (!ast_strlen_zero(id))
10039 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
10042 switch (argc) {
10043 case 5:
10044 if (!strcasecmp(argv[3], "like")) {
10045 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
10046 return RESULT_SHOWUSAGE;
10047 havepattern = TRUE;
10048 } else
10049 return RESULT_SHOWUSAGE;
10050 case 3:
10051 break;
10052 default:
10053 return RESULT_SHOWUSAGE;
10056 if (!s) /* Normal list */
10057 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
10059 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
10060 char status[20] = "";
10061 char srch[2000];
10062 char pstatus;
10064 ASTOBJ_RDLOCK(iterator);
10066 if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
10067 ASTOBJ_UNLOCK(iterator);
10068 continue;
10071 if (!ast_strlen_zero(iterator->username) && !s)
10072 snprintf(name, sizeof(name), "%s/%s", iterator->name, iterator->username);
10073 else
10074 ast_copy_string(name, iterator->name, sizeof(name));
10076 pstatus = peer_status(iterator, status, sizeof(status));
10077 if (pstatus == 1)
10078 peers_mon_online++;
10079 else if (pstatus == 0)
10080 peers_mon_offline++;
10081 else {
10082 if (iterator->addr.sin_port == 0)
10083 peers_unmon_offline++;
10084 else
10085 peers_unmon_online++;
10088 snprintf(srch, sizeof(srch), FORMAT, name,
10089 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
10090 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ", /* Dynamic or not? */
10091 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
10092 iterator->ha ? " A " : " ", /* permit/deny */
10093 ntohs(iterator->addr.sin_port), status,
10094 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
10096 if (!s) {/* Normal CLI list */
10097 ast_cli(fd, FORMAT, name,
10098 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
10099 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ", /* Dynamic or not? */
10100 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
10101 iterator->ha ? " A " : " ", /* permit/deny */
10103 ntohs(iterator->addr.sin_port), status,
10104 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
10105 } else { /* Manager format */
10106 /* The names here need to be the same as other channels */
10107 astman_append(s,
10108 "Event: PeerEntry\r\n%s"
10109 "Channeltype: SIP\r\n"
10110 "ObjectName: %s\r\n"
10111 "ChanObjectType: peer\r\n" /* "peer" or "user" */
10112 "IPaddress: %s\r\n"
10113 "IPport: %d\r\n"
10114 "Dynamic: %s\r\n"
10115 "Natsupport: %s\r\n"
10116 "VideoSupport: %s\r\n"
10117 "ACL: %s\r\n"
10118 "Status: %s\r\n"
10119 "RealtimeDevice: %s\r\n\r\n",
10120 idtext,
10121 iterator->name,
10122 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "-none-",
10123 ntohs(iterator->addr.sin_port),
10124 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no", /* Dynamic or not? */
10125 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? "yes" : "no", /* NAT=yes? */
10126 ast_test_flag(&iterator->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no", /* VIDEOSUPPORT=yes? */
10127 iterator->ha ? "yes" : "no", /* permit/deny */
10128 status,
10129 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "yes":"no") : "no");
10132 ASTOBJ_UNLOCK(iterator);
10134 total_peers++;
10135 } while(0) );
10137 if (!s)
10138 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
10139 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
10141 if (havepattern)
10142 regfree(&regexbuf);
10144 if (total)
10145 *total = total_peers;
10148 return RESULT_SUCCESS;
10149 #undef FORMAT
10150 #undef FORMAT2
10153 /*! \brief List all allocated SIP Objects (realtime or static) */
10154 static int sip_show_objects(int fd, int argc, char *argv[])
10156 char tmp[256];
10157 if (argc != 3)
10158 return RESULT_SHOWUSAGE;
10159 ast_cli(fd, "-= User objects: %d static, %d realtime =-\n\n", suserobjs, ruserobjs);
10160 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &userl);
10161 ast_cli(fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
10162 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &peerl);
10163 ast_cli(fd, "-= Registry objects: %d =-\n\n", regobjs);
10164 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &regl);
10165 return RESULT_SUCCESS;
10167 /*! \brief Print call group and pickup group */
10168 static void print_group(int fd, ast_group_t group, int crlf)
10170 char buf[256];
10171 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
10174 /*! \brief Convert DTMF mode to printable string */
10175 static const char *dtmfmode2str(int mode)
10177 switch (mode) {
10178 case SIP_DTMF_RFC2833:
10179 return "rfc2833";
10180 case SIP_DTMF_INFO:
10181 return "info";
10182 case SIP_DTMF_INBAND:
10183 return "inband";
10184 case SIP_DTMF_AUTO:
10185 return "auto";
10187 return "<error>";
10190 /*! \brief Convert Insecure setting to printable string */
10191 static const char *insecure2str(int port, int invite)
10193 if (port && invite)
10194 return "port,invite";
10195 else if (port)
10196 return "port";
10197 else if (invite)
10198 return "invite";
10199 else
10200 return "no";
10203 /*! \brief Destroy disused contexts between reloads
10204 Only used in reload_config so the code for regcontext doesn't get ugly
10206 static void cleanup_stale_contexts(char *new, char *old)
10208 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
10210 while ((oldcontext = strsep(&old, "&"))) {
10211 stalecontext = '\0';
10212 ast_copy_string(newlist, new, sizeof(newlist));
10213 stringp = newlist;
10214 while ((newcontext = strsep(&stringp, "&"))) {
10215 if (strcmp(newcontext, oldcontext) == 0) {
10216 /* This is not the context you're looking for */
10217 stalecontext = '\0';
10218 break;
10219 } else if (strcmp(newcontext, oldcontext)) {
10220 stalecontext = oldcontext;
10224 if (stalecontext)
10225 ast_context_destroy(ast_context_find(stalecontext), "SIP");
10229 /*! \brief Remove temporary realtime objects from memory (CLI) */
10230 static int sip_prune_realtime(int fd, int argc, char *argv[])
10232 struct sip_peer *peer;
10233 struct sip_user *user;
10234 int pruneuser = FALSE;
10235 int prunepeer = FALSE;
10236 int multi = FALSE;
10237 char *name = NULL;
10238 regex_t regexbuf;
10240 switch (argc) {
10241 case 4:
10242 if (!strcasecmp(argv[3], "user"))
10243 return RESULT_SHOWUSAGE;
10244 if (!strcasecmp(argv[3], "peer"))
10245 return RESULT_SHOWUSAGE;
10246 if (!strcasecmp(argv[3], "like"))
10247 return RESULT_SHOWUSAGE;
10248 if (!strcasecmp(argv[3], "all")) {
10249 multi = TRUE;
10250 pruneuser = prunepeer = TRUE;
10251 } else {
10252 pruneuser = prunepeer = TRUE;
10253 name = argv[3];
10255 break;
10256 case 5:
10257 if (!strcasecmp(argv[4], "like"))
10258 return RESULT_SHOWUSAGE;
10259 if (!strcasecmp(argv[3], "all"))
10260 return RESULT_SHOWUSAGE;
10261 if (!strcasecmp(argv[3], "like")) {
10262 multi = TRUE;
10263 name = argv[4];
10264 pruneuser = prunepeer = TRUE;
10265 } else if (!strcasecmp(argv[3], "user")) {
10266 pruneuser = TRUE;
10267 if (!strcasecmp(argv[4], "all"))
10268 multi = TRUE;
10269 else
10270 name = argv[4];
10271 } else if (!strcasecmp(argv[3], "peer")) {
10272 prunepeer = TRUE;
10273 if (!strcasecmp(argv[4], "all"))
10274 multi = TRUE;
10275 else
10276 name = argv[4];
10277 } else
10278 return RESULT_SHOWUSAGE;
10279 break;
10280 case 6:
10281 if (strcasecmp(argv[4], "like"))
10282 return RESULT_SHOWUSAGE;
10283 if (!strcasecmp(argv[3], "user")) {
10284 pruneuser = TRUE;
10285 name = argv[5];
10286 } else if (!strcasecmp(argv[3], "peer")) {
10287 prunepeer = TRUE;
10288 name = argv[5];
10289 } else
10290 return RESULT_SHOWUSAGE;
10291 break;
10292 default:
10293 return RESULT_SHOWUSAGE;
10296 if (multi && name) {
10297 if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
10298 return RESULT_SHOWUSAGE;
10301 if (multi) {
10302 if (prunepeer) {
10303 int pruned = 0;
10305 ASTOBJ_CONTAINER_WRLOCK(&peerl);
10306 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
10307 ASTOBJ_RDLOCK(iterator);
10308 if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
10309 ASTOBJ_UNLOCK(iterator);
10310 continue;
10312 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10313 ASTOBJ_MARK(iterator);
10314 pruned++;
10316 ASTOBJ_UNLOCK(iterator);
10317 } while (0) );
10318 if (pruned) {
10319 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
10320 ast_cli(fd, "%d peers pruned.\n", pruned);
10321 } else
10322 ast_cli(fd, "No peers found to prune.\n");
10323 ASTOBJ_CONTAINER_UNLOCK(&peerl);
10325 if (pruneuser) {
10326 int pruned = 0;
10328 ASTOBJ_CONTAINER_WRLOCK(&userl);
10329 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
10330 ASTOBJ_RDLOCK(iterator);
10331 if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
10332 ASTOBJ_UNLOCK(iterator);
10333 continue;
10335 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10336 ASTOBJ_MARK(iterator);
10337 pruned++;
10339 ASTOBJ_UNLOCK(iterator);
10340 } while (0) );
10341 if (pruned) {
10342 ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, sip_destroy_user);
10343 ast_cli(fd, "%d users pruned.\n", pruned);
10344 } else
10345 ast_cli(fd, "No users found to prune.\n");
10346 ASTOBJ_CONTAINER_UNLOCK(&userl);
10348 } else {
10349 if (prunepeer) {
10350 if ((peer = ASTOBJ_CONTAINER_FIND_UNLINK(&peerl, name))) {
10351 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10352 ast_cli(fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
10353 ASTOBJ_CONTAINER_LINK(&peerl, peer);
10354 } else
10355 ast_cli(fd, "Peer '%s' pruned.\n", name);
10356 ASTOBJ_UNREF(peer, sip_destroy_peer);
10357 } else
10358 ast_cli(fd, "Peer '%s' not found.\n", name);
10360 if (pruneuser) {
10361 if ((user = ASTOBJ_CONTAINER_FIND_UNLINK(&userl, name))) {
10362 if (!ast_test_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10363 ast_cli(fd, "User '%s' is not a Realtime user, cannot be pruned.\n", name);
10364 ASTOBJ_CONTAINER_LINK(&userl, user);
10365 } else
10366 ast_cli(fd, "User '%s' pruned.\n", name);
10367 ASTOBJ_UNREF(user, sip_destroy_user);
10368 } else
10369 ast_cli(fd, "User '%s' not found.\n", name);
10373 return RESULT_SUCCESS;
10376 /*! \brief Print codec list from preference to CLI/manager */
10377 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
10379 int x, codec;
10381 for(x = 0; x < 32 ; x++) {
10382 codec = ast_codec_pref_index(pref, x);
10383 if (!codec)
10384 break;
10385 ast_cli(fd, "%s", ast_getformatname(codec));
10386 ast_cli(fd, ":%d", pref->framing[x]);
10387 if (x < 31 && ast_codec_pref_index(pref, x + 1))
10388 ast_cli(fd, ",");
10390 if (!x)
10391 ast_cli(fd, "none");
10394 /*! \brief Print domain mode to cli */
10395 static const char *domain_mode_to_text(const enum domain_mode mode)
10397 switch (mode) {
10398 case SIP_DOMAIN_AUTO:
10399 return "[Automatic]";
10400 case SIP_DOMAIN_CONFIG:
10401 return "[Configured]";
10404 return "";
10407 /*! \brief CLI command to list local domains */
10408 static int sip_show_domains(int fd, int argc, char *argv[])
10410 struct domain *d;
10411 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
10413 if (AST_LIST_EMPTY(&domain_list)) {
10414 ast_cli(fd, "SIP Domain support not enabled.\n\n");
10415 return RESULT_SUCCESS;
10416 } else {
10417 ast_cli(fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
10418 AST_LIST_LOCK(&domain_list);
10419 AST_LIST_TRAVERSE(&domain_list, d, list)
10420 ast_cli(fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
10421 domain_mode_to_text(d->mode));
10422 AST_LIST_UNLOCK(&domain_list);
10423 ast_cli(fd, "\n");
10424 return RESULT_SUCCESS;
10427 #undef FORMAT
10429 static char mandescr_show_peer[] =
10430 "Description: Show one SIP peer with details on current status.\n"
10431 "Variables: \n"
10432 " Peer: <name> The peer name you want to check.\n"
10433 " ActionID: <id> Optional action ID for this AMI transaction.\n";
10435 /*! \brief Show SIP peers in the manager API */
10436 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
10438 const char *a[4];
10439 const char *peer;
10440 int ret;
10442 peer = astman_get_header(m,"Peer");
10443 if (ast_strlen_zero(peer)) {
10444 astman_send_error(s, m, "Peer: <name> missing.");
10445 return 0;
10447 a[0] = "sip";
10448 a[1] = "show";
10449 a[2] = "peer";
10450 a[3] = peer;
10452 ret = _sip_show_peer(1, -1, s, m, 4, a);
10453 astman_append(s, "\r\n\r\n" );
10454 return ret;
10459 /*! \brief Show one peer in detail */
10460 static int sip_show_peer(int fd, int argc, char *argv[])
10462 return _sip_show_peer(0, fd, NULL, NULL, argc, (const char **) argv);
10465 /*! \brief Show one peer in detail (main function) */
10466 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
10468 char status[30] = "";
10469 char cbuf[256];
10470 struct sip_peer *peer;
10471 char codec_buf[512];
10472 struct ast_codec_pref *pref;
10473 struct ast_variable *v;
10474 struct sip_auth *auth;
10475 int x = 0, codec = 0, load_realtime;
10476 int realtimepeers;
10478 realtimepeers = ast_check_realtime("sippeers");
10480 if (argc < 4)
10481 return RESULT_SHOWUSAGE;
10483 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
10484 peer = find_peer(argv[3], NULL, load_realtime, 0);
10485 if (s) { /* Manager */
10486 if (peer) {
10487 const char *id = astman_get_header(m,"ActionID");
10489 astman_append(s, "Response: Success\r\n");
10490 if (!ast_strlen_zero(id))
10491 astman_append(s, "ActionID: %s\r\n",id);
10492 } else {
10493 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
10494 astman_send_error(s, m, cbuf);
10495 return 0;
10498 if (peer && type==0 ) { /* Normal listing */
10499 ast_cli(fd,"\n\n");
10500 ast_cli(fd, " * Name : %s\n", peer->name);
10501 if (realtimepeers) { /* Realtime is enabled */
10502 ast_cli(fd, " Realtime peer: %s\n", ast_test_flag(&peer->flags[0], SIP_REALTIME) ? "Yes, cached" : "No");
10504 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
10505 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
10506 for (auth = peer->auth; auth; auth = auth->next) {
10507 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
10508 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
10510 ast_cli(fd, " Context : %s\n", peer->context);
10511 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
10512 ast_cli(fd, " Language : %s\n", peer->language);
10513 if (!ast_strlen_zero(peer->accountcode))
10514 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
10515 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
10516 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
10517 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
10518 if (!ast_strlen_zero(peer->fromuser))
10519 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
10520 if (!ast_strlen_zero(peer->fromdomain))
10521 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
10522 ast_cli(fd, " Callgroup : ");
10523 print_group(fd, peer->callgroup, 0);
10524 ast_cli(fd, " Pickupgroup : ");
10525 print_group(fd, peer->pickupgroup, 0);
10526 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
10527 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
10528 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
10529 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
10530 ast_cli(fd, " Dynamic : %s\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Yes":"No"));
10531 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
10532 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
10533 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
10534 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)));
10535 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
10536 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
10537 ast_cli(fd, " T38 pt UDPTL : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL)?"Yes":"No");
10538 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10539 ast_cli(fd, " T38 pt RTP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_RTP)?"Yes":"No");
10540 ast_cli(fd, " T38 pt TCP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_TCP)?"Yes":"No");
10541 #endif
10542 ast_cli(fd, " CanReinvite : %s\n", ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Yes":"No");
10543 ast_cli(fd, " PromiscRedir : %s\n", ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Yes":"No");
10544 ast_cli(fd, " User=Phone : %s\n", ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Yes":"No");
10545 ast_cli(fd, " Video Support: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Yes":"No");
10546 ast_cli(fd, " Trust RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_TRUSTRPID) ? "Yes" : "No");
10547 ast_cli(fd, " Send RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_SENDRPID) ? "Yes" : "No");
10548 ast_cli(fd, " Subscriptions: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
10549 ast_cli(fd, " Overlap dial : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
10551 /* - is enumerated */
10552 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
10553 ast_cli(fd, " LastMsg : %d\n", peer->lastmsg);
10554 ast_cli(fd, " ToHost : %s\n", peer->tohost);
10555 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));
10556 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
10557 if (!ast_strlen_zero(global_regcontext))
10558 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
10559 ast_cli(fd, " Def. Username: %s\n", peer->username);
10560 ast_cli(fd, " SIP Options : ");
10561 if (peer->sipoptions) {
10562 int lastoption = -1;
10563 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
10564 if (sip_options[x].id != lastoption) {
10565 if (peer->sipoptions & sip_options[x].id)
10566 ast_cli(fd, "%s ", sip_options[x].text);
10567 lastoption = x;
10570 } else
10571 ast_cli(fd, "(none)");
10573 ast_cli(fd, "\n");
10574 ast_cli(fd, " Codecs : ");
10575 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
10576 ast_cli(fd, "%s\n", codec_buf);
10577 ast_cli(fd, " Codec Order : (");
10578 print_codec_to_cli(fd, &peer->prefs);
10579 ast_cli(fd, ")\n");
10581 ast_cli(fd, " Auto-Framing: %s \n", peer->autoframing ? "Yes" : "No");
10582 ast_cli(fd, " Status : ");
10583 peer_status(peer, status, sizeof(status));
10584 ast_cli(fd, "%s\n",status);
10585 ast_cli(fd, " Useragent : %s\n", peer->useragent);
10586 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
10587 if (peer->chanvars) {
10588 ast_cli(fd, " Variables :\n");
10589 for (v = peer->chanvars ; v ; v = v->next)
10590 ast_cli(fd, " %s = %s\n", v->name, v->value);
10592 ast_cli(fd,"\n");
10593 ASTOBJ_UNREF(peer,sip_destroy_peer);
10594 } else if (peer && type == 1) { /* manager listing */
10595 char buf[256];
10596 astman_append(s, "Channeltype: SIP\r\n");
10597 astman_append(s, "ObjectName: %s\r\n", peer->name);
10598 astman_append(s, "ChanObjectType: peer\r\n");
10599 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
10600 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
10601 astman_append(s, "Context: %s\r\n", peer->context);
10602 astman_append(s, "Language: %s\r\n", peer->language);
10603 if (!ast_strlen_zero(peer->accountcode))
10604 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
10605 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
10606 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
10607 if (!ast_strlen_zero(peer->fromuser))
10608 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
10609 if (!ast_strlen_zero(peer->fromdomain))
10610 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
10611 astman_append(s, "Callgroup: ");
10612 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->callgroup));
10613 astman_append(s, "Pickupgroup: ");
10614 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->pickupgroup));
10615 astman_append(s, "VoiceMailbox: %s\r\n", peer->mailbox);
10616 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
10617 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
10618 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
10619 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
10620 astman_append(s, "Dynamic: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Y":"N"));
10621 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
10622 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched,peer->expire));
10623 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)));
10624 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
10625 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
10626 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
10627 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
10628 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
10629 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
10631 /* - is enumerated */
10632 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
10633 astman_append(s, "SIPLastMsg: %d\r\n", peer->lastmsg);
10634 astman_append(s, "ToHost: %s\r\n", peer->tohost);
10635 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));
10636 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));
10637 astman_append(s, "Default-Username: %s\r\n", peer->username);
10638 if (!ast_strlen_zero(global_regcontext))
10639 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
10640 astman_append(s, "Codecs: ");
10641 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
10642 astman_append(s, "%s\r\n", codec_buf);
10643 astman_append(s, "CodecOrder: ");
10644 pref = &peer->prefs;
10645 for(x = 0; x < 32 ; x++) {
10646 codec = ast_codec_pref_index(pref,x);
10647 if (!codec)
10648 break;
10649 astman_append(s, "%s", ast_getformatname(codec));
10650 if (x < 31 && ast_codec_pref_index(pref,x+1))
10651 astman_append(s, ",");
10654 astman_append(s, "\r\n");
10655 astman_append(s, "Status: ");
10656 peer_status(peer, status, sizeof(status));
10657 astman_append(s, "%s\r\n", status);
10658 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
10659 astman_append(s, "Reg-Contact : %s\r\n", peer->fullcontact);
10660 if (peer->chanvars) {
10661 for (v = peer->chanvars ; v ; v = v->next) {
10662 astman_append(s, "ChanVariable:\n");
10663 astman_append(s, " %s,%s\r\n", v->name, v->value);
10667 ASTOBJ_UNREF(peer,sip_destroy_peer);
10669 } else {
10670 ast_cli(fd,"Peer %s not found.\n", argv[3]);
10671 ast_cli(fd,"\n");
10674 return RESULT_SUCCESS;
10677 /*! \brief Show one user in detail */
10678 static int sip_show_user(int fd, int argc, char *argv[])
10680 char cbuf[256];
10681 struct sip_user *user;
10682 struct ast_variable *v;
10683 int load_realtime;
10685 if (argc < 4)
10686 return RESULT_SHOWUSAGE;
10688 /* Load from realtime storage? */
10689 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
10691 user = find_user(argv[3], load_realtime);
10692 if (user) {
10693 ast_cli(fd,"\n\n");
10694 ast_cli(fd, " * Name : %s\n", user->name);
10695 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
10696 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
10697 ast_cli(fd, " Context : %s\n", user->context);
10698 ast_cli(fd, " Language : %s\n", user->language);
10699 if (!ast_strlen_zero(user->accountcode))
10700 ast_cli(fd, " Accountcode : %s\n", user->accountcode);
10701 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
10702 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
10703 ast_cli(fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
10704 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
10705 ast_cli(fd, " Call limit : %d\n", user->call_limit);
10706 ast_cli(fd, " Callgroup : ");
10707 print_group(fd, user->callgroup, 0);
10708 ast_cli(fd, " Pickupgroup : ");
10709 print_group(fd, user->pickupgroup, 0);
10710 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
10711 ast_cli(fd, " ACL : %s\n", (user->ha?"Yes":"No"));
10712 ast_cli(fd, " Codec Order : (");
10713 print_codec_to_cli(fd, &user->prefs);
10714 ast_cli(fd, ")\n");
10716 ast_cli(fd, " Auto-Framing: %s \n", user->autoframing ? "Yes" : "No");
10717 if (user->chanvars) {
10718 ast_cli(fd, " Variables :\n");
10719 for (v = user->chanvars ; v ; v = v->next)
10720 ast_cli(fd, " %s = %s\n", v->name, v->value);
10722 ast_cli(fd,"\n");
10723 ASTOBJ_UNREF(user,sip_destroy_user);
10724 } else {
10725 ast_cli(fd,"User %s not found.\n", argv[3]);
10726 ast_cli(fd,"\n");
10729 return RESULT_SUCCESS;
10732 /*! \brief Show SIP Registry (registrations with other SIP proxies */
10733 static int sip_show_registry(int fd, int argc, char *argv[])
10735 #define FORMAT2 "%-30.30s %-12.12s %8.8s %-20.20s %-25.25s\n"
10736 #define FORMAT "%-30.30s %-12.12s %8d %-20.20s %-25.25s\n"
10737 char host[80];
10738 char tmpdat[256];
10739 struct tm tm;
10742 if (argc != 3)
10743 return RESULT_SHOWUSAGE;
10744 ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State", "Reg.Time");
10745 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
10746 ASTOBJ_RDLOCK(iterator);
10747 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
10748 if (iterator->regtime) {
10749 ast_localtime(&iterator->regtime, &tm, NULL);
10750 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
10751 } else {
10752 tmpdat[0] = 0;
10754 ast_cli(fd, FORMAT, host, iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
10755 ASTOBJ_UNLOCK(iterator);
10756 } while(0));
10757 return RESULT_SUCCESS;
10758 #undef FORMAT
10759 #undef FORMAT2
10762 /*! \brief List global settings for the SIP channel */
10763 static int sip_show_settings(int fd, int argc, char *argv[])
10765 int realtimepeers;
10766 int realtimeusers;
10767 char codec_buf[SIPBUFSIZE];
10769 realtimepeers = ast_check_realtime("sippeers");
10770 realtimeusers = ast_check_realtime("sipusers");
10772 if (argc != 3)
10773 return RESULT_SHOWUSAGE;
10774 ast_cli(fd, "\n\nGlobal Settings:\n");
10775 ast_cli(fd, "----------------\n");
10776 ast_cli(fd, " SIP Port: %d\n", ntohs(bindaddr.sin_port));
10777 ast_cli(fd, " Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
10778 ast_cli(fd, " Videosupport: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "Yes" : "No");
10779 ast_cli(fd, " AutoCreatePeer: %s\n", autocreatepeer ? "Yes" : "No");
10780 ast_cli(fd, " Allow unknown access: %s\n", global_allowguest ? "Yes" : "No");
10781 ast_cli(fd, " Allow subscriptions: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
10782 ast_cli(fd, " Allow overlap dialing: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
10783 ast_cli(fd, " Promsic. redir: %s\n", ast_test_flag(&global_flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
10784 ast_cli(fd, " SIP domain support: %s\n", AST_LIST_EMPTY(&domain_list) ? "No" : "Yes");
10785 ast_cli(fd, " Call to non-local dom.: %s\n", allow_external_domains ? "Yes" : "No");
10786 ast_cli(fd, " URI user is phone no: %s\n", ast_test_flag(&global_flags[0], SIP_USEREQPHONE) ? "Yes" : "No");
10787 ast_cli(fd, " Our auth realm %s\n", global_realm);
10788 ast_cli(fd, " Realm. auth: %s\n", authl ? "Yes": "No");
10789 ast_cli(fd, " Always auth rejects: %s\n", global_alwaysauthreject ? "Yes" : "No");
10790 ast_cli(fd, " Call limit peers only: %s\n", global_limitonpeers ? "Yes" : "No");
10791 ast_cli(fd, " Direct RTP setup: %s\n", global_directrtpsetup ? "Yes" : "No");
10792 ast_cli(fd, " User Agent: %s\n", global_useragent);
10793 ast_cli(fd, " MWI checking interval: %d secs\n", global_mwitime);
10794 ast_cli(fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
10795 ast_cli(fd, " Caller ID: %s\n", default_callerid);
10796 ast_cli(fd, " From: Domain: %s\n", default_fromdomain);
10797 ast_cli(fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
10798 ast_cli(fd, " Call Events: %s\n", global_callevents ? "On" : "Off");
10799 ast_cli(fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
10800 ast_cli(fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
10801 ast_cli(fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
10802 ast_cli(fd, " T38 fax pt UDPTL: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_UDPTL) ? "Yes" : "No");
10803 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10804 ast_cli(fd, " T38 fax pt RTP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_RTP) ? "Yes" : "No");
10805 ast_cli(fd, " T38 fax pt TCP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_TCP) ? "Yes" : "No");
10806 #endif
10807 ast_cli(fd, " RFC2833 Compensation: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE) ? "Yes" : "No");
10808 if (!realtimepeers && !realtimeusers)
10809 ast_cli(fd, " SIP realtime: Disabled\n" );
10810 else
10811 ast_cli(fd, " SIP realtime: Enabled\n" );
10813 ast_cli(fd, "\nGlobal Signalling Settings:\n");
10814 ast_cli(fd, "---------------------------\n");
10815 ast_cli(fd, " Codecs: ");
10816 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
10817 ast_cli(fd, "%s\n", codec_buf);
10818 ast_cli(fd, " Codec Order: ");
10819 print_codec_to_cli(fd, &default_prefs);
10820 ast_cli(fd, "\n");
10821 ast_cli(fd, " T1 minimum: %d\n", global_t1min);
10822 ast_cli(fd, " Relax DTMF: %s\n", global_relaxdtmf ? "Yes" : "No");
10823 ast_cli(fd, " Compact SIP headers: %s\n", compactheaders ? "Yes" : "No");
10824 ast_cli(fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
10825 ast_cli(fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
10826 ast_cli(fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
10827 ast_cli(fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
10828 ast_cli(fd, " DNS SRV lookup: %s\n", srvlookup ? "Yes" : "No");
10829 ast_cli(fd, " Pedantic SIP support: %s\n", pedanticsipchecking ? "Yes" : "No");
10830 ast_cli(fd, " Reg. min duration %d secs\n", min_expiry);
10831 ast_cli(fd, " Reg. max duration: %d secs\n", max_expiry);
10832 ast_cli(fd, " Reg. default duration: %d secs\n", default_expiry);
10833 ast_cli(fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
10834 ast_cli(fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
10835 ast_cli(fd, " Notify ringing state: %s\n", global_notifyringing ? "Yes" : "No");
10836 ast_cli(fd, " Notify hold state: %s\n", global_notifyhold ? "Yes" : "No");
10837 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(global_allowtransfer));
10838 ast_cli(fd, " Max Call Bitrate: %d kbps\r\n", default_maxcallbitrate);
10839 ast_cli(fd, " Auto-Framing: %s \r\n", global_autoframing ? "Yes" : "No");
10840 ast_cli(fd, "\nDefault Settings:\n");
10841 ast_cli(fd, "-----------------\n");
10842 ast_cli(fd, " Context: %s\n", default_context);
10843 ast_cli(fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
10844 ast_cli(fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
10845 ast_cli(fd, " Qualify: %d\n", default_qualify);
10846 ast_cli(fd, " Use ClientCode: %s\n", ast_test_flag(&global_flags[0], SIP_USECLIENTCODE) ? "Yes" : "No");
10847 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" );
10848 ast_cli(fd, " Language: %s\n", S_OR(default_language, "(Defaults to English)"));
10849 ast_cli(fd, " MOH Interpret: %s\n", default_mohinterpret);
10850 ast_cli(fd, " MOH Suggest: %s\n", default_mohsuggest);
10851 ast_cli(fd, " Voice Mail Extension: %s\n", default_vmexten);
10854 if (realtimepeers || realtimeusers) {
10855 ast_cli(fd, "\nRealtime SIP Settings:\n");
10856 ast_cli(fd, "----------------------\n");
10857 ast_cli(fd, " Realtime Peers: %s\n", realtimepeers ? "Yes" : "No");
10858 ast_cli(fd, " Realtime Users: %s\n", realtimeusers ? "Yes" : "No");
10859 ast_cli(fd, " Cache Friends: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? "Yes" : "No");
10860 ast_cli(fd, " Update: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) ? "Yes" : "No");
10861 ast_cli(fd, " Ignore Reg. Expire: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) ? "Yes" : "No");
10862 ast_cli(fd, " Save sys. name: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME) ? "Yes" : "No");
10863 ast_cli(fd, " Auto Clear: %d\n", global_rtautoclear);
10865 ast_cli(fd, "\n----\n");
10866 return RESULT_SUCCESS;
10869 /*! \brief Show subscription type in string format */
10870 static const char *subscription_type2str(enum subscriptiontype subtype)
10872 int i;
10874 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10875 if (subscription_types[i].type == subtype) {
10876 return subscription_types[i].text;
10879 return subscription_types[0].text;
10882 /*! \brief Find subscription type in array */
10883 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
10885 int i;
10887 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10888 if (subscription_types[i].type == subtype) {
10889 return &subscription_types[i];
10892 return &subscription_types[0];
10895 /*! \brief Show active SIP channels */
10896 static int sip_show_channels(int fd, int argc, char *argv[])
10898 return __sip_show_channels(fd, argc, argv, 0);
10901 /*! \brief Show active SIP subscriptions */
10902 static int sip_show_subscriptions(int fd, int argc, char *argv[])
10904 return __sip_show_channels(fd, argc, argv, 1);
10907 /*! \brief SIP show channels CLI (main function) */
10908 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions)
10910 #define FORMAT3 "%-15.15s %-10.10s %-11.11s %-15.15s %-13.13s %-15.15s %-10.10s\n"
10911 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-15.15s %-7.7s %-15.15s\n"
10912 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s\n"
10913 struct sip_pvt *cur;
10914 int numchans = 0;
10915 char *referstatus = NULL;
10917 if (argc != 3)
10918 return RESULT_SHOWUSAGE;
10919 ast_mutex_lock(&iflock);
10920 cur = iflist;
10921 if (!subscriptions)
10922 ast_cli(fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Seq (Tx/Rx)", "Format", "Hold", "Last Message");
10923 else
10924 ast_cli(fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox");
10925 for (; cur; cur = cur->next) {
10926 referstatus = "";
10927 if (cur->refer) { /* SIP transfer in progress */
10928 referstatus = referstatus2str(cur->refer->status);
10930 if (cur->subscribed == NONE && !subscriptions) {
10931 char formatbuf[SIPBUFSIZE/2];
10932 ast_cli(fd, FORMAT, ast_inet_ntoa(cur->sa.sin_addr),
10933 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10934 cur->callid,
10935 cur->ocseq, cur->icseq,
10936 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
10937 ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD) ? "Yes" : "No",
10938 ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY) ? "(d)" : "",
10939 cur->lastmsg ,
10940 referstatus
10942 numchans++;
10944 if (cur->subscribed != NONE && subscriptions) {
10945 ast_cli(fd, FORMAT3, ast_inet_ntoa(cur->sa.sin_addr),
10946 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10947 cur->callid,
10948 /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
10949 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
10950 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
10951 subscription_type2str(cur->subscribed),
10952 cur->subscribed == MWI_NOTIFICATION ? (cur->relatedpeer ? cur->relatedpeer->mailbox : "<none>") : "<none>"
10954 numchans++;
10957 ast_mutex_unlock(&iflock);
10958 if (!subscriptions)
10959 ast_cli(fd, "%d active SIP channel%s\n", numchans, (numchans != 1) ? "s" : "");
10960 else
10961 ast_cli(fd, "%d active SIP subscription%s\n", numchans, (numchans != 1) ? "s" : "");
10962 return RESULT_SUCCESS;
10963 #undef FORMAT
10964 #undef FORMAT2
10965 #undef FORMAT3
10968 /*! \brief Support routine for 'sip show channel' CLI */
10969 static char *complete_sipch(const char *line, const char *word, int pos, int state)
10971 int which=0;
10972 struct sip_pvt *cur;
10973 char *c = NULL;
10974 int wordlen = strlen(word);
10976 if (pos != 3) {
10977 return NULL;
10980 ast_mutex_lock(&iflock);
10981 for (cur = iflist; cur; cur = cur->next) {
10982 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
10983 c = ast_strdup(cur->callid);
10984 break;
10987 ast_mutex_unlock(&iflock);
10988 return c;
10991 /*! \brief Do completion on peer name */
10992 static char *complete_sip_peer(const char *word, int state, int flags2)
10994 char *result = NULL;
10995 int wordlen = strlen(word);
10996 int which = 0;
10998 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !result, do {
10999 /* locking of the object is not required because only the name and flags are being compared */
11000 if (!strncasecmp(word, iterator->name, wordlen) &&
11001 (!flags2 || ast_test_flag(&iterator->flags[1], flags2)) &&
11002 ++which > state)
11003 result = ast_strdup(iterator->name);
11004 } while(0) );
11005 return result;
11008 /*! \brief Support routine for 'sip show peer' CLI */
11009 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
11011 if (pos == 3)
11012 return complete_sip_peer(word, state, 0);
11014 return NULL;
11017 /*! \brief Support routine for 'sip debug peer' CLI */
11018 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state)
11020 if (pos == 3)
11021 return complete_sip_peer(word, state, 0);
11023 return NULL;
11026 /*! \brief Do completion on user name */
11027 static char *complete_sip_user(const char *word, int state, int flags2)
11029 char *result = NULL;
11030 int wordlen = strlen(word);
11031 int which = 0;
11033 ASTOBJ_CONTAINER_TRAVERSE(&userl, !result, do {
11034 /* locking of the object is not required because only the name and flags are being compared */
11035 if (!strncasecmp(word, iterator->name, wordlen)) {
11036 if (flags2 && !ast_test_flag(&iterator->flags[1], flags2))
11037 continue;
11038 if (++which > state) {
11039 result = ast_strdup(iterator->name);
11042 } while(0) );
11043 return result;
11046 /*! \brief Support routine for 'sip show user' CLI */
11047 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
11049 if (pos == 3)
11050 return complete_sip_user(word, state, 0);
11052 return NULL;
11055 /*! \brief Support routine for 'sip notify' CLI */
11056 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
11058 char *c = NULL;
11060 if (pos == 2) {
11061 int which = 0;
11062 char *cat = NULL;
11063 int wordlen = strlen(word);
11065 /* do completion for notify type */
11067 if (!notify_types)
11068 return NULL;
11070 while ( (cat = ast_category_browse(notify_types, cat)) ) {
11071 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
11072 c = ast_strdup(cat);
11073 break;
11076 return c;
11079 if (pos > 2)
11080 return complete_sip_peer(word, state, 0);
11082 return NULL;
11085 /*! \brief Support routine for 'sip prune realtime peer' CLI */
11086 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state)
11088 if (pos == 4)
11089 return complete_sip_peer(word, state, SIP_PAGE2_RTCACHEFRIENDS);
11090 return NULL;
11093 /*! \brief Support routine for 'sip prune realtime user' CLI */
11094 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state)
11096 if (pos == 4)
11097 return complete_sip_user(word, state, SIP_PAGE2_RTCACHEFRIENDS);
11099 return NULL;
11102 /*! \brief Show details of one active dialog */
11103 static int sip_show_channel(int fd, int argc, char *argv[])
11105 struct sip_pvt *cur;
11106 size_t len;
11107 int found = 0;
11109 if (argc != 4)
11110 return RESULT_SHOWUSAGE;
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 char formatbuf[SIPBUFSIZE/2];
11116 ast_cli(fd,"\n");
11117 if (cur->subscribed != NONE)
11118 ast_cli(fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
11119 else
11120 ast_cli(fd, " * SIP Call\n");
11121 ast_cli(fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
11122 ast_cli(fd, " Call-ID: %s\n", cur->callid);
11123 ast_cli(fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
11124 ast_cli(fd, " Our Codec Capability: %d\n", cur->capability);
11125 ast_cli(fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
11126 ast_cli(fd, " Their Codec Capability: %d\n", cur->peercapability);
11127 ast_cli(fd, " Joint Codec Capability: %d\n", cur->jointcapability);
11128 ast_cli(fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
11129 ast_cli(fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
11130 ast_cli(fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
11131 ast_cli(fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
11132 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
11133 ast_cli(fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
11134 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)" );
11135 ast_cli(fd, " Our Tag: %s\n", cur->tag);
11136 ast_cli(fd, " Their Tag: %s\n", cur->theirtag);
11137 ast_cli(fd, " SIP User agent: %s\n", cur->useragent);
11138 if (!ast_strlen_zero(cur->username))
11139 ast_cli(fd, " Username: %s\n", cur->username);
11140 if (!ast_strlen_zero(cur->peername))
11141 ast_cli(fd, " Peername: %s\n", cur->peername);
11142 if (!ast_strlen_zero(cur->uri))
11143 ast_cli(fd, " Original uri: %s\n", cur->uri);
11144 if (!ast_strlen_zero(cur->cid_num))
11145 ast_cli(fd, " Caller-ID: %s\n", cur->cid_num);
11146 ast_cli(fd, " Need Destroy: %d\n", ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY));
11147 ast_cli(fd, " Last Message: %s\n", cur->lastmsg);
11148 ast_cli(fd, " Promiscuous Redir: %s\n", ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
11149 ast_cli(fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
11150 ast_cli(fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
11151 ast_cli(fd, " SIP Options: ");
11152 if (cur->sipoptions) {
11153 int x;
11154 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
11155 if (cur->sipoptions & sip_options[x].id)
11156 ast_cli(fd, "%s ", sip_options[x].text);
11158 } else
11159 ast_cli(fd, "(none)\n");
11160 ast_cli(fd, "\n\n");
11161 found++;
11164 ast_mutex_unlock(&iflock);
11165 if (!found)
11166 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
11167 return RESULT_SUCCESS;
11170 /*! \brief Show history details of one dialog */
11171 static int sip_show_history(int fd, int argc, char *argv[])
11173 struct sip_pvt *cur;
11174 size_t len;
11175 int found = 0;
11177 if (argc != 4)
11178 return RESULT_SHOWUSAGE;
11179 if (!recordhistory)
11180 ast_cli(fd, "\n***Note: History recording is currently DISABLED. Use 'sip history' to ENABLE.\n");
11181 len = strlen(argv[3]);
11182 ast_mutex_lock(&iflock);
11183 for (cur = iflist; cur; cur = cur->next) {
11184 if (!strncasecmp(cur->callid, argv[3], len)) {
11185 struct sip_history *hist;
11186 int x = 0;
11188 ast_cli(fd,"\n");
11189 if (cur->subscribed != NONE)
11190 ast_cli(fd, " * Subscription\n");
11191 else
11192 ast_cli(fd, " * SIP Call\n");
11193 if (cur->history)
11194 AST_LIST_TRAVERSE(cur->history, hist, list)
11195 ast_cli(fd, "%d. %s\n", ++x, hist->event);
11196 if (x == 0)
11197 ast_cli(fd, "Call '%s' has no history\n", cur->callid);
11198 found++;
11201 ast_mutex_unlock(&iflock);
11202 if (!found)
11203 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
11204 return RESULT_SUCCESS;
11207 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
11208 static void sip_dump_history(struct sip_pvt *dialog)
11210 int x = 0;
11211 struct sip_history *hist;
11212 static int errmsg = 0;
11214 if (!dialog)
11215 return;
11217 if (!option_debug && !sipdebug) {
11218 if (!errmsg) {
11219 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
11220 errmsg = 1;
11222 return;
11225 ast_log(LOG_DEBUG, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
11226 if (dialog->subscribed)
11227 ast_log(LOG_DEBUG, " * Subscription\n");
11228 else
11229 ast_log(LOG_DEBUG, " * SIP Call\n");
11230 if (dialog->history)
11231 AST_LIST_TRAVERSE(dialog->history, hist, list)
11232 ast_log(LOG_DEBUG, " %-3.3d. %s\n", ++x, hist->event);
11233 if (!x)
11234 ast_log(LOG_DEBUG, "Call '%s' has no history\n", dialog->callid);
11235 ast_log(LOG_DEBUG, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
11239 /*! \brief Receive SIP INFO Message
11240 \note Doesn't read the duration of the DTMF signal */
11241 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
11243 char buf[1024];
11244 unsigned int event;
11245 const char *c = get_header(req, "Content-Type");
11247 /* Need to check the media/type */
11248 if (!strcasecmp(c, "application/dtmf-relay") ||
11249 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
11250 unsigned int duration = 0;
11252 /* Try getting the "signal=" part */
11253 if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
11254 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
11255 transmit_response(p, "200 OK", req); /* Should return error */
11256 return;
11257 } else {
11258 ast_copy_string(buf, c, sizeof(buf));
11261 if (!ast_strlen_zero((c = get_body(req, "Duration"))))
11262 duration = atoi(c);
11263 if (!duration)
11264 duration = 100; /* 100 ms */
11266 if (!p->owner) { /* not a PBX call */
11267 transmit_response(p, "481 Call leg/transaction does not exist", req);
11268 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11269 return;
11272 if (ast_strlen_zero(buf)) {
11273 transmit_response(p, "200 OK", req);
11274 return;
11277 if (buf[0] == '*')
11278 event = 10;
11279 else if (buf[0] == '#')
11280 event = 11;
11281 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
11282 event = 12 + buf[0] - 'A';
11283 else
11284 event = atoi(buf);
11285 if (event == 16) {
11286 /* send a FLASH event */
11287 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
11288 ast_queue_frame(p->owner, &f);
11289 if (sipdebug)
11290 ast_verbose("* DTMF-relay event received: FLASH\n");
11291 } else {
11292 /* send a DTMF event */
11293 struct ast_frame f = { AST_FRAME_DTMF, };
11294 if (event < 10) {
11295 f.subclass = '0' + event;
11296 } else if (event < 11) {
11297 f.subclass = '*';
11298 } else if (event < 12) {
11299 f.subclass = '#';
11300 } else if (event < 16) {
11301 f.subclass = 'A' + (event - 12);
11303 f.len = duration;
11304 ast_queue_frame(p->owner, &f);
11305 if (sipdebug)
11306 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
11308 transmit_response(p, "200 OK", req);
11309 return;
11310 } else if (!strcasecmp(c, "application/media_control+xml")) {
11311 /* Eh, we'll just assume it's a fast picture update for now */
11312 if (p->owner)
11313 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
11314 transmit_response(p, "200 OK", req);
11315 return;
11316 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
11317 /* Client code (from SNOM phone) */
11318 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
11319 if (p->owner && p->owner->cdr)
11320 ast_cdr_setuserfield(p->owner, c);
11321 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
11322 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
11323 transmit_response(p, "200 OK", req);
11324 } else {
11325 transmit_response(p, "403 Unauthorized", req);
11327 return;
11328 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
11329 /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
11330 transmit_response(p, "200 OK", req);
11331 return;
11334 /* Other type of INFO message, not really understood by Asterisk */
11335 /* if (get_msg_text(buf, sizeof(buf), req)) { */
11337 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
11338 transmit_response(p, "415 Unsupported media type", req);
11339 return;
11342 /*! \brief Enable SIP Debugging in CLI */
11343 static int sip_do_debug_ip(int fd, int argc, char *argv[])
11345 struct hostent *hp;
11346 struct ast_hostent ahp;
11347 int port = 0;
11348 char *p, *arg;
11350 /* sip set debug ip <ip> */
11351 if (argc != 5)
11352 return RESULT_SHOWUSAGE;
11353 p = arg = argv[4];
11354 strsep(&p, ":");
11355 if (p)
11356 port = atoi(p);
11357 hp = ast_gethostbyname(arg, &ahp);
11358 if (hp == NULL)
11359 return RESULT_SHOWUSAGE;
11361 debugaddr.sin_family = AF_INET;
11362 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
11363 debugaddr.sin_port = htons(port);
11364 if (port == 0)
11365 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
11366 else
11367 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
11369 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11371 return RESULT_SUCCESS;
11374 /*! \brief sip_do_debug_peer: Turn on SIP debugging with peer mask */
11375 static int sip_do_debug_peer(int fd, int argc, char *argv[])
11377 struct sip_peer *peer;
11378 if (argc != 5)
11379 return RESULT_SHOWUSAGE;
11380 peer = find_peer(argv[4], NULL, 1, 0);
11381 if (peer) {
11382 if (peer->addr.sin_addr.s_addr) {
11383 debugaddr.sin_family = AF_INET;
11384 debugaddr.sin_addr = peer->addr.sin_addr;
11385 debugaddr.sin_port = peer->addr.sin_port;
11386 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
11387 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11388 } else
11389 ast_cli(fd, "Unable to get IP address of peer '%s'\n", argv[4]);
11390 ASTOBJ_UNREF(peer,sip_destroy_peer);
11391 } else
11392 ast_cli(fd, "No such peer '%s'\n", argv[4]);
11393 return RESULT_SUCCESS;
11396 /*! \brief Turn on SIP debugging (CLI command) */
11397 static int sip_do_debug(int fd, int argc, char *argv[])
11399 int oldsipdebug = sipdebug_console;
11400 if (argc != 3) {
11401 if (argc != 5)
11402 return RESULT_SHOWUSAGE;
11403 else if (strcmp(argv[3], "ip") == 0)
11404 return sip_do_debug_ip(fd, argc, argv);
11405 else if (strcmp(argv[3], "peer") == 0)
11406 return sip_do_debug_peer(fd, argc, argv);
11407 else
11408 return RESULT_SHOWUSAGE;
11410 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11411 memset(&debugaddr, 0, sizeof(debugaddr));
11412 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
11413 return RESULT_SUCCESS;
11416 static int sip_do_debug_deprecated(int fd, int argc, char *argv[])
11418 int oldsipdebug = sipdebug_console;
11419 char *newargv[6] = { "sip", "set", "debug", NULL };
11420 if (argc != 2) {
11421 if (argc != 4)
11422 return RESULT_SHOWUSAGE;
11423 else if (strcmp(argv[2], "ip") == 0) {
11424 newargv[3] = argv[2];
11425 newargv[4] = argv[3];
11426 return sip_do_debug_ip(fd, argc + 1, newargv);
11427 } else if (strcmp(argv[2], "peer") == 0) {
11428 newargv[3] = argv[2];
11429 newargv[4] = argv[3];
11430 return sip_do_debug_peer(fd, argc + 1, newargv);
11431 } else
11432 return RESULT_SHOWUSAGE;
11434 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11435 memset(&debugaddr, 0, sizeof(debugaddr));
11436 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
11437 return RESULT_SUCCESS;
11440 /*! \brief Cli command to send SIP notify to peer */
11441 static int sip_notify(int fd, int argc, char *argv[])
11443 struct ast_variable *varlist;
11444 int i;
11446 if (argc < 4)
11447 return RESULT_SHOWUSAGE;
11449 if (!notify_types) {
11450 ast_cli(fd, "No %s file found, or no types listed there\n", notify_config);
11451 return RESULT_FAILURE;
11454 varlist = ast_variable_browse(notify_types, argv[2]);
11456 if (!varlist) {
11457 ast_cli(fd, "Unable to find notify type '%s'\n", argv[2]);
11458 return RESULT_FAILURE;
11461 for (i = 3; i < argc; i++) {
11462 struct sip_pvt *p;
11463 struct sip_request req;
11464 struct ast_variable *var;
11466 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY))) {
11467 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
11468 return RESULT_FAILURE;
11471 if (create_addr(p, argv[i])) {
11472 /* Maybe they're not registered, etc. */
11473 sip_destroy(p);
11474 ast_cli(fd, "Could not create address for '%s'\n", argv[i]);
11475 continue;
11478 initreqprep(&req, p, SIP_NOTIFY);
11480 for (var = varlist; var; var = var->next)
11481 add_header(&req, var->name, ast_unescape_semicolon(var->value));
11483 /* Recalculate our side, and recalculate Call ID */
11484 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
11485 p->ourip = __ourip;
11486 build_via(p);
11487 build_callid_pvt(p);
11488 ast_cli(fd, "Sending NOTIFY of type '%s' to '%s'\n", argv[2], argv[i]);
11489 transmit_sip_request(p, &req);
11490 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11493 return RESULT_SUCCESS;
11496 /*! \brief Disable SIP Debugging in CLI */
11497 static int sip_no_debug(int fd, int argc, char *argv[])
11499 if (argc != 4)
11500 return RESULT_SHOWUSAGE;
11501 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11502 ast_cli(fd, "SIP Debugging Disabled\n");
11503 return RESULT_SUCCESS;
11506 static int sip_no_debug_deprecated(int fd, int argc, char *argv[])
11508 if (argc != 3)
11509 return RESULT_SHOWUSAGE;
11510 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11511 ast_cli(fd, "SIP Debugging Disabled\n");
11512 return RESULT_SUCCESS;
11515 /*! \brief Enable SIP History logging (CLI) */
11516 static int sip_do_history(int fd, int argc, char *argv[])
11518 if (argc != 2) {
11519 return RESULT_SHOWUSAGE;
11521 recordhistory = TRUE;
11522 ast_cli(fd, "SIP History Recording Enabled (use 'sip show history')\n");
11523 return RESULT_SUCCESS;
11526 /*! \brief Disable SIP History logging (CLI) */
11527 static int sip_no_history(int fd, int argc, char *argv[])
11529 if (argc != 3) {
11530 return RESULT_SHOWUSAGE;
11532 recordhistory = FALSE;
11533 ast_cli(fd, "SIP History Recording Disabled\n");
11534 return RESULT_SUCCESS;
11537 /*! \brief Authenticate for outbound registration */
11538 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader)
11540 char digest[1024];
11541 p->authtries++;
11542 memset(digest,0,sizeof(digest));
11543 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
11544 /* There's nothing to use for authentication */
11545 /* No digest challenge in request */
11546 if (sip_debug_test_pvt(p) && p->registry)
11547 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
11548 /* No old challenge */
11549 return -1;
11551 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
11552 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
11553 if (sip_debug_test_pvt(p) && p->registry)
11554 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
11555 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
11558 /*! \brief Add authentication on outbound SIP packet */
11559 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init)
11561 char digest[1024];
11563 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
11564 return -2;
11566 p->authtries++;
11567 if (option_debug > 1)
11568 ast_log(LOG_DEBUG, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
11569 memset(digest, 0, sizeof(digest));
11570 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
11571 /* No way to authenticate */
11572 return -1;
11574 /* Now we have a reply digest */
11575 p->options->auth = digest;
11576 p->options->authheader = respheader;
11577 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
11580 /*! \brief reply to authentication for outbound registrations
11581 \return Returns -1 if we have no auth
11582 \note This is used for register= servers in sip.conf, SIP proxies we register
11583 with for receiving calls from. */
11584 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
11586 char tmp[512];
11587 char *c;
11588 char oldnonce[256];
11590 /* table of recognised keywords, and places where they should be copied */
11591 const struct x {
11592 const char *key;
11593 int field_index;
11594 } *i, keys[] = {
11595 { "realm=", ast_string_field_index(p, realm) },
11596 { "nonce=", ast_string_field_index(p, nonce) },
11597 { "opaque=", ast_string_field_index(p, opaque) },
11598 { "qop=", ast_string_field_index(p, qop) },
11599 { "domain=", ast_string_field_index(p, domain) },
11600 { NULL, 0 },
11603 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
11604 if (ast_strlen_zero(tmp))
11605 return -1;
11606 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
11607 ast_log(LOG_WARNING, "missing Digest.\n");
11608 return -1;
11610 c = tmp + strlen("Digest ");
11611 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
11612 while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
11613 for (i = keys; i->key != NULL; i++) {
11614 char *src, *separator;
11615 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
11616 continue;
11617 /* Found. Skip keyword, take text in quotes or up to the separator. */
11618 c += strlen(i->key);
11619 if (*c == '"') {
11620 src = ++c;
11621 separator = "\"";
11622 } else {
11623 src = c;
11624 separator = ",";
11626 strsep(&c, separator); /* clear separator and move ptr */
11627 ast_string_field_index_set(p, i->field_index, src);
11628 break;
11630 if (i->key == NULL) /* not found, try ',' */
11631 strsep(&c, ",");
11633 /* Reset nonce count */
11634 if (strcmp(p->nonce, oldnonce))
11635 p->noncecount = 0;
11637 /* Save auth data for following registrations */
11638 if (p->registry) {
11639 struct sip_registry *r = p->registry;
11641 if (strcmp(r->nonce, p->nonce)) {
11642 ast_string_field_set(r, realm, p->realm);
11643 ast_string_field_set(r, nonce, p->nonce);
11644 ast_string_field_set(r, domain, p->domain);
11645 ast_string_field_set(r, opaque, p->opaque);
11646 ast_string_field_set(r, qop, p->qop);
11647 r->noncecount = 0;
11650 return build_reply_digest(p, sipmethod, digest, digest_len);
11653 /*! \brief Build reply digest
11654 \return Returns -1 if we have no auth
11655 \note Build digest challenge for authentication of peers (for registration)
11656 and users (for calls). Also used for authentication of CANCEL and BYE
11658 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
11660 char a1[256];
11661 char a2[256];
11662 char a1_hash[256];
11663 char a2_hash[256];
11664 char resp[256];
11665 char resp_hash[256];
11666 char uri[256];
11667 char opaque[256] = "";
11668 char cnonce[80];
11669 const char *username;
11670 const char *secret;
11671 const char *md5secret;
11672 struct sip_auth *auth = NULL; /* Realm authentication */
11674 if (!ast_strlen_zero(p->domain))
11675 ast_copy_string(uri, p->domain, sizeof(uri));
11676 else if (!ast_strlen_zero(p->uri))
11677 ast_copy_string(uri, p->uri, sizeof(uri));
11678 else
11679 snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, ast_inet_ntoa(p->sa.sin_addr));
11681 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
11683 /* Check if we have separate auth credentials */
11684 if(!(auth = find_realm_authentication(p->peerauth, p->realm))) /* Start with peer list */
11685 auth = find_realm_authentication(authl, p->realm); /* If not, global list */
11687 if (auth) {
11688 ast_log(LOG_DEBUG, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
11689 username = auth->username;
11690 secret = auth->secret;
11691 md5secret = auth->md5secret;
11692 if (sipdebug)
11693 ast_log(LOG_DEBUG,"Using realm %s authentication for call %s\n", p->realm, p->callid);
11694 } else {
11695 /* No authentication, use peer or register= config */
11696 username = p->authname;
11697 secret = p->peersecret;
11698 md5secret = p->peermd5secret;
11700 if (ast_strlen_zero(username)) /* We have no authentication */
11701 return -1;
11703 /* Calculate SIP digest response */
11704 snprintf(a1,sizeof(a1),"%s:%s:%s", username, p->realm, secret);
11705 snprintf(a2,sizeof(a2),"%s:%s", sip_methods[method].text, uri);
11706 if (!ast_strlen_zero(md5secret))
11707 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
11708 else
11709 ast_md5_hash(a1_hash,a1);
11710 ast_md5_hash(a2_hash,a2);
11712 p->noncecount++;
11713 if (!ast_strlen_zero(p->qop))
11714 snprintf(resp,sizeof(resp),"%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
11715 else
11716 snprintf(resp,sizeof(resp),"%s:%s:%s", a1_hash, p->nonce, a2_hash);
11717 ast_md5_hash(resp_hash, resp);
11719 /* only include the opaque string if it's set */
11720 if (!ast_strlen_zero(p->opaque)) {
11721 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
11724 /* XXX We hard code our qop to "auth" for now. XXX */
11725 if (!ast_strlen_zero(p->qop))
11726 snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s, qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, opaque, cnonce, p->noncecount);
11727 else
11728 snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s", username, p->realm, uri, p->nonce, resp_hash, opaque);
11730 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
11732 return 0;
11735 static char show_domains_usage[] =
11736 "Usage: sip show domains\n"
11737 " Lists all configured SIP local domains.\n"
11738 " Asterisk only responds to SIP messages to local domains.\n";
11740 static char notify_usage[] =
11741 "Usage: sip notify <type> <peer> [<peer>...]\n"
11742 " Send a NOTIFY message to a SIP peer or peers\n"
11743 " Message types are defined in sip_notify.conf\n";
11745 static char show_users_usage[] =
11746 "Usage: sip show users [like <pattern>]\n"
11747 " Lists all known SIP users.\n"
11748 " Optional regular expression pattern is used to filter the user list.\n";
11750 static char show_user_usage[] =
11751 "Usage: sip show user <name> [load]\n"
11752 " Shows all details on one SIP user and the current status.\n"
11753 " Option \"load\" forces lookup of peer in realtime storage.\n";
11755 static char show_inuse_usage[] =
11756 "Usage: sip show inuse [all]\n"
11757 " List all SIP users and peers usage counters and limits.\n"
11758 " Add option \"all\" to show all devices, not only those with a limit.\n";
11760 static char show_channels_usage[] =
11761 "Usage: sip show channels\n"
11762 " Lists all currently active SIP channels.\n";
11764 static char show_channel_usage[] =
11765 "Usage: sip show channel <channel>\n"
11766 " Provides detailed status on a given SIP channel.\n";
11768 static char show_history_usage[] =
11769 "Usage: sip show history <channel>\n"
11770 " Provides detailed dialog history on a given SIP channel.\n";
11772 static char show_peers_usage[] =
11773 "Usage: sip show peers [like <pattern>]\n"
11774 " Lists all known SIP peers.\n"
11775 " Optional regular expression pattern is used to filter the peer list.\n";
11777 static char show_peer_usage[] =
11778 "Usage: sip show peer <name> [load]\n"
11779 " Shows all details on one SIP peer and the current status.\n"
11780 " Option \"load\" forces lookup of peer in realtime storage.\n";
11782 static char prune_realtime_usage[] =
11783 "Usage: sip prune realtime [peer|user] [<name>|all|like <pattern>]\n"
11784 " Prunes object(s) from the cache.\n"
11785 " Optional regular expression pattern is used to filter the objects.\n";
11787 static char show_reg_usage[] =
11788 "Usage: sip show registry\n"
11789 " Lists all registration requests and status.\n";
11791 static char debug_usage[] =
11792 "Usage: sip set debug\n"
11793 " Enables dumping of SIP packets for debugging purposes\n\n"
11794 " sip set debug ip <host[:PORT]>\n"
11795 " Enables dumping of SIP packets to and from host.\n\n"
11796 " sip set debug peer <peername>\n"
11797 " Enables dumping of SIP packets to and from host.\n"
11798 " Require peer to be registered.\n";
11800 static char no_debug_usage[] =
11801 "Usage: sip set debug off\n"
11802 " Disables dumping of SIP packets for debugging purposes\n";
11804 static char no_history_usage[] =
11805 "Usage: sip history off\n"
11806 " Disables recording of SIP dialog history for debugging purposes\n";
11808 static char history_usage[] =
11809 "Usage: sip history\n"
11810 " Enables recording of SIP dialog history for debugging purposes.\n"
11811 "Use 'sip show history' to view the history of a call number.\n";
11813 static char sip_reload_usage[] =
11814 "Usage: sip reload\n"
11815 " Reloads SIP configuration from sip.conf\n";
11817 static char show_subscriptions_usage[] =
11818 "Usage: sip show subscriptions\n"
11819 " Lists active SIP subscriptions for extension states\n";
11821 static char show_objects_usage[] =
11822 "Usage: sip show objects\n"
11823 " Lists status of known SIP objects\n";
11825 static char show_settings_usage[] =
11826 "Usage: sip show settings\n"
11827 " Provides detailed list of the configuration of the SIP channel.\n";
11829 /*! \brief Read SIP header (dialplan function) */
11830 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len)
11832 struct sip_pvt *p;
11833 const char *content = NULL;
11834 AST_DECLARE_APP_ARGS(args,
11835 AST_APP_ARG(header);
11836 AST_APP_ARG(number);
11838 int i, number, start = 0;
11840 if (ast_strlen_zero(data)) {
11841 ast_log(LOG_WARNING, "This function requires a header name.\n");
11842 return -1;
11845 ast_channel_lock(chan);
11846 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
11847 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
11848 ast_channel_unlock(chan);
11849 return -1;
11852 AST_STANDARD_APP_ARGS(args, data);
11853 if (!args.number) {
11854 number = 1;
11855 } else {
11856 sscanf(args.number, "%d", &number);
11857 if (number < 1)
11858 number = 1;
11861 p = chan->tech_pvt;
11863 /* If there is no private structure, this channel is no longer alive */
11864 if (!p) {
11865 ast_channel_unlock(chan);
11866 return -1;
11869 for (i = 0; i < number; i++)
11870 content = __get_header(&p->initreq, args.header, &start);
11872 if (ast_strlen_zero(content)) {
11873 ast_channel_unlock(chan);
11874 return -1;
11877 ast_copy_string(buf, content, len);
11878 ast_channel_unlock(chan);
11880 return 0;
11883 static struct ast_custom_function sip_header_function = {
11884 .name = "SIP_HEADER",
11885 .synopsis = "Gets the specified SIP header",
11886 .syntax = "SIP_HEADER(<name>[,<number>])",
11887 .desc = "Since there are several headers (such as Via) which can occur multiple\n"
11888 "times, SIP_HEADER takes an optional second argument to specify which header with\n"
11889 "that name to retrieve. Headers start at offset 1.\n",
11890 .read = func_header_read,
11893 /*! \brief Dial plan function to check if domain is local */
11894 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11896 if (ast_strlen_zero(data)) {
11897 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
11898 return -1;
11900 if (check_sip_domain(data, NULL, 0))
11901 ast_copy_string(buf, data, len);
11902 else
11903 buf[0] = '\0';
11904 return 0;
11907 static struct ast_custom_function checksipdomain_function = {
11908 .name = "CHECKSIPDOMAIN",
11909 .synopsis = "Checks if domain is a local domain",
11910 .syntax = "CHECKSIPDOMAIN(<domain|IP>)",
11911 .read = func_check_sipdomain,
11912 .desc = "This function checks if the domain in the argument is configured\n"
11913 "as a local SIP domain that this Asterisk server is configured to handle.\n"
11914 "Returns the domain name if it is locally handled, otherwise an empty string.\n"
11915 "Check the domain= configuration in sip.conf\n",
11918 /*! \brief ${SIPPEER()} Dialplan function - reads peer data */
11919 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11921 struct sip_peer *peer;
11922 char *colname;
11924 if ((colname = strchr(data, ':'))) /*! \todo Will be deprecated after 1.4 */
11925 *colname++ = '\0';
11926 else if ((colname = strchr(data, '|')))
11927 *colname++ = '\0';
11928 else
11929 colname = "ip";
11931 if (!(peer = find_peer(data, NULL, 1, 0)))
11932 return -1;
11934 if (!strcasecmp(colname, "ip")) {
11935 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
11936 } else if (!strcasecmp(colname, "status")) {
11937 peer_status(peer, buf, len);
11938 } else if (!strcasecmp(colname, "language")) {
11939 ast_copy_string(buf, peer->language, len);
11940 } else if (!strcasecmp(colname, "regexten")) {
11941 ast_copy_string(buf, peer->regexten, len);
11942 } else if (!strcasecmp(colname, "limit")) {
11943 snprintf(buf, len, "%d", peer->call_limit);
11944 } else if (!strcasecmp(colname, "curcalls")) {
11945 snprintf(buf, len, "%d", peer->inUse);
11946 } else if (!strcasecmp(colname, "accountcode")) {
11947 ast_copy_string(buf, peer->accountcode, len);
11948 } else if (!strcasecmp(colname, "useragent")) {
11949 ast_copy_string(buf, peer->useragent, len);
11950 } else if (!strcasecmp(colname, "mailbox")) {
11951 ast_copy_string(buf, peer->mailbox, len);
11952 } else if (!strcasecmp(colname, "context")) {
11953 ast_copy_string(buf, peer->context, len);
11954 } else if (!strcasecmp(colname, "expire")) {
11955 snprintf(buf, len, "%d", peer->expire);
11956 } else if (!strcasecmp(colname, "dynamic")) {
11957 ast_copy_string(buf, (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no"), len);
11958 } else if (!strcasecmp(colname, "callerid_name")) {
11959 ast_copy_string(buf, peer->cid_name, len);
11960 } else if (!strcasecmp(colname, "callerid_num")) {
11961 ast_copy_string(buf, peer->cid_num, len);
11962 } else if (!strcasecmp(colname, "codecs")) {
11963 ast_getformatname_multiple(buf, len -1, peer->capability);
11964 } else if (!strncasecmp(colname, "codec[", 6)) {
11965 char *codecnum;
11966 int index = 0, codec = 0;
11968 codecnum = colname + 6; /* move past the '[' */
11969 codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
11970 index = atoi(codecnum);
11971 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
11972 ast_copy_string(buf, ast_getformatname(codec), len);
11976 ASTOBJ_UNREF(peer, sip_destroy_peer);
11978 return 0;
11981 /*! \brief Structure to declare a dialplan function: SIPPEER */
11982 struct ast_custom_function sippeer_function = {
11983 .name = "SIPPEER",
11984 .synopsis = "Gets SIP peer information",
11985 .syntax = "SIPPEER(<peername>[|item])",
11986 .read = function_sippeer,
11987 .desc = "Valid items are:\n"
11988 "- ip (default) The IP address.\n"
11989 "- mailbox The configured mailbox.\n"
11990 "- context The configured context.\n"
11991 "- expire The epoch time of the next expire.\n"
11992 "- dynamic Is it dynamic? (yes/no).\n"
11993 "- callerid_name The configured Caller ID name.\n"
11994 "- callerid_num The configured Caller ID number.\n"
11995 "- codecs The configured codecs.\n"
11996 "- status Status (if qualify=yes).\n"
11997 "- regexten Registration extension\n"
11998 "- limit Call limit (call-limit)\n"
11999 "- curcalls Current amount of calls \n"
12000 " Only available if call-limit is set\n"
12001 "- language Default language for peer\n"
12002 "- accountcode Account code for this peer\n"
12003 "- useragent Current user agent id for peer\n"
12004 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
12005 "\n"
12008 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
12009 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
12011 struct sip_pvt *p;
12013 *buf = 0;
12015 if (!data) {
12016 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
12017 return -1;
12020 ast_channel_lock(chan);
12021 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
12022 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
12023 ast_channel_unlock(chan);
12024 return -1;
12027 p = chan->tech_pvt;
12029 /* If there is no private structure, this channel is no longer alive */
12030 if (!p) {
12031 ast_channel_unlock(chan);
12032 return -1;
12035 if (!strcasecmp(data, "peerip")) {
12036 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
12037 } else if (!strcasecmp(data, "recvip")) {
12038 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
12039 } else if (!strcasecmp(data, "from")) {
12040 ast_copy_string(buf, p->from, len);
12041 } else if (!strcasecmp(data, "uri")) {
12042 ast_copy_string(buf, p->uri, len);
12043 } else if (!strcasecmp(data, "useragent")) {
12044 ast_copy_string(buf, p->useragent, len);
12045 } else if (!strcasecmp(data, "peername")) {
12046 ast_copy_string(buf, p->peername, len);
12047 } else if (!strcasecmp(data, "t38passthrough")) {
12048 if (p->t38.state == T38_DISABLED)
12049 ast_copy_string(buf, "0", sizeof("0"));
12050 else /* T38 is offered or enabled in this call */
12051 ast_copy_string(buf, "1", sizeof("1"));
12052 } else {
12053 ast_channel_unlock(chan);
12054 return -1;
12056 ast_channel_unlock(chan);
12058 return 0;
12061 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
12062 static struct ast_custom_function sipchaninfo_function = {
12063 .name = "SIPCHANINFO",
12064 .synopsis = "Gets the specified SIP parameter from the current channel",
12065 .syntax = "SIPCHANINFO(item)",
12066 .read = function_sipchaninfo_read,
12067 .desc = "Valid items are:\n"
12068 "- peerip The IP address of the peer.\n"
12069 "- recvip The source IP address of the peer.\n"
12070 "- from The URI from the From: header.\n"
12071 "- uri The URI from the Contact: header.\n"
12072 "- useragent The useragent.\n"
12073 "- peername The name of the peer.\n"
12074 "- t38passthrough 1 if T38 is offered or enabled in this channel, otherwise 0\n"
12077 /*! \brief Parse 302 Moved temporalily response */
12078 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
12080 char tmp[SIPBUFSIZE];
12081 char *s, *e, *uri, *t;
12082 char *domain;
12084 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
12085 if ((t = strchr(tmp, ',')))
12086 *t = '\0';
12087 s = get_in_brackets(tmp);
12088 uri = ast_strdupa(s);
12089 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
12090 if (!strncasecmp(s, "sip:", 4))
12091 s += 4;
12092 e = strchr(s, ';');
12093 if (e)
12094 *e = '\0';
12095 if (option_debug)
12096 ast_log(LOG_DEBUG, "Found promiscuous redirection to 'SIP/%s'\n", s);
12097 if (p->owner)
12098 ast_string_field_build(p->owner, call_forward, "SIP/%s", s);
12099 } else {
12100 e = strchr(tmp, '@');
12101 if (e) {
12102 *e++ = '\0';
12103 domain = e;
12104 } else {
12105 /* No username part */
12106 domain = tmp;
12108 e = strchr(s, ';'); /* Strip of parameters in the username part */
12109 if (e)
12110 *e = '\0';
12111 e = strchr(domain, ';'); /* Strip of parameters in the domain part */
12112 if (e)
12113 *e = '\0';
12115 if (!strncasecmp(s, "sip:", 4))
12116 s += 4;
12117 if (option_debug > 1)
12118 ast_log(LOG_DEBUG, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
12119 if (p->owner) {
12120 pbx_builtin_setvar_helper(p->owner, "SIPREDIRECTURI", uri);
12121 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
12122 ast_string_field_set(p->owner, call_forward, s);
12127 /*! \brief Check pending actions on SIP call */
12128 static void check_pendings(struct sip_pvt *p)
12130 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
12131 /* if we can't BYE, then this is really a pending CANCEL */
12132 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
12133 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
12134 /* Actually don't destroy us yet, wait for the 487 on our original
12135 INVITE, but do set an autodestruct just in case we never get it. */
12136 else {
12137 /* We have a pending outbound invite, don't send someting
12138 new in-transaction */
12139 if (p->pendinginvite)
12140 return;
12142 /* Perhaps there is an SD change INVITE outstanding */
12143 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
12145 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
12146 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12147 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
12148 /* if we can't REINVITE, hold it for later */
12149 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
12150 if (option_debug)
12151 ast_log(LOG_DEBUG, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
12152 } else {
12153 if (option_debug)
12154 ast_log(LOG_DEBUG, "Sending pending reinvite on '%s'\n", p->callid);
12155 /* Didn't get to reinvite yet, so do it now */
12156 transmit_reinvite_with_sdp(p);
12157 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
12162 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
12163 to avoid race conditions between asterisk servers.
12164 Called from the scheduler.
12166 static int sip_reinvite_retry(const void *data)
12168 struct sip_pvt *p = (struct sip_pvt *) data;
12170 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
12171 p->waitid = -1;
12172 return 0;
12176 /*! \brief Handle SIP response to INVITE dialogue */
12177 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
12179 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
12180 int res = 0;
12181 int xmitres = 0;
12182 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
12183 struct ast_channel *bridgepeer = NULL;
12185 if (option_debug > 3) {
12186 if (reinvite)
12187 ast_log(LOG_DEBUG, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
12188 else
12189 ast_log(LOG_DEBUG, "SIP response %d to standard invite\n", resp);
12192 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) { /* This call is already gone */
12193 if (option_debug)
12194 ast_log(LOG_DEBUG, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
12195 return;
12198 /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
12199 /* Don't auto congest anymore since we've gotten something useful back */
12200 AST_SCHED_DEL(sched, p->initid);
12202 /* RFC3261 says we must treat every 1xx response (but not 100)
12203 that we don't recognize as if it was 183.
12205 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
12206 resp = 183;
12208 /* Any response between 100 and 199 is PROCEEDING */
12209 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
12210 p->invitestate = INV_PROCEEDING;
12212 /* Final response, not 200 ? */
12213 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
12214 p->invitestate = INV_COMPLETED;
12217 switch (resp) {
12218 case 100: /* Trying */
12219 case 101: /* Dialog establishment */
12220 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12221 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12222 check_pendings(p);
12223 break;
12225 case 180: /* 180 Ringing */
12226 case 182: /* 182 Queued */
12227 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12228 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12229 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12230 ast_queue_control(p->owner, AST_CONTROL_RINGING);
12231 if (p->owner->_state != AST_STATE_UP) {
12232 ast_setstate(p->owner, AST_STATE_RINGING);
12235 if (find_sdp(req)) {
12236 if (p->invitestate != INV_CANCELLED)
12237 p->invitestate = INV_EARLY_MEDIA;
12238 res = process_sdp(p, req);
12239 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12240 /* Queue a progress frame only if we have SDP in 180 or 182 */
12241 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
12244 check_pendings(p);
12245 break;
12247 case 183: /* Session progress */
12248 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12249 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12250 /* Ignore 183 Session progress without SDP */
12251 if (find_sdp(req)) {
12252 if (p->invitestate != INV_CANCELLED)
12253 p->invitestate = INV_EARLY_MEDIA;
12254 res = process_sdp(p, req);
12255 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12256 /* Queue a progress frame */
12257 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
12260 check_pendings(p);
12261 break;
12263 case 200: /* 200 OK on invite - someone's answering our call */
12264 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12265 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12266 p->authtries = 0;
12267 if (find_sdp(req)) {
12268 if ((res = process_sdp(p, req)) && !ast_test_flag(req, SIP_PKT_IGNORE))
12269 if (!reinvite)
12270 /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
12271 /* For re-invites, we try to recover */
12272 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12275 /* Parse contact header for continued conversation */
12276 /* When we get 200 OK, we know which device (and IP) to contact for this call */
12277 /* This is important when we have a SIP proxy between us and the phone */
12278 if (outgoing) {
12279 update_call_counter(p, DEC_CALL_RINGING);
12280 parse_ok_contact(p, req);
12281 /* Save Record-Route for any later requests we make on this dialogue */
12282 if (!reinvite)
12283 build_route(p, req, 1);
12285 if(set_address_from_contact(p)) {
12286 /* Bad contact - we don't know how to reach this device */
12287 /* We need to ACK, but then send a bye */
12288 if (!p->route && !ast_test_flag(req, SIP_PKT_IGNORE))
12289 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12294 if (p->owner && (p->owner->_state == AST_STATE_UP) && (bridgepeer = ast_bridged_channel(p->owner))) { /* if this is a re-invite */
12295 struct sip_pvt *bridgepvt = NULL;
12297 if (!bridgepeer->tech) {
12298 ast_log(LOG_WARNING, "Ooooh.. no tech! That's REALLY bad\n");
12299 break;
12301 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
12302 bridgepvt = (struct sip_pvt*)(bridgepeer->tech_pvt);
12303 if (bridgepvt->udptl) {
12304 if (p->t38.state == T38_PEER_REINVITE) {
12305 sip_handle_t38_reinvite(bridgepeer, p, 0);
12306 ast_rtp_set_rtptimers_onhold(p->rtp);
12307 if (p->vrtp)
12308 ast_rtp_set_rtptimers_onhold(p->vrtp); /* Turn off RTP timers while we send fax */
12309 } else if (p->t38.state == T38_DISABLED && bridgepeer && (bridgepvt->t38.state == T38_ENABLED)) {
12310 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
12311 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
12312 /* XXXX Should we really destroy this session here, without any response at all??? */
12313 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12315 } else {
12316 if (option_debug > 1)
12317 ast_log(LOG_DEBUG, "Strange... The other side of the bridge does not have a udptl struct\n");
12318 ast_mutex_lock(&bridgepvt->lock);
12319 bridgepvt->t38.state = T38_DISABLED;
12320 ast_mutex_unlock(&bridgepvt->lock);
12321 if (option_debug)
12322 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->tech->type);
12323 p->t38.state = T38_DISABLED;
12324 if (option_debug > 1)
12325 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12327 } else {
12328 /* Other side is not a SIP channel */
12329 if (option_debug > 1)
12330 ast_log(LOG_DEBUG, "Strange... The other side of the bridge is not a SIP channel\n");
12331 p->t38.state = T38_DISABLED;
12332 if (option_debug > 1)
12333 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12336 if ((p->t38.state == T38_LOCAL_REINVITE) || (p->t38.state == T38_LOCAL_DIRECT)) {
12337 /* If there was T38 reinvite and we are supposed to answer with 200 OK than this should set us to T38 negotiated mode */
12338 p->t38.state = T38_ENABLED;
12339 if (option_debug)
12340 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12343 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12344 if (!reinvite) {
12345 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
12346 } else { /* RE-invite */
12347 ast_queue_frame(p->owner, &ast_null_frame);
12349 } else {
12350 /* It's possible we're getting an 200 OK after we've tried to disconnect
12351 by sending CANCEL */
12352 /* First send ACK, then send bye */
12353 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12354 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12356 /* If I understand this right, the branch is different for a non-200 ACK only */
12357 p->invitestate = INV_TERMINATED;
12358 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
12359 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
12360 check_pendings(p);
12361 break;
12362 case 407: /* Proxy authentication */
12363 case 401: /* Www auth */
12364 /* First we ACK */
12365 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12366 if (p->options)
12367 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
12369 /* Then we AUTH */
12370 ast_string_field_free(p, theirtag); /* forget their old tag, so we don't match tags when getting response */
12371 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
12372 char *authenticate = (resp == 401 ? "WWW-Authenticate" : "Proxy-Authenticate");
12373 char *authorization = (resp == 401 ? "Authorization" : "Proxy-Authorization");
12374 if (p->authtries < MAX_AUTHTRIES)
12375 p->invitestate = INV_CALLING;
12376 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, authenticate, authorization, SIP_INVITE, 1)) {
12377 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
12378 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12379 sip_alreadygone(p);
12380 if (p->owner)
12381 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12384 break;
12386 case 403: /* Forbidden */
12387 /* First we ACK */
12388 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12389 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
12390 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner)
12391 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12392 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12393 sip_alreadygone(p);
12394 break;
12396 case 404: /* Not found */
12397 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12398 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12399 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12400 sip_alreadygone(p);
12401 break;
12403 case 408: /* Request timeout */
12404 case 481: /* Call leg does not exist */
12405 /* Could be REFER caused INVITE with replaces */
12406 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
12407 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12408 if (p->owner)
12409 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12410 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12411 break;
12412 case 487: /* Cancelled transaction */
12413 /* We have sent CANCEL on an outbound INVITE
12414 This transaction is already scheduled to be killed by sip_hangup().
12416 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12417 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE)) {
12418 ast_queue_hangup(p->owner);
12419 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
12420 } else if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
12421 update_call_counter(p, DEC_CALL_LIMIT);
12422 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
12423 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12424 sip_alreadygone(p);
12426 break;
12427 case 488: /* Not acceptable here */
12428 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12429 if (reinvite && p->udptl) {
12430 /* If this is a T.38 call, we should go back to
12431 audio. If this is an audio call - something went
12432 terribly wrong since we don't renegotiate codecs,
12433 only IP/port .
12435 p->t38.state = T38_DISABLED;
12436 /* Try to reset RTP timers */
12437 ast_rtp_set_rtptimers_onhold(p->rtp);
12438 ast_log(LOG_ERROR, "Got error on T.38 re-invite. Bad configuration. Peer needs to have T.38 disabled.\n");
12440 /*! \bug Is there any way we can go back to the audio call on both
12441 sides here?
12443 /* While figuring that out, hangup the call */
12444 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12445 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12446 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12447 } else if (p->udptl && p->t38.state == T38_LOCAL_DIRECT) {
12448 /* We tried to send T.38 out in an initial INVITE and the remote side rejected it,
12449 right now we can't fall back to audio so totally abort.
12451 p->t38.state = T38_DISABLED;
12452 /* Try to reset RTP timers */
12453 ast_rtp_set_rtptimers_onhold(p->rtp);
12454 ast_log(LOG_ERROR, "Got error on T.38 initial invite. Bailing out.\n");
12456 /* The dialog is now terminated */
12457 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12458 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12459 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12460 sip_alreadygone(p);
12461 } else {
12462 /* We can't set up this call, so give up */
12463 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12464 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12465 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12466 /* If there's no dialog to end, then mark p as already gone */
12467 if (!reinvite)
12468 sip_alreadygone(p);
12470 break;
12471 case 491: /* Pending */
12472 /* we really should have to wait a while, then retransmit
12473 * We should support the retry-after at some point
12474 * At this point, we treat this as a congestion if the call is not in UP state
12476 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12477 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE)) {
12478 if (p->owner->_state != AST_STATE_UP) {
12479 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12480 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12481 } else {
12482 /* This is a re-invite that failed.
12483 * Reset the flag after a while
12485 int wait = 3 + ast_random() % 5;
12486 p->waitid = ast_sched_add(sched, wait, sip_reinvite_retry, p);
12487 if (option_debug > 2)
12488 ast_log(LOG_DEBUG, "Reinvite race. Waiting %d secs before retry\n", wait);
12491 break;
12493 case 501: /* Not implemented */
12494 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12495 if (p->owner)
12496 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12497 break;
12499 if (xmitres == XMIT_ERROR)
12500 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
12503 /* \brief Handle SIP response in REFER transaction
12504 We've sent a REFER, now handle responses to it
12506 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
12508 char *auth = "Proxy-Authenticate";
12509 char *auth2 = "Proxy-Authorization";
12511 /* If no refer structure exists, then do nothing */
12512 if (!p->refer)
12513 return;
12515 switch (resp) {
12516 case 202: /* Transfer accepted */
12517 /* We need to do something here */
12518 /* The transferee is now sending INVITE to target */
12519 p->refer->status = REFER_ACCEPTED;
12520 /* Now wait for next message */
12521 if (option_debug > 2)
12522 ast_log(LOG_DEBUG, "Got 202 accepted on transfer\n");
12523 /* We should hang along, waiting for NOTIFY's here */
12524 break;
12526 case 401: /* Not www-authorized on SIP method */
12527 case 407: /* Proxy auth */
12528 if (ast_strlen_zero(p->authname)) {
12529 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
12530 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12531 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12533 if (resp == 401) {
12534 auth = "WWW-Authenticate";
12535 auth2 = "Authorization";
12537 if ((p->authtries > 1) || do_proxy_auth(p, req, auth, auth2, SIP_REFER, 0)) {
12538 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
12539 p->refer->status = REFER_NOAUTH;
12540 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12542 break;
12543 case 481: /* Call leg does not exist */
12545 /* A transfer with Replaces did not work */
12546 /* OEJ: We should Set flag, cancel the REFER, go back
12547 to original call - but right now we can't */
12548 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
12549 if (p->owner)
12550 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12551 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12552 break;
12554 case 500: /* Server error */
12555 case 501: /* Method not implemented */
12556 /* Return to the current call onhold */
12557 /* Status flag needed to be reset */
12558 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
12559 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12560 p->refer->status = REFER_FAILED;
12561 break;
12562 case 603: /* Transfer declined */
12563 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
12564 p->refer->status = REFER_FAILED;
12565 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12566 break;
12570 /*! \brief Handle responses on REGISTER to services */
12571 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
12573 int expires, expires_ms;
12574 struct sip_registry *r;
12575 r=p->registry;
12577 switch (resp) {
12578 case 401: /* Unauthorized */
12579 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "WWW-Authenticate", "Authorization")) {
12580 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
12581 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12583 break;
12584 case 403: /* Forbidden */
12585 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
12586 if (global_regattempts_max)
12587 p->registry->regattempts = global_regattempts_max+1;
12588 AST_SCHED_DEL(sched, r->timeout);
12589 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12590 break;
12591 case 404: /* Not found */
12592 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username,p->registry->hostname);
12593 if (global_regattempts_max)
12594 p->registry->regattempts = global_regattempts_max+1;
12595 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12596 r->call = NULL;
12597 AST_SCHED_DEL(sched, r->timeout);
12598 break;
12599 case 407: /* Proxy auth */
12600 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization")) {
12601 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
12602 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12604 break;
12605 case 408: /* Request timeout */
12606 /* Got a timeout response, so reset the counter of failed responses */
12607 r->regattempts = 0;
12608 break;
12609 case 479: /* SER: Not able to process the URI - address is wrong in register*/
12610 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username,p->registry->hostname);
12611 if (global_regattempts_max)
12612 p->registry->regattempts = global_regattempts_max+1;
12613 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12614 r->call = NULL;
12615 AST_SCHED_DEL(sched, r->timeout);
12616 break;
12617 case 200: /* 200 OK */
12618 if (!r) {
12619 ast_log(LOG_WARNING, "Got 200 OK on REGISTER that isn't a register\n");
12620 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12621 return 0;
12624 r->regstate = REG_STATE_REGISTERED;
12625 r->regtime = time(NULL); /* Reset time of last succesful registration */
12626 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
12627 r->regattempts = 0;
12628 if (option_debug)
12629 ast_log(LOG_DEBUG, "Registration successful\n");
12630 if (r->timeout > -1) {
12631 if (option_debug)
12632 ast_log(LOG_DEBUG, "Cancelling timeout %d\n", r->timeout);
12634 AST_SCHED_DEL(sched, r->timeout);
12635 r->call = NULL;
12636 p->registry = NULL;
12637 /* Let this one hang around until we have all the responses */
12638 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12639 /* ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); */
12641 /* set us up for re-registering */
12642 /* figure out how long we got registered for */
12643 AST_SCHED_DEL(sched, r->expire);
12644 /* according to section 6.13 of RFC, contact headers override
12645 expires headers, so check those first */
12646 expires = 0;
12648 /* XXX todo: try to save the extra call */
12649 if (!ast_strlen_zero(get_header(req, "Contact"))) {
12650 const char *contact = NULL;
12651 const char *tmptmp = NULL;
12652 int start = 0;
12653 for(;;) {
12654 contact = __get_header(req, "Contact", &start);
12655 /* this loop ensures we get a contact header about our register request */
12656 if(!ast_strlen_zero(contact)) {
12657 if( (tmptmp=strstr(contact, p->our_contact))) {
12658 contact=tmptmp;
12659 break;
12661 } else
12662 break;
12664 tmptmp = strcasestr(contact, "expires=");
12665 if (tmptmp) {
12666 if (sscanf(tmptmp + 8, "%d;", &expires) != 1)
12667 expires = 0;
12671 if (!expires)
12672 expires=atoi(get_header(req, "expires"));
12673 if (!expires)
12674 expires=default_expiry;
12676 expires_ms = expires * 1000;
12677 if (expires <= EXPIRY_GUARD_LIMIT)
12678 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT),EXPIRY_GUARD_MIN);
12679 else
12680 expires_ms -= EXPIRY_GUARD_SECS * 1000;
12681 if (sipdebug)
12682 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
12684 r->refresh= (int) expires_ms / 1000;
12686 /* Schedule re-registration before we expire */
12687 AST_SCHED_DEL(sched, r->expire);
12688 r->expire = ast_sched_add(sched, expires_ms, sip_reregister, r);
12689 ASTOBJ_UNREF(r, sip_registry_destroy);
12691 return 1;
12694 /*! \brief Handle qualification responses (OPTIONS) */
12695 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
12697 struct sip_peer *peer = p->relatedpeer;
12698 int statechanged, is_reachable, was_reachable;
12699 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
12702 * Compute the response time to a ping (goes in peer->lastms.)
12703 * -1 means did not respond, 0 means unknown,
12704 * 1..maxms is a valid response, >maxms means late response.
12706 if (pingtime < 1) /* zero = unknown, so round up to 1 */
12707 pingtime = 1;
12709 /* Now determine new state and whether it has changed.
12710 * Use some helper variables to simplify the writing
12711 * of the expressions.
12713 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
12714 is_reachable = pingtime <= peer->maxms;
12715 statechanged = peer->lastms == 0 /* yes, unknown before */
12716 || was_reachable != is_reachable;
12718 peer->lastms = pingtime;
12719 peer->call = NULL;
12720 if (statechanged) {
12721 const char *s = is_reachable ? "Reachable" : "Lagged";
12723 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
12724 peer->name, s, pingtime, peer->maxms);
12725 ast_device_state_changed("SIP/%s", peer->name);
12726 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
12727 "Peer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
12728 peer->name, s, pingtime);
12731 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
12732 struct sip_peer *peer_ptr = peer;
12733 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
12736 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12738 /* Try again eventually */
12739 peer->pokeexpire = ast_sched_add(sched,
12740 is_reachable ? DEFAULT_FREQ_OK : DEFAULT_FREQ_NOTOK,
12741 sip_poke_peer_s, ASTOBJ_REF(peer));
12743 if (peer->pokeexpire == -1) {
12744 ASTOBJ_UNREF(peer, sip_destroy_peer);
12748 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
12749 static void stop_media_flows(struct sip_pvt *p)
12751 /* Immediately stop RTP, VRTP and UDPTL as applicable */
12752 if (p->rtp)
12753 ast_rtp_stop(p->rtp);
12754 if (p->vrtp)
12755 ast_rtp_stop(p->vrtp);
12756 if (p->udptl)
12757 ast_udptl_stop(p->udptl);
12760 /*! \brief Handle SIP response in dialogue */
12761 /* XXX only called by handle_request */
12762 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
12764 struct ast_channel *owner;
12765 int sipmethod;
12766 int res = 1;
12767 const char *c = get_header(req, "Cseq");
12768 /* GCC 4.2 complains if I try to cast c as a char * when passing it to ast_skip_nonblanks, so make a copy of it */
12769 char *c_copy = ast_strdupa(c);
12770 /* Skip the Cseq and its subsequent spaces */
12771 const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
12773 if (!msg)
12774 msg = "";
12776 sipmethod = find_sip_method(msg);
12778 owner = p->owner;
12779 if (owner)
12780 owner->hangupcause = hangup_sip2cause(resp);
12782 /* Acknowledge whatever it is destined for */
12783 if ((resp >= 100) && (resp <= 199))
12784 __sip_semi_ack(p, seqno, 0, sipmethod);
12785 else
12786 __sip_ack(p, seqno, 0, sipmethod);
12788 /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
12789 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite)
12790 p->pendinginvite = 0;
12792 /* Get their tag if we haven't already */
12793 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
12794 char tag[128];
12796 gettag(req, "To", tag, sizeof(tag));
12797 ast_string_field_set(p, theirtag, tag);
12799 if (p->relatedpeer && p->method == SIP_OPTIONS) {
12800 /* We don't really care what the response is, just that it replied back.
12801 Well, as long as it's not a 100 response... since we might
12802 need to hang around for something more "definitive" */
12803 if (resp != 100)
12804 handle_response_peerpoke(p, resp, req);
12805 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12806 switch(resp) {
12807 case 100: /* 100 Trying */
12808 case 101: /* 101 Dialog establishment */
12809 if (sipmethod == SIP_INVITE)
12810 handle_response_invite(p, resp, rest, req, seqno);
12811 break;
12812 case 183: /* 183 Session Progress */
12813 if (sipmethod == SIP_INVITE)
12814 handle_response_invite(p, resp, rest, req, seqno);
12815 break;
12816 case 180: /* 180 Ringing */
12817 if (sipmethod == SIP_INVITE)
12818 handle_response_invite(p, resp, rest, req, seqno);
12819 break;
12820 case 182: /* 182 Queued */
12821 if (sipmethod == SIP_INVITE)
12822 handle_response_invite(p, resp, rest, req, seqno);
12823 break;
12824 case 200: /* 200 OK */
12825 p->authtries = 0; /* Reset authentication counter */
12826 if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
12827 /* We successfully transmitted a message
12828 or a video update request in INFO */
12829 /* Nothing happens here - the message is inside a dialog */
12830 } else if (sipmethod == SIP_INVITE) {
12831 handle_response_invite(p, resp, rest, req, seqno);
12832 } else if (sipmethod == SIP_NOTIFY) {
12833 /* They got the notify, this is the end */
12834 if (p->owner) {
12835 if (!p->refer) {
12836 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
12837 ast_queue_hangup(p->owner);
12838 } else if (option_debug > 3)
12839 ast_log(LOG_DEBUG, "Got OK on REFER Notify message\n");
12840 } else {
12841 if (p->subscribed == NONE)
12842 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12843 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
12844 /* Ready to send the next state we have on queue */
12845 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
12846 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
12849 } else if (sipmethod == SIP_REGISTER)
12850 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12851 else if (sipmethod == SIP_BYE) { /* Ok, we're ready to go */
12852 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12853 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
12854 } else if (sipmethod == SIP_SUBSCRIBE)
12855 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
12856 break;
12857 case 202: /* Transfer accepted */
12858 if (sipmethod == SIP_REFER)
12859 handle_response_refer(p, resp, rest, req, seqno);
12860 break;
12861 case 401: /* Not www-authorized on SIP method */
12862 if (sipmethod == SIP_INVITE)
12863 handle_response_invite(p, resp, rest, req, seqno);
12864 else if (sipmethod == SIP_REFER)
12865 handle_response_refer(p, resp, rest, req, seqno);
12866 else if (p->registry && sipmethod == SIP_REGISTER)
12867 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12868 else if (sipmethod == SIP_BYE) {
12869 if (ast_strlen_zero(p->authname)) {
12870 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12871 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12872 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12873 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "WWW-Authenticate", "Authorization", sipmethod, 0)) {
12874 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
12875 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12876 /* We fail to auth bye on our own call, but still needs to tear down the call.
12877 Life, they call it. */
12879 } else {
12880 ast_log(LOG_WARNING, "Got authentication request (401) on unknown %s to '%s'\n", sip_methods[sipmethod].text, get_header(req, "To"));
12881 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12883 break;
12884 case 403: /* Forbidden - we failed authentication */
12885 if (sipmethod == SIP_INVITE)
12886 handle_response_invite(p, resp, rest, req, seqno);
12887 else if (p->registry && sipmethod == SIP_REGISTER)
12888 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12889 else {
12890 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
12891 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12893 break;
12894 case 404: /* Not found */
12895 if (p->registry && sipmethod == SIP_REGISTER)
12896 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12897 else if (sipmethod == SIP_INVITE)
12898 handle_response_invite(p, resp, rest, req, seqno);
12899 else if (owner)
12900 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12901 break;
12902 case 407: /* Proxy auth required */
12903 if (sipmethod == SIP_INVITE)
12904 handle_response_invite(p, resp, rest, req, seqno);
12905 else if (sipmethod == SIP_REFER)
12906 handle_response_refer(p, resp, rest, req, seqno);
12907 else if (p->registry && sipmethod == SIP_REGISTER)
12908 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12909 else if (sipmethod == SIP_BYE) {
12910 if (ast_strlen_zero(p->authname)) {
12911 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12912 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12913 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12914 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", sipmethod, 0)) {
12915 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
12916 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12918 } else /* We can't handle this, giving up in a bad way */
12919 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12921 break;
12922 case 408: /* Request timeout - terminate dialog */
12923 if (sipmethod == SIP_INVITE)
12924 handle_response_invite(p, resp, rest, req, seqno);
12925 else if (sipmethod == SIP_REGISTER)
12926 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12927 else if (sipmethod == SIP_BYE) {
12928 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12929 if (option_debug)
12930 ast_log(LOG_DEBUG, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
12931 } else {
12932 if (owner)
12933 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12934 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12936 break;
12937 case 481: /* Call leg does not exist */
12938 if (sipmethod == SIP_INVITE) {
12939 handle_response_invite(p, resp, rest, req, seqno);
12940 } else if (sipmethod == SIP_REFER) {
12941 handle_response_refer(p, resp, rest, req, seqno);
12942 } else if (sipmethod == SIP_BYE) {
12943 /* The other side has no transaction to bye,
12944 just assume it's all right then */
12945 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12946 } else if (sipmethod == SIP_CANCEL) {
12947 /* The other side has no transaction to cancel,
12948 just assume it's all right then */
12949 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12950 } else {
12951 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12952 /* Guessing that this is not an important request */
12954 break;
12955 case 487:
12956 if (sipmethod == SIP_INVITE)
12957 handle_response_invite(p, resp, rest, req, seqno);
12958 break;
12959 case 488: /* Not acceptable here - codec error */
12960 if (sipmethod == SIP_INVITE)
12961 handle_response_invite(p, resp, rest, req, seqno);
12962 break;
12963 case 491: /* Pending */
12964 if (sipmethod == SIP_INVITE)
12965 handle_response_invite(p, resp, rest, req, seqno);
12966 else {
12967 if (option_debug)
12968 ast_log(LOG_DEBUG, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
12969 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12971 break;
12972 case 501: /* Not Implemented */
12973 if (sipmethod == SIP_INVITE)
12974 handle_response_invite(p, resp, rest, req, seqno);
12975 else if (sipmethod == SIP_REFER)
12976 handle_response_refer(p, resp, rest, req, seqno);
12977 else
12978 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
12979 break;
12980 case 603: /* Declined transfer */
12981 if (sipmethod == SIP_REFER) {
12982 handle_response_refer(p, resp, rest, req, seqno);
12983 break;
12985 /* Fallthrough */
12986 default:
12987 if ((resp >= 300) && (resp < 700)) {
12988 /* Fatal response */
12989 if ((option_verbose > 2) && (resp != 487))
12990 ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
12992 if (sipmethod == SIP_INVITE)
12993 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
12995 /* XXX Locking issues?? XXX */
12996 switch(resp) {
12997 case 300: /* Multiple Choices */
12998 case 301: /* Moved permenantly */
12999 case 302: /* Moved temporarily */
13000 case 305: /* Use Proxy */
13001 parse_moved_contact(p, req);
13002 /* Fall through */
13003 case 486: /* Busy here */
13004 case 600: /* Busy everywhere */
13005 case 603: /* Decline */
13006 if (p->owner)
13007 ast_queue_control(p->owner, AST_CONTROL_BUSY);
13008 break;
13009 case 482: /*
13010 \note SIP is incapable of performing a hairpin call, which
13011 is yet another failure of not having a layer 2 (again, YAY
13012 IETF for thinking ahead). So we treat this as a call
13013 forward and hope we end up at the right place... */
13014 if (option_debug)
13015 ast_log(LOG_DEBUG, "Hairpin detected, setting up call forward for what it's worth\n");
13016 if (p->owner)
13017 ast_string_field_build(p->owner, call_forward,
13018 "Local/%s@%s", p->username, p->context);
13019 /* Fall through */
13020 case 480: /* Temporarily Unavailable */
13021 case 404: /* Not Found */
13022 case 410: /* Gone */
13023 case 400: /* Bad Request */
13024 case 500: /* Server error */
13025 if (sipmethod == SIP_REFER) {
13026 handle_response_refer(p, resp, rest, req, seqno);
13027 break;
13029 /* Fall through */
13030 case 502: /* Bad gateway */
13031 case 503: /* Service Unavailable */
13032 case 504: /* Server Timeout */
13033 if (owner)
13034 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
13035 break;
13036 default:
13037 /* Send hangup */
13038 if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
13039 ast_queue_hangup(p->owner);
13040 break;
13042 /* ACK on invite */
13043 if (sipmethod == SIP_INVITE)
13044 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
13045 if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
13046 sip_alreadygone(p);
13047 if (!p->owner)
13048 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13049 } else if ((resp >= 100) && (resp < 200)) {
13050 if (sipmethod == SIP_INVITE) {
13051 if (!ast_test_flag(req, SIP_PKT_IGNORE) && sip_cancel_destroy(p))
13052 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13053 if (find_sdp(req))
13054 process_sdp(p, req);
13055 if (p->owner) {
13056 /* Queue a progress frame */
13057 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
13060 } else
13061 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));
13063 } else {
13064 /* Responses to OUTGOING SIP requests on INCOMING calls
13065 get handled here. As well as out-of-call message responses */
13066 if (ast_test_flag(req, SIP_PKT_DEBUG))
13067 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
13069 if (sipmethod == SIP_INVITE && resp == 200) {
13070 /* Tags in early session is replaced by the tag in 200 OK, which is
13071 the final reply to our INVITE */
13072 char tag[128];
13074 gettag(req, "To", tag, sizeof(tag));
13075 ast_string_field_set(p, theirtag, tag);
13078 switch(resp) {
13079 case 200:
13080 if (sipmethod == SIP_INVITE) {
13081 handle_response_invite(p, resp, rest, req, seqno);
13082 } else if (sipmethod == SIP_CANCEL) {
13083 if (option_debug)
13084 ast_log(LOG_DEBUG, "Got 200 OK on CANCEL\n");
13086 /* Wait for 487, then destroy */
13087 } else if (sipmethod == SIP_NOTIFY) {
13088 /* They got the notify, this is the end */
13089 if (p->owner) {
13090 if (p->refer) {
13091 if (option_debug)
13092 ast_log(LOG_DEBUG, "Got 200 OK on NOTIFY for transfer\n");
13093 } else
13094 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
13095 /* ast_queue_hangup(p->owner); Disabled */
13096 } else {
13097 if (!p->subscribed && !p->refer)
13098 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13099 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
13100 /* Ready to send the next state we have on queue */
13101 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
13102 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
13105 } else if (sipmethod == SIP_BYE)
13106 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13107 else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO)
13108 /* We successfully transmitted a message or
13109 a video update request in INFO */
13111 else if (sipmethod == SIP_BYE)
13112 /* Ok, we're ready to go */
13113 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13114 break;
13115 case 202: /* Transfer accepted */
13116 if (sipmethod == SIP_REFER)
13117 handle_response_refer(p, resp, rest, req, seqno);
13118 break;
13119 case 401: /* www-auth */
13120 case 407:
13121 if (sipmethod == SIP_REFER)
13122 handle_response_refer(p, resp, rest, req, seqno);
13123 else if (sipmethod == SIP_INVITE)
13124 handle_response_invite(p, resp, rest, req, seqno);
13125 else if (sipmethod == SIP_BYE) {
13126 char *auth, *auth2;
13128 auth = (resp == 407 ? "Proxy-Authenticate" : "WWW-Authenticate");
13129 auth2 = (resp == 407 ? "Proxy-Authorization" : "Authorization");
13130 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, auth, auth2, sipmethod, 0)) {
13131 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
13132 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13135 break;
13136 case 481: /* Call leg does not exist */
13137 if (sipmethod == SIP_INVITE) {
13138 /* Re-invite failed */
13139 handle_response_invite(p, resp, rest, req, seqno);
13140 } else if (sipmethod == SIP_BYE) {
13141 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13142 } else if (sipdebug) {
13143 ast_log (LOG_DEBUG, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
13145 break;
13146 case 501: /* Not Implemented */
13147 if (sipmethod == SIP_INVITE)
13148 handle_response_invite(p, resp, rest, req, seqno);
13149 else if (sipmethod == SIP_REFER)
13150 handle_response_refer(p, resp, rest, req, seqno);
13151 break;
13152 case 603: /* Declined transfer */
13153 if (sipmethod == SIP_REFER) {
13154 handle_response_refer(p, resp, rest, req, seqno);
13155 break;
13157 /* Fallthrough */
13158 default: /* Errors without handlers */
13159 if ((resp >= 100) && (resp < 200)) {
13160 if (sipmethod == SIP_INVITE) { /* re-invite */
13161 if (!ast_test_flag(req, SIP_PKT_IGNORE) && sip_cancel_destroy(p))
13162 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13165 if ((resp >= 300) && (resp < 700)) {
13166 if ((option_verbose > 2) && (resp != 487))
13167 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));
13168 switch(resp) {
13169 case 488: /* Not acceptable here - codec error */
13170 case 603: /* Decline */
13171 case 500: /* Server error */
13172 case 502: /* Bad gateway */
13173 case 503: /* Service Unavailable */
13174 case 504: /* Server timeout */
13176 /* re-invite failed */
13177 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
13178 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13179 break;
13182 break;
13188 /*! \brief Park SIP call support function
13189 Starts in a new thread, then parks the call
13190 XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
13191 audio can't be heard before hangup
13193 static void *sip_park_thread(void *stuff)
13195 struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
13196 struct sip_dual *d;
13197 struct sip_request req;
13198 int ext;
13199 int res;
13201 d = stuff;
13202 transferee = d->chan1;
13203 transferer = d->chan2;
13204 copy_request(&req, &d->req);
13205 free(d);
13207 if (!transferee || !transferer) {
13208 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
13209 return NULL;
13211 if (option_debug > 3)
13212 ast_log(LOG_DEBUG, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
13214 ast_channel_lock(transferee);
13215 if (ast_do_masquerade(transferee)) {
13216 ast_log(LOG_WARNING, "Masquerade failed.\n");
13217 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
13218 ast_channel_unlock(transferee);
13219 return NULL;
13221 ast_channel_unlock(transferee);
13223 res = ast_park_call(transferee, transferer, 0, &ext);
13226 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
13227 if (!res) {
13228 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
13229 } else {
13230 /* Then tell the transferer what happened */
13231 sprintf(buf, "Call parked on extension '%d'", ext);
13232 transmit_message_with_text(transferer->tech_pvt, buf);
13234 #endif
13236 /* Any way back to the current call??? */
13237 /* Transmit response to the REFER request */
13238 transmit_response(transferer->tech_pvt, "202 Accepted", &req);
13239 if (!res) {
13240 /* Transfer succeeded */
13241 append_history(transferer->tech_pvt, "SIPpark","Parked call on %d", ext);
13242 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
13243 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
13244 ast_hangup(transferer); /* This will cause a BYE */
13245 if (option_debug)
13246 ast_log(LOG_DEBUG, "SIP Call parked on extension '%d'\n", ext);
13247 } else {
13248 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
13249 append_history(transferer->tech_pvt, "SIPpark","Parking failed\n");
13250 if (option_debug)
13251 ast_log(LOG_DEBUG, "SIP Call parked failed \n");
13252 /* Do not hangup call */
13254 return NULL;
13257 /*! \brief Park a call using the subsystem in res_features.c
13258 This is executed in a separate thread
13260 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
13262 struct sip_dual *d;
13263 struct ast_channel *transferee, *transferer;
13264 /* Chan2m: The transferer, chan1m: The transferee */
13265 pthread_t th;
13267 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
13268 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
13269 if ((!transferer) || (!transferee)) {
13270 if (transferee) {
13271 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13272 ast_hangup(transferee);
13274 if (transferer) {
13275 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13276 ast_hangup(transferer);
13278 return -1;
13281 /* Make formats okay */
13282 transferee->readformat = chan1->readformat;
13283 transferee->writeformat = chan1->writeformat;
13285 /* Prepare for taking over the channel */
13286 ast_channel_masquerade(transferee, chan1);
13288 /* Setup the extensions and such */
13289 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
13290 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
13291 transferee->priority = chan1->priority;
13293 /* We make a clone of the peer channel too, so we can play
13294 back the announcement */
13296 /* Make formats okay */
13297 transferer->readformat = chan2->readformat;
13298 transferer->writeformat = chan2->writeformat;
13300 /* Prepare for taking over the channel. Go ahead and grab this channel
13301 * lock here to avoid a deadlock with callbacks into the channel driver
13302 * that hold the channel lock and want the pvt lock. */
13303 while (ast_channel_trylock(chan2)) {
13304 struct sip_pvt *pvt = chan2->tech_pvt;
13305 DEADLOCK_AVOIDANCE(&pvt->lock);
13307 ast_channel_masquerade(transferer, chan2);
13308 ast_channel_unlock(chan2);
13310 /* Setup the extensions and such */
13311 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
13312 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
13313 transferer->priority = chan2->priority;
13315 ast_channel_lock(transferer);
13316 if (ast_do_masquerade(transferer)) {
13317 ast_log(LOG_WARNING, "Masquerade failed :(\n");
13318 ast_channel_unlock(transferer);
13319 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13320 ast_hangup(transferer);
13321 return -1;
13323 ast_channel_unlock(transferer);
13324 if (!transferer || !transferee) {
13325 if (!transferer) {
13326 if (option_debug)
13327 ast_log(LOG_DEBUG, "No transferer channel, giving up parking\n");
13329 if (!transferee) {
13330 if (option_debug)
13331 ast_log(LOG_DEBUG, "No transferee channel, giving up parking\n");
13333 return -1;
13335 if ((d = ast_calloc(1, sizeof(*d)))) {
13336 pthread_attr_t attr;
13338 pthread_attr_init(&attr);
13339 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
13341 /* Save original request for followup */
13342 copy_request(&d->req, req);
13343 d->chan1 = transferee; /* Transferee */
13344 d->chan2 = transferer; /* Transferer */
13345 d->seqno = seqno;
13346 if (ast_pthread_create_background(&th, &attr, sip_park_thread, d) < 0) {
13347 /* Could not start thread */
13348 free(d); /* We don't need it anymore. If thread is created, d will be free'd
13349 by sip_park_thread() */
13350 pthread_attr_destroy(&attr);
13351 return 0;
13353 pthread_attr_destroy(&attr);
13355 return -1;
13358 /*! \brief Turn off generator data
13359 XXX Does this function belong in the SIP channel?
13361 static void ast_quiet_chan(struct ast_channel *chan)
13363 if (chan && chan->_state == AST_STATE_UP) {
13364 if (ast_test_flag(chan, AST_FLAG_MOH))
13365 ast_moh_stop(chan);
13366 else if (chan->generatordata)
13367 ast_deactivate_generator(chan);
13371 /*! \brief Attempt transfer of SIP call
13372 This fix for attended transfers on a local PBX */
13373 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
13375 int res = 0;
13376 struct ast_channel *peera = NULL,
13377 *peerb = NULL,
13378 *peerc = NULL,
13379 *peerd = NULL;
13382 /* We will try to connect the transferee with the target and hangup
13383 all channels to the transferer */
13384 if (option_debug > 3) {
13385 ast_log(LOG_DEBUG, "Sip transfer:--------------------\n");
13386 if (transferer->chan1)
13387 ast_log(LOG_DEBUG, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
13388 else
13389 ast_log(LOG_DEBUG, "-- No transferer first channel - odd??? \n");
13390 if (target->chan1)
13391 ast_log(LOG_DEBUG, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
13392 else
13393 ast_log(LOG_DEBUG, "-- No target first channel ---\n");
13394 if (transferer->chan2)
13395 ast_log(LOG_DEBUG, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
13396 else
13397 ast_log(LOG_DEBUG, "-- No bridged call to transferee\n");
13398 if (target->chan2)
13399 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)");
13400 else
13401 ast_log(LOG_DEBUG, "-- No target second channel ---\n");
13402 ast_log(LOG_DEBUG, "-- END Sip transfer:--------------------\n");
13404 if (transferer->chan2) { /* We have a bridge on the transferer's channel */
13405 peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
13406 peerb = target->chan1; /* Transferer - PBX -> target channel - This will get lost in masq */
13407 peerc = transferer->chan2; /* Asterisk to Transferee */
13408 peerd = target->chan2; /* Asterisk to Target */
13409 if (option_debug > 2)
13410 ast_log(LOG_DEBUG, "SIP transfer: Four channels to handle\n");
13411 } else if (target->chan2) { /* Transferer has no bridge (IVR), but transferee */
13412 peera = target->chan1; /* Transferer to PBX -> target channel */
13413 peerb = transferer->chan1; /* Transferer to IVR*/
13414 peerc = target->chan2; /* Asterisk to Target */
13415 peerd = transferer->chan2; /* Nothing */
13416 if (option_debug > 2)
13417 ast_log(LOG_DEBUG, "SIP transfer: Three channels to handle\n");
13420 if (peera && peerb && peerc && (peerb != peerc)) {
13421 ast_quiet_chan(peera); /* Stop generators */
13422 ast_quiet_chan(peerb);
13423 ast_quiet_chan(peerc);
13424 if (peerd)
13425 ast_quiet_chan(peerd);
13427 if (option_debug > 3)
13428 ast_log(LOG_DEBUG, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
13429 if (ast_channel_masquerade(peerb, peerc)) {
13430 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
13431 res = -1;
13432 } else
13433 ast_log(LOG_DEBUG, "SIP transfer: Succeeded to masquerade channels.\n");
13434 return res;
13435 } else {
13436 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
13437 if (transferer->chan1)
13438 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
13439 if (target->chan1)
13440 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
13441 return -2;
13443 return 0;
13446 /*! \brief Get tag from packet
13448 * \return Returns the pointer to the provided tag buffer,
13449 * or NULL if the tag was not found.
13451 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
13453 const char *thetag;
13455 if (!tagbuf)
13456 return NULL;
13457 tagbuf[0] = '\0'; /* reset the buffer */
13458 thetag = get_header(req, header);
13459 thetag = strcasestr(thetag, ";tag=");
13460 if (thetag) {
13461 thetag += 5;
13462 ast_copy_string(tagbuf, thetag, tagbufsize);
13463 return strsep(&tagbuf, ";");
13465 return NULL;
13468 /*! \brief Handle incoming notifications */
13469 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
13471 /* This is mostly a skeleton for future improvements */
13472 /* Mostly created to return proper answers on notifications on outbound REFER's */
13473 int res = 0;
13474 const char *event = get_header(req, "Event");
13475 char *eventid = NULL;
13476 char *sep;
13478 if( (sep = strchr(event, ';')) ) { /* XXX bug here - overwriting string ? */
13479 *sep++ = '\0';
13480 eventid = sep;
13483 if (option_debug > 1 && sipdebug)
13484 ast_log(LOG_DEBUG, "Got NOTIFY Event: %s\n", event);
13486 if (strcmp(event, "refer")) {
13487 /* We don't understand this event. */
13488 /* Here's room to implement incoming voicemail notifications :-) */
13489 transmit_response(p, "489 Bad event", req);
13490 res = -1;
13491 } else {
13492 /* Save nesting depth for now, since there might be other events we will
13493 support in the future */
13495 /* Handle REFER notifications */
13497 char buf[1024];
13498 char *cmd, *code;
13499 int respcode;
13500 int success = TRUE;
13502 /* EventID for each transfer... EventID is basically the REFER cseq
13504 We are getting notifications on a call that we transfered
13505 We should hangup when we are getting a 200 OK in a sipfrag
13506 Check if we have an owner of this event */
13508 /* Check the content type */
13509 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
13510 /* We need a sipfrag */
13511 transmit_response(p, "400 Bad request", req);
13512 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13513 return -1;
13516 /* Get the text of the attachment */
13517 if (get_msg_text(buf, sizeof(buf), req)) {
13518 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
13519 transmit_response(p, "400 Bad request", req);
13520 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13521 return -1;
13525 From the RFC...
13526 A minimal, but complete, implementation can respond with a single
13527 NOTIFY containing either the body:
13528 SIP/2.0 100 Trying
13530 if the subscription is pending, the body:
13531 SIP/2.0 200 OK
13532 if the reference was successful, the body:
13533 SIP/2.0 503 Service Unavailable
13534 if the reference failed, or the body:
13535 SIP/2.0 603 Declined
13537 if the REFER request was accepted before approval to follow the
13538 reference could be obtained and that approval was subsequently denied
13539 (see Section 2.4.7).
13541 If there are several REFERs in the same dialog, we need to
13542 match the ID of the event header...
13544 if (option_debug > 2)
13545 ast_log(LOG_DEBUG, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
13546 cmd = ast_skip_blanks(buf);
13547 code = cmd;
13548 /* We are at SIP/2.0 */
13549 while(*code && (*code > 32)) { /* Search white space */
13550 code++;
13552 *code++ = '\0';
13553 code = ast_skip_blanks(code);
13554 sep = code;
13555 sep++;
13556 while(*sep && (*sep > 32)) { /* Search white space */
13557 sep++;
13559 *sep++ = '\0'; /* Response string */
13560 respcode = atoi(code);
13561 switch (respcode) {
13562 case 100: /* Trying: */
13563 case 101: /* dialog establishment */
13564 /* Don't do anything yet */
13565 break;
13566 case 183: /* Ringing: */
13567 /* Don't do anything yet */
13568 break;
13569 case 200: /* OK: The new call is up, hangup this call */
13570 /* Hangup the call that we are replacing */
13571 break;
13572 case 301: /* Moved permenantly */
13573 case 302: /* Moved temporarily */
13574 /* Do we get the header in the packet in this case? */
13575 success = FALSE;
13576 break;
13577 case 503: /* Service Unavailable: The new call failed */
13578 /* Cancel transfer, continue the call */
13579 success = FALSE;
13580 break;
13581 case 603: /* Declined: Not accepted */
13582 /* Cancel transfer, continue the current call */
13583 success = FALSE;
13584 break;
13586 if (!success) {
13587 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
13590 /* Confirm that we received this packet */
13591 transmit_response(p, "200 OK", req);
13594 if (!p->lastinvite)
13595 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13597 return res;
13600 /*! \brief Handle incoming OPTIONS request */
13601 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
13603 int res;
13606 /* XXX Should we authenticate OPTIONS? XXX */
13608 if (p->lastinvite) {
13609 /* if this is a request in an active dialog, just confirm that the dialog exists. */
13610 transmit_response_with_allow(p, "200 OK", req, 0);
13611 return 0;
13614 res = get_destination(p, req);
13615 build_contact(p);
13617 if (ast_strlen_zero(p->context))
13618 ast_string_field_set(p, context, default_context);
13620 if (ast_shutting_down())
13621 transmit_response_with_allow(p, "503 Unavailable", req, 0);
13622 else if (res < 0)
13623 transmit_response_with_allow(p, "404 Not Found", req, 0);
13624 else
13625 transmit_response_with_allow(p, "200 OK", req, 0);
13627 /* Destroy if this OPTIONS was the opening request, but not if
13628 it's in the middle of a normal call flow. */
13629 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13631 return res;
13634 /*! \brief Handle the transfer part of INVITE with a replaces: header,
13635 meaning a target pickup or an attended transfer */
13636 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin)
13638 struct ast_frame *f;
13639 int earlyreplace = 0;
13640 int oneleggedreplace = 0; /* Call with no bridge, propably IVR or voice message */
13641 struct ast_channel *c = p->owner; /* Our incoming call */
13642 struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
13643 struct ast_channel *targetcall; /* The bridge to the take-over target */
13645 /* Check if we're in ring state */
13646 if (replacecall->_state == AST_STATE_RING)
13647 earlyreplace = 1;
13649 /* Check if we have a bridge */
13650 if (!(targetcall = ast_bridged_channel(replacecall))) {
13651 /* We have no bridge */
13652 if (!earlyreplace) {
13653 if (option_debug > 1)
13654 ast_log(LOG_DEBUG, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
13655 oneleggedreplace = 1;
13658 if (option_debug > 3 && targetcall && targetcall->_state == AST_STATE_RINGING)
13659 ast_log(LOG_DEBUG, "SIP transfer: Target channel is in ringing state\n");
13661 if (option_debug > 3) {
13662 if (targetcall)
13663 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);
13664 else
13665 ast_log(LOG_DEBUG, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
13668 if (ignore) {
13669 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
13670 /* We should answer something here. If we are here, the
13671 call we are replacing exists, so an accepted
13672 can't harm */
13673 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
13674 /* Do something more clever here */
13675 ast_channel_unlock(c);
13676 ast_mutex_unlock(&p->refer->refer_call->lock);
13677 return 1;
13679 if (!c) {
13680 /* What to do if no channel ??? */
13681 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
13682 transmit_response_reliable(p, "503 Service Unavailable", req);
13683 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
13684 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13685 ast_mutex_unlock(&p->refer->refer_call->lock);
13686 return 1;
13688 append_history(p, "Xfer", "INVITE/Replace received");
13689 /* We have three channels to play with
13690 channel c: New incoming call
13691 targetcall: Call from PBX to target
13692 p->refer->refer_call: SIP pvt dialog from transferer to pbx.
13693 replacecall: The owner of the previous
13694 We need to masq C into refer_call to connect to
13695 targetcall;
13696 If we are talking to internal audio stream, target call is null.
13699 /* Fake call progress */
13700 transmit_response(p, "100 Trying", req);
13701 ast_setstate(c, AST_STATE_RING);
13703 /* Masquerade the new call into the referred call to connect to target call
13704 Targetcall is not touched by the masq */
13706 /* Answer the incoming call and set channel to UP state */
13707 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
13709 ast_setstate(c, AST_STATE_UP);
13711 /* Stop music on hold and other generators */
13712 ast_quiet_chan(replacecall);
13713 ast_quiet_chan(targetcall);
13714 if (option_debug > 3)
13715 ast_log(LOG_DEBUG, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
13716 /* Unlock clone, but not original (replacecall) */
13717 if (!oneleggedreplace)
13718 ast_channel_unlock(c);
13720 /* Unlock PVT */
13721 ast_mutex_unlock(&p->refer->refer_call->lock);
13723 /* Make sure that the masq does not free our PVT for the old call */
13724 if (! earlyreplace && ! oneleggedreplace )
13725 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
13727 /* Prepare the masquerade - if this does not happen, we will be gone */
13728 if(ast_channel_masquerade(replacecall, c))
13729 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
13730 else if (option_debug > 3)
13731 ast_log(LOG_DEBUG, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
13733 /* The masquerade will happen as soon as someone reads a frame from the channel */
13735 /* C should now be in place of replacecall */
13736 /* ast_read needs to lock channel */
13737 ast_channel_unlock(c);
13739 if (earlyreplace || oneleggedreplace ) {
13740 /* Force the masq to happen */
13741 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
13742 ast_frfree(f);
13743 f = NULL;
13744 if (option_debug > 3)
13745 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from RING channel!\n");
13746 } else {
13747 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from RING channel \n");
13749 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13750 if (!oneleggedreplace)
13751 ast_channel_unlock(replacecall);
13752 } else { /* Bridged call, UP channel */
13753 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
13754 /* Masq ok */
13755 ast_frfree(f);
13756 f = NULL;
13757 if (option_debug > 2)
13758 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from channel! Masq done.\n");
13759 } else {
13760 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from channel. Transfer failed\n");
13762 ast_channel_unlock(replacecall);
13764 ast_mutex_unlock(&p->refer->refer_call->lock);
13766 ast_setstate(c, AST_STATE_DOWN);
13767 if (option_debug > 3) {
13768 struct ast_channel *test;
13769 ast_log(LOG_DEBUG, "After transfer:----------------------------\n");
13770 ast_log(LOG_DEBUG, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
13771 if (replacecall)
13772 ast_log(LOG_DEBUG, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
13773 if (p->owner) {
13774 ast_log(LOG_DEBUG, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
13775 test = ast_bridged_channel(p->owner);
13776 if (test)
13777 ast_log(LOG_DEBUG, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
13778 else
13779 ast_log(LOG_DEBUG, " -- No call bridged to C->owner \n");
13780 } else
13781 ast_log(LOG_DEBUG, " -- No channel yet \n");
13782 ast_log(LOG_DEBUG, "End After transfer:----------------------------\n");
13785 ast_channel_unlock(p->owner); /* Unlock new owner */
13786 if (!oneleggedreplace)
13787 ast_mutex_unlock(&p->lock); /* Unlock SIP structure */
13789 /* The call should be down with no ast_channel, so hang it up */
13790 c->tech_pvt = NULL;
13791 ast_hangup(c);
13792 return 0;
13795 /*! \brief helper routine for sip_uri_cmp
13797 * This takes the parameters from two SIP URIs and determines
13798 * if the URIs match. The rules for parameters *suck*. Here's a breakdown
13799 * 1. If a parameter appears in both URIs, then they must have the same value
13800 * in order for the URIs to match
13801 * 2. If one URI has a user, maddr, ttl, or method parameter, then the other
13802 * URI must also have that parameter and must have the same value
13803 * in order for the URIs to match
13804 * 3. All other headers appearing in only one URI are not considered when
13805 * determining if URIs match
13807 * \param input1 Parameters from URI 1
13808 * \param input2 Parameters from URI 2
13809 * \return Return 0 if the URIs' parameters match, 1 if they do not
13811 static int sip_uri_params_cmp(const char *input1, const char *input2)
13813 char *params1 = ast_strdupa(input1);
13814 char *params2 = ast_strdupa(input2);
13815 char *pos1;
13816 char *pos2;
13817 int maddrmatch = 0;
13818 int ttlmatch = 0;
13819 int usermatch = 0;
13820 int methodmatch = 0;
13822 /*Quick optimization. If both params are zero-length, then
13823 * they match
13825 if (ast_strlen_zero(params1) && ast_strlen_zero(params2)) {
13826 return 0;
13829 pos1 = params1;
13830 while (!ast_strlen_zero(pos1)) {
13831 char *name1 = pos1;
13832 char *value1 = strchr(pos1, '=');
13833 char *semicolon1 = strchr(pos1, ';');
13834 int matched = 0;
13835 if (semicolon1) {
13836 *semicolon1++ = '\0';
13838 if (!value1) {
13839 goto fail;
13841 *value1++ = '\0';
13842 /* Checkpoint reached. We have the name and value parsed for param1
13843 * We have to duplicate params2 each time through the second loop
13844 * or else we can't search and replace the semicolons with \0 each
13845 * time
13847 pos2 = ast_strdupa(params2);
13848 while (!ast_strlen_zero(pos2)) {
13849 char *name2 = pos2;
13850 char *value2 = strchr(pos2, '=');
13851 char *semicolon2 = strchr(pos2, ';');
13852 if (semicolon2) {
13853 *semicolon2++ = '\0';
13855 if (!value2) {
13856 goto fail;
13858 *value2++ = '\0';
13859 if (!strcasecmp(name1, name2)) {
13860 if (strcasecmp(value1, value2)) {
13861 goto fail;
13862 } else {
13863 matched = 1;
13864 break;
13867 pos2 = semicolon2;
13869 /* Need to see if the parameter we're looking at is one of the 'must-match' parameters */
13870 if (!strcasecmp(name1, "maddr")) {
13871 if (matched) {
13872 maddrmatch = 1;
13873 } else {
13874 goto fail;
13876 } else if (!strcasecmp(name1, "ttl")) {
13877 if (matched) {
13878 ttlmatch = 1;
13879 } else {
13880 goto fail;
13882 } else if (!strcasecmp(name1, "user")) {
13883 if (matched) {
13884 usermatch = 1;
13885 } else {
13886 goto fail;
13888 } else if (!strcasecmp(name1, "method")) {
13889 if (matched) {
13890 methodmatch = 1;
13891 } else {
13892 goto fail;
13895 pos1 = semicolon1;
13898 /* We've made it out of that horrible O(m*n) construct and there are no
13899 * failures yet. We're not done yet, though, because params2 could have
13900 * an maddr, ttl, user, or method header and params1 did not.
13902 pos2 = params2;
13903 while (!ast_strlen_zero(pos2)) {
13904 char *name2 = pos2;
13905 char *value2 = strchr(pos2, '=');
13906 char *semicolon2 = strchr(pos2, ';');
13907 if (semicolon2) {
13908 *semicolon2++ = '\0';
13910 if (!value2) {
13911 goto fail;
13913 *value2++ = '\0';
13914 if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
13915 (!strcasecmp(name2, "ttl") && !ttlmatch) ||
13916 (!strcasecmp(name2, "user") && !usermatch) ||
13917 (!strcasecmp(name2, "method") && !methodmatch)) {
13918 goto fail;
13921 return 0;
13923 fail:
13924 return 1;
13927 /*! \brief helper routine for sip_uri_cmp
13929 * This takes the "headers" from two SIP URIs and determines
13930 * if the URIs match. The rules for headers is simple. If a header
13931 * appears in one URI, then it must also appear in the other URI. The
13932 * order in which the headers appear does not matter.
13934 * \param input1 Headers from URI 1
13935 * \param input2 Headers from URI 2
13936 * \return Return 0 if the URIs' headers match, 1 if they do not
13938 static int sip_uri_headers_cmp(const char *input1, const char *input2)
13940 char *headers1 = ast_strdupa(input1);
13941 char *headers2 = ast_strdupa(input2);
13942 int zerolength1 = ast_strlen_zero(headers1);
13943 int zerolength2 = ast_strlen_zero(headers2);
13944 int different = 0;
13945 char *header1;
13947 if ((zerolength1 && !zerolength2) ||
13948 (zerolength2 && !zerolength1))
13949 return 1;
13951 if (zerolength1 && zerolength2)
13952 return 0;
13954 /* At this point, we can definitively state that both inputs are
13955 * not zero-length. First, one more optimization. If the length
13956 * of the headers is not equal, then we definitely have no match
13958 if (strlen(headers1) != strlen(headers2)) {
13959 return 1;
13962 for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
13963 if (!strcasestr(headers2, header1)) {
13964 different = 1;
13965 break;
13969 return different;
13972 static int sip_uri_cmp(const char *input1, const char *input2)
13974 char *uri1 = ast_strdupa(input1);
13975 char *uri2 = ast_strdupa(input2);
13976 char *host1;
13977 char *host2;
13978 char *params1;
13979 char *params2;
13980 char *headers1;
13981 char *headers2;
13983 /* Strip off "sip:" from the URI. We know this is present
13984 * because it was checked back in parse_request()
13986 strsep(&uri1, ":");
13987 strsep(&uri2, ":");
13989 if ((host1 = strchr(uri1, '@'))) {
13990 *host1++ = '\0';
13992 if ((host2 = strchr(uri2, '@'))) {
13993 *host2++ = '\0';
13996 /* Check for mismatched username and passwords. This is the
13997 * only case-sensitive comparison of a SIP URI
13999 if ((host1 && !host2) ||
14000 (host2 && !host1) ||
14001 (host1 && host2 && strcmp(uri1, uri2))) {
14002 return 1;
14005 if (!host1)
14006 host1 = uri1;
14007 if (!host2)
14008 host2 = uri2;
14010 /* Strip off the parameters and headers so we can compare
14011 * host and port
14014 if ((params1 = strchr(host1, ';'))) {
14015 *params1++ = '\0';
14017 if ((params2 = strchr(host2, ';'))) {
14018 *params2++ = '\0';
14021 /* Headers come after parameters, but there may be headers without
14022 * parameters, thus the S_OR
14024 if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
14025 *headers1++ = '\0';
14027 if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
14028 *headers2++ = '\0';
14031 /* Now the host/port are properly isolated. We can get by with a string comparison
14032 * because the SIP URI checking rules have some interesting exceptions that make
14033 * this possible. I will note 2 in particular
14034 * 1. hostnames which resolve to the same IP address as well as a hostname and its
14035 * IP address are not considered a match with SIP URI's.
14036 * 2. If one URI specifies a port and the other does not, then the URIs do not match.
14037 * This includes if one URI explicitly contains port 5060 and the other implies it
14038 * by not having a port specified.
14041 if (strcasecmp(host1, host2)) {
14042 return 1;
14045 /* Headers have easier rules to follow, so do those first */
14046 if (sip_uri_headers_cmp(headers1, headers2)) {
14047 return 1;
14050 /* And now the parameters. Ugh */
14051 return sip_uri_params_cmp(params1, params2);
14055 /*! \brief Handle incoming INVITE request
14056 \note If the INVITE has a Replaces header, it is part of an
14057 * attended transfer. If so, we do not go through the dial
14058 * plan but tries to find the active call and masquerade
14059 * into it
14061 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)
14063 int res = 1;
14064 int gotdest;
14065 const char *p_replaces;
14066 char *replace_id = NULL;
14067 const char *required;
14068 unsigned int required_profile = 0;
14069 struct ast_channel *c = NULL; /* New channel */
14070 int reinvite = 0;
14072 /* Find out what they support */
14073 if (!p->sipoptions) {
14074 const char *supported = get_header(req, "Supported");
14075 if (!ast_strlen_zero(supported))
14076 parse_sip_options(p, supported);
14079 /* Find out what they require */
14080 required = get_header(req, "Require");
14081 if (!ast_strlen_zero(required)) {
14082 required_profile = parse_sip_options(NULL, required);
14083 if (required_profile && required_profile != SIP_OPT_REPLACES) {
14084 /* At this point we only support REPLACES */
14085 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
14086 ast_log(LOG_WARNING,"Received SIP INVITE with unsupported required extension: %s\n", required);
14087 p->invitestate = INV_COMPLETED;
14088 if (!p->lastinvite)
14089 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14090 return -1;
14094 /* Check if this is a loop */
14095 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->owner->_state != AST_STATE_UP)) {
14096 /* This is a call to ourself. Send ourselves an error code and stop
14097 processing immediately, as SIP really has no good mechanism for
14098 being able to call yourself */
14099 /* If pedantic is on, we need to check the tags. If they're different, this is
14100 in fact a forked call through a SIP proxy somewhere. */
14101 int different;
14102 if (pedanticsipchecking)
14103 different = sip_uri_cmp(p->initreq.rlPart2, req->rlPart2);
14104 else
14105 different = strcmp(p->initreq.rlPart2, req->rlPart2);
14106 if (!different) {
14107 transmit_response(p, "482 Loop Detected", req);
14108 p->invitestate = INV_COMPLETED;
14109 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14110 return 0;
14111 } else {
14112 /* This is a spiral. What we need to do is to just change the outgoing INVITE
14113 * so that it now routes to the new Request URI. Since we created the INVITE ourselves
14114 * that should be all we need to do.
14116 char *uri = ast_strdupa(req->rlPart2);
14117 char *at = strchr(uri, '@');
14118 char *peerorhost;
14119 struct sip_pkt *pkt = NULL;
14120 if (option_debug > 2) {
14121 ast_log(LOG_DEBUG, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", p->initreq.rlPart2, req->rlPart2);
14123 if (at) {
14124 *at = '\0';
14126 /* Parse out "sip:" */
14127 if ((peerorhost = strchr(uri, ':'))) {
14128 *peerorhost++ = '\0';
14130 create_addr(p, peerorhost);
14131 ast_string_field_free(p, theirtag);
14132 for (pkt = p->packets; pkt; pkt = pkt->next) {
14133 if (pkt->seqno == p->icseq && pkt->method == SIP_INVITE) {
14134 AST_SCHED_DEL(sched, pkt->retransid);
14137 return transmit_invite(p, SIP_INVITE, 1, 3);
14141 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->pendinginvite) {
14142 /* We already have a pending invite. Sorry. You are on hold. */
14143 transmit_response_reliable(p, "491 Request Pending", req);
14144 if (option_debug)
14145 ast_log(LOG_DEBUG, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
14146 /* Don't destroy dialog here */
14147 return 0;
14150 p_replaces = get_header(req, "Replaces");
14151 if (!ast_strlen_zero(p_replaces)) {
14152 /* We have a replaces header */
14153 char *ptr;
14154 char *fromtag = NULL;
14155 char *totag = NULL;
14156 char *start, *to;
14157 int error = 0;
14159 if (p->owner) {
14160 if (option_debug > 2)
14161 ast_log(LOG_DEBUG, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
14162 transmit_response_reliable(p, "400 Bad request", req); /* The best way to not not accept the transfer */
14163 /* Do not destroy existing call */
14164 return -1;
14167 if (sipdebug && option_debug > 2)
14168 ast_log(LOG_DEBUG, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
14169 /* Create a buffer we can manipulate */
14170 replace_id = ast_strdupa(p_replaces);
14171 ast_uri_decode(replace_id);
14173 if (!p->refer && !sip_refer_allocate(p)) {
14174 transmit_response_reliable(p, "500 Server Internal Error", req);
14175 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
14176 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14177 p->invitestate = INV_COMPLETED;
14178 return -1;
14181 /* Todo: (When we find phones that support this)
14182 if the replaces header contains ";early-only"
14183 we can only replace the call in early
14184 stage, not after it's up.
14186 If it's not in early mode, 486 Busy.
14189 /* Skip leading whitespace */
14190 replace_id = ast_skip_blanks(replace_id);
14192 start = replace_id;
14193 while ( (ptr = strsep(&start, ";")) ) {
14194 ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
14195 if ( (to = strcasestr(ptr, "to-tag=") ) )
14196 totag = to + 7; /* skip the keyword */
14197 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
14198 fromtag = to + 9; /* skip the keyword */
14199 fromtag = strsep(&fromtag, "&"); /* trim what ? */
14203 if (sipdebug && option_debug > 3)
14204 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>");
14207 /* Try to find call that we are replacing
14208 If we have a Replaces header, we need to cancel that call if we succeed with this call
14210 if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
14211 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
14212 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
14213 error = 1;
14216 /* At this point, bot the pvt and the owner of the call to be replaced is locked */
14218 /* The matched call is the call from the transferer to Asterisk .
14219 We want to bridge the bridged part of the call to the
14220 incoming invite, thus taking over the refered call */
14222 if (p->refer->refer_call == p) {
14223 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
14224 p->refer->refer_call = NULL;
14225 transmit_response_reliable(p, "400 Bad request", req); /* The best way to not not accept the transfer */
14226 error = 1;
14229 if (!error && !p->refer->refer_call->owner) {
14230 /* Oops, someting wrong anyway, no owner, no call */
14231 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
14232 /* Check for better return code */
14233 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
14234 error = 1;
14237 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 ) {
14238 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
14239 transmit_response_reliable(p, "603 Declined (Replaces)", req);
14240 error = 1;
14243 if (error) { /* Give up this dialog */
14244 append_history(p, "Xfer", "INVITE/Replace Failed.");
14245 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14246 ast_mutex_unlock(&p->lock);
14247 if (p->refer->refer_call) {
14248 ast_mutex_unlock(&p->refer->refer_call->lock);
14249 ast_channel_unlock(p->refer->refer_call->owner);
14251 p->invitestate = INV_COMPLETED;
14252 return -1;
14257 /* Check if this is an INVITE that sets up a new dialog or
14258 a re-invite in an existing dialog */
14260 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
14261 int newcall = (p->initreq.headers ? TRUE : FALSE);
14263 if (sip_cancel_destroy(p))
14264 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
14265 /* This also counts as a pending invite */
14266 p->pendinginvite = seqno;
14267 check_via(p, req);
14269 copy_request(&p->initreq, req); /* Save this INVITE as the transaction basis */
14270 if (!p->owner) { /* Not a re-invite */
14271 if (debug)
14272 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
14273 if (newcall)
14274 append_history(p, "Invite", "New call: %s", p->callid);
14275 parse_ok_contact(p, req);
14276 } else { /* Re-invite on existing call */
14277 ast_clear_flag(&p->flags[0], SIP_OUTGOING); /* This is now an inbound dialog */
14278 /* Handle SDP here if we already have an owner */
14279 if (find_sdp(req)) {
14280 if (process_sdp(p, req)) {
14281 transmit_response_reliable(p, "488 Not acceptable here", req);
14282 if (!p->lastinvite)
14283 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14284 return -1;
14286 } else {
14287 p->jointcapability = p->capability;
14288 if (option_debug > 2)
14289 ast_log(LOG_DEBUG, "Hm.... No sdp for the moment\n");
14290 /* Some devices signal they want to be put off hold by sending a re-invite
14291 *without* an SDP, which is supposed to mean "Go back to your state"
14292 and since they put os on remote hold, we go back to off hold */
14293 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
14294 change_hold_state(p, req, FALSE, 0);
14296 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) /* This is a response, note what it was for */
14297 append_history(p, "ReInv", "Re-invite received");
14299 } else if (debug)
14300 ast_verbose("Ignoring this INVITE request\n");
14303 if (!p->lastinvite && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner) {
14304 /* This is a new invite */
14305 /* Handle authentication if this is our first invite */
14306 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
14307 if (res == AUTH_CHALLENGE_SENT) {
14308 p->invitestate = INV_COMPLETED; /* Needs to restart in another INVITE transaction */
14309 return 0;
14311 if (res < 0) { /* Something failed in authentication */
14312 if (res == AUTH_FAKE_AUTH) {
14313 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
14314 transmit_fake_auth_response(p, req, 1);
14315 } else {
14316 ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
14317 transmit_response_reliable(p, "403 Forbidden", req);
14319 p->invitestate = INV_COMPLETED;
14320 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14321 ast_string_field_free(p, theirtag);
14322 return 0;
14325 /* We have a succesful authentication, process the SDP portion if there is one */
14326 if (find_sdp(req)) {
14327 if (process_sdp(p, req)) {
14328 /* Unacceptable codecs */
14329 transmit_response_reliable(p, "488 Not acceptable here", req);
14330 p->invitestate = INV_COMPLETED;
14331 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14332 if (option_debug)
14333 ast_log(LOG_DEBUG, "No compatible codecs for this SIP call.\n");
14334 return -1;
14336 } else { /* No SDP in invite, call control session */
14337 p->jointcapability = p->capability;
14338 if (option_debug > 1)
14339 ast_log(LOG_DEBUG, "No SDP in Invite, third party call control\n");
14342 /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
14343 /* This seems redundant ... see !p-owner above */
14344 if (p->owner)
14345 ast_queue_frame(p->owner, &ast_null_frame);
14348 /* Initialize the context if it hasn't been already */
14349 if (ast_strlen_zero(p->context))
14350 ast_string_field_set(p, context, default_context);
14353 /* Check number of concurrent calls -vs- incoming limit HERE */
14354 if (option_debug)
14355 ast_log(LOG_DEBUG, "Checking SIP call limits for device %s\n", p->username);
14356 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
14357 if (res < 0) {
14358 ast_log(LOG_NOTICE, "Failed to place call for user %s, too many calls\n", p->username);
14359 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
14360 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14361 p->invitestate = INV_COMPLETED;
14363 return 0;
14365 gotdest = get_destination(p, NULL); /* Get destination right away */
14366 get_rdnis(p, NULL); /* Get redirect information */
14367 extract_uri(p, req); /* Get the Contact URI */
14368 build_contact(p); /* Build our contact header */
14370 if (p->rtp) {
14371 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
14372 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
14375 if (!replace_id && gotdest) { /* No matching extension found */
14376 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
14377 transmit_response_reliable(p, "484 Address Incomplete", req);
14378 else {
14379 char *decoded_exten = ast_strdupa(p->exten);
14381 transmit_response_reliable(p, "404 Not Found", req);
14382 ast_uri_decode(decoded_exten);
14383 ast_log(LOG_NOTICE, "Call from '%s' to extension"
14384 " '%s' rejected because extension not found.\n",
14385 S_OR(p->username, p->peername), decoded_exten);
14387 p->invitestate = INV_COMPLETED;
14388 update_call_counter(p, DEC_CALL_LIMIT);
14389 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14390 return 0;
14391 } else {
14392 /* If no extension was specified, use the s one */
14393 /* Basically for calling to IP/Host name only */
14394 if (ast_strlen_zero(p->exten))
14395 ast_string_field_set(p, exten, "s");
14396 /* Initialize our tag */
14398 make_our_tag(p->tag, sizeof(p->tag));
14399 /* First invitation - create the channel */
14400 c = sip_new(p, AST_STATE_DOWN, S_OR(p->username, NULL));
14401 *recount = 1;
14403 /* Save Record-Route for any later requests we make on this dialogue */
14404 build_route(p, req, 0);
14406 if (c) {
14407 /* Pre-lock the call */
14408 ast_channel_lock(c);
14411 } else {
14412 if (option_debug > 1 && sipdebug) {
14413 if (!ast_test_flag(req, SIP_PKT_IGNORE))
14414 ast_log(LOG_DEBUG, "Got a SIP re-invite for call %s\n", p->callid);
14415 else
14416 ast_log(LOG_DEBUG, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
14418 if (!ast_test_flag(req, SIP_PKT_IGNORE))
14419 reinvite = 1;
14420 c = p->owner;
14423 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
14424 p->lastinvite = seqno;
14426 if (replace_id) { /* Attended transfer or call pickup - we're the target */
14427 /* Go and take over the target call */
14428 if (sipdebug && option_debug > 3)
14429 ast_log(LOG_DEBUG, "Sending this call to the invite/replcaes handler %s\n", p->callid);
14430 return handle_invite_replaces(p, req, debug, ast_test_flag(req, SIP_PKT_IGNORE), seqno, sin);
14434 if (c) { /* We have a call -either a new call or an old one (RE-INVITE) */
14435 switch(c->_state) {
14436 case AST_STATE_DOWN:
14437 if (option_debug > 1)
14438 ast_log(LOG_DEBUG, "%s: New call is still down.... Trying... \n", c->name);
14439 transmit_response(p, "100 Trying", req);
14440 p->invitestate = INV_PROCEEDING;
14441 ast_setstate(c, AST_STATE_RING);
14442 if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
14443 enum ast_pbx_result res;
14445 res = ast_pbx_start(c);
14447 switch(res) {
14448 case AST_PBX_FAILED:
14449 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
14450 p->invitestate = INV_COMPLETED;
14451 if (ast_test_flag(req, SIP_PKT_IGNORE))
14452 transmit_response(p, "503 Unavailable", req);
14453 else
14454 transmit_response_reliable(p, "503 Unavailable", req);
14455 break;
14456 case AST_PBX_CALL_LIMIT:
14457 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
14458 p->invitestate = INV_COMPLETED;
14459 if (ast_test_flag(req, SIP_PKT_IGNORE))
14460 transmit_response(p, "480 Temporarily Unavailable", req);
14461 else
14462 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
14463 break;
14464 case AST_PBX_SUCCESS:
14465 /* nothing to do */
14466 break;
14469 if (res) {
14471 /* Unlock locks so ast_hangup can do its magic */
14472 ast_mutex_unlock(&c->lock);
14473 ast_mutex_unlock(&p->lock);
14474 ast_hangup(c);
14475 ast_mutex_lock(&p->lock);
14476 c = NULL;
14478 } else { /* Pickup call in call group */
14479 ast_channel_unlock(c);
14480 *nounlock = 1;
14481 if (ast_pickup_call(c)) {
14482 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
14483 if (ast_test_flag(req, SIP_PKT_IGNORE))
14484 transmit_response(p, "503 Unavailable", req); /* OEJ - Right answer? */
14485 else
14486 transmit_response_reliable(p, "503 Unavailable", req);
14487 sip_alreadygone(p);
14488 /* Unlock locks so ast_hangup can do its magic */
14489 ast_mutex_unlock(&p->lock);
14490 c->hangupcause = AST_CAUSE_CALL_REJECTED;
14491 } else {
14492 ast_mutex_unlock(&p->lock);
14493 ast_setstate(c, AST_STATE_DOWN);
14494 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
14496 p->invitestate = INV_COMPLETED;
14497 ast_hangup(c);
14498 ast_mutex_lock(&p->lock);
14499 c = NULL;
14501 break;
14502 case AST_STATE_RING:
14503 transmit_response(p, "100 Trying", req);
14504 p->invitestate = INV_PROCEEDING;
14505 break;
14506 case AST_STATE_RINGING:
14507 transmit_response(p, "180 Ringing", req);
14508 p->invitestate = INV_PROCEEDING;
14509 break;
14510 case AST_STATE_UP:
14511 if (option_debug > 1)
14512 ast_log(LOG_DEBUG, "%s: This call is UP.... \n", c->name);
14514 transmit_response(p, "100 Trying", req);
14516 if (p->t38.state == T38_PEER_REINVITE) {
14517 struct ast_channel *bridgepeer = NULL;
14518 struct sip_pvt *bridgepvt = NULL;
14520 if ((bridgepeer = ast_bridged_channel(p->owner))) {
14521 /* 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*/
14522 /*! XXX: we should also check here does the other side supports t38 at all !!! XXX */
14523 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
14524 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
14525 if (bridgepvt->t38.state == T38_DISABLED) {
14526 if (bridgepvt->udptl) { /* If everything is OK with other side's udptl struct */
14527 /* Send re-invite to the bridged channel */
14528 sip_handle_t38_reinvite(bridgepeer, p, 1);
14529 } else { /* Something is wrong with peers udptl struct */
14530 ast_log(LOG_WARNING, "Strange... The other side of the bridge don't have udptl struct\n");
14531 ast_mutex_lock(&bridgepvt->lock);
14532 bridgepvt->t38.state = T38_DISABLED;
14533 ast_mutex_unlock(&bridgepvt->lock);
14534 if (option_debug > 1)
14535 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->name);
14536 if (ast_test_flag(req, SIP_PKT_IGNORE))
14537 transmit_response(p, "488 Not acceptable here", req);
14538 else
14539 transmit_response_reliable(p, "488 Not acceptable here", req);
14542 } else {
14543 /* The other side is already setup for T.38 most likely so we need to acknowledge this too */
14544 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
14545 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
14546 p->t38.state = T38_ENABLED;
14547 if (option_debug)
14548 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14550 } else {
14551 /* Other side is not a SIP channel */
14552 if (ast_test_flag(req, SIP_PKT_IGNORE))
14553 transmit_response(p, "488 Not acceptable here", req);
14554 else
14555 transmit_response_reliable(p, "488 Not acceptable here", req);
14556 p->t38.state = T38_DISABLED;
14557 if (option_debug > 1)
14558 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14560 if (!p->lastinvite) /* Only destroy if this is *not* a re-invite */
14561 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14563 } else {
14564 /* we are not bridged in a call */
14565 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
14566 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
14567 p->t38.state = T38_ENABLED;
14568 if (option_debug)
14569 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14571 } else if (p->t38.state == T38_DISABLED) { /* Channel doesn't have T38 offered or enabled */
14572 int sendok = TRUE;
14574 /* If we are bridged to a channel that has T38 enabled than this is a case of RTP re-invite after T38 session */
14575 /* so handle it here (re-invite other party to RTP) */
14576 struct ast_channel *bridgepeer = NULL;
14577 struct sip_pvt *bridgepvt = NULL;
14578 if ((bridgepeer = ast_bridged_channel(p->owner))) {
14579 if ((bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) && !ast_check_hangup(bridgepeer)) {
14580 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
14581 /* Does the bridged peer have T38 ? */
14582 if (bridgepvt->t38.state == T38_ENABLED) {
14583 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
14584 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
14585 if (ast_test_flag(req, SIP_PKT_IGNORE))
14586 transmit_response(p, "488 Not Acceptable Here (unsupported)", req);
14587 else
14588 transmit_response_reliable(p, "488 Not Acceptable Here (unsupported)", req);
14589 sendok = FALSE;
14591 /* No bridged peer with T38 enabled*/
14594 /* Respond to normal re-invite */
14595 if (sendok) {
14596 /* If this is not a re-invite or something to ignore - it's critical */
14597 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
14598 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (ast_test_flag(req, SIP_PKT_IGNORE) ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
14601 p->invitestate = INV_TERMINATED;
14602 break;
14603 default:
14604 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
14605 transmit_response(p, "100 Trying", req);
14606 break;
14608 } else {
14609 if (p && (p->autokillid == -1)) {
14610 const char *msg;
14612 if (!p->jointcapability)
14613 msg = "488 Not Acceptable Here (codec error)";
14614 else {
14615 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
14616 msg = "503 Unavailable";
14618 if (ast_test_flag(req, SIP_PKT_IGNORE))
14619 transmit_response(p, msg, req);
14620 else
14621 transmit_response_reliable(p, msg, req);
14622 p->invitestate = INV_COMPLETED;
14623 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14626 return res;
14629 /*! \brief Find all call legs and bridge transferee with target
14630 * called from handle_request_refer */
14631 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
14633 struct sip_dual target; /* Chan 1: Call from tranferer to Asterisk */
14634 /* Chan 2: Call from Asterisk to target */
14635 int res = 0;
14636 struct sip_pvt *targetcall_pvt;
14638 /* Check if the call ID of the replaces header does exist locally */
14639 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
14640 transferer->refer->replaces_callid_fromtag))) {
14641 if (transferer->refer->localtransfer) {
14642 /* We did not find the refered call. Sorry, can't accept then */
14643 transmit_response(transferer, "202 Accepted", req);
14644 /* Let's fake a response from someone else in order
14645 to follow the standard */
14646 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
14647 append_history(transferer, "Xfer", "Refer failed");
14648 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
14649 transferer->refer->status = REFER_FAILED;
14650 return -1;
14652 /* Fall through for remote transfers that we did not find locally */
14653 if (option_debug > 2)
14654 ast_log(LOG_DEBUG, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
14655 return 0;
14658 /* Ok, we can accept this transfer */
14659 transmit_response(transferer, "202 Accepted", req);
14660 append_history(transferer, "Xfer", "Refer accepted");
14661 if (!targetcall_pvt->owner) { /* No active channel */
14662 if (option_debug > 3)
14663 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No owner of target call\n");
14664 /* Cancel transfer */
14665 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
14666 append_history(transferer, "Xfer", "Refer failed");
14667 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
14668 transferer->refer->status = REFER_FAILED;
14669 ast_mutex_unlock(&targetcall_pvt->lock);
14670 ast_channel_unlock(current->chan1);
14671 return -1;
14674 /* We have a channel, find the bridge */
14675 target.chan1 = targetcall_pvt->owner; /* Transferer to Asterisk */
14676 target.chan2 = ast_bridged_channel(targetcall_pvt->owner); /* Asterisk to target */
14678 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
14679 /* Wrong state of new channel */
14680 if (option_debug > 3) {
14681 if (target.chan2)
14682 ast_log(LOG_DEBUG, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
14683 else if (target.chan1->_state != AST_STATE_RING)
14684 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No target channel\n");
14685 else
14686 ast_log(LOG_DEBUG, "SIP attended transfer: Attempting transfer in ringing state\n");
14690 /* Transfer */
14691 if (option_debug > 3 && sipdebug) {
14692 if (current->chan2) /* We have two bridges */
14693 ast_log(LOG_DEBUG, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
14694 else /* One bridge, propably transfer of IVR/voicemail etc */
14695 ast_log(LOG_DEBUG, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
14698 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
14700 /* Perform the transfer */
14701 res = attempt_transfer(current, &target);
14702 ast_mutex_unlock(&targetcall_pvt->lock);
14703 if (res) {
14704 /* Failed transfer */
14705 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
14706 append_history(transferer, "Xfer", "Refer failed");
14707 transferer->refer->status = REFER_FAILED;
14708 if (targetcall_pvt->owner)
14709 ast_channel_unlock(targetcall_pvt->owner);
14710 /* Right now, we have to hangup, sorry. Bridge is destroyed */
14711 if (res != -2)
14712 ast_hangup(transferer->owner);
14713 else
14714 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
14715 } else {
14716 /* Transfer succeeded! */
14718 /* Tell transferer that we're done. */
14719 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
14720 append_history(transferer, "Xfer", "Refer succeeded");
14721 transferer->refer->status = REFER_200OK;
14722 if (targetcall_pvt->owner) {
14723 if (option_debug)
14724 ast_log(LOG_DEBUG, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
14725 ast_channel_unlock(targetcall_pvt->owner);
14728 return 1;
14732 /*! \brief Handle incoming REFER request */
14733 /*! \page SIP_REFER SIP transfer Support (REFER)
14735 REFER is used for call transfer in SIP. We get a REFER
14736 to place a new call with an INVITE somwhere and then
14737 keep the transferor up-to-date of the transfer. If the
14738 transfer fails, get back on line with the orginal call.
14740 - REFER can be sent outside or inside of a dialog.
14741 Asterisk only accepts REFER inside of a dialog.
14743 - If we get a replaces header, it is an attended transfer
14745 \par Blind transfers
14746 The transferor provides the transferee
14747 with the transfer targets contact. The signalling between
14748 transferer or transferee should not be cancelled, so the
14749 call is recoverable if the transfer target can not be reached
14750 by the transferee.
14752 In this case, Asterisk receives a TRANSFER from
14753 the transferor, thus is the transferee. We should
14754 try to set up a call to the contact provided
14755 and if that fails, re-connect the current session.
14756 If the new call is set up, we issue a hangup.
14757 In this scenario, we are following section 5.2
14758 in the SIP CC Transfer draft. (Transfer without
14759 a GRUU)
14761 \par Transfer with consultation hold
14762 In this case, the transferor
14763 talks to the transfer target before the transfer takes place.
14764 This is implemented with SIP hold and transfer.
14765 Note: The invite From: string could indicate a transfer.
14766 (Section 6. Transfer with consultation hold)
14767 The transferor places the transferee on hold, starts a call
14768 with the transfer target to alert them to the impending
14769 transfer, terminates the connection with the target, then
14770 proceeds with the transfer (as in Blind transfer above)
14772 \par Attended transfer
14773 The transferor places the transferee
14774 on hold, calls the transfer target to alert them,
14775 places the target on hold, then proceeds with the transfer
14776 using a Replaces header field in the Refer-to header. This
14777 will force the transfee to send an Invite to the target,
14778 with a replaces header that instructs the target to
14779 hangup the call between the transferor and the target.
14780 In this case, the Refer/to: uses the AOR address. (The same
14781 URI that the transferee used to establish the session with
14782 the transfer target (To: ). The Require: replaces header should
14783 be in the INVITE to avoid the wrong UA in a forked SIP proxy
14784 scenario to answer and have no call to replace with.
14786 The referred-by header is *NOT* required, but if we get it,
14787 can be copied into the INVITE to the transfer target to
14788 inform the target about the transferor
14790 "Any REFER request has to be appropriately authenticated.".
14792 We can't destroy dialogs, since we want the call to continue.
14795 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock)
14797 struct sip_dual current; /* Chan1: Call between asterisk and transferer */
14798 /* Chan2: Call between asterisk and transferee */
14800 int res = 0;
14802 if (ast_test_flag(req, SIP_PKT_DEBUG))
14803 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");
14805 if (!p->owner) {
14806 /* This is a REFER outside of an existing SIP dialog */
14807 /* We can't handle that, so decline it */
14808 if (option_debug > 2)
14809 ast_log(LOG_DEBUG, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
14810 transmit_response(p, "603 Declined (No dialog)", req);
14811 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
14812 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
14813 sip_alreadygone(p);
14814 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14816 return 0;
14820 /* Check if transfer is allowed from this device */
14821 if (p->allowtransfer == TRANSFER_CLOSED ) {
14822 /* Transfer not allowed, decline */
14823 transmit_response(p, "603 Declined (policy)", req);
14824 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
14825 /* Do not destroy SIP session */
14826 return 0;
14829 if(!ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
14830 /* Already have a pending REFER */
14831 transmit_response(p, "491 Request pending", req);
14832 append_history(p, "Xfer", "Refer failed. Request pending.");
14833 return 0;
14836 /* Allocate memory for call transfer data */
14837 if (!p->refer && !sip_refer_allocate(p)) {
14838 transmit_response(p, "500 Internal Server Error", req);
14839 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
14840 return -3;
14843 res = get_refer_info(p, req); /* Extract headers */
14845 p->refer->status = REFER_SENT;
14847 if (res != 0) {
14848 switch (res) {
14849 case -2: /* Syntax error */
14850 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
14851 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
14852 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14853 ast_log(LOG_DEBUG, "SIP transfer to black hole can't be handled (no refer-to: )\n");
14854 break;
14855 case -3:
14856 transmit_response(p, "603 Declined (Non sip: uri)", req);
14857 append_history(p, "Xfer", "Refer failed. Non SIP uri");
14858 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14859 ast_log(LOG_DEBUG, "SIP transfer to non-SIP uri denied\n");
14860 break;
14861 default:
14862 /* Refer-to extension not found, fake a failed transfer */
14863 transmit_response(p, "202 Accepted", req);
14864 append_history(p, "Xfer", "Refer failed. Bad extension.");
14865 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
14866 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14867 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14868 ast_log(LOG_DEBUG, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
14869 break;
14871 return 0;
14873 if (ast_strlen_zero(p->context))
14874 ast_string_field_set(p, context, default_context);
14876 /* If we do not support SIP domains, all transfers are local */
14877 if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
14878 p->refer->localtransfer = 1;
14879 if (sipdebug && option_debug > 2)
14880 ast_log(LOG_DEBUG, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
14881 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
14882 /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
14883 p->refer->localtransfer = 1;
14884 } else if (sipdebug && option_debug > 2)
14885 ast_log(LOG_DEBUG, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
14887 /* Is this a repeat of a current request? Ignore it */
14888 /* Don't know what else to do right now. */
14889 if (ignore)
14890 return res;
14892 /* If this is a blind transfer, we have the following
14893 channels to work with:
14894 - chan1, chan2: The current call between transferer and transferee (2 channels)
14895 - target_channel: A new call from the transferee to the target (1 channel)
14896 We need to stay tuned to what happens in order to be able
14897 to bring back the call to the transferer */
14899 /* If this is a attended transfer, we should have all call legs within reach:
14900 - chan1, chan2: The call between the transferer and transferee (2 channels)
14901 - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
14902 We want to bridge chan2 with targetcall_pvt!
14904 The replaces call id in the refer message points
14905 to the call leg between Asterisk and the transferer.
14906 So we need to connect the target and the transferee channel
14907 and hangup the two other channels silently
14909 If the target is non-local, the call ID could be on a remote
14910 machine and we need to send an INVITE with replaces to the
14911 target. We basically handle this as a blind transfer
14912 and let the sip_call function catch that we need replaces
14913 header in the INVITE.
14917 /* Get the transferer's channel */
14918 current.chan1 = p->owner;
14920 /* Find the other part of the bridge (2) - transferee */
14921 current.chan2 = ast_bridged_channel(current.chan1);
14923 if (sipdebug && option_debug > 2)
14924 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>");
14926 if (!current.chan2 && !p->refer->attendedtransfer) {
14927 /* No bridged channel, propably IVR or echo or similar... */
14928 /* Guess we should masquerade or something here */
14929 /* Until we figure it out, refuse transfer of such calls */
14930 if (sipdebug && option_debug > 2)
14931 ast_log(LOG_DEBUG,"Refused SIP transfer on non-bridged channel.\n");
14932 p->refer->status = REFER_FAILED;
14933 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
14934 transmit_response(p, "603 Declined", req);
14935 return -1;
14938 if (current.chan2) {
14939 if (sipdebug && option_debug > 3)
14940 ast_log(LOG_DEBUG, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
14942 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
14945 ast_set_flag(&p->flags[0], SIP_GOTREFER);
14947 /* Attended transfer: Find all call legs and bridge transferee with target*/
14948 if (p->refer->attendedtransfer) {
14949 if ((res = local_attended_transfer(p, &current, req, seqno)))
14950 return res; /* We're done with the transfer */
14951 /* Fall through for remote transfers that we did not find locally */
14952 if (sipdebug && option_debug > 3)
14953 ast_log(LOG_DEBUG, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
14954 /* Fallthrough if we can't find the call leg internally */
14958 /* Parking a call */
14959 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
14960 /* Must release c's lock now, because it will not longer be accessible after the transfer! */
14961 *nounlock = 1;
14962 ast_channel_unlock(current.chan1);
14963 copy_request(&current.req, req);
14964 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14965 p->refer->status = REFER_200OK;
14966 append_history(p, "Xfer", "REFER to call parking.");
14967 if (sipdebug && option_debug > 3)
14968 ast_log(LOG_DEBUG, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
14969 sip_park(current.chan2, current.chan1, req, seqno);
14970 return res;
14973 /* Blind transfers and remote attended xfers */
14974 transmit_response(p, "202 Accepted", req);
14976 if (current.chan1 && current.chan2) {
14977 if (option_debug > 2)
14978 ast_log(LOG_DEBUG, "chan1->name: %s\n", current.chan1->name);
14979 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
14981 if (current.chan2) {
14982 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
14983 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
14984 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
14985 /* One for the new channel */
14986 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
14987 /* Attended transfer to remote host, prepare headers for the INVITE */
14988 if (p->refer->referred_by)
14989 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
14991 /* Generate a Replaces string to be used in the INVITE during attended transfer */
14992 if (p->refer->replaces_callid && !ast_strlen_zero(p->refer->replaces_callid)) {
14993 char tempheader[SIPBUFSIZE];
14994 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
14995 p->refer->replaces_callid_totag ? ";to-tag=" : "",
14996 p->refer->replaces_callid_totag,
14997 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
14998 p->refer->replaces_callid_fromtag);
14999 if (current.chan2)
15000 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
15002 /* Must release lock now, because it will not longer
15003 be accessible after the transfer! */
15004 *nounlock = 1;
15005 ast_channel_unlock(current.chan1);
15007 /* Connect the call */
15009 /* FAKE ringing if not attended transfer */
15010 if (!p->refer->attendedtransfer)
15011 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
15013 /* For blind transfer, this will lead to a new call */
15014 /* For attended transfer to remote host, this will lead to
15015 a new SIP call with a replaces header, if the dial plan allows it
15017 if (!current.chan2) {
15018 /* We have no bridge, so we're talking with Asterisk somehow */
15019 /* We need to masquerade this call */
15020 /* What to do to fix this situation:
15021 * Set up the new call in a new channel
15022 * Let the new channel masq into this channel
15023 Please add that code here :-)
15025 p->refer->status = REFER_FAILED;
15026 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
15027 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
15028 append_history(p, "Xfer", "Refer failed (only bridged calls).");
15029 return -1;
15031 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
15033 /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
15034 servers - generate an INVITE with Replaces. Either way, let the dial plan decided */
15035 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
15037 if (!res) {
15038 /* Success - we have a new channel */
15039 if (option_debug > 2)
15040 ast_log(LOG_DEBUG, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
15041 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
15042 if (p->refer->localtransfer)
15043 p->refer->status = REFER_200OK;
15044 if (p->owner)
15045 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
15046 append_history(p, "Xfer", "Refer succeeded.");
15047 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
15048 /* Do not hangup call, the other side do that when we say 200 OK */
15049 /* We could possibly implement a timer here, auto congestion */
15050 res = 0;
15051 } else {
15052 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
15053 if (option_debug > 2)
15054 ast_log(LOG_DEBUG, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
15055 append_history(p, "Xfer", "Refer failed.");
15056 /* Failure of some kind */
15057 p->refer->status = REFER_FAILED;
15058 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
15059 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
15060 res = -1;
15062 return res;
15065 /*! \brief Handle incoming CANCEL request */
15066 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
15069 check_via(p, req);
15070 sip_alreadygone(p);
15072 /* At this point, we could have cancelled the invite at the same time
15073 as the other side sends a CANCEL. Our final reply with error code
15074 might not have been received by the other side before the CANCEL
15075 was sent, so let's just give up retransmissions and waiting for
15076 ACK on our error code. The call is hanging up any way. */
15077 if (p->invitestate == INV_TERMINATED)
15078 __sip_pretend_ack(p);
15079 else
15080 p->invitestate = INV_CANCELLED;
15082 if (p->owner && p->owner->_state == AST_STATE_UP) {
15083 /* This call is up, cancel is ignored, we need a bye */
15084 transmit_response(p, "200 OK", req);
15085 if (option_debug)
15086 ast_log(LOG_DEBUG, "Got CANCEL on an answered call. Ignoring... \n");
15087 return 0;
15090 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
15091 update_call_counter(p, DEC_CALL_LIMIT);
15093 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
15094 if (p->owner)
15095 ast_queue_hangup(p->owner);
15096 else
15097 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15098 if (p->initreq.len > 0) {
15099 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
15100 transmit_response(p, "200 OK", req);
15101 return 1;
15102 } else {
15103 transmit_response(p, "481 Call Leg Does Not Exist", req);
15104 return 0;
15108 static int acf_channel_read(struct ast_channel *chan, char *funcname, char *preparse, char *buf, size_t buflen)
15110 struct ast_rtp_quality qos;
15111 struct sip_pvt *p = chan->tech_pvt;
15112 char *all = "", *parse = ast_strdupa(preparse);
15113 AST_DECLARE_APP_ARGS(args,
15114 AST_APP_ARG(param);
15115 AST_APP_ARG(type);
15116 AST_APP_ARG(field);
15118 AST_STANDARD_APP_ARGS(args, parse);
15120 /* Sanity check */
15121 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
15122 ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
15123 return 0;
15126 if (strcasecmp(args.param, "rtpqos"))
15127 return 0;
15129 /* Default arguments of audio,all */
15130 if (ast_strlen_zero(args.type))
15131 args.type = "audio";
15132 if (ast_strlen_zero(args.field))
15133 args.field = "all";
15135 memset(buf, 0, buflen);
15136 memset(&qos, 0, sizeof(qos));
15138 if (strcasecmp(args.type, "AUDIO") == 0) {
15139 all = ast_rtp_get_quality(p->rtp, &qos);
15140 } else if (strcasecmp(args.type, "VIDEO") == 0) {
15141 all = ast_rtp_get_quality(p->vrtp, &qos);
15144 if (strcasecmp(args.field, "local_ssrc") == 0)
15145 snprintf(buf, buflen, "%u", qos.local_ssrc);
15146 else if (strcasecmp(args.field, "local_lostpackets") == 0)
15147 snprintf(buf, buflen, "%u", qos.local_lostpackets);
15148 else if (strcasecmp(args.field, "local_jitter") == 0)
15149 snprintf(buf, buflen, "%.0lf", qos.local_jitter * 1000.0);
15150 else if (strcasecmp(args.field, "local_count") == 0)
15151 snprintf(buf, buflen, "%u", qos.local_count);
15152 else if (strcasecmp(args.field, "remote_ssrc") == 0)
15153 snprintf(buf, buflen, "%u", qos.remote_ssrc);
15154 else if (strcasecmp(args.field, "remote_lostpackets") == 0)
15155 snprintf(buf, buflen, "%u", qos.remote_lostpackets);
15156 else if (strcasecmp(args.field, "remote_jitter") == 0)
15157 snprintf(buf, buflen, "%.0lf", qos.remote_jitter * 1000.0);
15158 else if (strcasecmp(args.field, "remote_count") == 0)
15159 snprintf(buf, buflen, "%u", qos.remote_count);
15160 else if (strcasecmp(args.field, "rtt") == 0)
15161 snprintf(buf, buflen, "%.0lf", qos.rtt * 1000.0);
15162 else if (strcasecmp(args.field, "all") == 0)
15163 ast_copy_string(buf, all, buflen);
15164 else {
15165 ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
15166 return -1;
15168 return 0;
15171 /*! \brief Handle incoming BYE request */
15172 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
15174 struct ast_channel *c=NULL;
15175 int res;
15176 struct ast_channel *bridged_to;
15178 /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
15179 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner)
15180 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
15182 __sip_pretend_ack(p);
15184 p->invitestate = INV_TERMINATED;
15186 copy_request(&p->initreq, req);
15187 check_via(p, req);
15188 sip_alreadygone(p);
15190 /* Get RTCP quality before end of call */
15191 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY) || p->owner) {
15192 char *audioqos, *videoqos;
15193 if (p->rtp) {
15194 audioqos = ast_rtp_get_quality(p->rtp, NULL);
15195 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
15196 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
15197 if (p->owner)
15198 pbx_builtin_setvar_helper(p->owner, "RTPAUDIOQOS", audioqos);
15200 if (p->vrtp) {
15201 videoqos = ast_rtp_get_quality(p->vrtp, NULL);
15202 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
15203 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
15204 if (p->owner)
15205 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
15209 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
15211 if (!ast_strlen_zero(get_header(req, "Also"))) {
15212 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
15213 ast_inet_ntoa(p->recv.sin_addr));
15214 if (ast_strlen_zero(p->context))
15215 ast_string_field_set(p, context, default_context);
15216 res = get_also_info(p, req);
15217 if (!res) {
15218 c = p->owner;
15219 if (c) {
15220 bridged_to = ast_bridged_channel(c);
15221 if (bridged_to) {
15222 /* Don't actually hangup here... */
15223 ast_queue_control(c, AST_CONTROL_UNHOLD);
15224 ast_async_goto(bridged_to, p->context, p->refer->refer_to,1);
15225 } else
15226 ast_queue_hangup(p->owner);
15228 } else {
15229 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
15230 if (p->owner)
15231 ast_queue_hangup(p->owner);
15233 } else if (p->owner) {
15234 ast_queue_hangup(p->owner);
15235 if (option_debug > 2)
15236 ast_log(LOG_DEBUG, "Received bye, issuing owner hangup\n");
15237 } else {
15238 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15239 if (option_debug > 2)
15240 ast_log(LOG_DEBUG, "Received bye, no owner, selfdestruct soon.\n");
15242 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
15243 transmit_response(p, "200 OK", req);
15245 return 1;
15248 /*! \brief Handle incoming MESSAGE request */
15249 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
15251 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
15252 if (ast_test_flag(req, SIP_PKT_DEBUG))
15253 ast_verbose("Receiving message!\n");
15254 receive_message(p, req);
15255 } else
15256 transmit_response(p, "202 Accepted", req);
15257 return 1;
15260 /*! \brief Handle incoming SUBSCRIBE request */
15261 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
15263 int gotdest;
15264 int res = 0;
15265 int firststate = AST_EXTENSION_REMOVED;
15266 struct sip_peer *authpeer = NULL;
15267 const char *eventheader = get_header(req, "Event"); /* Get Event package name */
15268 const char *accept = get_header(req, "Accept");
15269 int resubscribe = (p->subscribed != NONE);
15270 char *temp, *event;
15272 if (p->initreq.headers) {
15273 /* We already have a dialog */
15274 if (p->initreq.method != SIP_SUBSCRIBE) {
15275 /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
15276 /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
15277 transmit_response(p, "403 Forbidden (within dialog)", req);
15278 /* Do not destroy session, since we will break the call if we do */
15279 if (option_debug)
15280 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);
15281 return 0;
15282 } else if (ast_test_flag(req, SIP_PKT_DEBUG)) {
15283 if (option_debug) {
15284 if (resubscribe)
15285 ast_log(LOG_DEBUG, "Got a re-subscribe on existing subscription %s\n", p->callid);
15286 else
15287 ast_log(LOG_DEBUG, "Got a new subscription %s (possibly with auth)\n", p->callid);
15292 /* Check if we have a global disallow setting on subscriptions.
15293 if so, we don't have to check peer/user settings after auth, which saves a lot of processing
15295 if (!global_allowsubscribe) {
15296 transmit_response(p, "403 Forbidden (policy)", req);
15297 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15298 return 0;
15301 if (!ast_test_flag(req, SIP_PKT_IGNORE) && !resubscribe) { /* Set up dialog, new subscription */
15302 const char *to = get_header(req, "To");
15303 char totag[128];
15305 /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
15306 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
15307 if (ast_test_flag(req, SIP_PKT_DEBUG))
15308 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
15309 transmit_response(p, "481 Subscription does not exist", req);
15310 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15311 return 0;
15314 /* Use this as the basis */
15315 if (ast_test_flag(req, SIP_PKT_DEBUG))
15316 ast_verbose("Creating new subscription\n");
15318 copy_request(&p->initreq, req);
15319 check_via(p, req);
15320 } else if (ast_test_flag(req, SIP_PKT_DEBUG) && ast_test_flag(req, SIP_PKT_IGNORE))
15321 ast_verbose("Ignoring this SUBSCRIBE request\n");
15323 /* Find parameters to Event: header value and remove them for now */
15324 if (ast_strlen_zero(eventheader)) {
15325 transmit_response(p, "489 Bad Event", req);
15326 if (option_debug > 1)
15327 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: <none>\n");
15328 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15329 return 0;
15332 if ( (strchr(eventheader, ';'))) {
15333 event = ast_strdupa(eventheader); /* Since eventheader is a const, we can't change it */
15334 temp = strchr(event, ';');
15335 *temp = '\0'; /* Remove any options for now */
15336 /* We might need to use them later :-) */
15337 } else
15338 event = (char *) eventheader; /* XXX is this legal ? */
15340 /* Handle authentication */
15341 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
15342 /* if an authentication response was sent, we are done here */
15343 if (res == AUTH_CHALLENGE_SENT) {
15344 if (authpeer)
15345 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15346 return 0;
15348 if (res < 0) {
15349 if (res == AUTH_FAKE_AUTH) {
15350 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
15351 transmit_fake_auth_response(p, req, 1);
15352 } else {
15353 ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
15354 transmit_response_reliable(p, "403 Forbidden", req);
15356 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15357 if (authpeer)
15358 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15359 return 0;
15362 /* Check if this user/peer is allowed to subscribe at all */
15363 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
15364 transmit_response(p, "403 Forbidden (policy)", req);
15365 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15366 if (authpeer)
15367 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15368 return 0;
15371 /* Get destination right away */
15372 gotdest = get_destination(p, NULL);
15374 /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
15375 parse_ok_contact(p, req);
15377 build_contact(p);
15378 if (strcmp(event, "message-summary") && gotdest) {
15379 transmit_response(p, "404 Not Found", req);
15380 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15381 if (authpeer)
15382 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15383 return 0;
15386 /* Initialize tag for new subscriptions */
15387 if (ast_strlen_zero(p->tag))
15388 make_our_tag(p->tag, sizeof(p->tag));
15390 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
15391 if (authpeer) /* No need for authpeer here */
15392 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15394 /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
15395 /* Polycom phones only handle xpidf+xml, even if they say they can
15396 handle pidf+xml as well
15398 if (strstr(p->useragent, "Polycom")) {
15399 p->subscribed = XPIDF_XML;
15400 } else if (strstr(accept, "application/pidf+xml")) {
15401 p->subscribed = PIDF_XML; /* RFC 3863 format */
15402 } else if (strstr(accept, "application/dialog-info+xml")) {
15403 p->subscribed = DIALOG_INFO_XML;
15404 /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
15405 } else if (strstr(accept, "application/cpim-pidf+xml")) {
15406 p->subscribed = CPIM_PIDF_XML; /* RFC 3863 format */
15407 } else if (strstr(accept, "application/xpidf+xml")) {
15408 p->subscribed = XPIDF_XML; /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
15409 } else if (ast_strlen_zero(accept)) {
15410 if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
15411 transmit_response(p, "489 Bad Event", req);
15413 ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
15414 p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
15415 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15416 return 0;
15418 /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
15419 so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
15420 } else {
15421 /* Can't find a format for events that we know about */
15422 char mybuf[200];
15423 snprintf(mybuf,sizeof(mybuf),"489 Bad Event (format %s)", accept);
15424 transmit_response(p, mybuf, req);
15426 ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
15427 accept, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
15428 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15429 return 0;
15431 } else if (!strcmp(event, "message-summary")) {
15432 if (!ast_strlen_zero(accept) && strcmp(accept, "application/simple-message-summary")) {
15433 /* Format requested that we do not support */
15434 transmit_response(p, "406 Not Acceptable", req);
15435 if (option_debug > 1)
15436 ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", accept);
15437 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15438 if (authpeer) /* No need for authpeer here */
15439 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15440 return 0;
15442 /* Looks like they actually want a mailbox status
15443 This version of Asterisk supports mailbox subscriptions
15444 The subscribed URI needs to exist in the dial plan
15445 In most devices, this is configurable to the voicemailmain extension you use
15447 if (!authpeer || ast_strlen_zero(authpeer->mailbox)) {
15448 transmit_response(p, "404 Not found (no mailbox)", req);
15449 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15450 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
15451 if (authpeer) /* No need for authpeer here */
15452 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15453 return 0;
15456 p->subscribed = MWI_NOTIFICATION;
15457 if (authpeer->mwipvt && authpeer->mwipvt != p) /* Destroy old PVT if this is a new one */
15458 /* We only allow one subscription per peer */
15459 sip_destroy(authpeer->mwipvt);
15460 authpeer->mwipvt = p; /* Link from peer to pvt */
15461 p->relatedpeer = ASTOBJ_REF(authpeer); /* Link from pvt to peer */
15462 } else { /* At this point, Asterisk does not understand the specified event */
15463 transmit_response(p, "489 Bad Event", req);
15464 if (option_debug > 1)
15465 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: %s\n", event);
15466 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15467 if (authpeer) /* No need for authpeer here */
15468 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15469 return 0;
15472 if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
15473 if (p->stateid > -1)
15474 ast_extension_state_del(p->stateid, cb_extensionstate);
15475 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, p);
15478 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
15479 p->lastinvite = seqno;
15480 if (p && !ast_test_flag(&p->flags[0], SIP_NEEDDESTROY)) {
15481 p->expiry = atoi(get_header(req, "Expires"));
15483 /* check if the requested expiry-time is within the approved limits from sip.conf */
15484 if (p->expiry > max_expiry)
15485 p->expiry = max_expiry;
15486 if (p->expiry < min_expiry && p->expiry > 0)
15487 p->expiry = min_expiry;
15489 if (sipdebug || option_debug > 1) {
15490 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
15491 ast_log(LOG_DEBUG, "Adding subscription for mailbox notification - peer %s Mailbox %s\n", p->relatedpeer->name, p->relatedpeer->mailbox);
15492 else
15493 ast_log(LOG_DEBUG, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
15495 if (p->autokillid > -1 && sip_cancel_destroy(p)) /* Remove subscription expiry for renewals */
15496 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15497 if (p->expiry > 0)
15498 sip_scheddestroy(p, (p->expiry + 10) * 1000); /* Set timer for destruction of call at expiration */
15500 if (p->subscribed == MWI_NOTIFICATION) {
15501 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
15502 transmit_response(p, "200 OK", req);
15503 if (p->relatedpeer) { /* Send first notification */
15504 ASTOBJ_WRLOCK(p->relatedpeer);
15505 sip_send_mwi_to_peer(p->relatedpeer);
15506 ASTOBJ_UNLOCK(p->relatedpeer);
15508 } else {
15509 struct sip_pvt *p_old;
15511 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
15513 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));
15514 transmit_response(p, "404 Not found", req);
15515 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15516 return 0;
15518 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
15519 transmit_response(p, "200 OK", req);
15520 transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
15521 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
15522 /* hide the 'complete' exten/context in the refer_to field for later display */
15523 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
15525 /* remove any old subscription from this peer for the same exten/context,
15526 as the peer has obviously forgotten about it and it's wasteful to wait
15527 for it to expire and send NOTIFY messages to the peer only to have them
15528 ignored (or generate errors)
15530 ast_mutex_lock(&iflock);
15531 for (p_old = iflist; p_old; p_old = p_old->next) {
15532 if (p_old == p)
15533 continue;
15534 if (p_old->initreq.method != SIP_SUBSCRIBE)
15535 continue;
15536 if (p_old->subscribed == NONE)
15537 continue;
15538 ast_mutex_lock(&p_old->lock);
15539 if (!strcmp(p_old->username, p->username)) {
15540 if (!strcmp(p_old->exten, p->exten) &&
15541 !strcmp(p_old->context, p->context)) {
15542 ast_set_flag(&p_old->flags[0], SIP_NEEDDESTROY);
15543 ast_mutex_unlock(&p_old->lock);
15544 break;
15547 ast_mutex_unlock(&p_old->lock);
15549 ast_mutex_unlock(&iflock);
15551 if (!p->expiry)
15552 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15554 return 1;
15557 /*! \brief Handle incoming REGISTER request */
15558 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
15560 enum check_auth_result res;
15562 /* Use this as the basis */
15563 if (ast_test_flag(req, SIP_PKT_DEBUG))
15564 ast_verbose("Using latest REGISTER request as basis request\n");
15565 copy_request(&p->initreq, req);
15566 check_via(p, req);
15567 if ((res = register_verify(p, sin, req, e)) < 0) {
15568 const char *reason;
15570 switch (res) {
15571 case AUTH_SECRET_FAILED:
15572 reason = "Wrong password";
15573 break;
15574 case AUTH_USERNAME_MISMATCH:
15575 reason = "Username/auth name mismatch";
15576 break;
15577 case AUTH_NOT_FOUND:
15578 reason = "No matching peer found";
15579 break;
15580 case AUTH_UNKNOWN_DOMAIN:
15581 reason = "Not a local domain";
15582 break;
15583 case AUTH_PEER_NOT_DYNAMIC:
15584 reason = "Peer is not supposed to register";
15585 break;
15586 case AUTH_ACL_FAILED:
15587 reason = "Device does not match ACL";
15588 break;
15589 default:
15590 reason = "Unknown failure";
15591 break;
15593 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
15594 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
15595 reason);
15596 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
15597 } else
15598 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
15600 if (res < 1) {
15601 /* Destroy the session, but keep us around for just a bit in case they don't
15602 get our 200 OK */
15603 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15605 return res;
15608 /*! \brief Handle incoming SIP requests (methods)
15609 \note This is where all incoming requests go first */
15610 /* called with p and p->owner locked */
15611 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
15613 /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
15614 relatively static */
15615 const char *cmd;
15616 const char *cseq;
15617 const char *useragent;
15618 int seqno;
15619 int len;
15620 int ignore = FALSE;
15621 int respid;
15622 int res = 0;
15623 int debug = sip_debug_test_pvt(p);
15624 char *e;
15625 int error = 0;
15627 /* Get Method and Cseq */
15628 cseq = get_header(req, "Cseq");
15629 cmd = req->header[0];
15631 /* Must have Cseq */
15632 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
15633 ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
15634 error = 1;
15636 if (!error && sscanf(cseq, "%d%n", &seqno, &len) != 1) {
15637 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
15638 error = 1;
15640 if (error) {
15641 if (!p->initreq.headers) /* New call */
15642 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); /* Make sure we destroy this dialog */
15643 return -1;
15645 /* Get the command XXX */
15647 cmd = req->rlPart1;
15648 e = req->rlPart2;
15650 /* Save useragent of the client */
15651 useragent = get_header(req, "User-Agent");
15652 if (!ast_strlen_zero(useragent))
15653 ast_string_field_set(p, useragent, useragent);
15655 /* Find out SIP method for incoming request */
15656 if (req->method == SIP_RESPONSE) { /* Response to our request */
15657 /* Response to our request -- Do some sanity checks */
15658 if (!p->initreq.headers) {
15659 if (option_debug)
15660 ast_log(LOG_DEBUG, "That's odd... Got a response on a call we dont know about. Cseq %d Cmd %s\n", seqno, cmd);
15661 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15662 return 0;
15663 } else if (p->ocseq && (p->ocseq < seqno) && (seqno != p->lastnoninvite)) {
15664 if (option_debug)
15665 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
15666 return -1;
15667 } else if (p->ocseq && (p->ocseq != seqno) && (seqno != p->lastnoninvite)) {
15668 /* ignore means "don't do anything with it" but still have to
15669 respond appropriately */
15670 ignore = TRUE;
15671 ast_set_flag(req, SIP_PKT_IGNORE);
15672 ast_set_flag(req, SIP_PKT_IGNORE_RESP);
15673 append_history(p, "Ignore", "Ignoring this retransmit\n");
15674 } else if (e) {
15675 e = ast_skip_blanks(e);
15676 if (sscanf(e, "%d %n", &respid, &len) != 1) {
15677 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
15678 } else {
15679 if (respid <= 0) {
15680 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
15681 return 0;
15683 /* More SIP ridiculousness, we have to ignore bogus contacts in 100 etc responses */
15684 if ((respid == 200) || ((respid >= 300) && (respid <= 399)))
15685 extract_uri(p, req);
15686 handle_response(p, respid, e + len, req, ignore, seqno);
15689 return 0;
15692 /* New SIP request coming in
15693 (could be new request in existing SIP dialog as well...)
15696 p->method = req->method; /* Find out which SIP method they are using */
15697 if (option_debug > 3)
15698 ast_log(LOG_DEBUG, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
15700 if (p->icseq && (p->icseq > seqno) ) {
15701 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
15702 if (option_debug > 2)
15703 ast_log(LOG_DEBUG, "Got CANCEL or ACK on INVITE with transactions in between.\n");
15704 } else {
15705 if (option_debug)
15706 ast_log(LOG_DEBUG, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
15707 if (req->method != SIP_ACK)
15708 transmit_response(p, "503 Server error", req); /* We must respond according to RFC 3261 sec 12.2 */
15709 return -1;
15711 } else if (p->icseq &&
15712 p->icseq == seqno &&
15713 req->method != SIP_ACK &&
15714 (p->method != SIP_CANCEL || ast_test_flag(&p->flags[0], SIP_ALREADYGONE))) {
15715 /* ignore means "don't do anything with it" but still have to
15716 respond appropriately. We do this if we receive a repeat of
15717 the last sequence number */
15718 ignore = 2;
15719 ast_set_flag(req, SIP_PKT_IGNORE);
15720 ast_set_flag(req, SIP_PKT_IGNORE_REQ);
15721 if (option_debug > 2)
15722 ast_log(LOG_DEBUG, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
15725 if (seqno >= p->icseq)
15726 /* Next should follow monotonically (but not necessarily
15727 incrementally -- thanks again to the genius authors of SIP --
15728 increasing */
15729 p->icseq = seqno;
15731 /* Find their tag if we haven't got it */
15732 if (ast_strlen_zero(p->theirtag)) {
15733 char tag[128];
15735 gettag(req, "From", tag, sizeof(tag));
15736 ast_string_field_set(p, theirtag, tag);
15738 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
15740 if (pedanticsipchecking) {
15741 /* If this is a request packet without a from tag, it's not
15742 correct according to RFC 3261 */
15743 /* Check if this a new request in a new dialog with a totag already attached to it,
15744 RFC 3261 - section 12.2 - and we don't want to mess with recovery */
15745 if (!p->initreq.headers && ast_test_flag(req, SIP_PKT_WITH_TOTAG)) {
15746 /* If this is a first request and it got a to-tag, it is not for us */
15747 if (!ast_test_flag(req, SIP_PKT_IGNORE) && req->method == SIP_INVITE) {
15748 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
15749 /* Will cease to exist after ACK */
15750 } else if (req->method != SIP_ACK) {
15751 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
15752 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15754 return res;
15758 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
15759 transmit_response(p, "400 Bad request", req);
15760 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15761 return -1;
15764 /* Handle various incoming SIP methods in requests */
15765 switch (p->method) {
15766 case SIP_OPTIONS:
15767 res = handle_request_options(p, req);
15768 break;
15769 case SIP_INVITE:
15770 res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
15771 break;
15772 case SIP_REFER:
15773 res = handle_request_refer(p, req, debug, ignore, seqno, nounlock);
15774 break;
15775 case SIP_CANCEL:
15776 res = handle_request_cancel(p, req);
15777 break;
15778 case SIP_BYE:
15779 res = handle_request_bye(p, req);
15780 break;
15781 case SIP_MESSAGE:
15782 res = handle_request_message(p, req);
15783 break;
15784 case SIP_SUBSCRIBE:
15785 res = handle_request_subscribe(p, req, sin, seqno, e);
15786 break;
15787 case SIP_REGISTER:
15788 res = handle_request_register(p, req, sin, e);
15789 break;
15790 case SIP_INFO:
15791 if (ast_test_flag(req, SIP_PKT_DEBUG))
15792 ast_verbose("Receiving INFO!\n");
15793 if (!ignore)
15794 handle_request_info(p, req);
15795 else /* if ignoring, transmit response */
15796 transmit_response(p, "200 OK", req);
15797 break;
15798 case SIP_NOTIFY:
15799 res = handle_request_notify(p, req, sin, seqno, e);
15800 break;
15801 case SIP_ACK:
15802 /* Make sure we don't ignore this */
15803 if (seqno == p->pendinginvite) {
15804 p->invitestate = INV_TERMINATED;
15805 p->pendinginvite = 0;
15806 __sip_ack(p, seqno, FLAG_RESPONSE, 0);
15807 if (find_sdp(req)) {
15808 if (process_sdp(p, req))
15809 return -1;
15811 check_pendings(p);
15813 /* Got an ACK that we did not match. Ignore silently */
15814 if (!p->lastinvite && ast_strlen_zero(p->randdata))
15815 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15816 break;
15817 default:
15818 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
15819 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
15820 cmd, ast_inet_ntoa(p->sa.sin_addr));
15821 /* If this is some new method, and we don't have a call, destroy it now */
15822 if (!p->initreq.headers)
15823 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15824 break;
15826 return res;
15829 /*! \brief Read data from SIP socket
15830 \note sipsock_read locks the owner channel while we are processing the SIP message
15831 \return 1 on error, 0 on success
15832 \note Successful messages is connected to SIP call and forwarded to handle_request()
15834 static int sipsock_read(int *id, int fd, short events, void *ignore)
15836 struct sip_request req;
15837 struct sockaddr_in sin = { 0, };
15838 struct sip_pvt *p;
15839 int res;
15840 socklen_t len = sizeof(sin);
15841 int nounlock;
15842 int recount = 0;
15843 int lockretry;
15845 memset(&req, 0, sizeof(req));
15846 res = recvfrom(sipsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
15847 if (res < 0) {
15848 #if !defined(__FreeBSD__)
15849 if (errno == EAGAIN)
15850 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
15851 else
15852 #endif
15853 if (errno != ECONNREFUSED)
15854 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
15855 return 1;
15857 if (option_debug && res == sizeof(req.data) - 1)
15858 ast_log(LOG_DEBUG, "Received packet exceeds buffer. Data is possibly lost\n");
15860 req.data[res] = '\0';
15861 req.len = res;
15862 if(sip_debug_test_addr(&sin)) /* Set the debug flag early on packet level */
15863 ast_set_flag(&req, SIP_PKT_DEBUG);
15864 if (pedanticsipchecking)
15865 req.len = lws2sws(req.data, req.len); /* Fix multiline headers */
15866 if (ast_test_flag(&req, SIP_PKT_DEBUG))
15867 ast_verbose("\n<--- SIP read from %s:%d --->\n%s\n<------------->\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), req.data);
15869 if(parse_request(&req) == -1) /* Bad packet, can't parse */
15870 return 1;
15872 req.method = find_sip_method(req.rlPart1);
15874 if (ast_test_flag(&req, SIP_PKT_DEBUG))
15875 ast_verbose("--- (%d headers %d lines)%s ---\n", req.headers, req.lines, (req.headers + req.lines == 0) ? " Nat keepalive" : "");
15877 if (req.headers < 2) /* Must have at least two headers */
15878 return 1;
15880 /* Process request, with netlock held, and with usual deadlock avoidance */
15881 for (lockretry = 100; lockretry > 0; lockretry--) {
15882 ast_mutex_lock(&netlock);
15884 /* Find the active SIP dialog or create a new one */
15885 p = find_call(&req, &sin, req.method); /* returns p locked */
15886 if (p == NULL) {
15887 if (option_debug)
15888 ast_log(LOG_DEBUG, "Invalid SIP message - rejected , no callid, len %d\n", req.len);
15889 ast_mutex_unlock(&netlock);
15890 return 1;
15892 /* Go ahead and lock the owner if it has one -- we may need it */
15893 /* because this is deadlock-prone, we need to try and unlock if failed */
15894 if (!p->owner || !ast_channel_trylock(p->owner))
15895 break; /* locking succeeded */
15896 if (lockretry == 1) {
15897 if (option_debug) {
15898 ast_log(LOG_DEBUG, "Failed to grab owner channel lock. (SIP call %s)\n", p->callid);
15900 } else {
15901 if (option_debug) {
15902 ast_log(LOG_DEBUG, "Failed to grab owner channel lock, trying again. (SIP call %s)\n", p->callid);
15904 ast_mutex_unlock(&p->lock);
15905 ast_mutex_unlock(&netlock);
15906 /* Sleep for a very short amount of time */
15907 usleep(1);
15910 p->recv = sin;
15912 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) /* This is a request or response, note what it was for */
15913 append_history(p, "Rx", "%s / %s / %s", req.data, get_header(&req, "CSeq"), req.rlPart2);
15915 if (!lockretry) {
15916 /* XXX Wouldn't p->owner always exist here? */
15917 /* This is unsafe, since p->owner wouldn't be locked. */
15918 if (p->owner)
15919 ast_log(LOG_ERROR, "We could NOT get the channel lock for %s! \n", S_OR(p->owner->name, "- no channel name ??? - "));
15920 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
15921 if (req.method != SIP_ACK)
15922 transmit_response(p, "503 Server error", &req); /* We must respond according to RFC 3261 sec 12.2 */
15923 /* XXX We could add retry-after to make sure they come back */
15924 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
15925 ast_mutex_unlock(&p->lock);
15926 ast_mutex_unlock(&netlock);
15927 return 1;
15929 nounlock = 0;
15930 if (handle_request(p, &req, &sin, &recount, &nounlock) == -1) {
15931 /* Request failed */
15932 if (option_debug)
15933 ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
15936 if (p->owner && !nounlock)
15937 ast_channel_unlock(p->owner);
15938 ast_mutex_unlock(&p->lock);
15939 ast_mutex_unlock(&netlock);
15940 if (recount)
15941 ast_update_use_count();
15943 return 1;
15946 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
15947 static int sip_send_mwi_to_peer(struct sip_peer *peer)
15949 /* Called with peerl lock, but releases it */
15950 struct sip_pvt *p;
15951 int newmsgs, oldmsgs;
15953 /* Do we have an IP address? If not, skip this peer */
15954 if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr)
15955 return 0;
15957 /* Check for messages */
15958 ast_app_inboxcount(peer->mailbox, &newmsgs, &oldmsgs);
15960 peer->lastmsgcheck = time(NULL);
15962 /* Return now if it's the same thing we told them last time */
15963 if (((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)) == peer->lastmsgssent) {
15964 return 0;
15968 peer->lastmsgssent = ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs));
15970 if (peer->mwipvt) {
15971 /* Base message on subscription */
15972 p = peer->mwipvt;
15973 } else {
15974 /* Build temporary dialog for this message */
15975 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY)))
15976 return -1;
15977 if (create_addr_from_peer(p, peer)) {
15978 /* Maybe they're not registered, etc. */
15979 sip_destroy(p);
15980 return 0;
15982 /* Recalculate our side, and recalculate Call ID */
15983 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
15984 p->ourip = __ourip;
15985 build_via(p);
15986 build_callid_pvt(p);
15987 /* Destroy this session after 32 secs */
15988 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15990 /* Send MWI */
15991 ast_set_flag(&p->flags[0], SIP_OUTGOING);
15992 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
15993 return 0;
15996 /*! \brief Check whether peer needs a new MWI notification check */
15997 static int does_peer_need_mwi(struct sip_peer *peer)
15999 time_t t = time(NULL);
16001 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
16002 !peer->mwipvt) { /* We don't have a subscription */
16003 peer->lastmsgcheck = t; /* Reset timer */
16004 return FALSE;
16007 if (!ast_strlen_zero(peer->mailbox) && (t - peer->lastmsgcheck) > global_mwitime)
16008 return TRUE;
16010 return FALSE;
16014 /*! \brief The SIP monitoring thread
16015 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
16016 (and thus do not have a separate thread) indefinitely
16018 static void *do_monitor(void *data)
16020 int res;
16021 struct sip_pvt *sip;
16022 struct sip_peer *peer = NULL;
16023 time_t t;
16024 int fastrestart = FALSE;
16025 int lastpeernum = -1;
16026 int curpeernum;
16027 int reloading;
16029 /* Add an I/O event to our SIP UDP socket */
16030 if (sipsock > -1)
16031 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
16033 /* From here on out, we die whenever asked */
16034 for(;;) {
16035 /* Check for a reload request */
16036 ast_mutex_lock(&sip_reload_lock);
16037 reloading = sip_reloading;
16038 sip_reloading = FALSE;
16039 ast_mutex_unlock(&sip_reload_lock);
16040 if (reloading) {
16041 if (option_verbose > 0)
16042 ast_verbose(VERBOSE_PREFIX_1 "Reloading SIP\n");
16043 sip_do_reload(sip_reloadreason);
16045 /* Change the I/O fd of our UDP socket */
16046 if (sipsock > -1) {
16047 if (sipsock_read_id)
16048 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
16049 else
16050 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
16051 } else if (sipsock_read_id) {
16052 ast_io_remove(io, sipsock_read_id);
16053 sipsock_read_id = NULL;
16056 restartsearch:
16057 /* Check for interfaces needing to be killed */
16058 ast_mutex_lock(&iflock);
16059 t = time(NULL);
16060 /* don't scan the interface list if it hasn't been a reasonable period
16061 of time since the last time we did it (when MWI is being sent, we can
16062 get back to this point every millisecond or less)
16064 for (sip = iflist; !fastrestart && sip; sip = sip->next) {
16065 /*! \note If we can't get a lock on an interface, skip it and come
16066 * back later. Note that there is the possibility of a deadlock with
16067 * sip_hangup otherwise, because sip_hangup is called with the channel
16068 * locked first, and the iface lock is attempted second.
16070 if (ast_mutex_trylock(&sip->lock))
16071 continue;
16073 /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
16074 if (sip->rtp && sip->owner &&
16075 (sip->owner->_state == AST_STATE_UP) &&
16076 !sip->redirip.sin_addr.s_addr &&
16077 sip->t38.state != T38_ENABLED) {
16078 if (sip->lastrtptx &&
16079 ast_rtp_get_rtpkeepalive(sip->rtp) &&
16080 (t > sip->lastrtptx + ast_rtp_get_rtpkeepalive(sip->rtp))) {
16081 /* Need to send an empty RTP packet */
16082 sip->lastrtptx = time(NULL);
16083 ast_rtp_sendcng(sip->rtp, 0);
16085 if (sip->lastrtprx &&
16086 (ast_rtp_get_rtptimeout(sip->rtp) || ast_rtp_get_rtpholdtimeout(sip->rtp)) &&
16087 (t > sip->lastrtprx + ast_rtp_get_rtptimeout(sip->rtp))) {
16088 /* Might be a timeout now -- see if we're on hold */
16089 struct sockaddr_in sin;
16090 ast_rtp_get_peer(sip->rtp, &sin);
16091 if (sin.sin_addr.s_addr ||
16092 (ast_rtp_get_rtpholdtimeout(sip->rtp) &&
16093 (t > sip->lastrtprx + ast_rtp_get_rtpholdtimeout(sip->rtp)))) {
16094 /* Needs a hangup */
16095 if (ast_rtp_get_rtptimeout(sip->rtp)) {
16096 while (sip->owner && ast_channel_trylock(sip->owner)) {
16097 DEADLOCK_AVOIDANCE(&sip->lock);
16099 if (sip->owner) {
16100 ast_log(LOG_NOTICE,
16101 "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
16102 sip->owner->name,
16103 (long) (t - sip->lastrtprx));
16104 /* Issue a softhangup */
16105 ast_softhangup_nolock(sip->owner, AST_SOFTHANGUP_DEV);
16106 ast_channel_unlock(sip->owner);
16107 /* forget the timeouts for this call, since a hangup
16108 has already been requested and we don't want to
16109 repeatedly request hangups
16111 ast_rtp_set_rtptimeout(sip->rtp, 0);
16112 ast_rtp_set_rtpholdtimeout(sip->rtp, 0);
16113 if (sip->vrtp) {
16114 ast_rtp_set_rtptimeout(sip->vrtp, 0);
16115 ast_rtp_set_rtpholdtimeout(sip->vrtp, 0);
16122 /* If we have sessions that needs to be destroyed, do it now */
16123 if (ast_test_flag(&sip->flags[0], SIP_NEEDDESTROY) && !sip->packets &&
16124 !sip->owner) {
16125 ast_mutex_unlock(&sip->lock);
16126 __sip_destroy(sip, 1);
16127 ast_mutex_unlock(&iflock);
16128 usleep(1);
16129 goto restartsearch;
16131 ast_mutex_unlock(&sip->lock);
16133 ast_mutex_unlock(&iflock);
16135 /* XXX TODO The scheduler usage in this module does not have sufficient
16136 * synchronization being done between running the scheduler and places
16137 * scheduling tasks. As it is written, any scheduled item may not run
16138 * any sooner than about 1 second, regardless of whether a sooner time
16139 * was asked for. */
16141 pthread_testcancel();
16142 /* Wait for sched or io */
16143 res = ast_sched_wait(sched);
16144 if ((res < 0) || (res > 1000))
16145 res = 1000;
16146 /* If we might need to send more mailboxes, don't wait long at all.*/
16147 if (fastrestart)
16148 res = 1;
16149 res = ast_io_wait(io, res);
16150 if (option_debug && res > 20)
16151 ast_log(LOG_DEBUG, "chan_sip: ast_io_wait ran %d all at once\n", res);
16152 ast_mutex_lock(&monlock);
16153 res = ast_sched_runq(sched);
16154 if (option_debug && res >= 20)
16155 ast_log(LOG_DEBUG, "chan_sip: ast_sched_runq ran %d all at once\n", res);
16157 /* Send MWI notifications to peers - static and cached realtime peers */
16158 t = time(NULL);
16159 fastrestart = FALSE;
16160 curpeernum = 0;
16161 peer = NULL;
16162 /* Find next peer that needs mwi */
16163 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !peer, do {
16164 if ((curpeernum > lastpeernum) && does_peer_need_mwi(iterator)) {
16165 fastrestart = TRUE;
16166 lastpeernum = curpeernum;
16167 peer = ASTOBJ_REF(iterator);
16169 curpeernum++;
16170 } while (0)
16172 /* Send MWI to the peer */
16173 if (peer) {
16174 ASTOBJ_WRLOCK(peer);
16175 sip_send_mwi_to_peer(peer);
16176 ASTOBJ_UNLOCK(peer);
16177 ASTOBJ_UNREF(peer,sip_destroy_peer);
16178 } else {
16179 /* Reset where we come from */
16180 lastpeernum = -1;
16182 ast_mutex_unlock(&monlock);
16184 /* Never reached */
16185 return NULL;
16189 /*! \brief Start the channel monitor thread */
16190 static int restart_monitor(void)
16192 /* If we're supposed to be stopped -- stay stopped */
16193 if (monitor_thread == AST_PTHREADT_STOP)
16194 return 0;
16195 ast_mutex_lock(&monlock);
16196 if (monitor_thread == pthread_self()) {
16197 ast_mutex_unlock(&monlock);
16198 ast_log(LOG_WARNING, "Cannot kill myself\n");
16199 return -1;
16201 if (monitor_thread != AST_PTHREADT_NULL) {
16202 /* Wake up the thread */
16203 pthread_kill(monitor_thread, SIGURG);
16204 } else {
16205 /* Start a new monitor */
16206 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
16207 ast_mutex_unlock(&monlock);
16208 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
16209 return -1;
16212 ast_mutex_unlock(&monlock);
16213 return 0;
16216 /*! \brief React to lack of answer to Qualify poke */
16217 static int sip_poke_noanswer(const void *data)
16219 struct sip_peer *peer = (struct sip_peer *)data;
16221 peer->pokeexpire = -1;
16222 if (peer->lastms > -1) {
16223 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
16224 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
16226 if (peer->call)
16227 sip_destroy(peer->call);
16228 peer->call = NULL;
16229 peer->lastms = -1;
16230 ast_device_state_changed("SIP/%s", peer->name);
16232 /* This function gets called one place outside of the scheduler ... */
16233 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
16234 struct sip_peer *peer_ptr = peer;
16235 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
16238 /* There is no need to ASTOBJ_REF() here. Just let the scheduled callback
16239 * inherit the reference that the current callback already has. */
16240 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
16241 if (peer->pokeexpire == -1) {
16242 ASTOBJ_UNREF(peer, sip_destroy_peer);
16245 return 0;
16248 /*! \brief Check availability of peer, also keep NAT open
16249 \note This is done with the interval in qualify= configuration option
16250 Default is 2 seconds */
16251 static int sip_poke_peer(struct sip_peer *peer)
16253 struct sip_pvt *p;
16254 int xmitres = 0;
16256 if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
16257 /* IF we have no IP, or this isn't to be monitored, return
16258 imeediately after clearing things out */
16259 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
16260 struct sip_peer *peer_ptr = peer;
16261 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
16263 peer->lastms = 0;
16264 peer->call = NULL;
16265 return 0;
16267 if (peer->call) {
16268 if (sipdebug)
16269 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
16270 sip_destroy(peer->call);
16272 if (!(p = peer->call = sip_alloc(NULL, NULL, 0, SIP_OPTIONS)))
16273 return -1;
16275 p->sa = peer->addr;
16276 p->recv = peer->addr;
16277 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
16278 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16280 /* Send OPTIONs to peer's fullcontact */
16281 if (!ast_strlen_zero(peer->fullcontact))
16282 ast_string_field_set(p, fullcontact, peer->fullcontact);
16284 if (!ast_strlen_zero(peer->tohost))
16285 ast_string_field_set(p, tohost, peer->tohost);
16286 else
16287 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
16289 /* Recalculate our side, and recalculate Call ID */
16290 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
16291 p->ourip = __ourip;
16292 build_via(p);
16293 build_callid_pvt(p);
16295 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
16296 struct sip_peer *peer_ptr = peer;
16297 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
16300 p->relatedpeer = ASTOBJ_REF(peer);
16301 ast_set_flag(&p->flags[0], SIP_OUTGOING);
16302 #ifdef VOCAL_DATA_HACK
16303 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
16304 xmitres = transmit_invite(p, SIP_INVITE, 0, 2);
16305 #else
16306 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2);
16307 #endif
16308 gettimeofday(&peer->ps, NULL);
16309 if (xmitres == XMIT_ERROR) {
16310 sip_poke_noanswer(ASTOBJ_REF(peer)); /* Immediately unreachable, network problems */
16311 } else {
16312 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
16313 struct sip_peer *peer_ptr = peer;
16314 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
16316 peer->pokeexpire = ast_sched_add(sched, peer->maxms * 2, sip_poke_noanswer, ASTOBJ_REF(peer));
16317 if (peer->pokeexpire == -1) {
16318 struct sip_peer *peer_ptr = peer;
16319 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
16323 return 0;
16326 /*! \brief Part of PBX channel interface
16327 \note
16328 \par Return values:---
16330 If we have qualify on and the device is not reachable, regardless of registration
16331 state we return AST_DEVICE_UNAVAILABLE
16333 For peers with call limit:
16334 - not registered AST_DEVICE_UNAVAILABLE
16335 - registered, no call AST_DEVICE_NOT_INUSE
16336 - registered, active calls AST_DEVICE_INUSE
16337 - registered, call limit reached AST_DEVICE_BUSY
16338 - registered, onhold AST_DEVICE_ONHOLD
16339 - registered, ringing AST_DEVICE_RINGING
16341 For peers without call limit:
16342 - not registered AST_DEVICE_UNAVAILABLE
16343 - registered AST_DEVICE_NOT_INUSE
16344 - fixed IP (!dynamic) AST_DEVICE_NOT_INUSE
16346 Peers that does not have a known call and can't be reached by OPTIONS
16347 - unreachable AST_DEVICE_UNAVAILABLE
16349 If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
16350 out a state by walking the channel list.
16352 The queue system (\ref app_queue.c) treats a member as "active"
16353 if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
16355 When placing a call to the queue member, queue system sets a member to busy if
16356 != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
16359 static int sip_devicestate(void *data)
16361 char *host;
16362 char *tmp;
16364 struct hostent *hp;
16365 struct ast_hostent ahp;
16366 struct sip_peer *p;
16368 int res = AST_DEVICE_INVALID;
16370 /* make sure data is not null. Maybe unnecessary, but better be safe */
16371 host = ast_strdupa(data ? data : "");
16372 if ((tmp = strchr(host, '@')))
16373 host = tmp + 1;
16375 if (option_debug > 2)
16376 ast_log(LOG_DEBUG, "Checking device state for peer %s\n", host);
16378 /* If find_peer asks for a realtime peer, then this breaks rtautoclear. This
16379 * is because when a peer tries to autoexpire, the last thing it does is to
16380 * queue up an event telling the system that the devicestate has changed
16381 * (presumably to unavailable). If we ask for a realtime peer here, this would
16382 * load it BACK into memory, thus defeating the point of trying to trying to
16383 * clear dead hosts out of memory.
16385 if ((p = find_peer(host, NULL, 0, 1))) {
16386 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
16387 /* we have an address for the peer */
16389 /* Check status in this order
16390 - Hold
16391 - Ringing
16392 - Busy (enforced only by call limit)
16393 - Inuse (we have a call)
16394 - Unreachable (qualify)
16395 If we don't find any of these state, report AST_DEVICE_NOT_INUSE
16396 for registered devices */
16398 if (p->onHold)
16399 /* First check for hold or ring states */
16400 res = AST_DEVICE_ONHOLD;
16401 else if (p->inRinging) {
16402 if (p->inRinging == p->inUse)
16403 res = AST_DEVICE_RINGING;
16404 else
16405 res = AST_DEVICE_RINGINUSE;
16406 } else if (p->call_limit && (p->inUse == p->call_limit))
16407 /* check call limit */
16408 res = AST_DEVICE_BUSY;
16409 else if (p->call_limit && p->inUse)
16410 /* Not busy, but we do have a call */
16411 res = AST_DEVICE_INUSE;
16412 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
16413 /* We don't have a call. Are we reachable at all? Requires qualify= */
16414 res = AST_DEVICE_UNAVAILABLE;
16415 else /* Default reply if we're registered and have no other data */
16416 res = AST_DEVICE_NOT_INUSE;
16417 } else {
16418 /* there is no address, it's unavailable */
16419 res = AST_DEVICE_UNAVAILABLE;
16421 ASTOBJ_UNREF(p,sip_destroy_peer);
16422 } else {
16423 char *port = strchr(host, ':');
16424 if (port)
16425 *port = '\0';
16426 hp = ast_gethostbyname(host, &ahp);
16427 if (hp)
16428 res = AST_DEVICE_UNKNOWN;
16431 return res;
16434 /*! \brief PBX interface function -build SIP pvt structure
16435 SIP calls initiated by the PBX arrive here */
16436 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
16438 int oldformat;
16439 struct sip_pvt *p;
16440 struct ast_channel *tmpc = NULL;
16441 char *ext, *host;
16442 char tmp[256];
16443 char *dest = data;
16445 oldformat = format;
16446 if (!(format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1))) {
16447 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));
16448 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL; /* Can't find codec to connect to host */
16449 return NULL;
16451 if (option_debug)
16452 ast_log(LOG_DEBUG, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
16454 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE))) {
16455 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", (char *)data);
16456 *cause = AST_CAUSE_SWITCH_CONGESTION;
16457 return NULL;
16460 ast_set_flag(&p->flags[1], SIP_PAGE2_OUTGOING_CALL);
16462 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
16463 sip_destroy(p);
16464 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
16465 *cause = AST_CAUSE_SWITCH_CONGESTION;
16466 return NULL;
16469 ast_copy_string(tmp, dest, sizeof(tmp));
16470 host = strchr(tmp, '@');
16471 if (host) {
16472 *host++ = '\0';
16473 ext = tmp;
16474 } else {
16475 ext = strchr(tmp, '/');
16476 if (ext)
16477 *ext++ = '\0';
16478 host = tmp;
16481 if (create_addr(p, host)) {
16482 *cause = AST_CAUSE_UNREGISTERED;
16483 if (option_debug > 2)
16484 ast_log(LOG_DEBUG, "Cant create SIP call - target device not registred\n");
16485 sip_destroy(p);
16486 return NULL;
16488 if (ast_strlen_zero(p->peername) && ext)
16489 ast_string_field_set(p, peername, ext);
16490 /* Recalculate our side, and recalculate Call ID */
16491 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
16492 p->ourip = __ourip;
16493 build_via(p);
16494 build_callid_pvt(p);
16496 /* We have an extension to call, don't use the full contact here */
16497 /* This to enable dialing registered peers with extension dialling,
16498 like SIP/peername/extension
16499 SIP/peername will still use the full contact */
16500 if (ext) {
16501 ast_string_field_set(p, username, ext);
16502 ast_string_field_free(p, fullcontact);
16504 #if 0
16505 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
16506 #endif
16507 p->prefcodec = oldformat; /* Format for this call */
16508 ast_mutex_lock(&p->lock);
16509 tmpc = sip_new(p, AST_STATE_DOWN, host); /* Place the call */
16510 ast_mutex_unlock(&p->lock);
16511 if (!tmpc)
16512 sip_destroy(p);
16513 ast_update_use_count();
16514 restart_monitor();
16515 return tmpc;
16519 * \brief Parse the "insecure" setting from sip.conf or from realtime.
16520 * \param flags a pointer to an ast_flags structure
16521 * \param value the value of the SIP insecure setting
16522 * \param lineno linenumber in sip.conf or -1 for realtime
16524 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno)
16526 static int dep_insecure_very = 0;
16527 static int dep_insecure_yes = 0;
16529 if (ast_strlen_zero(value))
16530 return;
16532 if (!strcasecmp(value, "very")) {
16533 ast_set_flag(flags, SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16534 if(!dep_insecure_very) {
16535 if(lineno != -1)
16536 ast_log(LOG_WARNING, "insecure=very at line %d is deprecated; use insecure=port,invite instead\n", lineno);
16537 else
16538 ast_log(LOG_WARNING, "insecure=very is deprecated; use insecure=port,invite instead\n");
16539 dep_insecure_very = 1;
16542 else if (ast_true(value)) {
16543 ast_set_flag(flags, SIP_INSECURE_PORT);
16544 if(!dep_insecure_yes) {
16545 if(lineno != -1)
16546 ast_log(LOG_WARNING, "insecure=%s at line %d is deprecated; use insecure=port instead\n", value, lineno);
16547 else
16548 ast_log(LOG_WARNING, "insecure=%s is deprecated; use insecure=port instead\n", value);
16549 dep_insecure_yes = 1;
16552 else if (!ast_false(value)) {
16553 char buf[64];
16554 char *word, *next;
16555 ast_copy_string(buf, value, sizeof(buf));
16556 next = buf;
16557 while ((word = strsep(&next, ","))) {
16558 if (!strcasecmp(word, "port"))
16559 ast_set_flag(flags, SIP_INSECURE_PORT);
16560 else if (!strcasecmp(word, "invite"))
16561 ast_set_flag(flags, SIP_INSECURE_INVITE);
16562 else
16563 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
16569 \brief Handle flag-type options common to configuration of devices - users and peers
16570 \param flags array of two struct ast_flags
16571 \param mask array of two struct ast_flags
16572 \param v linked list of config variables to process
16573 \returns non-zero if any config options were handled, zero otherwise
16575 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
16577 int res = 1;
16579 if (!strcasecmp(v->name, "trustrpid")) {
16580 ast_set_flag(&mask[0], SIP_TRUSTRPID);
16581 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
16582 } else if (!strcasecmp(v->name, "sendrpid")) {
16583 ast_set_flag(&mask[0], SIP_SENDRPID);
16584 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
16585 } else if (!strcasecmp(v->name, "g726nonstandard")) {
16586 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
16587 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
16588 } else if (!strcasecmp(v->name, "useclientcode")) {
16589 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
16590 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
16591 } else if (!strcasecmp(v->name, "dtmfmode")) {
16592 ast_set_flag(&mask[0], SIP_DTMF);
16593 ast_clear_flag(&flags[0], SIP_DTMF);
16594 if (!strcasecmp(v->value, "inband"))
16595 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
16596 else if (!strcasecmp(v->value, "rfc2833"))
16597 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
16598 else if (!strcasecmp(v->value, "info"))
16599 ast_set_flag(&flags[0], SIP_DTMF_INFO);
16600 else if (!strcasecmp(v->value, "auto"))
16601 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
16602 else {
16603 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
16604 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
16606 } else if (!strcasecmp(v->name, "nat")) {
16607 ast_set_flag(&mask[0], SIP_NAT);
16608 ast_clear_flag(&flags[0], SIP_NAT);
16609 if (!strcasecmp(v->value, "never"))
16610 ast_set_flag(&flags[0], SIP_NAT_NEVER);
16611 else if (!strcasecmp(v->value, "route"))
16612 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
16613 else if (ast_true(v->value))
16614 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
16615 else
16616 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
16617 } else if (!strcasecmp(v->name, "canreinvite")) {
16618 ast_set_flag(&mask[0], SIP_REINVITE);
16619 ast_clear_flag(&flags[0], SIP_REINVITE);
16620 if(ast_true(v->value)) {
16621 ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
16622 } else if (!ast_false(v->value)) {
16623 char buf[64];
16624 char *word, *next = buf;
16626 ast_copy_string(buf, v->value, sizeof(buf));
16627 while ((word = strsep(&next, ","))) {
16628 if(!strcasecmp(word, "update")) {
16629 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
16630 } else if(!strcasecmp(word, "nonat")) {
16631 ast_set_flag(&flags[0], SIP_CAN_REINVITE);
16632 ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
16633 } else {
16634 ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
16638 } else if (!strcasecmp(v->name, "insecure")) {
16639 ast_set_flag(&mask[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16640 ast_clear_flag(&flags[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16641 set_insecure_flags(flags, v->value, v->lineno);
16642 } else if (!strcasecmp(v->name, "progressinband")) {
16643 ast_set_flag(&mask[0], SIP_PROG_INBAND);
16644 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
16645 if (ast_true(v->value))
16646 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
16647 else if (strcasecmp(v->value, "never"))
16648 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
16649 } else if (!strcasecmp(v->name, "promiscredir")) {
16650 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
16651 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
16652 } else if (!strcasecmp(v->name, "videosupport")) {
16653 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
16654 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
16655 } else if (!strcasecmp(v->name, "allowoverlap")) {
16656 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
16657 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
16658 } else if (!strcasecmp(v->name, "allowsubscribe")) {
16659 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
16660 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
16661 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
16662 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_UDPTL);
16663 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_UDPTL);
16664 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
16665 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
16666 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_RTP);
16667 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_RTP);
16668 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
16669 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_TCP);
16670 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_TCP);
16671 #endif
16672 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
16673 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
16674 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
16675 } else if (!strcasecmp(v->name, "buggymwi")) {
16676 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
16677 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
16678 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
16679 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
16680 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
16681 } else
16682 res = 0;
16684 return res;
16687 /*! \brief Add SIP domain to list of domains we are responsible for */
16688 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
16690 struct domain *d;
16692 if (ast_strlen_zero(domain)) {
16693 ast_log(LOG_WARNING, "Zero length domain.\n");
16694 return 1;
16697 if (!(d = ast_calloc(1, sizeof(*d))))
16698 return 0;
16700 ast_copy_string(d->domain, domain, sizeof(d->domain));
16702 if (!ast_strlen_zero(context))
16703 ast_copy_string(d->context, context, sizeof(d->context));
16705 d->mode = mode;
16707 AST_LIST_LOCK(&domain_list);
16708 AST_LIST_INSERT_TAIL(&domain_list, d, list);
16709 AST_LIST_UNLOCK(&domain_list);
16711 if (sipdebug)
16712 ast_log(LOG_DEBUG, "Added local SIP domain '%s'\n", domain);
16714 return 1;
16717 /*! \brief check_sip_domain: Check if domain part of uri is local to our server */
16718 static int check_sip_domain(const char *domain, char *context, size_t len)
16720 struct domain *d;
16721 int result = 0;
16723 AST_LIST_LOCK(&domain_list);
16724 AST_LIST_TRAVERSE(&domain_list, d, list) {
16725 if (strcasecmp(d->domain, domain))
16726 continue;
16728 if (len && !ast_strlen_zero(d->context))
16729 ast_copy_string(context, d->context, len);
16731 result = 1;
16732 break;
16734 AST_LIST_UNLOCK(&domain_list);
16736 return result;
16739 /*! \brief Clear our domain list (at reload) */
16740 static void clear_sip_domains(void)
16742 struct domain *d;
16744 AST_LIST_LOCK(&domain_list);
16745 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
16746 free(d);
16747 AST_LIST_UNLOCK(&domain_list);
16751 /*! \brief Add realm authentication in list */
16752 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno)
16754 char authcopy[256];
16755 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
16756 char *stringp;
16757 struct sip_auth *a, *b, *auth;
16759 if (ast_strlen_zero(configuration))
16760 return authlist;
16762 if (option_debug)
16763 ast_log(LOG_DEBUG, "Auth config :: %s\n", configuration);
16765 ast_copy_string(authcopy, configuration, sizeof(authcopy));
16766 stringp = authcopy;
16768 username = stringp;
16769 realm = strrchr(stringp, '@');
16770 if (realm)
16771 *realm++ = '\0';
16772 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
16773 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
16774 return authlist;
16776 stringp = username;
16777 username = strsep(&stringp, ":");
16778 if (username) {
16779 secret = strsep(&stringp, ":");
16780 if (!secret) {
16781 stringp = username;
16782 md5secret = strsep(&stringp,"#");
16785 if (!(auth = ast_calloc(1, sizeof(*auth))))
16786 return authlist;
16788 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
16789 ast_copy_string(auth->username, username, sizeof(auth->username));
16790 if (secret)
16791 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
16792 if (md5secret)
16793 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
16795 /* find the end of the list */
16796 for (b = NULL, a = authlist; a ; b = a, a = a->next)
16798 if (b)
16799 b->next = auth; /* Add structure add end of list */
16800 else
16801 authlist = auth;
16803 if (option_verbose > 2)
16804 ast_verbose("Added authentication for realm %s\n", realm);
16806 return authlist;
16810 /*! \brief Clear realm authentication list (at reload) */
16811 static int clear_realm_authentication(struct sip_auth *authlist)
16813 struct sip_auth *a = authlist;
16814 struct sip_auth *b;
16816 while (a) {
16817 b = a;
16818 a = a->next;
16819 free(b);
16822 return 1;
16825 /*! \brief Find authentication for a specific realm */
16826 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
16828 struct sip_auth *a;
16830 for (a = authlist; a; a = a->next) {
16831 if (!strcasecmp(a->realm, realm))
16832 break;
16835 return a;
16838 /*! \brief Initiate a SIP user structure from configuration (configuration or realtime) */
16839 static struct sip_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
16841 struct sip_user *user;
16842 int format;
16843 struct ast_ha *oldha = NULL;
16844 char *varname = NULL, *varval = NULL;
16845 struct ast_variable *tmpvar = NULL;
16846 struct ast_flags userflags[2] = {{(0)}};
16847 struct ast_flags mask[2] = {{(0)}};
16850 if (!(user = ast_calloc(1, sizeof(*user))))
16851 return NULL;
16853 suserobjs++;
16854 ASTOBJ_INIT(user);
16855 ast_copy_string(user->name, name, sizeof(user->name));
16856 oldha = user->ha;
16857 user->ha = NULL;
16858 ast_copy_flags(&user->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
16859 ast_copy_flags(&user->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16860 user->capability = global_capability;
16861 user->allowtransfer = global_allowtransfer;
16862 user->maxcallbitrate = default_maxcallbitrate;
16863 user->autoframing = global_autoframing;
16864 user->prefs = default_prefs;
16865 /* set default context */
16866 strcpy(user->context, default_context);
16867 strcpy(user->language, default_language);
16868 strcpy(user->mohinterpret, default_mohinterpret);
16869 strcpy(user->mohsuggest, default_mohsuggest);
16870 /* First we walk through the v parameters list and then the alt parameters list */
16871 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
16872 if (handle_common_options(&userflags[0], &mask[0], v))
16873 continue;
16875 if (!strcasecmp(v->name, "context")) {
16876 ast_copy_string(user->context, v->value, sizeof(user->context));
16877 } else if (!strcasecmp(v->name, "subscribecontext")) {
16878 ast_copy_string(user->subscribecontext, v->value, sizeof(user->subscribecontext));
16879 } else if (!strcasecmp(v->name, "setvar")) {
16880 varname = ast_strdupa(v->value);
16881 if ((varval = strchr(varname,'='))) {
16882 *varval++ = '\0';
16883 if ((tmpvar = ast_variable_new(varname, varval))) {
16884 tmpvar->next = user->chanvars;
16885 user->chanvars = tmpvar;
16888 } else if (!strcasecmp(v->name, "permit") ||
16889 !strcasecmp(v->name, "deny")) {
16890 user->ha = ast_append_ha(v->name, v->value, user->ha);
16891 } else if (!strcasecmp(v->name, "allowtransfer")) {
16892 user->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
16893 } else if (!strcasecmp(v->name, "secret")) {
16894 ast_copy_string(user->secret, v->value, sizeof(user->secret));
16895 } else if (!strcasecmp(v->name, "md5secret")) {
16896 ast_copy_string(user->md5secret, v->value, sizeof(user->md5secret));
16897 } else if (!strcasecmp(v->name, "callerid")) {
16898 ast_callerid_split(v->value, user->cid_name, sizeof(user->cid_name), user->cid_num, sizeof(user->cid_num));
16899 } else if (!strcasecmp(v->name, "fullname")) {
16900 ast_copy_string(user->cid_name, v->value, sizeof(user->cid_name));
16901 } else if (!strcasecmp(v->name, "cid_number")) {
16902 ast_copy_string(user->cid_num, v->value, sizeof(user->cid_num));
16903 } else if (!strcasecmp(v->name, "callgroup")) {
16904 user->callgroup = ast_get_group(v->value);
16905 } else if (!strcasecmp(v->name, "pickupgroup")) {
16906 user->pickupgroup = ast_get_group(v->value);
16907 } else if (!strcasecmp(v->name, "language")) {
16908 ast_copy_string(user->language, v->value, sizeof(user->language));
16909 } else if (!strcasecmp(v->name, "mohinterpret")
16910 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
16911 ast_copy_string(user->mohinterpret, v->value, sizeof(user->mohinterpret));
16912 } else if (!strcasecmp(v->name, "mohsuggest")) {
16913 ast_copy_string(user->mohsuggest, v->value, sizeof(user->mohsuggest));
16914 } else if (!strcasecmp(v->name, "accountcode")) {
16915 ast_copy_string(user->accountcode, v->value, sizeof(user->accountcode));
16916 } else if (!strcasecmp(v->name, "call-limit")) {
16917 user->call_limit = atoi(v->value);
16918 if (user->call_limit < 0)
16919 user->call_limit = 0;
16920 } else if (!strcasecmp(v->name, "amaflags")) {
16921 format = ast_cdr_amaflags2int(v->value);
16922 if (format < 0) {
16923 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
16924 } else {
16925 user->amaflags = format;
16927 } else if (!strcasecmp(v->name, "allow")) {
16928 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
16929 } else if (!strcasecmp(v->name, "disallow")) {
16930 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 0);
16931 } else if (!strcasecmp(v->name, "autoframing")) {
16932 user->autoframing = ast_true(v->value);
16933 } else if (!strcasecmp(v->name, "callingpres")) {
16934 user->callingpres = ast_parse_caller_presentation(v->value);
16935 if (user->callingpres == -1)
16936 user->callingpres = atoi(v->value);
16937 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
16938 user->maxcallbitrate = atoi(v->value);
16939 if (user->maxcallbitrate < 0)
16940 user->maxcallbitrate = default_maxcallbitrate;
16942 /* We can't just report unknown options here because this may be a
16943 * type=friend entry. All user options are valid for a peer, but not
16944 * the other way around. */
16946 ast_copy_flags(&user->flags[0], &userflags[0], mask[0].flags);
16947 ast_copy_flags(&user->flags[1], &userflags[1], mask[1].flags);
16948 if (ast_test_flag(&user->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
16949 global_allowsubscribe = TRUE; /* No global ban any more */
16950 ast_free_ha(oldha);
16951 return user;
16954 /*! \brief Set peer defaults before configuring specific configurations */
16955 static void set_peer_defaults(struct sip_peer *peer)
16957 if (peer->expire == 0) {
16958 /* Don't reset expire or port time during reload
16959 if we have an active registration
16961 peer->expire = -1;
16962 peer->pokeexpire = -1;
16963 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
16965 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
16966 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16967 strcpy(peer->context, default_context);
16968 strcpy(peer->subscribecontext, default_subscribecontext);
16969 strcpy(peer->language, default_language);
16970 strcpy(peer->mohinterpret, default_mohinterpret);
16971 strcpy(peer->mohsuggest, default_mohsuggest);
16972 peer->addr.sin_family = AF_INET;
16973 peer->defaddr.sin_family = AF_INET;
16974 peer->capability = global_capability;
16975 peer->maxcallbitrate = default_maxcallbitrate;
16976 peer->rtptimeout = global_rtptimeout;
16977 peer->rtpholdtimeout = global_rtpholdtimeout;
16978 peer->rtpkeepalive = global_rtpkeepalive;
16979 peer->allowtransfer = global_allowtransfer;
16980 peer->autoframing = global_autoframing;
16981 strcpy(peer->vmexten, default_vmexten);
16982 peer->secret[0] = '\0';
16983 peer->md5secret[0] = '\0';
16984 peer->cid_num[0] = '\0';
16985 peer->cid_name[0] = '\0';
16986 peer->fromdomain[0] = '\0';
16987 peer->fromuser[0] = '\0';
16988 peer->regexten[0] = '\0';
16989 peer->mailbox[0] = '\0';
16990 peer->callgroup = 0;
16991 peer->pickupgroup = 0;
16992 peer->maxms = default_qualify;
16993 peer->prefs = default_prefs;
16996 /*! \brief Create temporary peer (used in autocreatepeer mode) */
16997 static struct sip_peer *temp_peer(const char *name)
16999 struct sip_peer *peer;
17001 if (!(peer = ast_calloc(1, sizeof(*peer))))
17002 return NULL;
17004 apeerobjs++;
17005 ASTOBJ_INIT(peer);
17006 set_peer_defaults(peer);
17008 ast_copy_string(peer->name, name, sizeof(peer->name));
17010 ast_set_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT);
17011 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
17012 peer->prefs = default_prefs;
17013 reg_source_db(peer);
17015 return peer;
17018 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
17019 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
17021 struct sip_peer *peer = NULL;
17022 struct ast_ha *oldha = NULL;
17023 int obproxyfound=0;
17024 int found=0;
17025 int firstpass=1;
17026 int format=0; /* Ama flags */
17027 time_t regseconds = 0;
17028 char *varname = NULL, *varval = NULL;
17029 struct ast_variable *tmpvar = NULL;
17030 struct ast_flags peerflags[2] = {{(0)}};
17031 struct ast_flags mask[2] = {{(0)}};
17032 char fullcontact[sizeof(peer->fullcontact)] = "";
17034 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))
17035 /* Note we do NOT use find_peer here, to avoid realtime recursion */
17036 /* We also use a case-sensitive comparison (unlike find_peer) so
17037 that case changes made to the peer name will be properly handled
17038 during reload
17040 peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);
17042 if (peer) {
17043 /* Already in the list, remove it and it will be added back (or FREE'd) */
17044 found = 1;
17045 if (!(peer->objflags & ASTOBJ_FLAG_MARKED))
17046 firstpass = 0;
17047 } else {
17048 if (!(peer = ast_calloc(1, sizeof(*peer))))
17049 return NULL;
17051 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))
17052 rpeerobjs++;
17053 else
17054 speerobjs++;
17055 ASTOBJ_INIT(peer);
17057 /* Note that our peer HAS had its reference count incrased */
17058 if (firstpass) {
17059 peer->lastmsgssent = -1;
17060 oldha = peer->ha;
17061 peer->ha = NULL;
17062 set_peer_defaults(peer); /* Set peer defaults */
17064 if (!found && name)
17065 ast_copy_string(peer->name, name, sizeof(peer->name));
17067 /* If we have channel variables, remove them (reload) */
17068 if (peer->chanvars) {
17069 ast_variables_destroy(peer->chanvars);
17070 peer->chanvars = NULL;
17071 /* XXX should unregister ? */
17074 /* If we have realm authentication information, remove them (reload) */
17075 clear_realm_authentication(peer->auth);
17076 peer->auth = NULL;
17078 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
17079 if (handle_common_options(&peerflags[0], &mask[0], v))
17080 continue;
17081 if (realtime && !strcasecmp(v->name, "regseconds")) {
17082 ast_get_time_t(v->value, &regseconds, 0, NULL);
17083 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
17084 inet_aton(v->value, &(peer->addr.sin_addr));
17085 } else if (realtime && !strcasecmp(v->name, "name"))
17086 ast_copy_string(peer->name, v->value, sizeof(peer->name));
17087 else if (realtime && !strcasecmp(v->name, "fullcontact")) {
17088 /* Reconstruct field, because realtime separates our value at the ';' */
17089 if (!ast_strlen_zero(fullcontact)) {
17090 strncat(fullcontact, ";", sizeof(fullcontact) - strlen(fullcontact) - 1);
17091 strncat(fullcontact, v->value, sizeof(fullcontact) - strlen(fullcontact) - 1);
17092 } else {
17093 ast_copy_string(fullcontact, v->value, sizeof(fullcontact));
17094 ast_set_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT);
17096 } else if (!strcasecmp(v->name, "secret"))
17097 ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
17098 else if (!strcasecmp(v->name, "md5secret"))
17099 ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
17100 else if (!strcasecmp(v->name, "auth"))
17101 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
17102 else if (!strcasecmp(v->name, "callerid")) {
17103 ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
17104 } else if (!strcasecmp(v->name, "fullname")) {
17105 ast_copy_string(peer->cid_name, v->value, sizeof(peer->cid_name));
17106 } else if (!strcasecmp(v->name, "cid_number")) {
17107 ast_copy_string(peer->cid_num, v->value, sizeof(peer->cid_num));
17108 } else if (!strcasecmp(v->name, "context")) {
17109 ast_copy_string(peer->context, v->value, sizeof(peer->context));
17110 } else if (!strcasecmp(v->name, "subscribecontext")) {
17111 ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
17112 } else if (!strcasecmp(v->name, "fromdomain")) {
17113 ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
17114 } else if (!strcasecmp(v->name, "usereqphone")) {
17115 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
17116 } else if (!strcasecmp(v->name, "fromuser")) {
17117 ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
17118 } else if (!strcasecmp(v->name, "host") || !strcasecmp(v->name, "outboundproxy")) {
17119 if (!strcasecmp(v->value, "dynamic")) {
17120 if (!strcasecmp(v->name, "outboundproxy") || obproxyfound) {
17121 ast_log(LOG_WARNING, "You can't have a dynamic outbound proxy, you big silly head at line %d.\n", v->lineno);
17122 } else {
17123 /* They'll register with us */
17124 if (!found || !ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
17125 /* Initialize stuff if this is a new peer, or if it used to be
17126 * non-dynamic before the reload. */
17127 memset(&peer->addr.sin_addr, 0, 4);
17128 if (peer->addr.sin_port) {
17129 /* If we've already got a port, make it the default rather than absolute */
17130 peer->defaddr.sin_port = peer->addr.sin_port;
17131 peer->addr.sin_port = 0;
17134 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
17136 } else {
17137 /* Non-dynamic. Make sure we become that way if we're not */
17138 if (!AST_SCHED_DEL(sched, peer->expire)) {
17139 struct sip_peer *peer_ptr = peer;
17140 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
17142 ast_clear_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
17143 if (!obproxyfound || !strcasecmp(v->name, "outboundproxy")) {
17144 if (ast_get_ip_or_srv(&peer->addr, v->value, srvlookup ? "_sip._udp" : NULL)) {
17145 ASTOBJ_UNREF(peer, sip_destroy_peer);
17146 return NULL;
17149 if (!strcasecmp(v->name, "outboundproxy"))
17150 obproxyfound=1;
17151 else {
17152 ast_copy_string(peer->tohost, v->value, sizeof(peer->tohost));
17153 if (!peer->addr.sin_port)
17154 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
17157 } else if (!strcasecmp(v->name, "defaultip")) {
17158 if (ast_get_ip(&peer->defaddr, v->value)) {
17159 ASTOBJ_UNREF(peer, sip_destroy_peer);
17160 return NULL;
17162 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
17163 peer->ha = ast_append_ha(v->name, v->value, peer->ha);
17164 } else if (!strcasecmp(v->name, "port")) {
17165 if (!realtime && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC))
17166 peer->defaddr.sin_port = htons(atoi(v->value));
17167 else
17168 peer->addr.sin_port = htons(atoi(v->value));
17169 } else if (!strcasecmp(v->name, "callingpres")) {
17170 peer->callingpres = ast_parse_caller_presentation(v->value);
17171 if (peer->callingpres == -1)
17172 peer->callingpres = atoi(v->value);
17173 } else if (!strcasecmp(v->name, "username")) {
17174 ast_copy_string(peer->username, v->value, sizeof(peer->username));
17175 } else if (!strcasecmp(v->name, "language")) {
17176 ast_copy_string(peer->language, v->value, sizeof(peer->language));
17177 } else if (!strcasecmp(v->name, "regexten")) {
17178 ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
17179 } else if (!strcasecmp(v->name, "call-limit") || !strcasecmp(v->name, "incominglimit")) {
17180 peer->call_limit = atoi(v->value);
17181 if (peer->call_limit < 0)
17182 peer->call_limit = 0;
17183 } else if (!strcasecmp(v->name, "amaflags")) {
17184 format = ast_cdr_amaflags2int(v->value);
17185 if (format < 0) {
17186 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
17187 } else {
17188 peer->amaflags = format;
17190 } else if (!strcasecmp(v->name, "accountcode")) {
17191 ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
17192 } else if (!strcasecmp(v->name, "mohinterpret")
17193 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
17194 ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
17195 } else if (!strcasecmp(v->name, "mohsuggest")) {
17196 ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
17197 } else if (!strcasecmp(v->name, "mailbox")) {
17198 ast_copy_string(peer->mailbox, v->value, sizeof(peer->mailbox));
17199 } else if (!strcasecmp(v->name, "hasvoicemail")) {
17200 /* People expect that if 'hasvoicemail' is set, that the mailbox will
17201 * be also set, even if not explicitly specified. */
17202 if (ast_true(v->value) && ast_strlen_zero(peer->mailbox)) {
17203 ast_copy_string(peer->mailbox, name, sizeof(peer->mailbox));
17205 } else if (!strcasecmp(v->name, "subscribemwi")) {
17206 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
17207 } else if (!strcasecmp(v->name, "vmexten")) {
17208 ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
17209 } else if (!strcasecmp(v->name, "callgroup")) {
17210 peer->callgroup = ast_get_group(v->value);
17211 } else if (!strcasecmp(v->name, "allowtransfer")) {
17212 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
17213 } else if (!strcasecmp(v->name, "pickupgroup")) {
17214 peer->pickupgroup = ast_get_group(v->value);
17215 } else if (!strcasecmp(v->name, "allow")) {
17216 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
17217 } else if (!strcasecmp(v->name, "disallow")) {
17218 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
17219 } else if (!strcasecmp(v->name, "autoframing")) {
17220 peer->autoframing = ast_true(v->value);
17221 } else if (!strcasecmp(v->name, "rtptimeout")) {
17222 if ((sscanf(v->value, "%d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
17223 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
17224 peer->rtptimeout = global_rtptimeout;
17226 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
17227 if ((sscanf(v->value, "%d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
17228 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
17229 peer->rtpholdtimeout = global_rtpholdtimeout;
17231 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
17232 if ((sscanf(v->value, "%d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
17233 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
17234 peer->rtpkeepalive = global_rtpkeepalive;
17236 } else if (!strcasecmp(v->name, "setvar")) {
17237 /* Set peer channel variable */
17238 varname = ast_strdupa(v->value);
17239 if ((varval = strchr(varname, '='))) {
17240 *varval++ = '\0';
17241 if ((tmpvar = ast_variable_new(varname, varval))) {
17242 tmpvar->next = peer->chanvars;
17243 peer->chanvars = tmpvar;
17246 } else if (!strcasecmp(v->name, "qualify")) {
17247 if (!strcasecmp(v->value, "no")) {
17248 peer->maxms = 0;
17249 } else if (!strcasecmp(v->value, "yes")) {
17250 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
17251 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
17252 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);
17253 peer->maxms = 0;
17255 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
17256 peer->maxcallbitrate = atoi(v->value);
17257 if (peer->maxcallbitrate < 0)
17258 peer->maxcallbitrate = default_maxcallbitrate;
17261 if (!ast_strlen_zero(fullcontact)) {
17262 ast_copy_string(peer->fullcontact, fullcontact, sizeof(peer->fullcontact));
17263 /* We have a hostname in the fullcontact, but if we don't have an
17264 * address listed on the entry (or if it's 'dynamic'), then we need to
17265 * parse the entry to obtain the IP address, so a dynamic host can be
17266 * contacted immediately after reload (as opposed to waiting for it to
17267 * register once again). */
17268 __set_address_from_contact(fullcontact, &peer->addr);
17271 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && realtime) {
17272 time_t nowtime = time(NULL);
17274 if ((nowtime - regseconds) > 0) {
17275 destroy_association(peer);
17276 memset(&peer->addr, 0, sizeof(peer->addr));
17277 if (option_debug)
17278 ast_log(LOG_DEBUG, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
17281 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
17282 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
17283 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
17284 global_allowsubscribe = TRUE; /* No global ban any more */
17285 if (!found && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && !ast_test_flag(&peer->flags[0], SIP_REALTIME))
17286 reg_source_db(peer);
17287 ASTOBJ_UNMARK(peer);
17288 ast_free_ha(oldha);
17289 return peer;
17292 /*! \brief Re-read SIP.conf config file
17293 \note This function reloads all config data, except for
17294 active peers (with registrations). They will only
17295 change configuration data at restart, not at reload.
17296 SIP debug and recordhistory state will not change
17298 static int reload_config(enum channelreloadreason reason)
17300 struct ast_config *cfg, *ucfg;
17301 struct ast_variable *v;
17302 struct sip_peer *peer;
17303 struct sip_user *user;
17304 struct ast_hostent ahp;
17305 char *cat, *stringp, *context, *oldregcontext;
17306 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
17307 struct hostent *hp;
17308 int format;
17309 struct ast_flags dummy[2];
17310 int auto_sip_domains = FALSE;
17311 struct sockaddr_in old_bindaddr = bindaddr;
17312 int registry_count = 0, peer_count = 0, user_count = 0;
17313 unsigned int temp_tos = 0;
17314 struct ast_flags debugflag = {0};
17316 cfg = ast_config_load(config);
17318 /* We *must* have a config file otherwise stop immediately */
17319 if (!cfg) {
17320 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
17321 return -1;
17324 if (option_debug > 3)
17325 ast_log(LOG_DEBUG, "--------------- SIP reload started\n");
17327 clear_realm_authentication(authl);
17328 clear_sip_domains();
17329 authl = NULL;
17331 /* First, destroy all outstanding registry calls */
17332 /* This is needed, since otherwise active registry entries will not be destroyed */
17333 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
17334 ASTOBJ_RDLOCK(iterator);
17335 if (iterator->call) {
17336 if (option_debug > 2)
17337 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
17338 /* This will also remove references to the registry */
17339 sip_destroy(iterator->call);
17341 ASTOBJ_UNLOCK(iterator);
17343 } while(0));
17345 /* Then, actually destroy users and registry */
17346 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
17347 if (option_debug > 3)
17348 ast_log(LOG_DEBUG, "--------------- Done destroying user list\n");
17349 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
17350 if (option_debug > 3)
17351 ast_log(LOG_DEBUG, "--------------- Done destroying registry list\n");
17352 ASTOBJ_CONTAINER_MARKALL(&peerl);
17354 /* Initialize copy of current global_regcontext for later use in removing stale contexts */
17355 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
17356 oldregcontext = oldcontexts;
17358 /* Clear all flags before setting default values */
17359 /* Preserve debugging settings for console */
17360 ast_copy_flags(&debugflag, &global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
17361 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
17362 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
17363 ast_copy_flags(&global_flags[1], &debugflag, SIP_PAGE2_DEBUG_CONSOLE);
17365 /* Reset IP addresses */
17366 memset(&bindaddr, 0, sizeof(bindaddr));
17367 ast_free_ha(localaddr);
17368 memset(&localaddr, 0, sizeof(localaddr));
17369 memset(&externip, 0, sizeof(externip));
17370 memset(&default_prefs, 0 , sizeof(default_prefs));
17371 outboundproxyip.sin_port = htons(STANDARD_SIP_PORT);
17372 outboundproxyip.sin_family = AF_INET; /* Type of address: IPv4 */
17373 ourport = STANDARD_SIP_PORT;
17374 srvlookup = DEFAULT_SRVLOOKUP;
17375 global_tos_sip = DEFAULT_TOS_SIP;
17376 global_tos_audio = DEFAULT_TOS_AUDIO;
17377 global_tos_video = DEFAULT_TOS_VIDEO;
17378 externhost[0] = '\0'; /* External host name (for behind NAT DynDNS support) */
17379 externexpire = 0; /* Expiration for DNS re-issuing */
17380 externrefresh = 10;
17381 memset(&outboundproxyip, 0, sizeof(outboundproxyip));
17383 /* Reset channel settings to default before re-configuring */
17384 allow_external_domains = DEFAULT_ALLOW_EXT_DOM; /* Allow external invites */
17385 global_regcontext[0] = '\0';
17386 expiry = DEFAULT_EXPIRY;
17387 global_notifyringing = DEFAULT_NOTIFYRINGING;
17388 global_limitonpeers = FALSE;
17389 global_directrtpsetup = FALSE; /* Experimental feature, disabled by default */
17390 global_notifyhold = FALSE;
17391 global_alwaysauthreject = 0;
17392 global_allowsubscribe = FALSE;
17393 ast_copy_string(global_useragent, DEFAULT_USERAGENT, sizeof(global_useragent));
17394 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
17395 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME))
17396 ast_copy_string(global_realm, DEFAULT_REALM, sizeof(global_realm));
17397 else
17398 ast_copy_string(global_realm, ast_config_AST_SYSTEM_NAME, sizeof(global_realm));
17399 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
17400 compactheaders = DEFAULT_COMPACTHEADERS;
17401 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
17402 global_regattempts_max = 0;
17403 pedanticsipchecking = DEFAULT_PEDANTIC;
17404 global_mwitime = DEFAULT_MWITIME;
17405 autocreatepeer = DEFAULT_AUTOCREATEPEER;
17406 global_autoframing = 0;
17407 global_allowguest = DEFAULT_ALLOWGUEST;
17408 global_rtptimeout = 0;
17409 global_rtpholdtimeout = 0;
17410 global_rtpkeepalive = 0;
17411 global_allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
17412 global_rtautoclear = 120;
17413 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE); /* Default for peers, users: TRUE */
17414 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP); /* Default for peers, users: TRUE */
17415 ast_set_flag(&global_flags[1], SIP_PAGE2_RTUPDATE);
17417 /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for peers and users */
17418 ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
17419 default_subscribecontext[0] = '\0';
17420 default_language[0] = '\0';
17421 default_fromdomain[0] = '\0';
17422 default_qualify = DEFAULT_QUALIFY;
17423 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
17424 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
17425 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
17426 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
17427 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833); /*!< Default DTMF setting: RFC2833 */
17428 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581); /*!< NAT support if requested by device with rport */
17429 ast_set_flag(&global_flags[0], SIP_CAN_REINVITE); /*!< Allow re-invites */
17431 /* Debugging settings, always default to off */
17432 dumphistory = FALSE;
17433 recordhistory = FALSE;
17434 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
17436 /* Misc settings for the channel */
17437 global_relaxdtmf = FALSE;
17438 global_callevents = FALSE;
17439 global_t1min = DEFAULT_T1MIN;
17441 global_matchexterniplocally = FALSE;
17443 /* Copy the default jb config over global_jbconf */
17444 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
17446 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT);
17448 /* Read the [general] config section of sip.conf (or from realtime config) */
17449 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
17450 if (handle_common_options(&global_flags[0], &dummy[0], v))
17451 continue;
17452 /* handle jb conf */
17453 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
17454 continue;
17456 /* Create the interface list */
17457 if (!strcasecmp(v->name, "context")) {
17458 ast_copy_string(default_context, v->value, sizeof(default_context));
17459 } else if (!strcasecmp(v->name, "subscribecontext")) {
17460 ast_copy_string(default_subscribecontext, v->value, sizeof(default_subscribecontext));
17461 } else if (!strcasecmp(v->name, "allowguest")) {
17462 global_allowguest = ast_true(v->value) ? 1 : 0;
17463 } else if (!strcasecmp(v->name, "realm")) {
17464 ast_copy_string(global_realm, v->value, sizeof(global_realm));
17465 } else if (!strcasecmp(v->name, "useragent")) {
17466 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
17467 if (option_debug)
17468 ast_log(LOG_DEBUG, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
17469 } else if (!strcasecmp(v->name, "allowtransfer")) {
17470 global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
17471 } else if (!strcasecmp(v->name, "rtcachefriends")) {
17472 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
17473 } else if (!strcasecmp(v->name, "rtsavesysname")) {
17474 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTSAVE_SYSNAME);
17475 } else if (!strcasecmp(v->name, "rtupdate")) {
17476 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTUPDATE);
17477 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
17478 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_IGNOREREGEXPIRE);
17479 } else if (!strcasecmp(v->name, "t1min")) {
17480 global_t1min = atoi(v->value);
17481 } else if (!strcasecmp(v->name, "rtautoclear")) {
17482 int i = atoi(v->value);
17483 if (i > 0)
17484 global_rtautoclear = i;
17485 else
17486 i = 0;
17487 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
17488 } else if (!strcasecmp(v->name, "usereqphone")) {
17489 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
17490 } else if (!strcasecmp(v->name, "relaxdtmf")) {
17491 global_relaxdtmf = ast_true(v->value);
17492 } else if (!strcasecmp(v->name, "checkmwi")) {
17493 if ((sscanf(v->value, "%d", &global_mwitime) != 1) || (global_mwitime < 0)) {
17494 ast_log(LOG_WARNING, "'%s' is not a valid MWI time setting at line %d. Using default (10).\n", v->value, v->lineno);
17495 global_mwitime = DEFAULT_MWITIME;
17497 } else if (!strcasecmp(v->name, "vmexten")) {
17498 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
17499 } else if (!strcasecmp(v->name, "rtptimeout")) {
17500 if ((sscanf(v->value, "%d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
17501 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
17502 global_rtptimeout = 0;
17504 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
17505 if ((sscanf(v->value, "%d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
17506 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
17507 global_rtpholdtimeout = 0;
17509 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
17510 if ((sscanf(v->value, "%d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
17511 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
17512 global_rtpkeepalive = 0;
17514 } else if (!strcasecmp(v->name, "compactheaders")) {
17515 compactheaders = ast_true(v->value);
17516 } else if (!strcasecmp(v->name, "notifymimetype")) {
17517 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
17518 } else if (!strncasecmp(v->name, "limitonpeer", 11)) {
17519 global_limitonpeers = ast_true(v->value);
17520 } else if (!strcasecmp(v->name, "directrtpsetup")) {
17521 global_directrtpsetup = ast_true(v->value);
17522 } else if (!strcasecmp(v->name, "notifyringing")) {
17523 global_notifyringing = ast_true(v->value);
17524 } else if (!strcasecmp(v->name, "notifyhold")) {
17525 global_notifyhold = ast_true(v->value);
17526 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
17527 global_alwaysauthreject = ast_true(v->value);
17528 } else if (!strcasecmp(v->name, "mohinterpret")
17529 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
17530 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
17531 } else if (!strcasecmp(v->name, "mohsuggest")) {
17532 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
17533 } else if (!strcasecmp(v->name, "language")) {
17534 ast_copy_string(default_language, v->value, sizeof(default_language));
17535 } else if (!strcasecmp(v->name, "regcontext")) {
17536 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
17537 stringp = newcontexts;
17538 /* Let's remove any contexts that are no longer defined in regcontext */
17539 cleanup_stale_contexts(stringp, oldregcontext);
17540 /* Create contexts if they don't exist already */
17541 while ((context = strsep(&stringp, "&"))) {
17542 if (!ast_context_find(context))
17543 ast_context_create(NULL, context,"SIP");
17545 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
17546 } else if (!strcasecmp(v->name, "callerid")) {
17547 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
17548 } else if (!strcasecmp(v->name, "fromdomain")) {
17549 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
17550 } else if (!strcasecmp(v->name, "outboundproxy")) {
17551 if (ast_get_ip_or_srv(&outboundproxyip, v->value, srvlookup ? "_sip._udp" : NULL) < 0)
17552 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", v->value);
17553 } else if (!strcasecmp(v->name, "outboundproxyport")) {
17554 /* Port needs to be after IP */
17555 sscanf(v->value, "%d", &format);
17556 outboundproxyip.sin_port = htons(format);
17557 } else if (!strcasecmp(v->name, "autocreatepeer")) {
17558 autocreatepeer = ast_true(v->value);
17559 } else if (!strcasecmp(v->name, "srvlookup")) {
17560 srvlookup = ast_true(v->value);
17561 } else if (!strcasecmp(v->name, "pedantic")) {
17562 pedanticsipchecking = ast_true(v->value);
17563 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
17564 max_expiry = atoi(v->value);
17565 if (max_expiry < 1)
17566 max_expiry = DEFAULT_MAX_EXPIRY;
17567 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
17568 min_expiry = atoi(v->value);
17569 if (min_expiry < 1)
17570 min_expiry = DEFAULT_MIN_EXPIRY;
17571 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
17572 default_expiry = atoi(v->value);
17573 if (default_expiry < 1)
17574 default_expiry = DEFAULT_DEFAULT_EXPIRY;
17575 } else if (!strcasecmp(v->name, "sipdebug")) { /* XXX maybe ast_set2_flags ? */
17576 if (ast_true(v->value))
17577 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
17578 } else if (!strcasecmp(v->name, "dumphistory")) {
17579 dumphistory = ast_true(v->value);
17580 } else if (!strcasecmp(v->name, "recordhistory")) {
17581 recordhistory = ast_true(v->value);
17582 } else if (!strcasecmp(v->name, "registertimeout")) {
17583 global_reg_timeout = atoi(v->value);
17584 if (global_reg_timeout < 1)
17585 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
17586 } else if (!strcasecmp(v->name, "registerattempts")) {
17587 global_regattempts_max = atoi(v->value);
17588 } else if (!strcasecmp(v->name, "bindaddr")) {
17589 if (!(hp = ast_gethostbyname(v->value, &ahp))) {
17590 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
17591 } else {
17592 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
17594 } else if (!strcasecmp(v->name, "localnet")) {
17595 struct ast_ha *na;
17596 if (!(na = ast_append_ha("d", v->value, localaddr)))
17597 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
17598 else
17599 localaddr = na;
17600 } else if (!strcasecmp(v->name, "localmask")) {
17601 ast_log(LOG_WARNING, "Use of localmask is no long supported -- use localnet with mask syntax\n");
17602 } else if (!strcasecmp(v->name, "externip")) {
17603 if (!(hp = ast_gethostbyname(v->value, &ahp)))
17604 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
17605 else
17606 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
17607 externexpire = 0;
17608 } else if (!strcasecmp(v->name, "externhost")) {
17609 ast_copy_string(externhost, v->value, sizeof(externhost));
17610 if (!(hp = ast_gethostbyname(externhost, &ahp)))
17611 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
17612 else
17613 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
17614 externexpire = time(NULL);
17615 } else if (!strcasecmp(v->name, "externrefresh")) {
17616 if (sscanf(v->value, "%d", &externrefresh) != 1) {
17617 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
17618 externrefresh = 10;
17620 } else if (!strcasecmp(v->name, "allow")) {
17621 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 1);
17622 } else if (!strcasecmp(v->name, "disallow")) {
17623 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 0);
17624 } else if (!strcasecmp(v->name, "autoframing")) {
17625 global_autoframing = ast_true(v->value);
17626 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
17627 allow_external_domains = ast_true(v->value);
17628 } else if (!strcasecmp(v->name, "autodomain")) {
17629 auto_sip_domains = ast_true(v->value);
17630 } else if (!strcasecmp(v->name, "domain")) {
17631 char *domain = ast_strdupa(v->value);
17632 char *context = strchr(domain, ',');
17634 if (context)
17635 *context++ = '\0';
17637 if (option_debug && ast_strlen_zero(context))
17638 ast_log(LOG_DEBUG, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
17639 if (ast_strlen_zero(domain))
17640 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
17641 else
17642 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, context ? ast_strip(context) : "");
17643 } else if (!strcasecmp(v->name, "register")) {
17644 if (sip_register(v->value, v->lineno) == 0)
17645 registry_count++;
17646 } else if (!strcasecmp(v->name, "tos")) {
17647 if (!ast_str2tos(v->value, &temp_tos)) {
17648 global_tos_sip = temp_tos;
17649 global_tos_audio = temp_tos;
17650 global_tos_video = temp_tos;
17651 ast_log(LOG_WARNING, "tos value at line %d is deprecated. See doc/ip-tos.txt for more information.\n", v->lineno);
17652 } else
17653 ast_log(LOG_WARNING, "Invalid tos value at line %d, See doc/ip-tos.txt for more information.\n", v->lineno);
17654 } else if (!strcasecmp(v->name, "tos_sip")) {
17655 if (ast_str2tos(v->value, &global_tos_sip))
17656 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, recommended value is 'cs3'. See doc/ip-tos.txt.\n", v->lineno);
17657 } else if (!strcasecmp(v->name, "tos_audio")) {
17658 if (ast_str2tos(v->value, &global_tos_audio))
17659 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, recommended value is 'ef'. See doc/ip-tos.txt.\n", v->lineno);
17660 } else if (!strcasecmp(v->name, "tos_video")) {
17661 if (ast_str2tos(v->value, &global_tos_video))
17662 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, recommended value is 'af41'. See doc/ip-tos.txt.\n", v->lineno);
17663 } else if (!strcasecmp(v->name, "bindport")) {
17664 if (sscanf(v->value, "%d", &ourport) == 1) {
17665 bindaddr.sin_port = htons(ourport);
17666 } else {
17667 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
17669 } else if (!strcasecmp(v->name, "qualify")) {
17670 if (!strcasecmp(v->value, "no")) {
17671 default_qualify = 0;
17672 } else if (!strcasecmp(v->value, "yes")) {
17673 default_qualify = DEFAULT_MAXMS;
17674 } else if (sscanf(v->value, "%d", &default_qualify) != 1) {
17675 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
17676 default_qualify = 0;
17678 } else if (!strcasecmp(v->name, "callevents")) {
17679 global_callevents = ast_true(v->value);
17680 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
17681 default_maxcallbitrate = atoi(v->value);
17682 if (default_maxcallbitrate < 0)
17683 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
17684 } else if (!strcasecmp(v->name, "matchexterniplocally")) {
17685 global_matchexterniplocally = ast_true(v->value);
17689 if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
17690 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
17691 allow_external_domains = 1;
17694 /* Build list of authentication to various SIP realms, i.e. service providers */
17695 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
17696 /* Format for authentication is auth = username:password@realm */
17697 if (!strcasecmp(v->name, "auth"))
17698 authl = add_realm_authentication(authl, v->value, v->lineno);
17701 ucfg = ast_config_load("users.conf");
17702 if (ucfg) {
17703 struct ast_variable *gen;
17704 int genhassip, genregistersip;
17705 const char *hassip, *registersip;
17707 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
17708 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
17709 gen = ast_variable_browse(ucfg, "general");
17710 cat = ast_category_browse(ucfg, NULL);
17711 while (cat) {
17712 if (strcasecmp(cat, "general")) {
17713 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
17714 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
17715 if (ast_true(hassip) || (!hassip && genhassip)) {
17716 user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
17717 if (user) {
17718 ASTOBJ_CONTAINER_LINK(&userl,user);
17719 ASTOBJ_UNREF(user, sip_destroy_user);
17720 user_count++;
17722 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
17723 if (peer) {
17724 ast_device_state_changed("SIP/%s", peer->name);
17725 ASTOBJ_CONTAINER_LINK(&peerl,peer);
17726 ASTOBJ_UNREF(peer, sip_destroy_peer);
17727 peer_count++;
17730 if (ast_true(registersip) || (!registersip && genregistersip)) {
17731 char tmp[256];
17732 const char *host = ast_variable_retrieve(ucfg, cat, "host");
17733 const char *username = ast_variable_retrieve(ucfg, cat, "username");
17734 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
17735 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
17736 if (!host)
17737 host = ast_variable_retrieve(ucfg, "general", "host");
17738 if (!username)
17739 username = ast_variable_retrieve(ucfg, "general", "username");
17740 if (!secret)
17741 secret = ast_variable_retrieve(ucfg, "general", "secret");
17742 if (!contact)
17743 contact = "s";
17744 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
17745 if (!ast_strlen_zero(secret))
17746 snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
17747 else
17748 snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
17749 if (sip_register(tmp, 0) == 0)
17750 registry_count++;
17754 cat = ast_category_browse(ucfg, cat);
17756 ast_config_destroy(ucfg);
17760 /* Load peers, users and friends */
17761 cat = NULL;
17762 while ( (cat = ast_category_browse(cfg, cat)) ) {
17763 const char *utype;
17764 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
17765 continue;
17766 utype = ast_variable_retrieve(cfg, cat, "type");
17767 if (!utype) {
17768 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
17769 continue;
17770 } else {
17771 int is_user = 0, is_peer = 0;
17772 if (!strcasecmp(utype, "user"))
17773 is_user = 1;
17774 else if (!strcasecmp(utype, "friend"))
17775 is_user = is_peer = 1;
17776 else if (!strcasecmp(utype, "peer"))
17777 is_peer = 1;
17778 else {
17779 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
17780 continue;
17782 if (is_user) {
17783 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
17784 if (user) {
17785 ASTOBJ_CONTAINER_LINK(&userl,user);
17786 ASTOBJ_UNREF(user, sip_destroy_user);
17787 user_count++;
17790 if (is_peer) {
17791 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
17792 if (peer) {
17793 ASTOBJ_CONTAINER_LINK(&peerl,peer);
17794 ASTOBJ_UNREF(peer, sip_destroy_peer);
17795 peer_count++;
17800 if (ast_find_ourip(&__ourip, bindaddr)) {
17801 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
17802 ast_config_destroy(cfg);
17803 return 0;
17805 if (!ntohs(bindaddr.sin_port))
17806 bindaddr.sin_port = ntohs(STANDARD_SIP_PORT);
17807 bindaddr.sin_family = AF_INET;
17808 ast_mutex_lock(&netlock);
17809 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
17810 close(sipsock);
17811 sipsock = -1;
17813 if (sipsock < 0) {
17814 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
17815 if (sipsock < 0) {
17816 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
17817 ast_config_destroy(cfg);
17818 return -1;
17819 } else {
17820 /* Allow SIP clients on the same host to access us: */
17821 const int reuseFlag = 1;
17823 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
17824 (const char*)&reuseFlag,
17825 sizeof reuseFlag);
17827 ast_enable_packet_fragmentation(sipsock);
17829 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
17830 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
17831 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
17832 strerror(errno));
17833 close(sipsock);
17834 sipsock = -1;
17835 } else {
17836 if (option_verbose > 1) {
17837 ast_verbose(VERBOSE_PREFIX_2 "SIP Listening on %s:%d\n",
17838 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
17839 ast_verbose(VERBOSE_PREFIX_2 "Using SIP TOS: %s\n", ast_tos2str(global_tos_sip));
17841 if (setsockopt(sipsock, IPPROTO_IP, IP_TOS, &global_tos_sip, sizeof(global_tos_sip)))
17842 ast_log(LOG_WARNING, "Unable to set SIP TOS to %s\n", ast_tos2str(global_tos_sip));
17846 ast_mutex_unlock(&netlock);
17848 /* Add default domains - host name, IP address and IP:port */
17849 /* Only do this if user added any sip domain with "localdomains" */
17850 /* In order to *not* break backwards compatibility */
17851 /* Some phones address us at IP only, some with additional port number */
17852 if (auto_sip_domains) {
17853 char temp[MAXHOSTNAMELEN];
17855 /* First our default IP address */
17856 if (bindaddr.sin_addr.s_addr)
17857 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
17858 else
17859 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
17861 /* Our extern IP address, if configured */
17862 if (externip.sin_addr.s_addr)
17863 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
17865 /* Extern host name (NAT traversal support) */
17866 if (!ast_strlen_zero(externhost))
17867 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
17869 /* Our host name */
17870 if (!gethostname(temp, sizeof(temp)))
17871 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
17874 /* Release configuration from memory */
17875 ast_config_destroy(cfg);
17877 /* Load the list of manual NOTIFY types to support */
17878 if (notify_types)
17879 ast_config_destroy(notify_types);
17880 notify_types = ast_config_load(notify_config);
17882 /* Done, tell the manager */
17883 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);
17885 return 0;
17888 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
17890 struct sip_pvt *p;
17891 struct ast_udptl *udptl = NULL;
17893 p = chan->tech_pvt;
17894 if (!p)
17895 return NULL;
17897 ast_mutex_lock(&p->lock);
17898 if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
17899 udptl = p->udptl;
17900 ast_mutex_unlock(&p->lock);
17901 return udptl;
17904 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
17906 struct sip_pvt *p;
17908 p = chan->tech_pvt;
17909 if (!p)
17910 return -1;
17911 ast_mutex_lock(&p->lock);
17912 if (udptl)
17913 ast_udptl_get_peer(udptl, &p->udptlredirip);
17914 else
17915 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
17916 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
17917 if (!p->pendinginvite) {
17918 if (option_debug > 2) {
17919 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);
17921 transmit_reinvite_with_t38_sdp(p);
17922 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17923 if (option_debug > 2) {
17924 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);
17926 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17929 /* Reset lastrtprx timer */
17930 p->lastrtprx = p->lastrtptx = time(NULL);
17931 ast_mutex_unlock(&p->lock);
17932 return 0;
17935 /*! \brief Handle T38 reinvite
17936 \todo Make sure we don't destroy the call if we can't handle the re-invite.
17937 Nothing should be changed until we have processed the SDP and know that we
17938 can handle it.
17940 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite)
17942 struct sip_pvt *p;
17943 int flag = 0;
17945 p = chan->tech_pvt;
17946 if (!p || !pvt->udptl)
17947 return -1;
17949 /* Setup everything on the other side like offered/responded from first side */
17950 ast_mutex_lock(&p->lock);
17952 /*! \todo check if this is not set earlier when setting up the PVT. If not
17953 maybe it should move there. */
17954 p->t38.jointcapability = p->t38.peercapability = pvt->t38.jointcapability;
17956 ast_udptl_set_far_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
17957 ast_udptl_set_local_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
17958 ast_udptl_set_error_correction_scheme(p->udptl, ast_udptl_get_error_correction_scheme(pvt->udptl));
17960 if (reinvite) { /* If we are handling sending re-invite to the other side of the bridge */
17961 /*! \note The SIP_CAN_REINVITE flag is for RTP media redirects,
17962 not really T38 re-invites which are different. In this
17963 case it's used properly, to see if we can reinvite over
17964 NAT
17966 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
17967 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
17968 flag =1;
17969 } else {
17970 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
17972 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
17973 if (!p->pendinginvite) {
17974 if (option_debug > 2) {
17975 if (flag)
17976 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));
17977 else
17978 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));
17980 transmit_reinvite_with_t38_sdp(p);
17981 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17982 if (option_debug > 2) {
17983 if (flag)
17984 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));
17985 else
17986 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));
17988 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17991 /* Reset lastrtprx timer */
17992 p->lastrtprx = p->lastrtptx = time(NULL);
17993 ast_mutex_unlock(&p->lock);
17994 return 0;
17995 } else { /* If we are handling sending 200 OK to the other side of the bridge */
17996 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
17997 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
17998 flag = 1;
17999 } else {
18000 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
18002 if (option_debug > 2) {
18003 if (flag)
18004 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));
18005 else
18006 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));
18008 pvt->t38.state = T38_ENABLED;
18009 p->t38.state = T38_ENABLED;
18010 if (option_debug > 1) {
18011 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", pvt->t38.state, pvt->owner ? pvt->owner->name : "<none>");
18012 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
18014 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
18015 p->lastrtprx = p->lastrtptx = time(NULL);
18016 ast_mutex_unlock(&p->lock);
18017 return 0;
18022 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
18023 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
18025 struct sip_pvt *p = NULL;
18026 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
18028 if (!(p = chan->tech_pvt))
18029 return AST_RTP_GET_FAILED;
18031 ast_mutex_lock(&p->lock);
18032 if (!(p->rtp)) {
18033 ast_mutex_unlock(&p->lock);
18034 return AST_RTP_GET_FAILED;
18037 *rtp = p->rtp;
18039 if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT))
18040 res = AST_RTP_TRY_PARTIAL;
18041 else if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
18042 res = AST_RTP_TRY_NATIVE;
18043 else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
18044 res = AST_RTP_GET_FAILED;
18046 ast_mutex_unlock(&p->lock);
18048 return res;
18051 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
18052 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
18054 struct sip_pvt *p = NULL;
18055 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
18057 if (!(p = chan->tech_pvt))
18058 return AST_RTP_GET_FAILED;
18060 ast_mutex_lock(&p->lock);
18061 if (!(p->vrtp)) {
18062 ast_mutex_unlock(&p->lock);
18063 return AST_RTP_GET_FAILED;
18066 *rtp = p->vrtp;
18068 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
18069 res = AST_RTP_TRY_NATIVE;
18071 ast_mutex_unlock(&p->lock);
18073 return res;
18076 /*! \brief Set the RTP peer for this call */
18077 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
18079 struct sip_pvt *p;
18080 int changed = 0;
18082 p = chan->tech_pvt;
18083 if (!p)
18084 return -1;
18086 /* Disable early RTP bridge */
18087 if (chan->_state != AST_STATE_UP && !global_directrtpsetup) /* We are in early state */
18088 return 0;
18090 ast_mutex_lock(&p->lock);
18091 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) {
18092 /* If we're destroyed, don't bother */
18093 ast_mutex_unlock(&p->lock);
18094 return 0;
18097 /* if this peer cannot handle reinvites of the media stream to devices
18098 that are known to be behind a NAT, then stop the process now
18100 if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
18101 ast_mutex_unlock(&p->lock);
18102 return 0;
18105 if (rtp) {
18106 changed |= ast_rtp_get_peer(rtp, &p->redirip);
18107 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
18108 memset(&p->redirip, 0, sizeof(p->redirip));
18109 changed = 1;
18111 if (vrtp) {
18112 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
18113 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
18114 memset(&p->vredirip, 0, sizeof(p->vredirip));
18115 changed = 1;
18117 if (codecs) {
18118 if ((p->redircodecs != codecs)) {
18119 p->redircodecs = codecs;
18120 changed = 1;
18122 if ((p->capability & codecs) != p->capability) {
18123 p->jointcapability &= codecs;
18124 p->capability &= codecs;
18125 changed = 1;
18128 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
18129 if (chan->_state != AST_STATE_UP) { /* We are in early state */
18130 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
18131 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
18132 if (option_debug)
18133 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));
18134 } else if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
18135 if (option_debug > 2) {
18136 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));
18138 transmit_reinvite_with_sdp(p);
18139 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
18140 if (option_debug > 2) {
18141 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));
18143 /* We have a pending Invite. Send re-invite when we're done with the invite */
18144 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
18147 /* Reset lastrtprx timer */
18148 p->lastrtprx = p->lastrtptx = time(NULL);
18149 ast_mutex_unlock(&p->lock);
18150 return 0;
18153 static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
18154 static char *descrip_dtmfmode = "SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
18155 static char *app_dtmfmode = "SIPDtmfMode";
18157 static char *app_sipaddheader = "SIPAddHeader";
18158 static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
18160 static char *descrip_sipaddheader = ""
18161 " SIPAddHeader(Header: Content)\n"
18162 "Adds a header to a SIP call placed with DIAL.\n"
18163 "Remember to user the X-header if you are adding non-standard SIP\n"
18164 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
18165 "Adding the wrong headers may jeopardize the SIP dialog.\n"
18166 "Always returns 0\n";
18169 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
18170 static int sip_dtmfmode(struct ast_channel *chan, void *data)
18172 struct sip_pvt *p;
18173 char *mode;
18174 if (data)
18175 mode = (char *)data;
18176 else {
18177 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
18178 return 0;
18180 ast_channel_lock(chan);
18181 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
18182 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
18183 ast_channel_unlock(chan);
18184 return 0;
18186 p = chan->tech_pvt;
18187 if (!p) {
18188 ast_channel_unlock(chan);
18189 return 0;
18191 ast_mutex_lock(&p->lock);
18192 if (!strcasecmp(mode,"info")) {
18193 ast_clear_flag(&p->flags[0], SIP_DTMF);
18194 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
18195 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
18196 } else if (!strcasecmp(mode,"rfc2833")) {
18197 ast_clear_flag(&p->flags[0], SIP_DTMF);
18198 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
18199 p->jointnoncodeccapability |= AST_RTP_DTMF;
18200 } else if (!strcasecmp(mode,"inband")) {
18201 ast_clear_flag(&p->flags[0], SIP_DTMF);
18202 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
18203 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
18204 } else
18205 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n",mode);
18206 if (p->rtp)
18207 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
18208 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
18209 if (!p->vad) {
18210 p->vad = ast_dsp_new();
18211 ast_dsp_set_features(p->vad, DSP_FEATURE_DTMF_DETECT);
18213 } else {
18214 if (p->vad) {
18215 ast_dsp_free(p->vad);
18216 p->vad = NULL;
18219 ast_mutex_unlock(&p->lock);
18220 ast_channel_unlock(chan);
18221 return 0;
18224 /*! \brief Add a SIP header to an outbound INVITE */
18225 static int sip_addheader(struct ast_channel *chan, void *data)
18227 int no = 0;
18228 int ok = FALSE;
18229 char varbuf[30];
18230 char *inbuf = (char *) data;
18232 if (ast_strlen_zero(inbuf)) {
18233 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
18234 return 0;
18236 ast_channel_lock(chan);
18238 /* Check for headers */
18239 while (!ok && no <= 50) {
18240 no++;
18241 snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
18243 /* Compare without the leading underscores */
18244 if( (pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL) )
18245 ok = TRUE;
18247 if (ok) {
18248 pbx_builtin_setvar_helper (chan, varbuf, inbuf);
18249 if (sipdebug)
18250 ast_log(LOG_DEBUG,"SIP Header added \"%s\" as %s\n", inbuf, varbuf);
18251 } else {
18252 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
18254 ast_channel_unlock(chan);
18255 return 0;
18258 /*! \brief Transfer call before connect with a 302 redirect
18259 \note Called by the transfer() dialplan application through the sip_transfer()
18260 pbx interface function if the call is in ringing state
18261 \todo Fix this function so that we wait for reply to the REFER and
18262 react to errors, denials or other issues the other end might have.
18264 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
18266 char *cdest;
18267 char *extension, *host, *port;
18268 char tmp[80];
18270 cdest = ast_strdupa(dest);
18272 extension = strsep(&cdest, "@");
18273 host = strsep(&cdest, ":");
18274 port = strsep(&cdest, ":");
18275 if (ast_strlen_zero(extension)) {
18276 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
18277 return 0;
18280 /* we'll issue the redirect message here */
18281 if (!host) {
18282 char *localtmp;
18283 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
18284 if (ast_strlen_zero(tmp)) {
18285 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
18286 return 0;
18288 if ((localtmp = strcasestr(tmp, "sip:")) && (localtmp = strchr(localtmp, '@'))) {
18289 char lhost[80], lport[80];
18290 memset(lhost, 0, sizeof(lhost));
18291 memset(lport, 0, sizeof(lport));
18292 localtmp++;
18293 /* This is okey because lhost and lport are as big as tmp */
18294 sscanf(localtmp, "%[^<>:; ]:%[^<>:; ]", lhost, lport);
18295 if (ast_strlen_zero(lhost)) {
18296 ast_log(LOG_ERROR, "Can't find the host address\n");
18297 return 0;
18299 host = ast_strdupa(lhost);
18300 if (!ast_strlen_zero(lport)) {
18301 port = ast_strdupa(lport);
18306 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
18307 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
18309 sip_scheddestroy(p, SIP_TRANS_TIMEOUT); /* Make sure we stop send this reply. */
18310 sip_alreadygone(p);
18311 return 0;
18314 /*! \brief Return SIP UA's codec (part of the RTP interface) */
18315 static int sip_get_codec(struct ast_channel *chan)
18317 struct sip_pvt *p = chan->tech_pvt;
18318 return p->peercapability ? p->peercapability : p->capability;
18321 /*! \brief Send a poke to all known peers
18322 Space them out 100 ms apart
18323 XXX We might have a cool algorithm for this or use random - any suggestions?
18325 static void sip_poke_all_peers(void)
18327 int ms = 0;
18329 if (!speerobjs) /* No peers, just give up */
18330 return;
18332 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
18333 ASTOBJ_WRLOCK(iterator);
18334 if (!AST_SCHED_DEL(sched, iterator->pokeexpire)) {
18335 struct sip_peer *peer_ptr = iterator;
18336 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
18338 ms += 100;
18339 iterator->pokeexpire = ast_sched_add(sched, ms, sip_poke_peer_s, ASTOBJ_REF(iterator));
18340 if (iterator->pokeexpire == -1) {
18341 struct sip_peer *peer_ptr = iterator;
18342 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
18344 ASTOBJ_UNLOCK(iterator);
18345 } while (0)
18349 /*! \brief Send all known registrations */
18350 static void sip_send_all_registers(void)
18352 int ms;
18353 int regspacing;
18354 if (!regobjs)
18355 return;
18356 regspacing = default_expiry * 1000/regobjs;
18357 if (regspacing > 100)
18358 regspacing = 100;
18359 ms = regspacing;
18360 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
18361 ASTOBJ_WRLOCK(iterator);
18362 AST_SCHED_DEL(sched, iterator->expire);
18363 ms += regspacing;
18364 iterator->expire = ast_sched_add(sched, ms, sip_reregister, iterator);
18365 ASTOBJ_UNLOCK(iterator);
18366 } while (0)
18370 /*! \brief Reload module */
18371 static int sip_do_reload(enum channelreloadreason reason)
18373 reload_config(reason);
18375 /* Prune peers who still are supposed to be deleted */
18376 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
18377 if (option_debug > 3)
18378 ast_log(LOG_DEBUG, "--------------- Done destroying pruned peers\n");
18380 /* Send qualify (OPTIONS) to all peers */
18381 sip_poke_all_peers();
18383 /* Register with all services */
18384 sip_send_all_registers();
18386 if (option_debug > 3)
18387 ast_log(LOG_DEBUG, "--------------- SIP reload done\n");
18389 return 0;
18392 /*! \brief Force reload of module from cli */
18393 static int sip_reload(int fd, int argc, char *argv[])
18395 ast_mutex_lock(&sip_reload_lock);
18396 if (sip_reloading)
18397 ast_verbose("Previous SIP reload not yet done\n");
18398 else {
18399 sip_reloading = TRUE;
18400 if (fd)
18401 sip_reloadreason = CHANNEL_CLI_RELOAD;
18402 else
18403 sip_reloadreason = CHANNEL_MODULE_RELOAD;
18405 ast_mutex_unlock(&sip_reload_lock);
18406 restart_monitor();
18408 return 0;
18411 /*! \brief Part of Asterisk module interface */
18412 static int reload(void)
18414 return sip_reload(0, 0, NULL);
18417 static struct ast_cli_entry cli_sip_debug_deprecated =
18418 { { "sip", "debug", NULL },
18419 sip_do_debug_deprecated, "Enable SIP debugging",
18420 debug_usage };
18422 static struct ast_cli_entry cli_sip_no_debug_deprecated =
18423 { { "sip", "no", "debug", NULL },
18424 sip_no_debug_deprecated, "Disable SIP debugging",
18425 debug_usage };
18427 static struct ast_cli_entry cli_sip[] = {
18428 { { "sip", "show", "channels", NULL },
18429 sip_show_channels, "List active SIP channels",
18430 show_channels_usage },
18432 { { "sip", "show", "domains", NULL },
18433 sip_show_domains, "List our local SIP domains.",
18434 show_domains_usage },
18436 { { "sip", "show", "inuse", NULL },
18437 sip_show_inuse, "List all inuse/limits",
18438 show_inuse_usage },
18440 { { "sip", "show", "objects", NULL },
18441 sip_show_objects, "List all SIP object allocations",
18442 show_objects_usage },
18444 { { "sip", "show", "peers", NULL },
18445 sip_show_peers, "List defined SIP peers",
18446 show_peers_usage },
18448 { { "sip", "show", "registry", NULL },
18449 sip_show_registry, "List SIP registration status",
18450 show_reg_usage },
18452 { { "sip", "show", "settings", NULL },
18453 sip_show_settings, "Show SIP global settings",
18454 show_settings_usage },
18456 { { "sip", "show", "subscriptions", NULL },
18457 sip_show_subscriptions, "List active SIP subscriptions",
18458 show_subscriptions_usage },
18460 { { "sip", "show", "users", NULL },
18461 sip_show_users, "List defined SIP users",
18462 show_users_usage },
18464 { { "sip", "notify", NULL },
18465 sip_notify, "Send a notify packet to a SIP peer",
18466 notify_usage, complete_sipnotify },
18468 { { "sip", "show", "channel", NULL },
18469 sip_show_channel, "Show detailed SIP channel info",
18470 show_channel_usage, complete_sipch },
18472 { { "sip", "show", "history", NULL },
18473 sip_show_history, "Show SIP dialog history",
18474 show_history_usage, complete_sipch },
18476 { { "sip", "show", "peer", NULL },
18477 sip_show_peer, "Show details on specific SIP peer",
18478 show_peer_usage, complete_sip_show_peer },
18480 { { "sip", "show", "user", NULL },
18481 sip_show_user, "Show details on specific SIP user",
18482 show_user_usage, complete_sip_show_user },
18484 { { "sip", "prune", "realtime", NULL },
18485 sip_prune_realtime, "Prune cached Realtime object(s)",
18486 prune_realtime_usage },
18488 { { "sip", "prune", "realtime", "peer", NULL },
18489 sip_prune_realtime, "Prune cached Realtime peer(s)",
18490 prune_realtime_usage, complete_sip_prune_realtime_peer },
18492 { { "sip", "prune", "realtime", "user", NULL },
18493 sip_prune_realtime, "Prune cached Realtime user(s)",
18494 prune_realtime_usage, complete_sip_prune_realtime_user },
18496 { { "sip", "set", "debug", NULL },
18497 sip_do_debug, "Enable SIP debugging",
18498 debug_usage, NULL, &cli_sip_debug_deprecated },
18500 { { "sip", "set", "debug", "ip", NULL },
18501 sip_do_debug, "Enable SIP debugging on IP",
18502 debug_usage },
18504 { { "sip", "set", "debug", "peer", NULL },
18505 sip_do_debug, "Enable SIP debugging on Peername",
18506 debug_usage, complete_sip_debug_peer },
18508 { { "sip", "set", "debug", "off", NULL },
18509 sip_no_debug, "Disable SIP debugging",
18510 no_debug_usage, NULL, &cli_sip_no_debug_deprecated },
18512 { { "sip", "history", NULL },
18513 sip_do_history, "Enable SIP history",
18514 history_usage },
18516 { { "sip", "history", "off", NULL },
18517 sip_no_history, "Disable SIP history",
18518 no_history_usage },
18520 { { "sip", "reload", NULL },
18521 sip_reload, "Reload SIP configuration",
18522 sip_reload_usage },
18525 /*! \brief PBX load module - initialization */
18526 static int load_module(void)
18528 ASTOBJ_CONTAINER_INIT(&userl); /* User object list */
18529 ASTOBJ_CONTAINER_INIT(&peerl); /* Peer object list */
18530 ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list */
18532 if (!(sched = sched_context_create())) {
18533 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
18534 return AST_MODULE_LOAD_FAILURE;
18537 if (!(io = io_context_create())) {
18538 ast_log(LOG_ERROR, "Unable to create I/O context\n");
18539 sched_context_destroy(sched);
18540 return AST_MODULE_LOAD_FAILURE;
18543 sip_reloadreason = CHANNEL_MODULE_LOAD;
18545 if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
18546 return AST_MODULE_LOAD_DECLINE;
18548 /* Make sure we can register our sip channel type */
18549 if (ast_channel_register(&sip_tech)) {
18550 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
18551 io_context_destroy(io);
18552 sched_context_destroy(sched);
18553 return AST_MODULE_LOAD_FAILURE;
18556 /* Register all CLI functions for SIP */
18557 ast_cli_register_multiple(cli_sip, sizeof(cli_sip)/ sizeof(struct ast_cli_entry));
18559 /* Tell the RTP subdriver that we're here */
18560 ast_rtp_proto_register(&sip_rtp);
18562 /* Tell the UDPTL subdriver that we're here */
18563 ast_udptl_proto_register(&sip_udptl);
18565 /* Register dialplan applications */
18566 ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
18567 ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
18569 /* Register dialplan functions */
18570 ast_custom_function_register(&sip_header_function);
18571 ast_custom_function_register(&sippeer_function);
18572 ast_custom_function_register(&sipchaninfo_function);
18573 ast_custom_function_register(&checksipdomain_function);
18575 /* Register manager commands */
18576 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM, manager_sip_show_peers,
18577 "List SIP peers (text format)", mandescr_show_peers);
18578 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM, manager_sip_show_peer,
18579 "Show SIP peer (text format)", mandescr_show_peer);
18581 sip_poke_all_peers();
18582 sip_send_all_registers();
18584 /* And start the monitor for the first time */
18585 restart_monitor();
18587 return AST_MODULE_LOAD_SUCCESS;
18590 /*! \brief PBX unload module API */
18591 static int unload_module(void)
18593 struct sip_pvt *p, *pl;
18595 /* First, take us out of the channel type list */
18596 ast_channel_unregister(&sip_tech);
18598 /* Unregister dial plan functions */
18599 ast_custom_function_unregister(&sipchaninfo_function);
18600 ast_custom_function_unregister(&sippeer_function);
18601 ast_custom_function_unregister(&sip_header_function);
18602 ast_custom_function_unregister(&checksipdomain_function);
18604 /* Unregister dial plan applications */
18605 ast_unregister_application(app_dtmfmode);
18606 ast_unregister_application(app_sipaddheader);
18608 /* Unregister CLI commands */
18609 ast_cli_unregister_multiple(cli_sip, sizeof(cli_sip) / sizeof(struct ast_cli_entry));
18611 /* Disconnect from the RTP subsystem */
18612 ast_rtp_proto_unregister(&sip_rtp);
18614 /* Disconnect from UDPTL */
18615 ast_udptl_proto_unregister(&sip_udptl);
18617 /* Unregister AMI actions */
18618 ast_manager_unregister("SIPpeers");
18619 ast_manager_unregister("SIPshowpeer");
18621 ast_mutex_lock(&iflock);
18622 /* Hangup all interfaces if they have an owner */
18623 for (p = iflist; p ; p = p->next) {
18624 if (p->owner)
18625 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
18627 ast_mutex_unlock(&iflock);
18629 ast_mutex_lock(&monlock);
18630 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
18631 pthread_cancel(monitor_thread);
18632 pthread_kill(monitor_thread, SIGURG);
18633 pthread_join(monitor_thread, NULL);
18635 monitor_thread = AST_PTHREADT_STOP;
18636 ast_mutex_unlock(&monlock);
18638 restartdestroy:
18639 ast_mutex_lock(&iflock);
18640 /* Destroy all the interfaces and free their memory */
18641 p = iflist;
18642 while (p) {
18643 pl = p;
18644 p = p->next;
18645 if (__sip_destroy(pl, TRUE) < 0) {
18646 /* Something is still bridged, let it react to getting a hangup */
18647 iflist = p;
18648 ast_mutex_unlock(&iflock);
18649 usleep(1);
18650 goto restartdestroy;
18653 iflist = NULL;
18654 ast_mutex_unlock(&iflock);
18656 /* Free memory for local network address mask */
18657 ast_free_ha(localaddr);
18659 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
18660 ASTOBJ_CONTAINER_DESTROY(&userl);
18661 ASTOBJ_CONTAINER_DESTROYALL(&peerl, sip_destroy_peer);
18662 ASTOBJ_CONTAINER_DESTROY(&peerl);
18663 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
18664 ASTOBJ_CONTAINER_DESTROY(&regl);
18666 clear_realm_authentication(authl);
18667 clear_sip_domains();
18668 close(sipsock);
18669 sched_context_destroy(sched);
18671 return 0;
18674 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
18675 .load = load_module,
18676 .unload = unload_module,
18677 .reload = reload,