The CDRfix4/5/6 omnibus cdr fixes.
[asterisk-bristuff.git] / channels / chan_sip.c
blob0cafa796b3f2678999c9495c2684fbcc05e25a97
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
19 /*!
20 * \file
21 * \brief Implementation of Session Initiation Protocol
23 * \author Mark Spencer <markster@digium.com>
25 * See Also:
26 * \arg \ref AstCREDITS
28 * Implementation of RFC 3261 - without S/MIME, TCP and TLS support
29 * Configuration file \link Config_sip sip.conf \endlink
32 * \todo SIP over TCP
33 * \todo SIP over TLS
34 * \todo Better support of forking
35 * \todo VIA branch tag transaction checking
36 * \todo Transaction support
38 * \ingroup channel_drivers
40 * \par Overview of the handling of SIP sessions
41 * The SIP channel handles several types of SIP sessions, or dialogs,
42 * not all of them being "telephone calls".
43 * - Incoming calls that will be sent to the PBX core
44 * - Outgoing calls, generated by the PBX
45 * - SIP subscriptions and notifications of states and voicemail messages
46 * - SIP registrations, both inbound and outbound
47 * - SIP peer management (peerpoke, OPTIONS)
48 * - SIP text messages
50 * In the SIP channel, there's a list of active SIP dialogs, which includes
51 * all of these when they are active. "sip show channels" in the CLI will
52 * show most of these, excluding subscriptions which are shown by
53 * "sip show subscriptions"
55 * \par incoming packets
56 * Incoming packets are received in the monitoring thread, then handled by
57 * sipsock_read(). This function parses the packet and matches an existing
58 * dialog or starts a new SIP dialog.
60 * sipsock_read sends the packet to handle_request(), that parses a bit more.
61 * if it's a response to an outbound request, it's sent to handle_response().
62 * If it is a request, handle_request sends it to one of a list of functions
63 * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
64 * sipsock_read locks the ast_channel if it exists (an active call) and
65 * unlocks it after we have processed the SIP message.
67 * A new INVITE is sent to handle_request_invite(), that will end up
68 * starting a new channel in the PBX, the new channel after that executing
69 * in a separate channel thread. This is an incoming "call".
70 * When the call is answered, either by a bridged channel or the PBX itself
71 * the sip_answer() function is called.
73 * The actual media - Video or Audio - is mostly handled by the RTP subsystem
74 * in rtp.c
76 * \par Outbound calls
77 * Outbound calls are set up by the PBX through the sip_request_call()
78 * function. After that, they are activated by sip_call().
80 * \par Hanging up
81 * The PBX issues a hangup on both incoming and outgoing calls through
82 * the sip_hangup() function
84 * \par Deprecated stuff
85 * This is deprecated and will be removed after the 1.4 release
86 * - the SIPUSERAGENT dialplan variable
87 * - the ALERT_INFO dialplan variable
90 /*** MODULEINFO
91 <depend>res_features</depend>
92 ***/
95 #include "asterisk.h"
97 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
99 #include <stdio.h>
100 #include <ctype.h>
101 #include <string.h>
102 #include <unistd.h>
103 #include <sys/socket.h>
104 #include <sys/ioctl.h>
105 #include <net/if.h>
106 #include <errno.h>
107 #include <stdlib.h>
108 #include <fcntl.h>
109 #include <netdb.h>
110 #include <signal.h>
111 #include <sys/signal.h>
112 #include <netinet/in.h>
113 #include <netinet/in_systm.h>
114 #include <arpa/inet.h>
115 #include <netinet/ip.h>
116 #include <regex.h>
118 #include "asterisk/lock.h"
119 #include "asterisk/channel.h"
120 #include "asterisk/config.h"
121 #include "asterisk/logger.h"
122 #include "asterisk/module.h"
123 #include "asterisk/pbx.h"
124 #include "asterisk/options.h"
125 #include "asterisk/sched.h"
126 #include "asterisk/io.h"
127 #include "asterisk/rtp.h"
128 #include "asterisk/udptl.h"
129 #include "asterisk/acl.h"
130 #include "asterisk/manager.h"
131 #include "asterisk/callerid.h"
132 #include "asterisk/cli.h"
133 #include "asterisk/app.h"
134 #include "asterisk/musiconhold.h"
135 #include "asterisk/dsp.h"
136 #include "asterisk/features.h"
137 #include "asterisk/srv.h"
138 #include "asterisk/astdb.h"
139 #include "asterisk/causes.h"
140 #include "asterisk/utils.h"
141 #include "asterisk/file.h"
142 #include "asterisk/astobj.h"
143 #include "asterisk/devicestate.h"
144 #include "asterisk/linkedlists.h"
145 #include "asterisk/stringfields.h"
146 #include "asterisk/monitor.h"
147 #include "asterisk/localtime.h"
148 #include "asterisk/abstract_jb.h"
149 #include "asterisk/compiler.h"
150 #include "asterisk/threadstorage.h"
151 #include "asterisk/translate.h"
153 #ifndef FALSE
154 #define FALSE 0
155 #endif
157 #ifndef TRUE
158 #define TRUE 1
159 #endif
161 #define SIPBUFSIZE 512
163 #define XMIT_ERROR -2
165 #define VIDEO_CODEC_MASK 0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
166 #ifndef IPTOS_MINCOST
167 #define IPTOS_MINCOST 0x02
168 #endif
170 /* #define VOCAL_DATA_HACK */
172 #define DEFAULT_DEFAULT_EXPIRY 120
173 #define DEFAULT_MIN_EXPIRY 60
174 #define DEFAULT_MAX_EXPIRY 3600
175 #define DEFAULT_REGISTRATION_TIMEOUT 20
176 #define DEFAULT_MAX_FORWARDS "70"
178 /* guard limit must be larger than guard secs */
179 /* guard min must be < 1000, and should be >= 250 */
180 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
181 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
182 EXPIRY_GUARD_SECS */
183 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
184 GUARD_PCT turns out to be lower than this, it
185 will use this time instead.
186 This is in milliseconds. */
187 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
188 below EXPIRY_GUARD_LIMIT */
189 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
191 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
192 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
193 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
194 static int expiry = DEFAULT_EXPIRY;
196 #ifndef MAX
197 #define MAX(a,b) ((a) > (b) ? (a) : (b))
198 #endif
200 #define CALLERID_UNKNOWN "Unknown"
202 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
203 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
204 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
206 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
207 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
208 #define SIP_TRANS_TIMEOUT 32000 /*!< SIP request timeout (rfc 3261) 64*T1
209 \todo Use known T1 for timeout (peerpoke)
211 #define DEFAULT_TRANS_TIMEOUT -1 /* Use default SIP transaction timeout */
212 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
214 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
215 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
216 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
218 #define SDP_MAX_RTPMAP_CODECS 32 /*!< Maximum number of codecs allowed in received SDP */
220 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
222 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
223 static struct ast_jb_conf default_jbconf =
225 .flags = 0,
226 .max_size = -1,
227 .resync_threshold = -1,
228 .impl = ""
230 static struct ast_jb_conf global_jbconf;
232 static const char config[] = "sip.conf";
233 static const char notify_config[] = "sip_notify.conf";
235 #define RTP 1
236 #define NO_RTP 0
238 /*! \brief Authorization scheme for call transfers
239 \note Not a bitfield flag, since there are plans for other modes,
240 like "only allow transfers for authenticated devices" */
241 enum transfermodes {
242 TRANSFER_OPENFORALL, /*!< Allow all SIP transfers */
243 TRANSFER_CLOSED, /*!< Allow no SIP transfers */
247 enum sip_result {
248 AST_SUCCESS = 0,
249 AST_FAILURE = -1,
252 /*! \brief States for the INVITE transaction, not the dialog
253 \note this is for the INVITE that sets up the dialog
255 enum invitestates {
256 INV_NONE = 0, /*!< No state at all, maybe not an INVITE dialog */
257 INV_CALLING = 1, /*!< Invite sent, no answer */
258 INV_PROCEEDING = 2, /*!< We got/sent 1xx message */
259 INV_EARLY_MEDIA = 3, /*!< We got 18x message with to-tag back */
260 INV_COMPLETED = 4, /*!< Got final response with error. Wait for ACK, then CONFIRMED */
261 INV_CONFIRMED = 5, /*!< Confirmed response - we've got an ack (Incoming calls only) */
262 INV_TERMINATED = 6, /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done
263 The only way out of this is a BYE from one side */
264 INV_CANCELLED = 7, /*!< Transaction cancelled by client or server in non-terminated state */
267 /* Do _NOT_ make any changes to this enum, or the array following it;
268 if you think you are doing the right thing, you are probably
269 not doing the right thing. If you think there are changes
270 needed, get someone else to review them first _before_
271 submitting a patch. If these two lists do not match properly
272 bad things will happen.
275 enum xmittype {
276 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
277 If it fails, it's critical and will cause a teardown of the session */
278 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
279 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
282 enum parse_register_result {
283 PARSE_REGISTER_FAILED,
284 PARSE_REGISTER_UPDATE,
285 PARSE_REGISTER_QUERY,
288 enum subscriptiontype {
289 NONE = 0,
290 XPIDF_XML,
291 DIALOG_INFO_XML,
292 CPIM_PIDF_XML,
293 PIDF_XML,
294 MWI_NOTIFICATION
297 static const struct cfsubscription_types {
298 enum subscriptiontype type;
299 const char * const event;
300 const char * const mediatype;
301 const char * const text;
302 } subscription_types[] = {
303 { NONE, "-", "unknown", "unknown" },
304 /* RFC 4235: SIP Dialog event package */
305 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
306 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
307 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
308 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
309 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
312 /*! \brief SIP Request methods known by Asterisk */
313 enum sipmethod {
314 SIP_UNKNOWN, /* Unknown response */
315 SIP_RESPONSE, /* Not request, response to outbound request */
316 SIP_REGISTER,
317 SIP_OPTIONS,
318 SIP_NOTIFY,
319 SIP_INVITE,
320 SIP_ACK,
321 SIP_PRACK, /* Not supported at all */
322 SIP_BYE,
323 SIP_REFER,
324 SIP_SUBSCRIBE,
325 SIP_MESSAGE,
326 SIP_UPDATE, /* We can send UPDATE; but not accept it */
327 SIP_INFO,
328 SIP_CANCEL,
329 SIP_PUBLISH, /* Not supported at all */
330 SIP_PING, /* Not supported at all, no standard but still implemented out there */
333 /*! \brief Authentication types - proxy or www authentication
334 \note Endpoints, like Asterisk, should always use WWW authentication to
335 allow multiple authentications in the same call - to the proxy and
336 to the end point.
338 enum sip_auth_type {
339 PROXY_AUTH,
340 WWW_AUTH,
343 /*! \brief Authentication result from check_auth* functions */
344 enum check_auth_result {
345 AUTH_SUCCESSFUL = 0,
346 AUTH_CHALLENGE_SENT = 1,
347 AUTH_SECRET_FAILED = -1,
348 AUTH_USERNAME_MISMATCH = -2,
349 AUTH_NOT_FOUND = -3,
350 AUTH_FAKE_AUTH = -4,
351 AUTH_UNKNOWN_DOMAIN = -5,
352 AUTH_PEER_NOT_DYNAMIC = -6,
353 AUTH_ACL_FAILED = -7,
356 /*! \brief States for outbound registrations (with register= lines in sip.conf */
357 enum sipregistrystate {
358 REG_STATE_UNREGISTERED = 0, /*!< We are not registred */
359 REG_STATE_REGSENT, /*!< Registration request sent */
360 REG_STATE_AUTHSENT, /*!< We have tried to authenticate */
361 REG_STATE_REGISTERED, /*!< Registred and done */
362 REG_STATE_REJECTED, /*!< Registration rejected */
363 REG_STATE_TIMEOUT, /*!< Registration timed out */
364 REG_STATE_NOAUTH, /*!< We have no accepted credentials */
365 REG_STATE_FAILED, /*!< Registration failed after several tries */
368 #define CAN_NOT_CREATE_DIALOG 0
369 #define CAN_CREATE_DIALOG 1
370 #define CAN_CREATE_DIALOG_UNSUPPORTED_METHOD 2
372 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
373 static const struct cfsip_methods {
374 enum sipmethod id;
375 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
376 char * const text;
377 int can_create;
378 } sip_methods[] = {
379 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
380 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
381 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
382 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
383 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
384 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
385 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
386 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
387 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
388 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
389 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
390 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
391 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
392 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
393 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
394 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
395 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
398 /*! Define SIP option tags, used in Require: and Supported: headers
399 We need to be aware of these properties in the phones to use
400 the replace: header. We should not do that without knowing
401 that the other end supports it...
402 This is nothing we can configure, we learn by the dialog
403 Supported: header on the REGISTER (peer) or the INVITE
404 (other devices)
405 We are not using many of these today, but will in the future.
406 This is documented in RFC 3261
408 #define SUPPORTED 1
409 #define NOT_SUPPORTED 0
411 #define SIP_OPT_REPLACES (1 << 0)
412 #define SIP_OPT_100REL (1 << 1)
413 #define SIP_OPT_TIMER (1 << 2)
414 #define SIP_OPT_EARLY_SESSION (1 << 3)
415 #define SIP_OPT_JOIN (1 << 4)
416 #define SIP_OPT_PATH (1 << 5)
417 #define SIP_OPT_PREF (1 << 6)
418 #define SIP_OPT_PRECONDITION (1 << 7)
419 #define SIP_OPT_PRIVACY (1 << 8)
420 #define SIP_OPT_SDP_ANAT (1 << 9)
421 #define SIP_OPT_SEC_AGREE (1 << 10)
422 #define SIP_OPT_EVENTLIST (1 << 11)
423 #define SIP_OPT_GRUU (1 << 12)
424 #define SIP_OPT_TARGET_DIALOG (1 << 13)
425 #define SIP_OPT_NOREFERSUB (1 << 14)
426 #define SIP_OPT_HISTINFO (1 << 15)
427 #define SIP_OPT_RESPRIORITY (1 << 16)
429 /*! \brief List of well-known SIP options. If we get this in a require,
430 we should check the list and answer accordingly. */
431 static const struct cfsip_options {
432 int id; /*!< Bitmap ID */
433 int supported; /*!< Supported by Asterisk ? */
434 char * const text; /*!< Text id, as in standard */
435 } sip_options[] = { /* XXX used in 3 places */
436 /* RFC3891: Replaces: header for transfer */
437 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
438 /* One version of Polycom firmware has the wrong label */
439 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
440 /* RFC3262: PRACK 100% reliability */
441 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
442 /* RFC4028: SIP Session Timers */
443 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
444 /* RFC3959: SIP Early session support */
445 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
446 /* RFC3911: SIP Join header support */
447 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
448 /* RFC3327: Path support */
449 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
450 /* RFC3840: Callee preferences */
451 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
452 /* RFC3312: Precondition support */
453 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
454 /* RFC3323: Privacy with proxies*/
455 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
456 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
457 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
458 /* RFC3329: Security agreement mechanism */
459 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
460 /* SIMPLE events: RFC4662 */
461 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
462 /* GRUU: Globally Routable User Agent URI's */
463 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
464 /* RFC4538: Target-dialog */
465 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
466 /* Disable the REFER subscription, RFC 4488 */
467 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
468 /* ietf-sip-history-info-06.txt */
469 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
470 /* ietf-sip-resource-priority-10.txt */
471 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
475 /*! \brief SIP Methods we support */
476 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
478 /*! \brief SIP Extensions we support */
479 #define SUPPORTED_EXTENSIONS "replaces"
481 /*! \brief Standard SIP port from RFC 3261. DO NOT CHANGE THIS */
482 #define STANDARD_SIP_PORT 5060
483 /* Note: in many SIP headers, absence of a port number implies port 5060,
484 * and this is why we cannot change the above constant.
485 * There is a limited number of places in asterisk where we could,
486 * in principle, use a different "default" port number, but
487 * we do not support this feature at the moment.
490 /* Default values, set and reset in reload_config before reading configuration */
491 /* These are default values in the source. There are other recommended values in the
492 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
493 yet encouraging new behaviour on new installations
495 #define DEFAULT_CONTEXT "default"
496 #define DEFAULT_MOHINTERPRET "default"
497 #define DEFAULT_MOHSUGGEST ""
498 #define DEFAULT_VMEXTEN "asterisk"
499 #define DEFAULT_CALLERID "asterisk"
500 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
501 #define DEFAULT_MWITIME 10
502 #define DEFAULT_ALLOWGUEST TRUE
503 #define DEFAULT_SRVLOOKUP TRUE /*!< Recommended setting is ON */
504 #define DEFAULT_COMPACTHEADERS FALSE
505 #define DEFAULT_TOS_SIP 0 /*!< Call signalling packets should be marked as DSCP CS3, but the default is 0 to be compatible with previous versions. */
506 #define DEFAULT_TOS_AUDIO 0 /*!< Audio packets should be marked as DSCP EF (Expedited Forwarding), but the default is 0 to be compatible with previous versions. */
507 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
508 #define DEFAULT_ALLOW_EXT_DOM TRUE
509 #define DEFAULT_REALM "asterisk"
510 #define DEFAULT_NOTIFYRINGING TRUE
511 #define DEFAULT_PEDANTIC FALSE
512 #define DEFAULT_AUTOCREATEPEER FALSE
513 #define DEFAULT_QUALIFY FALSE
514 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
515 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
516 #ifndef DEFAULT_USERAGENT
517 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
518 #endif
521 /* Default setttings are used as a channel setting and as a default when
522 configuring devices */
523 static char default_context[AST_MAX_CONTEXT];
524 static char default_subscribecontext[AST_MAX_CONTEXT];
525 static char default_language[MAX_LANGUAGE];
526 static char default_callerid[AST_MAX_EXTENSION];
527 static char default_fromdomain[AST_MAX_EXTENSION];
528 static char default_notifymime[AST_MAX_EXTENSION];
529 static int default_qualify; /*!< Default Qualify= setting */
530 static char default_vmexten[AST_MAX_EXTENSION];
531 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
532 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
533 * a bridged channel on hold */
534 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
535 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
537 /* Global settings only apply to the channel */
538 static int global_directrtpsetup; /*!< Enable support for Direct RTP setup (no re-invites) */
539 static int global_limitonpeers; /*!< Match call limit on peers only */
540 static int global_rtautoclear;
541 static int global_notifyringing; /*!< Send notifications on ringing */
542 static int global_notifyhold; /*!< Send notifications on hold */
543 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
544 static int srvlookup; /*!< SRV Lookup on or off. Default is on */
545 static int pedanticsipchecking; /*!< Extra checking ? Default off */
546 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
547 static int global_relaxdtmf; /*!< Relax DTMF */
548 static int global_rtptimeout; /*!< Time out call if no RTP */
549 static int global_rtpholdtimeout;
550 static int global_rtpkeepalive; /*!< Send RTP keepalives */
551 static int global_reg_timeout;
552 static int global_regattempts_max; /*!< Registration attempts before giving up */
553 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
554 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
555 the global setting is in globals_flags[1] */
556 static int global_mwitime; /*!< Time between MWI checks for peers */
557 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
558 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
559 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
560 static int compactheaders; /*!< send compact sip headers */
561 static int recordhistory; /*!< Record SIP history. Off by default */
562 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
563 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
564 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
565 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
566 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
567 static int global_callevents; /*!< Whether we send manager events or not */
568 static int global_t1min; /*!< T1 roundtrip time minimum */
569 static int global_autoframing; /*!< Turn autoframing on or off. */
570 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
572 static int global_matchexterniplocally; /*!< Match externip/externhost setting against localnet setting */
574 /*! \brief Codecs that we support by default: */
575 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
577 /* Object counters */
578 static int suserobjs = 0; /*!< Static users */
579 static int ruserobjs = 0; /*!< Realtime users */
580 static int speerobjs = 0; /*!< Statis peers */
581 static int rpeerobjs = 0; /*!< Realtime peers */
582 static int apeerobjs = 0; /*!< Autocreated peer objects */
583 static int regobjs = 0; /*!< Registry objects */
585 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
587 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
588 AST_MUTEX_DEFINE_STATIC(iflock);
590 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
591 when it's doing something critical. */
592 AST_MUTEX_DEFINE_STATIC(netlock);
594 AST_MUTEX_DEFINE_STATIC(monlock);
596 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
598 /*! \brief This is the thread for the monitor which checks for input on the channels
599 which are not currently in use. */
600 static pthread_t monitor_thread = AST_PTHREADT_NULL;
602 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
603 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
605 static struct sched_context *sched; /*!< The scheduling context */
606 static struct io_context *io; /*!< The IO context */
607 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
609 #define DEC_CALL_LIMIT 0
610 #define INC_CALL_LIMIT 1
611 #define DEC_CALL_RINGING 2
612 #define INC_CALL_RINGING 3
614 /*! \brief sip_request: The data grabbed from the UDP socket */
615 struct sip_request {
616 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
617 char *rlPart2; /*!< The Request URI or Response Status */
618 int len; /*!< Length */
619 int headers; /*!< # of SIP Headers */
620 int method; /*!< Method of this request */
621 int lines; /*!< Body Content */
622 unsigned int flags; /*!< SIP_PKT Flags for this packet */
623 char *header[SIP_MAX_HEADERS];
624 char *line[SIP_MAX_LINES];
625 char data[SIP_MAX_PACKET];
626 unsigned int sdp_start; /*!< the line number where the SDP begins */
627 unsigned int sdp_end; /*!< the line number where the SDP ends */
631 * A sip packet is stored into the data[] buffer, with the header followed
632 * by an empty line and the body of the message.
633 * On outgoing packets, data is accumulated in data[] with len reflecting
634 * the next available byte, headers and lines count the number of lines
635 * in both parts. There are no '\0' in data[0..len-1].
637 * On received packet, the input read from the socket is copied into data[],
638 * len is set and the string is NUL-terminated. Then a parser fills up
639 * the other fields -header[] and line[] to point to the lines of the
640 * message, rlPart1 and rlPart2 parse the first lnie as below:
642 * Requests have in the first line METHOD URI SIP/2.0
643 * rlPart1 = method; rlPart2 = uri;
644 * Responses have in the first line SIP/2.0 code description
645 * rlPart1 = SIP/2.0; rlPart2 = code + description;
649 /*! \brief structure used in transfers */
650 struct sip_dual {
651 struct ast_channel *chan1; /*!< First channel involved */
652 struct ast_channel *chan2; /*!< Second channel involved */
653 struct sip_request req; /*!< Request that caused the transfer (REFER) */
654 int seqno; /*!< Sequence number */
657 struct sip_pkt;
659 /*! \brief Parameters to the transmit_invite function */
660 struct sip_invite_param {
661 const char *distinctive_ring; /*!< Distinctive ring header */
662 int addsipheaders; /*!< Add extra SIP headers */
663 const char *uri_options; /*!< URI options to add to the URI */
664 const char *vxml_url; /*!< VXML url for Cisco phones */
665 char *auth; /*!< Authentication */
666 char *authheader; /*!< Auth header */
667 enum sip_auth_type auth_type; /*!< Authentication type */
668 const char *replaces; /*!< Replaces header for call transfers */
669 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
672 /*! \brief Structure to save routing information for a SIP session */
673 struct sip_route {
674 struct sip_route *next;
675 char hop[0];
678 /*! \brief Modes for SIP domain handling in the PBX */
679 enum domain_mode {
680 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
681 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
684 /*! \brief Domain data structure.
685 \note In the future, we will connect this to a configuration tree specific
686 for this domain
688 struct domain {
689 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
690 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
691 enum domain_mode mode; /*!< How did we find this domain? */
692 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
695 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
698 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
699 struct sip_history {
700 AST_LIST_ENTRY(sip_history) list;
701 char event[0]; /* actually more, depending on needs */
704 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
706 /*! \brief sip_auth: Credentials for authentication to other SIP services */
707 struct sip_auth {
708 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
709 char username[256]; /*!< Username */
710 char secret[256]; /*!< Secret */
711 char md5secret[256]; /*!< MD5Secret */
712 struct sip_auth *next; /*!< Next auth structure in list */
715 /*--- Various flags for the flags field in the pvt structure */
716 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
717 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed by the monitor thread */
718 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
719 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
720 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
721 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
722 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
723 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
724 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
725 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
726 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
727 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
728 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
729 #define SIP_OUTGOING (1 << 13) /*!< Direction of the last transaction in this dialog */
730 #define SIP_FREE_BIT (1 << 14) /*!< ---- */
731 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 15) /*!< Do not hangup at first ast_hangup */
732 #define SIP_DTMF (3 << 16) /*!< DTMF Support: four settings, uses two bits */
733 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DTMF Support: RTP DTMF - "rfc2833" */
734 #define SIP_DTMF_INBAND (1 << 16) /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
735 #define SIP_DTMF_INFO (2 << 16) /*!< DTMF Support: SIP Info messages - "info" */
736 #define SIP_DTMF_AUTO (3 << 16) /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
737 /* NAT settings */
738 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
739 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
740 #define SIP_NAT_RFC3581 (1 << 18) /*!< NAT RFC3581 */
741 #define SIP_NAT_ROUTE (2 << 18) /*!< NAT Only ROUTE */
742 #define SIP_NAT_ALWAYS (3 << 18) /*!< NAT Both ROUTE and RFC3581 */
743 /* re-INVITE related settings */
744 #define SIP_REINVITE (7 << 20) /*!< three bits used */
745 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
746 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< allow media reinvite when new peer is behind NAT */
747 #define SIP_REINVITE_UPDATE (4 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
748 /* "insecure" settings */
749 #define SIP_INSECURE_PORT (1 << 23) /*!< don't require matching port for incoming requests */
750 #define SIP_INSECURE_INVITE (1 << 24) /*!< don't require authentication for incoming INVITEs */
751 /* Sending PROGRESS in-band settings */
752 #define SIP_PROG_INBAND (3 << 25) /*!< three settings, uses two bits */
753 #define SIP_PROG_INBAND_NEVER (0 << 25)
754 #define SIP_PROG_INBAND_NO (1 << 25)
755 #define SIP_PROG_INBAND_YES (2 << 25)
756 #define SIP_NO_HISTORY (1 << 27) /*!< Suppress recording request/response history */
757 #define SIP_CALL_LIMIT (1 << 28) /*!< Call limit enforced for this call */
758 #define SIP_SENDRPID (1 << 29) /*!< Remote Party-ID Support */
759 #define SIP_INC_COUNT (1 << 30) /*!< Did this connection increment the counter of in-use calls? */
760 #define SIP_G726_NONSTANDARD (1 << 31) /*!< Use non-standard packing for G726-32 data */
762 #define SIP_FLAGS_TO_COPY \
763 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
764 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
765 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
767 /*--- a new page of flags (for flags[1] */
768 /* realtime flags */
769 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
770 #define SIP_PAGE2_RTUPDATE (1 << 1)
771 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
772 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
773 #define SIP_PAGE2_RTSAVE_SYSNAME (1 << 5)
774 /* Space for addition of other realtime flags in the future */
775 #define SIP_PAGE2_STATECHANGEQUEUE (1 << 9) /*!< D: Unsent state pending change exists */
776 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 10)
777 #define SIP_PAGE2_DEBUG (3 << 11)
778 #define SIP_PAGE2_DEBUG_CONFIG (1 << 11)
779 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 12)
780 #define SIP_PAGE2_DYNAMIC (1 << 13) /*!< Dynamic Peers register with Asterisk */
781 #define SIP_PAGE2_SELFDESTRUCT (1 << 14) /*!< Automatic peers need to destruct themselves */
782 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15)
783 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< Allow subscriptions from this peer? */
784 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< Allow overlap dialing ? */
785 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< Only issue MWI notification if subscribed to */
786 #define SIP_PAGE2_INC_RINGING (1 << 19) /*!< Did this connection increment the counter of in-use calls? */
787 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< T38 Fax Passthrough Support */
788 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< 20: T38 Fax Passthrough Support */
789 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< 21: T38 Fax Passthrough Support (not implemented) */
790 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< 22: T38 Fax Passthrough Support (not implemented) */
791 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< Call states */
792 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23) /*!< 23: Active hold */
793 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23) /*!< 23: One directional hold */
794 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23) /*!< 23: Inactive hold */
795 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25) /*!< 25: ???? */
796 #define SIP_PAGE2_BUGGY_MWI (1 << 26) /*!< 26: Buggy CISCO MWI fix */
797 #define SIP_PAGE2_OUTGOING_CALL (1 << 27) /*!< 27: Is this an outgoing call? */
798 #define SIP_PAGE2_UDPTL_DESTINATION (1 << 28) /*!< 28: Use source IP of RTP as destination if NAT is enabled */
800 #define SIP_PAGE2_FLAGS_TO_COPY \
801 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
802 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_UDPTL_DESTINATION)
804 /* SIP packet flags */
805 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
806 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
807 #define SIP_PKT_IGNORE (1 << 2) /*!< This is a re-transmit, ignore it */
808 #define SIP_PKT_IGNORE_RESP (1 << 3) /*!< Resp ignore - ??? */
809 #define SIP_PKT_IGNORE_REQ (1 << 4) /*!< Req ignore - ??? */
811 /* T.38 set of flags */
812 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
813 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
814 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
815 /* Rate management */
816 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
817 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
818 /* UDP Error correction */
819 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
820 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
821 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
822 /* T38 Spec version */
823 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
824 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
825 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
826 /* Maximum Fax Rate */
827 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
828 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
829 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
830 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
831 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
832 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
834 /*!< This is default: NO MMR and JBIG trancoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
835 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
837 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
838 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
839 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
841 /*! \brief T38 States for a call */
842 enum t38state {
843 T38_DISABLED = 0, /*!< Not enabled */
844 T38_LOCAL_DIRECT, /*!< Offered from local */
845 T38_LOCAL_REINVITE, /*!< Offered from local - REINVITE */
846 T38_PEER_DIRECT, /*!< Offered from peer */
847 T38_PEER_REINVITE, /*!< Offered from peer - REINVITE */
848 T38_ENABLED /*!< Negotiated (enabled) */
851 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
852 struct t38properties {
853 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
854 int capability; /*!< Our T38 capability */
855 int peercapability; /*!< Peers T38 capability */
856 int jointcapability; /*!< Supported T38 capability at both ends */
857 enum t38state state; /*!< T.38 state */
860 /*! \brief Parameters to know status of transfer */
861 enum referstatus {
862 REFER_IDLE, /*!< No REFER is in progress */
863 REFER_SENT, /*!< Sent REFER to transferee */
864 REFER_RECEIVED, /*!< Received REFER from transferer */
865 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING */
866 REFER_ACCEPTED, /*!< Accepted by transferee */
867 REFER_RINGING, /*!< Target Ringing */
868 REFER_200OK, /*!< Answered by transfer target */
869 REFER_FAILED, /*!< REFER declined - go on */
870 REFER_NOAUTH /*!< We had no auth for REFER */
873 static const struct c_referstatusstring {
874 enum referstatus status;
875 char *text;
876 } referstatusstrings[] = {
877 { REFER_IDLE, "<none>" },
878 { REFER_SENT, "Request sent" },
879 { REFER_RECEIVED, "Request received" },
880 { REFER_ACCEPTED, "Accepted" },
881 { REFER_RINGING, "Target ringing" },
882 { REFER_200OK, "Done" },
883 { REFER_FAILED, "Failed" },
884 { REFER_NOAUTH, "Failed - auth failure" }
887 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed */
888 /* OEJ: Should be moved to string fields */
889 struct sip_refer {
890 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
891 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
892 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
893 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
894 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
895 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
896 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
897 char replaces_callid[SIPBUFSIZE]; /*!< Replace info: callid */
898 char replaces_callid_totag[SIPBUFSIZE/2]; /*!< Replace info: to-tag */
899 char replaces_callid_fromtag[SIPBUFSIZE/2]; /*!< Replace info: from-tag */
900 struct sip_pvt *refer_call; /*!< Call we are referring */
901 int attendedtransfer; /*!< Attended or blind transfer? */
902 int localtransfer; /*!< Transfer to local domain? */
903 enum referstatus status; /*!< REFER status */
906 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
907 static struct sip_pvt {
908 ast_mutex_t lock; /*!< Dialog private lock */
909 int method; /*!< SIP method that opened this dialog */
910 enum invitestates invitestate; /*!< The state of the INVITE transaction only */
911 AST_DECLARE_STRING_FIELDS(
912 AST_STRING_FIELD(callid); /*!< Global CallID */
913 AST_STRING_FIELD(randdata); /*!< Random data */
914 AST_STRING_FIELD(accountcode); /*!< Account code */
915 AST_STRING_FIELD(realm); /*!< Authorization realm */
916 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
917 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
918 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
919 AST_STRING_FIELD(domain); /*!< Authorization domain */
920 AST_STRING_FIELD(from); /*!< The From: header */
921 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
922 AST_STRING_FIELD(exten); /*!< Extension where to start */
923 AST_STRING_FIELD(context); /*!< Context for this call */
924 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
925 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
926 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
927 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
928 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
929 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
930 AST_STRING_FIELD(language); /*!< Default language for this call */
931 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
932 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
933 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
934 AST_STRING_FIELD(theirtag); /*!< Their tag */
935 AST_STRING_FIELD(username); /*!< [user] name */
936 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
937 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
938 AST_STRING_FIELD(uri); /*!< Original requested URI */
939 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
940 AST_STRING_FIELD(peersecret); /*!< Password */
941 AST_STRING_FIELD(peermd5secret);
942 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
943 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
944 AST_STRING_FIELD(via); /*!< Via: header */
945 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
946 AST_STRING_FIELD(our_contact); /*!< Our contact header */
947 AST_STRING_FIELD(rpid); /*!< Our RPID header */
948 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
950 unsigned int ocseq; /*!< Current outgoing seqno */
951 unsigned int icseq; /*!< Current incoming seqno */
952 ast_group_t callgroup; /*!< Call group */
953 ast_group_t pickupgroup; /*!< Pickup group */
954 int lastinvite; /*!< Last Cseq of invite */
955 int lastnoninvite; /*!< Last Cseq of non-invite */
956 struct ast_flags flags[2]; /*!< SIP_ flags */
957 int timer_t1; /*!< SIP timer T1, ms rtt */
958 unsigned int sipoptions; /*!< Supported SIP options on the other end */
959 struct ast_codec_pref prefs; /*!< codec prefs */
960 int capability; /*!< Special capability (codec) */
961 int jointcapability; /*!< Supported capability at both ends (codecs) */
962 int peercapability; /*!< Supported peer capability */
963 int prefcodec; /*!< Preferred codec (outbound only) */
964 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
965 int jointnoncodeccapability; /*!< Joint Non codec capability */
966 int redircodecs; /*!< Redirect codecs */
967 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
968 struct t38properties t38; /*!< T38 settings */
969 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
970 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
971 int callingpres; /*!< Calling presentation */
972 int authtries; /*!< Times we've tried to authenticate */
973 int expiry; /*!< How long we take to expire */
974 long branch; /*!< The branch identifier of this session */
975 char tag[11]; /*!< Our tag for this session */
976 int sessionid; /*!< SDP Session ID */
977 int sessionversion; /*!< SDP Session Version */
978 struct sockaddr_in sa; /*!< Our peer */
979 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
980 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
981 time_t lastrtprx; /*!< Last RTP received */
982 time_t lastrtptx; /*!< Last RTP sent */
983 int rtptimeout; /*!< RTP timeout time */
984 struct sockaddr_in recv; /*!< Received as */
985 struct in_addr ourip; /*!< Our IP */
986 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
987 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
988 int route_persistant; /*!< Is this the "real" route? */
989 struct sip_auth *peerauth; /*!< Realm authentication */
990 int noncecount; /*!< Nonce-count */
991 char lastmsg[256]; /*!< Last Message sent/received */
992 int amaflags; /*!< AMA Flags */
993 int pendinginvite; /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
994 struct sip_request initreq; /*!< Request that opened the latest transaction
995 within this SIP dialog */
997 int maxtime; /*!< Max time for first response */
998 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
999 int waitid; /*!< Wait ID for scheduler after 491 or other delays */
1000 int autokillid; /*!< Auto-kill ID (scheduler) */
1001 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
1002 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
1003 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
1004 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
1005 int laststate; /*!< SUBSCRIBE: Last known extension state */
1006 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
1008 struct ast_dsp *vad; /*!< Voice Activation Detection dsp */
1010 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
1011 Used in peerpoke, mwi subscriptions */
1012 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
1013 struct ast_rtp *rtp; /*!< RTP Session */
1014 struct ast_rtp *vrtp; /*!< Video RTP session */
1015 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
1016 struct sip_history_head *history; /*!< History of this SIP dialog */
1017 size_t history_entries; /*!< Number of entires in the history */
1018 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1019 struct sip_pvt *next; /*!< Next dialog in chain */
1020 struct sip_invite_param *options; /*!< Options for INVITE */
1021 int autoframing;
1022 } *iflist = NULL;
1024 /*! Max entires in the history list for a sip_pvt */
1025 #define MAX_HISTORY_ENTRIES 50
1027 #define FLAG_RESPONSE (1 << 0)
1028 #define FLAG_FATAL (1 << 1)
1030 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */
1031 struct sip_pkt {
1032 struct sip_pkt *next; /*!< Next packet in linked list */
1033 int retrans; /*!< Retransmission number */
1034 int method; /*!< SIP method for this packet */
1035 int seqno; /*!< Sequence number */
1036 unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */
1037 struct sip_pvt *owner; /*!< Owner AST call */
1038 int retransid; /*!< Retransmission ID */
1039 int timer_a; /*!< SIP timer A, retransmission timer */
1040 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
1041 int packetlen; /*!< Length of packet */
1042 char data[0];
1045 /*! \brief Structure for SIP user data. User's place calls to us */
1046 struct sip_user {
1047 /* Users who can access various contexts */
1048 ASTOBJ_COMPONENTS(struct sip_user);
1049 char secret[80]; /*!< Password */
1050 char md5secret[80]; /*!< Password in md5 */
1051 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1052 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
1053 char cid_num[80]; /*!< Caller ID num */
1054 char cid_name[80]; /*!< Caller ID name */
1055 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
1056 char language[MAX_LANGUAGE]; /*!< Default language for this user */
1057 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1058 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1059 char useragent[256]; /*!< User agent in SIP request */
1060 struct ast_codec_pref prefs; /*!< codec prefs */
1061 ast_group_t callgroup; /*!< Call group */
1062 ast_group_t pickupgroup; /*!< Pickup Group */
1063 unsigned int sipoptions; /*!< Supported SIP options */
1064 struct ast_flags flags[2]; /*!< SIP_ flags */
1065 int amaflags; /*!< AMA flags for billing */
1066 int callingpres; /*!< Calling id presentation */
1067 int capability; /*!< Codec capability */
1068 int inUse; /*!< Number of calls in use */
1069 int call_limit; /*!< Limit of concurrent calls */
1070 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1071 struct ast_ha *ha; /*!< ACL setting */
1072 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1073 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1074 int autoframing;
1077 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1078 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1079 struct sip_peer {
1080 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
1081 /*!< peer->name is the unique name of this object */
1082 char secret[80]; /*!< Password */
1083 char md5secret[80]; /*!< Password in MD5 */
1084 struct sip_auth *auth; /*!< Realm authentication list */
1085 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1086 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1087 char username[80]; /*!< Temporary username until registration */
1088 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1089 int amaflags; /*!< AMA Flags (for billing) */
1090 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1091 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1092 char fromuser[80]; /*!< From: user when calling this peer */
1093 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1094 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1095 char cid_num[80]; /*!< Caller ID num */
1096 char cid_name[80]; /*!< Caller ID name */
1097 int callingpres; /*!< Calling id presentation */
1098 int inUse; /*!< Number of calls in use */
1099 int inRinging; /*!< Number of calls ringing */
1100 int onHold; /*!< Peer has someone on hold */
1101 int call_limit; /*!< Limit of concurrent calls */
1102 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1103 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1104 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
1105 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1106 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1107 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1108 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1109 struct ast_codec_pref prefs; /*!< codec prefs */
1110 int lastmsgssent;
1111 time_t lastmsgcheck; /*!< Last time we checked for MWI */
1112 unsigned int sipoptions; /*!< Supported SIP options */
1113 struct ast_flags flags[2]; /*!< SIP_ flags */
1114 int expire; /*!< When to expire this peer registration */
1115 int capability; /*!< Codec capability */
1116 int rtptimeout; /*!< RTP timeout */
1117 int rtpholdtimeout; /*!< RTP Hold Timeout */
1118 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1119 ast_group_t callgroup; /*!< Call group */
1120 ast_group_t pickupgroup; /*!< Pickup group */
1121 struct sockaddr_in addr; /*!< IP address of peer */
1122 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1124 /* Qualification */
1125 struct sip_pvt *call; /*!< Call pointer */
1126 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1127 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1128 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1129 struct timeval ps; /*!< Ping send time */
1131 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1132 struct ast_ha *ha; /*!< Access control list */
1133 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1134 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1135 int lastmsg;
1136 int autoframing;
1141 /*! \brief Registrations with other SIP proxies */
1142 struct sip_registry {
1143 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1144 AST_DECLARE_STRING_FIELDS(
1145 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1146 AST_STRING_FIELD(realm); /*!< Authorization realm */
1147 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1148 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1149 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1150 AST_STRING_FIELD(domain); /*!< Authorization domain */
1151 AST_STRING_FIELD(username); /*!< Who we are registering as */
1152 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1153 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1154 AST_STRING_FIELD(secret); /*!< Password in clear text */
1155 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1156 AST_STRING_FIELD(contact); /*!< Contact extension */
1157 AST_STRING_FIELD(random);
1159 int portno; /*!< Optional port override */
1160 int expire; /*!< Sched ID of expiration */
1161 int regattempts; /*!< Number of attempts (since the last success) */
1162 int timeout; /*!< sched id of sip_reg_timeout */
1163 int refresh; /*!< How often to refresh */
1164 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1165 enum sipregistrystate regstate; /*!< Registration state (see above) */
1166 time_t regtime; /*!< Last succesful registration time */
1167 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1168 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1169 struct sockaddr_in us; /*!< Who the server thinks we are */
1170 int noncecount; /*!< Nonce-count */
1171 char lastmsg[256]; /*!< Last Message sent/received */
1174 /* --- Linked lists of various objects --------*/
1176 /*! \brief The user list: Users and friends */
1177 static struct ast_user_list {
1178 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1179 } userl;
1181 /*! \brief The peer list: Peers and Friends */
1182 static struct ast_peer_list {
1183 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1184 } peerl;
1186 /*! \brief The register list: Other SIP proxys we register with and place calls to */
1187 static struct ast_register_list {
1188 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1189 int recheck;
1190 } regl;
1192 static void temp_pvt_cleanup(void *);
1194 /*! \brief A per-thread temporary pvt structure */
1195 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1197 #ifdef LOW_MEMORY
1198 static void ts_ast_rtp_destroy(void *);
1200 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, ts_audio_rtp_init, ts_ast_rtp_destroy);
1201 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, ts_video_rtp_init, ts_ast_rtp_destroy);
1202 #endif
1204 /*! \todo Move the sip_auth list to AST_LIST */
1205 static struct sip_auth *authl = NULL; /*!< Authentication list for realm authentication */
1208 /* --- Sockets and networking --------------*/
1209 static int sipsock = -1; /*!< Main socket for SIP network communication */
1210 static struct sockaddr_in bindaddr = { 0, }; /*!< The address we bind to */
1211 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1212 static char externhost[MAXHOSTNAMELEN]; /*!< External host name (possibly with dynamic DNS and DHCP */
1213 static time_t externexpire = 0; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1214 static int externrefresh = 10;
1215 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1216 static struct in_addr __ourip;
1217 static struct sockaddr_in outboundproxyip;
1218 static int ourport;
1219 static struct sockaddr_in debugaddr;
1221 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1223 /*---------------------------- Forward declarations of functions in chan_sip.c */
1224 /*! \note This is added to help splitting up chan_sip.c into several files
1225 in coming releases */
1227 /*--- PBX interface functions */
1228 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1229 static int sip_devicestate(void *data);
1230 static int sip_sendtext(struct ast_channel *ast, const char *text);
1231 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1232 static int sip_hangup(struct ast_channel *ast);
1233 static int sip_answer(struct ast_channel *ast);
1234 static struct ast_frame *sip_read(struct ast_channel *ast);
1235 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1236 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1237 static int sip_transfer(struct ast_channel *ast, const char *dest);
1238 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1239 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1240 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1242 /*--- Transmitting responses and requests */
1243 static int sipsock_read(int *id, int fd, short events, void *ignore);
1244 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
1245 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
1246 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1247 static int retrans_pkt(const void *data);
1248 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
1249 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);
1250 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1251 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1252 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1253 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1254 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1255 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);
1256 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1257 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1258 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1259 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1260 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1261 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
1262 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1263 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1264 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1265 static int transmit_refer(struct sip_pvt *p, const char *dest);
1266 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1267 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1268 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1269 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1270 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1271 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1272 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1273 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1274 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1275 static int does_peer_need_mwi(struct sip_peer *peer);
1277 /*--- Dialog management */
1278 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1279 int useglobal_nat, const int intended_method);
1280 static int __sip_autodestruct(const void *data);
1281 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1282 static int sip_cancel_destroy(struct sip_pvt *p);
1283 static void sip_destroy(struct sip_pvt *p);
1284 static int __sip_destroy(struct sip_pvt *p, int lockowner);
1285 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1286 static void __sip_pretend_ack(struct sip_pvt *p);
1287 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1288 static int auto_congest(const void *nothing);
1289 static int update_call_counter(struct sip_pvt *fup, int event);
1290 static int hangup_sip2cause(int cause);
1291 static const char *hangup_cause2sip(int cause);
1292 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1293 static void free_old_route(struct sip_route *route);
1294 static void list_route(struct sip_route *route);
1295 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1296 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1297 struct sip_request *req, char *uri);
1298 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1299 static void check_pendings(struct sip_pvt *p);
1300 static void *sip_park_thread(void *stuff);
1301 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1302 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1304 /*--- Codec handling / SDP */
1305 static void try_suggested_sip_codec(struct sip_pvt *p);
1306 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1307 static const char *get_sdp(struct sip_request *req, const char *name);
1308 static int find_sdp(struct sip_request *req);
1309 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
1310 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1311 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1312 int debug, int *min_packet_size);
1313 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1314 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1315 int debug);
1316 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p);
1317 static void stop_media_flows(struct sip_pvt *p);
1319 /*--- Authentication stuff */
1320 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1321 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1322 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1323 const char *secret, const char *md5secret, int sipmethod,
1324 char *uri, enum xmittype reliable, int ignore);
1325 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1326 int sipmethod, char *uri, enum xmittype reliable,
1327 struct sockaddr_in *sin, struct sip_peer **authpeer);
1328 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1330 /*--- Domain handling */
1331 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1332 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1333 static void clear_sip_domains(void);
1335 /*--- SIP realm authentication */
1336 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
1337 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1338 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1340 /*--- Misc functions */
1341 static int sip_do_reload(enum channelreloadreason reason);
1342 static int reload_config(enum channelreloadreason reason);
1343 static int expire_register(const void *data);
1344 static void *do_monitor(void *data);
1345 static int restart_monitor(void);
1346 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1347 static int sip_addrcmp(char *name, struct sockaddr_in *sin); /* Support for peer matching */
1348 static int sip_refer_allocate(struct sip_pvt *p);
1349 static void ast_quiet_chan(struct ast_channel *chan);
1350 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1352 /*--- Device monitoring and Device/extension state handling */
1353 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1354 static int sip_devicestate(void *data);
1355 static int sip_poke_noanswer(const void *data);
1356 static int sip_poke_peer(struct sip_peer *peer);
1357 static void sip_poke_all_peers(void);
1358 static void sip_peer_hold(struct sip_pvt *p, int hold);
1360 /*--- Applications, functions, CLI and manager command helpers */
1361 static const char *sip_nat_mode(const struct sip_pvt *p);
1362 static int sip_show_inuse(int fd, int argc, char *argv[]);
1363 static char *transfermode2str(enum transfermodes mode) attribute_const;
1364 static char *nat2str(int nat) attribute_const;
1365 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1366 static int sip_show_users(int fd, int argc, char *argv[]);
1367 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1368 static int sip_show_peers(int fd, int argc, char *argv[]);
1369 static int sip_show_objects(int fd, int argc, char *argv[]);
1370 static void print_group(int fd, ast_group_t group, int crlf);
1371 static const char *dtmfmode2str(int mode) attribute_const;
1372 static const char *insecure2str(int port, int invite) attribute_const;
1373 static void cleanup_stale_contexts(char *new, char *old);
1374 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1375 static const char *domain_mode_to_text(const enum domain_mode mode);
1376 static int sip_show_domains(int fd, int argc, char *argv[]);
1377 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1378 static int sip_show_peer(int fd, int argc, char *argv[]);
1379 static int sip_show_user(int fd, int argc, char *argv[]);
1380 static int sip_show_registry(int fd, int argc, char *argv[]);
1381 static int sip_show_settings(int fd, int argc, char *argv[]);
1382 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1383 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1384 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1385 static int sip_show_channels(int fd, int argc, char *argv[]);
1386 static int sip_show_subscriptions(int fd, int argc, char *argv[]);
1387 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1388 static char *complete_sipch(const char *line, const char *word, int pos, int state);
1389 static char *complete_sip_peer(const char *word, int state, int flags2);
1390 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1391 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state);
1392 static char *complete_sip_user(const char *word, int state, int flags2);
1393 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
1394 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1395 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state);
1396 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state);
1397 static int sip_show_channel(int fd, int argc, char *argv[]);
1398 static int sip_show_history(int fd, int argc, char *argv[]);
1399 static int sip_do_debug_ip(int fd, int argc, char *argv[]);
1400 static int sip_do_debug_peer(int fd, int argc, char *argv[]);
1401 static int sip_do_debug(int fd, int argc, char *argv[]);
1402 static int sip_no_debug(int fd, int argc, char *argv[]);
1403 static int sip_notify(int fd, int argc, char *argv[]);
1404 static int sip_do_history(int fd, int argc, char *argv[]);
1405 static int sip_no_history(int fd, int argc, char *argv[]);
1406 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
1407 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1408 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1409 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1410 static int sip_dtmfmode(struct ast_channel *chan, void *data);
1411 static int sip_addheader(struct ast_channel *chan, void *data);
1412 static int sip_do_reload(enum channelreloadreason reason);
1413 static int sip_reload(int fd, int argc, char *argv[]);
1414 static int acf_channel_read(struct ast_channel *chan, char *funcname, char *preparse, char *buf, size_t buflen);
1416 /*--- Debugging
1417 Functions for enabling debug per IP or fully, or enabling history logging for
1418 a SIP dialog
1420 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1421 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1422 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1423 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1424 static void sip_dump_history(struct sip_pvt *dialog);
1426 /*--- Device object handling */
1427 static struct sip_peer *temp_peer(const char *name);
1428 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1429 static struct sip_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1430 static int update_call_counter(struct sip_pvt *fup, int event);
1431 static void sip_destroy_peer(struct sip_peer *peer);
1432 static void sip_destroy_user(struct sip_user *user);
1433 static int sip_poke_peer(struct sip_peer *peer);
1434 static int sip_poke_peer_s(const void *data);
1435 static void set_peer_defaults(struct sip_peer *peer);
1436 static struct sip_peer *temp_peer(const char *name);
1437 static void register_peer_exten(struct sip_peer *peer, int onoff);
1438 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
1439 static struct sip_user *find_user(const char *name, int realtime);
1440 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1441 static int expire_register(const void *data);
1442 static void reg_source_db(struct sip_peer *peer);
1443 static void destroy_association(struct sip_peer *peer);
1444 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1446 /* Realtime device support */
1447 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
1448 static struct sip_user *realtime_user(const char *username);
1449 static void update_peer(struct sip_peer *p, int expiry);
1450 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
1451 static int sip_prune_realtime(int fd, int argc, char *argv[]);
1453 /*--- Internal UA client handling (outbound registrations) */
1454 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
1455 static void sip_registry_destroy(struct sip_registry *reg);
1456 static int sip_register(char *value, int lineno);
1457 static char *regstate2str(enum sipregistrystate regstate) attribute_const;
1458 static int sip_reregister(const void *data);
1459 static int __sip_do_register(struct sip_registry *r);
1460 static int sip_reg_timeout(const void *data);
1461 static void sip_send_all_registers(void);
1463 /*--- Parsing SIP requests and responses */
1464 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1465 static int determine_firstline_parts(struct sip_request *req);
1466 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1467 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1468 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1469 static int find_sip_method(const char *msg);
1470 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1471 static int parse_request(struct sip_request *req);
1472 static const char *get_header(const struct sip_request *req, const char *name);
1473 static char *referstatus2str(enum referstatus rstatus) attribute_pure;
1474 static int method_match(enum sipmethod id, const char *name);
1475 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1476 static char *get_in_brackets(char *tmp);
1477 static const char *find_alias(const char *name, const char *_default);
1478 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1479 static int lws2sws(char *msgbuf, int len);
1480 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1481 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1482 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1483 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1484 static int set_address_from_contact(struct sip_pvt *pvt);
1485 static void check_via(struct sip_pvt *p, const struct sip_request *req);
1486 static char *get_calleridname(const char *input, char *output, size_t outputsize);
1487 static int get_rpid_num(const char *input, char *output, int maxlen);
1488 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
1489 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1490 static int get_msg_text(char *buf, int len, struct sip_request *req);
1491 static void free_old_route(struct sip_route *route);
1492 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1494 /*--- Constructing requests and responses */
1495 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1496 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1497 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1498 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1499 static int init_resp(struct sip_request *resp, const char *msg);
1500 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1501 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1502 static void build_via(struct sip_pvt *p);
1503 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1504 static int create_addr(struct sip_pvt *dialog, const char *opeer);
1505 static char *generate_random_string(char *buf, size_t size);
1506 static void build_callid_pvt(struct sip_pvt *pvt);
1507 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1508 static void make_our_tag(char *tagbuf, size_t len);
1509 static int add_header(struct sip_request *req, const char *var, const char *value);
1510 static int add_header_contentLength(struct sip_request *req, int len);
1511 static int add_line(struct sip_request *req, const char *line);
1512 static int add_text(struct sip_request *req, const char *text);
1513 static int add_digit(struct sip_request *req, char digit, unsigned int duration);
1514 static int add_vidupdate(struct sip_request *req);
1515 static void add_route(struct sip_request *req, struct sip_route *route);
1516 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1517 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1518 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1519 static void set_destination(struct sip_pvt *p, char *uri);
1520 static void append_date(struct sip_request *req);
1521 static void build_contact(struct sip_pvt *p);
1522 static void build_rpid(struct sip_pvt *p);
1524 /*------Request handling functions */
1525 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1526 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);
1527 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock);
1528 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1529 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1530 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1531 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1532 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1533 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1534 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1535 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1536 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1537 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
1539 /*------Response handling functions */
1540 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1541 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1542 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
1543 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
1545 /*----- RTP interface functions */
1546 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
1547 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1548 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1549 static int sip_get_codec(struct ast_channel *chan);
1550 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
1552 /*------ T38 Support --------- */
1553 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite); /*!< T38 negotiation helper function */
1554 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1555 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p);
1556 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1557 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1559 /*! \brief Definition of this channel for PBX channel registration */
1560 static const struct ast_channel_tech sip_tech = {
1561 .type = "SIP",
1562 .description = "Session Initiation Protocol (SIP)",
1563 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1564 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1565 .requester = sip_request_call,
1566 .devicestate = sip_devicestate,
1567 .call = sip_call,
1568 .hangup = sip_hangup,
1569 .answer = sip_answer,
1570 .read = sip_read,
1571 .write = sip_write,
1572 .write_video = sip_write,
1573 .indicate = sip_indicate,
1574 .transfer = sip_transfer,
1575 .fixup = sip_fixup,
1576 .send_digit_begin = sip_senddigit_begin,
1577 .send_digit_end = sip_senddigit_end,
1578 .bridge = ast_rtp_bridge,
1579 .send_text = sip_sendtext,
1580 .func_channel_read = acf_channel_read,
1583 /*! \brief This version of the sip channel tech has no send_digit_begin
1584 * callback. This is for use with channels using SIP INFO DTMF so that
1585 * the core knows that the channel doesn't want DTMF BEGIN frames. */
1586 static const struct ast_channel_tech sip_tech_info = {
1587 .type = "SIP",
1588 .description = "Session Initiation Protocol (SIP)",
1589 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1590 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1591 .requester = sip_request_call,
1592 .devicestate = sip_devicestate,
1593 .call = sip_call,
1594 .hangup = sip_hangup,
1595 .answer = sip_answer,
1596 .read = sip_read,
1597 .write = sip_write,
1598 .write_video = sip_write,
1599 .indicate = sip_indicate,
1600 .transfer = sip_transfer,
1601 .fixup = sip_fixup,
1602 .send_digit_end = sip_senddigit_end,
1603 .bridge = ast_rtp_bridge,
1604 .send_text = sip_sendtext,
1605 .func_channel_read = acf_channel_read,
1608 /**--- some list management macros. **/
1610 #define UNLINK(element, head, prev) do { \
1611 if (prev) \
1612 (prev)->next = (element)->next; \
1613 else \
1614 (head) = (element)->next; \
1615 } while (0)
1617 /*! \brief Interface structure with callbacks used to connect to RTP module */
1618 static struct ast_rtp_protocol sip_rtp = {
1619 type: "SIP",
1620 get_rtp_info: sip_get_rtp_peer,
1621 get_vrtp_info: sip_get_vrtp_peer,
1622 set_rtp_peer: sip_set_rtp_peer,
1623 get_codec: sip_get_codec,
1626 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1627 static struct ast_udptl_protocol sip_udptl = {
1628 type: "SIP",
1629 get_udptl_info: sip_get_udptl_peer,
1630 set_udptl_peer: sip_set_udptl_peer,
1633 /*! \brief Convert transfer status to string */
1634 static char *referstatus2str(enum referstatus rstatus)
1636 int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
1637 int x;
1639 for (x = 0; x < i; x++) {
1640 if (referstatusstrings[x].status == rstatus)
1641 return (char *) referstatusstrings[x].text;
1643 return "";
1646 /*! \brief Initialize the initital request packet in the pvt structure.
1647 This packet is used for creating replies and future requests in
1648 a dialog */
1649 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
1651 if (p->initreq.headers && option_debug) {
1652 ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
1654 /* Use this as the basis */
1655 copy_request(&p->initreq, req);
1656 parse_request(&p->initreq);
1657 if (ast_test_flag(req, SIP_PKT_DEBUG))
1658 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
1661 static void sip_alreadygone(struct sip_pvt *dialog)
1663 if (option_debug > 2)
1664 ast_log(LOG_DEBUG, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
1665 ast_set_flag(&dialog->flags[0], SIP_ALREADYGONE);
1669 /*! \brief returns true if 'name' (with optional trailing whitespace)
1670 * matches the sip method 'id'.
1671 * Strictly speaking, SIP methods are case SENSITIVE, but we do
1672 * a case-insensitive comparison to be more tolerant.
1673 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1675 static int method_match(enum sipmethod id, const char *name)
1677 int len = strlen(sip_methods[id].text);
1678 int l_name = name ? strlen(name) : 0;
1679 /* true if the string is long enough, and ends with whitespace, and matches */
1680 return (l_name >= len && name[len] < 33 &&
1681 !strncasecmp(sip_methods[id].text, name, len));
1684 /*! \brief find_sip_method: Find SIP method from header */
1685 static int find_sip_method(const char *msg)
1687 int i, res = 0;
1689 if (ast_strlen_zero(msg))
1690 return 0;
1691 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
1692 if (method_match(i, msg))
1693 res = sip_methods[i].id;
1695 return res;
1698 /*! \brief Parse supported header in incoming packet */
1699 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
1701 char *next, *sep;
1702 char *temp;
1703 unsigned int profile = 0;
1704 int i, found;
1706 if (ast_strlen_zero(supported) )
1707 return 0;
1708 temp = ast_strdupa(supported);
1710 if (option_debug > 2 && sipdebug)
1711 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1713 for (next = temp; next; next = sep) {
1714 found = FALSE;
1715 if ( (sep = strchr(next, ',')) != NULL)
1716 *sep++ = '\0';
1717 next = ast_skip_blanks(next);
1718 if (option_debug > 2 && sipdebug)
1719 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1720 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
1721 if (!strcasecmp(next, sip_options[i].text)) {
1722 profile |= sip_options[i].id;
1723 found = TRUE;
1724 if (option_debug > 2 && sipdebug)
1725 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1726 break;
1729 if (!found && option_debug > 2 && sipdebug) {
1730 if (!strncasecmp(next, "x-", 2))
1731 ast_log(LOG_DEBUG, "Found private SIP option, not supported: %s\n", next);
1732 else
1733 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1737 if (pvt)
1738 pvt->sipoptions = profile;
1739 return profile;
1742 /*! \brief See if we pass debug IP filter */
1743 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
1745 if (!sipdebug)
1746 return 0;
1747 if (debugaddr.sin_addr.s_addr) {
1748 if (((ntohs(debugaddr.sin_port) != 0)
1749 && (debugaddr.sin_port != addr->sin_port))
1750 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1751 return 0;
1753 return 1;
1756 /*! \brief The real destination address for a write */
1757 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
1759 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
1762 /*! \brief Display SIP nat mode */
1763 static const char *sip_nat_mode(const struct sip_pvt *p)
1765 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
1768 /*! \brief Test PVT for debugging output */
1769 static inline int sip_debug_test_pvt(struct sip_pvt *p)
1771 if (!sipdebug)
1772 return 0;
1773 return sip_debug_test_addr(sip_real_dst(p));
1776 /*! \brief Transmit SIP message */
1777 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1779 int res;
1780 const struct sockaddr_in *dst = sip_real_dst(p);
1781 res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
1783 if (res == -1) {
1784 switch (errno) {
1785 case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
1786 case EHOSTUNREACH: /* Host can't be reached */
1787 case ENETDOWN: /* Inteface down */
1788 case ENETUNREACH: /* Network failure */
1789 case ECONNREFUSED: /* ICMP port unreachable */
1790 res = XMIT_ERROR; /* Don't bother with trying to transmit again */
1793 if (res != len)
1794 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));
1795 return res;
1799 /*! \brief Build a Via header for a request */
1800 static void build_via(struct sip_pvt *p)
1802 /* Work around buggy UNIDEN UIP200 firmware */
1803 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1805 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1806 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1807 ast_inet_ntoa(p->ourip), ourport, p->branch, rport);
1810 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1812 * Using the localaddr structure built up with localnet statements in sip.conf
1813 * apply it to their address to see if we need to substitute our
1814 * externip or can get away with our internal bindaddr
1816 static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1818 struct sockaddr_in theirs, ours;
1820 /* Get our local information */
1821 ast_ouraddrfor(them, us);
1822 theirs.sin_addr = *them;
1823 ours.sin_addr = *us;
1825 if (localaddr && externip.sin_addr.s_addr &&
1826 (ast_apply_ha(localaddr, &theirs)) &&
1827 (!global_matchexterniplocally || !ast_apply_ha(localaddr, &ours))) {
1828 if (externexpire && time(NULL) >= externexpire) {
1829 struct ast_hostent ahp;
1830 struct hostent *hp;
1832 externexpire = time(NULL) + externrefresh;
1833 if ((hp = ast_gethostbyname(externhost, &ahp))) {
1834 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1835 } else
1836 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1838 *us = externip.sin_addr;
1839 if (option_debug) {
1840 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n",
1841 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
1843 } else if (bindaddr.sin_addr.s_addr)
1844 *us = bindaddr.sin_addr;
1845 return AST_SUCCESS;
1848 /*! \brief Append to SIP dialog history
1849 \return Always returns 0 */
1850 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1852 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1853 __attribute__ ((format (printf, 2, 3)));
1855 /*! \brief Append to SIP dialog history with arg list */
1856 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1858 char buf[80], *c = buf; /* max history length */
1859 struct sip_history *hist;
1860 int l;
1862 vsnprintf(buf, sizeof(buf), fmt, ap);
1863 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1864 l = strlen(buf) + 1;
1865 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1866 return;
1867 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1868 free(hist);
1869 return;
1871 memcpy(hist->event, buf, l);
1872 if (p->history_entries == MAX_HISTORY_ENTRIES) {
1873 struct sip_history *oldest;
1874 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
1875 p->history_entries--;
1876 free(oldest);
1878 AST_LIST_INSERT_TAIL(p->history, hist, list);
1879 p->history_entries++;
1882 /*! \brief Append to SIP dialog history with arg list */
1883 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1885 va_list ap;
1887 if (!p)
1888 return;
1890 if (ast_test_flag(&p->flags[0], SIP_NO_HISTORY)
1891 && !recordhistory && !dumphistory) {
1892 return;
1895 va_start(ap, fmt);
1896 append_history_va(p, fmt, ap);
1897 va_end(ap);
1899 return;
1902 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
1903 static int retrans_pkt(const void *data)
1905 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
1906 int reschedule = DEFAULT_RETRANS;
1907 int xmitres = 0;
1909 /* Lock channel PVT */
1910 ast_mutex_lock(&pkt->owner->lock);
1912 if (pkt->retrans < MAX_RETRANS) {
1913 pkt->retrans++;
1914 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
1915 if (sipdebug && option_debug > 3)
1916 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);
1917 } else {
1918 int siptimer_a;
1920 if (sipdebug && option_debug > 3)
1921 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1922 if (!pkt->timer_a)
1923 pkt->timer_a = 2 ;
1924 else
1925 pkt->timer_a = 2 * pkt->timer_a;
1927 /* For non-invites, a maximum of 4 secs */
1928 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
1929 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1930 siptimer_a = 4000;
1932 /* Reschedule re-transmit */
1933 reschedule = siptimer_a;
1934 if (option_debug > 3)
1935 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);
1938 if (sip_debug_test_pvt(pkt->owner)) {
1939 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
1940 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
1941 pkt->retrans, sip_nat_mode(pkt->owner),
1942 ast_inet_ntoa(dst->sin_addr),
1943 ntohs(dst->sin_port), pkt->data);
1946 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1947 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1948 ast_mutex_unlock(&pkt->owner->lock);
1949 if (xmitres == XMIT_ERROR)
1950 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
1951 else
1952 return reschedule;
1954 /* Too many retries */
1955 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
1956 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1957 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (ast_test_flag(pkt, FLAG_FATAL)) ? "Critical" : "Non-critical", (ast_test_flag(pkt, FLAG_RESPONSE)) ? "Response" : "Request");
1958 } else if ((pkt->method == SIP_OPTIONS) && sipdebug) {
1959 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1961 if (xmitres == XMIT_ERROR) {
1962 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission of transaction in call id %s \n", pkt->owner->callid);
1963 append_history(pkt->owner, "XmitErr", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1964 } else
1965 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1967 pkt->retransid = -1;
1969 if (ast_test_flag(pkt, FLAG_FATAL)) {
1970 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
1971 DEADLOCK_AVOIDANCE(&pkt->owner->lock); /* SIP_PVT, not channel */
1974 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
1975 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
1977 if (pkt->owner->owner) {
1978 sip_alreadygone(pkt->owner);
1979 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1980 ast_queue_hangup(pkt->owner->owner);
1981 ast_channel_unlock(pkt->owner->owner);
1982 } else {
1983 /* If no channel owner, destroy now */
1985 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
1986 if (pkt->method != SIP_OPTIONS) {
1987 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
1988 sip_alreadygone(pkt->owner);
1989 if (option_debug)
1990 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
1995 if (pkt->method == SIP_BYE) {
1996 /* We're not getting answers on SIP BYE's. Tear down the call anyway. */
1997 if (pkt->owner->owner)
1998 ast_channel_unlock(pkt->owner->owner);
1999 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
2000 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
2003 /* In any case, go ahead and remove the packet */
2004 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
2005 if (cur == pkt)
2006 break;
2008 if (cur) {
2009 if (prev)
2010 prev->next = cur->next;
2011 else
2012 pkt->owner->packets = cur->next;
2013 ast_mutex_unlock(&pkt->owner->lock);
2014 free(cur);
2015 pkt = NULL;
2016 } else
2017 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
2018 if (pkt)
2019 ast_mutex_unlock(&pkt->owner->lock);
2020 return 0;
2023 /*! \brief Transmit packet with retransmits
2024 \return 0 on success, -1 on failure to allocate packet
2026 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
2028 struct sip_pkt *pkt;
2029 int siptimer_a = DEFAULT_RETRANS;
2030 int xmitres = 0;
2032 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
2033 return AST_FAILURE;
2034 memcpy(pkt->data, data, len);
2035 pkt->method = sipmethod;
2036 pkt->packetlen = len;
2037 pkt->next = p->packets;
2038 pkt->owner = p;
2039 pkt->seqno = seqno;
2040 if (resp)
2041 ast_set_flag(pkt, FLAG_RESPONSE);
2042 pkt->data[len] = '\0';
2043 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
2044 pkt->retransid = -1;
2045 if (fatal)
2046 ast_set_flag(pkt, FLAG_FATAL);
2047 if (pkt->timer_t1)
2048 siptimer_a = pkt->timer_t1 * 2;
2050 if (option_debug > 3 && sipdebug)
2051 ast_log(LOG_DEBUG, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
2052 pkt->retransid = -1;
2053 pkt->next = p->packets;
2054 p->packets = pkt;
2055 if (sipmethod == SIP_INVITE) {
2056 /* Note this is a pending invite */
2057 p->pendinginvite = seqno;
2060 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
2062 if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
2063 append_history(pkt->owner, "XmitErr", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
2064 return AST_FAILURE;
2065 } else {
2066 /* Schedule retransmission */
2067 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
2068 return AST_SUCCESS;
2072 /*! \brief Kill a SIP dialog (called by scheduler) */
2073 static int __sip_autodestruct(const void *data)
2075 struct sip_pvt *p = (struct sip_pvt *)data;
2077 /* If this is a subscription, tell the phone that we got a timeout */
2078 if (p->subscribed) {
2079 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */
2080 p->subscribed = NONE;
2081 append_history(p, "Subscribestatus", "timeout");
2082 if (option_debug > 2)
2083 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
2084 return 10000; /* Reschedule this destruction so that we know that it's gone */
2087 /* If there are packets still waiting for delivery, delay the destruction */
2088 if (p->packets) {
2089 if (option_debug > 2)
2090 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
2091 append_history(p, "ReliableXmit", "timeout");
2092 return 10000;
2095 /* If we're destroying a subscription, dereference peer object too */
2096 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
2097 ASTOBJ_UNREF(p->relatedpeer,sip_destroy_peer);
2099 /* Reset schedule ID */
2100 p->autokillid = -1;
2102 if (option_debug)
2103 ast_log(LOG_DEBUG, "Auto destroying SIP dialog '%s'\n", p->callid);
2104 append_history(p, "AutoDestroy", "%s", p->callid);
2105 if (p->owner) {
2106 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
2107 ast_queue_hangup(p->owner);
2108 } else if (p->refer && !ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) {
2109 if (option_debug > 2)
2110 ast_log(LOG_DEBUG, "Finally hanging up channel after transfer: %s\n", p->callid);
2111 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2112 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
2113 } else
2114 sip_destroy(p);
2115 return 0;
2118 /*! \brief Schedule destruction of SIP dialog */
2119 static void sip_scheddestroy(struct sip_pvt *p, int ms)
2121 if (ms < 0) {
2122 if (p->timer_t1 == 0)
2123 p->timer_t1 = 500; /* Set timer T1 if not set (RFC 3261) */
2124 ms = p->timer_t1 * 64;
2126 if (sip_debug_test_pvt(p))
2127 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
2128 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
2129 append_history(p, "SchedDestroy", "%d ms", ms);
2131 AST_SCHED_DEL(sched, p->autokillid);
2132 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
2135 /*! \brief Cancel destruction of SIP dialog */
2136 static int sip_cancel_destroy(struct sip_pvt *p)
2138 int res = 0;
2139 if (p->autokillid > -1) {
2140 if (!(res = ast_sched_del(sched, p->autokillid))) {
2141 append_history(p, "CancelDestroy", "");
2142 p->autokillid = -1;
2145 return res;
2148 /*! \brief Acknowledges receipt of a packet and stops retransmission
2149 * called with p locked*/
2150 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2152 struct sip_pkt *cur, *prev = NULL;
2154 /* Just in case... */
2155 char *msg;
2156 int res = FALSE;
2158 msg = sip_methods[sipmethod].text;
2160 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
2161 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
2162 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
2163 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
2164 if (!resp && (seqno == p->pendinginvite)) {
2165 if (option_debug)
2166 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
2167 p->pendinginvite = 0;
2169 /* this is our baby */
2170 res = TRUE;
2171 UNLINK(cur, p->packets, prev);
2172 if (cur->retransid > -1) {
2173 if (sipdebug && option_debug > 3)
2174 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
2176 /* This odd section is designed to thwart a
2177 * race condition in the packet scheduler. There are
2178 * two conditions under which deleting the packet from the
2179 * scheduler can fail.
2181 * 1. The packet has been removed from the scheduler because retransmission
2182 * is being attempted. The problem is that if the packet is currently attempting
2183 * retransmission and we are at this point in the code, then that MUST mean
2184 * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
2185 * lock temporarily to allow retransmission.
2187 * 2. The packet has reached its maximum number of retransmissions and has
2188 * been permanently removed from the packet scheduler. If this is the case, then
2189 * the packet's retransid will be set to -1. The atomicity of the setting and checking
2190 * of the retransid to -1 is ensured since in both cases p's lock is held.
2192 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
2193 DEADLOCK_AVOIDANCE(&p->lock);
2195 free(cur);
2196 break;
2199 if (option_debug)
2200 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");
2203 /*! \brief Pretend to ack all packets
2204 * called with p locked */
2205 static void __sip_pretend_ack(struct sip_pvt *p)
2207 struct sip_pkt *cur = NULL;
2209 while (p->packets) {
2210 int method;
2211 if (cur == p->packets) {
2212 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
2213 return;
2215 cur = p->packets;
2216 method = (cur->method) ? cur->method : find_sip_method(cur->data);
2217 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method);
2221 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2222 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2224 struct sip_pkt *cur;
2225 int res = -1;
2227 for (cur = p->packets; cur; cur = cur->next) {
2228 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
2229 (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
2230 /* this is our baby */
2231 if (cur->retransid > -1) {
2232 if (option_debug > 3 && sipdebug)
2233 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
2235 AST_SCHED_DEL(sched, cur->retransid);
2236 res = 0;
2237 break;
2240 if (option_debug)
2241 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");
2242 return res;
2246 /*! \brief Copy SIP request, parse it */
2247 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2249 memset(dst, 0, sizeof(*dst));
2250 memcpy(dst->data, src->data, sizeof(dst->data));
2251 dst->len = src->len;
2252 parse_request(dst);
2255 /*! \brief add a blank line if no body */
2256 static void add_blank(struct sip_request *req)
2258 if (!req->lines) {
2259 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2260 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2261 req->len += strlen(req->data + req->len);
2265 /*! \brief Transmit response on SIP request*/
2266 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2268 int res;
2270 add_blank(req);
2271 if (sip_debug_test_pvt(p)) {
2272 const struct sockaddr_in *dst = sip_real_dst(p);
2274 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
2275 reliable ? "Reliably " : "", sip_nat_mode(p),
2276 ast_inet_ntoa(dst->sin_addr),
2277 ntohs(dst->sin_port), req->data);
2279 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2280 struct sip_request tmp;
2281 parse_copy(&tmp, req);
2282 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
2283 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
2285 res = (reliable) ?
2286 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2287 __sip_xmit(p, req->data, req->len);
2288 if (res > 0)
2289 return 0;
2290 return res;
2293 /*! \brief Send SIP Request to the other part of the dialogue */
2294 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2296 int res;
2298 add_blank(req);
2299 if (sip_debug_test_pvt(p)) {
2300 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
2301 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);
2302 else
2303 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);
2305 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2306 struct sip_request tmp;
2307 parse_copy(&tmp, req);
2308 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
2310 res = (reliable) ?
2311 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2312 __sip_xmit(p, req->data, req->len);
2313 return res;
2316 /*! \brief Locate closing quote in a string, skipping escaped quotes.
2317 * optionally with a limit on the search.
2318 * start must be past the first quote.
2320 static const char *find_closing_quote(const char *start, const char *lim)
2322 char last_char = '\0';
2323 const char *s;
2324 for (s = start; *s && s != lim; last_char = *s++) {
2325 if (*s == '"' && last_char != '\\')
2326 break;
2328 return s;
2331 /*! \brief Pick out text in brackets from character string
2332 \return pointer to terminated stripped string
2333 \param tmp input string that will be modified
2334 Examples:
2336 "foo" <bar> valid input, returns bar
2337 foo returns the whole string
2338 < "foo ... > returns the string between brackets
2339 < "foo... bogus (missing closing bracket), returns the whole string
2340 XXX maybe should still skip the opening bracket
2342 static char *get_in_brackets(char *tmp)
2344 const char *parse = tmp;
2345 char *first_bracket;
2348 * Skip any quoted text until we find the part in brackets.
2349 * On any error give up and return the full string.
2351 while ( (first_bracket = strchr(parse, '<')) ) {
2352 char *first_quote = strchr(parse, '"');
2354 if (!first_quote || first_quote > first_bracket)
2355 break; /* no need to look at quoted part */
2356 /* the bracket is within quotes, so ignore it */
2357 parse = find_closing_quote(first_quote + 1, NULL);
2358 if (!*parse) { /* not found, return full string ? */
2359 /* XXX or be robust and return in-bracket part ? */
2360 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
2361 break;
2363 parse++;
2365 if (first_bracket) {
2366 char *second_bracket = strchr(first_bracket + 1, '>');
2367 if (second_bracket) {
2368 *second_bracket = '\0';
2369 tmp = first_bracket + 1;
2370 } else {
2371 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
2374 return tmp;
2377 /*! \brief Send SIP MESSAGE text within a call
2378 Called from PBX core sendtext() application */
2379 static int sip_sendtext(struct ast_channel *ast, const char *text)
2381 struct sip_pvt *p = ast->tech_pvt;
2382 int debug = sip_debug_test_pvt(p);
2384 if (debug)
2385 ast_verbose("Sending text %s on %s\n", text, ast->name);
2386 if (!p)
2387 return -1;
2388 if (ast_strlen_zero(text))
2389 return 0;
2390 if (debug)
2391 ast_verbose("Really sending text %s on %s\n", text, ast->name);
2392 transmit_message_with_text(p, text);
2393 return 0;
2396 /*! \brief Update peer object in realtime storage
2397 If the Asterisk system name is set in asterisk.conf, we will use
2398 that name and store that in the "regserver" field in the sippeers
2399 table to facilitate multi-server setups.
2401 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
2403 char port[10];
2404 char ipaddr[INET_ADDRSTRLEN];
2405 char regseconds[20];
2407 char *sysname = ast_config_AST_SYSTEM_NAME;
2408 char *syslabel = NULL;
2410 time_t nowtime = time(NULL) + expirey;
2411 const char *fc = fullcontact ? "fullcontact" : NULL;
2413 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
2414 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2415 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2417 if (ast_strlen_zero(sysname)) /* No system name, disable this */
2418 sysname = NULL;
2419 else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME))
2420 syslabel = "regserver";
2422 if (fc)
2423 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2424 "port", port, "regseconds", regseconds,
2425 "username", username, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
2426 else
2427 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2428 "port", port, "regseconds", regseconds,
2429 "username", username, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
2432 /*! \brief Automatically add peer extension to dial plan */
2433 static void register_peer_exten(struct sip_peer *peer, int onoff)
2435 char multi[256];
2436 char *stringp, *ext, *context;
2438 /* XXX note that global_regcontext is both a global 'enable' flag and
2439 * the name of the global regexten context, if not specified
2440 * individually.
2442 if (ast_strlen_zero(global_regcontext))
2443 return;
2445 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
2446 stringp = multi;
2447 while ((ext = strsep(&stringp, "&"))) {
2448 if ((context = strchr(ext, '@'))) {
2449 *context++ = '\0'; /* split ext@context */
2450 if (!ast_context_find(context)) {
2451 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
2452 continue;
2454 } else {
2455 context = global_regcontext;
2457 if (onoff)
2458 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2459 ast_strdup(peer->name), ast_free, "SIP");
2460 else
2461 ast_context_remove_extension(context, ext, 1, NULL);
2465 /*! \brief Destroy peer object from memory */
2466 static void sip_destroy_peer(struct sip_peer *peer)
2468 if (option_debug > 2)
2469 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
2471 /* Delete it, it needs to disappear */
2472 if (peer->call)
2473 sip_destroy(peer->call);
2475 if (peer->mwipvt) /* We have an active subscription, delete it */
2476 sip_destroy(peer->mwipvt);
2478 if (peer->chanvars) {
2479 ast_variables_destroy(peer->chanvars);
2480 peer->chanvars = NULL;
2483 register_peer_exten(peer, FALSE);
2484 ast_free_ha(peer->ha);
2485 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
2486 apeerobjs--;
2487 else if (ast_test_flag(&peer->flags[0], SIP_REALTIME))
2488 rpeerobjs--;
2489 else
2490 speerobjs--;
2491 clear_realm_authentication(peer->auth);
2492 peer->auth = NULL;
2493 free(peer);
2496 /*! \brief Update peer data in database (if used) */
2497 static void update_peer(struct sip_peer *p, int expiry)
2499 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2500 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
2501 (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
2502 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
2507 /*! \brief realtime_peer: Get peer from realtime storage
2508 * Checks the "sippeers" realtime family from extconfig.conf
2509 * \todo Consider adding check of port address when matching here to follow the same
2510 * algorithm as for static peers. Will we break anything by adding that?
2512 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
2514 struct sip_peer *peer=NULL;
2515 struct ast_variable *var = NULL;
2516 struct ast_config *peerlist = NULL;
2517 struct ast_variable *tmp;
2518 struct ast_flags flags = {0};
2519 const char *iabuf = NULL;
2520 char portstring[6]; /*up to five digits plus null terminator*/
2521 const char *insecure;
2522 char *cat = NULL;
2523 unsigned short portnum;
2525 /* First check on peer name */
2526 if (newpeername) {
2527 var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", NULL);
2528 if (!var && sin)
2529 var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), NULL);
2530 if (!var) {
2531 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
2532 /*!\note
2533 * If this one loaded something, then we need to ensure that the host
2534 * field matched. The only reason why we can't have this as a criteria
2535 * is because we only have the IP address and the host field might be
2536 * set as a name (and the reverse PTR might not match).
2538 if (var && sin) {
2539 for (tmp = var; tmp; tmp = tmp->next) {
2540 if (!strcasecmp(tmp->name, "host")) {
2541 struct hostent *hp;
2542 struct ast_hostent ahp;
2543 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
2544 /* No match */
2545 ast_variables_destroy(var);
2546 var = NULL;
2548 break;
2555 if (!var && sin) { /* Then check on IP address */
2556 iabuf = ast_inet_ntoa(sin->sin_addr);
2557 portnum = ntohs(sin->sin_port);
2558 sprintf(portstring, "%d", portnum);
2559 var = ast_load_realtime("sippeers", "host", iabuf, "port", portstring, NULL); /* First check for fixed IP hosts */
2560 if (!var)
2561 var = ast_load_realtime("sippeers", "ipaddr", iabuf, "port", portstring, NULL); /* Then check for registered hosts */
2562 if (!var) {
2563 peerlist = ast_load_realtime_multientry("sippeers", "host", iabuf, NULL); /*No exact match, see if port is insecure, try host match first*/
2564 if(peerlist){
2565 while((cat = ast_category_browse(peerlist, cat)))
2567 insecure = ast_variable_retrieve(peerlist, cat, "insecure");
2568 set_insecure_flags(&flags, insecure, -1);
2569 if(ast_test_flag(&flags, SIP_INSECURE_PORT)) {
2570 var = ast_category_root(peerlist, cat);
2571 break;
2575 if(!var) {
2576 ast_config_destroy(peerlist);
2577 peerlist = NULL; /*for safety's sake*/
2578 cat = NULL;
2579 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", iabuf, NULL); /*No exact match, see if port is insecure, now try ip address match*/
2580 if(peerlist) {
2581 while((cat = ast_category_browse(peerlist, cat)))
2583 insecure = ast_variable_retrieve(peerlist, cat, "insecure");
2584 set_insecure_flags(&flags, insecure, -1);
2585 if(ast_test_flag(&flags, SIP_INSECURE_PORT)) {
2586 var = ast_category_root(peerlist, cat);
2587 break;
2595 if (!var) {
2596 if(peerlist)
2597 ast_config_destroy(peerlist);
2598 return NULL;
2601 for (tmp = var; tmp; tmp = tmp->next) {
2602 /* If this is type=user, then skip this object. */
2603 if (!strcasecmp(tmp->name, "type") &&
2604 !strcasecmp(tmp->value, "user")) {
2605 ast_variables_destroy(var);
2606 return NULL;
2607 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
2608 newpeername = tmp->value;
2612 if (!newpeername) { /* Did not find peer in realtime */
2613 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
2614 if(peerlist)
2615 ast_config_destroy(peerlist);
2616 else
2617 ast_variables_destroy(var);
2618 return NULL;
2621 /* Peer found in realtime, now build it in memory */
2622 peer = build_peer(newpeername, var, NULL, 1);
2623 if (!peer) {
2624 if(peerlist)
2625 ast_config_destroy(peerlist);
2626 else
2627 ast_variables_destroy(var);
2628 return NULL;
2631 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2632 /* Cache peer */
2633 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
2634 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
2635 if (!AST_SCHED_DEL(sched, peer->expire)) {
2636 struct sip_peer *peer_ptr = peer;
2637 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
2639 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, ASTOBJ_REF(peer));
2640 if (peer->expire == -1) {
2641 struct sip_peer *peer_ptr = peer;
2642 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
2645 ASTOBJ_CONTAINER_LINK(&peerl,peer);
2646 } else {
2647 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)
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)
2679 p = realtime_peer(peer, sin);
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++;
2738 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);
2908 if (p) {
2909 int res = create_addr_from_peer(dialog, p);
2910 ASTOBJ_UNREF(p, sip_destroy_peer);
2911 return res;
2913 hostn = peer;
2914 portno = port ? atoi(port) : STANDARD_SIP_PORT;
2915 if (srvlookup) {
2916 char service[MAXHOSTNAMELEN];
2917 int tportno;
2918 int ret;
2920 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
2921 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
2922 if (ret > 0) {
2923 hostn = host;
2924 portno = tportno;
2927 hp = ast_gethostbyname(hostn, &ahp);
2928 if (!hp) {
2929 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2930 return -1;
2932 ast_string_field_set(dialog, tohost, peer);
2933 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
2934 dialog->sa.sin_port = htons(portno);
2935 dialog->recv = dialog->sa;
2936 return 0;
2939 /*! \brief Scheduled congestion on a call */
2940 static int auto_congest(const void *nothing)
2942 struct sip_pvt *p = (struct sip_pvt *)nothing;
2944 ast_mutex_lock(&p->lock);
2945 p->initid = -1;
2946 if (p->owner) {
2947 /* XXX fails on possible deadlock */
2948 if (!ast_channel_trylock(p->owner)) {
2949 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
2950 append_history(p, "Cong", "Auto-congesting (timer)");
2951 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
2952 ast_channel_unlock(p->owner);
2955 ast_mutex_unlock(&p->lock);
2956 return 0;
2960 /*! \brief Initiate SIP call from PBX
2961 * used from the dial() application */
2962 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2964 int res, xmitres = 0;
2965 struct sip_pvt *p;
2966 struct varshead *headp;
2967 struct ast_var_t *current;
2968 const char *referer = NULL; /* SIP refererer */
2970 p = ast->tech_pvt;
2971 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2972 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2973 return -1;
2976 /* Check whether there is vxml_url, distinctive ring variables */
2977 headp=&ast->varshead;
2978 AST_LIST_TRAVERSE(headp,current,entries) {
2979 /* Check whether there is a VXML_URL variable */
2980 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2981 p->options->vxml_url = ast_var_value(current);
2982 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
2983 p->options->uri_options = ast_var_value(current);
2984 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
2985 /* Check whether there is a ALERT_INFO variable */
2986 p->options->distinctive_ring = ast_var_value(current);
2987 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2988 /* Check whether there is a variable with a name starting with SIPADDHEADER */
2989 p->options->addsipheaders = 1;
2990 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
2991 /* This is a transfered call */
2992 p->options->transfer = 1;
2993 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
2994 /* This is the referer */
2995 referer = ast_var_value(current);
2996 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
2997 /* We're replacing a call. */
2998 p->options->replaces = ast_var_value(current);
2999 } else if (!strcasecmp(ast_var_name(current), "T38CALL")) {
3000 p->t38.state = T38_LOCAL_DIRECT;
3001 if (option_debug)
3002 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
3007 res = 0;
3008 ast_set_flag(&p->flags[0], SIP_OUTGOING);
3010 if (p->options->transfer) {
3011 char buf[SIPBUFSIZE/2];
3013 if (referer) {
3014 if (sipdebug && option_debug > 2)
3015 ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->username, referer);
3016 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
3017 } else
3018 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
3019 ast_string_field_set(p, cid_name, buf);
3021 if (option_debug)
3022 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
3024 res = update_call_counter(p, INC_CALL_RINGING);
3025 if ( res != -1 ) {
3026 p->callingpres = ast->cid.cid_pres;
3027 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
3028 p->jointnoncodeccapability = p->noncodeccapability;
3030 /* If there are no audio formats left to offer, punt */
3031 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
3032 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
3033 res = -1;
3034 } else {
3035 p->t38.jointcapability = p->t38.capability;
3036 if (option_debug > 1)
3037 ast_log(LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
3038 xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
3039 if (xmitres == XMIT_ERROR)
3040 return -1; /* Transmission error */
3042 p->invitestate = INV_CALLING;
3044 /* Initialize auto-congest time */
3045 AST_SCHED_DEL(sched, p->initid);
3046 p->initid = ast_sched_add(sched, p->maxtime ? (p->maxtime * 4) : SIP_TRANS_TIMEOUT, auto_congest, p);
3049 return res;
3052 /*! \brief Destroy registry object
3053 Objects created with the register= statement in static configuration */
3054 static void sip_registry_destroy(struct sip_registry *reg)
3056 /* Really delete */
3057 if (option_debug > 2)
3058 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
3060 if (reg->call) {
3061 /* Clear registry before destroying to ensure
3062 we don't get reentered trying to grab the registry lock */
3063 reg->call->registry = NULL;
3064 if (option_debug > 2)
3065 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
3066 sip_destroy(reg->call);
3068 AST_SCHED_DEL(sched, reg->expire);
3069 AST_SCHED_DEL(sched, reg->timeout);
3070 ast_string_field_free_memory(reg);
3071 regobjs--;
3072 free(reg);
3076 /*! \brief Execute destruction of SIP dialog structure, release memory */
3077 static int __sip_destroy(struct sip_pvt *p, int lockowner)
3079 struct sip_pvt *cur, *prev = NULL;
3080 struct sip_pkt *cp;
3082 /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
3083 if (p->rtp && ast_rtp_get_bridged(p->rtp)) {
3084 ast_verbose("Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
3085 return -1;
3088 if (p->vrtp && ast_rtp_get_bridged(p->vrtp)) {
3089 ast_verbose("Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
3090 return -1;
3093 if (sip_debug_test_pvt(p) || option_debug > 2)
3094 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
3096 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
3097 update_call_counter(p, DEC_CALL_LIMIT);
3098 if (option_debug > 1)
3099 ast_log(LOG_DEBUG, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
3102 /* Unlink us from the owner if we have one */
3103 if (p->owner) {
3104 if (lockowner)
3105 ast_channel_lock(p->owner);
3106 if (option_debug)
3107 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
3108 p->owner->tech_pvt = NULL;
3109 /* Make sure that the channel knows its backend is going away */
3110 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
3111 if (lockowner)
3112 ast_channel_unlock(p->owner);
3113 /* Give the channel a chance to react before deallocation */
3114 usleep(1);
3117 /* Remove link from peer to subscription of MWI */
3118 if (p->relatedpeer) {
3119 if (p->relatedpeer->mwipvt == p) {
3120 p->relatedpeer->mwipvt = NULL;
3122 ASTOBJ_UNREF(p->relatedpeer, sip_destroy_peer);
3125 if (dumphistory)
3126 sip_dump_history(p);
3128 if (p->options)
3129 free(p->options);
3131 if (p->stateid > -1)
3132 ast_extension_state_del(p->stateid, NULL);
3133 AST_SCHED_DEL(sched, p->initid);
3134 AST_SCHED_DEL(sched, p->waitid);
3135 AST_SCHED_DEL(sched, p->autokillid);
3137 if (p->rtp) {
3138 ast_rtp_destroy(p->rtp);
3140 if (p->vrtp) {
3141 ast_rtp_destroy(p->vrtp);
3143 if (p->udptl)
3144 ast_udptl_destroy(p->udptl);
3145 if (p->refer)
3146 free(p->refer);
3147 if (p->route) {
3148 free_old_route(p->route);
3149 p->route = NULL;
3151 if (p->registry) {
3152 if (p->registry->call == p)
3153 p->registry->call = NULL;
3154 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
3157 /* Clear history */
3158 if (p->history) {
3159 struct sip_history *hist;
3160 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
3161 free(hist);
3162 p->history_entries--;
3164 free(p->history);
3165 p->history = NULL;
3168 for (prev = NULL, cur = iflist; cur; prev = cur, cur = cur->next) {
3169 if (cur == p) {
3170 UNLINK(cur, iflist, prev);
3171 break;
3174 if (!cur) {
3175 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
3176 return 0;
3179 /* remove all current packets in this dialog */
3180 while((cp = p->packets)) {
3181 p->packets = p->packets->next;
3182 AST_SCHED_DEL(sched, cp->retransid);
3183 free(cp);
3185 if (p->chanvars) {
3186 ast_variables_destroy(p->chanvars);
3187 p->chanvars = NULL;
3189 ast_mutex_destroy(&p->lock);
3191 ast_string_field_free_memory(p);
3193 free(p);
3194 return 0;
3197 /*! \brief update_call_counter: Handle call_limit for SIP users
3198 * Setting a call-limit will cause calls above the limit not to be accepted.
3200 * Remember that for a type=friend, there's one limit for the user and
3201 * another for the peer, not a combined call limit.
3202 * This will cause unexpected behaviour in subscriptions, since a "friend"
3203 * is *two* devices in Asterisk, not one.
3205 * Thought: For realtime, we should propably update storage with inuse counter...
3207 * \return 0 if call is ok (no call limit, below treshold)
3208 * -1 on rejection of call
3211 static int update_call_counter(struct sip_pvt *fup, int event)
3213 char name[256];
3214 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
3215 int outgoing = ast_test_flag(&fup->flags[1], SIP_PAGE2_OUTGOING_CALL);
3216 struct sip_user *u = NULL;
3217 struct sip_peer *p = NULL;
3219 if (option_debug > 2)
3220 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
3222 /* Test if we need to check call limits, in order to avoid
3223 realtime lookups if we do not need it */
3224 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
3225 return 0;
3227 ast_copy_string(name, fup->username, sizeof(name));
3229 /* Check the list of users only for incoming calls */
3230 if (global_limitonpeers == FALSE && !outgoing && (u = find_user(name, 1))) {
3231 inuse = &u->inUse;
3232 call_limit = &u->call_limit;
3233 inringing = NULL;
3234 } else if ( (p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, 1) ) ) { /* Try to find peer */
3235 inuse = &p->inUse;
3236 call_limit = &p->call_limit;
3237 inringing = &p->inRinging;
3238 ast_copy_string(name, fup->peername, sizeof(name));
3240 if (!p && !u) {
3241 if (option_debug > 1)
3242 ast_log(LOG_DEBUG, "%s is not a local device, no call limit\n", name);
3243 return 0;
3246 switch(event) {
3247 /* incoming and outgoing affects the inUse counter */
3248 case DEC_CALL_LIMIT:
3249 if ( *inuse > 0 ) {
3250 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
3251 (*inuse)--;
3252 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
3254 } else {
3255 *inuse = 0;
3257 if (inringing) {
3258 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3259 if (*inringing > 0)
3260 (*inringing)--;
3261 else if (!ast_test_flag(&p->flags[0], SIP_REALTIME) || ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS))
3262 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", fup->peername);
3263 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3266 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && global_notifyhold) {
3267 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
3268 sip_peer_hold(fup, 0);
3270 if (option_debug > 1 || sipdebug) {
3271 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
3273 break;
3275 case INC_CALL_RINGING:
3276 case INC_CALL_LIMIT:
3277 if (*call_limit > 0 ) {
3278 if (*inuse >= *call_limit) {
3279 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);
3280 if (u)
3281 ASTOBJ_UNREF(u, sip_destroy_user);
3282 else
3283 ASTOBJ_UNREF(p, sip_destroy_peer);
3284 return -1;
3287 if (inringing && (event == INC_CALL_RINGING)) {
3288 if (!ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3289 (*inringing)++;
3290 ast_set_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3293 /* Continue */
3294 (*inuse)++;
3295 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
3296 if (option_debug > 1 || sipdebug) {
3297 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
3299 break;
3301 case DEC_CALL_RINGING:
3302 if (inringing) {
3303 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3304 if (*inringing > 0)
3305 (*inringing)--;
3306 else if (!ast_test_flag(&p->flags[0], SIP_REALTIME) || ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS))
3307 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", p->name);
3308 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3311 break;
3313 default:
3314 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
3316 if (p) {
3317 ast_device_state_changed("SIP/%s", p->name);
3318 ASTOBJ_UNREF(p, sip_destroy_peer);
3319 } else /* u must be set */
3320 ASTOBJ_UNREF(u, sip_destroy_user);
3321 return 0;
3324 /*! \brief Destroy SIP call structure */
3325 static void sip_destroy(struct sip_pvt *p)
3327 ast_mutex_lock(&iflock);
3328 if (option_debug > 2)
3329 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
3330 __sip_destroy(p, 1);
3331 ast_mutex_unlock(&iflock);
3334 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
3335 static int hangup_sip2cause(int cause)
3337 /* Possible values taken from causes.h */
3339 switch(cause) {
3340 case 401: /* Unauthorized */
3341 return AST_CAUSE_CALL_REJECTED;
3342 case 403: /* Not found */
3343 return AST_CAUSE_CALL_REJECTED;
3344 case 404: /* Not found */
3345 return AST_CAUSE_UNALLOCATED;
3346 case 405: /* Method not allowed */
3347 return AST_CAUSE_INTERWORKING;
3348 case 407: /* Proxy authentication required */
3349 return AST_CAUSE_CALL_REJECTED;
3350 case 408: /* No reaction */
3351 return AST_CAUSE_NO_USER_RESPONSE;
3352 case 409: /* Conflict */
3353 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
3354 case 410: /* Gone */
3355 return AST_CAUSE_UNALLOCATED;
3356 case 411: /* Length required */
3357 return AST_CAUSE_INTERWORKING;
3358 case 413: /* Request entity too large */
3359 return AST_CAUSE_INTERWORKING;
3360 case 414: /* Request URI too large */
3361 return AST_CAUSE_INTERWORKING;
3362 case 415: /* Unsupported media type */
3363 return AST_CAUSE_INTERWORKING;
3364 case 420: /* Bad extension */
3365 return AST_CAUSE_NO_ROUTE_DESTINATION;
3366 case 480: /* No answer */
3367 return AST_CAUSE_NO_ANSWER;
3368 case 481: /* No answer */
3369 return AST_CAUSE_INTERWORKING;
3370 case 482: /* Loop detected */
3371 return AST_CAUSE_INTERWORKING;
3372 case 483: /* Too many hops */
3373 return AST_CAUSE_NO_ANSWER;
3374 case 484: /* Address incomplete */
3375 return AST_CAUSE_INVALID_NUMBER_FORMAT;
3376 case 485: /* Ambigous */
3377 return AST_CAUSE_UNALLOCATED;
3378 case 486: /* Busy everywhere */
3379 return AST_CAUSE_BUSY;
3380 case 487: /* Request terminated */
3381 return AST_CAUSE_INTERWORKING;
3382 case 488: /* No codecs approved */
3383 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3384 case 491: /* Request pending */
3385 return AST_CAUSE_INTERWORKING;
3386 case 493: /* Undecipherable */
3387 return AST_CAUSE_INTERWORKING;
3388 case 500: /* Server internal failure */
3389 return AST_CAUSE_FAILURE;
3390 case 501: /* Call rejected */
3391 return AST_CAUSE_FACILITY_REJECTED;
3392 case 502:
3393 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
3394 case 503: /* Service unavailable */
3395 return AST_CAUSE_CONGESTION;
3396 case 504: /* Gateway timeout */
3397 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
3398 case 505: /* SIP version not supported */
3399 return AST_CAUSE_INTERWORKING;
3400 case 600: /* Busy everywhere */
3401 return AST_CAUSE_USER_BUSY;
3402 case 603: /* Decline */
3403 return AST_CAUSE_CALL_REJECTED;
3404 case 604: /* Does not exist anywhere */
3405 return AST_CAUSE_UNALLOCATED;
3406 case 606: /* Not acceptable */
3407 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3408 default:
3409 return AST_CAUSE_NORMAL;
3411 /* Never reached */
3412 return 0;
3415 /*! \brief Convert Asterisk hangup causes to SIP codes
3416 \verbatim
3417 Possible values from causes.h
3418 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
3419 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
3421 In addition to these, a lot of PRI codes is defined in causes.h
3422 ...should we take care of them too ?
3424 Quote RFC 3398
3426 ISUP Cause value SIP response
3427 ---------------- ------------
3428 1 unallocated number 404 Not Found
3429 2 no route to network 404 Not found
3430 3 no route to destination 404 Not found
3431 16 normal call clearing --- (*)
3432 17 user busy 486 Busy here
3433 18 no user responding 408 Request Timeout
3434 19 no answer from the user 480 Temporarily unavailable
3435 20 subscriber absent 480 Temporarily unavailable
3436 21 call rejected 403 Forbidden (+)
3437 22 number changed (w/o diagnostic) 410 Gone
3438 22 number changed (w/ diagnostic) 301 Moved Permanently
3439 23 redirection to new destination 410 Gone
3440 26 non-selected user clearing 404 Not Found (=)
3441 27 destination out of order 502 Bad Gateway
3442 28 address incomplete 484 Address incomplete
3443 29 facility rejected 501 Not implemented
3444 31 normal unspecified 480 Temporarily unavailable
3445 \endverbatim
3447 static const char *hangup_cause2sip(int cause)
3449 switch (cause) {
3450 case AST_CAUSE_UNALLOCATED: /* 1 */
3451 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
3452 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
3453 return "404 Not Found";
3454 case AST_CAUSE_CONGESTION: /* 34 */
3455 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
3456 return "503 Service Unavailable";
3457 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
3458 return "408 Request Timeout";
3459 case AST_CAUSE_NO_ANSWER: /* 19 */
3460 return "480 Temporarily unavailable";
3461 case AST_CAUSE_CALL_REJECTED: /* 21 */
3462 return "403 Forbidden";
3463 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
3464 return "410 Gone";
3465 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
3466 return "480 Temporarily unavailable";
3467 case AST_CAUSE_INVALID_NUMBER_FORMAT:
3468 return "484 Address incomplete";
3469 case AST_CAUSE_USER_BUSY:
3470 return "486 Busy here";
3471 case AST_CAUSE_FAILURE:
3472 return "500 Server internal failure";
3473 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
3474 return "501 Not Implemented";
3475 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
3476 return "503 Service Unavailable";
3477 /* Used in chan_iax2 */
3478 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
3479 return "502 Bad Gateway";
3480 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
3481 return "488 Not Acceptable Here";
3483 case AST_CAUSE_NOTDEFINED:
3484 default:
3485 if (option_debug)
3486 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
3487 return NULL;
3490 /* Never reached */
3491 return 0;
3495 /*! \brief sip_hangup: Hangup SIP call
3496 * Part of PBX interface, called from ast_hangup */
3497 static int sip_hangup(struct ast_channel *ast)
3499 struct sip_pvt *p = ast->tech_pvt;
3500 int needcancel = FALSE;
3501 int needdestroy = 0;
3502 struct ast_channel *oldowner = ast;
3504 if (!p) {
3505 if (option_debug)
3506 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
3507 return 0;
3510 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
3511 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
3512 if (option_debug && sipdebug)
3513 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
3514 update_call_counter(p, DEC_CALL_LIMIT);
3516 if (option_debug >3)
3517 ast_log(LOG_DEBUG, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
3518 if (p->autokillid > -1 && sip_cancel_destroy(p))
3519 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
3520 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3521 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
3522 ast_clear_flag(&p->flags[0], SIP_NEEDDESTROY);
3523 p->owner->tech_pvt = NULL;
3524 p->owner = NULL; /* Owner will be gone after we return, so take it away */
3525 return 0;
3527 if (option_debug) {
3528 if (ast_test_flag(ast, AST_FLAG_ZOMBIE) && p->refer && option_debug)
3529 ast_log(LOG_DEBUG, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
3530 else {
3531 if (option_debug)
3532 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
3535 if (option_debug && ast_test_flag(ast, AST_FLAG_ZOMBIE))
3536 ast_log(LOG_DEBUG, "Hanging up zombie call. Be scared.\n");
3538 ast_mutex_lock(&p->lock);
3539 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
3540 if (option_debug && sipdebug)
3541 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
3542 update_call_counter(p, DEC_CALL_LIMIT);
3545 /* Determine how to disconnect */
3546 if (p->owner != ast) {
3547 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
3548 ast_mutex_unlock(&p->lock);
3549 return 0;
3551 /* If the call is not UP, we need to send CANCEL instead of BYE */
3552 if (ast->_state == AST_STATE_RING || ast->_state == AST_STATE_RINGING || (p->invitestate < INV_COMPLETED && ast->_state != AST_STATE_UP)) {
3553 needcancel = TRUE;
3554 if (option_debug > 3)
3555 ast_log(LOG_DEBUG, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
3558 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
3560 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->owner->hangupcause) : "Unknown");
3562 /* Disconnect */
3563 if (p->vad)
3564 ast_dsp_free(p->vad);
3566 p->owner = NULL;
3567 ast->tech_pvt = NULL;
3569 ast_module_unref(ast_module_info->self);
3571 /* Do not destroy this pvt until we have timeout or
3572 get an answer to the BYE or INVITE/CANCEL
3573 If we get no answer during retransmit period, drop the call anyway.
3574 (Sorry, mother-in-law, you can't deny a hangup by sending
3575 603 declined to BYE...)
3577 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE))
3578 needdestroy = 1; /* Set destroy flag at end of this function */
3579 else if (p->invitestate != INV_CALLING)
3580 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3582 /* Start the process if it's not already started */
3583 if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
3584 if (needcancel) { /* Outgoing call, not up */
3585 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3586 /* stop retransmitting an INVITE that has not received a response */
3587 __sip_pretend_ack(p);
3588 p->invitestate = INV_CANCELLED;
3590 /* if we can't send right now, mark it pending */
3591 if (p->invitestate == INV_CALLING) {
3592 /* We can't send anything in CALLING state */
3593 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3594 /* 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. */
3595 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3596 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
3597 } else {
3598 /* Send a new request: CANCEL */
3599 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
3600 /* Actually don't destroy us yet, wait for the 487 on our original
3601 INVITE, but do set an autodestruct just in case we never get it. */
3602 needdestroy = 0;
3603 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3605 if ( p->initid != -1 ) {
3606 /* channel still up - reverse dec of inUse counter
3607 only if the channel is not auto-congested */
3608 update_call_counter(p, INC_CALL_LIMIT);
3610 } else { /* Incoming call, not up */
3611 const char *res;
3612 if (ast->hangupcause && (res = hangup_cause2sip(ast->hangupcause)))
3613 transmit_response_reliable(p, res, &p->initreq);
3614 else
3615 transmit_response_reliable(p, "603 Declined", &p->initreq);
3616 p->invitestate = INV_TERMINATED;
3618 } else { /* Call is in UP state, send BYE */
3619 if (!p->pendinginvite) {
3620 char *audioqos = "";
3621 char *videoqos = "";
3622 if (p->rtp)
3623 audioqos = ast_rtp_get_quality(p->rtp, NULL);
3624 if (p->vrtp)
3625 videoqos = ast_rtp_get_quality(p->vrtp, NULL);
3626 /* Send a hangup */
3627 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3629 /* Get RTCP quality before end of call */
3630 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
3631 if (p->rtp)
3632 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
3633 if (p->vrtp)
3634 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
3636 if (p->rtp && oldowner)
3637 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
3638 if (p->vrtp && oldowner)
3639 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
3640 } else {
3641 /* Note we will need a BYE when this all settles out
3642 but we can't send one while we have "INVITE" outstanding. */
3643 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3644 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
3645 AST_SCHED_DEL(sched, p->waitid);
3646 if (sip_cancel_destroy(p))
3647 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
3651 if (needdestroy)
3652 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
3653 ast_mutex_unlock(&p->lock);
3654 return 0;
3657 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
3658 static void try_suggested_sip_codec(struct sip_pvt *p)
3660 int fmt;
3661 const char *codec;
3663 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
3664 if (!codec)
3665 return;
3667 fmt = ast_getformatbyname(codec);
3668 if (fmt) {
3669 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
3670 if (p->jointcapability & fmt) {
3671 p->jointcapability &= fmt;
3672 p->capability &= fmt;
3673 } else
3674 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
3675 } else
3676 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
3677 return;
3680 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
3681 * Part of PBX interface */
3682 static int sip_answer(struct ast_channel *ast)
3684 int res = 0;
3685 struct sip_pvt *p = ast->tech_pvt;
3687 ast_mutex_lock(&p->lock);
3688 if (ast->_state != AST_STATE_UP) {
3689 try_suggested_sip_codec(p);
3691 ast_setstate(ast, AST_STATE_UP);
3692 if (option_debug)
3693 ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name);
3694 if (p->t38.state == T38_PEER_DIRECT) {
3695 p->t38.state = T38_ENABLED;
3696 if (option_debug > 1)
3697 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
3698 res = transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
3699 } else {
3700 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
3703 ast_mutex_unlock(&p->lock);
3704 return res;
3707 /*! \brief Send frame to media channel (rtp) */
3708 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
3710 struct sip_pvt *p = ast->tech_pvt;
3711 int res = 0;
3713 switch (frame->frametype) {
3714 case AST_FRAME_VOICE:
3715 if (!(frame->subclass & ast->nativeformats)) {
3716 char s1[512], s2[512], s3[512];
3717 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
3718 frame->subclass,
3719 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
3720 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
3721 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
3722 ast->readformat,
3723 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
3724 ast->writeformat);
3725 return 0;
3727 if (p) {
3728 ast_mutex_lock(&p->lock);
3729 if (p->rtp) {
3730 /* If channel is not up, activate early media session */
3731 if ((ast->_state != AST_STATE_UP) &&
3732 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3733 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3734 ast_rtp_new_source(p->rtp);
3735 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3736 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3738 p->lastrtptx = time(NULL);
3739 res = ast_rtp_write(p->rtp, frame);
3741 ast_mutex_unlock(&p->lock);
3743 break;
3744 case AST_FRAME_VIDEO:
3745 if (p) {
3746 ast_mutex_lock(&p->lock);
3747 if (p->vrtp) {
3748 /* Activate video early media */
3749 if ((ast->_state != AST_STATE_UP) &&
3750 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3751 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3752 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3753 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3755 p->lastrtptx = time(NULL);
3756 res = ast_rtp_write(p->vrtp, frame);
3758 ast_mutex_unlock(&p->lock);
3760 break;
3761 case AST_FRAME_IMAGE:
3762 return 0;
3763 break;
3764 case AST_FRAME_MODEM:
3765 if (p) {
3766 ast_mutex_lock(&p->lock);
3767 /* UDPTL requires two-way communication, so early media is not needed here.
3768 we simply forget the frames if we get modem frames before the bridge is up.
3769 Fax will re-transmit.
3771 if (p->udptl && ast->_state == AST_STATE_UP)
3772 res = ast_udptl_write(p->udptl, frame);
3773 ast_mutex_unlock(&p->lock);
3775 break;
3776 default:
3777 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
3778 return 0;
3781 return res;
3784 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
3785 Basically update any ->owner links */
3786 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
3788 int ret = -1;
3789 struct sip_pvt *p;
3791 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE) && option_debug)
3792 ast_log(LOG_DEBUG, "New channel is zombie\n");
3793 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE) && option_debug)
3794 ast_log(LOG_DEBUG, "Old channel is zombie\n");
3796 if (!newchan || !newchan->tech_pvt) {
3797 if (!newchan)
3798 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
3799 else
3800 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
3801 return -1;
3803 p = newchan->tech_pvt;
3805 if (!p) {
3806 ast_log(LOG_WARNING, "No pvt after masquerade. Strange things may happen\n");
3807 return -1;
3810 ast_mutex_lock(&p->lock);
3811 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
3812 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
3813 if (p->owner != oldchan)
3814 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
3815 else {
3816 p->owner = newchan;
3817 /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
3818 RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
3819 able to do this if the masquerade happens before the bridge breaks (e.g., AMI
3820 redirect of both channels). Note that a channel can not be masqueraded *into*
3821 a native bridge. So there is no danger that this breaks a native bridge that
3822 should stay up. */
3823 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0);
3824 ret = 0;
3826 if (option_debug > 2)
3827 ast_log(LOG_DEBUG, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
3829 ast_mutex_unlock(&p->lock);
3830 return ret;
3833 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
3835 struct sip_pvt *p = ast->tech_pvt;
3836 int res = 0;
3838 ast_mutex_lock(&p->lock);
3839 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
3840 case SIP_DTMF_INBAND:
3841 res = -1; /* Tell Asterisk to generate inband indications */
3842 break;
3843 case SIP_DTMF_RFC2833:
3844 if (p->rtp)
3845 ast_rtp_senddigit_begin(p->rtp, digit);
3846 break;
3847 default:
3848 break;
3850 ast_mutex_unlock(&p->lock);
3852 return res;
3855 /*! \brief Send DTMF character on SIP channel
3856 within one call, we're able to transmit in many methods simultaneously */
3857 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
3859 struct sip_pvt *p = ast->tech_pvt;
3860 int res = 0;
3862 ast_mutex_lock(&p->lock);
3863 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
3864 case SIP_DTMF_INFO:
3865 transmit_info_with_digit(p, digit, duration);
3866 break;
3867 case SIP_DTMF_RFC2833:
3868 if (p->rtp)
3869 ast_rtp_senddigit_end(p->rtp, digit);
3870 break;
3871 case SIP_DTMF_INBAND:
3872 res = -1; /* Tell Asterisk to stop inband indications */
3873 break;
3875 ast_mutex_unlock(&p->lock);
3877 return res;
3880 /*! \brief Transfer SIP call */
3881 static int sip_transfer(struct ast_channel *ast, const char *dest)
3883 struct sip_pvt *p = ast->tech_pvt;
3884 int res;
3886 if (dest == NULL) /* functions below do not take a NULL */
3887 dest = "";
3888 ast_mutex_lock(&p->lock);
3889 if (ast->_state == AST_STATE_RING)
3890 res = sip_sipredirect(p, dest);
3891 else
3892 res = transmit_refer(p, dest);
3893 ast_mutex_unlock(&p->lock);
3894 return res;
3897 /*! \brief Play indication to user
3898 * With SIP a lot of indications is sent as messages, letting the device play
3899 the indication - busy signal, congestion etc
3900 \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
3902 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
3904 struct sip_pvt *p = ast->tech_pvt;
3905 int res = 0;
3907 ast_mutex_lock(&p->lock);
3908 switch(condition) {
3909 case AST_CONTROL_RINGING:
3910 if (ast->_state == AST_STATE_RING) {
3911 p->invitestate = INV_EARLY_MEDIA;
3912 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
3913 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
3914 /* Send 180 ringing if out-of-band seems reasonable */
3915 transmit_response(p, "180 Ringing", &p->initreq);
3916 ast_set_flag(&p->flags[0], SIP_RINGING);
3917 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
3918 break;
3919 } else {
3920 /* Well, if it's not reasonable, just send in-band */
3923 res = -1;
3924 break;
3925 case AST_CONTROL_BUSY:
3926 if (ast->_state != AST_STATE_UP) {
3927 transmit_response_reliable(p, "486 Busy Here", &p->initreq);
3928 p->invitestate = INV_COMPLETED;
3929 sip_alreadygone(p);
3930 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
3931 break;
3933 res = -1;
3934 break;
3935 case AST_CONTROL_CONGESTION:
3936 if (ast->_state != AST_STATE_UP) {
3937 transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
3938 p->invitestate = INV_COMPLETED;
3939 sip_alreadygone(p);
3940 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
3941 break;
3943 res = -1;
3944 break;
3945 case AST_CONTROL_PROCEEDING:
3946 if ((ast->_state != AST_STATE_UP) &&
3947 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3948 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3949 transmit_response(p, "100 Trying", &p->initreq);
3950 p->invitestate = INV_PROCEEDING;
3951 break;
3953 res = -1;
3954 break;
3955 case AST_CONTROL_PROGRESS:
3956 if ((ast->_state != AST_STATE_UP) &&
3957 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3958 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3959 p->invitestate = INV_EARLY_MEDIA;
3960 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3961 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3962 break;
3964 res = -1;
3965 break;
3966 case AST_CONTROL_HOLD:
3967 ast_rtp_new_source(p->rtp);
3968 ast_moh_start(ast, data, p->mohinterpret);
3969 break;
3970 case AST_CONTROL_UNHOLD:
3971 ast_rtp_new_source(p->rtp);
3972 ast_moh_stop(ast);
3973 break;
3974 case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
3975 if (p->vrtp && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
3976 transmit_info_with_vidupdate(p);
3977 /* ast_rtcp_send_h261fur(p->vrtp); */
3978 } else
3979 res = -1;
3980 break;
3981 case AST_CONTROL_SRCUPDATE:
3982 ast_rtp_new_source(p->rtp);
3983 break;
3984 case -1:
3985 res = -1;
3986 break;
3987 default:
3988 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
3989 res = -1;
3990 break;
3992 ast_mutex_unlock(&p->lock);
3993 return res;
3997 /*! \brief Initiate a call in the SIP channel
3998 called from sip_request_call (calls from the pbx ) for outbound channels
3999 and from handle_request_invite for inbound channels
4002 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
4004 struct ast_channel *tmp;
4005 struct ast_variable *v = NULL;
4006 int fmt;
4007 int what;
4008 int needvideo = 0, video = 0;
4009 char *decoded_exten;
4011 const char *my_name; /* pick a good name */
4013 if (title)
4014 my_name = title;
4015 else if ( (my_name = strchr(i->fromdomain,':')) )
4016 my_name++; /* skip ':' */
4017 else
4018 my_name = i->fromdomain;
4020 ast_mutex_unlock(&i->lock);
4021 /* Don't hold a sip pvt lock while we allocate a channel */
4022 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);
4025 if (!tmp) {
4026 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
4027 ast_mutex_lock(&i->lock);
4028 return NULL;
4030 ast_mutex_lock(&i->lock);
4032 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO)
4033 tmp->tech = &sip_tech_info;
4034 else
4035 tmp->tech = &sip_tech;
4037 /* Select our native format based on codec preference until we receive
4038 something from another device to the contrary. */
4039 if (i->jointcapability) { /* The joint capabilities of us and peer */
4040 what = i->jointcapability;
4041 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
4042 } else if (i->capability) { /* Our configured capability for this peer */
4043 what = i->capability;
4044 video = i->capability & AST_FORMAT_VIDEO_MASK;
4045 } else {
4046 what = global_capability; /* Global codec support */
4047 video = global_capability & AST_FORMAT_VIDEO_MASK;
4050 /* Set the native formats for audio and merge in video */
4051 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video;
4052 if (option_debug > 2) {
4053 char buf[SIPBUFSIZE];
4054 ast_log(LOG_DEBUG, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
4055 ast_log(LOG_DEBUG, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
4056 ast_log(LOG_DEBUG, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
4057 ast_log(LOG_DEBUG, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
4058 if (i->prefcodec)
4059 ast_log(LOG_DEBUG, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
4062 /* XXX Why are we choosing a codec from the native formats?? */
4063 fmt = ast_best_codec(tmp->nativeformats);
4065 /* If we have a prefcodec setting, we have an inbound channel that set a
4066 preferred format for this call. Otherwise, we check the jointcapability
4067 We also check for vrtp. If it's not there, we are not allowed do any video anyway.
4069 if (i->vrtp) {
4070 if (i->prefcodec)
4071 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK; /* Outbound call */
4072 else
4073 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK; /* Inbound call */
4076 if (option_debug > 2) {
4077 if (needvideo)
4078 ast_log(LOG_DEBUG, "This channel can handle video! HOLLYWOOD next!\n");
4079 else
4080 ast_log(LOG_DEBUG, "This channel will not be able to handle video.\n");
4085 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
4086 i->vad = ast_dsp_new();
4087 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
4088 if (global_relaxdtmf)
4089 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
4091 if (i->rtp) {
4092 tmp->fds[0] = ast_rtp_fd(i->rtp);
4093 tmp->fds[1] = ast_rtcp_fd(i->rtp);
4095 if (needvideo && i->vrtp) {
4096 tmp->fds[2] = ast_rtp_fd(i->vrtp);
4097 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
4099 if (i->udptl) {
4100 tmp->fds[5] = ast_udptl_fd(i->udptl);
4102 if (state == AST_STATE_RING)
4103 tmp->rings = 1;
4104 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
4105 tmp->writeformat = fmt;
4106 tmp->rawwriteformat = fmt;
4107 tmp->readformat = fmt;
4108 tmp->rawreadformat = fmt;
4109 tmp->tech_pvt = i;
4111 tmp->callgroup = i->callgroup;
4112 tmp->pickupgroup = i->pickupgroup;
4113 tmp->cid.cid_pres = i->callingpres;
4114 if (!ast_strlen_zero(i->accountcode))
4115 ast_string_field_set(tmp, accountcode, i->accountcode);
4116 if (i->amaflags)
4117 tmp->amaflags = i->amaflags;
4118 if (!ast_strlen_zero(i->language))
4119 ast_string_field_set(tmp, language, i->language);
4120 i->owner = tmp;
4121 ast_module_ref(ast_module_info->self);
4122 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
4123 /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
4124 * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
4125 * structure so that there aren't issues when forming URI's
4127 decoded_exten = ast_strdupa(i->exten);
4128 ast_uri_decode(decoded_exten);
4129 ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
4131 /* Don't use ast_set_callerid() here because it will
4132 * generate an unnecessary NewCallerID event */
4133 tmp->cid.cid_ani = ast_strdup(i->cid_num);
4134 if (!ast_strlen_zero(i->rdnis))
4135 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
4137 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
4138 tmp->cid.cid_dnid = ast_strdup(i->exten);
4140 tmp->priority = 1;
4141 if (!ast_strlen_zero(i->uri))
4142 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
4143 if (!ast_strlen_zero(i->domain))
4144 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
4145 if (!ast_strlen_zero(i->useragent))
4146 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
4147 if (!ast_strlen_zero(i->callid))
4148 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
4149 if (i->rtp)
4150 ast_jb_configure(tmp, &global_jbconf);
4152 /* If the INVITE contains T.38 SDP information set the proper channel variable so a created outgoing call will also have T.38 */
4153 if (i->udptl && i->t38.state == T38_PEER_DIRECT)
4154 pbx_builtin_setvar_helper(tmp, "_T38CALL", "1");
4156 /* Set channel variables for this call from configuration */
4157 for (v = i->chanvars ; v ; v = v->next)
4158 pbx_builtin_setvar_helper(tmp, v->name, v->value);
4160 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
4161 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
4162 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
4163 ast_hangup(tmp);
4164 tmp = NULL;
4167 if (!ast_test_flag(&i->flags[0], SIP_NO_HISTORY))
4168 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
4170 return tmp;
4173 /*! \brief Reads one line of SIP message body */
4174 static char *get_body_by_line(const char *line, const char *name, int nameLen)
4176 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=')
4177 return ast_skip_blanks(line + nameLen + 1);
4179 return "";
4182 /*! \brief Lookup 'name' in the SDP starting
4183 * at the 'start' line. Returns the matching line, and 'start'
4184 * is updated with the next line number.
4186 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
4188 int len = strlen(name);
4190 while (*start < req->sdp_end) {
4191 const char *r = get_body_by_line(req->line[(*start)++], name, len);
4192 if (r[0] != '\0')
4193 return r;
4196 return "";
4199 /*! \brief Get a line from an SDP message body */
4200 static const char *get_sdp(struct sip_request *req, const char *name)
4202 int dummy = 0;
4204 return get_sdp_iterate(&dummy, req, name);
4207 /*! \brief Get a specific line from the message body */
4208 static char *get_body(struct sip_request *req, char *name)
4210 int x;
4211 int len = strlen(name);
4212 char *r;
4214 for (x = 0; x < req->lines; x++) {
4215 r = get_body_by_line(req->line[x], name, len);
4216 if (r[0] != '\0')
4217 return r;
4220 return "";
4223 /*! \brief Find compressed SIP alias */
4224 static const char *find_alias(const char *name, const char *_default)
4226 /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
4227 static const struct cfalias {
4228 char * const fullname;
4229 char * const shortname;
4230 } aliases[] = {
4231 { "Content-Type", "c" },
4232 { "Content-Encoding", "e" },
4233 { "From", "f" },
4234 { "Call-ID", "i" },
4235 { "Contact", "m" },
4236 { "Content-Length", "l" },
4237 { "Subject", "s" },
4238 { "To", "t" },
4239 { "Supported", "k" },
4240 { "Refer-To", "r" },
4241 { "Referred-By", "b" },
4242 { "Allow-Events", "u" },
4243 { "Event", "o" },
4244 { "Via", "v" },
4245 { "Accept-Contact", "a" },
4246 { "Reject-Contact", "j" },
4247 { "Request-Disposition", "d" },
4248 { "Session-Expires", "x" },
4249 { "Identity", "y" },
4250 { "Identity-Info", "n" },
4252 int x;
4254 for (x=0; x<sizeof(aliases) / sizeof(aliases[0]); x++)
4255 if (!strcasecmp(aliases[x].fullname, name))
4256 return aliases[x].shortname;
4258 return _default;
4261 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
4263 int pass;
4266 * Technically you can place arbitrary whitespace both before and after the ':' in
4267 * a header, although RFC3261 clearly says you shouldn't before, and place just
4268 * one afterwards. If you shouldn't do it, what absolute idiot decided it was
4269 * a good idea to say you can do it, and if you can do it, why in the hell would.
4270 * you say you shouldn't.
4271 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
4272 * and we always allow spaces after that for compatibility.
4274 for (pass = 0; name && pass < 2;pass++) {
4275 int x, len = strlen(name);
4276 for (x=*start; x<req->headers; x++) {
4277 if (!strncasecmp(req->header[x], name, len)) {
4278 char *r = req->header[x] + len; /* skip name */
4279 if (pedanticsipchecking)
4280 r = ast_skip_blanks(r);
4282 if (*r == ':') {
4283 *start = x+1;
4284 return ast_skip_blanks(r+1);
4288 if (pass == 0) /* Try aliases */
4289 name = find_alias(name, NULL);
4292 /* Don't return NULL, so get_header is always a valid pointer */
4293 return "";
4296 /*! \brief Get header from SIP request */
4297 static const char *get_header(const struct sip_request *req, const char *name)
4299 int start = 0;
4300 return __get_header(req, name, &start);
4303 /*! \brief Read RTP from network */
4304 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
4306 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
4307 struct ast_frame *f;
4309 if (!p->rtp) {
4310 /* We have no RTP allocated for this channel */
4311 return &ast_null_frame;
4314 switch(ast->fdno) {
4315 case 0:
4316 f = ast_rtp_read(p->rtp); /* RTP Audio */
4317 break;
4318 case 1:
4319 f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
4320 break;
4321 case 2:
4322 f = ast_rtp_read(p->vrtp); /* RTP Video */
4323 break;
4324 case 3:
4325 f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
4326 break;
4327 case 5:
4328 f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
4329 break;
4330 default:
4331 f = &ast_null_frame;
4333 /* Don't forward RFC2833 if we're not supposed to */
4334 if (f && (f->frametype == AST_FRAME_DTMF) &&
4335 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833))
4336 return &ast_null_frame;
4338 /* We already hold the channel lock */
4339 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
4340 return f;
4342 if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
4343 if (!(f->subclass & p->jointcapability)) {
4344 if (option_debug) {
4345 ast_log(LOG_DEBUG, "Bogus frame of format '%s' received from '%s'!\n",
4346 ast_getformatname(f->subclass), p->owner->name);
4348 return &ast_null_frame;
4350 if (option_debug)
4351 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
4352 p->owner->nativeformats = (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
4353 ast_set_read_format(p->owner, p->owner->readformat);
4354 ast_set_write_format(p->owner, p->owner->writeformat);
4357 if (f && (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
4358 f = ast_dsp_process(p->owner, p->vad, f);
4359 if (f && f->frametype == AST_FRAME_DTMF) {
4360 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && f->subclass == 'f') {
4361 if (option_debug)
4362 ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
4363 *faxdetect = 1;
4364 } else if (option_debug) {
4365 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
4370 return f;
4373 /*! \brief Read SIP RTP from channel */
4374 static struct ast_frame *sip_read(struct ast_channel *ast)
4376 struct ast_frame *fr;
4377 struct sip_pvt *p = ast->tech_pvt;
4378 int faxdetected = FALSE;
4380 ast_mutex_lock(&p->lock);
4381 fr = sip_rtp_read(ast, p, &faxdetected);
4382 p->lastrtprx = time(NULL);
4384 /* If we are NOT bridged to another channel, and we have detected fax tone we issue T38 re-invite to a peer */
4385 /* 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 */
4386 if (faxdetected && ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && (p->t38.state == T38_DISABLED) && !(ast_bridged_channel(ast))) {
4387 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
4388 if (!p->pendinginvite) {
4389 if (option_debug > 2)
4390 ast_log(LOG_DEBUG, "Sending reinvite on SIP (%s) for T.38 negotiation.\n",ast->name);
4391 p->t38.state = T38_LOCAL_REINVITE;
4392 transmit_reinvite_with_t38_sdp(p);
4393 if (option_debug > 1)
4394 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, ast->name);
4396 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
4397 if (option_debug > 2)
4398 ast_log(LOG_DEBUG, "Deferring reinvite on SIP (%s) - it will be re-negotiated for T.38\n", ast->name);
4399 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
4403 /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
4404 if (fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
4405 fr = &ast_null_frame;
4408 ast_mutex_unlock(&p->lock);
4409 return fr;
4413 /*! \brief Generate 32 byte random string for callid's etc */
4414 static char *generate_random_string(char *buf, size_t size)
4416 long val[4];
4417 int x;
4419 for (x=0; x<4; x++)
4420 val[x] = ast_random();
4421 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
4423 return buf;
4426 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
4427 static void build_callid_pvt(struct sip_pvt *pvt)
4429 char buf[33];
4431 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip));
4433 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
4437 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
4438 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
4440 char buf[33];
4442 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
4444 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
4447 /*! \brief Make our SIP dialog tag */
4448 static void make_our_tag(char *tagbuf, size_t len)
4450 snprintf(tagbuf, len, "as%08lx", ast_random());
4453 /*! \brief Allocate SIP_PVT structure and set defaults */
4454 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
4455 int useglobal_nat, const int intended_method)
4457 struct sip_pvt *p;
4459 if (!(p = ast_calloc(1, sizeof(*p))))
4460 return NULL;
4462 if (ast_string_field_init(p, 512)) {
4463 free(p);
4464 return NULL;
4467 ast_mutex_init(&p->lock);
4469 p->method = intended_method;
4470 p->initid = -1;
4471 p->waitid = -1;
4472 p->autokillid = -1;
4473 p->subscribed = NONE;
4474 p->stateid = -1;
4475 p->prefs = default_prefs; /* Set default codecs for this call */
4477 if (intended_method != SIP_OPTIONS) /* Peerpoke has it's own system */
4478 p->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
4480 if (sin) {
4481 p->sa = *sin;
4482 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
4483 p->ourip = __ourip;
4484 } else
4485 p->ourip = __ourip;
4487 /* Copy global flags to this PVT at setup. */
4488 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
4489 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
4491 ast_set2_flag(&p->flags[0], !recordhistory, SIP_NO_HISTORY);
4493 p->branch = ast_random();
4494 make_our_tag(p->tag, sizeof(p->tag));
4495 p->ocseq = INITIAL_CSEQ;
4497 if (sip_methods[intended_method].need_rtp) {
4498 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
4499 /* If the global videosupport flag is on, we always create a RTP interface for video */
4500 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
4501 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
4502 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
4503 p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
4504 if (!p->rtp || (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)) {
4505 ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n",
4506 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video" : "", strerror(errno));
4507 ast_mutex_destroy(&p->lock);
4508 if (p->chanvars) {
4509 ast_variables_destroy(p->chanvars);
4510 p->chanvars = NULL;
4512 free(p);
4513 return NULL;
4515 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
4516 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
4517 ast_rtp_settos(p->rtp, global_tos_audio);
4518 ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
4519 ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
4520 ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
4521 if (p->vrtp) {
4522 ast_rtp_settos(p->vrtp, global_tos_video);
4523 ast_rtp_setdtmf(p->vrtp, 0);
4524 ast_rtp_setdtmfcompensate(p->vrtp, 0);
4525 ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
4526 ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
4527 ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
4529 if (p->udptl)
4530 ast_udptl_settos(p->udptl, global_tos_audio);
4531 p->maxcallbitrate = default_maxcallbitrate;
4532 p->autoframing = global_autoframing;
4533 ast_rtp_codec_setpref(p->rtp, &p->prefs);
4536 if (useglobal_nat && sin) {
4537 /* Setup NAT structure according to global settings if we have an address */
4538 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
4539 p->recv = *sin;
4540 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
4543 if (p->method != SIP_REGISTER)
4544 ast_string_field_set(p, fromdomain, default_fromdomain);
4545 build_via(p);
4546 if (!callid)
4547 build_callid_pvt(p);
4548 else
4549 ast_string_field_set(p, callid, callid);
4550 /* Assign default music on hold class */
4551 ast_string_field_set(p, mohinterpret, default_mohinterpret);
4552 ast_string_field_set(p, mohsuggest, default_mohsuggest);
4553 p->capability = global_capability;
4554 p->allowtransfer = global_allowtransfer;
4555 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
4556 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
4557 p->noncodeccapability |= AST_RTP_DTMF;
4558 if (p->udptl) {
4559 p->t38.capability = global_t38_capability;
4560 if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY)
4561 p->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
4562 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_FEC)
4563 p->t38.capability |= T38FAX_UDP_EC_FEC;
4564 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_NONE)
4565 p->t38.capability |= T38FAX_UDP_EC_NONE;
4566 p->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
4567 p->t38.jointcapability = p->t38.capability;
4569 ast_string_field_set(p, context, default_context);
4571 /* Add to active dialog list */
4572 ast_mutex_lock(&iflock);
4573 p->next = iflist;
4574 iflist = p;
4575 ast_mutex_unlock(&iflock);
4576 if (option_debug)
4577 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");
4578 return p;
4581 /*! \brief Connect incoming SIP message to current dialog or create new dialog structure
4582 Called by handle_request, sipsock_read */
4583 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
4585 struct sip_pvt *p = NULL;
4586 char *tag = ""; /* note, tag is never NULL */
4587 char totag[128];
4588 char fromtag[128];
4589 const char *callid = get_header(req, "Call-ID");
4590 const char *from = get_header(req, "From");
4591 const char *to = get_header(req, "To");
4592 const char *cseq = get_header(req, "Cseq");
4594 /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
4595 /* get_header always returns non-NULL so we must use ast_strlen_zero() */
4596 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
4597 ast_strlen_zero(from) || ast_strlen_zero(cseq))
4598 return NULL; /* Invalid packet */
4600 if (pedanticsipchecking) {
4601 /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
4602 we need more to identify a branch - so we have to check branch, from
4603 and to tags to identify a call leg.
4604 For Asterisk to behave correctly, you need to turn on pedanticsipchecking
4605 in sip.conf
4607 if (gettag(req, "To", totag, sizeof(totag)))
4608 ast_set_flag(req, SIP_PKT_WITH_TOTAG); /* Used in handle_request/response */
4609 gettag(req, "From", fromtag, sizeof(fromtag));
4611 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
4613 if (option_debug > 4 )
4614 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);
4617 ast_mutex_lock(&iflock);
4618 for (p = iflist; p; p = p->next) {
4619 /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
4620 int found = FALSE;
4621 if (ast_strlen_zero(p->callid))
4622 continue;
4623 if (req->method == SIP_REGISTER)
4624 found = (!strcmp(p->callid, callid));
4625 else
4626 found = (!strcmp(p->callid, callid) &&
4627 (!pedanticsipchecking || ast_strlen_zero(tag) || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ;
4629 if (option_debug > 4)
4630 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);
4632 /* If we get a new request within an existing to-tag - check the to tag as well */
4633 if (pedanticsipchecking && found && req->method != SIP_RESPONSE) { /* SIP Request */
4634 if (p->tag[0] == '\0' && totag[0]) {
4635 /* We have no to tag, but they have. Wrong dialog */
4636 found = FALSE;
4637 } else if (totag[0]) { /* Both have tags, compare them */
4638 if (strcmp(totag, p->tag)) {
4639 found = FALSE; /* This is not our packet */
4642 if (!found && option_debug > 4)
4643 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);
4647 if (found) {
4648 /* Found the call */
4649 ast_mutex_lock(&p->lock);
4650 ast_mutex_unlock(&iflock);
4651 return p;
4654 ast_mutex_unlock(&iflock);
4656 /* See if the method is capable of creating a dialog */
4657 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
4658 if (intended_method == SIP_REFER) {
4659 /* We do support REFER, but not outside of a dialog yet */
4660 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
4661 } else if (intended_method == SIP_NOTIFY) {
4662 /* We do not support out-of-dialog NOTIFY either,
4663 like voicemail notification, so cancel that early */
4664 transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
4665 } else {
4666 /* Ok, time to create a new SIP dialog object, a pvt */
4667 if ((p = sip_alloc(callid, sin, 1, intended_method))) {
4668 /* Ok, we've created a dialog, let's go and process it */
4669 ast_mutex_lock(&p->lock);
4670 } else {
4671 /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
4672 getting a dialog from sip_alloc.
4674 Without a dialog we can't retransmit and handle ACKs and all that, but at least
4675 send an error message.
4677 Sorry, we apologize for the inconvienience
4679 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
4680 if (option_debug > 3)
4681 ast_log(LOG_DEBUG, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
4684 return p;
4685 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
4686 /* A method we do not support, let's take it on the volley */
4687 transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
4688 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
4689 /* This is a request outside of a dialog that we don't know about
4690 ...never reply to an ACK!
4692 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
4694 /* We do not respond to responses for dialogs that we don't know about, we just drop
4695 the session quickly */
4697 return p;
4700 /*! \brief Parse register=> line in sip.conf and add to registry */
4701 static int sip_register(char *value, int lineno)
4703 struct sip_registry *reg;
4704 int portnum = 0;
4705 char username[256] = "";
4706 char *hostname=NULL, *secret=NULL, *authuser=NULL;
4707 char *porta=NULL;
4708 char *contact=NULL;
4710 if (!value)
4711 return -1;
4712 ast_copy_string(username, value, sizeof(username));
4713 /* First split around the last '@' then parse the two components. */
4714 hostname = strrchr(username, '@'); /* allow @ in the first part */
4715 if (hostname)
4716 *hostname++ = '\0';
4717 if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
4718 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
4719 return -1;
4721 /* split user[:secret[:authuser]] */
4722 secret = strchr(username, ':');
4723 if (secret) {
4724 *secret++ = '\0';
4725 authuser = strchr(secret, ':');
4726 if (authuser)
4727 *authuser++ = '\0';
4729 /* split host[:port][/contact] */
4730 contact = strchr(hostname, '/');
4731 if (contact)
4732 *contact++ = '\0';
4733 if (ast_strlen_zero(contact))
4734 contact = "s";
4735 porta = strchr(hostname, ':');
4736 if (porta) {
4737 *porta++ = '\0';
4738 portnum = atoi(porta);
4739 if (portnum == 0) {
4740 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
4741 return -1;
4744 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
4745 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
4746 return -1;
4749 if (ast_string_field_init(reg, 256)) {
4750 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
4751 free(reg);
4752 return -1;
4755 regobjs++;
4756 ASTOBJ_INIT(reg);
4757 ast_string_field_set(reg, contact, contact);
4758 if (!ast_strlen_zero(username))
4759 ast_string_field_set(reg, username, username);
4760 if (hostname)
4761 ast_string_field_set(reg, hostname, hostname);
4762 if (authuser)
4763 ast_string_field_set(reg, authuser, authuser);
4764 if (secret)
4765 ast_string_field_set(reg, secret, secret);
4766 reg->expire = -1;
4767 reg->timeout = -1;
4768 reg->refresh = default_expiry;
4769 reg->portno = portnum;
4770 reg->callid_valid = FALSE;
4771 reg->ocseq = INITIAL_CSEQ;
4772 ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
4773 ASTOBJ_UNREF(reg,sip_registry_destroy);
4774 return 0;
4777 /*! \brief Parse multiline SIP headers into one header
4778 This is enabled if pedanticsipchecking is enabled */
4779 static int lws2sws(char *msgbuf, int len)
4781 int h = 0, t = 0;
4782 int lws = 0;
4784 for (; h < len;) {
4785 /* Eliminate all CRs */
4786 if (msgbuf[h] == '\r') {
4787 h++;
4788 continue;
4790 /* Check for end-of-line */
4791 if (msgbuf[h] == '\n') {
4792 /* Check for end-of-message */
4793 if (h + 1 == len)
4794 break;
4795 /* Check for a continuation line */
4796 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
4797 /* Merge continuation line */
4798 h++;
4799 continue;
4801 /* Propagate LF and start new line */
4802 msgbuf[t++] = msgbuf[h++];
4803 lws = 0;
4804 continue;
4806 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
4807 if (lws) {
4808 h++;
4809 continue;
4811 msgbuf[t++] = msgbuf[h++];
4812 lws = 1;
4813 continue;
4815 msgbuf[t++] = msgbuf[h++];
4816 if (lws)
4817 lws = 0;
4819 msgbuf[t] = '\0';
4820 return t;
4823 /*! \brief Parse a SIP message
4824 \note this function is used both on incoming and outgoing packets
4826 static int parse_request(struct sip_request *req)
4828 /* Divide fields by NULL's */
4829 char *c;
4830 int f = 0;
4832 c = req->data;
4834 /* First header starts immediately */
4835 req->header[f] = c;
4836 while(*c) {
4837 if (*c == '\n') {
4838 /* We've got a new header */
4839 *c = 0;
4841 if (sipdebug && option_debug > 3)
4842 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
4843 if (ast_strlen_zero(req->header[f])) {
4844 /* Line by itself means we're now in content */
4845 c++;
4846 break;
4848 if (f >= SIP_MAX_HEADERS - 1) {
4849 ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n");
4850 } else
4851 f++;
4852 req->header[f] = c + 1;
4853 } else if (*c == '\r') {
4854 /* Ignore but eliminate \r's */
4855 *c = 0;
4857 c++;
4859 /* Check for last header */
4860 if (!ast_strlen_zero(req->header[f])) {
4861 if (sipdebug && option_debug > 3)
4862 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
4863 f++;
4865 req->headers = f;
4866 /* Now we process any mime content */
4867 f = 0;
4868 req->line[f] = c;
4869 while(*c) {
4870 if (*c == '\n') {
4871 /* We've got a new line */
4872 *c = 0;
4873 if (sipdebug && option_debug > 3)
4874 ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
4875 if (f >= SIP_MAX_LINES - 1) {
4876 ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n");
4877 } else
4878 f++;
4879 req->line[f] = c + 1;
4880 } else if (*c == '\r') {
4881 /* Ignore and eliminate \r's */
4882 *c = 0;
4884 c++;
4886 /* Check for last line */
4887 if (!ast_strlen_zero(req->line[f]))
4888 f++;
4889 req->lines = f;
4890 if (*c)
4891 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
4892 /* Split up the first line parts */
4893 return determine_firstline_parts(req);
4897 \brief Determine whether a SIP message contains an SDP in its body
4898 \param req the SIP request to process
4899 \return 1 if SDP found, 0 if not found
4901 Also updates req->sdp_start and req->sdp_end to indicate where the SDP
4902 lives in the message body.
4904 static int find_sdp(struct sip_request *req)
4906 const char *content_type;
4907 const char *content_length;
4908 const char *search;
4909 char *boundary;
4910 unsigned int x;
4911 int boundaryisquoted = FALSE;
4912 int found_application_sdp = FALSE;
4913 int found_end_of_headers = FALSE;
4915 content_length = get_header(req, "Content-Length");
4917 if (!ast_strlen_zero(content_length)) {
4918 if (sscanf(content_length, "%ud", &x) != 1) {
4919 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
4920 return 0;
4923 /* Content-Length of zero means there can't possibly be an
4924 SDP here, even if the Content-Type says there is */
4925 if (x == 0)
4926 return 0;
4929 content_type = get_header(req, "Content-Type");
4931 /* if the body contains only SDP, this is easy */
4932 if (!strncasecmp(content_type, "application/sdp", 15)) {
4933 req->sdp_start = 0;
4934 req->sdp_end = req->lines;
4935 return req->lines ? 1 : 0;
4938 /* if it's not multipart/mixed, there cannot be an SDP */
4939 if (strncasecmp(content_type, "multipart/mixed", 15))
4940 return 0;
4942 /* if there is no boundary marker, it's invalid */
4943 if ((search = strcasestr(content_type, ";boundary=")))
4944 search += 10;
4945 else if ((search = strcasestr(content_type, "; boundary=")))
4946 search += 11;
4947 else
4948 return 0;
4950 if (ast_strlen_zero(search))
4951 return 0;
4953 /* If the boundary is quoted with ", remove quote */
4954 if (*search == '\"') {
4955 search++;
4956 boundaryisquoted = TRUE;
4959 /* make a duplicate of the string, with two extra characters
4960 at the beginning */
4961 boundary = ast_strdupa(search - 2);
4962 boundary[0] = boundary[1] = '-';
4963 /* Remove final quote */
4964 if (boundaryisquoted)
4965 boundary[strlen(boundary) - 1] = '\0';
4967 /* search for the boundary marker, the empty line delimiting headers from
4968 sdp part and the end boundry if it exists */
4970 for (x = 0; x < (req->lines ); x++) {
4971 if(!strncasecmp(req->line[x], boundary, strlen(boundary))){
4972 if(found_application_sdp && found_end_of_headers){
4973 req->sdp_end = x-1;
4974 return 1;
4976 found_application_sdp = FALSE;
4978 if(!strcasecmp(req->line[x], "Content-Type: application/sdp"))
4979 found_application_sdp = TRUE;
4981 if(strlen(req->line[x]) == 0 ){
4982 if(found_application_sdp && !found_end_of_headers){
4983 req->sdp_start = x;
4984 found_end_of_headers = TRUE;
4988 if(found_application_sdp && found_end_of_headers) {
4989 req->sdp_end = x;
4990 return TRUE;
4992 return FALSE;
4995 /*! \brief Change hold state for a call */
4996 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
4998 if (global_notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
4999 sip_peer_hold(dialog, holdstate);
5000 if (global_callevents)
5001 manager_event(EVENT_FLAG_CALL, holdstate ? "Hold" : "Unhold",
5002 "Channel: %s\r\n"
5003 "Uniqueid: %s\r\n",
5004 dialog->owner->name,
5005 dialog->owner->uniqueid);
5006 append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data);
5007 if (!holdstate) { /* Put off remote hold */
5008 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
5009 return;
5011 /* No address for RTP, we're on hold */
5013 if (sendonly == 1) /* One directional hold (sendonly/recvonly) */
5014 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
5015 else if (sendonly == 2) /* Inactive stream */
5016 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
5017 else
5018 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
5019 return;
5022 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
5023 If offer is rejected, we will not change any properties of the call
5024 Return 0 on success, a negative value on errors.
5025 Must be called after find_sdp().
5027 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
5029 const char *m; /* SDP media offer */
5030 const char *c;
5031 const char *a;
5032 char host[258];
5033 int len = -1;
5034 int portno = -1; /*!< RTP Audio port number */
5035 int vportno = -1; /*!< RTP Video port number */
5036 int udptlportno = -1;
5037 int peert38capability = 0;
5038 char s[256];
5039 int old = 0;
5041 /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
5042 int peercapability = 0, peernoncodeccapability = 0;
5043 int vpeercapability = 0, vpeernoncodeccapability = 0;
5044 struct sockaddr_in sin; /*!< media socket address */
5045 struct sockaddr_in vsin; /*!< Video socket address */
5047 const char *codecs;
5048 struct hostent *hp; /*!< RTP Audio host IP */
5049 struct hostent *vhp = NULL; /*!< RTP video host IP */
5050 struct ast_hostent audiohp;
5051 struct ast_hostent videohp;
5052 int codec;
5053 int destiterator = 0;
5054 int iterator;
5055 int sendonly = -1;
5056 int numberofports;
5057 struct ast_rtp *newaudiortp, *newvideortp; /* Buffers for codec handling */
5058 int newjointcapability; /* Negotiated capability */
5059 int newpeercapability;
5060 int newnoncodeccapability;
5061 int numberofmediastreams = 0;
5062 int debug = sip_debug_test_pvt(p);
5064 int found_rtpmap_codecs[SDP_MAX_RTPMAP_CODECS];
5065 int last_rtpmap_codec=0;
5067 if (!p->rtp) {
5068 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
5069 return -1;
5072 /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
5073 #ifdef LOW_MEMORY
5074 newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
5075 #else
5076 newaudiortp = alloca(ast_rtp_alloc_size());
5077 #endif
5078 memset(newaudiortp, 0, ast_rtp_alloc_size());
5079 ast_rtp_new_init(newaudiortp);
5080 ast_rtp_pt_clear(newaudiortp);
5082 #ifdef LOW_MEMORY
5083 newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
5084 #else
5085 newvideortp = alloca(ast_rtp_alloc_size());
5086 #endif
5087 memset(newvideortp, 0, ast_rtp_alloc_size());
5088 ast_rtp_new_init(newvideortp);
5089 ast_rtp_pt_clear(newvideortp);
5091 /* Update our last rtprx when we receive an SDP, too */
5092 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
5095 /* Try to find first media stream */
5096 m = get_sdp(req, "m");
5097 destiterator = req->sdp_start;
5098 c = get_sdp_iterate(&destiterator, req, "c");
5099 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
5100 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
5101 return -1;
5104 /* Check for IPv4 address (not IPv6 yet) */
5105 if (sscanf(c, "IN IP4 %256s", host) != 1) {
5106 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
5107 return -1;
5110 /* XXX This could block for a long time, and block the main thread! XXX */
5111 hp = ast_gethostbyname(host, &audiohp);
5112 if (!hp) {
5113 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
5114 return -1;
5116 vhp = hp; /* Copy to video address as default too */
5118 iterator = req->sdp_start;
5119 ast_set_flag(&p->flags[0], SIP_NOVIDEO);
5122 /* Find media streams in this SDP offer */
5123 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
5124 int x;
5125 int audio = FALSE;
5127 numberofports = 1;
5128 if ((sscanf(m, "audio %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
5129 (sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
5130 audio = TRUE;
5131 numberofmediastreams++;
5132 /* Found audio stream in this media definition */
5133 portno = x;
5134 /* Scan through the RTP payload types specified in a "m=" line: */
5135 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
5136 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
5137 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
5138 return -1;
5140 if (debug)
5141 ast_verbose("Found RTP audio format %d\n", codec);
5142 ast_rtp_set_m_type(newaudiortp, codec);
5144 } else if ((sscanf(m, "video %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
5145 (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
5146 /* If it is not audio - is it video ? */
5147 ast_clear_flag(&p->flags[0], SIP_NOVIDEO);
5148 numberofmediastreams++;
5149 vportno = x;
5150 /* Scan through the RTP payload types specified in a "m=" line: */
5151 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
5152 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
5153 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
5154 return -1;
5156 if (debug)
5157 ast_verbose("Found RTP video format %d\n", codec);
5158 ast_rtp_set_m_type(newvideortp, codec);
5160 } else if (p->udptl && ( (sscanf(m, "image %d udptl t38%n", &x, &len) == 1) ||
5161 (sscanf(m, "image %d UDPTL t38%n", &x, &len) == 1) )) {
5162 if (debug)
5163 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
5164 udptlportno = x;
5165 numberofmediastreams++;
5167 if (p->owner && p->lastinvite) {
5168 p->t38.state = T38_PEER_REINVITE; /* T38 Offered in re-invite from remote party */
5169 if (option_debug > 1)
5170 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>" );
5171 } else {
5172 p->t38.state = T38_PEER_DIRECT; /* T38 Offered directly from peer in first invite */
5173 if (option_debug > 1)
5174 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
5176 } else
5177 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
5178 if (numberofports > 1)
5179 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
5182 /* Check for Media-description-level-address for audio */
5183 c = get_sdp_iterate(&destiterator, req, "c");
5184 if (!ast_strlen_zero(c)) {
5185 if (sscanf(c, "IN IP4 %256s", host) != 1) {
5186 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
5187 } else {
5188 /* XXX This could block for a long time, and block the main thread! XXX */
5189 if (audio) {
5190 if ( !(hp = ast_gethostbyname(host, &audiohp))) {
5191 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in secondary c= line, '%s'\n", c);
5192 return -2;
5194 } else if (!(vhp = ast_gethostbyname(host, &videohp))) {
5195 ast_log(LOG_WARNING, "Unable to lookup RTP video host in secondary c= line, '%s'\n", c);
5196 return -2;
5202 if (portno == -1 && vportno == -1 && udptlportno == -1)
5203 /* No acceptable offer found in SDP - we have no ports */
5204 /* Do not change RTP or VRTP if this is a re-invite */
5205 return -2;
5207 if (numberofmediastreams > 2)
5208 /* We have too many fax, audio and/or video media streams, fail this offer */
5209 return -3;
5211 /* RTP addresses and ports for audio and video */
5212 sin.sin_family = AF_INET;
5213 vsin.sin_family = AF_INET;
5214 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
5215 if (vhp)
5216 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
5218 /* Setup UDPTL port number */
5219 if (p->udptl) {
5220 if (udptlportno > 0) {
5221 sin.sin_port = htons(udptlportno);
5222 if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
5223 struct sockaddr_in peer;
5224 ast_rtp_get_peer(p->rtp, &peer);
5225 if (peer.sin_addr.s_addr) {
5226 memcpy(&sin.sin_addr, &peer.sin_addr, sizeof(&sin.sin_addr));
5227 if (debug) {
5228 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));
5232 ast_udptl_set_peer(p->udptl, &sin);
5233 if (debug)
5234 ast_log(LOG_DEBUG,"Peer T.38 UDPTL is at port %s:%d\n",ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
5235 } else {
5236 ast_udptl_stop(p->udptl);
5237 if (debug)
5238 ast_log(LOG_DEBUG, "Peer doesn't provide T.38 UDPTL\n");
5243 if (p->rtp) {
5244 if (portno > 0) {
5245 sin.sin_port = htons(portno);
5246 ast_rtp_set_peer(p->rtp, &sin);
5247 if (debug)
5248 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
5249 } else {
5250 if (udptlportno > 0) {
5251 if (debug)
5252 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session. Callid %s\n", p->callid);
5253 } else {
5254 ast_rtp_stop(p->rtp);
5255 if (debug)
5256 ast_verbose("Peer doesn't provide audio. Callid %s\n", p->callid);
5260 /* Setup video port number */
5261 if (vportno != -1)
5262 vsin.sin_port = htons(vportno);
5264 /* Next, scan through each "a=rtpmap:" line, noting each
5265 * specified RTP payload type (with corresponding MIME subtype):
5267 /* XXX This needs to be done per media stream, since it's media stream specific */
5268 iterator = req->sdp_start;
5269 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
5270 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
5271 if (option_debug > 1) {
5272 int breakout = FALSE;
5274 /* If we're debugging, check for unsupported sdp options */
5275 if (!strncasecmp(a, "rtcp:", (size_t) 5)) {
5276 if (debug)
5277 ast_verbose("Got unsupported a:rtcp in SDP offer \n");
5278 breakout = TRUE;
5279 } else if (!strncasecmp(a, "fmtp:", (size_t) 5)) {
5280 /* Format parameters: Not supported */
5281 /* Note: This is used for codec parameters, like bitrate for
5282 G722 and video formats for H263 and H264
5283 See RFC2327 for an example */
5284 if (debug)
5285 ast_verbose("Got unsupported a:fmtp in SDP offer \n");
5286 breakout = TRUE;
5287 } else if (!strncasecmp(a, "framerate:", (size_t) 10)) {
5288 /* Video stuff: Not supported */
5289 if (debug)
5290 ast_verbose("Got unsupported a:framerate in SDP offer \n");
5291 breakout = TRUE;
5292 } else if (!strncasecmp(a, "maxprate:", (size_t) 9)) {
5293 /* Video stuff: Not supported */
5294 if (debug)
5295 ast_verbose("Got unsupported a:maxprate in SDP offer \n");
5296 breakout = TRUE;
5297 } else if (!strncasecmp(a, "crypto:", (size_t) 7)) {
5298 /* SRTP stuff, not yet supported */
5299 if (debug)
5300 ast_verbose("Got unsupported a:crypto in SDP offer \n");
5301 breakout = TRUE;
5303 if (breakout) /* We have a match, skip to next header */
5304 continue;
5306 if (!strcasecmp(a, "sendonly")) {
5307 if (sendonly == -1)
5308 sendonly = 1;
5309 continue;
5310 } else if (!strcasecmp(a, "inactive")) {
5311 if (sendonly == -1)
5312 sendonly = 2;
5313 continue;
5314 } else if (!strcasecmp(a, "sendrecv")) {
5315 if (sendonly == -1)
5316 sendonly = 0;
5317 continue;
5318 } else if (strlen(a) > 5 && !strncasecmp(a, "ptime", 5)) {
5319 char *tmp = strrchr(a, ':');
5320 long int framing = 0;
5321 if (tmp) {
5322 tmp++;
5323 framing = strtol(tmp, NULL, 10);
5324 if (framing == LONG_MIN || framing == LONG_MAX) {
5325 framing = 0;
5326 if (option_debug)
5327 ast_log(LOG_DEBUG, "Can't read framing from SDP: %s\n", a);
5330 if (framing && p->autoframing) {
5331 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
5332 int codec_n;
5333 int format = 0;
5334 for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
5335 format = ast_rtp_codec_getformat(codec_n);
5336 if (!format) /* non-codec or not found */
5337 continue;
5338 if (option_debug)
5339 ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
5340 ast_codec_pref_setsize(pref, format, framing);
5342 ast_rtp_codec_setpref(p->rtp, pref);
5344 continue;
5345 } else if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) == 2) {
5346 /* We have a rtpmap to handle */
5347 int found = FALSE;
5348 /* We should propably check if this is an audio or video codec
5349 so we know where to look */
5351 if (last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
5352 /* Note: should really look at the 'freq' and '#chans' params too */
5353 if(ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
5354 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0) != -1) {
5355 if (debug)
5356 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
5357 found_rtpmap_codecs[last_rtpmap_codec] = codec;
5358 last_rtpmap_codec++;
5359 found = TRUE;
5361 } else if (p->vrtp) {
5362 if(ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0) != -1) {
5363 if (debug)
5364 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
5365 found_rtpmap_codecs[last_rtpmap_codec] = codec;
5366 last_rtpmap_codec++;
5367 found = TRUE;
5370 } else {
5371 if (debug)
5372 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
5375 if (!found) {
5376 /* Remove this codec since it's an unknown media type for us */
5377 /* XXX This is buggy since the media line for audio and video can have the
5378 same numbers. We need to check as described above, but for testing this works... */
5379 ast_rtp_unset_m_type(newaudiortp, codec);
5380 ast_rtp_unset_m_type(newvideortp, codec);
5381 if (debug)
5382 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
5387 if (udptlportno != -1) {
5388 int found = 0, x;
5390 old = 0;
5392 /* Scan trough the a= lines for T38 attributes and set apropriate fileds */
5393 iterator = req->sdp_start;
5394 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
5395 if ((sscanf(a, "T38FaxMaxBuffer:%d", &x) == 1)) {
5396 found = 1;
5397 if (option_debug > 2)
5398 ast_log(LOG_DEBUG, "MaxBufferSize:%d\n",x);
5399 } else if ((sscanf(a, "T38MaxBitRate:%d", &x) == 1)) {
5400 found = 1;
5401 if (option_debug > 2)
5402 ast_log(LOG_DEBUG,"T38MaxBitRate: %d\n",x);
5403 switch (x) {
5404 case 14400:
5405 peert38capability |= T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5406 break;
5407 case 12000:
5408 peert38capability |= T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5409 break;
5410 case 9600:
5411 peert38capability |= T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5412 break;
5413 case 7200:
5414 peert38capability |= T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5415 break;
5416 case 4800:
5417 peert38capability |= T38FAX_RATE_4800 | T38FAX_RATE_2400;
5418 break;
5419 case 2400:
5420 peert38capability |= T38FAX_RATE_2400;
5421 break;
5423 } else if ((sscanf(a, "T38FaxVersion:%d", &x) == 1)) {
5424 found = 1;
5425 if (option_debug > 2)
5426 ast_log(LOG_DEBUG, "FaxVersion: %d\n",x);
5427 if (x == 0)
5428 peert38capability |= T38FAX_VERSION_0;
5429 else if (x == 1)
5430 peert38capability |= T38FAX_VERSION_1;
5431 } else if ((sscanf(a, "T38FaxMaxDatagram:%d", &x) == 1)) {
5432 found = 1;
5433 if (option_debug > 2)
5434 ast_log(LOG_DEBUG, "FaxMaxDatagram: %d\n",x);
5435 ast_udptl_set_far_max_datagram(p->udptl, x);
5436 ast_udptl_set_local_max_datagram(p->udptl, x);
5437 } else if ((sscanf(a, "T38FaxFillBitRemoval:%d", &x) == 1)) {
5438 found = 1;
5439 if (option_debug > 2)
5440 ast_log(LOG_DEBUG, "FillBitRemoval: %d\n",x);
5441 if (x == 1)
5442 peert38capability |= T38FAX_FILL_BIT_REMOVAL;
5443 } else if ((sscanf(a, "T38FaxTranscodingMMR:%d", &x) == 1)) {
5444 found = 1;
5445 if (option_debug > 2)
5446 ast_log(LOG_DEBUG, "Transcoding MMR: %d\n",x);
5447 if (x == 1)
5448 peert38capability |= T38FAX_TRANSCODING_MMR;
5450 if ((sscanf(a, "T38FaxTranscodingJBIG:%d", &x) == 1)) {
5451 found = 1;
5452 if (option_debug > 2)
5453 ast_log(LOG_DEBUG, "Transcoding JBIG: %d\n",x);
5454 if (x == 1)
5455 peert38capability |= T38FAX_TRANSCODING_JBIG;
5456 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
5457 found = 1;
5458 if (option_debug > 2)
5459 ast_log(LOG_DEBUG, "RateManagement: %s\n", s);
5460 if (!strcasecmp(s, "localTCF"))
5461 peert38capability |= T38FAX_RATE_MANAGEMENT_LOCAL_TCF;
5462 else if (!strcasecmp(s, "transferredTCF"))
5463 peert38capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
5464 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
5465 found = 1;
5466 if (option_debug > 2)
5467 ast_log(LOG_DEBUG, "UDP EC: %s\n", s);
5468 if (!strcasecmp(s, "t38UDPRedundancy")) {
5469 peert38capability |= T38FAX_UDP_EC_REDUNDANCY;
5470 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
5471 } else if (!strcasecmp(s, "t38UDPFEC")) {
5472 peert38capability |= T38FAX_UDP_EC_FEC;
5473 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
5474 } else {
5475 peert38capability |= T38FAX_UDP_EC_NONE;
5476 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
5480 if (found) { /* Some cisco equipment returns nothing beside c= and m= lines in 200 OK T38 SDP */
5481 p->t38.peercapability = peert38capability;
5482 p->t38.jointcapability = (peert38capability & 255); /* Put everything beside supported speeds settings */
5483 peert38capability &= (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400);
5484 p->t38.jointcapability |= (peert38capability & p->t38.capability); /* Put the lower of our's and peer's speed */
5486 if (debug)
5487 ast_log(LOG_DEBUG, "Our T38 capability = (%d), peer T38 capability (%d), joint T38 capability (%d)\n",
5488 p->t38.capability,
5489 p->t38.peercapability,
5490 p->t38.jointcapability);
5491 } else {
5492 p->t38.state = T38_DISABLED;
5493 if (option_debug > 2)
5494 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
5497 /* Now gather all of the codecs that we are asked for: */
5498 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
5499 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
5501 newjointcapability = p->capability & (peercapability | vpeercapability);
5502 newpeercapability = (peercapability | vpeercapability);
5503 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
5506 if (debug) {
5507 /* shame on whoever coded this.... */
5508 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE];
5510 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
5511 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
5512 ast_getformatname_multiple(s2, SIPBUFSIZE, newpeercapability),
5513 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
5514 ast_getformatname_multiple(s4, SIPBUFSIZE, newjointcapability));
5516 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
5517 ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
5518 ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
5519 ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
5521 if (!newjointcapability) {
5522 /* If T.38 was not negotiated either, totally bail out... */
5523 if (!p->t38.jointcapability || !udptlportno) {
5524 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
5525 /* Do NOT Change current setting */
5526 return -1;
5527 } else {
5528 if (option_debug > 2)
5529 ast_log(LOG_DEBUG, "Have T.38 but no audio codecs, accepting offer anyway\n");
5530 return 0;
5534 /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
5535 they are acceptable */
5536 p->jointcapability = newjointcapability; /* Our joint codec profile for this call */
5537 p->peercapability = newpeercapability; /* The other sides capability in latest offer */
5538 p->jointnoncodeccapability = newnoncodeccapability; /* DTMF capabilities */
5540 ast_rtp_pt_copy(p->rtp, newaudiortp);
5541 if (p->vrtp)
5542 ast_rtp_pt_copy(p->vrtp, newvideortp);
5544 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
5545 ast_clear_flag(&p->flags[0], SIP_DTMF);
5546 if (newnoncodeccapability & AST_RTP_DTMF) {
5547 /* XXX Would it be reasonable to drop the DSP at this point? XXX */
5548 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
5549 /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
5550 ast_rtp_setdtmf(p->rtp, 1);
5551 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
5552 } else {
5553 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
5557 /* Setup audio port number */
5558 if (p->rtp && sin.sin_port) {
5559 ast_rtp_set_peer(p->rtp, &sin);
5560 if (debug)
5561 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
5564 /* Setup video port number */
5565 if (p->vrtp && vsin.sin_port) {
5566 ast_rtp_set_peer(p->vrtp, &vsin);
5567 if (debug)
5568 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
5571 /* Ok, we're going with this offer */
5572 if (option_debug > 1) {
5573 char buf[SIPBUFSIZE];
5574 ast_log(LOG_DEBUG, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
5577 if (!p->owner) /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
5578 return 0;
5580 if (option_debug > 3)
5581 ast_log(LOG_DEBUG, "We have an owner, now see if we need to change this call\n");
5583 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
5584 if (debug) {
5585 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
5586 ast_log(LOG_DEBUG, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
5587 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
5588 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
5590 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability);
5591 ast_set_read_format(p->owner, p->owner->readformat);
5592 ast_set_write_format(p->owner, p->owner->writeformat);
5595 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
5596 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
5597 /* Activate a re-invite */
5598 ast_queue_frame(p->owner, &ast_null_frame);
5599 } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
5600 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
5601 S_OR(p->mohsuggest, NULL),
5602 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
5603 if (sendonly)
5604 ast_rtp_stop(p->rtp);
5605 /* RTCP needs to go ahead, even if we're on hold!!! */
5606 /* Activate a re-invite */
5607 ast_queue_frame(p->owner, &ast_null_frame);
5610 /* Manager Hold and Unhold events must be generated, if necessary */
5611 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1))
5612 change_hold_state(p, req, FALSE, sendonly);
5613 else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1))
5614 change_hold_state(p, req, TRUE, sendonly);
5615 return 0;
5618 #ifdef LOW_MEMORY
5619 static void ts_ast_rtp_destroy(void *data)
5621 struct ast_rtp *tmp = data;
5622 ast_rtp_destroy(tmp);
5624 #endif
5626 /*! \brief Add header to SIP message */
5627 static int add_header(struct sip_request *req, const char *var, const char *value)
5629 int maxlen = sizeof(req->data) - 4 - req->len; /* 4 bytes are for two \r\n ? */
5631 if (req->headers == SIP_MAX_HEADERS) {
5632 ast_log(LOG_WARNING, "Out of SIP header space\n");
5633 return -1;
5636 if (req->lines) {
5637 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
5638 return -1;
5641 if (maxlen <= 0) {
5642 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
5643 return -1;
5646 req->header[req->headers] = req->data + req->len;
5648 if (compactheaders)
5649 var = find_alias(var, var);
5651 snprintf(req->header[req->headers], maxlen, "%s: %s\r\n", var, value);
5652 req->len += strlen(req->header[req->headers]);
5653 req->headers++;
5655 return 0;
5658 /*! \brief Add 'Content-Length' header to SIP message */
5659 static int add_header_contentLength(struct sip_request *req, int len)
5661 char clen[10];
5663 snprintf(clen, sizeof(clen), "%d", len);
5664 return add_header(req, "Content-Length", clen);
5667 /*! \brief Add content (not header) to SIP message */
5668 static int add_line(struct sip_request *req, const char *line)
5670 if (req->lines == SIP_MAX_LINES) {
5671 ast_log(LOG_WARNING, "Out of SIP line space\n");
5672 return -1;
5674 if (!req->lines) {
5675 /* Add extra empty return */
5676 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
5677 req->len += strlen(req->data + req->len);
5679 if (req->len >= sizeof(req->data) - 4) {
5680 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
5681 return -1;
5683 req->line[req->lines] = req->data + req->len;
5684 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
5685 req->len += strlen(req->line[req->lines]);
5686 req->lines++;
5687 return 0;
5690 /*! \brief Copy one header field from one request to another */
5691 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
5693 const char *tmp = get_header(orig, field);
5695 if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
5696 return add_header(req, field, tmp);
5697 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
5698 return -1;
5701 /*! \brief Copy all headers from one request to another */
5702 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
5704 int start = 0;
5705 int copied = 0;
5706 for (;;) {
5707 const char *tmp = __get_header(orig, field, &start);
5709 if (ast_strlen_zero(tmp))
5710 break;
5711 /* Add what we're responding to */
5712 add_header(req, field, tmp);
5713 copied++;
5715 return copied ? 0 : -1;
5718 /*! \brief Copy SIP VIA Headers from the request to the response
5719 \note If the client indicates that it wishes to know the port we received from,
5720 it adds ;rport without an argument to the topmost via header. We need to
5721 add the port number (from our point of view) to that parameter.
5722 We always add ;received=<ip address> to the topmost via header.
5723 Received: RFC 3261, rport RFC 3581 */
5724 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
5726 int copied = 0;
5727 int start = 0;
5729 for (;;) {
5730 char new[512];
5731 const char *oh = __get_header(orig, field, &start);
5733 if (ast_strlen_zero(oh))
5734 break;
5736 if (!copied) { /* Only check for empty rport in topmost via header */
5737 char leftmost[512], *others, *rport;
5739 /* Only work on leftmost value */
5740 ast_copy_string(leftmost, oh, sizeof(leftmost));
5741 others = strchr(leftmost, ',');
5742 if (others)
5743 *others++ = '\0';
5745 /* Find ;rport; (empty request) */
5746 rport = strstr(leftmost, ";rport");
5747 if (rport && *(rport+6) == '=')
5748 rport = NULL; /* We already have a parameter to rport */
5750 /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting) */
5751 if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
5752 /* We need to add received port - rport */
5753 char *end;
5755 rport = strstr(leftmost, ";rport");
5757 if (rport) {
5758 end = strchr(rport + 1, ';');
5759 if (end)
5760 memmove(rport, end, strlen(end) + 1);
5761 else
5762 *rport = '\0';
5765 /* Add rport to first VIA header if requested */
5766 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
5767 leftmost, ast_inet_ntoa(p->recv.sin_addr),
5768 ntohs(p->recv.sin_port),
5769 others ? "," : "", others ? others : "");
5770 } else {
5771 /* We should *always* add a received to the topmost via */
5772 snprintf(new, sizeof(new), "%s;received=%s%s%s",
5773 leftmost, ast_inet_ntoa(p->recv.sin_addr),
5774 others ? "," : "", others ? others : "");
5776 oh = new; /* the header to copy */
5777 } /* else add the following via headers untouched */
5778 add_header(req, field, oh);
5779 copied++;
5781 if (!copied) {
5782 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
5783 return -1;
5785 return 0;
5788 /*! \brief Add route header into request per learned route */
5789 static void add_route(struct sip_request *req, struct sip_route *route)
5791 char r[SIPBUFSIZE*2], *p;
5792 int n, rem = sizeof(r);
5794 if (!route)
5795 return;
5797 p = r;
5798 for (;route ; route = route->next) {
5799 n = strlen(route->hop);
5800 if (rem < n+3) /* we need room for ",<route>" */
5801 break;
5802 if (p != r) { /* add a separator after fist route */
5803 *p++ = ',';
5804 --rem;
5806 *p++ = '<';
5807 ast_copy_string(p, route->hop, rem); /* cannot fail */
5808 p += n;
5809 *p++ = '>';
5810 rem -= (n+2);
5812 *p = '\0';
5813 add_header(req, "Route", r);
5816 /*! \brief Set destination from SIP URI */
5817 static void set_destination(struct sip_pvt *p, char *uri)
5819 char *h, *maddr, hostname[256];
5820 int port, hn;
5821 struct hostent *hp;
5822 struct ast_hostent ahp;
5823 int debug=sip_debug_test_pvt(p);
5825 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
5826 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
5828 if (debug)
5829 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
5831 /* Find and parse hostname */
5832 h = strchr(uri, '@');
5833 if (h)
5834 ++h;
5835 else {
5836 h = uri;
5837 if (strncasecmp(h, "sip:", 4) == 0)
5838 h += 4;
5839 else if (strncasecmp(h, "sips:", 5) == 0)
5840 h += 5;
5842 hn = strcspn(h, ":;>") + 1;
5843 if (hn > sizeof(hostname))
5844 hn = sizeof(hostname);
5845 ast_copy_string(hostname, h, hn);
5846 /* XXX bug here if string has been trimmed to sizeof(hostname) */
5847 h += hn - 1;
5849 /* Is "port" present? if not default to STANDARD_SIP_PORT */
5850 if (*h == ':') {
5851 /* Parse port */
5852 ++h;
5853 port = strtol(h, &h, 10);
5855 else
5856 port = STANDARD_SIP_PORT;
5858 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
5859 maddr = strstr(h, "maddr=");
5860 if (maddr) {
5861 maddr += 6;
5862 hn = strspn(maddr, "0123456789.") + 1;
5863 if (hn > sizeof(hostname))
5864 hn = sizeof(hostname);
5865 ast_copy_string(hostname, maddr, hn);
5868 hp = ast_gethostbyname(hostname, &ahp);
5869 if (hp == NULL) {
5870 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
5871 return;
5873 p->sa.sin_family = AF_INET;
5874 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
5875 p->sa.sin_port = htons(port);
5876 if (debug)
5877 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
5880 /*! \brief Initialize SIP response, based on SIP request */
5881 static int init_resp(struct sip_request *resp, const char *msg)
5883 /* Initialize a response */
5884 memset(resp, 0, sizeof(*resp));
5885 resp->method = SIP_RESPONSE;
5886 resp->header[0] = resp->data;
5887 snprintf(resp->header[0], sizeof(resp->data), "SIP/2.0 %s\r\n", msg);
5888 resp->len = strlen(resp->header[0]);
5889 resp->headers++;
5890 return 0;
5893 /*! \brief Initialize SIP request */
5894 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
5896 /* Initialize a request */
5897 memset(req, 0, sizeof(*req));
5898 req->method = sipmethod;
5899 req->header[0] = req->data;
5900 snprintf(req->header[0], sizeof(req->data), "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
5901 req->len = strlen(req->header[0]);
5902 req->headers++;
5903 return 0;
5907 /*! \brief Prepare SIP response packet */
5908 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
5910 char newto[256];
5911 const char *ot;
5913 init_resp(resp, msg);
5914 copy_via_headers(p, resp, req, "Via");
5915 if (msg[0] == '1' || msg[0] == '2')
5916 copy_all_header(resp, req, "Record-Route");
5917 copy_header(resp, req, "From");
5918 ot = get_header(req, "To");
5919 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
5920 /* Add the proper tag if we don't have it already. If they have specified
5921 their tag, use it. Otherwise, use our own tag */
5922 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
5923 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
5924 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
5925 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
5926 else
5927 ast_copy_string(newto, ot, sizeof(newto));
5928 ot = newto;
5930 add_header(resp, "To", ot);
5931 copy_header(resp, req, "Call-ID");
5932 copy_header(resp, req, "CSeq");
5933 if (!ast_strlen_zero(global_useragent))
5934 add_header(resp, "User-Agent", global_useragent);
5935 add_header(resp, "Allow", ALLOWED_METHODS);
5936 add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
5937 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
5938 /* For registration responses, we also need expiry and
5939 contact info */
5940 char tmp[256];
5942 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
5943 add_header(resp, "Expires", tmp);
5944 if (p->expiry) { /* Only add contact if we have an expiry time */
5945 char contact[SIPBUFSIZE];
5946 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
5947 add_header(resp, "Contact", contact); /* Not when we unregister */
5949 } else if (msg[0] != '4' && !ast_strlen_zero(p->our_contact)) {
5950 add_header(resp, "Contact", p->our_contact);
5952 return 0;
5955 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
5956 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
5958 struct sip_request *orig = &p->initreq;
5959 char stripped[80];
5960 char tmp[80];
5961 char newto[256];
5962 const char *c;
5963 const char *ot, *of;
5964 int is_strict = FALSE; /*!< Strict routing flag */
5966 memset(req, 0, sizeof(struct sip_request));
5968 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
5970 if (!seqno) {
5971 p->ocseq++;
5972 seqno = p->ocseq;
5975 if (newbranch) {
5976 p->branch ^= ast_random();
5977 build_via(p);
5980 /* Check for strict or loose router */
5981 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop,";lr") == NULL) {
5982 is_strict = TRUE;
5983 if (sipdebug)
5984 ast_log(LOG_DEBUG, "Strict routing enforced for session %s\n", p->callid);
5987 if (sipmethod == SIP_CANCEL)
5988 c = p->initreq.rlPart2; /* Use original URI */
5989 else if (sipmethod == SIP_ACK) {
5990 /* Use URI from Contact: in 200 OK (if INVITE)
5991 (we only have the contacturi on INVITEs) */
5992 if (!ast_strlen_zero(p->okcontacturi))
5993 c = is_strict ? p->route->hop : p->okcontacturi;
5994 else
5995 c = p->initreq.rlPart2;
5996 } else if (!ast_strlen_zero(p->okcontacturi))
5997 c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
5998 else if (!ast_strlen_zero(p->uri))
5999 c = p->uri;
6000 else {
6001 char *n;
6002 /* We have no URI, use To: or From: header as URI (depending on direction) */
6003 ast_copy_string(stripped, get_header(orig, (ast_test_flag(&p->flags[0], SIP_OUTGOING)) ? "To" : "From"),
6004 sizeof(stripped));
6005 n = get_in_brackets(stripped);
6006 c = strsep(&n, ";"); /* trim ; and beyond */
6008 init_req(req, sipmethod, c);
6010 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
6012 add_header(req, "Via", p->via);
6013 if (p->route) {
6014 set_destination(p, p->route->hop);
6015 add_route(req, is_strict ? p->route->next : p->route);
6018 ot = get_header(orig, "To");
6019 of = get_header(orig, "From");
6021 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
6022 as our original request, including tag (or presumably lack thereof) */
6023 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
6024 /* Add the proper tag if we don't have it already. If they have specified
6025 their tag, use it. Otherwise, use our own tag */
6026 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_strlen_zero(p->theirtag))
6027 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
6028 else if (!ast_test_flag(&p->flags[0], SIP_OUTGOING))
6029 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
6030 else
6031 snprintf(newto, sizeof(newto), "%s", ot);
6032 ot = newto;
6035 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
6036 add_header(req, "From", of);
6037 add_header(req, "To", ot);
6038 } else {
6039 add_header(req, "From", ot);
6040 add_header(req, "To", of);
6042 /* Do not add Contact for MESSAGE, BYE and Cancel requests */
6043 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
6044 add_header(req, "Contact", p->our_contact);
6046 copy_header(req, orig, "Call-ID");
6047 add_header(req, "CSeq", tmp);
6049 if (!ast_strlen_zero(global_useragent))
6050 add_header(req, "User-Agent", global_useragent);
6051 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
6053 if (!ast_strlen_zero(p->rpid))
6054 add_header(req, "Remote-Party-ID", p->rpid);
6056 return 0;
6059 /*! \brief Base transmit response function */
6060 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
6062 struct sip_request resp;
6063 int seqno = 0;
6065 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
6066 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
6067 return -1;
6069 respprep(&resp, p, msg, req);
6070 add_header_contentLength(&resp, 0);
6071 /* If we are cancelling an incoming invite for some reason, add information
6072 about the reason why we are doing this in clear text */
6073 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
6074 char buf[10];
6076 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
6077 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
6078 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
6080 return send_response(p, &resp, reliable, seqno);
6083 static void temp_pvt_cleanup(void *data)
6085 struct sip_pvt *p = data;
6087 ast_string_field_free_memory(p);
6089 free(data);
6092 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
6093 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)
6095 struct sip_pvt *p = NULL;
6097 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
6098 ast_log(LOG_NOTICE, "Failed to get temporary pvt\n");
6099 return -1;
6102 /* if the structure was just allocated, initialize it */
6103 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
6104 ast_set_flag(&p->flags[0], SIP_NO_HISTORY);
6105 if (ast_string_field_init(p, 512))
6106 return -1;
6109 /* Initialize the bare minimum */
6110 p->method = intended_method;
6112 if (sin) {
6113 p->sa = *sin;
6114 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
6115 p->ourip = __ourip;
6116 } else
6117 p->ourip = __ourip;
6119 p->branch = ast_random();
6120 make_our_tag(p->tag, sizeof(p->tag));
6121 p->ocseq = INITIAL_CSEQ;
6123 if (useglobal_nat && sin) {
6124 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
6125 p->recv = *sin;
6126 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
6128 check_via(p, req);
6130 ast_string_field_set(p, fromdomain, default_fromdomain);
6131 build_via(p);
6132 ast_string_field_set(p, callid, callid);
6134 /* Use this temporary pvt structure to send the message */
6135 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
6137 /* Free the string fields, but not the pool space */
6138 ast_string_field_reset_all(p);
6140 return 0;
6143 /*! \brief Transmit response, no retransmits */
6144 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
6146 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
6149 /*! \brief Transmit response, no retransmits */
6150 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
6152 struct sip_request resp;
6153 respprep(&resp, p, msg, req);
6154 append_date(&resp);
6155 add_header(&resp, "Unsupported", unsupported);
6156 add_header_contentLength(&resp, 0);
6157 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
6160 /*! \brief Transmit response, Make sure you get an ACK
6161 This is only used for responses to INVITEs, where we need to make sure we get an ACK
6163 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
6165 return __transmit_response(p, msg, req, XMIT_CRITICAL);
6168 /*! \brief Append date to SIP message */
6169 static void append_date(struct sip_request *req)
6171 char tmpdat[256];
6172 struct tm tm;
6173 time_t t = time(NULL);
6175 gmtime_r(&t, &tm);
6176 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
6177 add_header(req, "Date", tmpdat);
6180 /*! \brief Append date and content length before transmitting response */
6181 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
6183 struct sip_request resp;
6184 respprep(&resp, p, msg, req);
6185 append_date(&resp);
6186 add_header_contentLength(&resp, 0);
6187 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
6190 /*! \brief Append Accept header, content length before transmitting response */
6191 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
6193 struct sip_request resp;
6194 respprep(&resp, p, msg, req);
6195 add_header(&resp, "Accept", "application/sdp");
6196 add_header_contentLength(&resp, 0);
6197 return send_response(p, &resp, reliable, 0);
6200 /*! \brief Respond with authorization request */
6201 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)
6203 struct sip_request resp;
6204 char tmp[512];
6205 int seqno = 0;
6207 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
6208 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
6209 return -1;
6211 /* Stale means that they sent us correct authentication, but
6212 based it on an old challenge (nonce) */
6213 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
6214 respprep(&resp, p, msg, req);
6215 add_header(&resp, header, tmp);
6216 add_header_contentLength(&resp, 0);
6217 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
6218 return send_response(p, &resp, reliable, seqno);
6221 /*! \brief Add text body to SIP message */
6222 static int add_text(struct sip_request *req, const char *text)
6224 /* XXX Convert \n's to \r\n's XXX */
6225 add_header(req, "Content-Type", "text/plain");
6226 add_header_contentLength(req, strlen(text));
6227 add_line(req, text);
6228 return 0;
6231 /*! \brief Add DTMF INFO tone to sip message */
6232 /* Always adds default duration 250 ms, regardless of what came in over the line */
6233 static int add_digit(struct sip_request *req, char digit, unsigned int duration)
6235 char tmp[256];
6237 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
6238 add_header(req, "Content-Type", "application/dtmf-relay");
6239 add_header_contentLength(req, strlen(tmp));
6240 add_line(req, tmp);
6241 return 0;
6244 /*! \brief add XML encoded media control with update
6245 \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
6246 static int add_vidupdate(struct sip_request *req)
6248 const char *xml_is_a_huge_waste_of_space =
6249 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
6250 " <media_control>\r\n"
6251 " <vc_primitive>\r\n"
6252 " <to_encoder>\r\n"
6253 " <picture_fast_update>\r\n"
6254 " </picture_fast_update>\r\n"
6255 " </to_encoder>\r\n"
6256 " </vc_primitive>\r\n"
6257 " </media_control>\r\n";
6258 add_header(req, "Content-Type", "application/media_control+xml");
6259 add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
6260 add_line(req, xml_is_a_huge_waste_of_space);
6261 return 0;
6264 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
6265 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
6266 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
6267 int debug, int *min_packet_size)
6269 int rtp_code;
6270 struct ast_format_list fmt;
6273 if (debug)
6274 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
6275 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
6276 return;
6278 if (p->rtp) {
6279 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
6280 fmt = ast_codec_pref_getsize(pref, codec);
6281 } 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 */
6282 return;
6283 ast_build_string(m_buf, m_size, " %d", rtp_code);
6284 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
6285 ast_rtp_lookup_mime_subtype(1, codec,
6286 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
6287 sample_rate);
6288 if (codec == AST_FORMAT_G729A) {
6289 /* Indicate that we don't support VAD (G.729 annex B) */
6290 ast_build_string(a_buf, a_size, "a=fmtp:%d annexb=no\r\n", rtp_code);
6291 } else if (codec == AST_FORMAT_G723_1) {
6292 /* Indicate that we don't support VAD (G.723.1 annex A) */
6293 ast_build_string(a_buf, a_size, "a=fmtp:%d annexa=no\r\n", rtp_code);
6294 } else if (codec == AST_FORMAT_ILBC) {
6295 /* Add information about us using only 20/30 ms packetization */
6296 ast_build_string(a_buf, a_size, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
6299 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
6300 *min_packet_size = fmt.cur_ms;
6302 /* Our first codec packetization processed cannot be less than zero */
6303 if ((*min_packet_size) == 0 && fmt.cur_ms)
6304 *min_packet_size = fmt.cur_ms;
6307 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
6308 static int t38_get_rate(int t38cap)
6310 int maxrate = (t38cap & (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400));
6312 if (maxrate & T38FAX_RATE_14400) {
6313 if (option_debug > 1)
6314 ast_log(LOG_DEBUG, "T38MaxFaxRate 14400 found\n");
6315 return 14400;
6316 } else if (maxrate & T38FAX_RATE_12000) {
6317 if (option_debug > 1)
6318 ast_log(LOG_DEBUG, "T38MaxFaxRate 12000 found\n");
6319 return 12000;
6320 } else if (maxrate & T38FAX_RATE_9600) {
6321 if (option_debug > 1)
6322 ast_log(LOG_DEBUG, "T38MaxFaxRate 9600 found\n");
6323 return 9600;
6324 } else if (maxrate & T38FAX_RATE_7200) {
6325 if (option_debug > 1)
6326 ast_log(LOG_DEBUG, "T38MaxFaxRate 7200 found\n");
6327 return 7200;
6328 } else if (maxrate & T38FAX_RATE_4800) {
6329 if (option_debug > 1)
6330 ast_log(LOG_DEBUG, "T38MaxFaxRate 4800 found\n");
6331 return 4800;
6332 } else if (maxrate & T38FAX_RATE_2400) {
6333 if (option_debug > 1)
6334 ast_log(LOG_DEBUG, "T38MaxFaxRate 2400 found\n");
6335 return 2400;
6336 } else {
6337 if (option_debug > 1)
6338 ast_log(LOG_DEBUG, "Strange, T38MaxFaxRate NOT found in peers T38 SDP.\n");
6339 return 0;
6343 /*! \brief Add T.38 Session Description Protocol message */
6344 static int add_t38_sdp(struct sip_request *resp, struct sip_pvt *p)
6346 int len = 0;
6347 int x = 0;
6348 struct sockaddr_in udptlsin;
6349 char v[256] = "";
6350 char s[256] = "";
6351 char o[256] = "";
6352 char c[256] = "";
6353 char t[256] = "";
6354 char m_modem[256];
6355 char a_modem[1024];
6356 char *m_modem_next = m_modem;
6357 size_t m_modem_left = sizeof(m_modem);
6358 char *a_modem_next = a_modem;
6359 size_t a_modem_left = sizeof(a_modem);
6360 struct sockaddr_in udptldest = { 0, };
6361 int debug;
6363 debug = sip_debug_test_pvt(p);
6364 len = 0;
6365 if (!p->udptl) {
6366 ast_log(LOG_WARNING, "No way to add SDP without an UDPTL structure\n");
6367 return -1;
6370 if (!p->sessionid) {
6371 p->sessionid = getpid();
6372 p->sessionversion = p->sessionid;
6373 } else
6374 p->sessionversion++;
6376 /* Our T.38 end is */
6377 ast_udptl_get_us(p->udptl, &udptlsin);
6379 /* Determine T.38 UDPTL destination */
6380 if (p->udptlredirip.sin_addr.s_addr) {
6381 udptldest.sin_port = p->udptlredirip.sin_port;
6382 udptldest.sin_addr = p->udptlredirip.sin_addr;
6383 } else {
6384 udptldest.sin_addr = p->ourip;
6385 udptldest.sin_port = udptlsin.sin_port;
6388 if (debug)
6389 ast_log(LOG_DEBUG, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(udptlsin.sin_port));
6391 /* We break with the "recommendation" and send our IP, in order that our
6392 peer doesn't have to ast_gethostbyname() us */
6394 if (debug) {
6395 ast_log(LOG_DEBUG, "Our T38 capability (%d), peer T38 capability (%d), joint capability (%d)\n",
6396 p->t38.capability,
6397 p->t38.peercapability,
6398 p->t38.jointcapability);
6400 snprintf(v, sizeof(v), "v=0\r\n");
6401 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(udptldest.sin_addr));
6402 snprintf(s, sizeof(s), "s=session\r\n");
6403 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(udptldest.sin_addr));
6404 snprintf(t, sizeof(t), "t=0 0\r\n");
6405 ast_build_string(&m_modem_next, &m_modem_left, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
6407 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_0)
6408 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:0\r\n");
6409 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_1)
6410 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:1\r\n");
6411 if ((x = t38_get_rate(p->t38.jointcapability)))
6412 ast_build_string(&a_modem_next, &a_modem_left, "a=T38MaxBitRate:%d\r\n",x);
6413 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxFillBitRemoval:%d\r\n", (p->t38.jointcapability & T38FAX_FILL_BIT_REMOVAL) ? 1 : 0);
6414 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingMMR:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_MMR) ? 1 : 0);
6415 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingJBIG:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_JBIG) ? 1 : 0);
6416 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxRateManagement:%s\r\n", (p->t38.jointcapability & T38FAX_RATE_MANAGEMENT_LOCAL_TCF) ? "localTCF" : "transferredTCF");
6417 x = ast_udptl_get_local_max_datagram(p->udptl);
6418 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxBuffer:%d\r\n",x);
6419 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxDatagram:%d\r\n",x);
6420 if (p->t38.jointcapability != T38FAX_UDP_EC_NONE)
6421 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxUdpEC:%s\r\n", (p->t38.jointcapability & T38FAX_UDP_EC_REDUNDANCY) ? "t38UDPRedundancy" : "t38UDPFEC");
6422 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m_modem) + strlen(a_modem);
6423 add_header(resp, "Content-Type", "application/sdp");
6424 add_header_contentLength(resp, len);
6425 add_line(resp, v);
6426 add_line(resp, o);
6427 add_line(resp, s);
6428 add_line(resp, c);
6429 add_line(resp, t);
6430 add_line(resp, m_modem);
6431 add_line(resp, a_modem);
6433 /* Update lastrtprx when we send our SDP */
6434 p->lastrtprx = p->lastrtptx = time(NULL);
6436 return 0;
6440 /*! \brief Add RFC 2833 DTMF offer to SDP */
6441 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
6442 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
6443 int debug)
6445 int rtp_code;
6447 if (debug)
6448 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
6449 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
6450 return;
6452 ast_build_string(m_buf, m_size, " %d", rtp_code);
6453 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
6454 ast_rtp_lookup_mime_subtype(0, format, 0),
6455 sample_rate);
6456 if (format == AST_RTP_DTMF)
6457 /* Indicate we support DTMF and FLASH... */
6458 ast_build_string(a_buf, a_size, "a=fmtp:%d 0-16\r\n", rtp_code);
6462 * \note G.722 actually is supposed to specified as 8 kHz, even though it is
6463 * really 16 kHz. Update this macro for other formats as they are added in
6464 * the future.
6466 #define SDP_SAMPLE_RATE(x) 8000
6468 /*! \brief Add Session Description Protocol message */
6469 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p)
6471 int len = 0;
6472 int alreadysent = 0;
6474 struct sockaddr_in sin;
6475 struct sockaddr_in vsin;
6476 struct sockaddr_in dest;
6477 struct sockaddr_in vdest = { 0, };
6479 /* SDP fields */
6480 char *version = "v=0\r\n"; /* Protocol version */
6481 char *subject = "s=session\r\n"; /* Subject of the session */
6482 char owner[256]; /* Session owner/creator */
6483 char connection[256]; /* Connection data */
6484 char *stime = "t=0 0\r\n"; /* Time the session is active */
6485 char bandwidth[256] = ""; /* Max bitrate */
6486 char *hold;
6487 char m_audio[256]; /* Media declaration line for audio */
6488 char m_video[256]; /* Media declaration line for video */
6489 char a_audio[1024]; /* Attributes for audio */
6490 char a_video[1024]; /* Attributes for video */
6491 char *m_audio_next = m_audio;
6492 char *m_video_next = m_video;
6493 size_t m_audio_left = sizeof(m_audio);
6494 size_t m_video_left = sizeof(m_video);
6495 char *a_audio_next = a_audio;
6496 char *a_video_next = a_video;
6497 size_t a_audio_left = sizeof(a_audio);
6498 size_t a_video_left = sizeof(a_video);
6500 int x;
6501 int capability;
6502 int needvideo = FALSE;
6503 int debug = sip_debug_test_pvt(p);
6504 int min_audio_packet_size = 0;
6505 int min_video_packet_size = 0;
6507 m_video[0] = '\0'; /* Reset the video media string if it's not needed */
6509 if (!p->rtp) {
6510 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
6511 return AST_FAILURE;
6514 /* Set RTP Session ID and version */
6515 if (!p->sessionid) {
6516 p->sessionid = getpid();
6517 p->sessionversion = p->sessionid;
6518 } else
6519 p->sessionversion++;
6521 /* Get our addresses */
6522 ast_rtp_get_us(p->rtp, &sin);
6523 if (p->vrtp)
6524 ast_rtp_get_us(p->vrtp, &vsin);
6526 /* Is this a re-invite to move the media out, then use the original offer from caller */
6527 if (p->redirip.sin_addr.s_addr) {
6528 dest.sin_port = p->redirip.sin_port;
6529 dest.sin_addr = p->redirip.sin_addr;
6530 } else {
6531 dest.sin_addr = p->ourip;
6532 dest.sin_port = sin.sin_port;
6535 capability = p->jointcapability;
6538 if (option_debug > 1) {
6539 char codecbuf[SIPBUFSIZE];
6540 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");
6541 ast_log(LOG_DEBUG, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
6544 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
6545 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_RTP)) {
6546 ast_build_string(&m_audio_next, &m_audio_left, " %d", 191);
6547 ast_build_string(&a_audio_next, &a_audio_left, "a=rtpmap:%d %s/%d\r\n", 191, "t38", 8000);
6549 #endif
6551 /* Check if we need video in this call */
6552 if ((capability & AST_FORMAT_VIDEO_MASK) && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
6553 if (p->vrtp) {
6554 needvideo = TRUE;
6555 if (option_debug > 1)
6556 ast_log(LOG_DEBUG, "This call needs video offers!\n");
6557 } else if (option_debug > 1)
6558 ast_log(LOG_DEBUG, "This call needs video offers, but there's no video support enabled!\n");
6562 /* Ok, we need video. Let's add what we need for video and set codecs.
6563 Video is handled differently than audio since we can not transcode. */
6564 if (needvideo) {
6565 /* Determine video destination */
6566 if (p->vredirip.sin_addr.s_addr) {
6567 vdest.sin_addr = p->vredirip.sin_addr;
6568 vdest.sin_port = p->vredirip.sin_port;
6569 } else {
6570 vdest.sin_addr = p->ourip;
6571 vdest.sin_port = vsin.sin_port;
6573 ast_build_string(&m_video_next, &m_video_left, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
6575 /* Build max bitrate string */
6576 if (p->maxcallbitrate)
6577 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
6578 if (debug)
6579 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(vsin.sin_port));
6582 if (debug)
6583 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(sin.sin_port));
6585 /* Start building generic SDP headers */
6587 /* We break with the "recommendation" and send our IP, in order that our
6588 peer doesn't have to ast_gethostbyname() us */
6590 snprintf(owner, sizeof(owner), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
6591 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
6592 ast_build_string(&m_audio_next, &m_audio_left, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
6594 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
6595 hold = "a=recvonly\r\n";
6596 else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
6597 hold = "a=inactive\r\n";
6598 else
6599 hold = "a=sendrecv\r\n";
6601 /* Now, start adding audio codecs. These are added in this order:
6602 - First what was requested by the calling channel
6603 - Then preferences in order from sip.conf device config for this peer/user
6604 - Then other codecs in capabilities, including video
6607 /* Prefer the audio codec we were requested to use, first, no matter what
6608 Note that p->prefcodec can include video codecs, so mask them out
6610 if (capability & p->prefcodec) {
6611 int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
6613 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
6614 &m_audio_next, &m_audio_left,
6615 &a_audio_next, &a_audio_left,
6616 debug, &min_audio_packet_size);
6617 alreadysent |= codec;
6620 /* Start by sending our preferred audio codecs */
6621 for (x = 0; x < 32; x++) {
6622 int codec;
6624 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
6625 break;
6627 if (!(capability & codec))
6628 continue;
6630 if (alreadysent & codec)
6631 continue;
6633 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
6634 &m_audio_next, &m_audio_left,
6635 &a_audio_next, &a_audio_left,
6636 debug, &min_audio_packet_size);
6637 alreadysent |= codec;
6640 /* Now send any other common audio and video codecs, and non-codec formats: */
6641 for (x = 1; x <= (needvideo ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
6642 if (!(capability & x)) /* Codec not requested */
6643 continue;
6645 if (alreadysent & x) /* Already added to SDP */
6646 continue;
6648 if (x <= AST_FORMAT_MAX_AUDIO)
6649 add_codec_to_sdp(p, x, SDP_SAMPLE_RATE(x),
6650 &m_audio_next, &m_audio_left,
6651 &a_audio_next, &a_audio_left,
6652 debug, &min_audio_packet_size);
6653 else
6654 add_codec_to_sdp(p, x, 90000,
6655 &m_video_next, &m_video_left,
6656 &a_video_next, &a_video_left,
6657 debug, &min_video_packet_size);
6660 /* Now add DTMF RFC2833 telephony-event as a codec */
6661 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
6662 if (!(p->jointnoncodeccapability & x))
6663 continue;
6665 add_noncodec_to_sdp(p, x, 8000,
6666 &m_audio_next, &m_audio_left,
6667 &a_audio_next, &a_audio_left,
6668 debug);
6671 if (option_debug > 2)
6672 ast_log(LOG_DEBUG, "-- Done with adding codecs to SDP\n");
6674 if (!p->owner || !ast_internal_timing_enabled(p->owner))
6675 ast_build_string(&a_audio_next, &a_audio_left, "a=silenceSupp:off - - - -\r\n");
6677 if (min_audio_packet_size)
6678 ast_build_string(&a_audio_next, &a_audio_left, "a=ptime:%d\r\n", min_audio_packet_size);
6680 if (min_video_packet_size)
6681 ast_build_string(&a_video_next, &a_video_left, "a=ptime:%d\r\n", min_video_packet_size);
6683 if ((m_audio_left < 2) || (m_video_left < 2) || (a_audio_left == 0) || (a_video_left == 0))
6684 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
6686 ast_build_string(&m_audio_next, &m_audio_left, "\r\n");
6687 if (needvideo)
6688 ast_build_string(&m_video_next, &m_video_left, "\r\n");
6690 len = strlen(version) + strlen(subject) + strlen(owner) + strlen(connection) + strlen(stime) + strlen(m_audio) + strlen(a_audio) + strlen(hold);
6691 if (needvideo) /* only if video response is appropriate */
6692 len += strlen(m_video) + strlen(a_video) + strlen(bandwidth) + strlen(hold);
6694 add_header(resp, "Content-Type", "application/sdp");
6695 add_header_contentLength(resp, len);
6696 add_line(resp, version);
6697 add_line(resp, owner);
6698 add_line(resp, subject);
6699 add_line(resp, connection);
6700 if (needvideo) /* only if video response is appropriate */
6701 add_line(resp, bandwidth);
6702 add_line(resp, stime);
6703 add_line(resp, m_audio);
6704 add_line(resp, a_audio);
6705 add_line(resp, hold);
6706 if (needvideo) { /* only if video response is appropriate */
6707 add_line(resp, m_video);
6708 add_line(resp, a_video);
6709 add_line(resp, hold); /* Repeat hold for the video stream */
6712 /* Update lastrtprx when we send our SDP */
6713 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
6715 if (option_debug > 2) {
6716 char buf[SIPBUFSIZE];
6717 ast_log(LOG_DEBUG, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
6720 return AST_SUCCESS;
6723 /*! \brief Used for 200 OK and 183 early media */
6724 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
6726 struct sip_request resp;
6727 int seqno;
6729 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
6730 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
6731 return -1;
6733 respprep(&resp, p, msg, req);
6734 if (p->udptl) {
6735 ast_udptl_offered_from_local(p->udptl, 0);
6736 add_t38_sdp(&resp, p);
6737 } else
6738 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
6739 if (retrans && !p->pendinginvite)
6740 p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
6741 return send_response(p, &resp, retrans, seqno);
6744 /*! \brief copy SIP request (mostly used to save request for responses) */
6745 static void copy_request(struct sip_request *dst, const struct sip_request *src)
6747 long offset;
6748 int x;
6749 offset = ((void *)dst) - ((void *)src);
6750 /* First copy stuff */
6751 memcpy(dst, src, sizeof(*dst));
6752 /* Now fix pointer arithmetic */
6753 for (x=0; x < src->headers; x++)
6754 dst->header[x] += offset;
6755 for (x=0; x < src->lines; x++)
6756 dst->line[x] += offset;
6757 dst->rlPart1 += offset;
6758 dst->rlPart2 += offset;
6761 /*! \brief Used for 200 OK and 183 early media
6762 \return Will return XMIT_ERROR for network errors.
6764 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
6766 struct sip_request resp;
6767 int seqno;
6768 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
6769 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
6770 return -1;
6772 respprep(&resp, p, msg, req);
6773 if (p->rtp) {
6774 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
6775 if (option_debug)
6776 ast_log(LOG_DEBUG, "Setting framing from config on incoming call\n");
6777 ast_rtp_codec_setpref(p->rtp, &p->prefs);
6779 try_suggested_sip_codec(p);
6780 add_sdp(&resp, p);
6781 } else
6782 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
6783 if (reliable && !p->pendinginvite)
6784 p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
6785 return send_response(p, &resp, reliable, seqno);
6788 /*! \brief Parse first line of incoming SIP request */
6789 static int determine_firstline_parts(struct sip_request *req)
6791 char *e = ast_skip_blanks(req->header[0]); /* there shouldn't be any */
6793 if (!*e)
6794 return -1;
6795 req->rlPart1 = e; /* method or protocol */
6796 e = ast_skip_nonblanks(e);
6797 if (*e)
6798 *e++ = '\0';
6799 /* Get URI or status code */
6800 e = ast_skip_blanks(e);
6801 if ( !*e )
6802 return -1;
6803 ast_trim_blanks(e);
6805 if (!strcasecmp(req->rlPart1, "SIP/2.0") ) { /* We have a response */
6806 if (strlen(e) < 3) /* status code is 3 digits */
6807 return -1;
6808 req->rlPart2 = e;
6809 } else { /* We have a request */
6810 if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
6811 ast_log(LOG_WARNING, "bogus uri in <> %s\n", e);
6812 e++;
6813 if (!*e)
6814 return -1;
6816 req->rlPart2 = e; /* URI */
6817 e = ast_skip_nonblanks(e);
6818 if (*e)
6819 *e++ = '\0';
6820 e = ast_skip_blanks(e);
6821 if (strcasecmp(e, "SIP/2.0") ) {
6822 ast_log(LOG_WARNING, "Bad request protocol %s\n", e);
6823 return -1;
6826 return 1;
6829 /*! \brief Transmit reinvite with SDP
6830 \note A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
6831 INVITE that opened the SIP dialogue
6832 We reinvite so that the audio stream (RTP) go directly between
6833 the SIP UAs. SIP Signalling stays with * in the path.
6835 static int transmit_reinvite_with_sdp(struct sip_pvt *p)
6837 struct sip_request req;
6839 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
6841 add_header(&req, "Allow", ALLOWED_METHODS);
6842 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6843 if (sipdebug)
6844 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
6845 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
6846 append_history(p, "ReInv", "Re-invite sent");
6847 add_sdp(&req, p);
6848 /* Use this as the basis */
6849 initialize_initreq(p, &req);
6850 p->lastinvite = p->ocseq;
6851 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Change direction of this dialog */
6852 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
6855 /*! \brief Transmit reinvite with T38 SDP
6856 We reinvite so that the T38 processing can take place.
6857 SIP Signalling stays with * in the path.
6859 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p)
6861 struct sip_request req;
6863 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
6865 add_header(&req, "Allow", ALLOWED_METHODS);
6866 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6867 if (sipdebug)
6868 add_header(&req, "X-asterisk-info", "SIP re-invite (T38 switchover)");
6869 ast_udptl_offered_from_local(p->udptl, 1);
6870 add_t38_sdp(&req, p);
6871 /* Use this as the basis */
6872 initialize_initreq(p, &req);
6873 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Change direction of this dialog */
6874 p->lastinvite = p->ocseq;
6875 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
6878 /*! \brief Check Contact: URI of SIP message */
6879 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
6881 char stripped[SIPBUFSIZE];
6882 char *c;
6884 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
6885 c = get_in_brackets(stripped);
6886 c = strsep(&c, ";"); /* trim ; and beyond */
6887 if (!ast_strlen_zero(c))
6888 ast_string_field_set(p, uri, c);
6891 /*! \brief Build contact header - the contact header we send out */
6892 static void build_contact(struct sip_pvt *p)
6894 /* Construct Contact: header */
6895 if (ourport != STANDARD_SIP_PORT)
6896 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);
6897 else
6898 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip));
6901 /*! \brief Build the Remote Party-ID & From using callingpres options */
6902 static void build_rpid(struct sip_pvt *p)
6904 int send_pres_tags = TRUE;
6905 const char *privacy=NULL;
6906 const char *screen=NULL;
6907 char buf[256];
6908 const char *clid = default_callerid;
6909 const char *clin = NULL;
6910 const char *fromdomain;
6912 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
6913 return;
6915 if (p->owner && p->owner->cid.cid_num)
6916 clid = p->owner->cid.cid_num;
6917 if (p->owner && p->owner->cid.cid_name)
6918 clin = p->owner->cid.cid_name;
6919 if (ast_strlen_zero(clin))
6920 clin = clid;
6922 switch (p->callingpres) {
6923 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
6924 privacy = "off";
6925 screen = "no";
6926 break;
6927 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
6928 privacy = "off";
6929 screen = "yes";
6930 break;
6931 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
6932 privacy = "off";
6933 screen = "no";
6934 break;
6935 case AST_PRES_ALLOWED_NETWORK_NUMBER:
6936 privacy = "off";
6937 screen = "yes";
6938 break;
6939 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
6940 privacy = "full";
6941 screen = "no";
6942 break;
6943 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
6944 privacy = "full";
6945 screen = "yes";
6946 break;
6947 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
6948 privacy = "full";
6949 screen = "no";
6950 break;
6951 case AST_PRES_PROHIB_NETWORK_NUMBER:
6952 privacy = "full";
6953 screen = "yes";
6954 break;
6955 case AST_PRES_NUMBER_NOT_AVAILABLE:
6956 send_pres_tags = FALSE;
6957 break;
6958 default:
6959 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
6960 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
6961 privacy = "full";
6962 else
6963 privacy = "off";
6964 screen = "no";
6965 break;
6968 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip));
6970 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
6971 if (send_pres_tags)
6972 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
6973 ast_string_field_set(p, rpid, buf);
6975 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
6976 S_OR(p->fromuser, clid),
6977 fromdomain, p->tag);
6980 /*! \brief Initiate new SIP request to peer/user */
6981 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
6983 char invite_buf[256] = "";
6984 char *invite = invite_buf;
6985 size_t invite_max = sizeof(invite_buf);
6986 char from[256];
6987 char to[256];
6988 char tmp[SIPBUFSIZE/2];
6989 char tmp2[SIPBUFSIZE/2];
6990 const char *l = NULL, *n = NULL;
6991 const char *urioptions = "";
6993 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
6994 const char *s = p->username; /* being a string field, cannot be NULL */
6996 /* Test p->username against allowed characters in AST_DIGIT_ANY
6997 If it matches the allowed characters list, then sipuser = ";user=phone"
6998 If not, then sipuser = ""
7000 /* + is allowed in first position in a tel: uri */
7001 if (*s == '+')
7002 s++;
7003 for (; *s; s++) {
7004 if (!strchr(AST_DIGIT_ANYNUM, *s) )
7005 break;
7007 /* If we have only digits, add ;user=phone to the uri */
7008 if (*s)
7009 urioptions = ";user=phone";
7013 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
7015 if (p->owner) {
7016 l = p->owner->cid.cid_num;
7017 n = p->owner->cid.cid_name;
7019 /* if we are not sending RPID and user wants his callerid restricted */
7020 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
7021 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
7022 l = CALLERID_UNKNOWN;
7023 n = l;
7025 if (ast_strlen_zero(l))
7026 l = default_callerid;
7027 if (ast_strlen_zero(n))
7028 n = l;
7029 /* Allow user to be overridden */
7030 if (!ast_strlen_zero(p->fromuser))
7031 l = p->fromuser;
7032 else /* Save for any further attempts */
7033 ast_string_field_set(p, fromuser, l);
7035 /* Allow user to be overridden */
7036 if (!ast_strlen_zero(p->fromname))
7037 n = p->fromname;
7038 else /* Save for any further attempts */
7039 ast_string_field_set(p, fromname, n);
7041 if (pedanticsipchecking) {
7042 ast_uri_encode(n, tmp, sizeof(tmp), 0);
7043 n = tmp;
7044 ast_uri_encode(l, tmp2, sizeof(tmp2), 0);
7045 l = tmp2;
7048 if (ourport != STANDARD_SIP_PORT && ast_strlen_zero(p->fromdomain))
7049 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);
7050 else
7051 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)), p->tag);
7053 /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
7054 if (!ast_strlen_zero(p->fullcontact)) {
7055 /* If we have full contact, trust it */
7056 ast_build_string(&invite, &invite_max, "%s", p->fullcontact);
7057 } else {
7058 /* Otherwise, use the username while waiting for registration */
7059 ast_build_string(&invite, &invite_max, "sip:");
7060 if (!ast_strlen_zero(p->username)) {
7061 n = p->username;
7062 if (pedanticsipchecking) {
7063 ast_uri_encode(n, tmp, sizeof(tmp), 0);
7064 n = tmp;
7066 ast_build_string(&invite, &invite_max, "%s@", n);
7068 ast_build_string(&invite, &invite_max, "%s", p->tohost);
7069 if (ntohs(p->sa.sin_port) != STANDARD_SIP_PORT)
7070 ast_build_string(&invite, &invite_max, ":%d", ntohs(p->sa.sin_port));
7071 ast_build_string(&invite, &invite_max, "%s", urioptions);
7074 /* If custom URI options have been provided, append them */
7075 if (p->options && !ast_strlen_zero(p->options->uri_options))
7076 ast_build_string(&invite, &invite_max, ";%s", p->options->uri_options);
7078 ast_string_field_set(p, uri, invite_buf);
7080 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
7081 /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
7082 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "" : "sip:"), p->uri, p->theirtag);
7083 } else if (p->options && p->options->vxml_url) {
7084 /* If there is a VXML URL append it to the SIP URL */
7085 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
7086 } else
7087 snprintf(to, sizeof(to), "<%s>", p->uri);
7089 init_req(req, sipmethod, p->uri);
7090 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
7092 add_header(req, "Via", p->via);
7093 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
7094 * OTOH, then we won't have anything in p->route anyway */
7095 /* Build Remote Party-ID and From */
7096 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
7097 build_rpid(p);
7098 add_header(req, "From", p->rpid_from);
7099 } else
7100 add_header(req, "From", from);
7101 add_header(req, "To", to);
7102 ast_string_field_set(p, exten, l);
7103 build_contact(p);
7104 add_header(req, "Contact", p->our_contact);
7105 add_header(req, "Call-ID", p->callid);
7106 add_header(req, "CSeq", tmp);
7107 if (!ast_strlen_zero(global_useragent))
7108 add_header(req, "User-Agent", global_useragent);
7109 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
7110 if (!ast_strlen_zero(p->rpid))
7111 add_header(req, "Remote-Party-ID", p->rpid);
7114 /*! \brief Build REFER/INVITE/OPTIONS message and transmit it */
7115 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
7117 struct sip_request req;
7119 req.method = sipmethod;
7120 if (init) { /* Seems like init always is 2 */
7121 /* Bump branch even on initial requests */
7122 p->branch ^= ast_random();
7123 build_via(p);
7124 if (init > 1)
7125 initreqprep(&req, p, sipmethod);
7126 else
7127 reqprep(&req, p, sipmethod, 0, 1);
7128 } else
7129 reqprep(&req, p, sipmethod, 0, 1);
7131 if (p->options && p->options->auth)
7132 add_header(&req, p->options->authheader, p->options->auth);
7133 append_date(&req);
7134 if (sipmethod == SIP_REFER) { /* Call transfer */
7135 if (p->refer) {
7136 char buf[SIPBUFSIZE];
7137 if (!ast_strlen_zero(p->refer->refer_to))
7138 add_header(&req, "Refer-To", p->refer->refer_to);
7139 if (!ast_strlen_zero(p->refer->referred_by)) {
7140 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
7141 add_header(&req, "Referred-By", buf);
7145 /* This new INVITE is part of an attended transfer. Make sure that the
7146 other end knows and replace the current call with this new call */
7147 if (p->options && p->options->replaces && !ast_strlen_zero(p->options->replaces)) {
7148 add_header(&req, "Replaces", p->options->replaces);
7149 add_header(&req, "Require", "replaces");
7152 add_header(&req, "Allow", ALLOWED_METHODS);
7153 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7154 if (p->options && p->options->addsipheaders && p->owner) {
7155 struct ast_channel *chan = p->owner; /* The owner channel */
7156 struct varshead *headp;
7158 ast_channel_lock(chan);
7160 headp = &chan->varshead;
7162 if (!headp)
7163 ast_log(LOG_WARNING,"No Headp for the channel...ooops!\n");
7164 else {
7165 const struct ast_var_t *current;
7166 AST_LIST_TRAVERSE(headp, current, entries) {
7167 /* SIPADDHEADER: Add SIP header to outgoing call */
7168 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
7169 char *content, *end;
7170 const char *header = ast_var_value(current);
7171 char *headdup = ast_strdupa(header);
7173 /* Strip of the starting " (if it's there) */
7174 if (*headdup == '"')
7175 headdup++;
7176 if ((content = strchr(headdup, ':'))) {
7177 *content++ = '\0';
7178 content = ast_skip_blanks(content); /* Skip white space */
7179 /* Strip the ending " (if it's there) */
7180 end = content + strlen(content) -1;
7181 if (*end == '"')
7182 *end = '\0';
7184 add_header(&req, headdup, content);
7185 if (sipdebug)
7186 ast_log(LOG_DEBUG, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
7192 ast_channel_unlock(chan);
7194 if (sdp) {
7195 if (p->udptl && (p->t38.state == T38_LOCAL_DIRECT || p->t38.state == T38_LOCAL_REINVITE)) {
7196 ast_udptl_offered_from_local(p->udptl, 1);
7197 if (option_debug)
7198 ast_log(LOG_DEBUG, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
7199 add_t38_sdp(&req, p);
7200 } else if (p->rtp)
7201 add_sdp(&req, p);
7202 } else {
7203 add_header_contentLength(&req, 0);
7206 if (!p->initreq.headers)
7207 initialize_initreq(p, &req);
7208 p->lastinvite = p->ocseq;
7209 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
7212 /*! \brief Used in the SUBSCRIBE notification subsystem */
7213 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
7215 char tmp[4000], from[256], to[256];
7216 char *t = tmp, *c, *mfrom, *mto;
7217 size_t maxbytes = sizeof(tmp);
7218 struct sip_request req;
7219 char hint[AST_MAX_EXTENSION];
7220 char *statestring = "terminated";
7221 const struct cfsubscription_types *subscriptiontype;
7222 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
7223 char *pidfstate = "--";
7224 char *pidfnote= "Ready";
7226 memset(from, 0, sizeof(from));
7227 memset(to, 0, sizeof(to));
7228 memset(tmp, 0, sizeof(tmp));
7230 switch (state) {
7231 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
7232 statestring = (global_notifyringing) ? "early" : "confirmed";
7233 local_state = NOTIFY_INUSE;
7234 pidfstate = "busy";
7235 pidfnote = "Ringing";
7236 break;
7237 case AST_EXTENSION_RINGING:
7238 statestring = "early";
7239 local_state = NOTIFY_INUSE;
7240 pidfstate = "busy";
7241 pidfnote = "Ringing";
7242 break;
7243 case AST_EXTENSION_INUSE:
7244 statestring = "confirmed";
7245 local_state = NOTIFY_INUSE;
7246 pidfstate = "busy";
7247 pidfnote = "On the phone";
7248 break;
7249 case AST_EXTENSION_BUSY:
7250 statestring = "confirmed";
7251 local_state = NOTIFY_CLOSED;
7252 pidfstate = "busy";
7253 pidfnote = "On the phone";
7254 break;
7255 case AST_EXTENSION_UNAVAILABLE:
7256 statestring = "terminated";
7257 local_state = NOTIFY_CLOSED;
7258 pidfstate = "away";
7259 pidfnote = "Unavailable";
7260 break;
7261 case AST_EXTENSION_ONHOLD:
7262 statestring = "confirmed";
7263 local_state = NOTIFY_CLOSED;
7264 pidfstate = "busy";
7265 pidfnote = "On Hold";
7266 break;
7267 case AST_EXTENSION_NOT_INUSE:
7268 default:
7269 /* Default setting */
7270 break;
7273 subscriptiontype = find_subscription_type(p->subscribed);
7275 /* Check which device/devices we are watching and if they are registered */
7276 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
7277 char *hint2 = hint, *individual_hint = NULL;
7278 int hint_count = 0, unavailable_count = 0;
7280 while ((individual_hint = strsep(&hint2, "&"))) {
7281 hint_count++;
7283 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
7284 unavailable_count++;
7287 /* If none of the hinted devices are registered, we will
7288 * override notification and show no availability.
7290 if (hint_count > 0 && hint_count == unavailable_count) {
7291 local_state = NOTIFY_CLOSED;
7292 pidfstate = "away";
7293 pidfnote = "Not online";
7297 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
7298 c = get_in_brackets(from);
7299 if (strncasecmp(c, "sip:", 4)) {
7300 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
7301 return -1;
7303 mfrom = strsep(&c, ";"); /* trim ; and beyond */
7305 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
7306 c = get_in_brackets(to);
7307 if (strncasecmp(c, "sip:", 4)) {
7308 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
7309 return -1;
7311 mto = strsep(&c, ";"); /* trim ; and beyond */
7313 reqprep(&req, p, SIP_NOTIFY, 0, 1);
7316 add_header(&req, "Event", subscriptiontype->event);
7317 add_header(&req, "Content-Type", subscriptiontype->mediatype);
7318 switch(state) {
7319 case AST_EXTENSION_DEACTIVATED:
7320 if (timeout)
7321 add_header(&req, "Subscription-State", "terminated;reason=timeout");
7322 else {
7323 add_header(&req, "Subscription-State", "terminated;reason=probation");
7324 add_header(&req, "Retry-After", "60");
7326 break;
7327 case AST_EXTENSION_REMOVED:
7328 add_header(&req, "Subscription-State", "terminated;reason=noresource");
7329 break;
7330 default:
7331 if (p->expiry)
7332 add_header(&req, "Subscription-State", "active");
7333 else /* Expired */
7334 add_header(&req, "Subscription-State", "terminated;reason=timeout");
7336 switch (p->subscribed) {
7337 case XPIDF_XML:
7338 case CPIM_PIDF_XML:
7339 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
7340 ast_build_string(&t, &maxbytes, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
7341 ast_build_string(&t, &maxbytes, "<presence>\n");
7342 ast_build_string(&t, &maxbytes, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
7343 ast_build_string(&t, &maxbytes, "<atom id=\"%s\">\n", p->exten);
7344 ast_build_string(&t, &maxbytes, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
7345 ast_build_string(&t, &maxbytes, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
7346 ast_build_string(&t, &maxbytes, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
7347 ast_build_string(&t, &maxbytes, "</address>\n</atom>\n</presence>\n");
7348 break;
7349 case PIDF_XML: /* Eyebeam supports this format */
7350 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
7351 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);
7352 ast_build_string(&t, &maxbytes, "<pp:person><status>\n");
7353 if (pidfstate[0] != '-')
7354 ast_build_string(&t, &maxbytes, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
7355 ast_build_string(&t, &maxbytes, "</status></pp:person>\n");
7356 ast_build_string(&t, &maxbytes, "<note>%s</note>\n", pidfnote); /* Note */
7357 ast_build_string(&t, &maxbytes, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
7358 ast_build_string(&t, &maxbytes, "<contact priority=\"1\">%s</contact>\n", mto);
7359 if (pidfstate[0] == 'b') /* Busy? Still open ... */
7360 ast_build_string(&t, &maxbytes, "<status><basic>open</basic></status>\n");
7361 else
7362 ast_build_string(&t, &maxbytes, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
7363 ast_build_string(&t, &maxbytes, "</tuple>\n</presence>\n");
7364 break;
7365 case DIALOG_INFO_XML: /* SNOM subscribes in this format */
7366 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
7367 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);
7368 if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
7369 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
7370 else
7371 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\">\n", p->exten);
7372 ast_build_string(&t, &maxbytes, "<state>%s</state>\n", statestring);
7373 if (state == AST_EXTENSION_ONHOLD) {
7374 ast_build_string(&t, &maxbytes, "<local>\n<target uri=\"%s\">\n"
7375 "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
7376 "</target>\n</local>\n", mto);
7378 ast_build_string(&t, &maxbytes, "</dialog>\n</dialog-info>\n");
7379 break;
7380 case NONE:
7381 default:
7382 break;
7385 if (t > tmp + sizeof(tmp))
7386 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
7388 add_header_contentLength(&req, strlen(tmp));
7389 add_line(&req, tmp);
7390 p->pendinginvite = p->ocseq; /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
7392 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7395 /*! \brief Notify user of messages waiting in voicemail
7396 \note - Notification only works for registered peers with mailbox= definitions
7397 in sip.conf
7398 - We use the SIP Event package message-summary
7399 MIME type defaults to "application/simple-message-summary";
7401 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
7403 struct sip_request req;
7404 char tmp[500];
7405 char *t = tmp;
7406 size_t maxbytes = sizeof(tmp);
7408 initreqprep(&req, p, SIP_NOTIFY);
7409 add_header(&req, "Event", "message-summary");
7410 add_header(&req, "Content-Type", default_notifymime);
7412 ast_build_string(&t, &maxbytes, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
7413 ast_build_string(&t, &maxbytes, "Message-Account: sip:%s@%s\r\n",
7414 S_OR(vmexten, default_vmexten), S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)));
7415 /* Cisco has a bug in the SIP stack where it can't accept the
7416 (0/0) notification. This can temporarily be disabled in
7417 sip.conf with the "buggymwi" option */
7418 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)"));
7420 if (p->subscribed) {
7421 if (p->expiry)
7422 add_header(&req, "Subscription-State", "active");
7423 else /* Expired */
7424 add_header(&req, "Subscription-State", "terminated;reason=timeout");
7427 if (t > tmp + sizeof(tmp))
7428 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
7430 add_header_contentLength(&req, strlen(tmp));
7431 add_line(&req, tmp);
7433 if (!p->initreq.headers)
7434 initialize_initreq(p, &req);
7435 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7438 /*! \brief Transmit SIP request unreliably (only used in sip_notify subsystem) */
7439 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req)
7441 if (!p->initreq.headers) /* Initialize first request before sending */
7442 initialize_initreq(p, req);
7443 return send_request(p, req, XMIT_UNRELIABLE, p->ocseq);
7446 /*! \brief Notify a transferring party of the status of transfer */
7447 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
7449 struct sip_request req;
7450 char tmp[SIPBUFSIZE/2];
7452 reqprep(&req, p, SIP_NOTIFY, 0, 1);
7453 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
7454 add_header(&req, "Event", tmp);
7455 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
7456 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
7457 add_header(&req, "Allow", ALLOWED_METHODS);
7458 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7460 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
7461 add_header_contentLength(&req, strlen(tmp));
7462 add_line(&req, tmp);
7464 if (!p->initreq.headers)
7465 initialize_initreq(p, &req);
7467 p->lastnoninvite = p->ocseq;
7469 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7472 /*! \brief Convert registration state status to string */
7473 static char *regstate2str(enum sipregistrystate regstate)
7475 switch(regstate) {
7476 case REG_STATE_FAILED:
7477 return "Failed";
7478 case REG_STATE_UNREGISTERED:
7479 return "Unregistered";
7480 case REG_STATE_REGSENT:
7481 return "Request Sent";
7482 case REG_STATE_AUTHSENT:
7483 return "Auth. Sent";
7484 case REG_STATE_REGISTERED:
7485 return "Registered";
7486 case REG_STATE_REJECTED:
7487 return "Rejected";
7488 case REG_STATE_TIMEOUT:
7489 return "Timeout";
7490 case REG_STATE_NOAUTH:
7491 return "No Authentication";
7492 default:
7493 return "Unknown";
7497 /*! \brief Update registration with SIP Proxy */
7498 static int sip_reregister(const void *data)
7500 /* if we are here, we know that we need to reregister. */
7501 struct sip_registry *r= ASTOBJ_REF((struct sip_registry *) data);
7503 /* if we couldn't get a reference to the registry object, punt */
7504 if (!r)
7505 return 0;
7507 if (r->call && !ast_test_flag(&r->call->flags[0], SIP_NO_HISTORY))
7508 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
7509 /* Since registry's are only added/removed by the the monitor thread, this
7510 may be overkill to reference/dereference at all here */
7511 if (sipdebug)
7512 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
7514 r->expire = -1;
7515 __sip_do_register(r);
7516 ASTOBJ_UNREF(r, sip_registry_destroy);
7517 return 0;
7520 /*! \brief Register with SIP proxy */
7521 static int __sip_do_register(struct sip_registry *r)
7523 int res;
7525 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
7526 return res;
7529 /*! \brief Registration timeout, register again */
7530 static int sip_reg_timeout(const void *data)
7533 /* if we are here, our registration timed out, so we'll just do it over */
7534 struct sip_registry *r = ASTOBJ_REF((struct sip_registry *) data);
7535 struct sip_pvt *p;
7536 int res;
7538 /* if we couldn't get a reference to the registry object, punt */
7539 if (!r)
7540 return 0;
7542 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
7543 if (r->call) {
7544 /* Unlink us, destroy old call. Locking is not relevant here because all this happens
7545 in the single SIP manager thread. */
7546 p = r->call;
7547 ast_mutex_lock(&p->lock);
7548 if (p->registry)
7549 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
7550 r->call = NULL;
7551 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
7552 /* Pretend to ACK anything just in case */
7553 __sip_pretend_ack(p);
7554 ast_mutex_unlock(&p->lock);
7556 /* If we have a limit, stop registration and give up */
7557 if (global_regattempts_max && (r->regattempts > global_regattempts_max)) {
7558 /* Ok, enough is enough. Don't try any more */
7559 /* We could add an external notification here...
7560 steal it from app_voicemail :-) */
7561 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
7562 r->regstate = REG_STATE_FAILED;
7563 } else {
7564 r->regstate = REG_STATE_UNREGISTERED;
7565 r->timeout = -1;
7566 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
7568 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));
7569 ASTOBJ_UNREF(r, sip_registry_destroy);
7570 return 0;
7573 /*! \brief Transmit register to SIP proxy or UA */
7574 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
7576 struct sip_request req;
7577 char from[256];
7578 char to[256];
7579 char tmp[80];
7580 char addr[80];
7581 struct sip_pvt *p;
7582 char *fromdomain;
7584 /* exit if we are already in process with this registrar ?*/
7585 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
7586 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
7587 return 0;
7590 if (r->call) { /* We have a registration */
7591 if (!auth) {
7592 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
7593 return 0;
7594 } else {
7595 p = r->call;
7596 make_our_tag(p->tag, sizeof(p->tag)); /* create a new local tag for every register attempt */
7597 ast_string_field_free(p, theirtag); /* forget their old tag, so we don't match tags when getting response */
7599 } else {
7600 /* Build callid for registration if we haven't registered before */
7601 if (!r->callid_valid) {
7602 build_callid_registry(r, __ourip, default_fromdomain);
7603 r->callid_valid = TRUE;
7605 /* Allocate SIP packet for registration */
7606 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER))) {
7607 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
7608 return 0;
7610 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
7611 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
7612 /* Find address to hostname */
7613 if (create_addr(p, r->hostname)) {
7614 /* we have what we hope is a temporary network error,
7615 * probably DNS. We need to reschedule a registration try */
7616 sip_destroy(p);
7618 if (r->timeout > -1)
7619 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
7620 else
7621 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);
7623 AST_SCHED_DEL(sched, r->timeout);
7624 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
7625 r->regattempts++;
7626 return 0;
7628 /* Copy back Call-ID in case create_addr changed it */
7629 ast_string_field_set(r, callid, p->callid);
7630 if (r->portno) {
7631 p->sa.sin_port = htons(r->portno);
7632 p->recv.sin_port = htons(r->portno);
7633 } else /* Set registry port to the port set from the peer definition/srv or default */
7634 r->portno = ntohs(p->sa.sin_port);
7635 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
7636 r->call=p; /* Save pointer to SIP packet */
7637 p->registry = ASTOBJ_REF(r); /* Add pointer to registry in packet */
7638 if (!ast_strlen_zero(r->secret)) /* Secret (password) */
7639 ast_string_field_set(p, peersecret, r->secret);
7640 if (!ast_strlen_zero(r->md5secret))
7641 ast_string_field_set(p, peermd5secret, r->md5secret);
7642 /* User name in this realm
7643 - if authuser is set, use that, otherwise use username */
7644 if (!ast_strlen_zero(r->authuser)) {
7645 ast_string_field_set(p, peername, r->authuser);
7646 ast_string_field_set(p, authname, r->authuser);
7647 } else if (!ast_strlen_zero(r->username)) {
7648 ast_string_field_set(p, peername, r->username);
7649 ast_string_field_set(p, authname, r->username);
7650 ast_string_field_set(p, fromuser, r->username);
7652 if (!ast_strlen_zero(r->username))
7653 ast_string_field_set(p, username, r->username);
7654 /* Save extension in packet */
7655 ast_string_field_set(p, exten, r->contact);
7658 check which address we should use in our contact header
7659 based on whether the remote host is on the external or
7660 internal network so we can register through nat
7662 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
7663 p->ourip = bindaddr.sin_addr;
7664 build_contact(p);
7667 /* set up a timeout */
7668 if (auth == NULL) {
7669 if (r->timeout > -1)
7670 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
7671 AST_SCHED_DEL(sched, r->timeout);
7672 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
7673 if (option_debug)
7674 ast_log(LOG_DEBUG, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
7677 if ((fromdomain = strchr(r->username, '@'))) {
7678 /* We have a domain in the username for registration */
7679 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
7680 if (!ast_strlen_zero(p->theirtag))
7681 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
7682 else
7683 snprintf(to, sizeof(to), "<sip:%s>", r->username);
7685 /* If the registration username contains '@', then the domain should be used as
7686 the equivalent of "fromdomain" for the registration */
7687 if (ast_strlen_zero(p->fromdomain)) {
7688 ast_string_field_set(p, fromdomain, ++fromdomain);
7690 } else {
7691 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
7692 if (!ast_strlen_zero(p->theirtag))
7693 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
7694 else
7695 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
7698 /* Fromdomain is what we are registering to, regardless of actual
7699 host name from SRV */
7700 if (!ast_strlen_zero(p->fromdomain)) {
7701 if (r->portno && r->portno != STANDARD_SIP_PORT)
7702 snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
7703 else
7704 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
7705 } else {
7706 if (r->portno && r->portno != STANDARD_SIP_PORT)
7707 snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
7708 else
7709 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
7711 ast_string_field_set(p, uri, addr);
7713 p->branch ^= ast_random();
7715 init_req(&req, sipmethod, addr);
7717 /* Add to CSEQ */
7718 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
7719 p->ocseq = r->ocseq;
7721 build_via(p);
7722 add_header(&req, "Via", p->via);
7723 add_header(&req, "From", from);
7724 add_header(&req, "To", to);
7725 add_header(&req, "Call-ID", p->callid);
7726 add_header(&req, "CSeq", tmp);
7727 if (!ast_strlen_zero(global_useragent))
7728 add_header(&req, "User-Agent", global_useragent);
7729 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
7732 if (auth) /* Add auth header */
7733 add_header(&req, authheader, auth);
7734 else if (!ast_strlen_zero(r->nonce)) {
7735 char digest[1024];
7737 /* We have auth data to reuse, build a digest header! */
7738 if (sipdebug)
7739 ast_log(LOG_DEBUG, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
7740 ast_string_field_set(p, realm, r->realm);
7741 ast_string_field_set(p, nonce, r->nonce);
7742 ast_string_field_set(p, domain, r->domain);
7743 ast_string_field_set(p, opaque, r->opaque);
7744 ast_string_field_set(p, qop, r->qop);
7745 r->noncecount++;
7746 p->noncecount = r->noncecount;
7748 memset(digest,0,sizeof(digest));
7749 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
7750 add_header(&req, "Authorization", digest);
7751 else
7752 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
7756 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
7757 add_header(&req, "Expires", tmp);
7758 add_header(&req, "Contact", p->our_contact);
7759 add_header(&req, "Event", "registration");
7760 add_header_contentLength(&req, 0);
7762 initialize_initreq(p, &req);
7763 if (sip_debug_test_pvt(p))
7764 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
7765 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
7766 r->regattempts++; /* Another attempt */
7767 if (option_debug > 3)
7768 ast_verbose("REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
7769 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
7772 /*! \brief Transmit text with SIP MESSAGE method */
7773 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
7775 struct sip_request req;
7777 reqprep(&req, p, SIP_MESSAGE, 0, 1);
7778 add_text(&req, text);
7779 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7782 /*! \brief Allocate SIP refer structure */
7783 static int sip_refer_allocate(struct sip_pvt *p)
7785 p->refer = ast_calloc(1, sizeof(struct sip_refer));
7786 return p->refer ? 1 : 0;
7789 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
7790 \note this is currently broken as we have no way of telling the dialplan
7791 engine whether a transfer succeeds or fails.
7792 \todo Fix the transfer() dialplan function so that a transfer may fail
7794 static int transmit_refer(struct sip_pvt *p, const char *dest)
7796 struct sip_request req = {
7797 .headers = 0,
7799 char from[256];
7800 const char *of;
7801 char *c;
7802 char referto[256];
7803 char *ttag, *ftag;
7804 char *theirtag = ast_strdupa(p->theirtag);
7806 if (option_debug || sipdebug)
7807 ast_log(LOG_DEBUG, "SIP transfer of %s to %s\n", p->callid, dest);
7809 /* Are we transfering an inbound or outbound call ? */
7810 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
7811 of = get_header(&p->initreq, "To");
7812 ttag = theirtag;
7813 ftag = p->tag;
7814 } else {
7815 of = get_header(&p->initreq, "From");
7816 ftag = theirtag;
7817 ttag = p->tag;
7820 ast_copy_string(from, of, sizeof(from));
7821 of = get_in_brackets(from);
7822 ast_string_field_set(p, from, of);
7823 if (strncasecmp(of, "sip:", 4))
7824 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
7825 else
7826 of += 4;
7827 /* Get just the username part */
7828 if ((c = strchr(dest, '@')))
7829 c = NULL;
7830 else if ((c = strchr(of, '@')))
7831 *c++ = '\0';
7832 if (c)
7833 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
7834 else
7835 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
7837 /* save in case we get 407 challenge */
7838 sip_refer_allocate(p);
7839 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
7840 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
7841 p->refer->status = REFER_SENT; /* Set refer status */
7843 reqprep(&req, p, SIP_REFER, 0, 1);
7845 add_header(&req, "Refer-To", referto);
7846 add_header(&req, "Allow", ALLOWED_METHODS);
7847 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7848 if (!ast_strlen_zero(p->our_contact))
7849 add_header(&req, "Referred-By", p->our_contact);
7851 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7852 /* We should propably wait for a NOTIFY here until we ack the transfer */
7853 /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
7855 /*! \todo In theory, we should hang around and wait for a reply, before
7856 returning to the dial plan here. Don't know really how that would
7857 affect the transfer() app or the pbx, but, well, to make this
7858 useful we should have a STATUS code on transfer().
7863 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
7864 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
7866 struct sip_request req;
7868 reqprep(&req, p, SIP_INFO, 0, 1);
7869 add_digit(&req, digit, duration);
7870 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7873 /*! \brief Send SIP INFO with video update request */
7874 static int transmit_info_with_vidupdate(struct sip_pvt *p)
7876 struct sip_request req;
7878 reqprep(&req, p, SIP_INFO, 0, 1);
7879 add_vidupdate(&req);
7880 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7883 /*! \brief Transmit generic SIP request
7884 returns XMIT_ERROR if transmit failed with a critical error (don't retry)
7886 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
7888 struct sip_request resp;
7890 if (sipmethod == SIP_ACK)
7891 p->invitestate = INV_CONFIRMED;
7893 reqprep(&resp, p, sipmethod, seqno, newbranch);
7894 add_header_contentLength(&resp, 0);
7895 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
7898 /*! \brief Transmit SIP request, auth added */
7899 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
7901 struct sip_request resp;
7903 reqprep(&resp, p, sipmethod, seqno, newbranch);
7904 if (!ast_strlen_zero(p->realm)) {
7905 char digest[1024];
7907 memset(digest, 0, sizeof(digest));
7908 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
7909 if (p->options && p->options->auth_type == PROXY_AUTH)
7910 add_header(&resp, "Proxy-Authorization", digest);
7911 else if (p->options && p->options->auth_type == WWW_AUTH)
7912 add_header(&resp, "Authorization", digest);
7913 else /* Default, to be backwards compatible (maybe being too careful, but leaving it for now) */
7914 add_header(&resp, "Proxy-Authorization", digest);
7915 } else
7916 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
7918 /* If we are hanging up and know a cause for that, send it in clear text to make
7919 debugging easier. */
7920 if (sipmethod == SIP_BYE && p->owner && p->owner->hangupcause) {
7921 char buf[10];
7923 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
7924 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
7925 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
7928 add_header_contentLength(&resp, 0);
7929 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
7932 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
7933 static void destroy_association(struct sip_peer *peer)
7935 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE)) {
7936 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
7937 ast_update_realtime("sippeers", "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "username", "", "regserver", "", NULL);
7938 else
7939 ast_db_del("SIP/Registry", peer->name);
7943 /*! \brief Expire registration of SIP peer */
7944 static int expire_register(const void *data)
7946 struct sip_peer *peer = (struct sip_peer *)data;
7948 if (!peer) /* Hmmm. We have no peer. Weird. */
7949 return 0;
7951 memset(&peer->addr, 0, sizeof(peer->addr));
7953 destroy_association(peer); /* remove registration data from storage */
7955 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
7956 register_peer_exten(peer, FALSE); /* Remove regexten */
7957 peer->expire = -1;
7958 ast_device_state_changed("SIP/%s", peer->name);
7960 /* Do we need to release this peer from memory?
7961 Only for realtime peers and autocreated peers
7963 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT) ||
7964 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
7965 struct sip_peer *peer_ptr = peer_ptr;
7966 peer_ptr = ASTOBJ_CONTAINER_UNLINK(&peerl, peer);
7967 if (peer_ptr) {
7968 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
7972 ASTOBJ_UNREF(peer, sip_destroy_peer);
7974 return 0;
7977 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
7978 static int sip_poke_peer_s(const void *data)
7980 struct sip_peer *peer = (struct sip_peer *) data;
7982 peer->pokeexpire = -1;
7984 sip_poke_peer(peer);
7986 ASTOBJ_UNREF(peer, sip_destroy_peer);
7988 return 0;
7991 /*! \brief Get registration details from Asterisk DB */
7992 static void reg_source_db(struct sip_peer *peer)
7994 char data[256];
7995 struct in_addr in;
7996 int expiry;
7997 int port;
7998 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
8000 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
8001 return;
8002 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
8003 return;
8005 scan = data;
8006 addr = strsep(&scan, ":");
8007 port_str = strsep(&scan, ":");
8008 expiry_str = strsep(&scan, ":");
8009 username = strsep(&scan, ":");
8010 contact = scan; /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
8012 if (!inet_aton(addr, &in))
8013 return;
8015 if (port_str)
8016 port = atoi(port_str);
8017 else
8018 return;
8020 if (expiry_str)
8021 expiry = atoi(expiry_str);
8022 else
8023 return;
8025 if (username)
8026 ast_copy_string(peer->username, username, sizeof(peer->username));
8027 if (contact)
8028 ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
8030 if (option_debug > 1)
8031 ast_log(LOG_DEBUG, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
8032 peer->name, peer->username, ast_inet_ntoa(in), port, expiry);
8034 memset(&peer->addr, 0, sizeof(peer->addr));
8035 peer->addr.sin_family = AF_INET;
8036 peer->addr.sin_addr = in;
8037 peer->addr.sin_port = htons(port);
8038 if (sipsock < 0) {
8039 /* SIP isn't up yet, so schedule a poke only, pretty soon */
8040 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
8041 struct sip_peer *peer_ptr = peer;
8042 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8044 peer->pokeexpire = ast_sched_add(sched, ast_random() % 5000 + 1, sip_poke_peer_s, ASTOBJ_REF(peer));
8045 if (peer->pokeexpire == -1) {
8046 struct sip_peer *peer_ptr = peer;
8047 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8049 } else
8050 sip_poke_peer(peer);
8051 if (!AST_SCHED_DEL(sched, peer->expire)) {
8052 struct sip_peer *peer_ptr = peer;
8053 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8055 peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, ASTOBJ_REF(peer));
8056 if (peer->expire == -1) {
8057 struct sip_peer *peer_ptr = peer;
8058 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8060 register_peer_exten(peer, TRUE);
8063 /*! \brief Save contact header for 200 OK on INVITE */
8064 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
8066 char contact[SIPBUFSIZE];
8067 char *c;
8069 /* Look for brackets */
8070 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
8071 c = get_in_brackets(contact);
8073 /* Save full contact to call pvt for later bye or re-invite */
8074 ast_string_field_set(pvt, fullcontact, c);
8076 /* Save URI for later ACKs, BYE or RE-invites */
8077 ast_string_field_set(pvt, okcontacturi, c);
8079 /* We should return false for URI:s we can't handle,
8080 like sips:, tel:, mailto:,ldap: etc */
8081 return TRUE;
8084 /*! \brief Change the other partys IP address based on given contact */
8085 static int set_address_from_contact(struct sip_pvt *pvt)
8087 struct hostent *hp;
8088 struct ast_hostent ahp;
8089 int port;
8090 char *c, *host, *pt;
8091 char contact_buf[256];
8092 char *contact;
8094 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
8095 /* NAT: Don't trust the contact field. Just use what they came to us
8096 with. */
8097 pvt->sa = pvt->recv;
8098 return 0;
8101 /* Work on a copy */
8102 ast_copy_string(contact_buf, pvt->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 pvt->sa.sin_family = AF_INET;
8140 memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
8141 pvt->sa.sin_port = htons(port);
8143 return 0;
8147 /*! \brief Parse contact header and save registration (peer registration) */
8148 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
8150 char contact[SIPBUFSIZE];
8151 char data[SIPBUFSIZE];
8152 const char *expires = get_header(req, "Expires");
8153 int expiry = atoi(expires);
8154 char *curi, *n, *pt;
8155 int port;
8156 const char *useragent;
8157 struct hostent *hp;
8158 struct ast_hostent ahp;
8159 struct sockaddr_in oldsin;
8161 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
8163 if (ast_strlen_zero(expires)) { /* No expires header */
8164 expires = strcasestr(contact, ";expires=");
8165 if (expires) {
8166 /* XXX bug here, we overwrite the string */
8167 expires = strsep((char **) &expires, ";"); /* trim ; and beyond */
8168 if (sscanf(expires + 9, "%d", &expiry) != 1)
8169 expiry = default_expiry;
8170 } else {
8171 /* Nothing has been specified */
8172 expiry = default_expiry;
8176 /* Look for brackets */
8177 curi = contact;
8178 if (strchr(contact, '<') == NULL) /* No <, check for ; and strip it */
8179 strsep(&curi, ";"); /* This is Header options, not URI options */
8180 curi = get_in_brackets(contact);
8182 /* if they did not specify Contact: or Expires:, they are querying
8183 what we currently have stored as their contact address, so return
8186 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
8187 /* If we have an active registration, tell them when the registration is going to expire */
8188 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
8189 pvt->expiry = ast_sched_when(sched, peer->expire);
8190 return PARSE_REGISTER_QUERY;
8191 } else if (!strcasecmp(curi, "*") || !expiry) { /* Unregister this peer */
8192 /* This means remove all registrations and return OK */
8193 memset(&peer->addr, 0, sizeof(peer->addr));
8194 if (!AST_SCHED_DEL(sched, peer->expire)) {
8195 struct sip_peer *peer_ptr = peer;
8196 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8199 destroy_association(peer);
8201 register_peer_exten(peer, 0); /* Add extension from regexten= setting in sip.conf */
8202 peer->fullcontact[0] = '\0';
8203 peer->useragent[0] = '\0';
8204 peer->sipoptions = 0;
8205 peer->lastms = 0;
8207 if (option_verbose > 2)
8208 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", peer->name);
8209 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
8210 return PARSE_REGISTER_UPDATE;
8213 /* Store whatever we got as a contact from the client */
8214 ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));
8216 /* For the 200 OK, we should use the received contact */
8217 ast_string_field_build(pvt, our_contact, "<%s>", curi);
8219 /* Make sure it's a SIP URL */
8220 if (strncasecmp(curi, "sip:", 4)) {
8221 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", curi);
8222 } else
8223 curi += 4;
8224 /* Ditch q */
8225 curi = strsep(&curi, ";");
8226 /* Grab host */
8227 n = strchr(curi, '@');
8228 if (!n) {
8229 n = curi;
8230 curi = NULL;
8231 } else
8232 *n++ = '\0';
8233 pt = strchr(n, ':');
8234 if (pt) {
8235 *pt++ = '\0';
8236 port = atoi(pt);
8237 } else
8238 port = STANDARD_SIP_PORT;
8239 oldsin = peer->addr;
8240 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
8241 /* XXX This could block for a long time XXX */
8242 hp = ast_gethostbyname(n, &ahp);
8243 if (!hp) {
8244 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
8245 return PARSE_REGISTER_FAILED;
8247 peer->addr.sin_family = AF_INET;
8248 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
8249 peer->addr.sin_port = htons(port);
8250 } else {
8251 /* Don't trust the contact field. Just use what they came to us
8252 with */
8253 peer->addr = pvt->recv;
8256 /* Save SIP options profile */
8257 peer->sipoptions = pvt->sipoptions;
8259 if (curi && ast_strlen_zero(peer->username))
8260 ast_copy_string(peer->username, curi, sizeof(peer->username));
8262 if (!AST_SCHED_DEL(sched, peer->expire)) {
8263 struct sip_peer *peer_ptr = peer;
8264 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8266 if (expiry > max_expiry)
8267 expiry = max_expiry;
8268 if (expiry < min_expiry)
8269 expiry = min_expiry;
8270 if (ast_test_flag(&peer->flags[0], SIP_REALTIME)) {
8271 peer->expire = -1;
8272 } else {
8273 peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, ASTOBJ_REF(peer));
8274 if (peer->expire == -1) {
8275 struct sip_peer *peer_ptr = peer;
8276 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
8279 pvt->expiry = expiry;
8280 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);
8281 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
8282 ast_db_put("SIP/Registry", peer->name, data);
8283 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
8285 /* Is this a new IP address for us? */
8286 if (inaddrcmp(&peer->addr, &oldsin)) {
8287 sip_poke_peer(peer);
8288 if (option_verbose > 2)
8289 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);
8290 register_peer_exten(peer, 1);
8293 /* Save User agent */
8294 useragent = get_header(req, "User-Agent");
8295 if (strcasecmp(useragent, peer->useragent)) { /* XXX copy if they are different ? */
8296 ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
8297 if (option_verbose > 3)
8298 ast_verbose(VERBOSE_PREFIX_3 "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
8300 return PARSE_REGISTER_UPDATE;
8303 /*! \brief Remove route from route list */
8304 static void free_old_route(struct sip_route *route)
8306 struct sip_route *next;
8308 while (route) {
8309 next = route->next;
8310 free(route);
8311 route = next;
8315 /*! \brief List all routes - mostly for debugging */
8316 static void list_route(struct sip_route *route)
8318 if (!route)
8319 ast_verbose("list_route: no route\n");
8320 else {
8321 for (;route; route = route->next)
8322 ast_verbose("list_route: hop: <%s>\n", route->hop);
8326 /*! \brief Build route list from Record-Route header */
8327 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
8329 struct sip_route *thishop, *head, *tail;
8330 int start = 0;
8331 int len;
8332 const char *rr, *contact, *c;
8334 /* Once a persistant route is set, don't fool with it */
8335 if (p->route && p->route_persistant) {
8336 if (option_debug)
8337 ast_log(LOG_DEBUG, "build_route: Retaining previous route: <%s>\n", p->route->hop);
8338 return;
8341 if (p->route) {
8342 free_old_route(p->route);
8343 p->route = NULL;
8346 /* We only want to create the route set the first time this is called */
8347 p->route_persistant = 1;
8349 /* Build a tailq, then assign it to p->route when done.
8350 * If backwards, we add entries from the head so they end up
8351 * in reverse order. However, we do need to maintain a correct
8352 * tail pointer because the contact is always at the end.
8354 head = NULL;
8355 tail = head;
8356 /* 1st we pass through all the hops in any Record-Route headers */
8357 for (;;) {
8358 /* Each Record-Route header */
8359 rr = __get_header(req, "Record-Route", &start);
8360 if (*rr == '\0')
8361 break;
8362 for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
8363 ++rr;
8364 len = strcspn(rr, ">") + 1;
8365 /* Make a struct route */
8366 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
8367 /* ast_calloc is not needed because all fields are initialized in this block */
8368 ast_copy_string(thishop->hop, rr, len);
8369 if (option_debug > 1)
8370 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
8371 /* Link in */
8372 if (backwards) {
8373 /* Link in at head so they end up in reverse order */
8374 thishop->next = head;
8375 head = thishop;
8376 /* If this was the first then it'll be the tail */
8377 if (!tail)
8378 tail = thishop;
8379 } else {
8380 thishop->next = NULL;
8381 /* Link in at the end */
8382 if (tail)
8383 tail->next = thishop;
8384 else
8385 head = thishop;
8386 tail = thishop;
8392 /* Only append the contact if we are dealing with a strict router */
8393 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop,";lr") == NULL) ) {
8394 /* 2nd append the Contact: if there is one */
8395 /* Can be multiple Contact headers, comma separated values - we just take the first */
8396 contact = get_header(req, "Contact");
8397 if (!ast_strlen_zero(contact)) {
8398 if (option_debug > 1)
8399 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
8400 /* Look for <: delimited address */
8401 c = strchr(contact, '<');
8402 if (c) {
8403 /* Take to > */
8404 ++c;
8405 len = strcspn(c, ">") + 1;
8406 } else {
8407 /* No <> - just take the lot */
8408 c = contact;
8409 len = strlen(contact) + 1;
8411 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
8412 /* ast_calloc is not needed because all fields are initialized in this block */
8413 ast_copy_string(thishop->hop, c, len);
8414 thishop->next = NULL;
8415 /* Goes at the end */
8416 if (tail)
8417 tail->next = thishop;
8418 else
8419 head = thishop;
8424 /* Store as new route */
8425 p->route = head;
8427 /* For debugging dump what we ended up with */
8428 if (sip_debug_test_pvt(p))
8429 list_route(p->route);
8432 AST_THREADSTORAGE(check_auth_buf, check_auth_buf_init);
8433 #define CHECK_AUTH_BUF_INITLEN 256
8435 /*! \brief Check user authorization from peer definition
8436 Some actions, like REGISTER and INVITEs from peers require
8437 authentication (if peer have secret set)
8438 \return 0 on success, non-zero on error
8440 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
8441 const char *secret, const char *md5secret, int sipmethod,
8442 char *uri, enum xmittype reliable, int ignore)
8444 const char *response = "407 Proxy Authentication Required";
8445 const char *reqheader = "Proxy-Authorization";
8446 const char *respheader = "Proxy-Authenticate";
8447 const char *authtoken;
8448 char a1_hash[256];
8449 char resp_hash[256]="";
8450 char *c;
8451 int wrongnonce = FALSE;
8452 int good_response;
8453 const char *usednonce = p->randdata;
8454 struct ast_dynamic_str *buf;
8455 int res;
8457 /* table of recognised keywords, and their value in the digest */
8458 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
8459 struct x {
8460 const char *key;
8461 const char *s;
8462 } *i, keys[] = {
8463 [K_RESP] = { "response=", "" },
8464 [K_URI] = { "uri=", "" },
8465 [K_USER] = { "username=", "" },
8466 [K_NONCE] = { "nonce=", "" },
8467 [K_LAST] = { NULL, NULL}
8470 /* Always OK if no secret */
8471 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
8472 return AUTH_SUCCESSFUL;
8473 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
8474 /* On a REGISTER, we have to use 401 and its family of headers instead of 407 and its family
8475 of headers -- GO SIP! Whoo hoo! Two things that do the same thing but are used in
8476 different circumstances! What a surprise. */
8477 response = "401 Unauthorized";
8478 reqheader = "Authorization";
8479 respheader = "WWW-Authenticate";
8481 authtoken = get_header(req, reqheader);
8482 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
8483 /* This is a retransmitted invite/register/etc, don't reconstruct authentication
8484 information */
8485 if (!reliable) {
8486 /* Resend message if this was NOT a reliable delivery. Otherwise the
8487 retransmission should get it */
8488 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
8489 /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
8490 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8492 return AUTH_CHALLENGE_SENT;
8493 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
8494 /* We have no auth, so issue challenge and request authentication */
8495 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
8496 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
8497 /* Schedule auto destroy in 32 seconds */
8498 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8499 return AUTH_CHALLENGE_SENT;
8502 /* --- We have auth, so check it */
8504 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
8505 an example in the spec of just what it is you're doing a hash on. */
8507 if (!(buf = ast_dynamic_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
8508 return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
8510 /* Make a copy of the response and parse it */
8511 res = ast_dynamic_str_thread_set(&buf, 0, &check_auth_buf, "%s", authtoken);
8513 if (res == AST_DYNSTR_BUILD_FAILED)
8514 return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
8516 c = buf->str;
8518 while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
8519 for (i = keys; i->key != NULL; i++) {
8520 const char *separator = ","; /* default */
8522 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
8523 continue;
8524 /* Found. Skip keyword, take text in quotes or up to the separator. */
8525 c += strlen(i->key);
8526 if (*c == '"') { /* in quotes. Skip first and look for last */
8527 c++;
8528 separator = "\"";
8530 i->s = c;
8531 strsep(&c, separator);
8532 break;
8534 if (i->key == NULL) /* not found, jump after space or comma */
8535 strsep(&c, " ,");
8538 /* Verify that digest username matches the username we auth as */
8539 if (strcmp(username, keys[K_USER].s)) {
8540 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
8541 username, keys[K_USER].s);
8542 /* Oops, we're trying something here */
8543 return AUTH_USERNAME_MISMATCH;
8546 /* Verify nonce from request matches our nonce. If not, send 401 with new nonce */
8547 if (strcasecmp(p->randdata, keys[K_NONCE].s)) { /* XXX it was 'n'casecmp ? */
8548 wrongnonce = TRUE;
8549 usednonce = keys[K_NONCE].s;
8552 if (!ast_strlen_zero(md5secret))
8553 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
8554 else {
8555 char a1[256];
8556 snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
8557 ast_md5_hash(a1_hash, a1);
8560 /* compute the expected response to compare with what we received */
8562 char a2[256];
8563 char a2_hash[256];
8564 char resp[256];
8566 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
8567 S_OR(keys[K_URI].s, uri));
8568 ast_md5_hash(a2_hash, a2);
8569 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
8570 ast_md5_hash(resp_hash, resp);
8573 good_response = keys[K_RESP].s &&
8574 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
8575 if (wrongnonce) {
8576 if (good_response) {
8577 if (sipdebug)
8578 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
8579 /* We got working auth token, based on stale nonce . */
8580 ast_string_field_build(p, randdata, "%08lx", ast_random());
8581 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
8582 } else {
8583 /* Everything was wrong, so give the device one more try with a new challenge */
8584 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
8585 if (sipdebug)
8586 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
8587 ast_string_field_build(p, randdata, "%08lx", ast_random());
8588 } else {
8589 if (sipdebug)
8590 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
8592 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
8595 /* Schedule auto destroy in 32 seconds */
8596 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8597 return AUTH_CHALLENGE_SENT;
8599 if (good_response) {
8600 append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
8601 return AUTH_SUCCESSFUL;
8604 /* Ok, we have a bad username/secret pair */
8605 /* Tell the UAS not to re-send this authentication data, because
8606 it will continue to fail
8609 return AUTH_SECRET_FAILED;
8612 /*! \brief Change onhold state of a peer using a pvt structure */
8613 static void sip_peer_hold(struct sip_pvt *p, int hold)
8615 struct sip_peer *peer = find_peer(p->peername, NULL, 1);
8617 if (!peer)
8618 return;
8620 /* If they put someone on hold, increment the value... otherwise decrement it */
8621 if (hold)
8622 peer->onHold++;
8623 else
8624 peer->onHold--;
8626 /* Request device state update */
8627 ast_device_state_changed("SIP/%s", peer->name);
8629 return;
8632 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
8633 \note If you add an "hint" priority to the extension in the dial plan,
8634 you will get notifications on device state changes */
8635 static int cb_extensionstate(char *context, char* exten, int state, void *data)
8637 struct sip_pvt *p = data;
8639 ast_mutex_lock(&p->lock);
8641 switch(state) {
8642 case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
8643 case AST_EXTENSION_REMOVED: /* Extension is gone */
8644 if (p->autokillid > -1 && sip_cancel_destroy(p)) /* Remove subscription expiry for renewals */
8645 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
8646 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); /* Delete subscription in 32 secs */
8647 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);
8648 p->stateid = -1;
8649 p->subscribed = NONE;
8650 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
8651 break;
8652 default: /* Tell user */
8653 p->laststate = state;
8654 break;
8656 if (p->subscribed != NONE) { /* Only send state NOTIFY if we know the format */
8657 if (!p->pendinginvite) {
8658 transmit_state_notify(p, state, 1, FALSE);
8659 } else {
8660 /* We already have a NOTIFY sent that is not answered. Queue the state up.
8661 if many state changes happen meanwhile, we will only send a notification of the last one */
8662 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
8665 if (option_verbose > 1)
8666 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,
8667 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
8670 ast_mutex_unlock(&p->lock);
8672 return 0;
8675 /*! \brief Send a fake 401 Unauthorized response when the administrator
8676 wants to hide the names of local users/peers from fishers
8678 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable)
8680 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
8681 transmit_response_with_auth(p, "401 Unauthorized", req, p->randdata, reliable, "WWW-Authenticate", 0);
8684 /*! \brief Verify registration of user
8685 - Registration is done in several steps, first a REGISTER without auth
8686 to get a challenge (nonce) then a second one with auth
8687 - Registration requests are only matched with peers that are marked as "dynamic"
8689 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
8690 struct sip_request *req, char *uri)
8692 enum check_auth_result res = AUTH_NOT_FOUND;
8693 struct sip_peer *peer;
8694 char tmp[256];
8695 char *name, *c;
8696 char *t;
8697 char *domain;
8699 /* Terminate URI */
8700 t = uri;
8701 while(*t && (*t > 32) && (*t != ';'))
8702 t++;
8703 *t = '\0';
8705 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
8706 if (pedanticsipchecking)
8707 ast_uri_decode(tmp);
8709 c = get_in_brackets(tmp);
8710 c = strsep(&c, ";"); /* Ditch ;user=phone */
8712 if (!strncasecmp(c, "sip:", 4)) {
8713 name = c + 4;
8714 } else {
8715 name = c;
8716 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
8719 /* Strip off the domain name */
8720 if ((c = strchr(name, '@'))) {
8721 *c++ = '\0';
8722 domain = c;
8723 if ((c = strchr(domain, ':'))) /* Remove :port */
8724 *c = '\0';
8725 if (!AST_LIST_EMPTY(&domain_list)) {
8726 if (!check_sip_domain(domain, NULL, 0)) {
8727 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
8728 return AUTH_UNKNOWN_DOMAIN;
8733 ast_string_field_set(p, exten, name);
8734 build_contact(p);
8735 peer = find_peer(name, NULL, 1);
8736 if (!(peer && ast_apply_ha(peer->ha, sin))) {
8737 /* Peer fails ACL check */
8738 if (peer) {
8739 ASTOBJ_UNREF(peer, sip_destroy_peer);
8740 res = AUTH_ACL_FAILED;
8741 } else
8742 res = AUTH_NOT_FOUND;
8744 if (peer) {
8745 /* Set Frame packetization */
8746 if (p->rtp) {
8747 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
8748 p->autoframing = peer->autoframing;
8750 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
8751 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
8752 res = AUTH_PEER_NOT_DYNAMIC;
8753 } else {
8754 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
8755 transmit_response(p, "100 Trying", req);
8756 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, ast_test_flag(req, SIP_PKT_IGNORE)))) {
8757 if (sip_cancel_destroy(p))
8758 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
8760 /* We have a succesful registration attemp with proper authentication,
8761 now, update the peer */
8762 switch (parse_register_contact(p, peer, req)) {
8763 case PARSE_REGISTER_FAILED:
8764 ast_log(LOG_WARNING, "Failed to parse contact info\n");
8765 transmit_response_with_date(p, "400 Bad Request", req);
8766 peer->lastmsgssent = -1;
8767 res = 0;
8768 break;
8769 case PARSE_REGISTER_QUERY:
8770 transmit_response_with_date(p, "200 OK", req);
8771 peer->lastmsgssent = -1;
8772 res = 0;
8773 break;
8774 case PARSE_REGISTER_UPDATE:
8775 update_peer(peer, p->expiry);
8776 /* Say OK and ask subsystem to retransmit msg counter */
8777 transmit_response_with_date(p, "200 OK", req);
8778 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
8779 peer->lastmsgssent = -1;
8780 res = 0;
8781 break;
8786 if (!peer && autocreatepeer) {
8787 /* Create peer if we have autocreate mode enabled */
8788 peer = temp_peer(name);
8789 if (peer) {
8790 ASTOBJ_CONTAINER_LINK(&peerl, peer);
8791 if (sip_cancel_destroy(p))
8792 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
8793 switch (parse_register_contact(p, peer, req)) {
8794 case PARSE_REGISTER_FAILED:
8795 ast_log(LOG_WARNING, "Failed to parse contact info\n");
8796 transmit_response_with_date(p, "400 Bad Request", req);
8797 peer->lastmsgssent = -1;
8798 res = 0;
8799 break;
8800 case PARSE_REGISTER_QUERY:
8801 transmit_response_with_date(p, "200 OK", req);
8802 peer->lastmsgssent = -1;
8803 res = 0;
8804 break;
8805 case PARSE_REGISTER_UPDATE:
8806 /* Say OK and ask subsystem to retransmit msg counter */
8807 transmit_response_with_date(p, "200 OK", req);
8808 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
8809 peer->lastmsgssent = -1;
8810 res = 0;
8811 break;
8815 if (!res) {
8816 ast_device_state_changed("SIP/%s", peer->name);
8818 if (res < 0) {
8819 switch (res) {
8820 case AUTH_SECRET_FAILED:
8821 /* Wrong password in authentication. Go away, don't try again until you fixed it */
8822 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
8823 break;
8824 case AUTH_USERNAME_MISMATCH:
8825 /* Username and digest username does not match.
8826 Asterisk uses the From: username for authentication. We need the
8827 users to use the same authentication user name until we support
8828 proper authentication by digest auth name */
8829 transmit_response(p, "403 Authentication user name does not match account name", &p->initreq);
8830 break;
8831 case AUTH_NOT_FOUND:
8832 case AUTH_PEER_NOT_DYNAMIC:
8833 case AUTH_ACL_FAILED:
8834 if (global_alwaysauthreject) {
8835 transmit_fake_auth_response(p, &p->initreq, 1);
8836 } else {
8837 /* URI not found */
8838 if (res == AUTH_PEER_NOT_DYNAMIC)
8839 transmit_response(p, "403 Forbidden", &p->initreq);
8840 else
8841 transmit_response(p, "404 Not found", &p->initreq);
8843 break;
8844 default:
8845 break;
8848 if (peer)
8849 ASTOBJ_UNREF(peer, sip_destroy_peer);
8851 return res;
8854 /*! \brief Get referring dnis */
8855 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
8857 char tmp[256], *c, *a;
8858 struct sip_request *req;
8860 req = oreq;
8861 if (!req)
8862 req = &p->initreq;
8863 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
8864 if (ast_strlen_zero(tmp))
8865 return 0;
8866 c = get_in_brackets(tmp);
8867 if (strncasecmp(c, "sip:", 4)) {
8868 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", c);
8869 return -1;
8871 c += 4;
8872 a = c;
8873 strsep(&a, "@;"); /* trim anything after @ or ; */
8874 if (sip_debug_test_pvt(p))
8875 ast_verbose("RDNIS is %s\n", c);
8876 ast_string_field_set(p, rdnis, c);
8878 return 0;
8881 /*! \brief Find out who the call is for
8882 We use the INVITE uri to find out
8884 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
8886 char tmp[256] = "", *uri, *a;
8887 char tmpf[256] = "", *from;
8888 struct sip_request *req;
8889 char *colon;
8890 char *decoded_uri;
8892 req = oreq;
8893 if (!req)
8894 req = &p->initreq;
8896 /* Find the request URI */
8897 if (req->rlPart2)
8898 ast_copy_string(tmp, req->rlPart2, sizeof(tmp));
8900 if (pedanticsipchecking)
8901 ast_uri_decode(tmp);
8903 uri = get_in_brackets(tmp);
8905 if (strncasecmp(uri, "sip:", 4)) {
8906 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
8907 return -1;
8909 uri += 4;
8911 /* Now find the From: caller ID and name */
8912 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
8913 if (!ast_strlen_zero(tmpf)) {
8914 if (pedanticsipchecking)
8915 ast_uri_decode(tmpf);
8916 from = get_in_brackets(tmpf);
8917 } else {
8918 from = NULL;
8921 if (!ast_strlen_zero(from)) {
8922 if (strncasecmp(from, "sip:", 4)) {
8923 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
8924 return -1;
8926 from += 4;
8927 if ((a = strchr(from, '@')))
8928 *a++ = '\0';
8929 else
8930 a = from; /* just a domain */
8931 from = strsep(&from, ";"); /* Remove userinfo options */
8932 a = strsep(&a, ";"); /* Remove URI options */
8933 ast_string_field_set(p, fromdomain, a);
8936 /* Skip any options and find the domain */
8938 /* Get the target domain */
8939 if ((a = strchr(uri, '@'))) {
8940 *a++ = '\0';
8941 } else { /* No username part */
8942 a = uri;
8943 uri = "s"; /* Set extension to "s" */
8945 colon = strchr(a, ':'); /* Remove :port */
8946 if (colon)
8947 *colon = '\0';
8949 uri = strsep(&uri, ";"); /* Remove userinfo options */
8950 a = strsep(&a, ";"); /* Remove URI options */
8952 ast_string_field_set(p, domain, a);
8954 if (!AST_LIST_EMPTY(&domain_list)) {
8955 char domain_context[AST_MAX_EXTENSION];
8957 domain_context[0] = '\0';
8958 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
8959 if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
8960 if (option_debug)
8961 ast_log(LOG_DEBUG, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
8962 return -2;
8965 /* If we have a context defined, overwrite the original context */
8966 if (!ast_strlen_zero(domain_context))
8967 ast_string_field_set(p, context, domain_context);
8970 /* If the request coming in is a subscription and subscribecontext has been specified use it */
8971 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
8972 ast_string_field_set(p, context, p->subscribecontext);
8974 if (sip_debug_test_pvt(p))
8975 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
8977 /* If this is a subscription we actually just need to see if a hint exists for the extension */
8978 if (req->method == SIP_SUBSCRIBE) {
8979 char hint[AST_MAX_EXTENSION];
8980 return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
8981 } else {
8982 decoded_uri = ast_strdupa(uri);
8983 ast_uri_decode(decoded_uri);
8984 /* Check the dialplan for the username part of the request URI,
8985 the domain will be stored in the SIPDOMAIN variable
8986 Since extensions.conf can have unescaped characters, try matching a decoded
8987 uri in addition to the non-decoded uri
8988 Return 0 if we have a matching extension */
8989 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)) ||
8990 !strcmp(decoded_uri, ast_pickup_ext())) {
8991 if (!oreq)
8992 ast_string_field_set(p, exten, decoded_uri);
8993 return 0;
8997 /* Return 1 for pickup extension or overlap dialling support (if we support it) */
8998 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
8999 ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
9000 !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
9001 return 1;
9004 return -1;
9007 /*! \brief Lock interface lock and find matching pvt lock
9008 - Their tag is fromtag, our tag is to-tag
9009 - This means that in some transactions, totag needs to be their tag :-)
9010 depending upon the direction
9012 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
9014 struct sip_pvt *sip_pvt_ptr;
9016 ast_mutex_lock(&iflock);
9018 if (option_debug > 3 && totag)
9019 ast_log(LOG_DEBUG, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
9021 /* Search interfaces and find the match */
9022 for (sip_pvt_ptr = iflist; sip_pvt_ptr; sip_pvt_ptr = sip_pvt_ptr->next) {
9023 if (!strcmp(sip_pvt_ptr->callid, callid)) {
9024 int match = 1;
9025 char *ourtag = sip_pvt_ptr->tag;
9027 /* Go ahead and lock it (and its owner) before returning */
9028 ast_mutex_lock(&sip_pvt_ptr->lock);
9030 /* Check if tags match. If not, this is not the call we want
9031 (With a forking SIP proxy, several call legs share the
9032 call id, but have different tags)
9034 if (pedanticsipchecking && (strcmp(fromtag, sip_pvt_ptr->theirtag) || (!ast_strlen_zero(totag) && strcmp(totag, ourtag))))
9035 match = 0;
9037 if (!match) {
9038 ast_mutex_unlock(&sip_pvt_ptr->lock);
9039 continue;
9042 if (option_debug > 3 && totag)
9043 ast_log(LOG_DEBUG, "Matched %s call - their tag is %s Our tag is %s\n",
9044 ast_test_flag(&sip_pvt_ptr->flags[0], SIP_OUTGOING) ? "OUTGOING": "INCOMING",
9045 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
9047 /* deadlock avoidance... */
9048 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
9049 DEADLOCK_AVOIDANCE(&sip_pvt_ptr->lock);
9051 break;
9054 ast_mutex_unlock(&iflock);
9055 if (option_debug > 3 && !sip_pvt_ptr)
9056 ast_log(LOG_DEBUG, "Found no match for callid %s to-tag %s from-tag %s\n", callid, totag, fromtag);
9057 return sip_pvt_ptr;
9060 /*! \brief Call transfer support (the REFER method)
9061 * Extracts Refer headers into pvt dialog structure */
9062 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
9065 const char *p_referred_by = NULL;
9066 char *h_refer_to = NULL;
9067 char *h_referred_by = NULL;
9068 char *refer_to;
9069 const char *p_refer_to;
9070 char *referred_by_uri = NULL;
9071 char *ptr;
9072 struct sip_request *req = NULL;
9073 const char *transfer_context = NULL;
9074 struct sip_refer *referdata;
9077 req = outgoing_req;
9078 referdata = transferer->refer;
9080 if (!req)
9081 req = &transferer->initreq;
9083 p_refer_to = get_header(req, "Refer-To");
9084 if (ast_strlen_zero(p_refer_to)) {
9085 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
9086 return -2; /* Syntax error */
9088 h_refer_to = ast_strdupa(p_refer_to);
9089 refer_to = get_in_brackets(h_refer_to);
9090 if (pedanticsipchecking)
9091 ast_uri_decode(refer_to);
9093 if (strncasecmp(refer_to, "sip:", 4)) {
9094 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
9095 return -3;
9097 refer_to += 4; /* Skip sip: */
9099 /* Get referred by header if it exists */
9100 p_referred_by = get_header(req, "Referred-By");
9101 if (!ast_strlen_zero(p_referred_by)) {
9102 char *lessthan;
9103 h_referred_by = ast_strdupa(p_referred_by);
9104 if (pedanticsipchecking)
9105 ast_uri_decode(h_referred_by);
9107 /* Store referrer's caller ID name */
9108 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
9109 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
9110 *(lessthan - 1) = '\0'; /* Space */
9113 referred_by_uri = get_in_brackets(h_referred_by);
9114 if(strncasecmp(referred_by_uri, "sip:", 4)) {
9115 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
9116 referred_by_uri = (char *) NULL;
9117 } else {
9118 referred_by_uri += 4; /* Skip sip: */
9122 /* Check for arguments in the refer_to header */
9123 if ((ptr = strchr(refer_to, '?'))) { /* Search for arguments */
9124 *ptr++ = '\0';
9125 if (!strncasecmp(ptr, "REPLACES=", 9)) {
9126 char *to = NULL, *from = NULL;
9128 /* This is an attended transfer */
9129 referdata->attendedtransfer = 1;
9130 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
9131 ast_uri_decode(referdata->replaces_callid);
9132 if ((ptr = strchr(referdata->replaces_callid, ';'))) /* Find options */ {
9133 *ptr++ = '\0';
9136 if (ptr) {
9137 /* Find the different tags before we destroy the string */
9138 to = strcasestr(ptr, "to-tag=");
9139 from = strcasestr(ptr, "from-tag=");
9142 /* Grab the to header */
9143 if (to) {
9144 ptr = to + 7;
9145 if ((to = strchr(ptr, '&')))
9146 *to = '\0';
9147 if ((to = strchr(ptr, ';')))
9148 *to = '\0';
9149 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
9152 if (from) {
9153 ptr = from + 9;
9154 if ((to = strchr(ptr, '&')))
9155 *to = '\0';
9156 if ((to = strchr(ptr, ';')))
9157 *to = '\0';
9158 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
9161 if (option_debug > 1) {
9162 if (!pedanticsipchecking)
9163 ast_log(LOG_DEBUG,"Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
9164 else
9165 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>" );
9170 if ((ptr = strchr(refer_to, '@'))) { /* Separate domain */
9171 char *urioption = NULL, *domain;
9172 *ptr++ = '\0';
9174 if ((urioption = strchr(ptr, ';'))) /* Separate urioptions */
9175 *urioption++ = '\0';
9177 domain = ptr;
9178 if ((ptr = strchr(domain, ':'))) /* Remove :port */
9179 *ptr = '\0';
9181 /* Save the domain for the dial plan */
9182 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
9183 if (urioption)
9184 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
9187 if ((ptr = strchr(refer_to, ';'))) /* Remove options */
9188 *ptr = '\0';
9189 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
9191 if (referred_by_uri) {
9192 if ((ptr = strchr(referred_by_uri, ';'))) /* Remove options */
9193 *ptr = '\0';
9194 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
9195 } else {
9196 referdata->referred_by[0] = '\0';
9199 /* Determine transfer context */
9200 if (transferer->owner) /* Mimic behaviour in res_features.c */
9201 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
9203 /* By default, use the context in the channel sending the REFER */
9204 if (ast_strlen_zero(transfer_context)) {
9205 transfer_context = S_OR(transferer->owner->macrocontext,
9206 S_OR(transferer->context, default_context));
9209 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
9211 /* Either an existing extension or the parking extension */
9212 if (ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
9213 if (sip_debug_test_pvt(transferer)) {
9214 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
9216 /* We are ready to transfer to the extension */
9217 return 0;
9219 if (sip_debug_test_pvt(transferer))
9220 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
9222 /* Failure, we can't find this extension */
9223 return -1;
9227 /*! \brief Call transfer support (old way, deprecated by the IETF)--*/
9228 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
9230 char tmp[256] = "", *c, *a;
9231 struct sip_request *req = oreq ? oreq : &p->initreq;
9232 struct sip_refer *referdata = NULL;
9233 const char *transfer_context = NULL;
9235 if (!p->refer && !sip_refer_allocate(p))
9236 return -1;
9238 referdata = p->refer;
9240 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
9241 c = get_in_brackets(tmp);
9243 if (pedanticsipchecking)
9244 ast_uri_decode(c);
9246 if (strncasecmp(c, "sip:", 4)) {
9247 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
9248 return -1;
9250 c += 4;
9251 if ((a = strchr(c, ';'))) /* Remove arguments */
9252 *a = '\0';
9254 if ((a = strchr(c, '@'))) { /* Separate Domain */
9255 *a++ = '\0';
9256 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
9259 if (sip_debug_test_pvt(p))
9260 ast_verbose("Looking for %s in %s\n", c, p->context);
9262 if (p->owner) /* Mimic behaviour in res_features.c */
9263 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
9265 /* By default, use the context in the channel sending the REFER */
9266 if (ast_strlen_zero(transfer_context)) {
9267 transfer_context = S_OR(p->owner->macrocontext,
9268 S_OR(p->context, default_context));
9270 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
9271 /* This is a blind transfer */
9272 if (option_debug)
9273 ast_log(LOG_DEBUG,"SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
9274 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
9275 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
9276 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
9277 referdata->refer_call = NULL;
9278 /* Set new context */
9279 ast_string_field_set(p, context, transfer_context);
9280 return 0;
9281 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
9282 return 1;
9285 return -1;
9287 /*! \brief check Via: header for hostname, port and rport request/answer */
9288 static void check_via(struct sip_pvt *p, const struct sip_request *req)
9290 char via[512];
9291 char *c, *pt;
9292 struct hostent *hp;
9293 struct ast_hostent ahp;
9295 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
9297 /* Work on the leftmost value of the topmost Via header */
9298 c = strchr(via, ',');
9299 if (c)
9300 *c = '\0';
9302 /* Check for rport */
9303 c = strstr(via, ";rport");
9304 if (c && (c[6] != '=')) /* rport query, not answer */
9305 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
9307 c = strchr(via, ';');
9308 if (c)
9309 *c = '\0';
9311 c = strchr(via, ' ');
9312 if (c) {
9313 *c = '\0';
9314 c = ast_skip_blanks(c+1);
9315 if (strcasecmp(via, "SIP/2.0/UDP")) {
9316 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
9317 return;
9319 pt = strchr(c, ':');
9320 if (pt)
9321 *pt++ = '\0'; /* remember port pointer */
9322 hp = ast_gethostbyname(c, &ahp);
9323 if (!hp) {
9324 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
9325 return;
9327 memset(&p->sa, 0, sizeof(p->sa));
9328 p->sa.sin_family = AF_INET;
9329 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
9330 p->sa.sin_port = htons(pt ? atoi(pt) : STANDARD_SIP_PORT);
9332 if (sip_debug_test_pvt(p)) {
9333 const struct sockaddr_in *dst = sip_real_dst(p);
9334 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
9339 /*! \brief Get caller id name from SIP headers */
9340 static char *get_calleridname(const char *input, char *output, size_t outputsize)
9342 const char *end = strchr(input,'<'); /* first_bracket */
9343 const char *tmp = strchr(input,'"'); /* first quote */
9344 int bytes = 0;
9345 int maxbytes = outputsize - 1;
9347 if (!end || end == input) /* we require a part in brackets */
9348 return NULL;
9350 end--; /* move just before "<" */
9352 if (tmp && tmp <= end) {
9353 /* The quote (tmp) precedes the bracket (end+1).
9354 * Find the matching quote and return the content.
9356 end = strchr(tmp+1, '"');
9357 if (!end)
9358 return NULL;
9359 bytes = (int) (end - tmp);
9360 /* protect the output buffer */
9361 if (bytes > maxbytes)
9362 bytes = maxbytes;
9363 ast_copy_string(output, tmp + 1, bytes);
9364 } else {
9365 /* No quoted string, or it is inside brackets. */
9366 /* clear the empty characters in the begining*/
9367 input = ast_skip_blanks(input);
9368 /* clear the empty characters in the end */
9369 while(*end && *end < 33 && end > input)
9370 end--;
9371 if (end >= input) {
9372 bytes = (int) (end - input) + 2;
9373 /* protect the output buffer */
9374 if (bytes > maxbytes)
9375 bytes = maxbytes;
9376 ast_copy_string(output, input, bytes);
9377 } else
9378 return NULL;
9380 return output;
9383 /*! \brief Get caller id number from Remote-Party-ID header field
9384 * Returns true if number should be restricted (privacy setting found)
9385 * output is set to NULL if no number found
9387 static int get_rpid_num(const char *input, char *output, int maxlen)
9389 char *start;
9390 char *end;
9392 start = strchr(input,':');
9393 if (!start) {
9394 output[0] = '\0';
9395 return 0;
9397 start++;
9399 /* we found "number" */
9400 ast_copy_string(output,start,maxlen);
9401 output[maxlen-1] = '\0';
9403 end = strchr(output,'@');
9404 if (end)
9405 *end = '\0';
9406 else
9407 output[0] = '\0';
9408 if (strstr(input,"privacy=full") || strstr(input,"privacy=uri"))
9409 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
9411 return 0;
9415 /*! \brief Check if matching user or peer is defined
9416 Match user on From: user name and peer on IP/port
9417 This is used on first invite (not re-invites) and subscribe requests
9418 \return 0 on success, non-zero on failure
9420 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
9421 int sipmethod, char *uri, enum xmittype reliable,
9422 struct sockaddr_in *sin, struct sip_peer **authpeer)
9424 struct sip_user *user = NULL;
9425 struct sip_peer *peer;
9426 char from[256], *c;
9427 char *of;
9428 char rpid_num[50];
9429 const char *rpid;
9430 enum check_auth_result res = AUTH_SUCCESSFUL;
9431 char *t;
9432 char calleridname[50];
9433 int debug=sip_debug_test_addr(sin);
9434 struct ast_variable *tmpvar = NULL, *v = NULL;
9435 char *uri2 = ast_strdupa(uri);
9437 /* Terminate URI */
9438 t = uri2;
9439 while (*t && *t > 32 && *t != ';')
9440 t++;
9441 *t = '\0';
9442 ast_copy_string(from, get_header(req, "From"), sizeof(from)); /* XXX bug in original code, overwrote string */
9443 if (pedanticsipchecking)
9444 ast_uri_decode(from);
9445 /* XXX here tries to map the username for invite things */
9446 memset(calleridname, 0, sizeof(calleridname));
9447 get_calleridname(from, calleridname, sizeof(calleridname));
9448 if (calleridname[0])
9449 ast_string_field_set(p, cid_name, calleridname);
9451 rpid = get_header(req, "Remote-Party-ID");
9452 memset(rpid_num, 0, sizeof(rpid_num));
9453 if (!ast_strlen_zero(rpid))
9454 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
9456 of = get_in_brackets(from);
9457 if (ast_strlen_zero(p->exten)) {
9458 t = uri2;
9459 if (!strncasecmp(t, "sip:", 4))
9460 t+= 4;
9461 ast_string_field_set(p, exten, t);
9462 t = strchr(p->exten, '@');
9463 if (t)
9464 *t = '\0';
9465 if (ast_strlen_zero(p->our_contact))
9466 build_contact(p);
9468 /* save the URI part of the From header */
9469 ast_string_field_set(p, from, of);
9470 if (strncasecmp(of, "sip:", 4)) {
9471 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
9472 } else
9473 of += 4;
9474 /* Get just the username part */
9475 if ((c = strchr(of, '@'))) {
9476 char *tmp;
9477 *c = '\0';
9478 if ((c = strchr(of, ':')))
9479 *c = '\0';
9480 tmp = ast_strdupa(of);
9481 /* We need to be able to handle auth-headers looking like
9482 <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
9484 tmp = strsep(&tmp, ";");
9485 if (ast_is_shrinkable_phonenumber(tmp))
9486 ast_shrink_phone_number(tmp);
9487 ast_string_field_set(p, cid_num, tmp);
9490 if (!authpeer) /* If we are looking for a peer, don't check the user objects (or realtime) */
9491 user = find_user(of, 1);
9493 /* Find user based on user name in the from header */
9494 if (user && ast_apply_ha(user->ha, sin)) {
9495 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
9496 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9497 /* copy channel vars */
9498 for (v = user->chanvars ; v ; v = v->next) {
9499 if ((tmpvar = ast_variable_new(v->name, v->value))) {
9500 tmpvar->next = p->chanvars;
9501 p->chanvars = tmpvar;
9504 p->prefs = user->prefs;
9505 /* Set Frame packetization */
9506 if (p->rtp) {
9507 ast_rtp_codec_setpref(p->rtp, &p->prefs);
9508 p->autoframing = user->autoframing;
9510 /* replace callerid if rpid found, and not restricted */
9511 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
9512 char *tmp;
9513 if (*calleridname)
9514 ast_string_field_set(p, cid_name, calleridname);
9515 tmp = ast_strdupa(rpid_num);
9516 if (ast_is_shrinkable_phonenumber(tmp))
9517 ast_shrink_phone_number(tmp);
9518 ast_string_field_set(p, cid_num, tmp);
9521 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE) );
9523 if (!(res = check_auth(p, req, user->name, user->secret, user->md5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
9524 if (sip_cancel_destroy(p))
9525 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
9526 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
9527 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9528 /* Copy SIP extensions profile from INVITE */
9529 if (p->sipoptions)
9530 user->sipoptions = p->sipoptions;
9532 /* If we have a call limit, set flag */
9533 if (user->call_limit)
9534 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
9535 if (!ast_strlen_zero(user->context))
9536 ast_string_field_set(p, context, user->context);
9537 if (!ast_strlen_zero(user->cid_num)) {
9538 char *tmp = ast_strdupa(user->cid_num);
9539 if (ast_is_shrinkable_phonenumber(tmp))
9540 ast_shrink_phone_number(tmp);
9541 ast_string_field_set(p, cid_num, tmp);
9543 if (!ast_strlen_zero(user->cid_name))
9544 ast_string_field_set(p, cid_name, user->cid_name);
9545 ast_string_field_set(p, username, user->name);
9546 ast_string_field_set(p, peername, user->name);
9547 ast_string_field_set(p, peersecret, user->secret);
9548 ast_string_field_set(p, peermd5secret, user->md5secret);
9549 ast_string_field_set(p, subscribecontext, user->subscribecontext);
9550 ast_string_field_set(p, accountcode, user->accountcode);
9551 ast_string_field_set(p, language, user->language);
9552 ast_string_field_set(p, mohsuggest, user->mohsuggest);
9553 ast_string_field_set(p, mohinterpret, user->mohinterpret);
9554 p->allowtransfer = user->allowtransfer;
9555 p->amaflags = user->amaflags;
9556 p->callgroup = user->callgroup;
9557 p->pickupgroup = user->pickupgroup;
9558 if (user->callingpres) /* User callingpres setting will override RPID header */
9559 p->callingpres = user->callingpres;
9561 /* Set default codec settings for this call */
9562 p->capability = user->capability; /* User codec choice */
9563 p->jointcapability = user->capability; /* Our codecs */
9564 if (p->peercapability) /* AND with peer's codecs */
9565 p->jointcapability &= p->peercapability;
9566 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
9567 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
9568 p->noncodeccapability |= AST_RTP_DTMF;
9569 else
9570 p->noncodeccapability &= ~AST_RTP_DTMF;
9571 p->jointnoncodeccapability = p->noncodeccapability;
9572 if (p->t38.peercapability)
9573 p->t38.jointcapability &= p->t38.peercapability;
9574 p->maxcallbitrate = user->maxcallbitrate;
9575 /* If we do not support video, remove video from call structure */
9576 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
9577 ast_rtp_destroy(p->vrtp);
9578 p->vrtp = NULL;
9581 if (user && debug)
9582 ast_verbose("Found user '%s'\n", user->name);
9583 } else {
9584 if (user) {
9585 if (!authpeer && debug)
9586 ast_verbose("Found user '%s', but fails host access\n", user->name);
9587 ASTOBJ_UNREF(user,sip_destroy_user);
9589 user = NULL;
9592 if (!user) {
9593 /* If we didn't find a user match, check for peers */
9594 if (sipmethod == SIP_SUBSCRIBE)
9595 /* For subscribes, match on peer name only */
9596 peer = find_peer(of, NULL, 1);
9597 else
9598 /* Look for peer based on the IP address we received data from */
9599 /* If peer is registered from this IP address or have this as a default
9600 IP address, this call is from the peer
9602 peer = find_peer(NULL, &p->recv, 1);
9604 if (peer) {
9605 /* Set Frame packetization */
9606 if (p->rtp) {
9607 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
9608 p->autoframing = peer->autoframing;
9610 if (debug)
9611 ast_verbose("Found peer '%s'\n", peer->name);
9613 /* Take the peer */
9614 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
9615 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9617 /* Copy SIP extensions profile to peer */
9618 if (p->sipoptions)
9619 peer->sipoptions = p->sipoptions;
9621 /* replace callerid if rpid found, and not restricted */
9622 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
9623 char *tmp = ast_strdupa(rpid_num);
9624 if (*calleridname)
9625 ast_string_field_set(p, cid_name, calleridname);
9626 if (ast_is_shrinkable_phonenumber(tmp))
9627 ast_shrink_phone_number(tmp);
9628 ast_string_field_set(p, cid_num, tmp);
9630 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
9632 ast_string_field_set(p, peersecret, peer->secret);
9633 ast_string_field_set(p, peermd5secret, peer->md5secret);
9634 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
9635 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
9636 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
9637 if (peer->callingpres) /* Peer calling pres setting will override RPID */
9638 p->callingpres = peer->callingpres;
9639 if (peer->maxms && peer->lastms)
9640 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
9641 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
9642 /* Pretend there is no required authentication */
9643 ast_string_field_free(p, peersecret);
9644 ast_string_field_free(p, peermd5secret);
9646 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
9647 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
9648 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9649 /* If we have a call limit, set flag */
9650 if (peer->call_limit)
9651 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
9652 ast_string_field_set(p, peername, peer->name);
9653 ast_string_field_set(p, authname, peer->name);
9655 /* copy channel vars */
9656 for (v = peer->chanvars ; v ; v = v->next) {
9657 if ((tmpvar = ast_variable_new(v->name, v->value))) {
9658 tmpvar->next = p->chanvars;
9659 p->chanvars = tmpvar;
9662 if (authpeer) {
9663 (*authpeer) = ASTOBJ_REF(peer); /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
9666 if (!ast_strlen_zero(peer->username)) {
9667 ast_string_field_set(p, username, peer->username);
9668 /* Use the default username for authentication on outbound calls */
9669 /* XXX this takes the name from the caller... can we override ? */
9670 ast_string_field_set(p, authname, peer->username);
9672 if (!ast_strlen_zero(peer->cid_num)) {
9673 char *tmp = ast_strdupa(peer->cid_num);
9674 if (ast_is_shrinkable_phonenumber(tmp))
9675 ast_shrink_phone_number(tmp);
9676 ast_string_field_set(p, cid_num, tmp);
9678 if (!ast_strlen_zero(peer->cid_name))
9679 ast_string_field_set(p, cid_name, peer->cid_name);
9680 ast_string_field_set(p, fullcontact, peer->fullcontact);
9681 if (!ast_strlen_zero(peer->context))
9682 ast_string_field_set(p, context, peer->context);
9683 ast_string_field_set(p, peersecret, peer->secret);
9684 ast_string_field_set(p, peermd5secret, peer->md5secret);
9685 ast_string_field_set(p, language, peer->language);
9686 ast_string_field_set(p, accountcode, peer->accountcode);
9687 p->amaflags = peer->amaflags;
9688 p->callgroup = peer->callgroup;
9689 p->pickupgroup = peer->pickupgroup;
9690 p->capability = peer->capability;
9691 p->prefs = peer->prefs;
9692 p->jointcapability = peer->capability;
9693 if (p->peercapability)
9694 p->jointcapability &= p->peercapability;
9695 p->maxcallbitrate = peer->maxcallbitrate;
9696 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
9697 ast_rtp_destroy(p->vrtp);
9698 p->vrtp = NULL;
9700 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
9701 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
9702 p->noncodeccapability |= AST_RTP_DTMF;
9703 else
9704 p->noncodeccapability &= ~AST_RTP_DTMF;
9705 p->jointnoncodeccapability = p->noncodeccapability;
9706 if (p->t38.peercapability)
9707 p->t38.jointcapability &= p->t38.peercapability;
9709 ASTOBJ_UNREF(peer, sip_destroy_peer);
9710 } else {
9711 if (debug)
9712 ast_verbose("Found no matching peer or user for '%s:%d'\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
9714 /* do we allow guests? */
9715 if (!global_allowguest) {
9716 if (global_alwaysauthreject)
9717 res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
9718 else
9719 res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
9720 } else if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
9721 char *tmp = ast_strdupa(rpid_num);
9722 if (*calleridname)
9723 ast_string_field_set(p, cid_name, calleridname);
9724 if (ast_is_shrinkable_phonenumber(tmp))
9725 ast_shrink_phone_number(tmp);
9726 ast_string_field_set(p, cid_num, tmp);
9732 if (user)
9733 ASTOBJ_UNREF(user, sip_destroy_user);
9734 return res;
9737 /*! \brief Find user
9738 If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
9740 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
9742 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
9745 /*! \brief Get text out of a SIP MESSAGE packet */
9746 static int get_msg_text(char *buf, int len, struct sip_request *req)
9748 int x;
9749 int y;
9751 buf[0] = '\0';
9752 y = len - strlen(buf) - 5;
9753 if (y < 0)
9754 y = 0;
9755 for (x=0;x<req->lines;x++) {
9756 strncat(buf, req->line[x], y); /* safe */
9757 y -= strlen(req->line[x]) + 1;
9758 if (y < 0)
9759 y = 0;
9760 if (y != 0)
9761 strcat(buf, "\n"); /* safe */
9763 return 0;
9767 /*! \brief Receive SIP MESSAGE method messages
9768 \note We only handle messages within current calls currently
9769 Reference: RFC 3428 */
9770 static void receive_message(struct sip_pvt *p, struct sip_request *req)
9772 char buf[1024];
9773 struct ast_frame f;
9774 const char *content_type = get_header(req, "Content-Type");
9776 if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
9777 transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
9778 if (!p->owner)
9779 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
9780 return;
9783 if (get_msg_text(buf, sizeof(buf), req)) {
9784 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
9785 transmit_response(p, "202 Accepted", req);
9786 if (!p->owner)
9787 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
9788 return;
9791 if (p->owner) {
9792 if (sip_debug_test_pvt(p))
9793 ast_verbose("Message received: '%s'\n", buf);
9794 memset(&f, 0, sizeof(f));
9795 f.frametype = AST_FRAME_TEXT;
9796 f.subclass = 0;
9797 f.offset = 0;
9798 f.data = buf;
9799 f.datalen = strlen(buf);
9800 ast_queue_frame(p->owner, &f);
9801 transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
9802 } else { /* Message outside of a call, we do not support that */
9803 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);
9804 transmit_response(p, "405 Method Not Allowed", req); /* Good enough, or? */
9805 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
9807 return;
9810 /*! \brief CLI Command to show calls within limits set by call_limit */
9811 static int sip_show_inuse(int fd, int argc, char *argv[])
9813 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
9814 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
9815 char ilimits[40];
9816 char iused[40];
9817 int showall = FALSE;
9819 if (argc < 3)
9820 return RESULT_SHOWUSAGE;
9822 if (argc == 4 && !strcmp(argv[3],"all"))
9823 showall = TRUE;
9825 ast_cli(fd, FORMAT, "* User name", "In use", "Limit");
9826 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
9827 ASTOBJ_RDLOCK(iterator);
9828 if (iterator->call_limit)
9829 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
9830 else
9831 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
9832 snprintf(iused, sizeof(iused), "%d", iterator->inUse);
9833 if (showall || iterator->call_limit)
9834 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
9835 ASTOBJ_UNLOCK(iterator);
9836 } while (0) );
9838 ast_cli(fd, FORMAT, "* Peer name", "In use", "Limit");
9840 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
9841 ASTOBJ_RDLOCK(iterator);
9842 if (iterator->call_limit)
9843 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
9844 else
9845 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
9846 snprintf(iused, sizeof(iused), "%d/%d", iterator->inUse, iterator->inRinging);
9847 if (showall || iterator->call_limit)
9848 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
9849 ASTOBJ_UNLOCK(iterator);
9850 } while (0) );
9852 return RESULT_SUCCESS;
9853 #undef FORMAT
9854 #undef FORMAT2
9857 /*! \brief Convert transfer mode to text string */
9858 static char *transfermode2str(enum transfermodes mode)
9860 if (mode == TRANSFER_OPENFORALL)
9861 return "open";
9862 else if (mode == TRANSFER_CLOSED)
9863 return "closed";
9864 return "strict";
9867 /*! \brief Convert NAT setting to text string */
9868 static char *nat2str(int nat)
9870 switch(nat) {
9871 case SIP_NAT_NEVER:
9872 return "No";
9873 case SIP_NAT_ROUTE:
9874 return "Route";
9875 case SIP_NAT_ALWAYS:
9876 return "Always";
9877 case SIP_NAT_RFC3581:
9878 return "RFC3581";
9879 default:
9880 return "Unknown";
9884 /*! \brief Report Peer status in character string
9885 * \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
9887 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
9889 int res = 0;
9890 if (peer->maxms) {
9891 if (peer->lastms < 0) {
9892 ast_copy_string(status, "UNREACHABLE", statuslen);
9893 } else if (peer->lastms > peer->maxms) {
9894 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
9895 res = 1;
9896 } else if (peer->lastms) {
9897 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
9898 res = 1;
9899 } else {
9900 ast_copy_string(status, "UNKNOWN", statuslen);
9902 } else {
9903 ast_copy_string(status, "Unmonitored", statuslen);
9904 /* Checking if port is 0 */
9905 res = -1;
9907 return res;
9910 /*! \brief CLI Command 'SIP Show Users' */
9911 static int sip_show_users(int fd, int argc, char *argv[])
9913 regex_t regexbuf;
9914 int havepattern = FALSE;
9916 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
9918 switch (argc) {
9919 case 5:
9920 if (!strcasecmp(argv[3], "like")) {
9921 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
9922 return RESULT_SHOWUSAGE;
9923 havepattern = TRUE;
9924 } else
9925 return RESULT_SHOWUSAGE;
9926 case 3:
9927 break;
9928 default:
9929 return RESULT_SHOWUSAGE;
9932 ast_cli(fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
9933 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
9934 ASTOBJ_RDLOCK(iterator);
9936 if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
9937 ASTOBJ_UNLOCK(iterator);
9938 continue;
9941 ast_cli(fd, FORMAT, iterator->name,
9942 iterator->secret,
9943 iterator->accountcode,
9944 iterator->context,
9945 iterator->ha ? "Yes" : "No",
9946 nat2str(ast_test_flag(&iterator->flags[0], SIP_NAT)));
9947 ASTOBJ_UNLOCK(iterator);
9948 } while (0)
9951 if (havepattern)
9952 regfree(&regexbuf);
9954 return RESULT_SUCCESS;
9955 #undef FORMAT
9958 static char mandescr_show_peers[] =
9959 "Description: Lists SIP peers in text format with details on current status.\n"
9960 "Variables: \n"
9961 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
9963 /*! \brief Show SIP peers in the manager API */
9964 /* Inspired from chan_iax2 */
9965 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
9967 const char *id = astman_get_header(m,"ActionID");
9968 const char *a[] = {"sip", "show", "peers"};
9969 char idtext[256] = "";
9970 int total = 0;
9972 if (!ast_strlen_zero(id))
9973 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
9975 astman_send_ack(s, m, "Peer status list will follow");
9976 /* List the peers in separate manager events */
9977 _sip_show_peers(-1, &total, s, m, 3, a);
9978 /* Send final confirmation */
9979 astman_append(s,
9980 "Event: PeerlistComplete\r\n"
9981 "ListItems: %d\r\n"
9982 "%s"
9983 "\r\n", total, idtext);
9984 return 0;
9987 /*! \brief CLI Show Peers command */
9988 static int sip_show_peers(int fd, int argc, char *argv[])
9990 return _sip_show_peers(fd, NULL, NULL, NULL, argc, (const char **) argv);
9993 /*! \brief _sip_show_peers: Execute sip show peers command */
9994 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
9996 regex_t regexbuf;
9997 int havepattern = FALSE;
9999 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %-10s\n"
10000 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %-10s\n"
10002 char name[256];
10003 int total_peers = 0;
10004 int peers_mon_online = 0;
10005 int peers_mon_offline = 0;
10006 int peers_unmon_offline = 0;
10007 int peers_unmon_online = 0;
10008 const char *id;
10009 char idtext[256] = "";
10010 int realtimepeers;
10012 realtimepeers = ast_check_realtime("sippeers");
10014 if (s) { /* Manager - get ActionID */
10015 id = astman_get_header(m,"ActionID");
10016 if (!ast_strlen_zero(id))
10017 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
10020 switch (argc) {
10021 case 5:
10022 if (!strcasecmp(argv[3], "like")) {
10023 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
10024 return RESULT_SHOWUSAGE;
10025 havepattern = TRUE;
10026 } else
10027 return RESULT_SHOWUSAGE;
10028 case 3:
10029 break;
10030 default:
10031 return RESULT_SHOWUSAGE;
10034 if (!s) /* Normal list */
10035 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
10037 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
10038 char status[20] = "";
10039 char srch[2000];
10040 char pstatus;
10042 ASTOBJ_RDLOCK(iterator);
10044 if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
10045 ASTOBJ_UNLOCK(iterator);
10046 continue;
10049 if (!ast_strlen_zero(iterator->username) && !s)
10050 snprintf(name, sizeof(name), "%s/%s", iterator->name, iterator->username);
10051 else
10052 ast_copy_string(name, iterator->name, sizeof(name));
10054 pstatus = peer_status(iterator, status, sizeof(status));
10055 if (pstatus == 1)
10056 peers_mon_online++;
10057 else if (pstatus == 0)
10058 peers_mon_offline++;
10059 else {
10060 if (iterator->addr.sin_port == 0)
10061 peers_unmon_offline++;
10062 else
10063 peers_unmon_online++;
10066 snprintf(srch, sizeof(srch), FORMAT, name,
10067 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
10068 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ", /* Dynamic or not? */
10069 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
10070 iterator->ha ? " A " : " ", /* permit/deny */
10071 ntohs(iterator->addr.sin_port), status,
10072 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
10074 if (!s) {/* Normal CLI list */
10075 ast_cli(fd, FORMAT, name,
10076 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
10077 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ", /* Dynamic or not? */
10078 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
10079 iterator->ha ? " A " : " ", /* permit/deny */
10081 ntohs(iterator->addr.sin_port), status,
10082 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
10083 } else { /* Manager format */
10084 /* The names here need to be the same as other channels */
10085 astman_append(s,
10086 "Event: PeerEntry\r\n%s"
10087 "Channeltype: SIP\r\n"
10088 "ObjectName: %s\r\n"
10089 "ChanObjectType: peer\r\n" /* "peer" or "user" */
10090 "IPaddress: %s\r\n"
10091 "IPport: %d\r\n"
10092 "Dynamic: %s\r\n"
10093 "Natsupport: %s\r\n"
10094 "VideoSupport: %s\r\n"
10095 "ACL: %s\r\n"
10096 "Status: %s\r\n"
10097 "RealtimeDevice: %s\r\n\r\n",
10098 idtext,
10099 iterator->name,
10100 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "-none-",
10101 ntohs(iterator->addr.sin_port),
10102 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no", /* Dynamic or not? */
10103 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? "yes" : "no", /* NAT=yes? */
10104 ast_test_flag(&iterator->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no", /* VIDEOSUPPORT=yes? */
10105 iterator->ha ? "yes" : "no", /* permit/deny */
10106 status,
10107 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "yes":"no") : "no");
10110 ASTOBJ_UNLOCK(iterator);
10112 total_peers++;
10113 } while(0) );
10115 if (!s)
10116 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
10117 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
10119 if (havepattern)
10120 regfree(&regexbuf);
10122 if (total)
10123 *total = total_peers;
10126 return RESULT_SUCCESS;
10127 #undef FORMAT
10128 #undef FORMAT2
10131 /*! \brief List all allocated SIP Objects (realtime or static) */
10132 static int sip_show_objects(int fd, int argc, char *argv[])
10134 char tmp[256];
10135 if (argc != 3)
10136 return RESULT_SHOWUSAGE;
10137 ast_cli(fd, "-= User objects: %d static, %d realtime =-\n\n", suserobjs, ruserobjs);
10138 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &userl);
10139 ast_cli(fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
10140 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &peerl);
10141 ast_cli(fd, "-= Registry objects: %d =-\n\n", regobjs);
10142 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &regl);
10143 return RESULT_SUCCESS;
10145 /*! \brief Print call group and pickup group */
10146 static void print_group(int fd, ast_group_t group, int crlf)
10148 char buf[256];
10149 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
10152 /*! \brief Convert DTMF mode to printable string */
10153 static const char *dtmfmode2str(int mode)
10155 switch (mode) {
10156 case SIP_DTMF_RFC2833:
10157 return "rfc2833";
10158 case SIP_DTMF_INFO:
10159 return "info";
10160 case SIP_DTMF_INBAND:
10161 return "inband";
10162 case SIP_DTMF_AUTO:
10163 return "auto";
10165 return "<error>";
10168 /*! \brief Convert Insecure setting to printable string */
10169 static const char *insecure2str(int port, int invite)
10171 if (port && invite)
10172 return "port,invite";
10173 else if (port)
10174 return "port";
10175 else if (invite)
10176 return "invite";
10177 else
10178 return "no";
10181 /*! \brief Destroy disused contexts between reloads
10182 Only used in reload_config so the code for regcontext doesn't get ugly
10184 static void cleanup_stale_contexts(char *new, char *old)
10186 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
10188 while ((oldcontext = strsep(&old, "&"))) {
10189 stalecontext = '\0';
10190 ast_copy_string(newlist, new, sizeof(newlist));
10191 stringp = newlist;
10192 while ((newcontext = strsep(&stringp, "&"))) {
10193 if (strcmp(newcontext, oldcontext) == 0) {
10194 /* This is not the context you're looking for */
10195 stalecontext = '\0';
10196 break;
10197 } else if (strcmp(newcontext, oldcontext)) {
10198 stalecontext = oldcontext;
10202 if (stalecontext)
10203 ast_context_destroy(ast_context_find(stalecontext), "SIP");
10207 /*! \brief Remove temporary realtime objects from memory (CLI) */
10208 static int sip_prune_realtime(int fd, int argc, char *argv[])
10210 struct sip_peer *peer;
10211 struct sip_user *user;
10212 int pruneuser = FALSE;
10213 int prunepeer = FALSE;
10214 int multi = FALSE;
10215 char *name = NULL;
10216 regex_t regexbuf;
10218 switch (argc) {
10219 case 4:
10220 if (!strcasecmp(argv[3], "user"))
10221 return RESULT_SHOWUSAGE;
10222 if (!strcasecmp(argv[3], "peer"))
10223 return RESULT_SHOWUSAGE;
10224 if (!strcasecmp(argv[3], "like"))
10225 return RESULT_SHOWUSAGE;
10226 if (!strcasecmp(argv[3], "all")) {
10227 multi = TRUE;
10228 pruneuser = prunepeer = TRUE;
10229 } else {
10230 pruneuser = prunepeer = TRUE;
10231 name = argv[3];
10233 break;
10234 case 5:
10235 if (!strcasecmp(argv[4], "like"))
10236 return RESULT_SHOWUSAGE;
10237 if (!strcasecmp(argv[3], "all"))
10238 return RESULT_SHOWUSAGE;
10239 if (!strcasecmp(argv[3], "like")) {
10240 multi = TRUE;
10241 name = argv[4];
10242 pruneuser = prunepeer = TRUE;
10243 } else if (!strcasecmp(argv[3], "user")) {
10244 pruneuser = TRUE;
10245 if (!strcasecmp(argv[4], "all"))
10246 multi = TRUE;
10247 else
10248 name = argv[4];
10249 } else if (!strcasecmp(argv[3], "peer")) {
10250 prunepeer = TRUE;
10251 if (!strcasecmp(argv[4], "all"))
10252 multi = TRUE;
10253 else
10254 name = argv[4];
10255 } else
10256 return RESULT_SHOWUSAGE;
10257 break;
10258 case 6:
10259 if (strcasecmp(argv[4], "like"))
10260 return RESULT_SHOWUSAGE;
10261 if (!strcasecmp(argv[3], "user")) {
10262 pruneuser = TRUE;
10263 name = argv[5];
10264 } else if (!strcasecmp(argv[3], "peer")) {
10265 prunepeer = TRUE;
10266 name = argv[5];
10267 } else
10268 return RESULT_SHOWUSAGE;
10269 break;
10270 default:
10271 return RESULT_SHOWUSAGE;
10274 if (multi && name) {
10275 if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
10276 return RESULT_SHOWUSAGE;
10279 if (multi) {
10280 if (prunepeer) {
10281 int pruned = 0;
10283 ASTOBJ_CONTAINER_WRLOCK(&peerl);
10284 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
10285 ASTOBJ_RDLOCK(iterator);
10286 if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
10287 ASTOBJ_UNLOCK(iterator);
10288 continue;
10290 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10291 ASTOBJ_MARK(iterator);
10292 pruned++;
10294 ASTOBJ_UNLOCK(iterator);
10295 } while (0) );
10296 if (pruned) {
10297 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
10298 ast_cli(fd, "%d peers pruned.\n", pruned);
10299 } else
10300 ast_cli(fd, "No peers found to prune.\n");
10301 ASTOBJ_CONTAINER_UNLOCK(&peerl);
10303 if (pruneuser) {
10304 int pruned = 0;
10306 ASTOBJ_CONTAINER_WRLOCK(&userl);
10307 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
10308 ASTOBJ_RDLOCK(iterator);
10309 if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
10310 ASTOBJ_UNLOCK(iterator);
10311 continue;
10313 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10314 ASTOBJ_MARK(iterator);
10315 pruned++;
10317 ASTOBJ_UNLOCK(iterator);
10318 } while (0) );
10319 if (pruned) {
10320 ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, sip_destroy_user);
10321 ast_cli(fd, "%d users pruned.\n", pruned);
10322 } else
10323 ast_cli(fd, "No users found to prune.\n");
10324 ASTOBJ_CONTAINER_UNLOCK(&userl);
10326 } else {
10327 if (prunepeer) {
10328 if ((peer = ASTOBJ_CONTAINER_FIND_UNLINK(&peerl, name))) {
10329 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10330 ast_cli(fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
10331 ASTOBJ_CONTAINER_LINK(&peerl, peer);
10332 } else
10333 ast_cli(fd, "Peer '%s' pruned.\n", name);
10334 ASTOBJ_UNREF(peer, sip_destroy_peer);
10335 } else
10336 ast_cli(fd, "Peer '%s' not found.\n", name);
10338 if (pruneuser) {
10339 if ((user = ASTOBJ_CONTAINER_FIND_UNLINK(&userl, name))) {
10340 if (!ast_test_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10341 ast_cli(fd, "User '%s' is not a Realtime user, cannot be pruned.\n", name);
10342 ASTOBJ_CONTAINER_LINK(&userl, user);
10343 } else
10344 ast_cli(fd, "User '%s' pruned.\n", name);
10345 ASTOBJ_UNREF(user, sip_destroy_user);
10346 } else
10347 ast_cli(fd, "User '%s' not found.\n", name);
10351 return RESULT_SUCCESS;
10354 /*! \brief Print codec list from preference to CLI/manager */
10355 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
10357 int x, codec;
10359 for(x = 0; x < 32 ; x++) {
10360 codec = ast_codec_pref_index(pref, x);
10361 if (!codec)
10362 break;
10363 ast_cli(fd, "%s", ast_getformatname(codec));
10364 ast_cli(fd, ":%d", pref->framing[x]);
10365 if (x < 31 && ast_codec_pref_index(pref, x + 1))
10366 ast_cli(fd, ",");
10368 if (!x)
10369 ast_cli(fd, "none");
10372 /*! \brief Print domain mode to cli */
10373 static const char *domain_mode_to_text(const enum domain_mode mode)
10375 switch (mode) {
10376 case SIP_DOMAIN_AUTO:
10377 return "[Automatic]";
10378 case SIP_DOMAIN_CONFIG:
10379 return "[Configured]";
10382 return "";
10385 /*! \brief CLI command to list local domains */
10386 static int sip_show_domains(int fd, int argc, char *argv[])
10388 struct domain *d;
10389 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
10391 if (AST_LIST_EMPTY(&domain_list)) {
10392 ast_cli(fd, "SIP Domain support not enabled.\n\n");
10393 return RESULT_SUCCESS;
10394 } else {
10395 ast_cli(fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
10396 AST_LIST_LOCK(&domain_list);
10397 AST_LIST_TRAVERSE(&domain_list, d, list)
10398 ast_cli(fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
10399 domain_mode_to_text(d->mode));
10400 AST_LIST_UNLOCK(&domain_list);
10401 ast_cli(fd, "\n");
10402 return RESULT_SUCCESS;
10405 #undef FORMAT
10407 static char mandescr_show_peer[] =
10408 "Description: Show one SIP peer with details on current status.\n"
10409 "Variables: \n"
10410 " Peer: <name> The peer name you want to check.\n"
10411 " ActionID: <id> Optional action ID for this AMI transaction.\n";
10413 /*! \brief Show SIP peers in the manager API */
10414 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
10416 const char *a[4];
10417 const char *peer;
10418 int ret;
10420 peer = astman_get_header(m,"Peer");
10421 if (ast_strlen_zero(peer)) {
10422 astman_send_error(s, m, "Peer: <name> missing.\n");
10423 return 0;
10425 a[0] = "sip";
10426 a[1] = "show";
10427 a[2] = "peer";
10428 a[3] = peer;
10430 ret = _sip_show_peer(1, -1, s, m, 4, a);
10431 astman_append(s, "\r\n\r\n" );
10432 return ret;
10437 /*! \brief Show one peer in detail */
10438 static int sip_show_peer(int fd, int argc, char *argv[])
10440 return _sip_show_peer(0, fd, NULL, NULL, argc, (const char **) argv);
10443 /*! \brief Show one peer in detail (main function) */
10444 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
10446 char status[30] = "";
10447 char cbuf[256];
10448 struct sip_peer *peer;
10449 char codec_buf[512];
10450 struct ast_codec_pref *pref;
10451 struct ast_variable *v;
10452 struct sip_auth *auth;
10453 int x = 0, codec = 0, load_realtime;
10454 int realtimepeers;
10456 realtimepeers = ast_check_realtime("sippeers");
10458 if (argc < 4)
10459 return RESULT_SHOWUSAGE;
10461 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
10462 peer = find_peer(argv[3], NULL, load_realtime);
10463 if (s) { /* Manager */
10464 if (peer) {
10465 const char *id = astman_get_header(m,"ActionID");
10467 astman_append(s, "Response: Success\r\n");
10468 if (!ast_strlen_zero(id))
10469 astman_append(s, "ActionID: %s\r\n",id);
10470 } else {
10471 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.\n", argv[3]);
10472 astman_send_error(s, m, cbuf);
10473 return 0;
10476 if (peer && type==0 ) { /* Normal listing */
10477 ast_cli(fd,"\n\n");
10478 ast_cli(fd, " * Name : %s\n", peer->name);
10479 if (realtimepeers) { /* Realtime is enabled */
10480 ast_cli(fd, " Realtime peer: %s\n", ast_test_flag(&peer->flags[0], SIP_REALTIME) ? "Yes, cached" : "No");
10482 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
10483 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
10484 for (auth = peer->auth; auth; auth = auth->next) {
10485 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
10486 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
10488 ast_cli(fd, " Context : %s\n", peer->context);
10489 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
10490 ast_cli(fd, " Language : %s\n", peer->language);
10491 if (!ast_strlen_zero(peer->accountcode))
10492 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
10493 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
10494 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
10495 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
10496 if (!ast_strlen_zero(peer->fromuser))
10497 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
10498 if (!ast_strlen_zero(peer->fromdomain))
10499 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
10500 ast_cli(fd, " Callgroup : ");
10501 print_group(fd, peer->callgroup, 0);
10502 ast_cli(fd, " Pickupgroup : ");
10503 print_group(fd, peer->pickupgroup, 0);
10504 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
10505 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
10506 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
10507 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
10508 ast_cli(fd, " Dynamic : %s\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Yes":"No"));
10509 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
10510 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
10511 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
10512 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)));
10513 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
10514 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
10515 ast_cli(fd, " T38 pt UDPTL : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL)?"Yes":"No");
10516 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10517 ast_cli(fd, " T38 pt RTP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_RTP)?"Yes":"No");
10518 ast_cli(fd, " T38 pt TCP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_TCP)?"Yes":"No");
10519 #endif
10520 ast_cli(fd, " CanReinvite : %s\n", ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Yes":"No");
10521 ast_cli(fd, " PromiscRedir : %s\n", ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Yes":"No");
10522 ast_cli(fd, " User=Phone : %s\n", ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Yes":"No");
10523 ast_cli(fd, " Video Support: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Yes":"No");
10524 ast_cli(fd, " Trust RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_TRUSTRPID) ? "Yes" : "No");
10525 ast_cli(fd, " Send RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_SENDRPID) ? "Yes" : "No");
10526 ast_cli(fd, " Subscriptions: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
10527 ast_cli(fd, " Overlap dial : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
10529 /* - is enumerated */
10530 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
10531 ast_cli(fd, " LastMsg : %d\n", peer->lastmsg);
10532 ast_cli(fd, " ToHost : %s\n", peer->tohost);
10533 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));
10534 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
10535 if (!ast_strlen_zero(global_regcontext))
10536 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
10537 ast_cli(fd, " Def. Username: %s\n", peer->username);
10538 ast_cli(fd, " SIP Options : ");
10539 if (peer->sipoptions) {
10540 int lastoption = -1;
10541 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
10542 if (sip_options[x].id != lastoption) {
10543 if (peer->sipoptions & sip_options[x].id)
10544 ast_cli(fd, "%s ", sip_options[x].text);
10545 lastoption = x;
10548 } else
10549 ast_cli(fd, "(none)");
10551 ast_cli(fd, "\n");
10552 ast_cli(fd, " Codecs : ");
10553 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
10554 ast_cli(fd, "%s\n", codec_buf);
10555 ast_cli(fd, " Codec Order : (");
10556 print_codec_to_cli(fd, &peer->prefs);
10557 ast_cli(fd, ")\n");
10559 ast_cli(fd, " Auto-Framing: %s \n", peer->autoframing ? "Yes" : "No");
10560 ast_cli(fd, " Status : ");
10561 peer_status(peer, status, sizeof(status));
10562 ast_cli(fd, "%s\n",status);
10563 ast_cli(fd, " Useragent : %s\n", peer->useragent);
10564 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
10565 if (peer->chanvars) {
10566 ast_cli(fd, " Variables :\n");
10567 for (v = peer->chanvars ; v ; v = v->next)
10568 ast_cli(fd, " %s = %s\n", v->name, v->value);
10570 ast_cli(fd,"\n");
10571 ASTOBJ_UNREF(peer,sip_destroy_peer);
10572 } else if (peer && type == 1) { /* manager listing */
10573 char buf[256];
10574 astman_append(s, "Channeltype: SIP\r\n");
10575 astman_append(s, "ObjectName: %s\r\n", peer->name);
10576 astman_append(s, "ChanObjectType: peer\r\n");
10577 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
10578 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
10579 astman_append(s, "Context: %s\r\n", peer->context);
10580 astman_append(s, "Language: %s\r\n", peer->language);
10581 if (!ast_strlen_zero(peer->accountcode))
10582 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
10583 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
10584 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
10585 if (!ast_strlen_zero(peer->fromuser))
10586 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
10587 if (!ast_strlen_zero(peer->fromdomain))
10588 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
10589 astman_append(s, "Callgroup: ");
10590 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->callgroup));
10591 astman_append(s, "Pickupgroup: ");
10592 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->pickupgroup));
10593 astman_append(s, "VoiceMailbox: %s\r\n", peer->mailbox);
10594 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
10595 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
10596 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
10597 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
10598 astman_append(s, "Dynamic: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Y":"N"));
10599 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
10600 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched,peer->expire));
10601 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)));
10602 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
10603 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
10604 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
10605 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
10606 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
10607 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
10609 /* - is enumerated */
10610 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
10611 astman_append(s, "SIPLastMsg: %d\r\n", peer->lastmsg);
10612 astman_append(s, "ToHost: %s\r\n", peer->tohost);
10613 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));
10614 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));
10615 astman_append(s, "Default-Username: %s\r\n", peer->username);
10616 if (!ast_strlen_zero(global_regcontext))
10617 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
10618 astman_append(s, "Codecs: ");
10619 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
10620 astman_append(s, "%s\r\n", codec_buf);
10621 astman_append(s, "CodecOrder: ");
10622 pref = &peer->prefs;
10623 for(x = 0; x < 32 ; x++) {
10624 codec = ast_codec_pref_index(pref,x);
10625 if (!codec)
10626 break;
10627 astman_append(s, "%s", ast_getformatname(codec));
10628 if (x < 31 && ast_codec_pref_index(pref,x+1))
10629 astman_append(s, ",");
10632 astman_append(s, "\r\n");
10633 astman_append(s, "Status: ");
10634 peer_status(peer, status, sizeof(status));
10635 astman_append(s, "%s\r\n", status);
10636 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
10637 astman_append(s, "Reg-Contact : %s\r\n", peer->fullcontact);
10638 if (peer->chanvars) {
10639 for (v = peer->chanvars ; v ; v = v->next) {
10640 astman_append(s, "ChanVariable:\n");
10641 astman_append(s, " %s,%s\r\n", v->name, v->value);
10645 ASTOBJ_UNREF(peer,sip_destroy_peer);
10647 } else {
10648 ast_cli(fd,"Peer %s not found.\n", argv[3]);
10649 ast_cli(fd,"\n");
10652 return RESULT_SUCCESS;
10655 /*! \brief Show one user in detail */
10656 static int sip_show_user(int fd, int argc, char *argv[])
10658 char cbuf[256];
10659 struct sip_user *user;
10660 struct ast_variable *v;
10661 int load_realtime;
10663 if (argc < 4)
10664 return RESULT_SHOWUSAGE;
10666 /* Load from realtime storage? */
10667 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
10669 user = find_user(argv[3], load_realtime);
10670 if (user) {
10671 ast_cli(fd,"\n\n");
10672 ast_cli(fd, " * Name : %s\n", user->name);
10673 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
10674 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
10675 ast_cli(fd, " Context : %s\n", user->context);
10676 ast_cli(fd, " Language : %s\n", user->language);
10677 if (!ast_strlen_zero(user->accountcode))
10678 ast_cli(fd, " Accountcode : %s\n", user->accountcode);
10679 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
10680 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
10681 ast_cli(fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
10682 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
10683 ast_cli(fd, " Call limit : %d\n", user->call_limit);
10684 ast_cli(fd, " Callgroup : ");
10685 print_group(fd, user->callgroup, 0);
10686 ast_cli(fd, " Pickupgroup : ");
10687 print_group(fd, user->pickupgroup, 0);
10688 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
10689 ast_cli(fd, " ACL : %s\n", (user->ha?"Yes":"No"));
10690 ast_cli(fd, " Codec Order : (");
10691 print_codec_to_cli(fd, &user->prefs);
10692 ast_cli(fd, ")\n");
10694 ast_cli(fd, " Auto-Framing: %s \n", user->autoframing ? "Yes" : "No");
10695 if (user->chanvars) {
10696 ast_cli(fd, " Variables :\n");
10697 for (v = user->chanvars ; v ; v = v->next)
10698 ast_cli(fd, " %s = %s\n", v->name, v->value);
10700 ast_cli(fd,"\n");
10701 ASTOBJ_UNREF(user,sip_destroy_user);
10702 } else {
10703 ast_cli(fd,"User %s not found.\n", argv[3]);
10704 ast_cli(fd,"\n");
10707 return RESULT_SUCCESS;
10710 /*! \brief Show SIP Registry (registrations with other SIP proxies */
10711 static int sip_show_registry(int fd, int argc, char *argv[])
10713 #define FORMAT2 "%-30.30s %-12.12s %8.8s %-20.20s %-25.25s\n"
10714 #define FORMAT "%-30.30s %-12.12s %8d %-20.20s %-25.25s\n"
10715 char host[80];
10716 char tmpdat[256];
10717 struct tm tm;
10720 if (argc != 3)
10721 return RESULT_SHOWUSAGE;
10722 ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State", "Reg.Time");
10723 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
10724 ASTOBJ_RDLOCK(iterator);
10725 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
10726 if (iterator->regtime) {
10727 ast_localtime(&iterator->regtime, &tm, NULL);
10728 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
10729 } else {
10730 tmpdat[0] = 0;
10732 ast_cli(fd, FORMAT, host, iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
10733 ASTOBJ_UNLOCK(iterator);
10734 } while(0));
10735 return RESULT_SUCCESS;
10736 #undef FORMAT
10737 #undef FORMAT2
10740 /*! \brief List global settings for the SIP channel */
10741 static int sip_show_settings(int fd, int argc, char *argv[])
10743 int realtimepeers;
10744 int realtimeusers;
10745 char codec_buf[SIPBUFSIZE];
10747 realtimepeers = ast_check_realtime("sippeers");
10748 realtimeusers = ast_check_realtime("sipusers");
10750 if (argc != 3)
10751 return RESULT_SHOWUSAGE;
10752 ast_cli(fd, "\n\nGlobal Settings:\n");
10753 ast_cli(fd, "----------------\n");
10754 ast_cli(fd, " SIP Port: %d\n", ntohs(bindaddr.sin_port));
10755 ast_cli(fd, " Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
10756 ast_cli(fd, " Videosupport: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "Yes" : "No");
10757 ast_cli(fd, " AutoCreatePeer: %s\n", autocreatepeer ? "Yes" : "No");
10758 ast_cli(fd, " Allow unknown access: %s\n", global_allowguest ? "Yes" : "No");
10759 ast_cli(fd, " Allow subscriptions: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
10760 ast_cli(fd, " Allow overlap dialing: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
10761 ast_cli(fd, " Promsic. redir: %s\n", ast_test_flag(&global_flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
10762 ast_cli(fd, " SIP domain support: %s\n", AST_LIST_EMPTY(&domain_list) ? "No" : "Yes");
10763 ast_cli(fd, " Call to non-local dom.: %s\n", allow_external_domains ? "Yes" : "No");
10764 ast_cli(fd, " URI user is phone no: %s\n", ast_test_flag(&global_flags[0], SIP_USEREQPHONE) ? "Yes" : "No");
10765 ast_cli(fd, " Our auth realm %s\n", global_realm);
10766 ast_cli(fd, " Realm. auth: %s\n", authl ? "Yes": "No");
10767 ast_cli(fd, " Always auth rejects: %s\n", global_alwaysauthreject ? "Yes" : "No");
10768 ast_cli(fd, " Call limit peers only: %s\n", global_limitonpeers ? "Yes" : "No");
10769 ast_cli(fd, " Direct RTP setup: %s\n", global_directrtpsetup ? "Yes" : "No");
10770 ast_cli(fd, " User Agent: %s\n", global_useragent);
10771 ast_cli(fd, " MWI checking interval: %d secs\n", global_mwitime);
10772 ast_cli(fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
10773 ast_cli(fd, " Caller ID: %s\n", default_callerid);
10774 ast_cli(fd, " From: Domain: %s\n", default_fromdomain);
10775 ast_cli(fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
10776 ast_cli(fd, " Call Events: %s\n", global_callevents ? "On" : "Off");
10777 ast_cli(fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
10778 ast_cli(fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
10779 ast_cli(fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
10780 ast_cli(fd, " T38 fax pt UDPTL: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_UDPTL) ? "Yes" : "No");
10781 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10782 ast_cli(fd, " T38 fax pt RTP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_RTP) ? "Yes" : "No");
10783 ast_cli(fd, " T38 fax pt TCP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_TCP) ? "Yes" : "No");
10784 #endif
10785 ast_cli(fd, " RFC2833 Compensation: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE) ? "Yes" : "No");
10786 if (!realtimepeers && !realtimeusers)
10787 ast_cli(fd, " SIP realtime: Disabled\n" );
10788 else
10789 ast_cli(fd, " SIP realtime: Enabled\n" );
10791 ast_cli(fd, "\nGlobal Signalling Settings:\n");
10792 ast_cli(fd, "---------------------------\n");
10793 ast_cli(fd, " Codecs: ");
10794 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
10795 ast_cli(fd, "%s\n", codec_buf);
10796 ast_cli(fd, " Codec Order: ");
10797 print_codec_to_cli(fd, &default_prefs);
10798 ast_cli(fd, "\n");
10799 ast_cli(fd, " T1 minimum: %d\n", global_t1min);
10800 ast_cli(fd, " Relax DTMF: %s\n", global_relaxdtmf ? "Yes" : "No");
10801 ast_cli(fd, " Compact SIP headers: %s\n", compactheaders ? "Yes" : "No");
10802 ast_cli(fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
10803 ast_cli(fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
10804 ast_cli(fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
10805 ast_cli(fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
10806 ast_cli(fd, " DNS SRV lookup: %s\n", srvlookup ? "Yes" : "No");
10807 ast_cli(fd, " Pedantic SIP support: %s\n", pedanticsipchecking ? "Yes" : "No");
10808 ast_cli(fd, " Reg. min duration %d secs\n", min_expiry);
10809 ast_cli(fd, " Reg. max duration: %d secs\n", max_expiry);
10810 ast_cli(fd, " Reg. default duration: %d secs\n", default_expiry);
10811 ast_cli(fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
10812 ast_cli(fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
10813 ast_cli(fd, " Notify ringing state: %s\n", global_notifyringing ? "Yes" : "No");
10814 ast_cli(fd, " Notify hold state: %s\n", global_notifyhold ? "Yes" : "No");
10815 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(global_allowtransfer));
10816 ast_cli(fd, " Max Call Bitrate: %d kbps\r\n", default_maxcallbitrate);
10817 ast_cli(fd, " Auto-Framing: %s \r\n", global_autoframing ? "Yes" : "No");
10818 ast_cli(fd, "\nDefault Settings:\n");
10819 ast_cli(fd, "-----------------\n");
10820 ast_cli(fd, " Context: %s\n", default_context);
10821 ast_cli(fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
10822 ast_cli(fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
10823 ast_cli(fd, " Qualify: %d\n", default_qualify);
10824 ast_cli(fd, " Use ClientCode: %s\n", ast_test_flag(&global_flags[0], SIP_USECLIENTCODE) ? "Yes" : "No");
10825 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" );
10826 ast_cli(fd, " Language: %s\n", S_OR(default_language, "(Defaults to English)"));
10827 ast_cli(fd, " MOH Interpret: %s\n", default_mohinterpret);
10828 ast_cli(fd, " MOH Suggest: %s\n", default_mohsuggest);
10829 ast_cli(fd, " Voice Mail Extension: %s\n", default_vmexten);
10832 if (realtimepeers || realtimeusers) {
10833 ast_cli(fd, "\nRealtime SIP Settings:\n");
10834 ast_cli(fd, "----------------------\n");
10835 ast_cli(fd, " Realtime Peers: %s\n", realtimepeers ? "Yes" : "No");
10836 ast_cli(fd, " Realtime Users: %s\n", realtimeusers ? "Yes" : "No");
10837 ast_cli(fd, " Cache Friends: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? "Yes" : "No");
10838 ast_cli(fd, " Update: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) ? "Yes" : "No");
10839 ast_cli(fd, " Ignore Reg. Expire: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) ? "Yes" : "No");
10840 ast_cli(fd, " Save sys. name: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME) ? "Yes" : "No");
10841 ast_cli(fd, " Auto Clear: %d\n", global_rtautoclear);
10843 ast_cli(fd, "\n----\n");
10844 return RESULT_SUCCESS;
10847 /*! \brief Show subscription type in string format */
10848 static const char *subscription_type2str(enum subscriptiontype subtype)
10850 int i;
10852 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10853 if (subscription_types[i].type == subtype) {
10854 return subscription_types[i].text;
10857 return subscription_types[0].text;
10860 /*! \brief Find subscription type in array */
10861 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
10863 int i;
10865 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10866 if (subscription_types[i].type == subtype) {
10867 return &subscription_types[i];
10870 return &subscription_types[0];
10873 /*! \brief Show active SIP channels */
10874 static int sip_show_channels(int fd, int argc, char *argv[])
10876 return __sip_show_channels(fd, argc, argv, 0);
10879 /*! \brief Show active SIP subscriptions */
10880 static int sip_show_subscriptions(int fd, int argc, char *argv[])
10882 return __sip_show_channels(fd, argc, argv, 1);
10885 /*! \brief SIP show channels CLI (main function) */
10886 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions)
10888 #define FORMAT3 "%-15.15s %-10.10s %-11.11s %-15.15s %-13.13s %-15.15s %-10.10s\n"
10889 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-15.15s %-7.7s %-15.15s\n"
10890 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s\n"
10891 struct sip_pvt *cur;
10892 int numchans = 0;
10893 char *referstatus = NULL;
10895 if (argc != 3)
10896 return RESULT_SHOWUSAGE;
10897 ast_mutex_lock(&iflock);
10898 cur = iflist;
10899 if (!subscriptions)
10900 ast_cli(fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Seq (Tx/Rx)", "Format", "Hold", "Last Message");
10901 else
10902 ast_cli(fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox");
10903 for (; cur; cur = cur->next) {
10904 referstatus = "";
10905 if (cur->refer) { /* SIP transfer in progress */
10906 referstatus = referstatus2str(cur->refer->status);
10908 if (cur->subscribed == NONE && !subscriptions) {
10909 char formatbuf[SIPBUFSIZE/2];
10910 ast_cli(fd, FORMAT, ast_inet_ntoa(cur->sa.sin_addr),
10911 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10912 cur->callid,
10913 cur->ocseq, cur->icseq,
10914 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
10915 ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD) ? "Yes" : "No",
10916 ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY) ? "(d)" : "",
10917 cur->lastmsg ,
10918 referstatus
10920 numchans++;
10922 if (cur->subscribed != NONE && subscriptions) {
10923 ast_cli(fd, FORMAT3, ast_inet_ntoa(cur->sa.sin_addr),
10924 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10925 cur->callid,
10926 /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
10927 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
10928 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
10929 subscription_type2str(cur->subscribed),
10930 cur->subscribed == MWI_NOTIFICATION ? (cur->relatedpeer ? cur->relatedpeer->mailbox : "<none>") : "<none>"
10932 numchans++;
10935 ast_mutex_unlock(&iflock);
10936 if (!subscriptions)
10937 ast_cli(fd, "%d active SIP channel%s\n", numchans, (numchans != 1) ? "s" : "");
10938 else
10939 ast_cli(fd, "%d active SIP subscription%s\n", numchans, (numchans != 1) ? "s" : "");
10940 return RESULT_SUCCESS;
10941 #undef FORMAT
10942 #undef FORMAT2
10943 #undef FORMAT3
10946 /*! \brief Support routine for 'sip show channel' CLI */
10947 static char *complete_sipch(const char *line, const char *word, int pos, int state)
10949 int which=0;
10950 struct sip_pvt *cur;
10951 char *c = NULL;
10952 int wordlen = strlen(word);
10954 if (pos != 3) {
10955 return NULL;
10958 ast_mutex_lock(&iflock);
10959 for (cur = iflist; cur; cur = cur->next) {
10960 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
10961 c = ast_strdup(cur->callid);
10962 break;
10965 ast_mutex_unlock(&iflock);
10966 return c;
10969 /*! \brief Do completion on peer name */
10970 static char *complete_sip_peer(const char *word, int state, int flags2)
10972 char *result = NULL;
10973 int wordlen = strlen(word);
10974 int which = 0;
10976 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !result, do {
10977 /* locking of the object is not required because only the name and flags are being compared */
10978 if (!strncasecmp(word, iterator->name, wordlen) &&
10979 (!flags2 || ast_test_flag(&iterator->flags[1], flags2)) &&
10980 ++which > state)
10981 result = ast_strdup(iterator->name);
10982 } while(0) );
10983 return result;
10986 /*! \brief Support routine for 'sip show peer' CLI */
10987 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
10989 if (pos == 3)
10990 return complete_sip_peer(word, state, 0);
10992 return NULL;
10995 /*! \brief Support routine for 'sip debug peer' CLI */
10996 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state)
10998 if (pos == 3)
10999 return complete_sip_peer(word, state, 0);
11001 return NULL;
11004 /*! \brief Do completion on user name */
11005 static char *complete_sip_user(const char *word, int state, int flags2)
11007 char *result = NULL;
11008 int wordlen = strlen(word);
11009 int which = 0;
11011 ASTOBJ_CONTAINER_TRAVERSE(&userl, !result, do {
11012 /* locking of the object is not required because only the name and flags are being compared */
11013 if (!strncasecmp(word, iterator->name, wordlen)) {
11014 if (flags2 && !ast_test_flag(&iterator->flags[1], flags2))
11015 continue;
11016 if (++which > state) {
11017 result = ast_strdup(iterator->name);
11020 } while(0) );
11021 return result;
11024 /*! \brief Support routine for 'sip show user' CLI */
11025 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
11027 if (pos == 3)
11028 return complete_sip_user(word, state, 0);
11030 return NULL;
11033 /*! \brief Support routine for 'sip notify' CLI */
11034 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
11036 char *c = NULL;
11038 if (pos == 2) {
11039 int which = 0;
11040 char *cat = NULL;
11041 int wordlen = strlen(word);
11043 /* do completion for notify type */
11045 if (!notify_types)
11046 return NULL;
11048 while ( (cat = ast_category_browse(notify_types, cat)) ) {
11049 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
11050 c = ast_strdup(cat);
11051 break;
11054 return c;
11057 if (pos > 2)
11058 return complete_sip_peer(word, state, 0);
11060 return NULL;
11063 /*! \brief Support routine for 'sip prune realtime peer' CLI */
11064 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state)
11066 if (pos == 4)
11067 return complete_sip_peer(word, state, SIP_PAGE2_RTCACHEFRIENDS);
11068 return NULL;
11071 /*! \brief Support routine for 'sip prune realtime user' CLI */
11072 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state)
11074 if (pos == 4)
11075 return complete_sip_user(word, state, SIP_PAGE2_RTCACHEFRIENDS);
11077 return NULL;
11080 /*! \brief Show details of one active dialog */
11081 static int sip_show_channel(int fd, int argc, char *argv[])
11083 struct sip_pvt *cur;
11084 size_t len;
11085 int found = 0;
11087 if (argc != 4)
11088 return RESULT_SHOWUSAGE;
11089 len = strlen(argv[3]);
11090 ast_mutex_lock(&iflock);
11091 for (cur = iflist; cur; cur = cur->next) {
11092 if (!strncasecmp(cur->callid, argv[3], len)) {
11093 char formatbuf[SIPBUFSIZE/2];
11094 ast_cli(fd,"\n");
11095 if (cur->subscribed != NONE)
11096 ast_cli(fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
11097 else
11098 ast_cli(fd, " * SIP Call\n");
11099 ast_cli(fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
11100 ast_cli(fd, " Call-ID: %s\n", cur->callid);
11101 ast_cli(fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
11102 ast_cli(fd, " Our Codec Capability: %d\n", cur->capability);
11103 ast_cli(fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
11104 ast_cli(fd, " Their Codec Capability: %d\n", cur->peercapability);
11105 ast_cli(fd, " Joint Codec Capability: %d\n", cur->jointcapability);
11106 ast_cli(fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
11107 ast_cli(fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
11108 ast_cli(fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
11109 ast_cli(fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
11110 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
11111 ast_cli(fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
11112 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)" );
11113 ast_cli(fd, " Our Tag: %s\n", cur->tag);
11114 ast_cli(fd, " Their Tag: %s\n", cur->theirtag);
11115 ast_cli(fd, " SIP User agent: %s\n", cur->useragent);
11116 if (!ast_strlen_zero(cur->username))
11117 ast_cli(fd, " Username: %s\n", cur->username);
11118 if (!ast_strlen_zero(cur->peername))
11119 ast_cli(fd, " Peername: %s\n", cur->peername);
11120 if (!ast_strlen_zero(cur->uri))
11121 ast_cli(fd, " Original uri: %s\n", cur->uri);
11122 if (!ast_strlen_zero(cur->cid_num))
11123 ast_cli(fd, " Caller-ID: %s\n", cur->cid_num);
11124 ast_cli(fd, " Need Destroy: %d\n", ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY));
11125 ast_cli(fd, " Last Message: %s\n", cur->lastmsg);
11126 ast_cli(fd, " Promiscuous Redir: %s\n", ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
11127 ast_cli(fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
11128 ast_cli(fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
11129 ast_cli(fd, " SIP Options: ");
11130 if (cur->sipoptions) {
11131 int x;
11132 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
11133 if (cur->sipoptions & sip_options[x].id)
11134 ast_cli(fd, "%s ", sip_options[x].text);
11136 } else
11137 ast_cli(fd, "(none)\n");
11138 ast_cli(fd, "\n\n");
11139 found++;
11142 ast_mutex_unlock(&iflock);
11143 if (!found)
11144 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
11145 return RESULT_SUCCESS;
11148 /*! \brief Show history details of one dialog */
11149 static int sip_show_history(int fd, int argc, char *argv[])
11151 struct sip_pvt *cur;
11152 size_t len;
11153 int found = 0;
11155 if (argc != 4)
11156 return RESULT_SHOWUSAGE;
11157 if (!recordhistory)
11158 ast_cli(fd, "\n***Note: History recording is currently DISABLED. Use 'sip history' to ENABLE.\n");
11159 len = strlen(argv[3]);
11160 ast_mutex_lock(&iflock);
11161 for (cur = iflist; cur; cur = cur->next) {
11162 if (!strncasecmp(cur->callid, argv[3], len)) {
11163 struct sip_history *hist;
11164 int x = 0;
11166 ast_cli(fd,"\n");
11167 if (cur->subscribed != NONE)
11168 ast_cli(fd, " * Subscription\n");
11169 else
11170 ast_cli(fd, " * SIP Call\n");
11171 if (cur->history)
11172 AST_LIST_TRAVERSE(cur->history, hist, list)
11173 ast_cli(fd, "%d. %s\n", ++x, hist->event);
11174 if (x == 0)
11175 ast_cli(fd, "Call '%s' has no history\n", cur->callid);
11176 found++;
11179 ast_mutex_unlock(&iflock);
11180 if (!found)
11181 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
11182 return RESULT_SUCCESS;
11185 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
11186 static void sip_dump_history(struct sip_pvt *dialog)
11188 int x = 0;
11189 struct sip_history *hist;
11190 static int errmsg = 0;
11192 if (!dialog)
11193 return;
11195 if (!option_debug && !sipdebug) {
11196 if (!errmsg) {
11197 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
11198 errmsg = 1;
11200 return;
11203 ast_log(LOG_DEBUG, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
11204 if (dialog->subscribed)
11205 ast_log(LOG_DEBUG, " * Subscription\n");
11206 else
11207 ast_log(LOG_DEBUG, " * SIP Call\n");
11208 if (dialog->history)
11209 AST_LIST_TRAVERSE(dialog->history, hist, list)
11210 ast_log(LOG_DEBUG, " %-3.3d. %s\n", ++x, hist->event);
11211 if (!x)
11212 ast_log(LOG_DEBUG, "Call '%s' has no history\n", dialog->callid);
11213 ast_log(LOG_DEBUG, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
11217 /*! \brief Receive SIP INFO Message
11218 \note Doesn't read the duration of the DTMF signal */
11219 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
11221 char buf[1024];
11222 unsigned int event;
11223 const char *c = get_header(req, "Content-Type");
11225 /* Need to check the media/type */
11226 if (!strcasecmp(c, "application/dtmf-relay") ||
11227 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
11228 unsigned int duration = 0;
11230 /* Try getting the "signal=" part */
11231 if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
11232 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
11233 transmit_response(p, "200 OK", req); /* Should return error */
11234 return;
11235 } else {
11236 ast_copy_string(buf, c, sizeof(buf));
11239 if (!ast_strlen_zero((c = get_body(req, "Duration"))))
11240 duration = atoi(c);
11241 if (!duration)
11242 duration = 100; /* 100 ms */
11244 if (!p->owner) { /* not a PBX call */
11245 transmit_response(p, "481 Call leg/transaction does not exist", req);
11246 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11247 return;
11250 if (ast_strlen_zero(buf)) {
11251 transmit_response(p, "200 OK", req);
11252 return;
11255 if (buf[0] == '*')
11256 event = 10;
11257 else if (buf[0] == '#')
11258 event = 11;
11259 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
11260 event = 12 + buf[0] - 'A';
11261 else
11262 event = atoi(buf);
11263 if (event == 16) {
11264 /* send a FLASH event */
11265 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
11266 ast_queue_frame(p->owner, &f);
11267 if (sipdebug)
11268 ast_verbose("* DTMF-relay event received: FLASH\n");
11269 } else {
11270 /* send a DTMF event */
11271 struct ast_frame f = { AST_FRAME_DTMF, };
11272 if (event < 10) {
11273 f.subclass = '0' + event;
11274 } else if (event < 11) {
11275 f.subclass = '*';
11276 } else if (event < 12) {
11277 f.subclass = '#';
11278 } else if (event < 16) {
11279 f.subclass = 'A' + (event - 12);
11281 f.len = duration;
11282 ast_queue_frame(p->owner, &f);
11283 if (sipdebug)
11284 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
11286 transmit_response(p, "200 OK", req);
11287 return;
11288 } else if (!strcasecmp(c, "application/media_control+xml")) {
11289 /* Eh, we'll just assume it's a fast picture update for now */
11290 if (p->owner)
11291 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
11292 transmit_response(p, "200 OK", req);
11293 return;
11294 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
11295 /* Client code (from SNOM phone) */
11296 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
11297 if (p->owner && p->owner->cdr)
11298 ast_cdr_setuserfield(p->owner, c);
11299 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
11300 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
11301 transmit_response(p, "200 OK", req);
11302 } else {
11303 transmit_response(p, "403 Unauthorized", req);
11305 return;
11306 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
11307 /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
11308 transmit_response(p, "200 OK", req);
11309 return;
11312 /* Other type of INFO message, not really understood by Asterisk */
11313 /* if (get_msg_text(buf, sizeof(buf), req)) { */
11315 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
11316 transmit_response(p, "415 Unsupported media type", req);
11317 return;
11320 /*! \brief Enable SIP Debugging in CLI */
11321 static int sip_do_debug_ip(int fd, int argc, char *argv[])
11323 struct hostent *hp;
11324 struct ast_hostent ahp;
11325 int port = 0;
11326 char *p, *arg;
11328 /* sip set debug ip <ip> */
11329 if (argc != 5)
11330 return RESULT_SHOWUSAGE;
11331 p = arg = argv[4];
11332 strsep(&p, ":");
11333 if (p)
11334 port = atoi(p);
11335 hp = ast_gethostbyname(arg, &ahp);
11336 if (hp == NULL)
11337 return RESULT_SHOWUSAGE;
11339 debugaddr.sin_family = AF_INET;
11340 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
11341 debugaddr.sin_port = htons(port);
11342 if (port == 0)
11343 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
11344 else
11345 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
11347 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11349 return RESULT_SUCCESS;
11352 /*! \brief sip_do_debug_peer: Turn on SIP debugging with peer mask */
11353 static int sip_do_debug_peer(int fd, int argc, char *argv[])
11355 struct sip_peer *peer;
11356 if (argc != 5)
11357 return RESULT_SHOWUSAGE;
11358 peer = find_peer(argv[4], NULL, 1);
11359 if (peer) {
11360 if (peer->addr.sin_addr.s_addr) {
11361 debugaddr.sin_family = AF_INET;
11362 debugaddr.sin_addr = peer->addr.sin_addr;
11363 debugaddr.sin_port = peer->addr.sin_port;
11364 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
11365 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11366 } else
11367 ast_cli(fd, "Unable to get IP address of peer '%s'\n", argv[4]);
11368 ASTOBJ_UNREF(peer,sip_destroy_peer);
11369 } else
11370 ast_cli(fd, "No such peer '%s'\n", argv[4]);
11371 return RESULT_SUCCESS;
11374 /*! \brief Turn on SIP debugging (CLI command) */
11375 static int sip_do_debug(int fd, int argc, char *argv[])
11377 int oldsipdebug = sipdebug_console;
11378 if (argc != 3) {
11379 if (argc != 5)
11380 return RESULT_SHOWUSAGE;
11381 else if (strcmp(argv[3], "ip") == 0)
11382 return sip_do_debug_ip(fd, argc, argv);
11383 else if (strcmp(argv[3], "peer") == 0)
11384 return sip_do_debug_peer(fd, argc, argv);
11385 else
11386 return RESULT_SHOWUSAGE;
11388 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11389 memset(&debugaddr, 0, sizeof(debugaddr));
11390 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
11391 return RESULT_SUCCESS;
11394 static int sip_do_debug_deprecated(int fd, int argc, char *argv[])
11396 int oldsipdebug = sipdebug_console;
11397 char *newargv[6] = { "sip", "set", "debug", NULL };
11398 if (argc != 2) {
11399 if (argc != 4)
11400 return RESULT_SHOWUSAGE;
11401 else if (strcmp(argv[2], "ip") == 0) {
11402 newargv[3] = argv[2];
11403 newargv[4] = argv[3];
11404 return sip_do_debug_ip(fd, argc + 1, newargv);
11405 } else if (strcmp(argv[2], "peer") == 0) {
11406 newargv[3] = argv[2];
11407 newargv[4] = argv[3];
11408 return sip_do_debug_peer(fd, argc + 1, newargv);
11409 } else
11410 return RESULT_SHOWUSAGE;
11412 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11413 memset(&debugaddr, 0, sizeof(debugaddr));
11414 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
11415 return RESULT_SUCCESS;
11418 /*! \brief Cli command to send SIP notify to peer */
11419 static int sip_notify(int fd, int argc, char *argv[])
11421 struct ast_variable *varlist;
11422 int i;
11424 if (argc < 4)
11425 return RESULT_SHOWUSAGE;
11427 if (!notify_types) {
11428 ast_cli(fd, "No %s file found, or no types listed there\n", notify_config);
11429 return RESULT_FAILURE;
11432 varlist = ast_variable_browse(notify_types, argv[2]);
11434 if (!varlist) {
11435 ast_cli(fd, "Unable to find notify type '%s'\n", argv[2]);
11436 return RESULT_FAILURE;
11439 for (i = 3; i < argc; i++) {
11440 struct sip_pvt *p;
11441 struct sip_request req;
11442 struct ast_variable *var;
11444 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY))) {
11445 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
11446 return RESULT_FAILURE;
11449 if (create_addr(p, argv[i])) {
11450 /* Maybe they're not registered, etc. */
11451 sip_destroy(p);
11452 ast_cli(fd, "Could not create address for '%s'\n", argv[i]);
11453 continue;
11456 initreqprep(&req, p, SIP_NOTIFY);
11458 for (var = varlist; var; var = var->next)
11459 add_header(&req, var->name, ast_unescape_semicolon(var->value));
11461 /* Recalculate our side, and recalculate Call ID */
11462 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
11463 p->ourip = __ourip;
11464 build_via(p);
11465 build_callid_pvt(p);
11466 ast_cli(fd, "Sending NOTIFY of type '%s' to '%s'\n", argv[2], argv[i]);
11467 transmit_sip_request(p, &req);
11468 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11471 return RESULT_SUCCESS;
11474 /*! \brief Disable SIP Debugging in CLI */
11475 static int sip_no_debug(int fd, int argc, char *argv[])
11477 if (argc != 4)
11478 return RESULT_SHOWUSAGE;
11479 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11480 ast_cli(fd, "SIP Debugging Disabled\n");
11481 return RESULT_SUCCESS;
11484 static int sip_no_debug_deprecated(int fd, int argc, char *argv[])
11486 if (argc != 3)
11487 return RESULT_SHOWUSAGE;
11488 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11489 ast_cli(fd, "SIP Debugging Disabled\n");
11490 return RESULT_SUCCESS;
11493 /*! \brief Enable SIP History logging (CLI) */
11494 static int sip_do_history(int fd, int argc, char *argv[])
11496 if (argc != 2) {
11497 return RESULT_SHOWUSAGE;
11499 recordhistory = TRUE;
11500 ast_cli(fd, "SIP History Recording Enabled (use 'sip show history')\n");
11501 return RESULT_SUCCESS;
11504 /*! \brief Disable SIP History logging (CLI) */
11505 static int sip_no_history(int fd, int argc, char *argv[])
11507 if (argc != 3) {
11508 return RESULT_SHOWUSAGE;
11510 recordhistory = FALSE;
11511 ast_cli(fd, "SIP History Recording Disabled\n");
11512 return RESULT_SUCCESS;
11515 /*! \brief Authenticate for outbound registration */
11516 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader)
11518 char digest[1024];
11519 p->authtries++;
11520 memset(digest,0,sizeof(digest));
11521 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
11522 /* There's nothing to use for authentication */
11523 /* No digest challenge in request */
11524 if (sip_debug_test_pvt(p) && p->registry)
11525 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
11526 /* No old challenge */
11527 return -1;
11529 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
11530 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
11531 if (sip_debug_test_pvt(p) && p->registry)
11532 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
11533 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
11536 /*! \brief Add authentication on outbound SIP packet */
11537 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init)
11539 char digest[1024];
11541 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
11542 return -2;
11544 p->authtries++;
11545 if (option_debug > 1)
11546 ast_log(LOG_DEBUG, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
11547 memset(digest, 0, sizeof(digest));
11548 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
11549 /* No way to authenticate */
11550 return -1;
11552 /* Now we have a reply digest */
11553 p->options->auth = digest;
11554 p->options->authheader = respheader;
11555 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
11558 /*! \brief reply to authentication for outbound registrations
11559 \return Returns -1 if we have no auth
11560 \note This is used for register= servers in sip.conf, SIP proxies we register
11561 with for receiving calls from. */
11562 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
11564 char tmp[512];
11565 char *c;
11566 char oldnonce[256];
11568 /* table of recognised keywords, and places where they should be copied */
11569 const struct x {
11570 const char *key;
11571 int field_index;
11572 } *i, keys[] = {
11573 { "realm=", ast_string_field_index(p, realm) },
11574 { "nonce=", ast_string_field_index(p, nonce) },
11575 { "opaque=", ast_string_field_index(p, opaque) },
11576 { "qop=", ast_string_field_index(p, qop) },
11577 { "domain=", ast_string_field_index(p, domain) },
11578 { NULL, 0 },
11581 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
11582 if (ast_strlen_zero(tmp))
11583 return -1;
11584 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
11585 ast_log(LOG_WARNING, "missing Digest.\n");
11586 return -1;
11588 c = tmp + strlen("Digest ");
11589 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
11590 while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
11591 for (i = keys; i->key != NULL; i++) {
11592 char *src, *separator;
11593 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
11594 continue;
11595 /* Found. Skip keyword, take text in quotes or up to the separator. */
11596 c += strlen(i->key);
11597 if (*c == '"') {
11598 src = ++c;
11599 separator = "\"";
11600 } else {
11601 src = c;
11602 separator = ",";
11604 strsep(&c, separator); /* clear separator and move ptr */
11605 ast_string_field_index_set(p, i->field_index, src);
11606 break;
11608 if (i->key == NULL) /* not found, try ',' */
11609 strsep(&c, ",");
11611 /* Reset nonce count */
11612 if (strcmp(p->nonce, oldnonce))
11613 p->noncecount = 0;
11615 /* Save auth data for following registrations */
11616 if (p->registry) {
11617 struct sip_registry *r = p->registry;
11619 if (strcmp(r->nonce, p->nonce)) {
11620 ast_string_field_set(r, realm, p->realm);
11621 ast_string_field_set(r, nonce, p->nonce);
11622 ast_string_field_set(r, domain, p->domain);
11623 ast_string_field_set(r, opaque, p->opaque);
11624 ast_string_field_set(r, qop, p->qop);
11625 r->noncecount = 0;
11628 return build_reply_digest(p, sipmethod, digest, digest_len);
11631 /*! \brief Build reply digest
11632 \return Returns -1 if we have no auth
11633 \note Build digest challenge for authentication of peers (for registration)
11634 and users (for calls). Also used for authentication of CANCEL and BYE
11636 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
11638 char a1[256];
11639 char a2[256];
11640 char a1_hash[256];
11641 char a2_hash[256];
11642 char resp[256];
11643 char resp_hash[256];
11644 char uri[256];
11645 char opaque[256] = "";
11646 char cnonce[80];
11647 const char *username;
11648 const char *secret;
11649 const char *md5secret;
11650 struct sip_auth *auth = NULL; /* Realm authentication */
11652 if (!ast_strlen_zero(p->domain))
11653 ast_copy_string(uri, p->domain, sizeof(uri));
11654 else if (!ast_strlen_zero(p->uri))
11655 ast_copy_string(uri, p->uri, sizeof(uri));
11656 else
11657 snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, ast_inet_ntoa(p->sa.sin_addr));
11659 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
11661 /* Check if we have separate auth credentials */
11662 if(!(auth = find_realm_authentication(p->peerauth, p->realm))) /* Start with peer list */
11663 auth = find_realm_authentication(authl, p->realm); /* If not, global list */
11665 if (auth) {
11666 ast_log(LOG_DEBUG, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
11667 username = auth->username;
11668 secret = auth->secret;
11669 md5secret = auth->md5secret;
11670 if (sipdebug)
11671 ast_log(LOG_DEBUG,"Using realm %s authentication for call %s\n", p->realm, p->callid);
11672 } else {
11673 /* No authentication, use peer or register= config */
11674 username = p->authname;
11675 secret = p->peersecret;
11676 md5secret = p->peermd5secret;
11678 if (ast_strlen_zero(username)) /* We have no authentication */
11679 return -1;
11681 /* Calculate SIP digest response */
11682 snprintf(a1,sizeof(a1),"%s:%s:%s", username, p->realm, secret);
11683 snprintf(a2,sizeof(a2),"%s:%s", sip_methods[method].text, uri);
11684 if (!ast_strlen_zero(md5secret))
11685 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
11686 else
11687 ast_md5_hash(a1_hash,a1);
11688 ast_md5_hash(a2_hash,a2);
11690 p->noncecount++;
11691 if (!ast_strlen_zero(p->qop))
11692 snprintf(resp,sizeof(resp),"%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
11693 else
11694 snprintf(resp,sizeof(resp),"%s:%s:%s", a1_hash, p->nonce, a2_hash);
11695 ast_md5_hash(resp_hash, resp);
11697 /* only include the opaque string if it's set */
11698 if (!ast_strlen_zero(p->opaque)) {
11699 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
11702 /* XXX We hard code our qop to "auth" for now. XXX */
11703 if (!ast_strlen_zero(p->qop))
11704 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);
11705 else
11706 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);
11708 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
11710 return 0;
11713 static char show_domains_usage[] =
11714 "Usage: sip show domains\n"
11715 " Lists all configured SIP local domains.\n"
11716 " Asterisk only responds to SIP messages to local domains.\n";
11718 static char notify_usage[] =
11719 "Usage: sip notify <type> <peer> [<peer>...]\n"
11720 " Send a NOTIFY message to a SIP peer or peers\n"
11721 " Message types are defined in sip_notify.conf\n";
11723 static char show_users_usage[] =
11724 "Usage: sip show users [like <pattern>]\n"
11725 " Lists all known SIP users.\n"
11726 " Optional regular expression pattern is used to filter the user list.\n";
11728 static char show_user_usage[] =
11729 "Usage: sip show user <name> [load]\n"
11730 " Shows all details on one SIP user and the current status.\n"
11731 " Option \"load\" forces lookup of peer in realtime storage.\n";
11733 static char show_inuse_usage[] =
11734 "Usage: sip show inuse [all]\n"
11735 " List all SIP users and peers usage counters and limits.\n"
11736 " Add option \"all\" to show all devices, not only those with a limit.\n";
11738 static char show_channels_usage[] =
11739 "Usage: sip show channels\n"
11740 " Lists all currently active SIP channels.\n";
11742 static char show_channel_usage[] =
11743 "Usage: sip show channel <channel>\n"
11744 " Provides detailed status on a given SIP channel.\n";
11746 static char show_history_usage[] =
11747 "Usage: sip show history <channel>\n"
11748 " Provides detailed dialog history on a given SIP channel.\n";
11750 static char show_peers_usage[] =
11751 "Usage: sip show peers [like <pattern>]\n"
11752 " Lists all known SIP peers.\n"
11753 " Optional regular expression pattern is used to filter the peer list.\n";
11755 static char show_peer_usage[] =
11756 "Usage: sip show peer <name> [load]\n"
11757 " Shows all details on one SIP peer and the current status.\n"
11758 " Option \"load\" forces lookup of peer in realtime storage.\n";
11760 static char prune_realtime_usage[] =
11761 "Usage: sip prune realtime [peer|user] [<name>|all|like <pattern>]\n"
11762 " Prunes object(s) from the cache.\n"
11763 " Optional regular expression pattern is used to filter the objects.\n";
11765 static char show_reg_usage[] =
11766 "Usage: sip show registry\n"
11767 " Lists all registration requests and status.\n";
11769 static char debug_usage[] =
11770 "Usage: sip set debug\n"
11771 " Enables dumping of SIP packets for debugging purposes\n\n"
11772 " sip set debug ip <host[:PORT]>\n"
11773 " Enables dumping of SIP packets to and from host.\n\n"
11774 " sip set debug peer <peername>\n"
11775 " Enables dumping of SIP packets to and from host.\n"
11776 " Require peer to be registered.\n";
11778 static char no_debug_usage[] =
11779 "Usage: sip set debug off\n"
11780 " Disables dumping of SIP packets for debugging purposes\n";
11782 static char no_history_usage[] =
11783 "Usage: sip history off\n"
11784 " Disables recording of SIP dialog history for debugging purposes\n";
11786 static char history_usage[] =
11787 "Usage: sip history\n"
11788 " Enables recording of SIP dialog history for debugging purposes.\n"
11789 "Use 'sip show history' to view the history of a call number.\n";
11791 static char sip_reload_usage[] =
11792 "Usage: sip reload\n"
11793 " Reloads SIP configuration from sip.conf\n";
11795 static char show_subscriptions_usage[] =
11796 "Usage: sip show subscriptions\n"
11797 " Lists active SIP subscriptions for extension states\n";
11799 static char show_objects_usage[] =
11800 "Usage: sip show objects\n"
11801 " Lists status of known SIP objects\n";
11803 static char show_settings_usage[] =
11804 "Usage: sip show settings\n"
11805 " Provides detailed list of the configuration of the SIP channel.\n";
11807 /*! \brief Read SIP header (dialplan function) */
11808 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len)
11810 struct sip_pvt *p;
11811 const char *content = NULL;
11812 AST_DECLARE_APP_ARGS(args,
11813 AST_APP_ARG(header);
11814 AST_APP_ARG(number);
11816 int i, number, start = 0;
11818 if (ast_strlen_zero(data)) {
11819 ast_log(LOG_WARNING, "This function requires a header name.\n");
11820 return -1;
11823 ast_channel_lock(chan);
11824 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
11825 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
11826 ast_channel_unlock(chan);
11827 return -1;
11830 AST_STANDARD_APP_ARGS(args, data);
11831 if (!args.number) {
11832 number = 1;
11833 } else {
11834 sscanf(args.number, "%d", &number);
11835 if (number < 1)
11836 number = 1;
11839 p = chan->tech_pvt;
11841 /* If there is no private structure, this channel is no longer alive */
11842 if (!p) {
11843 ast_channel_unlock(chan);
11844 return -1;
11847 for (i = 0; i < number; i++)
11848 content = __get_header(&p->initreq, args.header, &start);
11850 if (ast_strlen_zero(content)) {
11851 ast_channel_unlock(chan);
11852 return -1;
11855 ast_copy_string(buf, content, len);
11856 ast_channel_unlock(chan);
11858 return 0;
11861 static struct ast_custom_function sip_header_function = {
11862 .name = "SIP_HEADER",
11863 .synopsis = "Gets the specified SIP header",
11864 .syntax = "SIP_HEADER(<name>[,<number>])",
11865 .desc = "Since there are several headers (such as Via) which can occur multiple\n"
11866 "times, SIP_HEADER takes an optional second argument to specify which header with\n"
11867 "that name to retrieve. Headers start at offset 1.\n",
11868 .read = func_header_read,
11871 /*! \brief Dial plan function to check if domain is local */
11872 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11874 if (ast_strlen_zero(data)) {
11875 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
11876 return -1;
11878 if (check_sip_domain(data, NULL, 0))
11879 ast_copy_string(buf, data, len);
11880 else
11881 buf[0] = '\0';
11882 return 0;
11885 static struct ast_custom_function checksipdomain_function = {
11886 .name = "CHECKSIPDOMAIN",
11887 .synopsis = "Checks if domain is a local domain",
11888 .syntax = "CHECKSIPDOMAIN(<domain|IP>)",
11889 .read = func_check_sipdomain,
11890 .desc = "This function checks if the domain in the argument is configured\n"
11891 "as a local SIP domain that this Asterisk server is configured to handle.\n"
11892 "Returns the domain name if it is locally handled, otherwise an empty string.\n"
11893 "Check the domain= configuration in sip.conf\n",
11896 /*! \brief ${SIPPEER()} Dialplan function - reads peer data */
11897 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11899 struct sip_peer *peer;
11900 char *colname;
11902 if ((colname = strchr(data, ':'))) /*! \todo Will be deprecated after 1.4 */
11903 *colname++ = '\0';
11904 else if ((colname = strchr(data, '|')))
11905 *colname++ = '\0';
11906 else
11907 colname = "ip";
11909 if (!(peer = find_peer(data, NULL, 1)))
11910 return -1;
11912 if (!strcasecmp(colname, "ip")) {
11913 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
11914 } else if (!strcasecmp(colname, "status")) {
11915 peer_status(peer, buf, len);
11916 } else if (!strcasecmp(colname, "language")) {
11917 ast_copy_string(buf, peer->language, len);
11918 } else if (!strcasecmp(colname, "regexten")) {
11919 ast_copy_string(buf, peer->regexten, len);
11920 } else if (!strcasecmp(colname, "limit")) {
11921 snprintf(buf, len, "%d", peer->call_limit);
11922 } else if (!strcasecmp(colname, "curcalls")) {
11923 snprintf(buf, len, "%d", peer->inUse);
11924 } else if (!strcasecmp(colname, "accountcode")) {
11925 ast_copy_string(buf, peer->accountcode, len);
11926 } else if (!strcasecmp(colname, "useragent")) {
11927 ast_copy_string(buf, peer->useragent, len);
11928 } else if (!strcasecmp(colname, "mailbox")) {
11929 ast_copy_string(buf, peer->mailbox, len);
11930 } else if (!strcasecmp(colname, "context")) {
11931 ast_copy_string(buf, peer->context, len);
11932 } else if (!strcasecmp(colname, "expire")) {
11933 snprintf(buf, len, "%d", peer->expire);
11934 } else if (!strcasecmp(colname, "dynamic")) {
11935 ast_copy_string(buf, (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no"), len);
11936 } else if (!strcasecmp(colname, "callerid_name")) {
11937 ast_copy_string(buf, peer->cid_name, len);
11938 } else if (!strcasecmp(colname, "callerid_num")) {
11939 ast_copy_string(buf, peer->cid_num, len);
11940 } else if (!strcasecmp(colname, "codecs")) {
11941 ast_getformatname_multiple(buf, len -1, peer->capability);
11942 } else if (!strncasecmp(colname, "codec[", 6)) {
11943 char *codecnum;
11944 int index = 0, codec = 0;
11946 codecnum = colname + 6; /* move past the '[' */
11947 codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
11948 index = atoi(codecnum);
11949 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
11950 ast_copy_string(buf, ast_getformatname(codec), len);
11954 ASTOBJ_UNREF(peer, sip_destroy_peer);
11956 return 0;
11959 /*! \brief Structure to declare a dialplan function: SIPPEER */
11960 struct ast_custom_function sippeer_function = {
11961 .name = "SIPPEER",
11962 .synopsis = "Gets SIP peer information",
11963 .syntax = "SIPPEER(<peername>[|item])",
11964 .read = function_sippeer,
11965 .desc = "Valid items are:\n"
11966 "- ip (default) The IP address.\n"
11967 "- mailbox The configured mailbox.\n"
11968 "- context The configured context.\n"
11969 "- expire The epoch time of the next expire.\n"
11970 "- dynamic Is it dynamic? (yes/no).\n"
11971 "- callerid_name The configured Caller ID name.\n"
11972 "- callerid_num The configured Caller ID number.\n"
11973 "- codecs The configured codecs.\n"
11974 "- status Status (if qualify=yes).\n"
11975 "- regexten Registration extension\n"
11976 "- limit Call limit (call-limit)\n"
11977 "- curcalls Current amount of calls \n"
11978 " Only available if call-limit is set\n"
11979 "- language Default language for peer\n"
11980 "- accountcode Account code for this peer\n"
11981 "- useragent Current user agent id for peer\n"
11982 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
11983 "\n"
11986 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
11987 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11989 struct sip_pvt *p;
11991 *buf = 0;
11993 if (!data) {
11994 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
11995 return -1;
11998 ast_channel_lock(chan);
11999 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
12000 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
12001 ast_channel_unlock(chan);
12002 return -1;
12005 p = chan->tech_pvt;
12007 /* If there is no private structure, this channel is no longer alive */
12008 if (!p) {
12009 ast_channel_unlock(chan);
12010 return -1;
12013 if (!strcasecmp(data, "peerip")) {
12014 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
12015 } else if (!strcasecmp(data, "recvip")) {
12016 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
12017 } else if (!strcasecmp(data, "from")) {
12018 ast_copy_string(buf, p->from, len);
12019 } else if (!strcasecmp(data, "uri")) {
12020 ast_copy_string(buf, p->uri, len);
12021 } else if (!strcasecmp(data, "useragent")) {
12022 ast_copy_string(buf, p->useragent, len);
12023 } else if (!strcasecmp(data, "peername")) {
12024 ast_copy_string(buf, p->peername, len);
12025 } else if (!strcasecmp(data, "t38passthrough")) {
12026 if (p->t38.state == T38_DISABLED)
12027 ast_copy_string(buf, "0", sizeof("0"));
12028 else /* T38 is offered or enabled in this call */
12029 ast_copy_string(buf, "1", sizeof("1"));
12030 } else {
12031 ast_channel_unlock(chan);
12032 return -1;
12034 ast_channel_unlock(chan);
12036 return 0;
12039 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
12040 static struct ast_custom_function sipchaninfo_function = {
12041 .name = "SIPCHANINFO",
12042 .synopsis = "Gets the specified SIP parameter from the current channel",
12043 .syntax = "SIPCHANINFO(item)",
12044 .read = function_sipchaninfo_read,
12045 .desc = "Valid items are:\n"
12046 "- peerip The IP address of the peer.\n"
12047 "- recvip The source IP address of the peer.\n"
12048 "- from The URI from the From: header.\n"
12049 "- uri The URI from the Contact: header.\n"
12050 "- useragent The useragent.\n"
12051 "- peername The name of the peer.\n"
12052 "- t38passthrough 1 if T38 is offered or enabled in this channel, otherwise 0\n"
12055 /*! \brief Parse 302 Moved temporalily response */
12056 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
12058 char tmp[SIPBUFSIZE];
12059 char *s, *e, *uri, *t;
12060 char *domain;
12062 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
12063 if ((t = strchr(tmp, ',')))
12064 *t = '\0';
12065 s = get_in_brackets(tmp);
12066 uri = ast_strdupa(s);
12067 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
12068 if (!strncasecmp(s, "sip:", 4))
12069 s += 4;
12070 e = strchr(s, ';');
12071 if (e)
12072 *e = '\0';
12073 if (option_debug)
12074 ast_log(LOG_DEBUG, "Found promiscuous redirection to 'SIP/%s'\n", s);
12075 if (p->owner)
12076 ast_string_field_build(p->owner, call_forward, "SIP/%s", s);
12077 } else {
12078 e = strchr(tmp, '@');
12079 if (e) {
12080 *e++ = '\0';
12081 domain = e;
12082 } else {
12083 /* No username part */
12084 domain = tmp;
12086 e = strchr(s, ';'); /* Strip of parameters in the username part */
12087 if (e)
12088 *e = '\0';
12089 e = strchr(domain, ';'); /* Strip of parameters in the domain part */
12090 if (e)
12091 *e = '\0';
12093 if (!strncasecmp(s, "sip:", 4))
12094 s += 4;
12095 if (option_debug > 1)
12096 ast_log(LOG_DEBUG, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
12097 if (p->owner) {
12098 pbx_builtin_setvar_helper(p->owner, "SIPREDIRECTURI", uri);
12099 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
12100 ast_string_field_set(p->owner, call_forward, s);
12105 /*! \brief Check pending actions on SIP call */
12106 static void check_pendings(struct sip_pvt *p)
12108 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
12109 /* if we can't BYE, then this is really a pending CANCEL */
12110 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
12111 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
12112 /* Actually don't destroy us yet, wait for the 487 on our original
12113 INVITE, but do set an autodestruct just in case we never get it. */
12114 else {
12115 /* We have a pending outbound invite, don't send someting
12116 new in-transaction */
12117 if (p->pendinginvite)
12118 return;
12120 /* Perhaps there is an SD change INVITE outstanding */
12121 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
12123 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
12124 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12125 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
12126 /* if we can't REINVITE, hold it for later */
12127 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
12128 if (option_debug)
12129 ast_log(LOG_DEBUG, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
12130 } else {
12131 if (option_debug)
12132 ast_log(LOG_DEBUG, "Sending pending reinvite on '%s'\n", p->callid);
12133 /* Didn't get to reinvite yet, so do it now */
12134 transmit_reinvite_with_sdp(p);
12135 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
12140 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
12141 to avoid race conditions between asterisk servers.
12142 Called from the scheduler.
12144 static int sip_reinvite_retry(const void *data)
12146 struct sip_pvt *p = (struct sip_pvt *) data;
12148 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
12149 p->waitid = -1;
12150 return 0;
12154 /*! \brief Handle SIP response to INVITE dialogue */
12155 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
12157 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
12158 int res = 0;
12159 int xmitres = 0;
12160 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
12161 struct ast_channel *bridgepeer = NULL;
12163 if (option_debug > 3) {
12164 if (reinvite)
12165 ast_log(LOG_DEBUG, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
12166 else
12167 ast_log(LOG_DEBUG, "SIP response %d to standard invite\n", resp);
12170 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) { /* This call is already gone */
12171 if (option_debug)
12172 ast_log(LOG_DEBUG, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
12173 return;
12176 /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
12177 /* Don't auto congest anymore since we've gotten something useful back */
12178 AST_SCHED_DEL(sched, p->initid);
12180 /* RFC3261 says we must treat every 1xx response (but not 100)
12181 that we don't recognize as if it was 183.
12183 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
12184 resp = 183;
12186 /* Any response between 100 and 199 is PROCEEDING */
12187 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
12188 p->invitestate = INV_PROCEEDING;
12190 /* Final response, not 200 ? */
12191 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
12192 p->invitestate = INV_COMPLETED;
12195 switch (resp) {
12196 case 100: /* Trying */
12197 case 101: /* Dialog establishment */
12198 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12199 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12200 check_pendings(p);
12201 break;
12203 case 180: /* 180 Ringing */
12204 case 182: /* 182 Queued */
12205 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12206 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12207 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12208 ast_queue_control(p->owner, AST_CONTROL_RINGING);
12209 if (p->owner->_state != AST_STATE_UP) {
12210 ast_setstate(p->owner, AST_STATE_RINGING);
12213 if (find_sdp(req)) {
12214 if (p->invitestate != INV_CANCELLED)
12215 p->invitestate = INV_EARLY_MEDIA;
12216 res = process_sdp(p, req);
12217 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12218 /* Queue a progress frame only if we have SDP in 180 or 182 */
12219 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
12222 check_pendings(p);
12223 break;
12225 case 183: /* Session progress */
12226 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12227 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12228 /* Ignore 183 Session progress without SDP */
12229 if (find_sdp(req)) {
12230 if (p->invitestate != INV_CANCELLED)
12231 p->invitestate = INV_EARLY_MEDIA;
12232 res = process_sdp(p, req);
12233 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12234 /* Queue a progress frame */
12235 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
12238 check_pendings(p);
12239 break;
12241 case 200: /* 200 OK on invite - someone's answering our call */
12242 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12243 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12244 p->authtries = 0;
12245 if (find_sdp(req)) {
12246 if ((res = process_sdp(p, req)) && !ast_test_flag(req, SIP_PKT_IGNORE))
12247 if (!reinvite)
12248 /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
12249 /* For re-invites, we try to recover */
12250 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12253 /* Parse contact header for continued conversation */
12254 /* When we get 200 OK, we know which device (and IP) to contact for this call */
12255 /* This is important when we have a SIP proxy between us and the phone */
12256 if (outgoing) {
12257 update_call_counter(p, DEC_CALL_RINGING);
12258 parse_ok_contact(p, req);
12259 if(set_address_from_contact(p)) {
12260 /* Bad contact - we don't know how to reach this device */
12261 /* We need to ACK, but then send a bye */
12262 /* OEJ: Possible issue that may need a check:
12263 If we have a proxy route between us and the device,
12264 should we care about resolving the contact
12265 or should we just send it?
12267 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12268 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12271 /* Save Record-Route for any later requests we make on this dialogue */
12272 if (!reinvite)
12273 build_route(p, req, 1);
12276 if (p->owner && (p->owner->_state == AST_STATE_UP) && (bridgepeer = ast_bridged_channel(p->owner))) { /* if this is a re-invite */
12277 struct sip_pvt *bridgepvt = NULL;
12279 if (!bridgepeer->tech) {
12280 ast_log(LOG_WARNING, "Ooooh.. no tech! That's REALLY bad\n");
12281 break;
12283 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
12284 bridgepvt = (struct sip_pvt*)(bridgepeer->tech_pvt);
12285 if (bridgepvt->udptl) {
12286 if (p->t38.state == T38_PEER_REINVITE) {
12287 sip_handle_t38_reinvite(bridgepeer, p, 0);
12288 ast_rtp_set_rtptimers_onhold(p->rtp);
12289 if (p->vrtp)
12290 ast_rtp_set_rtptimers_onhold(p->vrtp); /* Turn off RTP timers while we send fax */
12291 } else if (p->t38.state == T38_DISABLED && bridgepeer && (bridgepvt->t38.state == T38_ENABLED)) {
12292 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
12293 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
12294 /* XXXX Should we really destroy this session here, without any response at all??? */
12295 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12297 } else {
12298 if (option_debug > 1)
12299 ast_log(LOG_DEBUG, "Strange... The other side of the bridge does not have a udptl struct\n");
12300 ast_mutex_lock(&bridgepvt->lock);
12301 bridgepvt->t38.state = T38_DISABLED;
12302 ast_mutex_unlock(&bridgepvt->lock);
12303 if (option_debug)
12304 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->tech->type);
12305 p->t38.state = T38_DISABLED;
12306 if (option_debug > 1)
12307 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12309 } else {
12310 /* Other side is not a SIP channel */
12311 if (option_debug > 1)
12312 ast_log(LOG_DEBUG, "Strange... The other side of the bridge is not a SIP channel\n");
12313 p->t38.state = T38_DISABLED;
12314 if (option_debug > 1)
12315 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12318 if ((p->t38.state == T38_LOCAL_REINVITE) || (p->t38.state == T38_LOCAL_DIRECT)) {
12319 /* If there was T38 reinvite and we are supposed to answer with 200 OK than this should set us to T38 negotiated mode */
12320 p->t38.state = T38_ENABLED;
12321 if (option_debug)
12322 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12325 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12326 if (!reinvite) {
12327 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
12328 } else { /* RE-invite */
12329 ast_queue_frame(p->owner, &ast_null_frame);
12331 } else {
12332 /* It's possible we're getting an 200 OK after we've tried to disconnect
12333 by sending CANCEL */
12334 /* First send ACK, then send bye */
12335 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12336 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12338 /* If I understand this right, the branch is different for a non-200 ACK only */
12339 p->invitestate = INV_TERMINATED;
12340 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
12341 check_pendings(p);
12342 break;
12343 case 407: /* Proxy authentication */
12344 case 401: /* Www auth */
12345 /* First we ACK */
12346 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12347 if (p->options)
12348 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
12350 /* Then we AUTH */
12351 ast_string_field_free(p, theirtag); /* forget their old tag, so we don't match tags when getting response */
12352 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
12353 char *authenticate = (resp == 401 ? "WWW-Authenticate" : "Proxy-Authenticate");
12354 char *authorization = (resp == 401 ? "Authorization" : "Proxy-Authorization");
12355 if (p->authtries < MAX_AUTHTRIES)
12356 p->invitestate = INV_CALLING;
12357 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, authenticate, authorization, SIP_INVITE, 1)) {
12358 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
12359 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12360 sip_alreadygone(p);
12361 if (p->owner)
12362 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12365 break;
12367 case 403: /* Forbidden */
12368 /* First we ACK */
12369 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12370 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
12371 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner)
12372 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12373 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12374 sip_alreadygone(p);
12375 break;
12377 case 404: /* Not found */
12378 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12379 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12380 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12381 sip_alreadygone(p);
12382 break;
12384 case 408: /* Request timeout */
12385 case 481: /* Call leg does not exist */
12386 /* Could be REFER caused INVITE with replaces */
12387 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
12388 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12389 if (p->owner)
12390 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12391 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12392 break;
12393 case 487: /* Cancelled transaction */
12394 /* We have sent CANCEL on an outbound INVITE
12395 This transaction is already scheduled to be killed by sip_hangup().
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_hangup(p->owner);
12400 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
12401 } else if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
12402 update_call_counter(p, DEC_CALL_LIMIT);
12403 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
12404 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12405 sip_alreadygone(p);
12407 break;
12408 case 488: /* Not acceptable here */
12409 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12410 if (reinvite && p->udptl) {
12411 /* If this is a T.38 call, we should go back to
12412 audio. If this is an audio call - something went
12413 terribly wrong since we don't renegotiate codecs,
12414 only IP/port .
12416 p->t38.state = T38_DISABLED;
12417 /* Try to reset RTP timers */
12418 ast_rtp_set_rtptimers_onhold(p->rtp);
12419 ast_log(LOG_ERROR, "Got error on T.38 re-invite. Bad configuration. Peer needs to have T.38 disabled.\n");
12421 /*! \bug Is there any way we can go back to the audio call on both
12422 sides here?
12424 /* While figuring that out, hangup the call */
12425 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12426 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12427 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12428 } else if (p->udptl && p->t38.state == T38_LOCAL_DIRECT) {
12429 /* We tried to send T.38 out in an initial INVITE and the remote side rejected it,
12430 right now we can't fall back to audio so totally abort.
12432 p->t38.state = T38_DISABLED;
12433 /* Try to reset RTP timers */
12434 ast_rtp_set_rtptimers_onhold(p->rtp);
12435 ast_log(LOG_ERROR, "Got error on T.38 initial invite. Bailing out.\n");
12437 /* The dialog is now terminated */
12438 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12439 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12440 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12441 sip_alreadygone(p);
12442 } else {
12443 /* We can't set up this call, so give up */
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 /* If there's no dialog to end, then mark p as already gone */
12448 if (!reinvite)
12449 sip_alreadygone(p);
12451 break;
12452 case 491: /* Pending */
12453 /* we really should have to wait a while, then retransmit
12454 * We should support the retry-after at some point
12455 * At this point, we treat this as a congestion if the call is not in UP state
12457 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12458 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE)) {
12459 if (p->owner->_state != AST_STATE_UP) {
12460 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12461 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12462 } else {
12463 /* This is a re-invite that failed.
12464 * Reset the flag after a while
12466 int wait = 3 + ast_random() % 5;
12467 p->waitid = ast_sched_add(sched, wait, sip_reinvite_retry, p);
12468 if (option_debug > 2)
12469 ast_log(LOG_DEBUG, "Reinvite race. Waiting %d secs before retry\n", wait);
12472 break;
12474 case 501: /* Not implemented */
12475 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12476 if (p->owner)
12477 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12478 break;
12480 if (xmitres == XMIT_ERROR)
12481 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
12484 /* \brief Handle SIP response in REFER transaction
12485 We've sent a REFER, now handle responses to it
12487 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
12489 char *auth = "Proxy-Authenticate";
12490 char *auth2 = "Proxy-Authorization";
12492 /* If no refer structure exists, then do nothing */
12493 if (!p->refer)
12494 return;
12496 switch (resp) {
12497 case 202: /* Transfer accepted */
12498 /* We need to do something here */
12499 /* The transferee is now sending INVITE to target */
12500 p->refer->status = REFER_ACCEPTED;
12501 /* Now wait for next message */
12502 if (option_debug > 2)
12503 ast_log(LOG_DEBUG, "Got 202 accepted on transfer\n");
12504 /* We should hang along, waiting for NOTIFY's here */
12505 break;
12507 case 401: /* Not www-authorized on SIP method */
12508 case 407: /* Proxy auth */
12509 if (ast_strlen_zero(p->authname)) {
12510 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
12511 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12512 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12514 if (resp == 401) {
12515 auth = "WWW-Authenticate";
12516 auth2 = "Authorization";
12518 if ((p->authtries > 1) || do_proxy_auth(p, req, auth, auth2, SIP_REFER, 0)) {
12519 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
12520 p->refer->status = REFER_NOAUTH;
12521 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12523 break;
12524 case 481: /* Call leg does not exist */
12526 /* A transfer with Replaces did not work */
12527 /* OEJ: We should Set flag, cancel the REFER, go back
12528 to original call - but right now we can't */
12529 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
12530 if (p->owner)
12531 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12532 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12533 break;
12535 case 500: /* Server error */
12536 case 501: /* Method not implemented */
12537 /* Return to the current call onhold */
12538 /* Status flag needed to be reset */
12539 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
12540 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12541 p->refer->status = REFER_FAILED;
12542 break;
12543 case 603: /* Transfer declined */
12544 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
12545 p->refer->status = REFER_FAILED;
12546 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12547 break;
12551 /*! \brief Handle responses on REGISTER to services */
12552 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
12554 int expires, expires_ms;
12555 struct sip_registry *r;
12556 r=p->registry;
12558 switch (resp) {
12559 case 401: /* Unauthorized */
12560 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "WWW-Authenticate", "Authorization")) {
12561 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
12562 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12564 break;
12565 case 403: /* Forbidden */
12566 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
12567 if (global_regattempts_max)
12568 p->registry->regattempts = global_regattempts_max+1;
12569 AST_SCHED_DEL(sched, r->timeout);
12570 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12571 break;
12572 case 404: /* Not found */
12573 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username,p->registry->hostname);
12574 if (global_regattempts_max)
12575 p->registry->regattempts = global_regattempts_max+1;
12576 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12577 r->call = NULL;
12578 AST_SCHED_DEL(sched, r->timeout);
12579 break;
12580 case 407: /* Proxy auth */
12581 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization")) {
12582 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
12583 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12585 break;
12586 case 408: /* Request timeout */
12587 /* Got a timeout response, so reset the counter of failed responses */
12588 r->regattempts = 0;
12589 break;
12590 case 479: /* SER: Not able to process the URI - address is wrong in register*/
12591 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username,p->registry->hostname);
12592 if (global_regattempts_max)
12593 p->registry->regattempts = global_regattempts_max+1;
12594 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12595 r->call = NULL;
12596 AST_SCHED_DEL(sched, r->timeout);
12597 break;
12598 case 200: /* 200 OK */
12599 if (!r) {
12600 ast_log(LOG_WARNING, "Got 200 OK on REGISTER that isn't a register\n");
12601 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12602 return 0;
12605 r->regstate = REG_STATE_REGISTERED;
12606 r->regtime = time(NULL); /* Reset time of last succesful registration */
12607 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
12608 r->regattempts = 0;
12609 if (option_debug)
12610 ast_log(LOG_DEBUG, "Registration successful\n");
12611 if (r->timeout > -1) {
12612 if (option_debug)
12613 ast_log(LOG_DEBUG, "Cancelling timeout %d\n", r->timeout);
12615 AST_SCHED_DEL(sched, r->timeout);
12616 r->call = NULL;
12617 p->registry = NULL;
12618 /* Let this one hang around until we have all the responses */
12619 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12620 /* ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); */
12622 /* set us up for re-registering */
12623 /* figure out how long we got registered for */
12624 AST_SCHED_DEL(sched, r->expire);
12625 /* according to section 6.13 of RFC, contact headers override
12626 expires headers, so check those first */
12627 expires = 0;
12629 /* XXX todo: try to save the extra call */
12630 if (!ast_strlen_zero(get_header(req, "Contact"))) {
12631 const char *contact = NULL;
12632 const char *tmptmp = NULL;
12633 int start = 0;
12634 for(;;) {
12635 contact = __get_header(req, "Contact", &start);
12636 /* this loop ensures we get a contact header about our register request */
12637 if(!ast_strlen_zero(contact)) {
12638 if( (tmptmp=strstr(contact, p->our_contact))) {
12639 contact=tmptmp;
12640 break;
12642 } else
12643 break;
12645 tmptmp = strcasestr(contact, "expires=");
12646 if (tmptmp) {
12647 if (sscanf(tmptmp + 8, "%d;", &expires) != 1)
12648 expires = 0;
12652 if (!expires)
12653 expires=atoi(get_header(req, "expires"));
12654 if (!expires)
12655 expires=default_expiry;
12657 expires_ms = expires * 1000;
12658 if (expires <= EXPIRY_GUARD_LIMIT)
12659 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT),EXPIRY_GUARD_MIN);
12660 else
12661 expires_ms -= EXPIRY_GUARD_SECS * 1000;
12662 if (sipdebug)
12663 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
12665 r->refresh= (int) expires_ms / 1000;
12667 /* Schedule re-registration before we expire */
12668 AST_SCHED_DEL(sched, r->expire);
12669 r->expire = ast_sched_add(sched, expires_ms, sip_reregister, r);
12670 ASTOBJ_UNREF(r, sip_registry_destroy);
12672 return 1;
12675 /*! \brief Handle qualification responses (OPTIONS) */
12676 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
12678 struct sip_peer *peer = p->relatedpeer;
12679 int statechanged, is_reachable, was_reachable;
12680 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
12683 * Compute the response time to a ping (goes in peer->lastms.)
12684 * -1 means did not respond, 0 means unknown,
12685 * 1..maxms is a valid response, >maxms means late response.
12687 if (pingtime < 1) /* zero = unknown, so round up to 1 */
12688 pingtime = 1;
12690 /* Now determine new state and whether it has changed.
12691 * Use some helper variables to simplify the writing
12692 * of the expressions.
12694 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
12695 is_reachable = pingtime <= peer->maxms;
12696 statechanged = peer->lastms == 0 /* yes, unknown before */
12697 || was_reachable != is_reachable;
12699 peer->lastms = pingtime;
12700 peer->call = NULL;
12701 if (statechanged) {
12702 const char *s = is_reachable ? "Reachable" : "Lagged";
12704 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
12705 peer->name, s, pingtime, peer->maxms);
12706 ast_device_state_changed("SIP/%s", peer->name);
12707 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
12708 "Peer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
12709 peer->name, s, pingtime);
12712 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
12713 struct sip_peer *peer_ptr = peer;
12714 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
12717 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12719 /* Try again eventually */
12720 peer->pokeexpire = ast_sched_add(sched,
12721 is_reachable ? DEFAULT_FREQ_OK : DEFAULT_FREQ_NOTOK,
12722 sip_poke_peer_s, ASTOBJ_REF(peer));
12724 if (peer->pokeexpire == -1) {
12725 ASTOBJ_UNREF(peer, sip_destroy_peer);
12729 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
12730 static void stop_media_flows(struct sip_pvt *p)
12732 /* Immediately stop RTP, VRTP and UDPTL as applicable */
12733 if (p->rtp)
12734 ast_rtp_stop(p->rtp);
12735 if (p->vrtp)
12736 ast_rtp_stop(p->vrtp);
12737 if (p->udptl)
12738 ast_udptl_stop(p->udptl);
12741 /*! \brief Handle SIP response in dialogue */
12742 /* XXX only called by handle_request */
12743 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
12745 struct ast_channel *owner;
12746 int sipmethod;
12747 int res = 1;
12748 const char *c = get_header(req, "Cseq");
12749 /* 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 */
12750 char *c_copy = ast_strdupa(c);
12751 /* Skip the Cseq and its subsequent spaces */
12752 const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
12754 if (!msg)
12755 msg = "";
12757 sipmethod = find_sip_method(msg);
12759 owner = p->owner;
12760 if (owner)
12761 owner->hangupcause = hangup_sip2cause(resp);
12763 /* Acknowledge whatever it is destined for */
12764 if ((resp >= 100) && (resp <= 199))
12765 __sip_semi_ack(p, seqno, 0, sipmethod);
12766 else
12767 __sip_ack(p, seqno, 0, sipmethod);
12769 /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
12770 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite)
12771 p->pendinginvite = 0;
12773 /* Get their tag if we haven't already */
12774 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
12775 char tag[128];
12777 gettag(req, "To", tag, sizeof(tag));
12778 ast_string_field_set(p, theirtag, tag);
12780 if (p->relatedpeer && p->method == SIP_OPTIONS) {
12781 /* We don't really care what the response is, just that it replied back.
12782 Well, as long as it's not a 100 response... since we might
12783 need to hang around for something more "definitive" */
12784 if (resp != 100)
12785 handle_response_peerpoke(p, resp, req);
12786 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12787 switch(resp) {
12788 case 100: /* 100 Trying */
12789 case 101: /* 101 Dialog establishment */
12790 if (sipmethod == SIP_INVITE)
12791 handle_response_invite(p, resp, rest, req, seqno);
12792 break;
12793 case 183: /* 183 Session Progress */
12794 if (sipmethod == SIP_INVITE)
12795 handle_response_invite(p, resp, rest, req, seqno);
12796 break;
12797 case 180: /* 180 Ringing */
12798 if (sipmethod == SIP_INVITE)
12799 handle_response_invite(p, resp, rest, req, seqno);
12800 break;
12801 case 182: /* 182 Queued */
12802 if (sipmethod == SIP_INVITE)
12803 handle_response_invite(p, resp, rest, req, seqno);
12804 break;
12805 case 200: /* 200 OK */
12806 p->authtries = 0; /* Reset authentication counter */
12807 if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
12808 /* We successfully transmitted a message
12809 or a video update request in INFO */
12810 /* Nothing happens here - the message is inside a dialog */
12811 } else if (sipmethod == SIP_INVITE) {
12812 handle_response_invite(p, resp, rest, req, seqno);
12813 } else if (sipmethod == SIP_NOTIFY) {
12814 /* They got the notify, this is the end */
12815 if (p->owner) {
12816 if (!p->refer) {
12817 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
12818 ast_queue_hangup(p->owner);
12819 } else if (option_debug > 3)
12820 ast_log(LOG_DEBUG, "Got OK on REFER Notify message\n");
12821 } else {
12822 if (p->subscribed == NONE)
12823 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12824 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
12825 /* Ready to send the next state we have on queue */
12826 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
12827 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
12830 } else if (sipmethod == SIP_REGISTER)
12831 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12832 else if (sipmethod == SIP_BYE) /* Ok, we're ready to go */
12833 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12834 break;
12835 case 202: /* Transfer accepted */
12836 if (sipmethod == SIP_REFER)
12837 handle_response_refer(p, resp, rest, req, seqno);
12838 break;
12839 case 401: /* Not www-authorized on SIP method */
12840 if (sipmethod == SIP_INVITE)
12841 handle_response_invite(p, resp, rest, req, seqno);
12842 else if (sipmethod == SIP_REFER)
12843 handle_response_refer(p, resp, rest, req, seqno);
12844 else if (p->registry && sipmethod == SIP_REGISTER)
12845 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12846 else if (sipmethod == SIP_BYE) {
12847 if (ast_strlen_zero(p->authname)) {
12848 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12849 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12850 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12851 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "WWW-Authenticate", "Authorization", sipmethod, 0)) {
12852 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
12853 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12854 /* We fail to auth bye on our own call, but still needs to tear down the call.
12855 Life, they call it. */
12857 } else {
12858 ast_log(LOG_WARNING, "Got authentication request (401) on unknown %s to '%s'\n", sip_methods[sipmethod].text, get_header(req, "To"));
12859 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12861 break;
12862 case 403: /* Forbidden - we failed authentication */
12863 if (sipmethod == SIP_INVITE)
12864 handle_response_invite(p, resp, rest, req, seqno);
12865 else if (p->registry && sipmethod == SIP_REGISTER)
12866 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12867 else {
12868 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
12869 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12871 break;
12872 case 404: /* Not found */
12873 if (p->registry && sipmethod == SIP_REGISTER)
12874 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12875 else if (sipmethod == SIP_INVITE)
12876 handle_response_invite(p, resp, rest, req, seqno);
12877 else if (owner)
12878 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12879 break;
12880 case 407: /* Proxy auth required */
12881 if (sipmethod == SIP_INVITE)
12882 handle_response_invite(p, resp, rest, req, seqno);
12883 else if (sipmethod == SIP_REFER)
12884 handle_response_refer(p, resp, rest, req, seqno);
12885 else if (p->registry && sipmethod == SIP_REGISTER)
12886 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12887 else if (sipmethod == SIP_BYE) {
12888 if (ast_strlen_zero(p->authname)) {
12889 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12890 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12891 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12892 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", sipmethod, 0)) {
12893 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
12894 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12896 } else /* We can't handle this, giving up in a bad way */
12897 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12899 break;
12900 case 408: /* Request timeout - terminate dialog */
12901 if (sipmethod == SIP_INVITE)
12902 handle_response_invite(p, resp, rest, req, seqno);
12903 else if (sipmethod == SIP_REGISTER)
12904 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12905 else if (sipmethod == SIP_BYE) {
12906 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12907 if (option_debug)
12908 ast_log(LOG_DEBUG, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
12909 } else {
12910 if (owner)
12911 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12912 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12914 break;
12915 case 481: /* Call leg does not exist */
12916 if (sipmethod == SIP_INVITE) {
12917 handle_response_invite(p, resp, rest, req, seqno);
12918 } else if (sipmethod == SIP_REFER) {
12919 handle_response_refer(p, resp, rest, req, seqno);
12920 } else if (sipmethod == SIP_BYE) {
12921 /* The other side has no transaction to bye,
12922 just assume it's all right then */
12923 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12924 } else if (sipmethod == SIP_CANCEL) {
12925 /* The other side has no transaction to cancel,
12926 just assume it's all right then */
12927 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12928 } else {
12929 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12930 /* Guessing that this is not an important request */
12932 break;
12933 case 487:
12934 if (sipmethod == SIP_INVITE)
12935 handle_response_invite(p, resp, rest, req, seqno);
12936 break;
12937 case 488: /* Not acceptable here - codec error */
12938 if (sipmethod == SIP_INVITE)
12939 handle_response_invite(p, resp, rest, req, seqno);
12940 break;
12941 case 491: /* Pending */
12942 if (sipmethod == SIP_INVITE)
12943 handle_response_invite(p, resp, rest, req, seqno);
12944 else {
12945 if (option_debug)
12946 ast_log(LOG_DEBUG, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
12947 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12949 break;
12950 case 501: /* Not Implemented */
12951 if (sipmethod == SIP_INVITE)
12952 handle_response_invite(p, resp, rest, req, seqno);
12953 else if (sipmethod == SIP_REFER)
12954 handle_response_refer(p, resp, rest, req, seqno);
12955 else
12956 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
12957 break;
12958 case 603: /* Declined transfer */
12959 if (sipmethod == SIP_REFER) {
12960 handle_response_refer(p, resp, rest, req, seqno);
12961 break;
12963 /* Fallthrough */
12964 default:
12965 if ((resp >= 300) && (resp < 700)) {
12966 /* Fatal response */
12967 if ((option_verbose > 2) && (resp != 487))
12968 ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
12970 if (sipmethod == SIP_INVITE)
12971 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
12973 /* XXX Locking issues?? XXX */
12974 switch(resp) {
12975 case 300: /* Multiple Choices */
12976 case 301: /* Moved permenantly */
12977 case 302: /* Moved temporarily */
12978 case 305: /* Use Proxy */
12979 parse_moved_contact(p, req);
12980 /* Fall through */
12981 case 486: /* Busy here */
12982 case 600: /* Busy everywhere */
12983 case 603: /* Decline */
12984 if (p->owner)
12985 ast_queue_control(p->owner, AST_CONTROL_BUSY);
12986 break;
12987 case 482: /*
12988 \note SIP is incapable of performing a hairpin call, which
12989 is yet another failure of not having a layer 2 (again, YAY
12990 IETF for thinking ahead). So we treat this as a call
12991 forward and hope we end up at the right place... */
12992 if (option_debug)
12993 ast_log(LOG_DEBUG, "Hairpin detected, setting up call forward for what it's worth\n");
12994 if (p->owner)
12995 ast_string_field_build(p->owner, call_forward,
12996 "Local/%s@%s", p->username, p->context);
12997 /* Fall through */
12998 case 480: /* Temporarily Unavailable */
12999 case 404: /* Not Found */
13000 case 410: /* Gone */
13001 case 400: /* Bad Request */
13002 case 500: /* Server error */
13003 if (sipmethod == SIP_REFER) {
13004 handle_response_refer(p, resp, rest, req, seqno);
13005 break;
13007 /* Fall through */
13008 case 502: /* Bad gateway */
13009 case 503: /* Service Unavailable */
13010 case 504: /* Server Timeout */
13011 if (owner)
13012 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
13013 break;
13014 default:
13015 /* Send hangup */
13016 if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
13017 ast_queue_hangup(p->owner);
13018 break;
13020 /* ACK on invite */
13021 if (sipmethod == SIP_INVITE)
13022 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
13023 if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
13024 sip_alreadygone(p);
13025 if (!p->owner)
13026 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13027 } else if ((resp >= 100) && (resp < 200)) {
13028 if (sipmethod == SIP_INVITE) {
13029 if (!ast_test_flag(req, SIP_PKT_IGNORE) && sip_cancel_destroy(p))
13030 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13031 if (find_sdp(req))
13032 process_sdp(p, req);
13033 if (p->owner) {
13034 /* Queue a progress frame */
13035 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
13038 } else
13039 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));
13041 } else {
13042 /* Responses to OUTGOING SIP requests on INCOMING calls
13043 get handled here. As well as out-of-call message responses */
13044 if (ast_test_flag(req, SIP_PKT_DEBUG))
13045 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
13047 if (sipmethod == SIP_INVITE && resp == 200) {
13048 /* Tags in early session is replaced by the tag in 200 OK, which is
13049 the final reply to our INVITE */
13050 char tag[128];
13052 gettag(req, "To", tag, sizeof(tag));
13053 ast_string_field_set(p, theirtag, tag);
13056 switch(resp) {
13057 case 200:
13058 if (sipmethod == SIP_INVITE) {
13059 handle_response_invite(p, resp, rest, req, seqno);
13060 } else if (sipmethod == SIP_CANCEL) {
13061 if (option_debug)
13062 ast_log(LOG_DEBUG, "Got 200 OK on CANCEL\n");
13064 /* Wait for 487, then destroy */
13065 } else if (sipmethod == SIP_NOTIFY) {
13066 /* They got the notify, this is the end */
13067 if (p->owner) {
13068 if (p->refer) {
13069 if (option_debug)
13070 ast_log(LOG_DEBUG, "Got 200 OK on NOTIFY for transfer\n");
13071 } else
13072 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
13073 /* ast_queue_hangup(p->owner); Disabled */
13074 } else {
13075 if (!p->subscribed && !p->refer)
13076 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13077 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
13078 /* Ready to send the next state we have on queue */
13079 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
13080 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
13083 } else if (sipmethod == SIP_BYE)
13084 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13085 else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO)
13086 /* We successfully transmitted a message or
13087 a video update request in INFO */
13089 else if (sipmethod == SIP_BYE)
13090 /* Ok, we're ready to go */
13091 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13092 break;
13093 case 202: /* Transfer accepted */
13094 if (sipmethod == SIP_REFER)
13095 handle_response_refer(p, resp, rest, req, seqno);
13096 break;
13097 case 401: /* www-auth */
13098 case 407:
13099 if (sipmethod == SIP_REFER)
13100 handle_response_refer(p, resp, rest, req, seqno);
13101 else if (sipmethod == SIP_INVITE)
13102 handle_response_invite(p, resp, rest, req, seqno);
13103 else if (sipmethod == SIP_BYE) {
13104 char *auth, *auth2;
13106 auth = (resp == 407 ? "Proxy-Authenticate" : "WWW-Authenticate");
13107 auth2 = (resp == 407 ? "Proxy-Authorization" : "Authorization");
13108 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, auth, auth2, sipmethod, 0)) {
13109 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
13110 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13113 break;
13114 case 481: /* Call leg does not exist */
13115 if (sipmethod == SIP_INVITE) {
13116 /* Re-invite failed */
13117 handle_response_invite(p, resp, rest, req, seqno);
13118 } else if (sipmethod == SIP_BYE) {
13119 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13120 } else if (sipdebug) {
13121 ast_log (LOG_DEBUG, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
13123 break;
13124 case 501: /* Not Implemented */
13125 if (sipmethod == SIP_INVITE)
13126 handle_response_invite(p, resp, rest, req, seqno);
13127 else if (sipmethod == SIP_REFER)
13128 handle_response_refer(p, resp, rest, req, seqno);
13129 break;
13130 case 603: /* Declined transfer */
13131 if (sipmethod == SIP_REFER) {
13132 handle_response_refer(p, resp, rest, req, seqno);
13133 break;
13135 /* Fallthrough */
13136 default: /* Errors without handlers */
13137 if ((resp >= 100) && (resp < 200)) {
13138 if (sipmethod == SIP_INVITE) { /* re-invite */
13139 if (!ast_test_flag(req, SIP_PKT_IGNORE) && sip_cancel_destroy(p))
13140 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13143 if ((resp >= 300) && (resp < 700)) {
13144 if ((option_verbose > 2) && (resp != 487))
13145 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));
13146 switch(resp) {
13147 case 488: /* Not acceptable here - codec error */
13148 case 603: /* Decline */
13149 case 500: /* Server error */
13150 case 502: /* Bad gateway */
13151 case 503: /* Service Unavailable */
13152 case 504: /* Server timeout */
13154 /* re-invite failed */
13155 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
13156 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13157 break;
13160 break;
13166 /*! \brief Park SIP call support function
13167 Starts in a new thread, then parks the call
13168 XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
13169 audio can't be heard before hangup
13171 static void *sip_park_thread(void *stuff)
13173 struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
13174 struct sip_dual *d;
13175 struct sip_request req;
13176 int ext;
13177 int res;
13179 d = stuff;
13180 transferee = d->chan1;
13181 transferer = d->chan2;
13182 copy_request(&req, &d->req);
13183 free(d);
13185 if (!transferee || !transferer) {
13186 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
13187 return NULL;
13189 if (option_debug > 3)
13190 ast_log(LOG_DEBUG, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
13192 ast_channel_lock(transferee);
13193 if (ast_do_masquerade(transferee)) {
13194 ast_log(LOG_WARNING, "Masquerade failed.\n");
13195 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
13196 ast_channel_unlock(transferee);
13197 return NULL;
13199 ast_channel_unlock(transferee);
13201 res = ast_park_call(transferee, transferer, 0, &ext);
13204 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
13205 if (!res) {
13206 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
13207 } else {
13208 /* Then tell the transferer what happened */
13209 sprintf(buf, "Call parked on extension '%d'", ext);
13210 transmit_message_with_text(transferer->tech_pvt, buf);
13212 #endif
13214 /* Any way back to the current call??? */
13215 /* Transmit response to the REFER request */
13216 transmit_response(transferer->tech_pvt, "202 Accepted", &req);
13217 if (!res) {
13218 /* Transfer succeeded */
13219 append_history(transferer->tech_pvt, "SIPpark","Parked call on %d", ext);
13220 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
13221 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
13222 ast_hangup(transferer); /* This will cause a BYE */
13223 if (option_debug)
13224 ast_log(LOG_DEBUG, "SIP Call parked on extension '%d'\n", ext);
13225 } else {
13226 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
13227 append_history(transferer->tech_pvt, "SIPpark","Parking failed\n");
13228 if (option_debug)
13229 ast_log(LOG_DEBUG, "SIP Call parked failed \n");
13230 /* Do not hangup call */
13232 return NULL;
13235 /*! \brief Park a call using the subsystem in res_features.c
13236 This is executed in a separate thread
13238 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
13240 struct sip_dual *d;
13241 struct ast_channel *transferee, *transferer;
13242 /* Chan2m: The transferer, chan1m: The transferee */
13243 pthread_t th;
13245 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
13246 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
13247 if ((!transferer) || (!transferee)) {
13248 if (transferee) {
13249 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13250 ast_hangup(transferee);
13252 if (transferer) {
13253 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13254 ast_hangup(transferer);
13256 return -1;
13259 /* Make formats okay */
13260 transferee->readformat = chan1->readformat;
13261 transferee->writeformat = chan1->writeformat;
13263 /* Prepare for taking over the channel */
13264 ast_channel_masquerade(transferee, chan1);
13266 /* Setup the extensions and such */
13267 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
13268 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
13269 transferee->priority = chan1->priority;
13271 /* We make a clone of the peer channel too, so we can play
13272 back the announcement */
13274 /* Make formats okay */
13275 transferer->readformat = chan2->readformat;
13276 transferer->writeformat = chan2->writeformat;
13278 /* Prepare for taking over the channel. Go ahead and grab this channel
13279 * lock here to avoid a deadlock with callbacks into the channel driver
13280 * that hold the channel lock and want the pvt lock. */
13281 while (ast_channel_trylock(chan2)) {
13282 struct sip_pvt *pvt = chan2->tech_pvt;
13283 DEADLOCK_AVOIDANCE(&pvt->lock);
13285 ast_channel_masquerade(transferer, chan2);
13286 ast_channel_unlock(chan2);
13288 /* Setup the extensions and such */
13289 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
13290 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
13291 transferer->priority = chan2->priority;
13293 ast_channel_lock(transferer);
13294 if (ast_do_masquerade(transferer)) {
13295 ast_log(LOG_WARNING, "Masquerade failed :(\n");
13296 ast_channel_unlock(transferer);
13297 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13298 ast_hangup(transferer);
13299 return -1;
13301 ast_channel_unlock(transferer);
13302 if (!transferer || !transferee) {
13303 if (!transferer) {
13304 if (option_debug)
13305 ast_log(LOG_DEBUG, "No transferer channel, giving up parking\n");
13307 if (!transferee) {
13308 if (option_debug)
13309 ast_log(LOG_DEBUG, "No transferee channel, giving up parking\n");
13311 return -1;
13313 if ((d = ast_calloc(1, sizeof(*d)))) {
13314 pthread_attr_t attr;
13316 pthread_attr_init(&attr);
13317 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
13319 /* Save original request for followup */
13320 copy_request(&d->req, req);
13321 d->chan1 = transferee; /* Transferee */
13322 d->chan2 = transferer; /* Transferer */
13323 d->seqno = seqno;
13324 if (ast_pthread_create_background(&th, &attr, sip_park_thread, d) < 0) {
13325 /* Could not start thread */
13326 free(d); /* We don't need it anymore. If thread is created, d will be free'd
13327 by sip_park_thread() */
13328 pthread_attr_destroy(&attr);
13329 return 0;
13331 pthread_attr_destroy(&attr);
13333 return -1;
13336 /*! \brief Turn off generator data
13337 XXX Does this function belong in the SIP channel?
13339 static void ast_quiet_chan(struct ast_channel *chan)
13341 if (chan && chan->_state == AST_STATE_UP) {
13342 if (ast_test_flag(chan, AST_FLAG_MOH))
13343 ast_moh_stop(chan);
13344 else if (chan->generatordata)
13345 ast_deactivate_generator(chan);
13349 /*! \brief Attempt transfer of SIP call
13350 This fix for attended transfers on a local PBX */
13351 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
13353 int res = 0;
13354 struct ast_channel *peera = NULL,
13355 *peerb = NULL,
13356 *peerc = NULL,
13357 *peerd = NULL;
13360 /* We will try to connect the transferee with the target and hangup
13361 all channels to the transferer */
13362 if (option_debug > 3) {
13363 ast_log(LOG_DEBUG, "Sip transfer:--------------------\n");
13364 if (transferer->chan1)
13365 ast_log(LOG_DEBUG, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
13366 else
13367 ast_log(LOG_DEBUG, "-- No transferer first channel - odd??? \n");
13368 if (target->chan1)
13369 ast_log(LOG_DEBUG, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
13370 else
13371 ast_log(LOG_DEBUG, "-- No target first channel ---\n");
13372 if (transferer->chan2)
13373 ast_log(LOG_DEBUG, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
13374 else
13375 ast_log(LOG_DEBUG, "-- No bridged call to transferee\n");
13376 if (target->chan2)
13377 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)");
13378 else
13379 ast_log(LOG_DEBUG, "-- No target second channel ---\n");
13380 ast_log(LOG_DEBUG, "-- END Sip transfer:--------------------\n");
13382 if (transferer->chan2) { /* We have a bridge on the transferer's channel */
13383 peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
13384 peerb = target->chan1; /* Transferer - PBX -> target channel - This will get lost in masq */
13385 peerc = transferer->chan2; /* Asterisk to Transferee */
13386 peerd = target->chan2; /* Asterisk to Target */
13387 if (option_debug > 2)
13388 ast_log(LOG_DEBUG, "SIP transfer: Four channels to handle\n");
13389 } else if (target->chan2) { /* Transferer has no bridge (IVR), but transferee */
13390 peera = target->chan1; /* Transferer to PBX -> target channel */
13391 peerb = transferer->chan1; /* Transferer to IVR*/
13392 peerc = target->chan2; /* Asterisk to Target */
13393 peerd = transferer->chan2; /* Nothing */
13394 if (option_debug > 2)
13395 ast_log(LOG_DEBUG, "SIP transfer: Three channels to handle\n");
13398 if (peera && peerb && peerc && (peerb != peerc)) {
13399 ast_quiet_chan(peera); /* Stop generators */
13400 ast_quiet_chan(peerb);
13401 ast_quiet_chan(peerc);
13402 if (peerd)
13403 ast_quiet_chan(peerd);
13405 if (option_debug > 3)
13406 ast_log(LOG_DEBUG, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
13407 if (ast_channel_masquerade(peerb, peerc)) {
13408 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
13409 res = -1;
13410 } else
13411 ast_log(LOG_DEBUG, "SIP transfer: Succeeded to masquerade channels.\n");
13412 return res;
13413 } else {
13414 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
13415 if (transferer->chan1)
13416 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
13417 if (target->chan1)
13418 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
13419 return -2;
13421 return 0;
13424 /*! \brief Get tag from packet
13426 * \return Returns the pointer to the provided tag buffer,
13427 * or NULL if the tag was not found.
13429 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
13431 const char *thetag;
13433 if (!tagbuf)
13434 return NULL;
13435 tagbuf[0] = '\0'; /* reset the buffer */
13436 thetag = get_header(req, header);
13437 thetag = strcasestr(thetag, ";tag=");
13438 if (thetag) {
13439 thetag += 5;
13440 ast_copy_string(tagbuf, thetag, tagbufsize);
13441 return strsep(&tagbuf, ";");
13443 return NULL;
13446 /*! \brief Handle incoming notifications */
13447 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
13449 /* This is mostly a skeleton for future improvements */
13450 /* Mostly created to return proper answers on notifications on outbound REFER's */
13451 int res = 0;
13452 const char *event = get_header(req, "Event");
13453 char *eventid = NULL;
13454 char *sep;
13456 if( (sep = strchr(event, ';')) ) { /* XXX bug here - overwriting string ? */
13457 *sep++ = '\0';
13458 eventid = sep;
13461 if (option_debug > 1 && sipdebug)
13462 ast_log(LOG_DEBUG, "Got NOTIFY Event: %s\n", event);
13464 if (strcmp(event, "refer")) {
13465 /* We don't understand this event. */
13466 /* Here's room to implement incoming voicemail notifications :-) */
13467 transmit_response(p, "489 Bad event", req);
13468 res = -1;
13469 } else {
13470 /* Save nesting depth for now, since there might be other events we will
13471 support in the future */
13473 /* Handle REFER notifications */
13475 char buf[1024];
13476 char *cmd, *code;
13477 int respcode;
13478 int success = TRUE;
13480 /* EventID for each transfer... EventID is basically the REFER cseq
13482 We are getting notifications on a call that we transfered
13483 We should hangup when we are getting a 200 OK in a sipfrag
13484 Check if we have an owner of this event */
13486 /* Check the content type */
13487 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
13488 /* We need a sipfrag */
13489 transmit_response(p, "400 Bad request", req);
13490 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13491 return -1;
13494 /* Get the text of the attachment */
13495 if (get_msg_text(buf, sizeof(buf), req)) {
13496 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
13497 transmit_response(p, "400 Bad request", req);
13498 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13499 return -1;
13503 From the RFC...
13504 A minimal, but complete, implementation can respond with a single
13505 NOTIFY containing either the body:
13506 SIP/2.0 100 Trying
13508 if the subscription is pending, the body:
13509 SIP/2.0 200 OK
13510 if the reference was successful, the body:
13511 SIP/2.0 503 Service Unavailable
13512 if the reference failed, or the body:
13513 SIP/2.0 603 Declined
13515 if the REFER request was accepted before approval to follow the
13516 reference could be obtained and that approval was subsequently denied
13517 (see Section 2.4.7).
13519 If there are several REFERs in the same dialog, we need to
13520 match the ID of the event header...
13522 if (option_debug > 2)
13523 ast_log(LOG_DEBUG, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
13524 cmd = ast_skip_blanks(buf);
13525 code = cmd;
13526 /* We are at SIP/2.0 */
13527 while(*code && (*code > 32)) { /* Search white space */
13528 code++;
13530 *code++ = '\0';
13531 code = ast_skip_blanks(code);
13532 sep = code;
13533 sep++;
13534 while(*sep && (*sep > 32)) { /* Search white space */
13535 sep++;
13537 *sep++ = '\0'; /* Response string */
13538 respcode = atoi(code);
13539 switch (respcode) {
13540 case 100: /* Trying: */
13541 case 101: /* dialog establishment */
13542 /* Don't do anything yet */
13543 break;
13544 case 183: /* Ringing: */
13545 /* Don't do anything yet */
13546 break;
13547 case 200: /* OK: The new call is up, hangup this call */
13548 /* Hangup the call that we are replacing */
13549 break;
13550 case 301: /* Moved permenantly */
13551 case 302: /* Moved temporarily */
13552 /* Do we get the header in the packet in this case? */
13553 success = FALSE;
13554 break;
13555 case 503: /* Service Unavailable: The new call failed */
13556 /* Cancel transfer, continue the call */
13557 success = FALSE;
13558 break;
13559 case 603: /* Declined: Not accepted */
13560 /* Cancel transfer, continue the current call */
13561 success = FALSE;
13562 break;
13564 if (!success) {
13565 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
13568 /* Confirm that we received this packet */
13569 transmit_response(p, "200 OK", req);
13572 if (!p->lastinvite)
13573 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13575 return res;
13578 /*! \brief Handle incoming OPTIONS request */
13579 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
13581 int res;
13584 /* XXX Should we authenticate OPTIONS? XXX */
13586 if (p->lastinvite) {
13587 /* if this is a request in an active dialog, just confirm that the dialog exists. */
13588 transmit_response_with_allow(p, "200 OK", req, 0);
13589 return 0;
13592 res = get_destination(p, req);
13593 build_contact(p);
13595 if (ast_strlen_zero(p->context))
13596 ast_string_field_set(p, context, default_context);
13598 if (ast_shutting_down())
13599 transmit_response_with_allow(p, "503 Unavailable", req, 0);
13600 else if (res < 0)
13601 transmit_response_with_allow(p, "404 Not Found", req, 0);
13602 else
13603 transmit_response_with_allow(p, "200 OK", req, 0);
13605 /* Destroy if this OPTIONS was the opening request, but not if
13606 it's in the middle of a normal call flow. */
13607 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13609 return res;
13612 /*! \brief Handle the transfer part of INVITE with a replaces: header,
13613 meaning a target pickup or an attended transfer */
13614 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin)
13616 struct ast_frame *f;
13617 int earlyreplace = 0;
13618 int oneleggedreplace = 0; /* Call with no bridge, propably IVR or voice message */
13619 struct ast_channel *c = p->owner; /* Our incoming call */
13620 struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
13621 struct ast_channel *targetcall; /* The bridge to the take-over target */
13623 /* Check if we're in ring state */
13624 if (replacecall->_state == AST_STATE_RING)
13625 earlyreplace = 1;
13627 /* Check if we have a bridge */
13628 if (!(targetcall = ast_bridged_channel(replacecall))) {
13629 /* We have no bridge */
13630 if (!earlyreplace) {
13631 if (option_debug > 1)
13632 ast_log(LOG_DEBUG, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
13633 oneleggedreplace = 1;
13636 if (option_debug > 3 && targetcall && targetcall->_state == AST_STATE_RINGING)
13637 ast_log(LOG_DEBUG, "SIP transfer: Target channel is in ringing state\n");
13639 if (option_debug > 3) {
13640 if (targetcall)
13641 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);
13642 else
13643 ast_log(LOG_DEBUG, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
13646 if (ignore) {
13647 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
13648 /* We should answer something here. If we are here, the
13649 call we are replacing exists, so an accepted
13650 can't harm */
13651 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
13652 /* Do something more clever here */
13653 ast_channel_unlock(c);
13654 ast_mutex_unlock(&p->refer->refer_call->lock);
13655 return 1;
13657 if (!c) {
13658 /* What to do if no channel ??? */
13659 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
13660 transmit_response_reliable(p, "503 Service Unavailable", req);
13661 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
13662 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13663 ast_mutex_unlock(&p->refer->refer_call->lock);
13664 return 1;
13666 append_history(p, "Xfer", "INVITE/Replace received");
13667 /* We have three channels to play with
13668 channel c: New incoming call
13669 targetcall: Call from PBX to target
13670 p->refer->refer_call: SIP pvt dialog from transferer to pbx.
13671 replacecall: The owner of the previous
13672 We need to masq C into refer_call to connect to
13673 targetcall;
13674 If we are talking to internal audio stream, target call is null.
13677 /* Fake call progress */
13678 transmit_response(p, "100 Trying", req);
13679 ast_setstate(c, AST_STATE_RING);
13681 /* Masquerade the new call into the referred call to connect to target call
13682 Targetcall is not touched by the masq */
13684 /* Answer the incoming call and set channel to UP state */
13685 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
13687 ast_setstate(c, AST_STATE_UP);
13689 /* Stop music on hold and other generators */
13690 ast_quiet_chan(replacecall);
13691 ast_quiet_chan(targetcall);
13692 if (option_debug > 3)
13693 ast_log(LOG_DEBUG, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
13694 /* Unlock clone, but not original (replacecall) */
13695 if (!oneleggedreplace)
13696 ast_channel_unlock(c);
13698 /* Unlock PVT */
13699 ast_mutex_unlock(&p->refer->refer_call->lock);
13701 /* Make sure that the masq does not free our PVT for the old call */
13702 if (! earlyreplace && ! oneleggedreplace )
13703 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
13705 /* Prepare the masquerade - if this does not happen, we will be gone */
13706 if(ast_channel_masquerade(replacecall, c))
13707 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
13708 else if (option_debug > 3)
13709 ast_log(LOG_DEBUG, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
13711 /* The masquerade will happen as soon as someone reads a frame from the channel */
13713 /* C should now be in place of replacecall */
13714 /* ast_read needs to lock channel */
13715 ast_channel_unlock(c);
13717 if (earlyreplace || oneleggedreplace ) {
13718 /* Force the masq to happen */
13719 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
13720 ast_frfree(f);
13721 f = NULL;
13722 if (option_debug > 3)
13723 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from RING channel!\n");
13724 } else {
13725 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from RING channel \n");
13727 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13728 if (!oneleggedreplace)
13729 ast_channel_unlock(replacecall);
13730 } else { /* Bridged call, UP channel */
13731 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
13732 /* Masq ok */
13733 ast_frfree(f);
13734 f = NULL;
13735 if (option_debug > 2)
13736 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from channel! Masq done.\n");
13737 } else {
13738 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from channel. Transfer failed\n");
13740 ast_channel_unlock(replacecall);
13742 ast_mutex_unlock(&p->refer->refer_call->lock);
13744 ast_setstate(c, AST_STATE_DOWN);
13745 if (option_debug > 3) {
13746 struct ast_channel *test;
13747 ast_log(LOG_DEBUG, "After transfer:----------------------------\n");
13748 ast_log(LOG_DEBUG, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
13749 if (replacecall)
13750 ast_log(LOG_DEBUG, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
13751 if (p->owner) {
13752 ast_log(LOG_DEBUG, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
13753 test = ast_bridged_channel(p->owner);
13754 if (test)
13755 ast_log(LOG_DEBUG, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
13756 else
13757 ast_log(LOG_DEBUG, " -- No call bridged to C->owner \n");
13758 } else
13759 ast_log(LOG_DEBUG, " -- No channel yet \n");
13760 ast_log(LOG_DEBUG, "End After transfer:----------------------------\n");
13763 ast_channel_unlock(p->owner); /* Unlock new owner */
13764 if (!oneleggedreplace)
13765 ast_mutex_unlock(&p->lock); /* Unlock SIP structure */
13767 /* The call should be down with no ast_channel, so hang it up */
13768 c->tech_pvt = NULL;
13769 ast_hangup(c);
13770 return 0;
13774 /*! \brief Handle incoming INVITE request
13775 \note If the INVITE has a Replaces header, it is part of an
13776 * attended transfer. If so, we do not go through the dial
13777 * plan but tries to find the active call and masquerade
13778 * into it
13780 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)
13782 int res = 1;
13783 int gotdest;
13784 const char *p_replaces;
13785 char *replace_id = NULL;
13786 const char *required;
13787 unsigned int required_profile = 0;
13788 struct ast_channel *c = NULL; /* New channel */
13789 int reinvite = 0;
13791 /* Find out what they support */
13792 if (!p->sipoptions) {
13793 const char *supported = get_header(req, "Supported");
13794 if (!ast_strlen_zero(supported))
13795 parse_sip_options(p, supported);
13798 /* Find out what they require */
13799 required = get_header(req, "Require");
13800 if (!ast_strlen_zero(required)) {
13801 required_profile = parse_sip_options(NULL, required);
13802 if (required_profile && required_profile != SIP_OPT_REPLACES) {
13803 /* At this point we only support REPLACES */
13804 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
13805 ast_log(LOG_WARNING,"Received SIP INVITE with unsupported required extension: %s\n", required);
13806 p->invitestate = INV_COMPLETED;
13807 if (!p->lastinvite)
13808 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13809 return -1;
13813 /* Check if this is a loop */
13814 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->owner->_state != AST_STATE_UP)) {
13815 /* This is a call to ourself. Send ourselves an error code and stop
13816 processing immediately, as SIP really has no good mechanism for
13817 being able to call yourself */
13818 /* If pedantic is on, we need to check the tags. If they're different, this is
13819 in fact a forked call through a SIP proxy somewhere. */
13820 transmit_response_reliable(p, "482 Loop Detected", req);
13821 p->invitestate = INV_COMPLETED;
13822 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13823 return 0;
13826 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->pendinginvite) {
13827 /* We already have a pending invite. Sorry. You are on hold. */
13828 transmit_response_reliable(p, "491 Request Pending", req);
13829 if (option_debug)
13830 ast_log(LOG_DEBUG, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
13831 /* Don't destroy dialog here */
13832 return 0;
13835 p_replaces = get_header(req, "Replaces");
13836 if (!ast_strlen_zero(p_replaces)) {
13837 /* We have a replaces header */
13838 char *ptr;
13839 char *fromtag = NULL;
13840 char *totag = NULL;
13841 char *start, *to;
13842 int error = 0;
13844 if (p->owner) {
13845 if (option_debug > 2)
13846 ast_log(LOG_DEBUG, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
13847 transmit_response_reliable(p, "400 Bad request", req); /* The best way to not not accept the transfer */
13848 /* Do not destroy existing call */
13849 return -1;
13852 if (sipdebug && option_debug > 2)
13853 ast_log(LOG_DEBUG, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
13854 /* Create a buffer we can manipulate */
13855 replace_id = ast_strdupa(p_replaces);
13856 ast_uri_decode(replace_id);
13858 if (!p->refer && !sip_refer_allocate(p)) {
13859 transmit_response_reliable(p, "500 Server Internal Error", req);
13860 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
13861 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13862 p->invitestate = INV_COMPLETED;
13863 return -1;
13866 /* Todo: (When we find phones that support this)
13867 if the replaces header contains ";early-only"
13868 we can only replace the call in early
13869 stage, not after it's up.
13871 If it's not in early mode, 486 Busy.
13874 /* Skip leading whitespace */
13875 replace_id = ast_skip_blanks(replace_id);
13877 start = replace_id;
13878 while ( (ptr = strsep(&start, ";")) ) {
13879 ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
13880 if ( (to = strcasestr(ptr, "to-tag=") ) )
13881 totag = to + 7; /* skip the keyword */
13882 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
13883 fromtag = to + 9; /* skip the keyword */
13884 fromtag = strsep(&fromtag, "&"); /* trim what ? */
13888 if (sipdebug && option_debug > 3)
13889 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>");
13892 /* Try to find call that we are replacing
13893 If we have a Replaces header, we need to cancel that call if we succeed with this call
13895 if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
13896 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
13897 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
13898 error = 1;
13901 /* At this point, bot the pvt and the owner of the call to be replaced is locked */
13903 /* The matched call is the call from the transferer to Asterisk .
13904 We want to bridge the bridged part of the call to the
13905 incoming invite, thus taking over the refered call */
13907 if (p->refer->refer_call == p) {
13908 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
13909 p->refer->refer_call = NULL;
13910 transmit_response_reliable(p, "400 Bad request", req); /* The best way to not not accept the transfer */
13911 error = 1;
13914 if (!error && !p->refer->refer_call->owner) {
13915 /* Oops, someting wrong anyway, no owner, no call */
13916 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
13917 /* Check for better return code */
13918 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
13919 error = 1;
13922 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 ) {
13923 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
13924 transmit_response_reliable(p, "603 Declined (Replaces)", req);
13925 error = 1;
13928 if (error) { /* Give up this dialog */
13929 append_history(p, "Xfer", "INVITE/Replace Failed.");
13930 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13931 ast_mutex_unlock(&p->lock);
13932 if (p->refer->refer_call) {
13933 ast_mutex_unlock(&p->refer->refer_call->lock);
13934 ast_channel_unlock(p->refer->refer_call->owner);
13936 p->invitestate = INV_COMPLETED;
13937 return -1;
13942 /* Check if this is an INVITE that sets up a new dialog or
13943 a re-invite in an existing dialog */
13945 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
13946 int newcall = (p->initreq.headers ? TRUE : FALSE);
13948 if (sip_cancel_destroy(p))
13949 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13950 /* This also counts as a pending invite */
13951 p->pendinginvite = seqno;
13952 check_via(p, req);
13954 copy_request(&p->initreq, req); /* Save this INVITE as the transaction basis */
13955 if (!p->owner) { /* Not a re-invite */
13956 if (debug)
13957 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
13958 if (newcall)
13959 append_history(p, "Invite", "New call: %s", p->callid);
13960 parse_ok_contact(p, req);
13961 } else { /* Re-invite on existing call */
13962 ast_clear_flag(&p->flags[0], SIP_OUTGOING); /* This is now an inbound dialog */
13963 /* Handle SDP here if we already have an owner */
13964 if (find_sdp(req)) {
13965 if (process_sdp(p, req)) {
13966 transmit_response_reliable(p, "488 Not acceptable here", req);
13967 if (!p->lastinvite)
13968 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13969 return -1;
13971 } else {
13972 p->jointcapability = p->capability;
13973 if (option_debug > 2)
13974 ast_log(LOG_DEBUG, "Hm.... No sdp for the moment\n");
13975 /* Some devices signal they want to be put off hold by sending a re-invite
13976 *without* an SDP, which is supposed to mean "Go back to your state"
13977 and since they put os on remote hold, we go back to off hold */
13978 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
13979 change_hold_state(p, req, FALSE, 0);
13981 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) /* This is a response, note what it was for */
13982 append_history(p, "ReInv", "Re-invite received");
13984 } else if (debug)
13985 ast_verbose("Ignoring this INVITE request\n");
13988 if (!p->lastinvite && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner) {
13989 /* This is a new invite */
13990 /* Handle authentication if this is our first invite */
13991 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
13992 if (res == AUTH_CHALLENGE_SENT) {
13993 p->invitestate = INV_COMPLETED; /* Needs to restart in another INVITE transaction */
13994 return 0;
13996 if (res < 0) { /* Something failed in authentication */
13997 if (res == AUTH_FAKE_AUTH) {
13998 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
13999 transmit_fake_auth_response(p, req, 1);
14000 } else {
14001 ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
14002 transmit_response_reliable(p, "403 Forbidden", req);
14004 p->invitestate = INV_COMPLETED;
14005 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14006 ast_string_field_free(p, theirtag);
14007 return 0;
14010 /* We have a succesful authentication, process the SDP portion if there is one */
14011 if (find_sdp(req)) {
14012 if (process_sdp(p, req)) {
14013 /* Unacceptable codecs */
14014 transmit_response_reliable(p, "488 Not acceptable here", req);
14015 p->invitestate = INV_COMPLETED;
14016 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14017 if (option_debug)
14018 ast_log(LOG_DEBUG, "No compatible codecs for this SIP call.\n");
14019 return -1;
14021 } else { /* No SDP in invite, call control session */
14022 p->jointcapability = p->capability;
14023 if (option_debug > 1)
14024 ast_log(LOG_DEBUG, "No SDP in Invite, third party call control\n");
14027 /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
14028 /* This seems redundant ... see !p-owner above */
14029 if (p->owner)
14030 ast_queue_frame(p->owner, &ast_null_frame);
14033 /* Initialize the context if it hasn't been already */
14034 if (ast_strlen_zero(p->context))
14035 ast_string_field_set(p, context, default_context);
14038 /* Check number of concurrent calls -vs- incoming limit HERE */
14039 if (option_debug)
14040 ast_log(LOG_DEBUG, "Checking SIP call limits for device %s\n", p->username);
14041 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
14042 if (res < 0) {
14043 ast_log(LOG_NOTICE, "Failed to place call for user %s, too many calls\n", p->username);
14044 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
14045 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14046 p->invitestate = INV_COMPLETED;
14048 return 0;
14050 gotdest = get_destination(p, NULL); /* Get destination right away */
14051 get_rdnis(p, NULL); /* Get redirect information */
14052 extract_uri(p, req); /* Get the Contact URI */
14053 build_contact(p); /* Build our contact header */
14055 if (p->rtp) {
14056 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
14057 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
14060 if (!replace_id && gotdest) { /* No matching extension found */
14061 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
14062 transmit_response_reliable(p, "484 Address Incomplete", req);
14063 else {
14064 char *decoded_exten = ast_strdupa(p->exten);
14066 transmit_response_reliable(p, "404 Not Found", req);
14067 ast_uri_decode(decoded_exten);
14068 ast_log(LOG_NOTICE, "Call from '%s' to extension"
14069 " '%s' rejected because extension not found.\n",
14070 S_OR(p->username, p->peername), decoded_exten);
14072 p->invitestate = INV_COMPLETED;
14073 update_call_counter(p, DEC_CALL_LIMIT);
14074 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14075 return 0;
14076 } else {
14077 /* If no extension was specified, use the s one */
14078 /* Basically for calling to IP/Host name only */
14079 if (ast_strlen_zero(p->exten))
14080 ast_string_field_set(p, exten, "s");
14081 /* Initialize our tag */
14083 make_our_tag(p->tag, sizeof(p->tag));
14084 /* First invitation - create the channel */
14085 c = sip_new(p, AST_STATE_DOWN, S_OR(p->username, NULL));
14086 *recount = 1;
14088 /* Save Record-Route for any later requests we make on this dialogue */
14089 build_route(p, req, 0);
14091 if (c) {
14092 /* Pre-lock the call */
14093 ast_channel_lock(c);
14096 } else {
14097 if (option_debug > 1 && sipdebug) {
14098 if (!ast_test_flag(req, SIP_PKT_IGNORE))
14099 ast_log(LOG_DEBUG, "Got a SIP re-invite for call %s\n", p->callid);
14100 else
14101 ast_log(LOG_DEBUG, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
14103 reinvite = 1;
14104 c = p->owner;
14107 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
14108 p->lastinvite = seqno;
14110 if (replace_id) { /* Attended transfer or call pickup - we're the target */
14111 /* Go and take over the target call */
14112 if (sipdebug && option_debug > 3)
14113 ast_log(LOG_DEBUG, "Sending this call to the invite/replcaes handler %s\n", p->callid);
14114 return handle_invite_replaces(p, req, debug, ast_test_flag(req, SIP_PKT_IGNORE), seqno, sin);
14118 if (c) { /* We have a call -either a new call or an old one (RE-INVITE) */
14119 switch(c->_state) {
14120 case AST_STATE_DOWN:
14121 if (option_debug > 1)
14122 ast_log(LOG_DEBUG, "%s: New call is still down.... Trying... \n", c->name);
14123 transmit_response(p, "100 Trying", req);
14124 p->invitestate = INV_PROCEEDING;
14125 ast_setstate(c, AST_STATE_RING);
14126 if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
14127 enum ast_pbx_result res;
14129 res = ast_pbx_start(c);
14131 switch(res) {
14132 case AST_PBX_FAILED:
14133 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
14134 p->invitestate = INV_COMPLETED;
14135 if (ast_test_flag(req, SIP_PKT_IGNORE))
14136 transmit_response(p, "503 Unavailable", req);
14137 else
14138 transmit_response_reliable(p, "503 Unavailable", req);
14139 break;
14140 case AST_PBX_CALL_LIMIT:
14141 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
14142 p->invitestate = INV_COMPLETED;
14143 if (ast_test_flag(req, SIP_PKT_IGNORE))
14144 transmit_response(p, "480 Temporarily Unavailable", req);
14145 else
14146 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
14147 break;
14148 case AST_PBX_SUCCESS:
14149 /* nothing to do */
14150 break;
14153 if (res) {
14155 /* Unlock locks so ast_hangup can do its magic */
14156 ast_mutex_unlock(&c->lock);
14157 ast_mutex_unlock(&p->lock);
14158 ast_hangup(c);
14159 ast_mutex_lock(&p->lock);
14160 c = NULL;
14162 } else { /* Pickup call in call group */
14163 ast_channel_unlock(c);
14164 *nounlock = 1;
14165 if (ast_pickup_call(c)) {
14166 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
14167 if (ast_test_flag(req, SIP_PKT_IGNORE))
14168 transmit_response(p, "503 Unavailable", req); /* OEJ - Right answer? */
14169 else
14170 transmit_response_reliable(p, "503 Unavailable", req);
14171 sip_alreadygone(p);
14172 /* Unlock locks so ast_hangup can do its magic */
14173 ast_mutex_unlock(&p->lock);
14174 c->hangupcause = AST_CAUSE_CALL_REJECTED;
14175 } else {
14176 ast_mutex_unlock(&p->lock);
14177 ast_setstate(c, AST_STATE_DOWN);
14178 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
14180 p->invitestate = INV_COMPLETED;
14181 ast_hangup(c);
14182 ast_mutex_lock(&p->lock);
14183 c = NULL;
14185 break;
14186 case AST_STATE_RING:
14187 transmit_response(p, "100 Trying", req);
14188 p->invitestate = INV_PROCEEDING;
14189 break;
14190 case AST_STATE_RINGING:
14191 transmit_response(p, "180 Ringing", req);
14192 p->invitestate = INV_PROCEEDING;
14193 break;
14194 case AST_STATE_UP:
14195 if (option_debug > 1)
14196 ast_log(LOG_DEBUG, "%s: This call is UP.... \n", c->name);
14198 transmit_response(p, "100 Trying", req);
14200 if (p->t38.state == T38_PEER_REINVITE) {
14201 struct ast_channel *bridgepeer = NULL;
14202 struct sip_pvt *bridgepvt = NULL;
14204 if ((bridgepeer = ast_bridged_channel(p->owner))) {
14205 /* 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*/
14206 /*! XXX: we should also check here does the other side supports t38 at all !!! XXX */
14207 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
14208 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
14209 if (bridgepvt->t38.state == T38_DISABLED) {
14210 if (bridgepvt->udptl) { /* If everything is OK with other side's udptl struct */
14211 /* Send re-invite to the bridged channel */
14212 sip_handle_t38_reinvite(bridgepeer, p, 1);
14213 } else { /* Something is wrong with peers udptl struct */
14214 ast_log(LOG_WARNING, "Strange... The other side of the bridge don't have udptl struct\n");
14215 ast_mutex_lock(&bridgepvt->lock);
14216 bridgepvt->t38.state = T38_DISABLED;
14217 ast_mutex_unlock(&bridgepvt->lock);
14218 if (option_debug > 1)
14219 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->name);
14220 if (ast_test_flag(req, SIP_PKT_IGNORE))
14221 transmit_response(p, "488 Not acceptable here", req);
14222 else
14223 transmit_response_reliable(p, "488 Not acceptable here", req);
14226 } else {
14227 /* The other side is already setup for T.38 most likely so we need to acknowledge this too */
14228 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
14229 p->t38.state = T38_ENABLED;
14230 if (option_debug)
14231 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14233 } else {
14234 /* Other side is not a SIP channel */
14235 if (ast_test_flag(req, SIP_PKT_IGNORE))
14236 transmit_response(p, "488 Not acceptable here", req);
14237 else
14238 transmit_response_reliable(p, "488 Not acceptable here", req);
14239 p->t38.state = T38_DISABLED;
14240 if (option_debug > 1)
14241 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14243 if (!p->lastinvite) /* Only destroy if this is *not* a re-invite */
14244 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14246 } else {
14247 /* we are not bridged in a call */
14248 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
14249 p->t38.state = T38_ENABLED;
14250 if (option_debug)
14251 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14253 } else if (p->t38.state == T38_DISABLED) { /* Channel doesn't have T38 offered or enabled */
14254 int sendok = TRUE;
14256 /* If we are bridged to a channel that has T38 enabled than this is a case of RTP re-invite after T38 session */
14257 /* so handle it here (re-invite other party to RTP) */
14258 struct ast_channel *bridgepeer = NULL;
14259 struct sip_pvt *bridgepvt = NULL;
14260 if ((bridgepeer = ast_bridged_channel(p->owner))) {
14261 if ((bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) && !ast_check_hangup(bridgepeer)) {
14262 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
14263 /* Does the bridged peer have T38 ? */
14264 if (bridgepvt->t38.state == T38_ENABLED) {
14265 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
14266 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
14267 if (ast_test_flag(req, SIP_PKT_IGNORE))
14268 transmit_response(p, "488 Not Acceptable Here (unsupported)", req);
14269 else
14270 transmit_response_reliable(p, "488 Not Acceptable Here (unsupported)", req);
14271 sendok = FALSE;
14273 /* No bridged peer with T38 enabled*/
14276 /* Respond to normal re-invite */
14277 if (sendok)
14278 /* If this is not a re-invite or something to ignore - it's critical */
14279 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (ast_test_flag(req, SIP_PKT_IGNORE) ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
14281 p->invitestate = INV_TERMINATED;
14282 break;
14283 default:
14284 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
14285 transmit_response(p, "100 Trying", req);
14286 break;
14288 } else {
14289 if (p && (p->autokillid == -1)) {
14290 const char *msg;
14292 if (!p->jointcapability)
14293 msg = "488 Not Acceptable Here (codec error)";
14294 else {
14295 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
14296 msg = "503 Unavailable";
14298 if (ast_test_flag(req, SIP_PKT_IGNORE))
14299 transmit_response(p, msg, req);
14300 else
14301 transmit_response_reliable(p, msg, req);
14302 p->invitestate = INV_COMPLETED;
14303 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14306 return res;
14309 /*! \brief Find all call legs and bridge transferee with target
14310 * called from handle_request_refer */
14311 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
14313 struct sip_dual target; /* Chan 1: Call from tranferer to Asterisk */
14314 /* Chan 2: Call from Asterisk to target */
14315 int res = 0;
14316 struct sip_pvt *targetcall_pvt;
14318 /* Check if the call ID of the replaces header does exist locally */
14319 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
14320 transferer->refer->replaces_callid_fromtag))) {
14321 if (transferer->refer->localtransfer) {
14322 /* We did not find the refered call. Sorry, can't accept then */
14323 transmit_response(transferer, "202 Accepted", req);
14324 /* Let's fake a response from someone else in order
14325 to follow the standard */
14326 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
14327 append_history(transferer, "Xfer", "Refer failed");
14328 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
14329 transferer->refer->status = REFER_FAILED;
14330 return -1;
14332 /* Fall through for remote transfers that we did not find locally */
14333 if (option_debug > 2)
14334 ast_log(LOG_DEBUG, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
14335 return 0;
14338 /* Ok, we can accept this transfer */
14339 transmit_response(transferer, "202 Accepted", req);
14340 append_history(transferer, "Xfer", "Refer accepted");
14341 if (!targetcall_pvt->owner) { /* No active channel */
14342 if (option_debug > 3)
14343 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No owner of target call\n");
14344 /* Cancel transfer */
14345 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
14346 append_history(transferer, "Xfer", "Refer failed");
14347 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
14348 transferer->refer->status = REFER_FAILED;
14349 ast_mutex_unlock(&targetcall_pvt->lock);
14350 ast_channel_unlock(current->chan1);
14351 return -1;
14354 /* We have a channel, find the bridge */
14355 target.chan1 = targetcall_pvt->owner; /* Transferer to Asterisk */
14356 target.chan2 = ast_bridged_channel(targetcall_pvt->owner); /* Asterisk to target */
14358 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
14359 /* Wrong state of new channel */
14360 if (option_debug > 3) {
14361 if (target.chan2)
14362 ast_log(LOG_DEBUG, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
14363 else if (target.chan1->_state != AST_STATE_RING)
14364 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No target channel\n");
14365 else
14366 ast_log(LOG_DEBUG, "SIP attended transfer: Attempting transfer in ringing state\n");
14370 /* Transfer */
14371 if (option_debug > 3 && sipdebug) {
14372 if (current->chan2) /* We have two bridges */
14373 ast_log(LOG_DEBUG, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
14374 else /* One bridge, propably transfer of IVR/voicemail etc */
14375 ast_log(LOG_DEBUG, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
14378 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
14380 /* Perform the transfer */
14381 res = attempt_transfer(current, &target);
14382 ast_mutex_unlock(&targetcall_pvt->lock);
14383 if (res) {
14384 /* Failed transfer */
14385 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
14386 append_history(transferer, "Xfer", "Refer failed");
14387 transferer->refer->status = REFER_FAILED;
14388 if (targetcall_pvt->owner)
14389 ast_channel_unlock(targetcall_pvt->owner);
14390 /* Right now, we have to hangup, sorry. Bridge is destroyed */
14391 if (res != -2)
14392 ast_hangup(transferer->owner);
14393 else
14394 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
14395 } else {
14396 /* Transfer succeeded! */
14398 /* Tell transferer that we're done. */
14399 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
14400 append_history(transferer, "Xfer", "Refer succeeded");
14401 transferer->refer->status = REFER_200OK;
14402 if (targetcall_pvt->owner) {
14403 if (option_debug)
14404 ast_log(LOG_DEBUG, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
14405 ast_channel_unlock(targetcall_pvt->owner);
14408 return 1;
14412 /*! \brief Handle incoming REFER request */
14413 /*! \page SIP_REFER SIP transfer Support (REFER)
14415 REFER is used for call transfer in SIP. We get a REFER
14416 to place a new call with an INVITE somwhere and then
14417 keep the transferor up-to-date of the transfer. If the
14418 transfer fails, get back on line with the orginal call.
14420 - REFER can be sent outside or inside of a dialog.
14421 Asterisk only accepts REFER inside of a dialog.
14423 - If we get a replaces header, it is an attended transfer
14425 \par Blind transfers
14426 The transferor provides the transferee
14427 with the transfer targets contact. The signalling between
14428 transferer or transferee should not be cancelled, so the
14429 call is recoverable if the transfer target can not be reached
14430 by the transferee.
14432 In this case, Asterisk receives a TRANSFER from
14433 the transferor, thus is the transferee. We should
14434 try to set up a call to the contact provided
14435 and if that fails, re-connect the current session.
14436 If the new call is set up, we issue a hangup.
14437 In this scenario, we are following section 5.2
14438 in the SIP CC Transfer draft. (Transfer without
14439 a GRUU)
14441 \par Transfer with consultation hold
14442 In this case, the transferor
14443 talks to the transfer target before the transfer takes place.
14444 This is implemented with SIP hold and transfer.
14445 Note: The invite From: string could indicate a transfer.
14446 (Section 6. Transfer with consultation hold)
14447 The transferor places the transferee on hold, starts a call
14448 with the transfer target to alert them to the impending
14449 transfer, terminates the connection with the target, then
14450 proceeds with the transfer (as in Blind transfer above)
14452 \par Attended transfer
14453 The transferor places the transferee
14454 on hold, calls the transfer target to alert them,
14455 places the target on hold, then proceeds with the transfer
14456 using a Replaces header field in the Refer-to header. This
14457 will force the transfee to send an Invite to the target,
14458 with a replaces header that instructs the target to
14459 hangup the call between the transferor and the target.
14460 In this case, the Refer/to: uses the AOR address. (The same
14461 URI that the transferee used to establish the session with
14462 the transfer target (To: ). The Require: replaces header should
14463 be in the INVITE to avoid the wrong UA in a forked SIP proxy
14464 scenario to answer and have no call to replace with.
14466 The referred-by header is *NOT* required, but if we get it,
14467 can be copied into the INVITE to the transfer target to
14468 inform the target about the transferor
14470 "Any REFER request has to be appropriately authenticated.".
14472 We can't destroy dialogs, since we want the call to continue.
14475 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock)
14477 struct sip_dual current; /* Chan1: Call between asterisk and transferer */
14478 /* Chan2: Call between asterisk and transferee */
14480 int res = 0;
14482 if (ast_test_flag(req, SIP_PKT_DEBUG))
14483 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");
14485 if (!p->owner) {
14486 /* This is a REFER outside of an existing SIP dialog */
14487 /* We can't handle that, so decline it */
14488 if (option_debug > 2)
14489 ast_log(LOG_DEBUG, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
14490 transmit_response(p, "603 Declined (No dialog)", req);
14491 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
14492 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
14493 sip_alreadygone(p);
14494 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14496 return 0;
14500 /* Check if transfer is allowed from this device */
14501 if (p->allowtransfer == TRANSFER_CLOSED ) {
14502 /* Transfer not allowed, decline */
14503 transmit_response(p, "603 Declined (policy)", req);
14504 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
14505 /* Do not destroy SIP session */
14506 return 0;
14509 if(!ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
14510 /* Already have a pending REFER */
14511 transmit_response(p, "491 Request pending", req);
14512 append_history(p, "Xfer", "Refer failed. Request pending.");
14513 return 0;
14516 /* Allocate memory for call transfer data */
14517 if (!p->refer && !sip_refer_allocate(p)) {
14518 transmit_response(p, "500 Internal Server Error", req);
14519 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
14520 return -3;
14523 res = get_refer_info(p, req); /* Extract headers */
14525 p->refer->status = REFER_SENT;
14527 if (res != 0) {
14528 switch (res) {
14529 case -2: /* Syntax error */
14530 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
14531 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
14532 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14533 ast_log(LOG_DEBUG, "SIP transfer to black hole can't be handled (no refer-to: )\n");
14534 break;
14535 case -3:
14536 transmit_response(p, "603 Declined (Non sip: uri)", req);
14537 append_history(p, "Xfer", "Refer failed. Non SIP uri");
14538 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14539 ast_log(LOG_DEBUG, "SIP transfer to non-SIP uri denied\n");
14540 break;
14541 default:
14542 /* Refer-to extension not found, fake a failed transfer */
14543 transmit_response(p, "202 Accepted", req);
14544 append_history(p, "Xfer", "Refer failed. Bad extension.");
14545 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
14546 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14547 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14548 ast_log(LOG_DEBUG, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
14549 break;
14551 return 0;
14553 if (ast_strlen_zero(p->context))
14554 ast_string_field_set(p, context, default_context);
14556 /* If we do not support SIP domains, all transfers are local */
14557 if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
14558 p->refer->localtransfer = 1;
14559 if (sipdebug && option_debug > 2)
14560 ast_log(LOG_DEBUG, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
14561 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
14562 /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
14563 p->refer->localtransfer = 1;
14564 } else if (sipdebug && option_debug > 2)
14565 ast_log(LOG_DEBUG, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
14567 /* Is this a repeat of a current request? Ignore it */
14568 /* Don't know what else to do right now. */
14569 if (ignore)
14570 return res;
14572 /* If this is a blind transfer, we have the following
14573 channels to work with:
14574 - chan1, chan2: The current call between transferer and transferee (2 channels)
14575 - target_channel: A new call from the transferee to the target (1 channel)
14576 We need to stay tuned to what happens in order to be able
14577 to bring back the call to the transferer */
14579 /* If this is a attended transfer, we should have all call legs within reach:
14580 - chan1, chan2: The call between the transferer and transferee (2 channels)
14581 - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
14582 We want to bridge chan2 with targetcall_pvt!
14584 The replaces call id in the refer message points
14585 to the call leg between Asterisk and the transferer.
14586 So we need to connect the target and the transferee channel
14587 and hangup the two other channels silently
14589 If the target is non-local, the call ID could be on a remote
14590 machine and we need to send an INVITE with replaces to the
14591 target. We basically handle this as a blind transfer
14592 and let the sip_call function catch that we need replaces
14593 header in the INVITE.
14597 /* Get the transferer's channel */
14598 current.chan1 = p->owner;
14600 /* Find the other part of the bridge (2) - transferee */
14601 current.chan2 = ast_bridged_channel(current.chan1);
14603 if (sipdebug && option_debug > 2)
14604 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>");
14606 if (!current.chan2 && !p->refer->attendedtransfer) {
14607 /* No bridged channel, propably IVR or echo or similar... */
14608 /* Guess we should masquerade or something here */
14609 /* Until we figure it out, refuse transfer of such calls */
14610 if (sipdebug && option_debug > 2)
14611 ast_log(LOG_DEBUG,"Refused SIP transfer on non-bridged channel.\n");
14612 p->refer->status = REFER_FAILED;
14613 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
14614 transmit_response(p, "603 Declined", req);
14615 return -1;
14618 if (current.chan2) {
14619 if (sipdebug && option_debug > 3)
14620 ast_log(LOG_DEBUG, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
14622 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
14625 ast_set_flag(&p->flags[0], SIP_GOTREFER);
14627 /* Attended transfer: Find all call legs and bridge transferee with target*/
14628 if (p->refer->attendedtransfer) {
14629 if ((res = local_attended_transfer(p, &current, req, seqno)))
14630 return res; /* We're done with the transfer */
14631 /* Fall through for remote transfers that we did not find locally */
14632 if (sipdebug && option_debug > 3)
14633 ast_log(LOG_DEBUG, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
14634 /* Fallthrough if we can't find the call leg internally */
14638 /* Parking a call */
14639 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
14640 /* Must release c's lock now, because it will not longer be accessible after the transfer! */
14641 *nounlock = 1;
14642 ast_channel_unlock(current.chan1);
14643 copy_request(&current.req, req);
14644 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14645 p->refer->status = REFER_200OK;
14646 append_history(p, "Xfer", "REFER to call parking.");
14647 if (sipdebug && option_debug > 3)
14648 ast_log(LOG_DEBUG, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
14649 sip_park(current.chan2, current.chan1, req, seqno);
14650 return res;
14653 /* Blind transfers and remote attended xfers */
14654 transmit_response(p, "202 Accepted", req);
14656 if (current.chan1 && current.chan2) {
14657 if (option_debug > 2)
14658 ast_log(LOG_DEBUG, "chan1->name: %s\n", current.chan1->name);
14659 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
14661 if (current.chan2) {
14662 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
14663 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
14664 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
14665 /* One for the new channel */
14666 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
14667 /* Attended transfer to remote host, prepare headers for the INVITE */
14668 if (p->refer->referred_by)
14669 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
14671 /* Generate a Replaces string to be used in the INVITE during attended transfer */
14672 if (p->refer->replaces_callid && !ast_strlen_zero(p->refer->replaces_callid)) {
14673 char tempheader[SIPBUFSIZE];
14674 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
14675 p->refer->replaces_callid_totag ? ";to-tag=" : "",
14676 p->refer->replaces_callid_totag,
14677 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
14678 p->refer->replaces_callid_fromtag);
14679 if (current.chan2)
14680 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
14682 /* Must release lock now, because it will not longer
14683 be accessible after the transfer! */
14684 *nounlock = 1;
14685 ast_channel_unlock(current.chan1);
14687 /* Connect the call */
14689 /* FAKE ringing if not attended transfer */
14690 if (!p->refer->attendedtransfer)
14691 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
14693 /* For blind transfer, this will lead to a new call */
14694 /* For attended transfer to remote host, this will lead to
14695 a new SIP call with a replaces header, if the dial plan allows it
14697 if (!current.chan2) {
14698 /* We have no bridge, so we're talking with Asterisk somehow */
14699 /* We need to masquerade this call */
14700 /* What to do to fix this situation:
14701 * Set up the new call in a new channel
14702 * Let the new channel masq into this channel
14703 Please add that code here :-)
14705 p->refer->status = REFER_FAILED;
14706 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
14707 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14708 append_history(p, "Xfer", "Refer failed (only bridged calls).");
14709 return -1;
14711 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
14713 /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
14714 servers - generate an INVITE with Replaces. Either way, let the dial plan decided */
14715 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
14717 if (!res) {
14718 /* Success - we have a new channel */
14719 if (option_debug > 2)
14720 ast_log(LOG_DEBUG, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
14721 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
14722 if (p->refer->localtransfer)
14723 p->refer->status = REFER_200OK;
14724 if (p->owner)
14725 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
14726 append_history(p, "Xfer", "Refer succeeded.");
14727 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14728 /* Do not hangup call, the other side do that when we say 200 OK */
14729 /* We could possibly implement a timer here, auto congestion */
14730 res = 0;
14731 } else {
14732 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
14733 if (option_debug > 2)
14734 ast_log(LOG_DEBUG, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
14735 append_history(p, "Xfer", "Refer failed.");
14736 /* Failure of some kind */
14737 p->refer->status = REFER_FAILED;
14738 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
14739 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14740 res = -1;
14742 return res;
14745 /*! \brief Handle incoming CANCEL request */
14746 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
14749 check_via(p, req);
14750 sip_alreadygone(p);
14752 /* At this point, we could have cancelled the invite at the same time
14753 as the other side sends a CANCEL. Our final reply with error code
14754 might not have been received by the other side before the CANCEL
14755 was sent, so let's just give up retransmissions and waiting for
14756 ACK on our error code. The call is hanging up any way. */
14757 if (p->invitestate == INV_TERMINATED)
14758 __sip_pretend_ack(p);
14759 else
14760 p->invitestate = INV_CANCELLED;
14762 if (p->owner && p->owner->_state == AST_STATE_UP) {
14763 /* This call is up, cancel is ignored, we need a bye */
14764 transmit_response(p, "200 OK", req);
14765 if (option_debug)
14766 ast_log(LOG_DEBUG, "Got CANCEL on an answered call. Ignoring... \n");
14767 return 0;
14770 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
14771 update_call_counter(p, DEC_CALL_LIMIT);
14773 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
14774 if (p->owner)
14775 ast_queue_hangup(p->owner);
14776 else
14777 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14778 if (p->initreq.len > 0) {
14779 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
14780 transmit_response(p, "200 OK", req);
14781 return 1;
14782 } else {
14783 transmit_response(p, "481 Call Leg Does Not Exist", req);
14784 return 0;
14788 static int acf_channel_read(struct ast_channel *chan, char *funcname, char *preparse, char *buf, size_t buflen)
14790 struct ast_rtp_quality qos;
14791 struct sip_pvt *p = chan->tech_pvt;
14792 char *all = "", *parse = ast_strdupa(preparse);
14793 AST_DECLARE_APP_ARGS(args,
14794 AST_APP_ARG(param);
14795 AST_APP_ARG(type);
14796 AST_APP_ARG(field);
14798 AST_STANDARD_APP_ARGS(args, parse);
14800 /* Sanity check */
14801 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
14802 ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
14803 return 0;
14806 if (strcasecmp(args.param, "rtpqos"))
14807 return 0;
14809 /* Default arguments of audio,all */
14810 if (ast_strlen_zero(args.type))
14811 args.type = "audio";
14812 if (ast_strlen_zero(args.field))
14813 args.field = "all";
14815 memset(buf, 0, buflen);
14816 memset(&qos, 0, sizeof(qos));
14818 if (strcasecmp(args.type, "AUDIO") == 0) {
14819 all = ast_rtp_get_quality(p->rtp, &qos);
14820 } else if (strcasecmp(args.type, "VIDEO") == 0) {
14821 all = ast_rtp_get_quality(p->vrtp, &qos);
14824 if (strcasecmp(args.field, "local_ssrc") == 0)
14825 snprintf(buf, buflen, "%u", qos.local_ssrc);
14826 else if (strcasecmp(args.field, "local_lostpackets") == 0)
14827 snprintf(buf, buflen, "%u", qos.local_lostpackets);
14828 else if (strcasecmp(args.field, "local_jitter") == 0)
14829 snprintf(buf, buflen, "%.0lf", qos.local_jitter * 1000.0);
14830 else if (strcasecmp(args.field, "local_count") == 0)
14831 snprintf(buf, buflen, "%u", qos.local_count);
14832 else if (strcasecmp(args.field, "remote_ssrc") == 0)
14833 snprintf(buf, buflen, "%u", qos.remote_ssrc);
14834 else if (strcasecmp(args.field, "remote_lostpackets") == 0)
14835 snprintf(buf, buflen, "%u", qos.remote_lostpackets);
14836 else if (strcasecmp(args.field, "remote_jitter") == 0)
14837 snprintf(buf, buflen, "%.0lf", qos.remote_jitter * 1000.0);
14838 else if (strcasecmp(args.field, "remote_count") == 0)
14839 snprintf(buf, buflen, "%u", qos.remote_count);
14840 else if (strcasecmp(args.field, "rtt") == 0)
14841 snprintf(buf, buflen, "%.0lf", qos.rtt * 1000.0);
14842 else if (strcasecmp(args.field, "all") == 0)
14843 ast_copy_string(buf, all, buflen);
14844 else {
14845 ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
14846 return -1;
14848 return 0;
14851 /*! \brief Handle incoming BYE request */
14852 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
14854 struct ast_channel *c=NULL;
14855 int res;
14856 struct ast_channel *bridged_to;
14858 /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
14859 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner)
14860 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
14862 p->invitestate = INV_TERMINATED;
14864 copy_request(&p->initreq, req);
14865 check_via(p, req);
14866 sip_alreadygone(p);
14868 /* Get RTCP quality before end of call */
14869 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY) || p->owner) {
14870 char *audioqos, *videoqos;
14871 if (p->rtp) {
14872 audioqos = ast_rtp_get_quality(p->rtp, NULL);
14873 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
14874 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
14875 if (p->owner)
14876 pbx_builtin_setvar_helper(p->owner, "RTPAUDIOQOS", audioqos);
14878 if (p->vrtp) {
14879 videoqos = ast_rtp_get_quality(p->vrtp, NULL);
14880 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
14881 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
14882 if (p->owner)
14883 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
14887 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
14889 if (!ast_strlen_zero(get_header(req, "Also"))) {
14890 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
14891 ast_inet_ntoa(p->recv.sin_addr));
14892 if (ast_strlen_zero(p->context))
14893 ast_string_field_set(p, context, default_context);
14894 res = get_also_info(p, req);
14895 if (!res) {
14896 c = p->owner;
14897 if (c) {
14898 bridged_to = ast_bridged_channel(c);
14899 if (bridged_to) {
14900 /* Don't actually hangup here... */
14901 ast_queue_control(c, AST_CONTROL_UNHOLD);
14902 ast_async_goto(bridged_to, p->context, p->refer->refer_to,1);
14903 } else
14904 ast_queue_hangup(p->owner);
14906 } else {
14907 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
14908 if (p->owner)
14909 ast_queue_hangup(p->owner);
14911 } else if (p->owner) {
14912 ast_queue_hangup(p->owner);
14913 if (option_debug > 2)
14914 ast_log(LOG_DEBUG, "Received bye, issuing owner hangup\n");
14915 } else {
14916 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14917 if (option_debug > 2)
14918 ast_log(LOG_DEBUG, "Received bye, no owner, selfdestruct soon.\n");
14920 transmit_response(p, "200 OK", req);
14922 return 1;
14925 /*! \brief Handle incoming MESSAGE request */
14926 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
14928 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
14929 if (ast_test_flag(req, SIP_PKT_DEBUG))
14930 ast_verbose("Receiving message!\n");
14931 receive_message(p, req);
14932 } else
14933 transmit_response(p, "202 Accepted", req);
14934 return 1;
14937 /*! \brief Handle incoming SUBSCRIBE request */
14938 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
14940 int gotdest;
14941 int res = 0;
14942 int firststate = AST_EXTENSION_REMOVED;
14943 struct sip_peer *authpeer = NULL;
14944 const char *eventheader = get_header(req, "Event"); /* Get Event package name */
14945 const char *accept = get_header(req, "Accept");
14946 int resubscribe = (p->subscribed != NONE);
14947 char *temp, *event;
14949 if (p->initreq.headers) {
14950 /* We already have a dialog */
14951 if (p->initreq.method != SIP_SUBSCRIBE) {
14952 /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
14953 /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
14954 transmit_response(p, "403 Forbidden (within dialog)", req);
14955 /* Do not destroy session, since we will break the call if we do */
14956 if (option_debug)
14957 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);
14958 return 0;
14959 } else if (ast_test_flag(req, SIP_PKT_DEBUG)) {
14960 if (option_debug) {
14961 if (resubscribe)
14962 ast_log(LOG_DEBUG, "Got a re-subscribe on existing subscription %s\n", p->callid);
14963 else
14964 ast_log(LOG_DEBUG, "Got a new subscription %s (possibly with auth)\n", p->callid);
14969 /* Check if we have a global disallow setting on subscriptions.
14970 if so, we don't have to check peer/user settings after auth, which saves a lot of processing
14972 if (!global_allowsubscribe) {
14973 transmit_response(p, "403 Forbidden (policy)", req);
14974 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14975 return 0;
14978 if (!ast_test_flag(req, SIP_PKT_IGNORE) && !resubscribe) { /* Set up dialog, new subscription */
14979 const char *to = get_header(req, "To");
14980 char totag[128];
14982 /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
14983 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
14984 if (ast_test_flag(req, SIP_PKT_DEBUG))
14985 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
14986 transmit_response(p, "481 Subscription does not exist", req);
14987 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14988 return 0;
14991 /* Use this as the basis */
14992 if (ast_test_flag(req, SIP_PKT_DEBUG))
14993 ast_verbose("Creating new subscription\n");
14995 copy_request(&p->initreq, req);
14996 check_via(p, req);
14997 } else if (ast_test_flag(req, SIP_PKT_DEBUG) && ast_test_flag(req, SIP_PKT_IGNORE))
14998 ast_verbose("Ignoring this SUBSCRIBE request\n");
15000 /* Find parameters to Event: header value and remove them for now */
15001 if (ast_strlen_zero(eventheader)) {
15002 transmit_response(p, "489 Bad Event", req);
15003 if (option_debug > 1)
15004 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: <none>\n");
15005 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15006 return 0;
15009 if ( (strchr(eventheader, ';'))) {
15010 event = ast_strdupa(eventheader); /* Since eventheader is a const, we can't change it */
15011 temp = strchr(event, ';');
15012 *temp = '\0'; /* Remove any options for now */
15013 /* We might need to use them later :-) */
15014 } else
15015 event = (char *) eventheader; /* XXX is this legal ? */
15017 /* Handle authentication */
15018 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
15019 /* if an authentication response was sent, we are done here */
15020 if (res == AUTH_CHALLENGE_SENT) {
15021 if (authpeer)
15022 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15023 return 0;
15025 if (res < 0) {
15026 if (res == AUTH_FAKE_AUTH) {
15027 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
15028 transmit_fake_auth_response(p, req, 1);
15029 } else {
15030 ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
15031 transmit_response_reliable(p, "403 Forbidden", req);
15033 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15034 if (authpeer)
15035 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15036 return 0;
15039 /* Check if this user/peer is allowed to subscribe at all */
15040 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
15041 transmit_response(p, "403 Forbidden (policy)", req);
15042 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15043 if (authpeer)
15044 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15045 return 0;
15048 /* Get destination right away */
15049 gotdest = get_destination(p, NULL);
15051 /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
15052 parse_ok_contact(p, req);
15054 build_contact(p);
15055 if (strcmp(event, "message-summary") && gotdest) {
15056 transmit_response(p, "404 Not Found", req);
15057 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15058 if (authpeer)
15059 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15060 return 0;
15063 /* Initialize tag for new subscriptions */
15064 if (ast_strlen_zero(p->tag))
15065 make_our_tag(p->tag, sizeof(p->tag));
15067 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
15068 if (authpeer) /* No need for authpeer here */
15069 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15071 /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
15072 /* Polycom phones only handle xpidf+xml, even if they say they can
15073 handle pidf+xml as well
15075 if (strstr(p->useragent, "Polycom")) {
15076 p->subscribed = XPIDF_XML;
15077 } else if (strstr(accept, "application/pidf+xml")) {
15078 p->subscribed = PIDF_XML; /* RFC 3863 format */
15079 } else if (strstr(accept, "application/dialog-info+xml")) {
15080 p->subscribed = DIALOG_INFO_XML;
15081 /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
15082 } else if (strstr(accept, "application/cpim-pidf+xml")) {
15083 p->subscribed = CPIM_PIDF_XML; /* RFC 3863 format */
15084 } else if (strstr(accept, "application/xpidf+xml")) {
15085 p->subscribed = XPIDF_XML; /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
15086 } else if (ast_strlen_zero(accept)) {
15087 if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
15088 transmit_response(p, "489 Bad Event", req);
15090 ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
15091 p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
15092 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15093 return 0;
15095 /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
15096 so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
15097 } else {
15098 /* Can't find a format for events that we know about */
15099 char mybuf[200];
15100 snprintf(mybuf,sizeof(mybuf),"489 Bad Event (format %s)", accept);
15101 transmit_response(p, mybuf, req);
15103 ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
15104 accept, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
15105 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15106 return 0;
15108 } else if (!strcmp(event, "message-summary")) {
15109 if (!ast_strlen_zero(accept) && strcmp(accept, "application/simple-message-summary")) {
15110 /* Format requested that we do not support */
15111 transmit_response(p, "406 Not Acceptable", req);
15112 if (option_debug > 1)
15113 ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", accept);
15114 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15115 if (authpeer) /* No need for authpeer here */
15116 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15117 return 0;
15119 /* Looks like they actually want a mailbox status
15120 This version of Asterisk supports mailbox subscriptions
15121 The subscribed URI needs to exist in the dial plan
15122 In most devices, this is configurable to the voicemailmain extension you use
15124 if (!authpeer || ast_strlen_zero(authpeer->mailbox)) {
15125 transmit_response(p, "404 Not found (no mailbox)", req);
15126 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15127 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
15128 if (authpeer) /* No need for authpeer here */
15129 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15130 return 0;
15133 p->subscribed = MWI_NOTIFICATION;
15134 if (authpeer->mwipvt && authpeer->mwipvt != p) /* Destroy old PVT if this is a new one */
15135 /* We only allow one subscription per peer */
15136 sip_destroy(authpeer->mwipvt);
15137 authpeer->mwipvt = p; /* Link from peer to pvt */
15138 p->relatedpeer = ASTOBJ_REF(authpeer); /* Link from pvt to peer */
15139 } else { /* At this point, Asterisk does not understand the specified event */
15140 transmit_response(p, "489 Bad Event", req);
15141 if (option_debug > 1)
15142 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: %s\n", event);
15143 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15144 if (authpeer) /* No need for authpeer here */
15145 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15146 return 0;
15149 if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
15150 if (p->stateid > -1)
15151 ast_extension_state_del(p->stateid, cb_extensionstate);
15152 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, p);
15155 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
15156 p->lastinvite = seqno;
15157 if (p && !ast_test_flag(&p->flags[0], SIP_NEEDDESTROY)) {
15158 p->expiry = atoi(get_header(req, "Expires"));
15160 /* check if the requested expiry-time is within the approved limits from sip.conf */
15161 if (p->expiry > max_expiry)
15162 p->expiry = max_expiry;
15163 if (p->expiry < min_expiry && p->expiry > 0)
15164 p->expiry = min_expiry;
15166 if (sipdebug || option_debug > 1) {
15167 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
15168 ast_log(LOG_DEBUG, "Adding subscription for mailbox notification - peer %s Mailbox %s\n", p->relatedpeer->name, p->relatedpeer->mailbox);
15169 else
15170 ast_log(LOG_DEBUG, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
15172 if (p->autokillid > -1 && sip_cancel_destroy(p)) /* Remove subscription expiry for renewals */
15173 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15174 if (p->expiry > 0)
15175 sip_scheddestroy(p, (p->expiry + 10) * 1000); /* Set timer for destruction of call at expiration */
15177 if (p->subscribed == MWI_NOTIFICATION) {
15178 transmit_response(p, "200 OK", req);
15179 if (p->relatedpeer) { /* Send first notification */
15180 ASTOBJ_WRLOCK(p->relatedpeer);
15181 sip_send_mwi_to_peer(p->relatedpeer);
15182 ASTOBJ_UNLOCK(p->relatedpeer);
15184 } else {
15185 struct sip_pvt *p_old;
15187 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
15189 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));
15190 transmit_response(p, "404 Not found", req);
15191 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15192 return 0;
15195 transmit_response(p, "200 OK", req);
15196 transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
15197 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
15198 /* hide the 'complete' exten/context in the refer_to field for later display */
15199 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
15201 /* remove any old subscription from this peer for the same exten/context,
15202 as the peer has obviously forgotten about it and it's wasteful to wait
15203 for it to expire and send NOTIFY messages to the peer only to have them
15204 ignored (or generate errors)
15206 ast_mutex_lock(&iflock);
15207 for (p_old = iflist; p_old; p_old = p_old->next) {
15208 if (p_old == p)
15209 continue;
15210 if (p_old->initreq.method != SIP_SUBSCRIBE)
15211 continue;
15212 if (p_old->subscribed == NONE)
15213 continue;
15214 ast_mutex_lock(&p_old->lock);
15215 if (!strcmp(p_old->username, p->username)) {
15216 if (!strcmp(p_old->exten, p->exten) &&
15217 !strcmp(p_old->context, p->context)) {
15218 ast_set_flag(&p_old->flags[0], SIP_NEEDDESTROY);
15219 ast_mutex_unlock(&p_old->lock);
15220 break;
15223 ast_mutex_unlock(&p_old->lock);
15225 ast_mutex_unlock(&iflock);
15227 if (!p->expiry)
15228 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15230 return 1;
15233 /*! \brief Handle incoming REGISTER request */
15234 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
15236 enum check_auth_result res;
15238 /* Use this as the basis */
15239 if (ast_test_flag(req, SIP_PKT_DEBUG))
15240 ast_verbose("Using latest REGISTER request as basis request\n");
15241 copy_request(&p->initreq, req);
15242 check_via(p, req);
15243 if ((res = register_verify(p, sin, req, e)) < 0) {
15244 const char *reason;
15246 switch (res) {
15247 case AUTH_SECRET_FAILED:
15248 reason = "Wrong password";
15249 break;
15250 case AUTH_USERNAME_MISMATCH:
15251 reason = "Username/auth name mismatch";
15252 break;
15253 case AUTH_NOT_FOUND:
15254 reason = "No matching peer found";
15255 break;
15256 case AUTH_UNKNOWN_DOMAIN:
15257 reason = "Not a local domain";
15258 break;
15259 case AUTH_PEER_NOT_DYNAMIC:
15260 reason = "Peer is not supposed to register";
15261 break;
15262 case AUTH_ACL_FAILED:
15263 reason = "Device does not match ACL";
15264 break;
15265 default:
15266 reason = "Unknown failure";
15267 break;
15269 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
15270 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
15271 reason);
15272 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
15273 } else
15274 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
15276 if (res < 1) {
15277 /* Destroy the session, but keep us around for just a bit in case they don't
15278 get our 200 OK */
15279 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15281 return res;
15284 /*! \brief Handle incoming SIP requests (methods)
15285 \note This is where all incoming requests go first */
15286 /* called with p and p->owner locked */
15287 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
15289 /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
15290 relatively static */
15291 const char *cmd;
15292 const char *cseq;
15293 const char *useragent;
15294 int seqno;
15295 int len;
15296 int ignore = FALSE;
15297 int respid;
15298 int res = 0;
15299 int debug = sip_debug_test_pvt(p);
15300 char *e;
15301 int error = 0;
15303 /* Get Method and Cseq */
15304 cseq = get_header(req, "Cseq");
15305 cmd = req->header[0];
15307 /* Must have Cseq */
15308 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
15309 ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
15310 error = 1;
15312 if (!error && sscanf(cseq, "%d%n", &seqno, &len) != 1) {
15313 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
15314 error = 1;
15316 if (error) {
15317 if (!p->initreq.headers) /* New call */
15318 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); /* Make sure we destroy this dialog */
15319 return -1;
15321 /* Get the command XXX */
15323 cmd = req->rlPart1;
15324 e = req->rlPart2;
15326 /* Save useragent of the client */
15327 useragent = get_header(req, "User-Agent");
15328 if (!ast_strlen_zero(useragent))
15329 ast_string_field_set(p, useragent, useragent);
15331 /* Find out SIP method for incoming request */
15332 if (req->method == SIP_RESPONSE) { /* Response to our request */
15333 /* Response to our request -- Do some sanity checks */
15334 if (!p->initreq.headers) {
15335 if (option_debug)
15336 ast_log(LOG_DEBUG, "That's odd... Got a response on a call we dont know about. Cseq %d Cmd %s\n", seqno, cmd);
15337 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15338 return 0;
15339 } else if (p->ocseq && (p->ocseq < seqno) && (seqno != p->lastnoninvite)) {
15340 if (option_debug)
15341 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
15342 return -1;
15343 } else if (p->ocseq && (p->ocseq != seqno) && (seqno != p->lastnoninvite)) {
15344 /* ignore means "don't do anything with it" but still have to
15345 respond appropriately */
15346 ignore = TRUE;
15347 ast_set_flag(req, SIP_PKT_IGNORE);
15348 ast_set_flag(req, SIP_PKT_IGNORE_RESP);
15349 append_history(p, "Ignore", "Ignoring this retransmit\n");
15350 } else if (e) {
15351 e = ast_skip_blanks(e);
15352 if (sscanf(e, "%d %n", &respid, &len) != 1) {
15353 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
15354 } else {
15355 if (respid <= 0) {
15356 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
15357 return 0;
15359 /* More SIP ridiculousness, we have to ignore bogus contacts in 100 etc responses */
15360 if ((respid == 200) || ((respid >= 300) && (respid <= 399)))
15361 extract_uri(p, req);
15362 handle_response(p, respid, e + len, req, ignore, seqno);
15365 return 0;
15368 /* New SIP request coming in
15369 (could be new request in existing SIP dialog as well...)
15372 p->method = req->method; /* Find out which SIP method they are using */
15373 if (option_debug > 3)
15374 ast_log(LOG_DEBUG, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
15376 if (p->icseq && (p->icseq > seqno) ) {
15377 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
15378 if (option_debug > 2)
15379 ast_log(LOG_DEBUG, "Got CANCEL or ACK on INVITE with transactions in between.\n");
15380 } else {
15381 if (option_debug)
15382 ast_log(LOG_DEBUG, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
15383 if (req->method != SIP_ACK)
15384 transmit_response(p, "503 Server error", req); /* We must respond according to RFC 3261 sec 12.2 */
15385 return -1;
15387 } else if (p->icseq &&
15388 p->icseq == seqno &&
15389 req->method != SIP_ACK &&
15390 (p->method != SIP_CANCEL || ast_test_flag(&p->flags[0], SIP_ALREADYGONE))) {
15391 /* ignore means "don't do anything with it" but still have to
15392 respond appropriately. We do this if we receive a repeat of
15393 the last sequence number */
15394 ignore = 2;
15395 ast_set_flag(req, SIP_PKT_IGNORE);
15396 ast_set_flag(req, SIP_PKT_IGNORE_REQ);
15397 if (option_debug > 2)
15398 ast_log(LOG_DEBUG, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
15401 if (seqno >= p->icseq)
15402 /* Next should follow monotonically (but not necessarily
15403 incrementally -- thanks again to the genius authors of SIP --
15404 increasing */
15405 p->icseq = seqno;
15407 /* Find their tag if we haven't got it */
15408 if (ast_strlen_zero(p->theirtag)) {
15409 char tag[128];
15411 gettag(req, "From", tag, sizeof(tag));
15412 ast_string_field_set(p, theirtag, tag);
15414 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
15416 if (pedanticsipchecking) {
15417 /* If this is a request packet without a from tag, it's not
15418 correct according to RFC 3261 */
15419 /* Check if this a new request in a new dialog with a totag already attached to it,
15420 RFC 3261 - section 12.2 - and we don't want to mess with recovery */
15421 if (!p->initreq.headers && ast_test_flag(req, SIP_PKT_WITH_TOTAG)) {
15422 /* If this is a first request and it got a to-tag, it is not for us */
15423 if (!ast_test_flag(req, SIP_PKT_IGNORE) && req->method == SIP_INVITE) {
15424 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
15425 /* Will cease to exist after ACK */
15426 } else if (req->method != SIP_ACK) {
15427 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
15428 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15430 return res;
15434 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
15435 transmit_response(p, "400 Bad request", req);
15436 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15437 return -1;
15440 /* Handle various incoming SIP methods in requests */
15441 switch (p->method) {
15442 case SIP_OPTIONS:
15443 res = handle_request_options(p, req);
15444 break;
15445 case SIP_INVITE:
15446 res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
15447 break;
15448 case SIP_REFER:
15449 res = handle_request_refer(p, req, debug, ignore, seqno, nounlock);
15450 break;
15451 case SIP_CANCEL:
15452 res = handle_request_cancel(p, req);
15453 break;
15454 case SIP_BYE:
15455 res = handle_request_bye(p, req);
15456 break;
15457 case SIP_MESSAGE:
15458 res = handle_request_message(p, req);
15459 break;
15460 case SIP_SUBSCRIBE:
15461 res = handle_request_subscribe(p, req, sin, seqno, e);
15462 break;
15463 case SIP_REGISTER:
15464 res = handle_request_register(p, req, sin, e);
15465 break;
15466 case SIP_INFO:
15467 if (ast_test_flag(req, SIP_PKT_DEBUG))
15468 ast_verbose("Receiving INFO!\n");
15469 if (!ignore)
15470 handle_request_info(p, req);
15471 else /* if ignoring, transmit response */
15472 transmit_response(p, "200 OK", req);
15473 break;
15474 case SIP_NOTIFY:
15475 res = handle_request_notify(p, req, sin, seqno, e);
15476 break;
15477 case SIP_ACK:
15478 /* Make sure we don't ignore this */
15479 if (seqno == p->pendinginvite) {
15480 p->invitestate = INV_TERMINATED;
15481 p->pendinginvite = 0;
15482 __sip_ack(p, seqno, FLAG_RESPONSE, 0);
15483 if (find_sdp(req)) {
15484 if (process_sdp(p, req))
15485 return -1;
15487 check_pendings(p);
15489 /* Got an ACK that we did not match. Ignore silently */
15490 if (!p->lastinvite && ast_strlen_zero(p->randdata))
15491 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15492 break;
15493 default:
15494 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
15495 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
15496 cmd, ast_inet_ntoa(p->sa.sin_addr));
15497 /* If this is some new method, and we don't have a call, destroy it now */
15498 if (!p->initreq.headers)
15499 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15500 break;
15502 return res;
15505 /*! \brief Read data from SIP socket
15506 \note sipsock_read locks the owner channel while we are processing the SIP message
15507 \return 1 on error, 0 on success
15508 \note Successful messages is connected to SIP call and forwarded to handle_request()
15510 static int sipsock_read(int *id, int fd, short events, void *ignore)
15512 struct sip_request req;
15513 struct sockaddr_in sin = { 0, };
15514 struct sip_pvt *p;
15515 int res;
15516 socklen_t len = sizeof(sin);
15517 int nounlock;
15518 int recount = 0;
15519 int lockretry;
15521 memset(&req, 0, sizeof(req));
15522 res = recvfrom(sipsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
15523 if (res < 0) {
15524 #if !defined(__FreeBSD__)
15525 if (errno == EAGAIN)
15526 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
15527 else
15528 #endif
15529 if (errno != ECONNREFUSED)
15530 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
15531 return 1;
15533 if (option_debug && res == sizeof(req.data) - 1)
15534 ast_log(LOG_DEBUG, "Received packet exceeds buffer. Data is possibly lost\n");
15536 req.data[res] = '\0';
15537 req.len = res;
15538 if(sip_debug_test_addr(&sin)) /* Set the debug flag early on packet level */
15539 ast_set_flag(&req, SIP_PKT_DEBUG);
15540 if (pedanticsipchecking)
15541 req.len = lws2sws(req.data, req.len); /* Fix multiline headers */
15542 if (ast_test_flag(&req, SIP_PKT_DEBUG))
15543 ast_verbose("\n<--- SIP read from %s:%d --->\n%s\n<------------->\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), req.data);
15545 if(parse_request(&req) == -1) /* Bad packet, can't parse */
15546 return 1;
15548 req.method = find_sip_method(req.rlPart1);
15550 if (ast_test_flag(&req, SIP_PKT_DEBUG))
15551 ast_verbose("--- (%d headers %d lines)%s ---\n", req.headers, req.lines, (req.headers + req.lines == 0) ? " Nat keepalive" : "");
15553 if (req.headers < 2) /* Must have at least two headers */
15554 return 1;
15556 /* Process request, with netlock held, and with usual deadlock avoidance */
15557 for (lockretry = 100; lockretry > 0; lockretry--) {
15558 ast_mutex_lock(&netlock);
15560 /* Find the active SIP dialog or create a new one */
15561 p = find_call(&req, &sin, req.method); /* returns p locked */
15562 if (p == NULL) {
15563 if (option_debug)
15564 ast_log(LOG_DEBUG, "Invalid SIP message - rejected , no callid, len %d\n", req.len);
15565 ast_mutex_unlock(&netlock);
15566 return 1;
15568 /* Go ahead and lock the owner if it has one -- we may need it */
15569 /* because this is deadlock-prone, we need to try and unlock if failed */
15570 if (!p->owner || !ast_channel_trylock(p->owner))
15571 break; /* locking succeeded */
15572 if (lockretry == 1) {
15573 if (option_debug) {
15574 ast_log(LOG_DEBUG, "Failed to grab owner channel lock. (SIP call %s)\n", p->callid);
15576 } else {
15577 if (option_debug) {
15578 ast_log(LOG_DEBUG, "Failed to grab owner channel lock, trying again. (SIP call %s)\n", p->callid);
15580 ast_mutex_unlock(&p->lock);
15581 ast_mutex_unlock(&netlock);
15582 /* Sleep for a very short amount of time */
15583 usleep(1);
15586 p->recv = sin;
15588 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) /* This is a request or response, note what it was for */
15589 append_history(p, "Rx", "%s / %s / %s", req.data, get_header(&req, "CSeq"), req.rlPart2);
15591 if (!lockretry) {
15592 /* XXX Wouldn't p->owner always exist here? */
15593 /* This is unsafe, since p->owner wouldn't be locked. */
15594 if (p->owner)
15595 ast_log(LOG_ERROR, "We could NOT get the channel lock for %s! \n", S_OR(p->owner->name, "- no channel name ??? - "));
15596 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
15597 if (req.method != SIP_ACK)
15598 transmit_response(p, "503 Server error", &req); /* We must respond according to RFC 3261 sec 12.2 */
15599 /* XXX We could add retry-after to make sure they come back */
15600 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
15601 ast_mutex_unlock(&p->lock);
15602 ast_mutex_unlock(&netlock);
15603 return 1;
15605 nounlock = 0;
15606 if (handle_request(p, &req, &sin, &recount, &nounlock) == -1) {
15607 /* Request failed */
15608 if (option_debug)
15609 ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
15612 if (p->owner && !nounlock)
15613 ast_channel_unlock(p->owner);
15614 ast_mutex_unlock(&p->lock);
15615 ast_mutex_unlock(&netlock);
15616 if (recount)
15617 ast_update_use_count();
15619 return 1;
15622 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
15623 static int sip_send_mwi_to_peer(struct sip_peer *peer)
15625 /* Called with peerl lock, but releases it */
15626 struct sip_pvt *p;
15627 int newmsgs, oldmsgs;
15629 /* Do we have an IP address? If not, skip this peer */
15630 if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr)
15631 return 0;
15633 /* Check for messages */
15634 ast_app_inboxcount(peer->mailbox, &newmsgs, &oldmsgs);
15636 peer->lastmsgcheck = time(NULL);
15638 /* Return now if it's the same thing we told them last time */
15639 if (((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)) == peer->lastmsgssent) {
15640 return 0;
15644 peer->lastmsgssent = ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs));
15646 if (peer->mwipvt) {
15647 /* Base message on subscription */
15648 p = peer->mwipvt;
15649 } else {
15650 /* Build temporary dialog for this message */
15651 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY)))
15652 return -1;
15653 if (create_addr_from_peer(p, peer)) {
15654 /* Maybe they're not registered, etc. */
15655 sip_destroy(p);
15656 return 0;
15658 /* Recalculate our side, and recalculate Call ID */
15659 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
15660 p->ourip = __ourip;
15661 build_via(p);
15662 build_callid_pvt(p);
15663 /* Destroy this session after 32 secs */
15664 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15666 /* Send MWI */
15667 ast_set_flag(&p->flags[0], SIP_OUTGOING);
15668 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
15669 return 0;
15672 /*! \brief Check whether peer needs a new MWI notification check */
15673 static int does_peer_need_mwi(struct sip_peer *peer)
15675 time_t t = time(NULL);
15677 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
15678 !peer->mwipvt) { /* We don't have a subscription */
15679 peer->lastmsgcheck = t; /* Reset timer */
15680 return FALSE;
15683 if (!ast_strlen_zero(peer->mailbox) && (t - peer->lastmsgcheck) > global_mwitime)
15684 return TRUE;
15686 return FALSE;
15690 /*! \brief The SIP monitoring thread
15691 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
15692 (and thus do not have a separate thread) indefinitely
15694 static void *do_monitor(void *data)
15696 int res;
15697 struct sip_pvt *sip;
15698 struct sip_peer *peer = NULL;
15699 time_t t;
15700 int fastrestart = FALSE;
15701 int lastpeernum = -1;
15702 int curpeernum;
15703 int reloading;
15705 /* Add an I/O event to our SIP UDP socket */
15706 if (sipsock > -1)
15707 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
15709 /* From here on out, we die whenever asked */
15710 for(;;) {
15711 /* Check for a reload request */
15712 ast_mutex_lock(&sip_reload_lock);
15713 reloading = sip_reloading;
15714 sip_reloading = FALSE;
15715 ast_mutex_unlock(&sip_reload_lock);
15716 if (reloading) {
15717 if (option_verbose > 0)
15718 ast_verbose(VERBOSE_PREFIX_1 "Reloading SIP\n");
15719 sip_do_reload(sip_reloadreason);
15721 /* Change the I/O fd of our UDP socket */
15722 if (sipsock > -1) {
15723 if (sipsock_read_id)
15724 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
15725 else
15726 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
15727 } else if (sipsock_read_id) {
15728 ast_io_remove(io, sipsock_read_id);
15729 sipsock_read_id = NULL;
15732 restartsearch:
15733 /* Check for interfaces needing to be killed */
15734 ast_mutex_lock(&iflock);
15735 t = time(NULL);
15736 /* don't scan the interface list if it hasn't been a reasonable period
15737 of time since the last time we did it (when MWI is being sent, we can
15738 get back to this point every millisecond or less)
15740 for (sip = iflist; !fastrestart && sip; sip = sip->next) {
15741 /*! \note If we can't get a lock on an interface, skip it and come
15742 * back later. Note that there is the possibility of a deadlock with
15743 * sip_hangup otherwise, because sip_hangup is called with the channel
15744 * locked first, and the iface lock is attempted second.
15746 if (ast_mutex_trylock(&sip->lock))
15747 continue;
15749 /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
15750 if (sip->rtp && sip->owner &&
15751 (sip->owner->_state == AST_STATE_UP) &&
15752 !sip->redirip.sin_addr.s_addr &&
15753 sip->t38.state != T38_ENABLED) {
15754 if (sip->lastrtptx &&
15755 ast_rtp_get_rtpkeepalive(sip->rtp) &&
15756 (t > sip->lastrtptx + ast_rtp_get_rtpkeepalive(sip->rtp))) {
15757 /* Need to send an empty RTP packet */
15758 sip->lastrtptx = time(NULL);
15759 ast_rtp_sendcng(sip->rtp, 0);
15761 if (sip->lastrtprx &&
15762 (ast_rtp_get_rtptimeout(sip->rtp) || ast_rtp_get_rtpholdtimeout(sip->rtp)) &&
15763 (t > sip->lastrtprx + ast_rtp_get_rtptimeout(sip->rtp))) {
15764 /* Might be a timeout now -- see if we're on hold */
15765 struct sockaddr_in sin;
15766 ast_rtp_get_peer(sip->rtp, &sin);
15767 if (sin.sin_addr.s_addr ||
15768 (ast_rtp_get_rtpholdtimeout(sip->rtp) &&
15769 (t > sip->lastrtprx + ast_rtp_get_rtpholdtimeout(sip->rtp)))) {
15770 /* Needs a hangup */
15771 if (ast_rtp_get_rtptimeout(sip->rtp)) {
15772 while (sip->owner && ast_channel_trylock(sip->owner)) {
15773 DEADLOCK_AVOIDANCE(&sip->lock);
15775 if (sip->owner) {
15776 ast_log(LOG_NOTICE,
15777 "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
15778 sip->owner->name,
15779 (long) (t - sip->lastrtprx));
15780 /* Issue a softhangup */
15781 ast_softhangup_nolock(sip->owner, AST_SOFTHANGUP_DEV);
15782 ast_channel_unlock(sip->owner);
15783 /* forget the timeouts for this call, since a hangup
15784 has already been requested and we don't want to
15785 repeatedly request hangups
15787 ast_rtp_set_rtptimeout(sip->rtp, 0);
15788 ast_rtp_set_rtpholdtimeout(sip->rtp, 0);
15789 if (sip->vrtp) {
15790 ast_rtp_set_rtptimeout(sip->vrtp, 0);
15791 ast_rtp_set_rtpholdtimeout(sip->vrtp, 0);
15798 /* If we have sessions that needs to be destroyed, do it now */
15799 if (ast_test_flag(&sip->flags[0], SIP_NEEDDESTROY) && !sip->packets &&
15800 !sip->owner) {
15801 ast_mutex_unlock(&sip->lock);
15802 __sip_destroy(sip, 1);
15803 ast_mutex_unlock(&iflock);
15804 usleep(1);
15805 goto restartsearch;
15807 ast_mutex_unlock(&sip->lock);
15809 ast_mutex_unlock(&iflock);
15811 pthread_testcancel();
15812 /* Wait for sched or io */
15813 res = ast_sched_wait(sched);
15814 if ((res < 0) || (res > 1000))
15815 res = 1000;
15816 /* If we might need to send more mailboxes, don't wait long at all.*/
15817 if (fastrestart)
15818 res = 1;
15819 res = ast_io_wait(io, res);
15820 if (option_debug && res > 20)
15821 ast_log(LOG_DEBUG, "chan_sip: ast_io_wait ran %d all at once\n", res);
15822 ast_mutex_lock(&monlock);
15823 if (res >= 0) {
15824 res = ast_sched_runq(sched);
15825 if (option_debug && res >= 20)
15826 ast_log(LOG_DEBUG, "chan_sip: ast_sched_runq ran %d all at once\n", res);
15829 /* Send MWI notifications to peers - static and cached realtime peers */
15830 t = time(NULL);
15831 fastrestart = FALSE;
15832 curpeernum = 0;
15833 peer = NULL;
15834 /* Find next peer that needs mwi */
15835 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !peer, do {
15836 if ((curpeernum > lastpeernum) && does_peer_need_mwi(iterator)) {
15837 fastrestart = TRUE;
15838 lastpeernum = curpeernum;
15839 peer = ASTOBJ_REF(iterator);
15841 curpeernum++;
15842 } while (0)
15844 /* Send MWI to the peer */
15845 if (peer) {
15846 ASTOBJ_WRLOCK(peer);
15847 sip_send_mwi_to_peer(peer);
15848 ASTOBJ_UNLOCK(peer);
15849 ASTOBJ_UNREF(peer,sip_destroy_peer);
15850 } else {
15851 /* Reset where we come from */
15852 lastpeernum = -1;
15854 ast_mutex_unlock(&monlock);
15856 /* Never reached */
15857 return NULL;
15861 /*! \brief Start the channel monitor thread */
15862 static int restart_monitor(void)
15864 /* If we're supposed to be stopped -- stay stopped */
15865 if (monitor_thread == AST_PTHREADT_STOP)
15866 return 0;
15867 ast_mutex_lock(&monlock);
15868 if (monitor_thread == pthread_self()) {
15869 ast_mutex_unlock(&monlock);
15870 ast_log(LOG_WARNING, "Cannot kill myself\n");
15871 return -1;
15873 if (monitor_thread != AST_PTHREADT_NULL) {
15874 /* Wake up the thread */
15875 pthread_kill(monitor_thread, SIGURG);
15876 } else {
15877 /* Start a new monitor */
15878 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
15879 ast_mutex_unlock(&monlock);
15880 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
15881 return -1;
15884 ast_mutex_unlock(&monlock);
15885 return 0;
15888 /*! \brief React to lack of answer to Qualify poke */
15889 static int sip_poke_noanswer(const void *data)
15891 struct sip_peer *peer = (struct sip_peer *)data;
15893 peer->pokeexpire = -1;
15894 if (peer->lastms > -1) {
15895 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
15896 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
15898 if (peer->call)
15899 sip_destroy(peer->call);
15900 peer->call = NULL;
15901 peer->lastms = -1;
15902 ast_device_state_changed("SIP/%s", peer->name);
15904 /* This function gets called one place outside of the scheduler ... */
15905 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
15906 struct sip_peer *peer_ptr = peer;
15907 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
15910 /* There is no need to ASTOBJ_REF() here. Just let the scheduled callback
15911 * inherit the reference that the current callback already has. */
15912 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
15913 if (peer->pokeexpire == -1) {
15914 ASTOBJ_UNREF(peer, sip_destroy_peer);
15917 return 0;
15920 /*! \brief Check availability of peer, also keep NAT open
15921 \note This is done with the interval in qualify= configuration option
15922 Default is 2 seconds */
15923 static int sip_poke_peer(struct sip_peer *peer)
15925 struct sip_pvt *p;
15926 int xmitres = 0;
15928 if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
15929 /* IF we have no IP, or this isn't to be monitored, return
15930 imeediately after clearing things out */
15931 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
15932 struct sip_peer *peer_ptr = peer;
15933 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
15935 peer->lastms = 0;
15936 peer->call = NULL;
15937 return 0;
15939 if (peer->call) {
15940 if (sipdebug)
15941 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
15942 sip_destroy(peer->call);
15944 if (!(p = peer->call = sip_alloc(NULL, NULL, 0, SIP_OPTIONS)))
15945 return -1;
15947 p->sa = peer->addr;
15948 p->recv = peer->addr;
15949 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
15950 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15952 /* Send OPTIONs to peer's fullcontact */
15953 if (!ast_strlen_zero(peer->fullcontact))
15954 ast_string_field_set(p, fullcontact, peer->fullcontact);
15956 if (!ast_strlen_zero(peer->tohost))
15957 ast_string_field_set(p, tohost, peer->tohost);
15958 else
15959 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
15961 /* Recalculate our side, and recalculate Call ID */
15962 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
15963 p->ourip = __ourip;
15964 build_via(p);
15965 build_callid_pvt(p);
15967 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
15968 struct sip_peer *peer_ptr = peer;
15969 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
15972 p->relatedpeer = ASTOBJ_REF(peer);
15973 ast_set_flag(&p->flags[0], SIP_OUTGOING);
15974 #ifdef VOCAL_DATA_HACK
15975 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
15976 xmitres = transmit_invite(p, SIP_INVITE, 0, 2);
15977 #else
15978 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2);
15979 #endif
15980 gettimeofday(&peer->ps, NULL);
15981 if (xmitres == XMIT_ERROR) {
15982 sip_poke_noanswer(ASTOBJ_REF(peer)); /* Immediately unreachable, network problems */
15983 } else {
15984 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
15985 struct sip_peer *peer_ptr = peer;
15986 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
15988 peer->pokeexpire = ast_sched_add(sched, peer->maxms * 2, sip_poke_noanswer, ASTOBJ_REF(peer));
15989 if (peer->pokeexpire == -1) {
15990 struct sip_peer *peer_ptr = peer;
15991 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
15995 return 0;
15998 /*! \brief Part of PBX channel interface
15999 \note
16000 \par Return values:---
16002 If we have qualify on and the device is not reachable, regardless of registration
16003 state we return AST_DEVICE_UNAVAILABLE
16005 For peers with call limit:
16006 - not registered AST_DEVICE_UNAVAILABLE
16007 - registered, no call AST_DEVICE_NOT_INUSE
16008 - registered, active calls AST_DEVICE_INUSE
16009 - registered, call limit reached AST_DEVICE_BUSY
16010 - registered, onhold AST_DEVICE_ONHOLD
16011 - registered, ringing AST_DEVICE_RINGING
16013 For peers without call limit:
16014 - not registered AST_DEVICE_UNAVAILABLE
16015 - registered AST_DEVICE_NOT_INUSE
16016 - fixed IP (!dynamic) AST_DEVICE_NOT_INUSE
16018 Peers that does not have a known call and can't be reached by OPTIONS
16019 - unreachable AST_DEVICE_UNAVAILABLE
16021 If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
16022 out a state by walking the channel list.
16024 The queue system (\ref app_queue.c) treats a member as "active"
16025 if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
16027 When placing a call to the queue member, queue system sets a member to busy if
16028 != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
16031 static int sip_devicestate(void *data)
16033 char *host;
16034 char *tmp;
16036 struct hostent *hp;
16037 struct ast_hostent ahp;
16038 struct sip_peer *p;
16040 int res = AST_DEVICE_INVALID;
16042 /* make sure data is not null. Maybe unnecessary, but better be safe */
16043 host = ast_strdupa(data ? data : "");
16044 if ((tmp = strchr(host, '@')))
16045 host = tmp + 1;
16047 if (option_debug > 2)
16048 ast_log(LOG_DEBUG, "Checking device state for peer %s\n", host);
16050 if ((p = find_peer(host, NULL, 1))) {
16051 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
16052 /* we have an address for the peer */
16054 /* Check status in this order
16055 - Hold
16056 - Ringing
16057 - Busy (enforced only by call limit)
16058 - Inuse (we have a call)
16059 - Unreachable (qualify)
16060 If we don't find any of these state, report AST_DEVICE_NOT_INUSE
16061 for registered devices */
16063 if (p->onHold)
16064 /* First check for hold or ring states */
16065 res = AST_DEVICE_ONHOLD;
16066 else if (p->inRinging) {
16067 if (p->inRinging == p->inUse)
16068 res = AST_DEVICE_RINGING;
16069 else
16070 res = AST_DEVICE_RINGINUSE;
16071 } else if (p->call_limit && (p->inUse == p->call_limit))
16072 /* check call limit */
16073 res = AST_DEVICE_BUSY;
16074 else if (p->call_limit && p->inUse)
16075 /* Not busy, but we do have a call */
16076 res = AST_DEVICE_INUSE;
16077 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
16078 /* We don't have a call. Are we reachable at all? Requires qualify= */
16079 res = AST_DEVICE_UNAVAILABLE;
16080 else /* Default reply if we're registered and have no other data */
16081 res = AST_DEVICE_NOT_INUSE;
16082 } else {
16083 /* there is no address, it's unavailable */
16084 res = AST_DEVICE_UNAVAILABLE;
16086 ASTOBJ_UNREF(p,sip_destroy_peer);
16087 } else {
16088 char *port = strchr(host, ':');
16089 if (port)
16090 *port = '\0';
16091 hp = ast_gethostbyname(host, &ahp);
16092 if (hp)
16093 res = AST_DEVICE_UNKNOWN;
16096 return res;
16099 /*! \brief PBX interface function -build SIP pvt structure
16100 SIP calls initiated by the PBX arrive here */
16101 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
16103 int oldformat;
16104 struct sip_pvt *p;
16105 struct ast_channel *tmpc = NULL;
16106 char *ext, *host;
16107 char tmp[256];
16108 char *dest = data;
16110 oldformat = format;
16111 if (!(format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1))) {
16112 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));
16113 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL; /* Can't find codec to connect to host */
16114 return NULL;
16116 if (option_debug)
16117 ast_log(LOG_DEBUG, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
16119 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE))) {
16120 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", (char *)data);
16121 *cause = AST_CAUSE_SWITCH_CONGESTION;
16122 return NULL;
16125 ast_set_flag(&p->flags[1], SIP_PAGE2_OUTGOING_CALL);
16127 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
16128 sip_destroy(p);
16129 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
16130 *cause = AST_CAUSE_SWITCH_CONGESTION;
16131 return NULL;
16134 ast_copy_string(tmp, dest, sizeof(tmp));
16135 host = strchr(tmp, '@');
16136 if (host) {
16137 *host++ = '\0';
16138 ext = tmp;
16139 } else {
16140 ext = strchr(tmp, '/');
16141 if (ext)
16142 *ext++ = '\0';
16143 host = tmp;
16146 if (create_addr(p, host)) {
16147 *cause = AST_CAUSE_UNREGISTERED;
16148 if (option_debug > 2)
16149 ast_log(LOG_DEBUG, "Cant create SIP call - target device not registred\n");
16150 sip_destroy(p);
16151 return NULL;
16153 if (ast_strlen_zero(p->peername) && ext)
16154 ast_string_field_set(p, peername, ext);
16155 /* Recalculate our side, and recalculate Call ID */
16156 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
16157 p->ourip = __ourip;
16158 build_via(p);
16159 build_callid_pvt(p);
16161 /* We have an extension to call, don't use the full contact here */
16162 /* This to enable dialing registered peers with extension dialling,
16163 like SIP/peername/extension
16164 SIP/peername will still use the full contact */
16165 if (ext) {
16166 ast_string_field_set(p, username, ext);
16167 ast_string_field_free(p, fullcontact);
16169 #if 0
16170 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
16171 #endif
16172 p->prefcodec = oldformat; /* Format for this call */
16173 ast_mutex_lock(&p->lock);
16174 tmpc = sip_new(p, AST_STATE_DOWN, host); /* Place the call */
16175 ast_mutex_unlock(&p->lock);
16176 if (!tmpc)
16177 sip_destroy(p);
16178 ast_update_use_count();
16179 restart_monitor();
16180 return tmpc;
16184 * \brief Parse the "insecure" setting from sip.conf or from realtime.
16185 * \param flags a pointer to an ast_flags structure
16186 * \param value the value of the SIP insecure setting
16187 * \param lineno linenumber in sip.conf or -1 for realtime
16189 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno)
16191 static int dep_insecure_very = 0;
16192 static int dep_insecure_yes = 0;
16194 if (ast_strlen_zero(value))
16195 return;
16197 if (!strcasecmp(value, "very")) {
16198 ast_set_flag(flags, SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16199 if(!dep_insecure_very) {
16200 if(lineno != -1)
16201 ast_log(LOG_WARNING, "insecure=very at line %d is deprecated; use insecure=port,invite instead\n", lineno);
16202 else
16203 ast_log(LOG_WARNING, "insecure=very is deprecated; use insecure=port,invite instead\n");
16204 dep_insecure_very = 1;
16207 else if (ast_true(value)) {
16208 ast_set_flag(flags, SIP_INSECURE_PORT);
16209 if(!dep_insecure_yes) {
16210 if(lineno != -1)
16211 ast_log(LOG_WARNING, "insecure=%s at line %d is deprecated; use insecure=port instead\n", value, lineno);
16212 else
16213 ast_log(LOG_WARNING, "insecure=%s is deprecated; use insecure=port instead\n", value);
16214 dep_insecure_yes = 1;
16217 else if (!ast_false(value)) {
16218 char buf[64];
16219 char *word, *next;
16220 ast_copy_string(buf, value, sizeof(buf));
16221 next = buf;
16222 while ((word = strsep(&next, ","))) {
16223 if (!strcasecmp(word, "port"))
16224 ast_set_flag(flags, SIP_INSECURE_PORT);
16225 else if (!strcasecmp(word, "invite"))
16226 ast_set_flag(flags, SIP_INSECURE_INVITE);
16227 else
16228 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
16234 \brief Handle flag-type options common to configuration of devices - users and peers
16235 \param flags array of two struct ast_flags
16236 \param mask array of two struct ast_flags
16237 \param v linked list of config variables to process
16238 \returns non-zero if any config options were handled, zero otherwise
16240 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
16242 int res = 1;
16244 if (!strcasecmp(v->name, "trustrpid")) {
16245 ast_set_flag(&mask[0], SIP_TRUSTRPID);
16246 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
16247 } else if (!strcasecmp(v->name, "sendrpid")) {
16248 ast_set_flag(&mask[0], SIP_SENDRPID);
16249 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
16250 } else if (!strcasecmp(v->name, "g726nonstandard")) {
16251 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
16252 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
16253 } else if (!strcasecmp(v->name, "useclientcode")) {
16254 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
16255 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
16256 } else if (!strcasecmp(v->name, "dtmfmode")) {
16257 ast_set_flag(&mask[0], SIP_DTMF);
16258 ast_clear_flag(&flags[0], SIP_DTMF);
16259 if (!strcasecmp(v->value, "inband"))
16260 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
16261 else if (!strcasecmp(v->value, "rfc2833"))
16262 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
16263 else if (!strcasecmp(v->value, "info"))
16264 ast_set_flag(&flags[0], SIP_DTMF_INFO);
16265 else if (!strcasecmp(v->value, "auto"))
16266 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
16267 else {
16268 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
16269 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
16271 } else if (!strcasecmp(v->name, "nat")) {
16272 ast_set_flag(&mask[0], SIP_NAT);
16273 ast_clear_flag(&flags[0], SIP_NAT);
16274 if (!strcasecmp(v->value, "never"))
16275 ast_set_flag(&flags[0], SIP_NAT_NEVER);
16276 else if (!strcasecmp(v->value, "route"))
16277 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
16278 else if (ast_true(v->value))
16279 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
16280 else
16281 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
16282 } else if (!strcasecmp(v->name, "canreinvite")) {
16283 ast_set_flag(&mask[0], SIP_REINVITE);
16284 ast_clear_flag(&flags[0], SIP_REINVITE);
16285 if(ast_true(v->value)) {
16286 ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
16287 } else if (!ast_false(v->value)) {
16288 char buf[64];
16289 char *word, *next = buf;
16291 ast_copy_string(buf, v->value, sizeof(buf));
16292 while ((word = strsep(&next, ","))) {
16293 if(!strcasecmp(word, "update")) {
16294 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
16295 } else if(!strcasecmp(word, "nonat")) {
16296 ast_set_flag(&flags[0], SIP_CAN_REINVITE);
16297 ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
16298 } else {
16299 ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
16303 } else if (!strcasecmp(v->name, "insecure")) {
16304 ast_set_flag(&mask[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16305 ast_clear_flag(&flags[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16306 set_insecure_flags(flags, v->value, v->lineno);
16307 } else if (!strcasecmp(v->name, "progressinband")) {
16308 ast_set_flag(&mask[0], SIP_PROG_INBAND);
16309 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
16310 if (ast_true(v->value))
16311 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
16312 else if (strcasecmp(v->value, "never"))
16313 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
16314 } else if (!strcasecmp(v->name, "promiscredir")) {
16315 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
16316 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
16317 } else if (!strcasecmp(v->name, "videosupport")) {
16318 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
16319 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
16320 } else if (!strcasecmp(v->name, "allowoverlap")) {
16321 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
16322 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
16323 } else if (!strcasecmp(v->name, "allowsubscribe")) {
16324 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
16325 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
16326 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
16327 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_UDPTL);
16328 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_UDPTL);
16329 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
16330 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
16331 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_RTP);
16332 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_RTP);
16333 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
16334 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_TCP);
16335 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_TCP);
16336 #endif
16337 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
16338 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
16339 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
16340 } else if (!strcasecmp(v->name, "buggymwi")) {
16341 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
16342 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
16343 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
16344 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
16345 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
16346 } else
16347 res = 0;
16349 return res;
16352 /*! \brief Add SIP domain to list of domains we are responsible for */
16353 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
16355 struct domain *d;
16357 if (ast_strlen_zero(domain)) {
16358 ast_log(LOG_WARNING, "Zero length domain.\n");
16359 return 1;
16362 if (!(d = ast_calloc(1, sizeof(*d))))
16363 return 0;
16365 ast_copy_string(d->domain, domain, sizeof(d->domain));
16367 if (!ast_strlen_zero(context))
16368 ast_copy_string(d->context, context, sizeof(d->context));
16370 d->mode = mode;
16372 AST_LIST_LOCK(&domain_list);
16373 AST_LIST_INSERT_TAIL(&domain_list, d, list);
16374 AST_LIST_UNLOCK(&domain_list);
16376 if (sipdebug)
16377 ast_log(LOG_DEBUG, "Added local SIP domain '%s'\n", domain);
16379 return 1;
16382 /*! \brief check_sip_domain: Check if domain part of uri is local to our server */
16383 static int check_sip_domain(const char *domain, char *context, size_t len)
16385 struct domain *d;
16386 int result = 0;
16388 AST_LIST_LOCK(&domain_list);
16389 AST_LIST_TRAVERSE(&domain_list, d, list) {
16390 if (strcasecmp(d->domain, domain))
16391 continue;
16393 if (len && !ast_strlen_zero(d->context))
16394 ast_copy_string(context, d->context, len);
16396 result = 1;
16397 break;
16399 AST_LIST_UNLOCK(&domain_list);
16401 return result;
16404 /*! \brief Clear our domain list (at reload) */
16405 static void clear_sip_domains(void)
16407 struct domain *d;
16409 AST_LIST_LOCK(&domain_list);
16410 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
16411 free(d);
16412 AST_LIST_UNLOCK(&domain_list);
16416 /*! \brief Add realm authentication in list */
16417 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno)
16419 char authcopy[256];
16420 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
16421 char *stringp;
16422 struct sip_auth *a, *b, *auth;
16424 if (ast_strlen_zero(configuration))
16425 return authlist;
16427 if (option_debug)
16428 ast_log(LOG_DEBUG, "Auth config :: %s\n", configuration);
16430 ast_copy_string(authcopy, configuration, sizeof(authcopy));
16431 stringp = authcopy;
16433 username = stringp;
16434 realm = strrchr(stringp, '@');
16435 if (realm)
16436 *realm++ = '\0';
16437 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
16438 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
16439 return authlist;
16441 stringp = username;
16442 username = strsep(&stringp, ":");
16443 if (username) {
16444 secret = strsep(&stringp, ":");
16445 if (!secret) {
16446 stringp = username;
16447 md5secret = strsep(&stringp,"#");
16450 if (!(auth = ast_calloc(1, sizeof(*auth))))
16451 return authlist;
16453 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
16454 ast_copy_string(auth->username, username, sizeof(auth->username));
16455 if (secret)
16456 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
16457 if (md5secret)
16458 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
16460 /* find the end of the list */
16461 for (b = NULL, a = authlist; a ; b = a, a = a->next)
16463 if (b)
16464 b->next = auth; /* Add structure add end of list */
16465 else
16466 authlist = auth;
16468 if (option_verbose > 2)
16469 ast_verbose("Added authentication for realm %s\n", realm);
16471 return authlist;
16475 /*! \brief Clear realm authentication list (at reload) */
16476 static int clear_realm_authentication(struct sip_auth *authlist)
16478 struct sip_auth *a = authlist;
16479 struct sip_auth *b;
16481 while (a) {
16482 b = a;
16483 a = a->next;
16484 free(b);
16487 return 1;
16490 /*! \brief Find authentication for a specific realm */
16491 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
16493 struct sip_auth *a;
16495 for (a = authlist; a; a = a->next) {
16496 if (!strcasecmp(a->realm, realm))
16497 break;
16500 return a;
16503 /*! \brief Initiate a SIP user structure from configuration (configuration or realtime) */
16504 static struct sip_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
16506 struct sip_user *user;
16507 int format;
16508 struct ast_ha *oldha = NULL;
16509 char *varname = NULL, *varval = NULL;
16510 struct ast_variable *tmpvar = NULL;
16511 struct ast_flags userflags[2] = {{(0)}};
16512 struct ast_flags mask[2] = {{(0)}};
16515 if (!(user = ast_calloc(1, sizeof(*user))))
16516 return NULL;
16518 suserobjs++;
16519 ASTOBJ_INIT(user);
16520 ast_copy_string(user->name, name, sizeof(user->name));
16521 oldha = user->ha;
16522 user->ha = NULL;
16523 ast_copy_flags(&user->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
16524 ast_copy_flags(&user->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16525 user->capability = global_capability;
16526 user->allowtransfer = global_allowtransfer;
16527 user->maxcallbitrate = default_maxcallbitrate;
16528 user->autoframing = global_autoframing;
16529 user->prefs = default_prefs;
16530 /* set default context */
16531 strcpy(user->context, default_context);
16532 strcpy(user->language, default_language);
16533 strcpy(user->mohinterpret, default_mohinterpret);
16534 strcpy(user->mohsuggest, default_mohsuggest);
16535 /* First we walk through the v parameters list and then the alt parameters list */
16536 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
16537 if (handle_common_options(&userflags[0], &mask[0], v))
16538 continue;
16540 if (!strcasecmp(v->name, "context")) {
16541 ast_copy_string(user->context, v->value, sizeof(user->context));
16542 } else if (!strcasecmp(v->name, "subscribecontext")) {
16543 ast_copy_string(user->subscribecontext, v->value, sizeof(user->subscribecontext));
16544 } else if (!strcasecmp(v->name, "setvar")) {
16545 varname = ast_strdupa(v->value);
16546 if ((varval = strchr(varname,'='))) {
16547 *varval++ = '\0';
16548 if ((tmpvar = ast_variable_new(varname, varval))) {
16549 tmpvar->next = user->chanvars;
16550 user->chanvars = tmpvar;
16553 } else if (!strcasecmp(v->name, "permit") ||
16554 !strcasecmp(v->name, "deny")) {
16555 user->ha = ast_append_ha(v->name, v->value, user->ha);
16556 } else if (!strcasecmp(v->name, "allowtransfer")) {
16557 user->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
16558 } else if (!strcasecmp(v->name, "secret")) {
16559 ast_copy_string(user->secret, v->value, sizeof(user->secret));
16560 } else if (!strcasecmp(v->name, "md5secret")) {
16561 ast_copy_string(user->md5secret, v->value, sizeof(user->md5secret));
16562 } else if (!strcasecmp(v->name, "callerid")) {
16563 ast_callerid_split(v->value, user->cid_name, sizeof(user->cid_name), user->cid_num, sizeof(user->cid_num));
16564 } else if (!strcasecmp(v->name, "fullname")) {
16565 ast_copy_string(user->cid_name, v->value, sizeof(user->cid_name));
16566 } else if (!strcasecmp(v->name, "cid_number")) {
16567 ast_copy_string(user->cid_num, v->value, sizeof(user->cid_num));
16568 } else if (!strcasecmp(v->name, "callgroup")) {
16569 user->callgroup = ast_get_group(v->value);
16570 } else if (!strcasecmp(v->name, "pickupgroup")) {
16571 user->pickupgroup = ast_get_group(v->value);
16572 } else if (!strcasecmp(v->name, "language")) {
16573 ast_copy_string(user->language, v->value, sizeof(user->language));
16574 } else if (!strcasecmp(v->name, "mohinterpret")
16575 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
16576 ast_copy_string(user->mohinterpret, v->value, sizeof(user->mohinterpret));
16577 } else if (!strcasecmp(v->name, "mohsuggest")) {
16578 ast_copy_string(user->mohsuggest, v->value, sizeof(user->mohsuggest));
16579 } else if (!strcasecmp(v->name, "accountcode")) {
16580 ast_copy_string(user->accountcode, v->value, sizeof(user->accountcode));
16581 } else if (!strcasecmp(v->name, "call-limit")) {
16582 user->call_limit = atoi(v->value);
16583 if (user->call_limit < 0)
16584 user->call_limit = 0;
16585 } else if (!strcasecmp(v->name, "amaflags")) {
16586 format = ast_cdr_amaflags2int(v->value);
16587 if (format < 0) {
16588 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
16589 } else {
16590 user->amaflags = format;
16592 } else if (!strcasecmp(v->name, "allow")) {
16593 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
16594 } else if (!strcasecmp(v->name, "disallow")) {
16595 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 0);
16596 } else if (!strcasecmp(v->name, "autoframing")) {
16597 user->autoframing = ast_true(v->value);
16598 } else if (!strcasecmp(v->name, "callingpres")) {
16599 user->callingpres = ast_parse_caller_presentation(v->value);
16600 if (user->callingpres == -1)
16601 user->callingpres = atoi(v->value);
16602 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
16603 user->maxcallbitrate = atoi(v->value);
16604 if (user->maxcallbitrate < 0)
16605 user->maxcallbitrate = default_maxcallbitrate;
16607 /* We can't just report unknown options here because this may be a
16608 * type=friend entry. All user options are valid for a peer, but not
16609 * the other way around. */
16611 ast_copy_flags(&user->flags[0], &userflags[0], mask[0].flags);
16612 ast_copy_flags(&user->flags[1], &userflags[1], mask[1].flags);
16613 if (ast_test_flag(&user->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
16614 global_allowsubscribe = TRUE; /* No global ban any more */
16615 ast_free_ha(oldha);
16616 return user;
16619 /*! \brief Set peer defaults before configuring specific configurations */
16620 static void set_peer_defaults(struct sip_peer *peer)
16622 if (peer->expire == 0) {
16623 /* Don't reset expire or port time during reload
16624 if we have an active registration
16626 peer->expire = -1;
16627 peer->pokeexpire = -1;
16628 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
16630 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
16631 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16632 strcpy(peer->context, default_context);
16633 strcpy(peer->subscribecontext, default_subscribecontext);
16634 strcpy(peer->language, default_language);
16635 strcpy(peer->mohinterpret, default_mohinterpret);
16636 strcpy(peer->mohsuggest, default_mohsuggest);
16637 peer->addr.sin_family = AF_INET;
16638 peer->defaddr.sin_family = AF_INET;
16639 peer->capability = global_capability;
16640 peer->maxcallbitrate = default_maxcallbitrate;
16641 peer->rtptimeout = global_rtptimeout;
16642 peer->rtpholdtimeout = global_rtpholdtimeout;
16643 peer->rtpkeepalive = global_rtpkeepalive;
16644 peer->allowtransfer = global_allowtransfer;
16645 peer->autoframing = global_autoframing;
16646 strcpy(peer->vmexten, default_vmexten);
16647 peer->secret[0] = '\0';
16648 peer->md5secret[0] = '\0';
16649 peer->cid_num[0] = '\0';
16650 peer->cid_name[0] = '\0';
16651 peer->fromdomain[0] = '\0';
16652 peer->fromuser[0] = '\0';
16653 peer->regexten[0] = '\0';
16654 peer->mailbox[0] = '\0';
16655 peer->callgroup = 0;
16656 peer->pickupgroup = 0;
16657 peer->maxms = default_qualify;
16658 peer->prefs = default_prefs;
16661 /*! \brief Create temporary peer (used in autocreatepeer mode) */
16662 static struct sip_peer *temp_peer(const char *name)
16664 struct sip_peer *peer;
16666 if (!(peer = ast_calloc(1, sizeof(*peer))))
16667 return NULL;
16669 apeerobjs++;
16670 ASTOBJ_INIT(peer);
16671 set_peer_defaults(peer);
16673 ast_copy_string(peer->name, name, sizeof(peer->name));
16675 ast_set_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT);
16676 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
16677 peer->prefs = default_prefs;
16678 reg_source_db(peer);
16680 return peer;
16683 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
16684 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
16686 struct sip_peer *peer = NULL;
16687 struct ast_ha *oldha = NULL;
16688 int obproxyfound=0;
16689 int found=0;
16690 int firstpass=1;
16691 int format=0; /* Ama flags */
16692 time_t regseconds = 0;
16693 char *varname = NULL, *varval = NULL;
16694 struct ast_variable *tmpvar = NULL;
16695 struct ast_flags peerflags[2] = {{(0)}};
16696 struct ast_flags mask[2] = {{(0)}};
16697 char fullcontact[sizeof(peer->fullcontact)] = "";
16699 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))
16700 /* Note we do NOT use find_peer here, to avoid realtime recursion */
16701 /* We also use a case-sensitive comparison (unlike find_peer) so
16702 that case changes made to the peer name will be properly handled
16703 during reload
16705 peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);
16707 if (peer) {
16708 /* Already in the list, remove it and it will be added back (or FREE'd) */
16709 found = 1;
16710 if (!(peer->objflags & ASTOBJ_FLAG_MARKED))
16711 firstpass = 0;
16712 } else {
16713 if (!(peer = ast_calloc(1, sizeof(*peer))))
16714 return NULL;
16716 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))
16717 rpeerobjs++;
16718 else
16719 speerobjs++;
16720 ASTOBJ_INIT(peer);
16722 /* Note that our peer HAS had its reference count incrased */
16723 if (firstpass) {
16724 peer->lastmsgssent = -1;
16725 oldha = peer->ha;
16726 peer->ha = NULL;
16727 set_peer_defaults(peer); /* Set peer defaults */
16729 if (!found && name)
16730 ast_copy_string(peer->name, name, sizeof(peer->name));
16732 /* If we have channel variables, remove them (reload) */
16733 if (peer->chanvars) {
16734 ast_variables_destroy(peer->chanvars);
16735 peer->chanvars = NULL;
16736 /* XXX should unregister ? */
16739 /* If we have realm authentication information, remove them (reload) */
16740 clear_realm_authentication(peer->auth);
16741 peer->auth = NULL;
16743 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
16744 if (handle_common_options(&peerflags[0], &mask[0], v))
16745 continue;
16746 if (realtime && !strcasecmp(v->name, "regseconds")) {
16747 ast_get_time_t(v->value, &regseconds, 0, NULL);
16748 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
16749 inet_aton(v->value, &(peer->addr.sin_addr));
16750 } else if (realtime && !strcasecmp(v->name, "name"))
16751 ast_copy_string(peer->name, v->value, sizeof(peer->name));
16752 else if (realtime && !strcasecmp(v->name, "fullcontact")) {
16753 /* Reconstruct field, because realtime separates our value at the ';' */
16754 if (!ast_strlen_zero(fullcontact)) {
16755 strncat(fullcontact, ";", sizeof(fullcontact) - strlen(fullcontact) - 1);
16756 strncat(fullcontact, v->value, sizeof(fullcontact) - strlen(fullcontact) - 1);
16757 } else {
16758 ast_copy_string(fullcontact, v->value, sizeof(fullcontact));
16759 ast_set_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT);
16761 } else if (!strcasecmp(v->name, "secret"))
16762 ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
16763 else if (!strcasecmp(v->name, "md5secret"))
16764 ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
16765 else if (!strcasecmp(v->name, "auth"))
16766 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
16767 else if (!strcasecmp(v->name, "callerid")) {
16768 ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
16769 } else if (!strcasecmp(v->name, "fullname")) {
16770 ast_copy_string(peer->cid_name, v->value, sizeof(peer->cid_name));
16771 } else if (!strcasecmp(v->name, "cid_number")) {
16772 ast_copy_string(peer->cid_num, v->value, sizeof(peer->cid_num));
16773 } else if (!strcasecmp(v->name, "context")) {
16774 ast_copy_string(peer->context, v->value, sizeof(peer->context));
16775 } else if (!strcasecmp(v->name, "subscribecontext")) {
16776 ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
16777 } else if (!strcasecmp(v->name, "fromdomain")) {
16778 ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
16779 } else if (!strcasecmp(v->name, "usereqphone")) {
16780 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
16781 } else if (!strcasecmp(v->name, "fromuser")) {
16782 ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
16783 } else if (!strcasecmp(v->name, "host") || !strcasecmp(v->name, "outboundproxy")) {
16784 if (!strcasecmp(v->value, "dynamic")) {
16785 if (!strcasecmp(v->name, "outboundproxy") || obproxyfound) {
16786 ast_log(LOG_WARNING, "You can't have a dynamic outbound proxy, you big silly head at line %d.\n", v->lineno);
16787 } else {
16788 /* They'll register with us */
16789 if (!found || !ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
16790 /* Initialize stuff if this is a new peer, or if it used to be
16791 * non-dynamic before the reload. */
16792 memset(&peer->addr.sin_addr, 0, 4);
16793 if (peer->addr.sin_port) {
16794 /* If we've already got a port, make it the default rather than absolute */
16795 peer->defaddr.sin_port = peer->addr.sin_port;
16796 peer->addr.sin_port = 0;
16799 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
16801 } else {
16802 /* Non-dynamic. Make sure we become that way if we're not */
16803 if (!AST_SCHED_DEL(sched, peer->expire)) {
16804 struct sip_peer *peer_ptr = peer;
16805 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
16807 ast_clear_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
16808 if (!obproxyfound || !strcasecmp(v->name, "outboundproxy")) {
16809 if (ast_get_ip_or_srv(&peer->addr, v->value, srvlookup ? "_sip._udp" : NULL)) {
16810 ASTOBJ_UNREF(peer, sip_destroy_peer);
16811 return NULL;
16814 if (!strcasecmp(v->name, "outboundproxy"))
16815 obproxyfound=1;
16816 else {
16817 ast_copy_string(peer->tohost, v->value, sizeof(peer->tohost));
16818 if (!peer->addr.sin_port)
16819 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
16822 } else if (!strcasecmp(v->name, "defaultip")) {
16823 if (ast_get_ip(&peer->defaddr, v->value)) {
16824 ASTOBJ_UNREF(peer, sip_destroy_peer);
16825 return NULL;
16827 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
16828 peer->ha = ast_append_ha(v->name, v->value, peer->ha);
16829 } else if (!strcasecmp(v->name, "port")) {
16830 if (!realtime && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC))
16831 peer->defaddr.sin_port = htons(atoi(v->value));
16832 else
16833 peer->addr.sin_port = htons(atoi(v->value));
16834 } else if (!strcasecmp(v->name, "callingpres")) {
16835 peer->callingpres = ast_parse_caller_presentation(v->value);
16836 if (peer->callingpres == -1)
16837 peer->callingpres = atoi(v->value);
16838 } else if (!strcasecmp(v->name, "username")) {
16839 ast_copy_string(peer->username, v->value, sizeof(peer->username));
16840 } else if (!strcasecmp(v->name, "language")) {
16841 ast_copy_string(peer->language, v->value, sizeof(peer->language));
16842 } else if (!strcasecmp(v->name, "regexten")) {
16843 ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
16844 } else if (!strcasecmp(v->name, "call-limit") || !strcasecmp(v->name, "incominglimit")) {
16845 peer->call_limit = atoi(v->value);
16846 if (peer->call_limit < 0)
16847 peer->call_limit = 0;
16848 } else if (!strcasecmp(v->name, "amaflags")) {
16849 format = ast_cdr_amaflags2int(v->value);
16850 if (format < 0) {
16851 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
16852 } else {
16853 peer->amaflags = format;
16855 } else if (!strcasecmp(v->name, "accountcode")) {
16856 ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
16857 } else if (!strcasecmp(v->name, "mohinterpret")
16858 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
16859 ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
16860 } else if (!strcasecmp(v->name, "mohsuggest")) {
16861 ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
16862 } else if (!strcasecmp(v->name, "mailbox")) {
16863 ast_copy_string(peer->mailbox, v->value, sizeof(peer->mailbox));
16864 } else if (!strcasecmp(v->name, "hasvoicemail")) {
16865 /* People expect that if 'hasvoicemail' is set, that the mailbox will
16866 * be also set, even if not explicitly specified. */
16867 if (ast_true(v->value) && ast_strlen_zero(peer->mailbox)) {
16868 ast_copy_string(peer->mailbox, name, sizeof(peer->mailbox));
16870 } else if (!strcasecmp(v->name, "subscribemwi")) {
16871 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
16872 } else if (!strcasecmp(v->name, "vmexten")) {
16873 ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
16874 } else if (!strcasecmp(v->name, "callgroup")) {
16875 peer->callgroup = ast_get_group(v->value);
16876 } else if (!strcasecmp(v->name, "allowtransfer")) {
16877 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
16878 } else if (!strcasecmp(v->name, "pickupgroup")) {
16879 peer->pickupgroup = ast_get_group(v->value);
16880 } else if (!strcasecmp(v->name, "allow")) {
16881 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
16882 } else if (!strcasecmp(v->name, "disallow")) {
16883 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
16884 } else if (!strcasecmp(v->name, "autoframing")) {
16885 peer->autoframing = ast_true(v->value);
16886 } else if (!strcasecmp(v->name, "rtptimeout")) {
16887 if ((sscanf(v->value, "%d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
16888 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16889 peer->rtptimeout = global_rtptimeout;
16891 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
16892 if ((sscanf(v->value, "%d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
16893 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16894 peer->rtpholdtimeout = global_rtpholdtimeout;
16896 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
16897 if ((sscanf(v->value, "%d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
16898 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
16899 peer->rtpkeepalive = global_rtpkeepalive;
16901 } else if (!strcasecmp(v->name, "setvar")) {
16902 /* Set peer channel variable */
16903 varname = ast_strdupa(v->value);
16904 if ((varval = strchr(varname, '='))) {
16905 *varval++ = '\0';
16906 if ((tmpvar = ast_variable_new(varname, varval))) {
16907 tmpvar->next = peer->chanvars;
16908 peer->chanvars = tmpvar;
16911 } else if (!strcasecmp(v->name, "qualify")) {
16912 if (!strcasecmp(v->value, "no")) {
16913 peer->maxms = 0;
16914 } else if (!strcasecmp(v->value, "yes")) {
16915 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
16916 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
16917 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);
16918 peer->maxms = 0;
16920 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
16921 peer->maxcallbitrate = atoi(v->value);
16922 if (peer->maxcallbitrate < 0)
16923 peer->maxcallbitrate = default_maxcallbitrate;
16926 if (!ast_strlen_zero(fullcontact)) {
16927 ast_copy_string(peer->fullcontact, fullcontact, sizeof(peer->fullcontact));
16930 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && realtime) {
16931 time_t nowtime = time(NULL);
16933 if ((nowtime - regseconds) > 0) {
16934 destroy_association(peer);
16935 memset(&peer->addr, 0, sizeof(peer->addr));
16936 if (option_debug)
16937 ast_log(LOG_DEBUG, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
16940 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
16941 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
16942 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
16943 global_allowsubscribe = TRUE; /* No global ban any more */
16944 if (!found && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && !ast_test_flag(&peer->flags[0], SIP_REALTIME))
16945 reg_source_db(peer);
16946 ASTOBJ_UNMARK(peer);
16947 ast_free_ha(oldha);
16948 return peer;
16951 /*! \brief Re-read SIP.conf config file
16952 \note This function reloads all config data, except for
16953 active peers (with registrations). They will only
16954 change configuration data at restart, not at reload.
16955 SIP debug and recordhistory state will not change
16957 static int reload_config(enum channelreloadreason reason)
16959 struct ast_config *cfg, *ucfg;
16960 struct ast_variable *v;
16961 struct sip_peer *peer;
16962 struct sip_user *user;
16963 struct ast_hostent ahp;
16964 char *cat, *stringp, *context, *oldregcontext;
16965 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
16966 struct hostent *hp;
16967 int format;
16968 struct ast_flags dummy[2];
16969 int auto_sip_domains = FALSE;
16970 struct sockaddr_in old_bindaddr = bindaddr;
16971 int registry_count = 0, peer_count = 0, user_count = 0;
16972 unsigned int temp_tos = 0;
16973 struct ast_flags debugflag = {0};
16975 cfg = ast_config_load(config);
16977 /* We *must* have a config file otherwise stop immediately */
16978 if (!cfg) {
16979 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
16980 return -1;
16983 if (option_debug > 3)
16984 ast_log(LOG_DEBUG, "--------------- SIP reload started\n");
16986 clear_realm_authentication(authl);
16987 clear_sip_domains();
16988 authl = NULL;
16990 /* First, destroy all outstanding registry calls */
16991 /* This is needed, since otherwise active registry entries will not be destroyed */
16992 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
16993 ASTOBJ_RDLOCK(iterator);
16994 if (iterator->call) {
16995 if (option_debug > 2)
16996 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
16997 /* This will also remove references to the registry */
16998 sip_destroy(iterator->call);
17000 ASTOBJ_UNLOCK(iterator);
17002 } while(0));
17004 /* Then, actually destroy users and registry */
17005 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
17006 if (option_debug > 3)
17007 ast_log(LOG_DEBUG, "--------------- Done destroying user list\n");
17008 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
17009 if (option_debug > 3)
17010 ast_log(LOG_DEBUG, "--------------- Done destroying registry list\n");
17011 ASTOBJ_CONTAINER_MARKALL(&peerl);
17013 /* Initialize copy of current global_regcontext for later use in removing stale contexts */
17014 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
17015 oldregcontext = oldcontexts;
17017 /* Clear all flags before setting default values */
17018 /* Preserve debugging settings for console */
17019 ast_copy_flags(&debugflag, &global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
17020 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
17021 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
17022 ast_copy_flags(&global_flags[1], &debugflag, SIP_PAGE2_DEBUG_CONSOLE);
17024 /* Reset IP addresses */
17025 memset(&bindaddr, 0, sizeof(bindaddr));
17026 ast_free_ha(localaddr);
17027 memset(&localaddr, 0, sizeof(localaddr));
17028 memset(&externip, 0, sizeof(externip));
17029 memset(&default_prefs, 0 , sizeof(default_prefs));
17030 outboundproxyip.sin_port = htons(STANDARD_SIP_PORT);
17031 outboundproxyip.sin_family = AF_INET; /* Type of address: IPv4 */
17032 ourport = STANDARD_SIP_PORT;
17033 srvlookup = DEFAULT_SRVLOOKUP;
17034 global_tos_sip = DEFAULT_TOS_SIP;
17035 global_tos_audio = DEFAULT_TOS_AUDIO;
17036 global_tos_video = DEFAULT_TOS_VIDEO;
17037 externhost[0] = '\0'; /* External host name (for behind NAT DynDNS support) */
17038 externexpire = 0; /* Expiration for DNS re-issuing */
17039 externrefresh = 10;
17040 memset(&outboundproxyip, 0, sizeof(outboundproxyip));
17042 /* Reset channel settings to default before re-configuring */
17043 allow_external_domains = DEFAULT_ALLOW_EXT_DOM; /* Allow external invites */
17044 global_regcontext[0] = '\0';
17045 expiry = DEFAULT_EXPIRY;
17046 global_notifyringing = DEFAULT_NOTIFYRINGING;
17047 global_limitonpeers = FALSE;
17048 global_directrtpsetup = FALSE; /* Experimental feature, disabled by default */
17049 global_notifyhold = FALSE;
17050 global_alwaysauthreject = 0;
17051 global_allowsubscribe = FALSE;
17052 ast_copy_string(global_useragent, DEFAULT_USERAGENT, sizeof(global_useragent));
17053 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
17054 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME))
17055 ast_copy_string(global_realm, DEFAULT_REALM, sizeof(global_realm));
17056 else
17057 ast_copy_string(global_realm, ast_config_AST_SYSTEM_NAME, sizeof(global_realm));
17058 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
17059 compactheaders = DEFAULT_COMPACTHEADERS;
17060 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
17061 global_regattempts_max = 0;
17062 pedanticsipchecking = DEFAULT_PEDANTIC;
17063 global_mwitime = DEFAULT_MWITIME;
17064 autocreatepeer = DEFAULT_AUTOCREATEPEER;
17065 global_autoframing = 0;
17066 global_allowguest = DEFAULT_ALLOWGUEST;
17067 global_rtptimeout = 0;
17068 global_rtpholdtimeout = 0;
17069 global_rtpkeepalive = 0;
17070 global_allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
17071 global_rtautoclear = 120;
17072 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE); /* Default for peers, users: TRUE */
17073 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP); /* Default for peers, users: TRUE */
17074 ast_set_flag(&global_flags[1], SIP_PAGE2_RTUPDATE);
17076 /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for peers and users */
17077 ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
17078 default_subscribecontext[0] = '\0';
17079 default_language[0] = '\0';
17080 default_fromdomain[0] = '\0';
17081 default_qualify = DEFAULT_QUALIFY;
17082 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
17083 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
17084 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
17085 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
17086 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833); /*!< Default DTMF setting: RFC2833 */
17087 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581); /*!< NAT support if requested by device with rport */
17088 ast_set_flag(&global_flags[0], SIP_CAN_REINVITE); /*!< Allow re-invites */
17090 /* Debugging settings, always default to off */
17091 dumphistory = FALSE;
17092 recordhistory = FALSE;
17093 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
17095 /* Misc settings for the channel */
17096 global_relaxdtmf = FALSE;
17097 global_callevents = FALSE;
17098 global_t1min = DEFAULT_T1MIN;
17100 global_matchexterniplocally = FALSE;
17102 /* Copy the default jb config over global_jbconf */
17103 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
17105 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT);
17107 /* Read the [general] config section of sip.conf (or from realtime config) */
17108 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
17109 if (handle_common_options(&global_flags[0], &dummy[0], v))
17110 continue;
17111 /* handle jb conf */
17112 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
17113 continue;
17115 /* Create the interface list */
17116 if (!strcasecmp(v->name, "context")) {
17117 ast_copy_string(default_context, v->value, sizeof(default_context));
17118 } else if (!strcasecmp(v->name, "subscribecontext")) {
17119 ast_copy_string(default_subscribecontext, v->value, sizeof(default_subscribecontext));
17120 } else if (!strcasecmp(v->name, "allowguest")) {
17121 global_allowguest = ast_true(v->value) ? 1 : 0;
17122 } else if (!strcasecmp(v->name, "realm")) {
17123 ast_copy_string(global_realm, v->value, sizeof(global_realm));
17124 } else if (!strcasecmp(v->name, "useragent")) {
17125 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
17126 if (option_debug)
17127 ast_log(LOG_DEBUG, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
17128 } else if (!strcasecmp(v->name, "allowtransfer")) {
17129 global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
17130 } else if (!strcasecmp(v->name, "rtcachefriends")) {
17131 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
17132 } else if (!strcasecmp(v->name, "rtsavesysname")) {
17133 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTSAVE_SYSNAME);
17134 } else if (!strcasecmp(v->name, "rtupdate")) {
17135 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTUPDATE);
17136 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
17137 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_IGNOREREGEXPIRE);
17138 } else if (!strcasecmp(v->name, "t1min")) {
17139 global_t1min = atoi(v->value);
17140 } else if (!strcasecmp(v->name, "rtautoclear")) {
17141 int i = atoi(v->value);
17142 if (i > 0)
17143 global_rtautoclear = i;
17144 else
17145 i = 0;
17146 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
17147 } else if (!strcasecmp(v->name, "usereqphone")) {
17148 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
17149 } else if (!strcasecmp(v->name, "relaxdtmf")) {
17150 global_relaxdtmf = ast_true(v->value);
17151 } else if (!strcasecmp(v->name, "checkmwi")) {
17152 if ((sscanf(v->value, "%d", &global_mwitime) != 1) || (global_mwitime < 0)) {
17153 ast_log(LOG_WARNING, "'%s' is not a valid MWI time setting at line %d. Using default (10).\n", v->value, v->lineno);
17154 global_mwitime = DEFAULT_MWITIME;
17156 } else if (!strcasecmp(v->name, "vmexten")) {
17157 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
17158 } else if (!strcasecmp(v->name, "rtptimeout")) {
17159 if ((sscanf(v->value, "%d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
17160 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
17161 global_rtptimeout = 0;
17163 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
17164 if ((sscanf(v->value, "%d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
17165 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
17166 global_rtpholdtimeout = 0;
17168 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
17169 if ((sscanf(v->value, "%d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
17170 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
17171 global_rtpkeepalive = 0;
17173 } else if (!strcasecmp(v->name, "compactheaders")) {
17174 compactheaders = ast_true(v->value);
17175 } else if (!strcasecmp(v->name, "notifymimetype")) {
17176 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
17177 } else if (!strncasecmp(v->name, "limitonpeer", 11)) {
17178 global_limitonpeers = ast_true(v->value);
17179 } else if (!strcasecmp(v->name, "directrtpsetup")) {
17180 global_directrtpsetup = ast_true(v->value);
17181 } else if (!strcasecmp(v->name, "notifyringing")) {
17182 global_notifyringing = ast_true(v->value);
17183 } else if (!strcasecmp(v->name, "notifyhold")) {
17184 global_notifyhold = ast_true(v->value);
17185 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
17186 global_alwaysauthreject = ast_true(v->value);
17187 } else if (!strcasecmp(v->name, "mohinterpret")
17188 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
17189 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
17190 } else if (!strcasecmp(v->name, "mohsuggest")) {
17191 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
17192 } else if (!strcasecmp(v->name, "language")) {
17193 ast_copy_string(default_language, v->value, sizeof(default_language));
17194 } else if (!strcasecmp(v->name, "regcontext")) {
17195 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
17196 stringp = newcontexts;
17197 /* Let's remove any contexts that are no longer defined in regcontext */
17198 cleanup_stale_contexts(stringp, oldregcontext);
17199 /* Create contexts if they don't exist already */
17200 while ((context = strsep(&stringp, "&"))) {
17201 if (!ast_context_find(context))
17202 ast_context_create(NULL, context,"SIP");
17204 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
17205 } else if (!strcasecmp(v->name, "callerid")) {
17206 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
17207 } else if (!strcasecmp(v->name, "fromdomain")) {
17208 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
17209 } else if (!strcasecmp(v->name, "outboundproxy")) {
17210 if (ast_get_ip_or_srv(&outboundproxyip, v->value, srvlookup ? "_sip._udp" : NULL) < 0)
17211 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", v->value);
17212 } else if (!strcasecmp(v->name, "outboundproxyport")) {
17213 /* Port needs to be after IP */
17214 sscanf(v->value, "%d", &format);
17215 outboundproxyip.sin_port = htons(format);
17216 } else if (!strcasecmp(v->name, "autocreatepeer")) {
17217 autocreatepeer = ast_true(v->value);
17218 } else if (!strcasecmp(v->name, "srvlookup")) {
17219 srvlookup = ast_true(v->value);
17220 } else if (!strcasecmp(v->name, "pedantic")) {
17221 pedanticsipchecking = ast_true(v->value);
17222 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
17223 max_expiry = atoi(v->value);
17224 if (max_expiry < 1)
17225 max_expiry = DEFAULT_MAX_EXPIRY;
17226 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
17227 min_expiry = atoi(v->value);
17228 if (min_expiry < 1)
17229 min_expiry = DEFAULT_MIN_EXPIRY;
17230 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
17231 default_expiry = atoi(v->value);
17232 if (default_expiry < 1)
17233 default_expiry = DEFAULT_DEFAULT_EXPIRY;
17234 } else if (!strcasecmp(v->name, "sipdebug")) { /* XXX maybe ast_set2_flags ? */
17235 if (ast_true(v->value))
17236 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
17237 } else if (!strcasecmp(v->name, "dumphistory")) {
17238 dumphistory = ast_true(v->value);
17239 } else if (!strcasecmp(v->name, "recordhistory")) {
17240 recordhistory = ast_true(v->value);
17241 } else if (!strcasecmp(v->name, "registertimeout")) {
17242 global_reg_timeout = atoi(v->value);
17243 if (global_reg_timeout < 1)
17244 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
17245 } else if (!strcasecmp(v->name, "registerattempts")) {
17246 global_regattempts_max = atoi(v->value);
17247 } else if (!strcasecmp(v->name, "bindaddr")) {
17248 if (!(hp = ast_gethostbyname(v->value, &ahp))) {
17249 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
17250 } else {
17251 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
17253 } else if (!strcasecmp(v->name, "localnet")) {
17254 struct ast_ha *na;
17255 if (!(na = ast_append_ha("d", v->value, localaddr)))
17256 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
17257 else
17258 localaddr = na;
17259 } else if (!strcasecmp(v->name, "localmask")) {
17260 ast_log(LOG_WARNING, "Use of localmask is no long supported -- use localnet with mask syntax\n");
17261 } else if (!strcasecmp(v->name, "externip")) {
17262 if (!(hp = ast_gethostbyname(v->value, &ahp)))
17263 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
17264 else
17265 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
17266 externexpire = 0;
17267 } else if (!strcasecmp(v->name, "externhost")) {
17268 ast_copy_string(externhost, v->value, sizeof(externhost));
17269 if (!(hp = ast_gethostbyname(externhost, &ahp)))
17270 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
17271 else
17272 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
17273 externexpire = time(NULL);
17274 } else if (!strcasecmp(v->name, "externrefresh")) {
17275 if (sscanf(v->value, "%d", &externrefresh) != 1) {
17276 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
17277 externrefresh = 10;
17279 } else if (!strcasecmp(v->name, "allow")) {
17280 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 1);
17281 } else if (!strcasecmp(v->name, "disallow")) {
17282 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 0);
17283 } else if (!strcasecmp(v->name, "autoframing")) {
17284 global_autoframing = ast_true(v->value);
17285 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
17286 allow_external_domains = ast_true(v->value);
17287 } else if (!strcasecmp(v->name, "autodomain")) {
17288 auto_sip_domains = ast_true(v->value);
17289 } else if (!strcasecmp(v->name, "domain")) {
17290 char *domain = ast_strdupa(v->value);
17291 char *context = strchr(domain, ',');
17293 if (context)
17294 *context++ = '\0';
17296 if (option_debug && ast_strlen_zero(context))
17297 ast_log(LOG_DEBUG, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
17298 if (ast_strlen_zero(domain))
17299 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
17300 else
17301 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, context ? ast_strip(context) : "");
17302 } else if (!strcasecmp(v->name, "register")) {
17303 if (sip_register(v->value, v->lineno) == 0)
17304 registry_count++;
17305 } else if (!strcasecmp(v->name, "tos")) {
17306 if (!ast_str2tos(v->value, &temp_tos)) {
17307 global_tos_sip = temp_tos;
17308 global_tos_audio = temp_tos;
17309 global_tos_video = temp_tos;
17310 ast_log(LOG_WARNING, "tos value at line %d is deprecated. See doc/ip-tos.txt for more information.\n", v->lineno);
17311 } else
17312 ast_log(LOG_WARNING, "Invalid tos value at line %d, See doc/ip-tos.txt for more information.\n", v->lineno);
17313 } else if (!strcasecmp(v->name, "tos_sip")) {
17314 if (ast_str2tos(v->value, &global_tos_sip))
17315 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, recommended value is 'cs3'. See doc/ip-tos.txt.\n", v->lineno);
17316 } else if (!strcasecmp(v->name, "tos_audio")) {
17317 if (ast_str2tos(v->value, &global_tos_audio))
17318 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, recommended value is 'ef'. See doc/ip-tos.txt.\n", v->lineno);
17319 } else if (!strcasecmp(v->name, "tos_video")) {
17320 if (ast_str2tos(v->value, &global_tos_video))
17321 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, recommended value is 'af41'. See doc/ip-tos.txt.\n", v->lineno);
17322 } else if (!strcasecmp(v->name, "bindport")) {
17323 if (sscanf(v->value, "%d", &ourport) == 1) {
17324 bindaddr.sin_port = htons(ourport);
17325 } else {
17326 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
17328 } else if (!strcasecmp(v->name, "qualify")) {
17329 if (!strcasecmp(v->value, "no")) {
17330 default_qualify = 0;
17331 } else if (!strcasecmp(v->value, "yes")) {
17332 default_qualify = DEFAULT_MAXMS;
17333 } else if (sscanf(v->value, "%d", &default_qualify) != 1) {
17334 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
17335 default_qualify = 0;
17337 } else if (!strcasecmp(v->name, "callevents")) {
17338 global_callevents = ast_true(v->value);
17339 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
17340 default_maxcallbitrate = atoi(v->value);
17341 if (default_maxcallbitrate < 0)
17342 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
17343 } else if (!strcasecmp(v->name, "matchexterniplocally")) {
17344 global_matchexterniplocally = ast_true(v->value);
17348 if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
17349 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
17350 allow_external_domains = 1;
17353 /* Build list of authentication to various SIP realms, i.e. service providers */
17354 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
17355 /* Format for authentication is auth = username:password@realm */
17356 if (!strcasecmp(v->name, "auth"))
17357 authl = add_realm_authentication(authl, v->value, v->lineno);
17360 ucfg = ast_config_load("users.conf");
17361 if (ucfg) {
17362 struct ast_variable *gen;
17363 int genhassip, genregistersip;
17364 const char *hassip, *registersip;
17366 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
17367 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
17368 gen = ast_variable_browse(ucfg, "general");
17369 cat = ast_category_browse(ucfg, NULL);
17370 while (cat) {
17371 if (strcasecmp(cat, "general")) {
17372 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
17373 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
17374 if (ast_true(hassip) || (!hassip && genhassip)) {
17375 user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
17376 if (user) {
17377 ASTOBJ_CONTAINER_LINK(&userl,user);
17378 ASTOBJ_UNREF(user, sip_destroy_user);
17379 user_count++;
17381 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
17382 if (peer) {
17383 ast_device_state_changed("SIP/%s", peer->name);
17384 ASTOBJ_CONTAINER_LINK(&peerl,peer);
17385 ASTOBJ_UNREF(peer, sip_destroy_peer);
17386 peer_count++;
17389 if (ast_true(registersip) || (!registersip && genregistersip)) {
17390 char tmp[256];
17391 const char *host = ast_variable_retrieve(ucfg, cat, "host");
17392 const char *username = ast_variable_retrieve(ucfg, cat, "username");
17393 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
17394 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
17395 if (!host)
17396 host = ast_variable_retrieve(ucfg, "general", "host");
17397 if (!username)
17398 username = ast_variable_retrieve(ucfg, "general", "username");
17399 if (!secret)
17400 secret = ast_variable_retrieve(ucfg, "general", "secret");
17401 if (!contact)
17402 contact = "s";
17403 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
17404 if (!ast_strlen_zero(secret))
17405 snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
17406 else
17407 snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
17408 if (sip_register(tmp, 0) == 0)
17409 registry_count++;
17413 cat = ast_category_browse(ucfg, cat);
17415 ast_config_destroy(ucfg);
17419 /* Load peers, users and friends */
17420 cat = NULL;
17421 while ( (cat = ast_category_browse(cfg, cat)) ) {
17422 const char *utype;
17423 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
17424 continue;
17425 utype = ast_variable_retrieve(cfg, cat, "type");
17426 if (!utype) {
17427 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
17428 continue;
17429 } else {
17430 int is_user = 0, is_peer = 0;
17431 if (!strcasecmp(utype, "user"))
17432 is_user = 1;
17433 else if (!strcasecmp(utype, "friend"))
17434 is_user = is_peer = 1;
17435 else if (!strcasecmp(utype, "peer"))
17436 is_peer = 1;
17437 else {
17438 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
17439 continue;
17441 if (is_user) {
17442 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
17443 if (user) {
17444 ASTOBJ_CONTAINER_LINK(&userl,user);
17445 ASTOBJ_UNREF(user, sip_destroy_user);
17446 user_count++;
17449 if (is_peer) {
17450 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
17451 if (peer) {
17452 ASTOBJ_CONTAINER_LINK(&peerl,peer);
17453 ASTOBJ_UNREF(peer, sip_destroy_peer);
17454 peer_count++;
17459 if (ast_find_ourip(&__ourip, bindaddr)) {
17460 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
17461 ast_config_destroy(cfg);
17462 return 0;
17464 if (!ntohs(bindaddr.sin_port))
17465 bindaddr.sin_port = ntohs(STANDARD_SIP_PORT);
17466 bindaddr.sin_family = AF_INET;
17467 ast_mutex_lock(&netlock);
17468 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
17469 close(sipsock);
17470 sipsock = -1;
17472 if (sipsock < 0) {
17473 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
17474 if (sipsock < 0) {
17475 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
17476 ast_config_destroy(cfg);
17477 return -1;
17478 } else {
17479 /* Allow SIP clients on the same host to access us: */
17480 const int reuseFlag = 1;
17482 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
17483 (const char*)&reuseFlag,
17484 sizeof reuseFlag);
17486 ast_enable_packet_fragmentation(sipsock);
17488 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
17489 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
17490 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
17491 strerror(errno));
17492 close(sipsock);
17493 sipsock = -1;
17494 } else {
17495 if (option_verbose > 1) {
17496 ast_verbose(VERBOSE_PREFIX_2 "SIP Listening on %s:%d\n",
17497 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
17498 ast_verbose(VERBOSE_PREFIX_2 "Using SIP TOS: %s\n", ast_tos2str(global_tos_sip));
17500 if (setsockopt(sipsock, IPPROTO_IP, IP_TOS, &global_tos_sip, sizeof(global_tos_sip)))
17501 ast_log(LOG_WARNING, "Unable to set SIP TOS to %s\n", ast_tos2str(global_tos_sip));
17505 ast_mutex_unlock(&netlock);
17507 /* Add default domains - host name, IP address and IP:port */
17508 /* Only do this if user added any sip domain with "localdomains" */
17509 /* In order to *not* break backwards compatibility */
17510 /* Some phones address us at IP only, some with additional port number */
17511 if (auto_sip_domains) {
17512 char temp[MAXHOSTNAMELEN];
17514 /* First our default IP address */
17515 if (bindaddr.sin_addr.s_addr)
17516 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
17517 else
17518 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
17520 /* Our extern IP address, if configured */
17521 if (externip.sin_addr.s_addr)
17522 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
17524 /* Extern host name (NAT traversal support) */
17525 if (!ast_strlen_zero(externhost))
17526 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
17528 /* Our host name */
17529 if (!gethostname(temp, sizeof(temp)))
17530 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
17533 /* Release configuration from memory */
17534 ast_config_destroy(cfg);
17536 /* Load the list of manual NOTIFY types to support */
17537 if (notify_types)
17538 ast_config_destroy(notify_types);
17539 notify_types = ast_config_load(notify_config);
17541 /* Done, tell the manager */
17542 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);
17544 return 0;
17547 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
17549 struct sip_pvt *p;
17550 struct ast_udptl *udptl = NULL;
17552 p = chan->tech_pvt;
17553 if (!p)
17554 return NULL;
17556 ast_mutex_lock(&p->lock);
17557 if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
17558 udptl = p->udptl;
17559 ast_mutex_unlock(&p->lock);
17560 return udptl;
17563 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
17565 struct sip_pvt *p;
17567 p = chan->tech_pvt;
17568 if (!p)
17569 return -1;
17570 ast_mutex_lock(&p->lock);
17571 if (udptl)
17572 ast_udptl_get_peer(udptl, &p->udptlredirip);
17573 else
17574 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
17575 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
17576 if (!p->pendinginvite) {
17577 if (option_debug > 2) {
17578 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);
17580 transmit_reinvite_with_t38_sdp(p);
17581 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17582 if (option_debug > 2) {
17583 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);
17585 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17588 /* Reset lastrtprx timer */
17589 p->lastrtprx = p->lastrtptx = time(NULL);
17590 ast_mutex_unlock(&p->lock);
17591 return 0;
17594 /*! \brief Handle T38 reinvite
17595 \todo Make sure we don't destroy the call if we can't handle the re-invite.
17596 Nothing should be changed until we have processed the SDP and know that we
17597 can handle it.
17599 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite)
17601 struct sip_pvt *p;
17602 int flag = 0;
17604 p = chan->tech_pvt;
17605 if (!p || !pvt->udptl)
17606 return -1;
17608 /* Setup everything on the other side like offered/responded from first side */
17609 ast_mutex_lock(&p->lock);
17611 /*! \todo check if this is not set earlier when setting up the PVT. If not
17612 maybe it should move there. */
17613 p->t38.jointcapability = p->t38.peercapability = pvt->t38.jointcapability;
17615 ast_udptl_set_far_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
17616 ast_udptl_set_local_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
17617 ast_udptl_set_error_correction_scheme(p->udptl, ast_udptl_get_error_correction_scheme(pvt->udptl));
17619 if (reinvite) { /* If we are handling sending re-invite to the other side of the bridge */
17620 /*! \note The SIP_CAN_REINVITE flag is for RTP media redirects,
17621 not really T38 re-invites which are different. In this
17622 case it's used properly, to see if we can reinvite over
17623 NAT
17625 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
17626 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
17627 flag =1;
17628 } else {
17629 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
17631 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
17632 if (!p->pendinginvite) {
17633 if (option_debug > 2) {
17634 if (flag)
17635 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));
17636 else
17637 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));
17639 transmit_reinvite_with_t38_sdp(p);
17640 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17641 if (option_debug > 2) {
17642 if (flag)
17643 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));
17644 else
17645 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));
17647 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17650 /* Reset lastrtprx timer */
17651 p->lastrtprx = p->lastrtptx = time(NULL);
17652 ast_mutex_unlock(&p->lock);
17653 return 0;
17654 } else { /* If we are handling sending 200 OK to the other side of the bridge */
17655 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
17656 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
17657 flag = 1;
17658 } else {
17659 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
17661 if (option_debug > 2) {
17662 if (flag)
17663 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));
17664 else
17665 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));
17667 pvt->t38.state = T38_ENABLED;
17668 p->t38.state = T38_ENABLED;
17669 if (option_debug > 1) {
17670 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", pvt->t38.state, pvt->owner ? pvt->owner->name : "<none>");
17671 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
17673 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
17674 p->lastrtprx = p->lastrtptx = time(NULL);
17675 ast_mutex_unlock(&p->lock);
17676 return 0;
17681 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
17682 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
17684 struct sip_pvt *p = NULL;
17685 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
17687 if (!(p = chan->tech_pvt))
17688 return AST_RTP_GET_FAILED;
17690 ast_mutex_lock(&p->lock);
17691 if (!(p->rtp)) {
17692 ast_mutex_unlock(&p->lock);
17693 return AST_RTP_GET_FAILED;
17696 *rtp = p->rtp;
17698 if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT))
17699 res = AST_RTP_TRY_PARTIAL;
17700 else if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
17701 res = AST_RTP_TRY_NATIVE;
17702 else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
17703 res = AST_RTP_GET_FAILED;
17705 ast_mutex_unlock(&p->lock);
17707 return res;
17710 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
17711 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
17713 struct sip_pvt *p = NULL;
17714 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
17716 if (!(p = chan->tech_pvt))
17717 return AST_RTP_GET_FAILED;
17719 ast_mutex_lock(&p->lock);
17720 if (!(p->vrtp)) {
17721 ast_mutex_unlock(&p->lock);
17722 return AST_RTP_GET_FAILED;
17725 *rtp = p->vrtp;
17727 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
17728 res = AST_RTP_TRY_NATIVE;
17730 ast_mutex_unlock(&p->lock);
17732 return res;
17735 /*! \brief Set the RTP peer for this call */
17736 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
17738 struct sip_pvt *p;
17739 int changed = 0;
17741 p = chan->tech_pvt;
17742 if (!p)
17743 return -1;
17745 /* Disable early RTP bridge */
17746 if (chan->_state != AST_STATE_UP && !global_directrtpsetup) /* We are in early state */
17747 return 0;
17749 ast_mutex_lock(&p->lock);
17750 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) {
17751 /* If we're destroyed, don't bother */
17752 ast_mutex_unlock(&p->lock);
17753 return 0;
17756 /* if this peer cannot handle reinvites of the media stream to devices
17757 that are known to be behind a NAT, then stop the process now
17759 if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
17760 ast_mutex_unlock(&p->lock);
17761 return 0;
17764 if (rtp) {
17765 changed |= ast_rtp_get_peer(rtp, &p->redirip);
17766 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
17767 memset(&p->redirip, 0, sizeof(p->redirip));
17768 changed = 1;
17770 if (vrtp) {
17771 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
17772 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
17773 memset(&p->vredirip, 0, sizeof(p->vredirip));
17774 changed = 1;
17776 if (codecs) {
17777 if ((p->redircodecs != codecs)) {
17778 p->redircodecs = codecs;
17779 changed = 1;
17781 if ((p->capability & codecs) != p->capability) {
17782 p->jointcapability &= codecs;
17783 p->capability &= codecs;
17784 changed = 1;
17787 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
17788 if (chan->_state != AST_STATE_UP) { /* We are in early state */
17789 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
17790 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
17791 if (option_debug)
17792 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));
17793 } else if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
17794 if (option_debug > 2) {
17795 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));
17797 transmit_reinvite_with_sdp(p);
17798 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17799 if (option_debug > 2) {
17800 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));
17802 /* We have a pending Invite. Send re-invite when we're done with the invite */
17803 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17806 /* Reset lastrtprx timer */
17807 p->lastrtprx = p->lastrtptx = time(NULL);
17808 ast_mutex_unlock(&p->lock);
17809 return 0;
17812 static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
17813 static char *descrip_dtmfmode = "SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
17814 static char *app_dtmfmode = "SIPDtmfMode";
17816 static char *app_sipaddheader = "SIPAddHeader";
17817 static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
17819 static char *descrip_sipaddheader = ""
17820 " SIPAddHeader(Header: Content)\n"
17821 "Adds a header to a SIP call placed with DIAL.\n"
17822 "Remember to user the X-header if you are adding non-standard SIP\n"
17823 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
17824 "Adding the wrong headers may jeopardize the SIP dialog.\n"
17825 "Always returns 0\n";
17828 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
17829 static int sip_dtmfmode(struct ast_channel *chan, void *data)
17831 struct sip_pvt *p;
17832 char *mode;
17833 if (data)
17834 mode = (char *)data;
17835 else {
17836 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
17837 return 0;
17839 ast_channel_lock(chan);
17840 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
17841 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
17842 ast_channel_unlock(chan);
17843 return 0;
17845 p = chan->tech_pvt;
17846 if (!p) {
17847 ast_channel_unlock(chan);
17848 return 0;
17850 ast_mutex_lock(&p->lock);
17851 if (!strcasecmp(mode,"info")) {
17852 ast_clear_flag(&p->flags[0], SIP_DTMF);
17853 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
17854 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
17855 } else if (!strcasecmp(mode,"rfc2833")) {
17856 ast_clear_flag(&p->flags[0], SIP_DTMF);
17857 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
17858 p->jointnoncodeccapability |= AST_RTP_DTMF;
17859 } else if (!strcasecmp(mode,"inband")) {
17860 ast_clear_flag(&p->flags[0], SIP_DTMF);
17861 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
17862 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
17863 } else
17864 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n",mode);
17865 if (p->rtp)
17866 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
17867 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
17868 if (!p->vad) {
17869 p->vad = ast_dsp_new();
17870 ast_dsp_set_features(p->vad, DSP_FEATURE_DTMF_DETECT);
17872 } else {
17873 if (p->vad) {
17874 ast_dsp_free(p->vad);
17875 p->vad = NULL;
17878 ast_mutex_unlock(&p->lock);
17879 ast_channel_unlock(chan);
17880 return 0;
17883 /*! \brief Add a SIP header to an outbound INVITE */
17884 static int sip_addheader(struct ast_channel *chan, void *data)
17886 int no = 0;
17887 int ok = FALSE;
17888 char varbuf[30];
17889 char *inbuf = (char *) data;
17891 if (ast_strlen_zero(inbuf)) {
17892 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
17893 return 0;
17895 ast_channel_lock(chan);
17897 /* Check for headers */
17898 while (!ok && no <= 50) {
17899 no++;
17900 snprintf(varbuf, sizeof(varbuf), "_SIPADDHEADER%.2d", no);
17902 /* Compare without the leading underscore */
17903 if( (pbx_builtin_getvar_helper(chan, (const char *) varbuf + 1) == (const char *) NULL) )
17904 ok = TRUE;
17906 if (ok) {
17907 pbx_builtin_setvar_helper (chan, varbuf, inbuf);
17908 if (sipdebug)
17909 ast_log(LOG_DEBUG,"SIP Header added \"%s\" as %s\n", inbuf, varbuf);
17910 } else {
17911 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
17913 ast_channel_unlock(chan);
17914 return 0;
17917 /*! \brief Transfer call before connect with a 302 redirect
17918 \note Called by the transfer() dialplan application through the sip_transfer()
17919 pbx interface function if the call is in ringing state
17920 \todo Fix this function so that we wait for reply to the REFER and
17921 react to errors, denials or other issues the other end might have.
17923 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
17925 char *cdest;
17926 char *extension, *host, *port;
17927 char tmp[80];
17929 cdest = ast_strdupa(dest);
17931 extension = strsep(&cdest, "@");
17932 host = strsep(&cdest, ":");
17933 port = strsep(&cdest, ":");
17934 if (ast_strlen_zero(extension)) {
17935 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
17936 return 0;
17939 /* we'll issue the redirect message here */
17940 if (!host) {
17941 char *localtmp;
17942 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
17943 if (ast_strlen_zero(tmp)) {
17944 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
17945 return 0;
17947 if ((localtmp = strcasestr(tmp, "sip:")) && (localtmp = strchr(localtmp, '@'))) {
17948 char lhost[80], lport[80];
17949 memset(lhost, 0, sizeof(lhost));
17950 memset(lport, 0, sizeof(lport));
17951 localtmp++;
17952 /* This is okey because lhost and lport are as big as tmp */
17953 sscanf(localtmp, "%[^<>:; ]:%[^<>:; ]", lhost, lport);
17954 if (ast_strlen_zero(lhost)) {
17955 ast_log(LOG_ERROR, "Can't find the host address\n");
17956 return 0;
17958 host = ast_strdupa(lhost);
17959 if (!ast_strlen_zero(lport)) {
17960 port = ast_strdupa(lport);
17965 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
17966 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
17968 sip_scheddestroy(p, SIP_TRANS_TIMEOUT); /* Make sure we stop send this reply. */
17969 sip_alreadygone(p);
17970 return 0;
17973 /*! \brief Return SIP UA's codec (part of the RTP interface) */
17974 static int sip_get_codec(struct ast_channel *chan)
17976 struct sip_pvt *p = chan->tech_pvt;
17977 return p->peercapability ? p->peercapability : p->capability;
17980 /*! \brief Send a poke to all known peers
17981 Space them out 100 ms apart
17982 XXX We might have a cool algorithm for this or use random - any suggestions?
17984 static void sip_poke_all_peers(void)
17986 int ms = 0;
17988 if (!speerobjs) /* No peers, just give up */
17989 return;
17991 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
17992 ASTOBJ_WRLOCK(iterator);
17993 if (!AST_SCHED_DEL(sched, iterator->pokeexpire)) {
17994 struct sip_peer *peer_ptr = iterator;
17995 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
17997 ms += 100;
17998 iterator->pokeexpire = ast_sched_add(sched, ms, sip_poke_peer_s, ASTOBJ_REF(iterator));
17999 if (iterator->pokeexpire == -1) {
18000 struct sip_peer *peer_ptr = iterator;
18001 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
18003 ASTOBJ_UNLOCK(iterator);
18004 } while (0)
18008 /*! \brief Send all known registrations */
18009 static void sip_send_all_registers(void)
18011 int ms;
18012 int regspacing;
18013 if (!regobjs)
18014 return;
18015 regspacing = default_expiry * 1000/regobjs;
18016 if (regspacing > 100)
18017 regspacing = 100;
18018 ms = regspacing;
18019 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
18020 ASTOBJ_WRLOCK(iterator);
18021 AST_SCHED_DEL(sched, iterator->expire);
18022 ms += regspacing;
18023 iterator->expire = ast_sched_add(sched, ms, sip_reregister, iterator);
18024 ASTOBJ_UNLOCK(iterator);
18025 } while (0)
18029 /*! \brief Reload module */
18030 static int sip_do_reload(enum channelreloadreason reason)
18032 reload_config(reason);
18034 /* Prune peers who still are supposed to be deleted */
18035 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
18036 if (option_debug > 3)
18037 ast_log(LOG_DEBUG, "--------------- Done destroying pruned peers\n");
18039 /* Send qualify (OPTIONS) to all peers */
18040 sip_poke_all_peers();
18042 /* Register with all services */
18043 sip_send_all_registers();
18045 if (option_debug > 3)
18046 ast_log(LOG_DEBUG, "--------------- SIP reload done\n");
18048 return 0;
18051 /*! \brief Force reload of module from cli */
18052 static int sip_reload(int fd, int argc, char *argv[])
18054 ast_mutex_lock(&sip_reload_lock);
18055 if (sip_reloading)
18056 ast_verbose("Previous SIP reload not yet done\n");
18057 else {
18058 sip_reloading = TRUE;
18059 if (fd)
18060 sip_reloadreason = CHANNEL_CLI_RELOAD;
18061 else
18062 sip_reloadreason = CHANNEL_MODULE_RELOAD;
18064 ast_mutex_unlock(&sip_reload_lock);
18065 restart_monitor();
18067 return 0;
18070 /*! \brief Part of Asterisk module interface */
18071 static int reload(void)
18073 return sip_reload(0, 0, NULL);
18076 static struct ast_cli_entry cli_sip_debug_deprecated =
18077 { { "sip", "debug", NULL },
18078 sip_do_debug_deprecated, "Enable SIP debugging",
18079 debug_usage };
18081 static struct ast_cli_entry cli_sip_no_debug_deprecated =
18082 { { "sip", "no", "debug", NULL },
18083 sip_no_debug_deprecated, "Disable SIP debugging",
18084 debug_usage };
18086 static struct ast_cli_entry cli_sip[] = {
18087 { { "sip", "show", "channels", NULL },
18088 sip_show_channels, "List active SIP channels",
18089 show_channels_usage },
18091 { { "sip", "show", "domains", NULL },
18092 sip_show_domains, "List our local SIP domains.",
18093 show_domains_usage },
18095 { { "sip", "show", "inuse", NULL },
18096 sip_show_inuse, "List all inuse/limits",
18097 show_inuse_usage },
18099 { { "sip", "show", "objects", NULL },
18100 sip_show_objects, "List all SIP object allocations",
18101 show_objects_usage },
18103 { { "sip", "show", "peers", NULL },
18104 sip_show_peers, "List defined SIP peers",
18105 show_peers_usage },
18107 { { "sip", "show", "registry", NULL },
18108 sip_show_registry, "List SIP registration status",
18109 show_reg_usage },
18111 { { "sip", "show", "settings", NULL },
18112 sip_show_settings, "Show SIP global settings",
18113 show_settings_usage },
18115 { { "sip", "show", "subscriptions", NULL },
18116 sip_show_subscriptions, "List active SIP subscriptions",
18117 show_subscriptions_usage },
18119 { { "sip", "show", "users", NULL },
18120 sip_show_users, "List defined SIP users",
18121 show_users_usage },
18123 { { "sip", "notify", NULL },
18124 sip_notify, "Send a notify packet to a SIP peer",
18125 notify_usage, complete_sipnotify },
18127 { { "sip", "show", "channel", NULL },
18128 sip_show_channel, "Show detailed SIP channel info",
18129 show_channel_usage, complete_sipch },
18131 { { "sip", "show", "history", NULL },
18132 sip_show_history, "Show SIP dialog history",
18133 show_history_usage, complete_sipch },
18135 { { "sip", "show", "peer", NULL },
18136 sip_show_peer, "Show details on specific SIP peer",
18137 show_peer_usage, complete_sip_show_peer },
18139 { { "sip", "show", "user", NULL },
18140 sip_show_user, "Show details on specific SIP user",
18141 show_user_usage, complete_sip_show_user },
18143 { { "sip", "prune", "realtime", NULL },
18144 sip_prune_realtime, "Prune cached Realtime object(s)",
18145 prune_realtime_usage },
18147 { { "sip", "prune", "realtime", "peer", NULL },
18148 sip_prune_realtime, "Prune cached Realtime peer(s)",
18149 prune_realtime_usage, complete_sip_prune_realtime_peer },
18151 { { "sip", "prune", "realtime", "user", NULL },
18152 sip_prune_realtime, "Prune cached Realtime user(s)",
18153 prune_realtime_usage, complete_sip_prune_realtime_user },
18155 { { "sip", "set", "debug", NULL },
18156 sip_do_debug, "Enable SIP debugging",
18157 debug_usage, NULL, &cli_sip_debug_deprecated },
18159 { { "sip", "set", "debug", "ip", NULL },
18160 sip_do_debug, "Enable SIP debugging on IP",
18161 debug_usage },
18163 { { "sip", "set", "debug", "peer", NULL },
18164 sip_do_debug, "Enable SIP debugging on Peername",
18165 debug_usage, complete_sip_debug_peer },
18167 { { "sip", "set", "debug", "off", NULL },
18168 sip_no_debug, "Disable SIP debugging",
18169 no_debug_usage, NULL, &cli_sip_no_debug_deprecated },
18171 { { "sip", "history", NULL },
18172 sip_do_history, "Enable SIP history",
18173 history_usage },
18175 { { "sip", "history", "off", NULL },
18176 sip_no_history, "Disable SIP history",
18177 no_history_usage },
18179 { { "sip", "reload", NULL },
18180 sip_reload, "Reload SIP configuration",
18181 sip_reload_usage },
18184 /*! \brief PBX load module - initialization */
18185 static int load_module(void)
18187 ASTOBJ_CONTAINER_INIT(&userl); /* User object list */
18188 ASTOBJ_CONTAINER_INIT(&peerl); /* Peer object list */
18189 ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list */
18191 if (!(sched = sched_context_create())) {
18192 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
18193 return AST_MODULE_LOAD_FAILURE;
18196 if (!(io = io_context_create())) {
18197 ast_log(LOG_ERROR, "Unable to create I/O context\n");
18198 sched_context_destroy(sched);
18199 return AST_MODULE_LOAD_FAILURE;
18202 sip_reloadreason = CHANNEL_MODULE_LOAD;
18204 if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
18205 return AST_MODULE_LOAD_DECLINE;
18207 /* Make sure we can register our sip channel type */
18208 if (ast_channel_register(&sip_tech)) {
18209 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
18210 io_context_destroy(io);
18211 sched_context_destroy(sched);
18212 return AST_MODULE_LOAD_FAILURE;
18215 /* Register all CLI functions for SIP */
18216 ast_cli_register_multiple(cli_sip, sizeof(cli_sip)/ sizeof(struct ast_cli_entry));
18218 /* Tell the RTP subdriver that we're here */
18219 ast_rtp_proto_register(&sip_rtp);
18221 /* Tell the UDPTL subdriver that we're here */
18222 ast_udptl_proto_register(&sip_udptl);
18224 /* Register dialplan applications */
18225 ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
18226 ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
18228 /* Register dialplan functions */
18229 ast_custom_function_register(&sip_header_function);
18230 ast_custom_function_register(&sippeer_function);
18231 ast_custom_function_register(&sipchaninfo_function);
18232 ast_custom_function_register(&checksipdomain_function);
18234 /* Register manager commands */
18235 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM, manager_sip_show_peers,
18236 "List SIP peers (text format)", mandescr_show_peers);
18237 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM, manager_sip_show_peer,
18238 "Show SIP peer (text format)", mandescr_show_peer);
18240 sip_poke_all_peers();
18241 sip_send_all_registers();
18243 /* And start the monitor for the first time */
18244 restart_monitor();
18246 return AST_MODULE_LOAD_SUCCESS;
18249 /*! \brief PBX unload module API */
18250 static int unload_module(void)
18252 struct sip_pvt *p, *pl;
18254 /* First, take us out of the channel type list */
18255 ast_channel_unregister(&sip_tech);
18257 /* Unregister dial plan functions */
18258 ast_custom_function_unregister(&sipchaninfo_function);
18259 ast_custom_function_unregister(&sippeer_function);
18260 ast_custom_function_unregister(&sip_header_function);
18261 ast_custom_function_unregister(&checksipdomain_function);
18263 /* Unregister dial plan applications */
18264 ast_unregister_application(app_dtmfmode);
18265 ast_unregister_application(app_sipaddheader);
18267 /* Unregister CLI commands */
18268 ast_cli_unregister_multiple(cli_sip, sizeof(cli_sip) / sizeof(struct ast_cli_entry));
18270 /* Disconnect from the RTP subsystem */
18271 ast_rtp_proto_unregister(&sip_rtp);
18273 /* Disconnect from UDPTL */
18274 ast_udptl_proto_unregister(&sip_udptl);
18276 /* Unregister AMI actions */
18277 ast_manager_unregister("SIPpeers");
18278 ast_manager_unregister("SIPshowpeer");
18280 ast_mutex_lock(&iflock);
18281 /* Hangup all interfaces if they have an owner */
18282 for (p = iflist; p ; p = p->next) {
18283 if (p->owner)
18284 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
18286 ast_mutex_unlock(&iflock);
18288 ast_mutex_lock(&monlock);
18289 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
18290 pthread_cancel(monitor_thread);
18291 pthread_kill(monitor_thread, SIGURG);
18292 pthread_join(monitor_thread, NULL);
18294 monitor_thread = AST_PTHREADT_STOP;
18295 ast_mutex_unlock(&monlock);
18297 restartdestroy:
18298 ast_mutex_lock(&iflock);
18299 /* Destroy all the interfaces and free their memory */
18300 p = iflist;
18301 while (p) {
18302 pl = p;
18303 p = p->next;
18304 if (__sip_destroy(pl, TRUE) < 0) {
18305 /* Something is still bridged, let it react to getting a hangup */
18306 iflist = p;
18307 ast_mutex_unlock(&iflock);
18308 usleep(1);
18309 goto restartdestroy;
18312 iflist = NULL;
18313 ast_mutex_unlock(&iflock);
18315 /* Free memory for local network address mask */
18316 ast_free_ha(localaddr);
18318 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
18319 ASTOBJ_CONTAINER_DESTROY(&userl);
18320 ASTOBJ_CONTAINER_DESTROYALL(&peerl, sip_destroy_peer);
18321 ASTOBJ_CONTAINER_DESTROY(&peerl);
18322 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
18323 ASTOBJ_CONTAINER_DESTROY(&regl);
18325 clear_realm_authentication(authl);
18326 clear_sip_domains();
18327 close(sipsock);
18328 sched_context_destroy(sched);
18330 return 0;
18333 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
18334 .load = load_module,
18335 .unload = unload_module,
18336 .reload = reload,