Merged revisions 57118 via svnmerge from
[asterisk-bristuff.git] / channels / chan_sip.c
blobc99c330da661d79801a73571406d97615922de4f
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
91 #include "asterisk.h"
93 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
95 #include <stdio.h>
96 #include <ctype.h>
97 #include <string.h>
98 #include <unistd.h>
99 #include <sys/socket.h>
100 #include <sys/ioctl.h>
101 #include <net/if.h>
102 #include <errno.h>
103 #include <stdlib.h>
104 #include <fcntl.h>
105 #include <netdb.h>
106 #include <signal.h>
107 #include <sys/signal.h>
108 #include <netinet/in.h>
109 #include <netinet/in_systm.h>
110 #include <arpa/inet.h>
111 #include <netinet/ip.h>
112 #include <regex.h>
114 #include "asterisk/lock.h"
115 #include "asterisk/channel.h"
116 #include "asterisk/config.h"
117 #include "asterisk/logger.h"
118 #include "asterisk/module.h"
119 #include "asterisk/pbx.h"
120 #include "asterisk/options.h"
121 #include "asterisk/sched.h"
122 #include "asterisk/io.h"
123 #include "asterisk/rtp.h"
124 #include "asterisk/udptl.h"
125 #include "asterisk/acl.h"
126 #include "asterisk/manager.h"
127 #include "asterisk/callerid.h"
128 #include "asterisk/cli.h"
129 #include "asterisk/app.h"
130 #include "asterisk/musiconhold.h"
131 #include "asterisk/dsp.h"
132 #include "asterisk/features.h"
133 #include "asterisk/srv.h"
134 #include "asterisk/astdb.h"
135 #include "asterisk/causes.h"
136 #include "asterisk/utils.h"
137 #include "asterisk/file.h"
138 #include "asterisk/astobj.h"
139 #include "asterisk/devicestate.h"
140 #include "asterisk/linkedlists.h"
141 #include "asterisk/stringfields.h"
142 #include "asterisk/monitor.h"
143 #include "asterisk/localtime.h"
144 #include "asterisk/abstract_jb.h"
145 #include "asterisk/compiler.h"
146 #include "asterisk/threadstorage.h"
147 #include "asterisk/translate.h"
149 #ifndef FALSE
150 #define FALSE 0
151 #endif
153 #ifndef TRUE
154 #define TRUE 1
155 #endif
157 #define VIDEO_CODEC_MASK 0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
158 #ifndef IPTOS_MINCOST
159 #define IPTOS_MINCOST 0x02
160 #endif
162 /* #define VOCAL_DATA_HACK */
164 #define DEFAULT_DEFAULT_EXPIRY 120
165 #define DEFAULT_MIN_EXPIRY 60
166 #define DEFAULT_MAX_EXPIRY 3600
167 #define DEFAULT_REGISTRATION_TIMEOUT 20
168 #define DEFAULT_MAX_FORWARDS "70"
170 /* guard limit must be larger than guard secs */
171 /* guard min must be < 1000, and should be >= 250 */
172 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
173 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
174 EXPIRY_GUARD_SECS */
175 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
176 GUARD_PCT turns out to be lower than this, it
177 will use this time instead.
178 This is in milliseconds. */
179 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
180 below EXPIRY_GUARD_LIMIT */
181 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
183 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
184 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
185 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
186 static int expiry = DEFAULT_EXPIRY;
188 #ifndef MAX
189 #define MAX(a,b) ((a) > (b) ? (a) : (b))
190 #endif
192 #define CALLERID_UNKNOWN "Unknown"
194 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
195 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
196 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
198 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
199 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
200 #define SIP_TRANS_TIMEOUT 32000 /*!< SIP request timeout (rfc 3261) 64*T1
201 \todo Use known T1 for timeout (peerpoke)
203 #define DEFAULT_TRANS_TIMEOUT -1 /* Use default SIP transaction timeout */
204 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
206 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
207 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
208 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
210 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
212 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
213 static struct ast_jb_conf default_jbconf =
215 .flags = 0,
216 .max_size = -1,
217 .resync_threshold = -1,
218 .impl = ""
220 static struct ast_jb_conf global_jbconf;
222 static const char config[] = "sip.conf";
223 static const char notify_config[] = "sip_notify.conf";
225 #define RTP 1
226 #define NO_RTP 0
228 /*! \brief Authorization scheme for call transfers
229 \note Not a bitfield flag, since there are plans for other modes,
230 like "only allow transfers for authenticated devices" */
231 enum transfermodes {
232 TRANSFER_OPENFORALL, /*!< Allow all SIP transfers */
233 TRANSFER_CLOSED, /*!< Allow no SIP transfers */
237 enum sip_result {
238 AST_SUCCESS = 0,
239 AST_FAILURE = -1,
242 /*! \brief States for the INVITE transaction, not the dialog
243 \note this is for the INVITE that sets up the dialog
245 enum invitestates {
246 INV_NONE = 0, /*!< No state at all, maybe not an INVITE dialog */
247 INV_CALLING = 1, /*!< Invite sent, no answer */
248 INV_PROCEEDING = 2, /*!< We got/sent 1xx message */
249 INV_EARLY_MEDIA = 3, /*!< We got 18x message with to-tag back */
250 INV_COMPLETED = 4, /*!< Got final response with error. Wait for ACK, then CONFIRMED */
251 INV_CONFIRMED = 5, /*!< Confirmed response - we've got an ack (Incoming calls only) */
252 INV_TERMINATED = 6, /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done
253 The only way out of this is a BYE from one side */
254 INV_CANCELLED = 7, /*!< Transaction cancelled by client or server in non-terminated state */
257 /* Do _NOT_ make any changes to this enum, or the array following it;
258 if you think you are doing the right thing, you are probably
259 not doing the right thing. If you think there are changes
260 needed, get someone else to review them first _before_
261 submitting a patch. If these two lists do not match properly
262 bad things will happen.
265 enum xmittype {
266 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
267 If it fails, it's critical and will cause a teardown of the session */
268 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
269 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
272 enum parse_register_result {
273 PARSE_REGISTER_FAILED,
274 PARSE_REGISTER_UPDATE,
275 PARSE_REGISTER_QUERY,
278 enum subscriptiontype {
279 NONE = 0,
280 XPIDF_XML,
281 DIALOG_INFO_XML,
282 CPIM_PIDF_XML,
283 PIDF_XML,
284 MWI_NOTIFICATION
287 static const struct cfsubscription_types {
288 enum subscriptiontype type;
289 const char * const event;
290 const char * const mediatype;
291 const char * const text;
292 } subscription_types[] = {
293 { NONE, "-", "unknown", "unknown" },
294 /* RFC 4235: SIP Dialog event package */
295 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
296 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
297 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
298 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
299 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
302 /*! \brief SIP Request methods known by Asterisk */
303 enum sipmethod {
304 SIP_UNKNOWN, /* Unknown response */
305 SIP_RESPONSE, /* Not request, response to outbound request */
306 SIP_REGISTER,
307 SIP_OPTIONS,
308 SIP_NOTIFY,
309 SIP_INVITE,
310 SIP_ACK,
311 SIP_PRACK, /* Not supported at all */
312 SIP_BYE,
313 SIP_REFER,
314 SIP_SUBSCRIBE,
315 SIP_MESSAGE,
316 SIP_UPDATE, /* We can send UPDATE; but not accept it */
317 SIP_INFO,
318 SIP_CANCEL,
319 SIP_PUBLISH, /* Not supported at all */
320 SIP_PING, /* Not supported at all, no standard but still implemented out there */
323 /*! \brief Authentication types - proxy or www authentication
324 \note Endpoints, like Asterisk, should always use WWW authentication to
325 allow multiple authentications in the same call - to the proxy and
326 to the end point.
328 enum sip_auth_type {
329 PROXY_AUTH,
330 WWW_AUTH,
333 /*! \brief Authentication result from check_auth* functions */
334 enum check_auth_result {
335 AUTH_SUCCESSFUL = 0,
336 AUTH_CHALLENGE_SENT = 1,
337 AUTH_SECRET_FAILED = -1,
338 AUTH_USERNAME_MISMATCH = -2,
339 AUTH_NOT_FOUND = -3,
340 AUTH_FAKE_AUTH = -4,
341 AUTH_UNKNOWN_DOMAIN = -5,
344 /*! \brief States for outbound registrations (with register= lines in sip.conf */
345 enum sipregistrystate {
346 REG_STATE_UNREGISTERED = 0, /*!< We are not registred */
347 REG_STATE_REGSENT, /*!< Registration request sent */
348 REG_STATE_AUTHSENT, /*!< We have tried to authenticate */
349 REG_STATE_REGISTERED, /*!< Registred and done */
350 REG_STATE_REJECTED, /*!< Registration rejected */
351 REG_STATE_TIMEOUT, /*!< Registration timed out */
352 REG_STATE_NOAUTH, /*!< We have no accepted credentials */
353 REG_STATE_FAILED, /*!< Registration failed after several tries */
356 #define CAN_NOT_CREATE_DIALOG 0
357 #define CAN_CREATE_DIALOG 1
358 #define CAN_CREATE_DIALOG_UNSUPPORTED_METHOD 2
360 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
361 static const struct cfsip_methods {
362 enum sipmethod id;
363 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
364 char * const text;
365 int can_create;
366 } sip_methods[] = {
367 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
368 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
369 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
370 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
371 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
372 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
373 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
374 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
375 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
376 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
377 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
378 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
379 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
380 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
381 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
382 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
383 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
386 /*! Define SIP option tags, used in Require: and Supported: headers
387 We need to be aware of these properties in the phones to use
388 the replace: header. We should not do that without knowing
389 that the other end supports it...
390 This is nothing we can configure, we learn by the dialog
391 Supported: header on the REGISTER (peer) or the INVITE
392 (other devices)
393 We are not using many of these today, but will in the future.
394 This is documented in RFC 3261
396 #define SUPPORTED 1
397 #define NOT_SUPPORTED 0
399 #define SIP_OPT_REPLACES (1 << 0)
400 #define SIP_OPT_100REL (1 << 1)
401 #define SIP_OPT_TIMER (1 << 2)
402 #define SIP_OPT_EARLY_SESSION (1 << 3)
403 #define SIP_OPT_JOIN (1 << 4)
404 #define SIP_OPT_PATH (1 << 5)
405 #define SIP_OPT_PREF (1 << 6)
406 #define SIP_OPT_PRECONDITION (1 << 7)
407 #define SIP_OPT_PRIVACY (1 << 8)
408 #define SIP_OPT_SDP_ANAT (1 << 9)
409 #define SIP_OPT_SEC_AGREE (1 << 10)
410 #define SIP_OPT_EVENTLIST (1 << 11)
411 #define SIP_OPT_GRUU (1 << 12)
412 #define SIP_OPT_TARGET_DIALOG (1 << 13)
413 #define SIP_OPT_NOREFERSUB (1 << 14)
414 #define SIP_OPT_HISTINFO (1 << 15)
415 #define SIP_OPT_RESPRIORITY (1 << 16)
417 /*! \brief List of well-known SIP options. If we get this in a require,
418 we should check the list and answer accordingly. */
419 static const struct cfsip_options {
420 int id; /*!< Bitmap ID */
421 int supported; /*!< Supported by Asterisk ? */
422 char * const text; /*!< Text id, as in standard */
423 } sip_options[] = { /* XXX used in 3 places */
424 /* RFC3891: Replaces: header for transfer */
425 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
426 /* One version of Polycom firmware has the wrong label */
427 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
428 /* RFC3262: PRACK 100% reliability */
429 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
430 /* RFC4028: SIP Session Timers */
431 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
432 /* RFC3959: SIP Early session support */
433 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
434 /* RFC3911: SIP Join header support */
435 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
436 /* RFC3327: Path support */
437 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
438 /* RFC3840: Callee preferences */
439 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
440 /* RFC3312: Precondition support */
441 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
442 /* RFC3323: Privacy with proxies*/
443 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
444 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
445 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
446 /* RFC3329: Security agreement mechanism */
447 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
448 /* SIMPLE events: RFC4662 */
449 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
450 /* GRUU: Globally Routable User Agent URI's */
451 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
452 /* RFC4538: Target-dialog */
453 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
454 /* Disable the REFER subscription, RFC 4488 */
455 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
456 /* ietf-sip-history-info-06.txt */
457 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
458 /* ietf-sip-resource-priority-10.txt */
459 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
463 /*! \brief SIP Methods we support */
464 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
466 /*! \brief SIP Extensions we support */
467 #define SUPPORTED_EXTENSIONS "replaces"
469 /*! \brief Standard SIP port from RFC 3261. DO NOT CHANGE THIS */
470 #define STANDARD_SIP_PORT 5060
471 /* Note: in many SIP headers, absence of a port number implies port 5060,
472 * and this is why we cannot change the above constant.
473 * There is a limited number of places in asterisk where we could,
474 * in principle, use a different "default" port number, but
475 * we do not support this feature at the moment.
478 /* Default values, set and reset in reload_config before reading configuration */
479 /* These are default values in the source. There are other recommended values in the
480 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
481 yet encouraging new behaviour on new installations
483 #define DEFAULT_CONTEXT "default"
484 #define DEFAULT_MOHINTERPRET "default"
485 #define DEFAULT_MOHSUGGEST ""
486 #define DEFAULT_VMEXTEN "asterisk"
487 #define DEFAULT_CALLERID "asterisk"
488 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
489 #define DEFAULT_MWITIME 10
490 #define DEFAULT_ALLOWGUEST TRUE
491 #define DEFAULT_SRVLOOKUP FALSE /*!< Recommended setting is ON */
492 #define DEFAULT_COMPACTHEADERS FALSE
493 #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. */
494 #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. */
495 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
496 #define DEFAULT_ALLOW_EXT_DOM TRUE
497 #define DEFAULT_REALM "asterisk"
498 #define DEFAULT_NOTIFYRINGING TRUE
499 #define DEFAULT_PEDANTIC FALSE
500 #define DEFAULT_AUTOCREATEPEER FALSE
501 #define DEFAULT_QUALIFY FALSE
502 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
503 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
504 #ifndef DEFAULT_USERAGENT
505 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
506 #endif
509 /* Default setttings are used as a channel setting and as a default when
510 configuring devices */
511 static char default_context[AST_MAX_CONTEXT];
512 static char default_subscribecontext[AST_MAX_CONTEXT];
513 static char default_language[MAX_LANGUAGE];
514 static char default_callerid[AST_MAX_EXTENSION];
515 static char default_fromdomain[AST_MAX_EXTENSION];
516 static char default_notifymime[AST_MAX_EXTENSION];
517 static int default_qualify; /*!< Default Qualify= setting */
518 static char default_vmexten[AST_MAX_EXTENSION];
519 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
520 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
521 * a bridged channel on hold */
522 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
523 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
525 /* Global settings only apply to the channel */
526 static int global_directrtpsetup; /*!< Enable support for Direct RTP setup (no re-invites) */
527 static int global_limitonpeers; /*!< Match call limit on peers only */
528 static int global_rtautoclear;
529 static int global_notifyringing; /*!< Send notifications on ringing */
530 static int global_notifyhold; /*!< Send notifications on hold */
531 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
532 static int srvlookup; /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
533 static int pedanticsipchecking; /*!< Extra checking ? Default off */
534 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
535 static int global_relaxdtmf; /*!< Relax DTMF */
536 static int global_rtptimeout; /*!< Time out call if no RTP */
537 static int global_rtpholdtimeout;
538 static int global_rtpkeepalive; /*!< Send RTP keepalives */
539 static int global_reg_timeout;
540 static int global_regattempts_max; /*!< Registration attempts before giving up */
541 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
542 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
543 the global setting is in globals_flags[1] */
544 static int global_mwitime; /*!< Time between MWI checks for peers */
545 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
546 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
547 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
548 static int compactheaders; /*!< send compact sip headers */
549 static int recordhistory; /*!< Record SIP history. Off by default */
550 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
551 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
552 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
553 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
554 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
555 static int global_callevents; /*!< Whether we send manager events or not */
556 static int global_t1min; /*!< T1 roundtrip time minimum */
557 static int global_autoframing; /*!< Turn autoframing on or off. */
558 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
560 /*! \brief Codecs that we support by default: */
561 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
563 /* Object counters */
564 static int suserobjs = 0; /*!< Static users */
565 static int ruserobjs = 0; /*!< Realtime users */
566 static int speerobjs = 0; /*!< Statis peers */
567 static int rpeerobjs = 0; /*!< Realtime peers */
568 static int apeerobjs = 0; /*!< Autocreated peer objects */
569 static int regobjs = 0; /*!< Registry objects */
571 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
573 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
574 AST_MUTEX_DEFINE_STATIC(iflock);
576 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
577 when it's doing something critical. */
578 AST_MUTEX_DEFINE_STATIC(netlock);
580 AST_MUTEX_DEFINE_STATIC(monlock);
582 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
584 /*! \brief This is the thread for the monitor which checks for input on the channels
585 which are not currently in use. */
586 static pthread_t monitor_thread = AST_PTHREADT_NULL;
588 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
589 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
591 static struct sched_context *sched; /*!< The scheduling context */
592 static struct io_context *io; /*!< The IO context */
593 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
595 #define DEC_CALL_LIMIT 0
596 #define INC_CALL_LIMIT 1
597 #define DEC_CALL_RINGING 2
598 #define INC_CALL_RINGING 3
600 /*! \brief sip_request: The data grabbed from the UDP socket */
601 struct sip_request {
602 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
603 char *rlPart2; /*!< The Request URI or Response Status */
604 int len; /*!< Length */
605 int headers; /*!< # of SIP Headers */
606 int method; /*!< Method of this request */
607 int lines; /*!< Body Content */
608 unsigned int flags; /*!< SIP_PKT Flags for this packet */
609 char *header[SIP_MAX_HEADERS];
610 char *line[SIP_MAX_LINES];
611 char data[SIP_MAX_PACKET];
612 unsigned int sdp_start; /*!< the line number where the SDP begins */
613 unsigned int sdp_end; /*!< the line number where the SDP ends */
617 * A sip packet is stored into the data[] buffer, with the header followed
618 * by an empty line and the body of the message.
619 * On outgoing packets, data is accumulated in data[] with len reflecting
620 * the next available byte, headers and lines count the number of lines
621 * in both parts. There are no '\0' in data[0..len-1].
623 * On received packet, the input read from the socket is copied into data[],
624 * len is set and the string is NUL-terminated. Then a parser fills up
625 * the other fields -header[] and line[] to point to the lines of the
626 * message, rlPart1 and rlPart2 parse the first lnie as below:
628 * Requests have in the first line METHOD URI SIP/2.0
629 * rlPart1 = method; rlPart2 = uri;
630 * Responses have in the first line SIP/2.0 code description
631 * rlPart1 = SIP/2.0; rlPart2 = code + description;
635 /*! \brief structure used in transfers */
636 struct sip_dual {
637 struct ast_channel *chan1; /*!< First channel involved */
638 struct ast_channel *chan2; /*!< Second channel involved */
639 struct sip_request req; /*!< Request that caused the transfer (REFER) */
640 int seqno; /*!< Sequence number */
643 struct sip_pkt;
645 /*! \brief Parameters to the transmit_invite function */
646 struct sip_invite_param {
647 const char *distinctive_ring; /*!< Distinctive ring header */
648 int addsipheaders; /*!< Add extra SIP headers */
649 const char *uri_options; /*!< URI options to add to the URI */
650 const char *vxml_url; /*!< VXML url for Cisco phones */
651 char *auth; /*!< Authentication */
652 char *authheader; /*!< Auth header */
653 enum sip_auth_type auth_type; /*!< Authentication type */
654 const char *replaces; /*!< Replaces header for call transfers */
655 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
658 /*! \brief Structure to save routing information for a SIP session */
659 struct sip_route {
660 struct sip_route *next;
661 char hop[0];
664 /*! \brief Modes for SIP domain handling in the PBX */
665 enum domain_mode {
666 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
667 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
670 /*! \brief Domain data structure.
671 \note In the future, we will connect this to a configuration tree specific
672 for this domain
674 struct domain {
675 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
676 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
677 enum domain_mode mode; /*!< How did we find this domain? */
678 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
681 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
684 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
685 struct sip_history {
686 AST_LIST_ENTRY(sip_history) list;
687 char event[0]; /* actually more, depending on needs */
690 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
692 /*! \brief sip_auth: Credentials for authentication to other SIP services */
693 struct sip_auth {
694 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
695 char username[256]; /*!< Username */
696 char secret[256]; /*!< Secret */
697 char md5secret[256]; /*!< MD5Secret */
698 struct sip_auth *next; /*!< Next auth structure in list */
701 /*--- Various flags for the flags field in the pvt structure */
702 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
703 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed by the monitor thread */
704 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
705 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
706 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
707 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
708 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
709 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
710 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
711 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
712 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
713 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
714 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
715 #define SIP_OUTGOING (1 << 13) /*!< Direction of the last transaction in this dialog */
716 #define SIP_FREE_BIT (1 << 14) /*!< ---- */
717 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 15) /*!< Do not hangup at first ast_hangup */
718 #define SIP_DTMF (3 << 16) /*!< DTMF Support: four settings, uses two bits */
719 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DTMF Support: RTP DTMF - "rfc2833" */
720 #define SIP_DTMF_INBAND (1 << 16) /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
721 #define SIP_DTMF_INFO (2 << 16) /*!< DTMF Support: SIP Info messages - "info" */
722 #define SIP_DTMF_AUTO (3 << 16) /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
723 /* NAT settings */
724 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
725 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
726 #define SIP_NAT_RFC3581 (1 << 18) /*!< NAT RFC3581 */
727 #define SIP_NAT_ROUTE (2 << 18) /*!< NAT Only ROUTE */
728 #define SIP_NAT_ALWAYS (3 << 18) /*!< NAT Both ROUTE and RFC3581 */
729 /* re-INVITE related settings */
730 #define SIP_REINVITE (7 << 20) /*!< three bits used */
731 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
732 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< allow media reinvite when new peer is behind NAT */
733 #define SIP_REINVITE_UPDATE (4 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
734 /* "insecure" settings */
735 #define SIP_INSECURE_PORT (1 << 23) /*!< don't require matching port for incoming requests */
736 #define SIP_INSECURE_INVITE (1 << 24) /*!< don't require authentication for incoming INVITEs */
737 /* Sending PROGRESS in-band settings */
738 #define SIP_PROG_INBAND (3 << 25) /*!< three settings, uses two bits */
739 #define SIP_PROG_INBAND_NEVER (0 << 25)
740 #define SIP_PROG_INBAND_NO (1 << 25)
741 #define SIP_PROG_INBAND_YES (2 << 25)
742 #define SIP_NO_HISTORY (1 << 27) /*!< Suppress recording request/response history */
743 #define SIP_CALL_LIMIT (1 << 28) /*!< Call limit enforced for this call */
744 #define SIP_SENDRPID (1 << 29) /*!< Remote Party-ID Support */
745 #define SIP_INC_COUNT (1 << 30) /*!< Did this connection increment the counter of in-use calls? */
746 #define SIP_G726_NONSTANDARD (1 << 31) /*!< Use non-standard packing for G726-32 data */
748 #define SIP_FLAGS_TO_COPY \
749 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
750 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
751 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
753 /*--- a new page of flags (for flags[1] */
754 /* realtime flags */
755 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
756 #define SIP_PAGE2_RTUPDATE (1 << 1)
757 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
758 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
759 #define SIP_PAGE2_RTSAVE_SYSNAME (1 << 5)
760 /* Space for addition of other realtime flags in the future */
761 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 10)
762 #define SIP_PAGE2_DEBUG (3 << 11)
763 #define SIP_PAGE2_DEBUG_CONFIG (1 << 11)
764 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 12)
765 #define SIP_PAGE2_DYNAMIC (1 << 13) /*!< Dynamic Peers register with Asterisk */
766 #define SIP_PAGE2_SELFDESTRUCT (1 << 14) /*!< Automatic peers need to destruct themselves */
767 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15)
768 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< Allow subscriptions from this peer? */
769 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< Allow overlap dialing ? */
770 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< Only issue MWI notification if subscribed to */
771 #define SIP_PAGE2_INC_RINGING (1 << 19) /*!< Did this connection increment the counter of in-use calls? */
772 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< T38 Fax Passthrough Support */
773 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< 20: T38 Fax Passthrough Support */
774 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< 21: T38 Fax Passthrough Support (not implemented) */
775 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< 22: T38 Fax Passthrough Support (not implemented) */
776 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< Call states */
777 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (1 << 23) /*!< 23: One directional hold */
778 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (1 << 24) /*!< 24: Inactive */
779 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25) /*!< 25: ???? */
780 #define SIP_PAGE2_BUGGY_MWI (1 << 26) /*!< 26: Buggy CISCO MWI fix */
781 #define SIP_PAGE2_OUTGOING_CALL (1 << 27) /*!< 27: Is this an outgoing call? */
783 #define SIP_PAGE2_FLAGS_TO_COPY \
784 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
785 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI)
787 /* SIP packet flags */
788 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
789 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
790 #define SIP_PKT_IGNORE (1 << 2) /*!< This is a re-transmit, ignore it */
791 #define SIP_PKT_IGNORE_RESP (1 << 3) /*!< Resp ignore - ??? */
792 #define SIP_PKT_IGNORE_REQ (1 << 4) /*!< Req ignore - ??? */
794 /* T.38 set of flags */
795 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
796 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
797 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
798 /* Rate management */
799 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
800 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
801 /* UDP Error correction */
802 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
803 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
804 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
805 /* T38 Spec version */
806 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
807 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
808 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
809 /* Maximum Fax Rate */
810 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
811 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
812 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
813 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
814 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
815 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
817 /*!< This is default: NO MMR and JBIG trancoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
818 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
820 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
821 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
822 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
824 /*! \brief T38 States for a call */
825 enum t38state {
826 T38_DISABLED = 0, /*!< Not enabled */
827 T38_LOCAL_DIRECT, /*!< Offered from local */
828 T38_LOCAL_REINVITE, /*!< Offered from local - REINVITE */
829 T38_PEER_DIRECT, /*!< Offered from peer */
830 T38_PEER_REINVITE, /*!< Offered from peer - REINVITE */
831 T38_ENABLED /*!< Negotiated (enabled) */
834 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
835 struct t38properties {
836 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
837 int capability; /*!< Our T38 capability */
838 int peercapability; /*!< Peers T38 capability */
839 int jointcapability; /*!< Supported T38 capability at both ends */
840 enum t38state state; /*!< T.38 state */
843 /*! \brief Parameters to know status of transfer */
844 enum referstatus {
845 REFER_IDLE, /*!< No REFER is in progress */
846 REFER_SENT, /*!< Sent REFER to transferee */
847 REFER_RECEIVED, /*!< Received REFER from transferer */
848 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING */
849 REFER_ACCEPTED, /*!< Accepted by transferee */
850 REFER_RINGING, /*!< Target Ringing */
851 REFER_200OK, /*!< Answered by transfer target */
852 REFER_FAILED, /*!< REFER declined - go on */
853 REFER_NOAUTH /*!< We had no auth for REFER */
856 static const struct c_referstatusstring {
857 enum referstatus status;
858 char *text;
859 } referstatusstrings[] = {
860 { REFER_IDLE, "<none>" },
861 { REFER_SENT, "Request sent" },
862 { REFER_RECEIVED, "Request received" },
863 { REFER_ACCEPTED, "Accepted" },
864 { REFER_RINGING, "Target ringing" },
865 { REFER_200OK, "Done" },
866 { REFER_FAILED, "Failed" },
867 { REFER_NOAUTH, "Failed - auth failure" }
870 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed */
871 /* OEJ: Should be moved to string fields */
872 struct sip_refer {
873 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
874 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
875 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
876 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
877 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
878 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
879 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
880 char replaces_callid[BUFSIZ]; /*!< Replace info: callid */
881 char replaces_callid_totag[BUFSIZ/2]; /*!< Replace info: to-tag */
882 char replaces_callid_fromtag[BUFSIZ/2]; /*!< Replace info: from-tag */
883 struct sip_pvt *refer_call; /*!< Call we are referring */
884 int attendedtransfer; /*!< Attended or blind transfer? */
885 int localtransfer; /*!< Transfer to local domain? */
886 enum referstatus status; /*!< REFER status */
889 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
890 static struct sip_pvt {
891 ast_mutex_t lock; /*!< Dialog private lock */
892 int method; /*!< SIP method that opened this dialog */
893 enum invitestates invitestate; /*!< The state of the INVITE transaction only */
894 AST_DECLARE_STRING_FIELDS(
895 AST_STRING_FIELD(callid); /*!< Global CallID */
896 AST_STRING_FIELD(randdata); /*!< Random data */
897 AST_STRING_FIELD(accountcode); /*!< Account code */
898 AST_STRING_FIELD(realm); /*!< Authorization realm */
899 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
900 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
901 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
902 AST_STRING_FIELD(domain); /*!< Authorization domain */
903 AST_STRING_FIELD(from); /*!< The From: header */
904 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
905 AST_STRING_FIELD(exten); /*!< Extension where to start */
906 AST_STRING_FIELD(context); /*!< Context for this call */
907 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
908 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
909 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
910 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
911 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
912 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
913 AST_STRING_FIELD(language); /*!< Default language for this call */
914 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
915 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
916 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
917 AST_STRING_FIELD(theirtag); /*!< Their tag */
918 AST_STRING_FIELD(username); /*!< [user] name */
919 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
920 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
921 AST_STRING_FIELD(uri); /*!< Original requested URI */
922 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
923 AST_STRING_FIELD(peersecret); /*!< Password */
924 AST_STRING_FIELD(peermd5secret);
925 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
926 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
927 AST_STRING_FIELD(via); /*!< Via: header */
928 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
929 AST_STRING_FIELD(our_contact); /*!< Our contact header */
930 AST_STRING_FIELD(rpid); /*!< Our RPID header */
931 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
933 unsigned int ocseq; /*!< Current outgoing seqno */
934 unsigned int icseq; /*!< Current incoming seqno */
935 ast_group_t callgroup; /*!< Call group */
936 ast_group_t pickupgroup; /*!< Pickup group */
937 int lastinvite; /*!< Last Cseq of invite */
938 struct ast_flags flags[2]; /*!< SIP_ flags */
939 int timer_t1; /*!< SIP timer T1, ms rtt */
940 unsigned int sipoptions; /*!< Supported SIP options on the other end */
941 struct ast_codec_pref prefs; /*!< codec prefs */
942 int capability; /*!< Special capability (codec) */
943 int jointcapability; /*!< Supported capability at both ends (codecs) */
944 int peercapability; /*!< Supported peer capability */
945 int prefcodec; /*!< Preferred codec (outbound only) */
946 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
947 int jointnoncodeccapability; /*!< Joint Non codec capability */
948 int redircodecs; /*!< Redirect codecs */
949 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
950 struct t38properties t38; /*!< T38 settings */
951 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
952 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
953 int callingpres; /*!< Calling presentation */
954 int authtries; /*!< Times we've tried to authenticate */
955 int expiry; /*!< How long we take to expire */
956 long branch; /*!< The branch identifier of this session */
957 char tag[11]; /*!< Our tag for this session */
958 int sessionid; /*!< SDP Session ID */
959 int sessionversion; /*!< SDP Session Version */
960 struct sockaddr_in sa; /*!< Our peer */
961 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
962 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
963 time_t lastrtprx; /*!< Last RTP received */
964 time_t lastrtptx; /*!< Last RTP sent */
965 int rtptimeout; /*!< RTP timeout time */
966 struct sockaddr_in recv; /*!< Received as */
967 struct in_addr ourip; /*!< Our IP */
968 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
969 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
970 int route_persistant; /*!< Is this the "real" route? */
971 struct sip_auth *peerauth; /*!< Realm authentication */
972 int noncecount; /*!< Nonce-count */
973 char lastmsg[256]; /*!< Last Message sent/received */
974 int amaflags; /*!< AMA Flags */
975 int pendinginvite; /*!< Any pending invite ? (seqno of this) */
976 struct sip_request initreq; /*!< Request that opened the latest transaction
977 within this SIP dialog */
979 int maxtime; /*!< Max time for first response */
980 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
981 int autokillid; /*!< Auto-kill ID (scheduler) */
982 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
983 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
984 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
985 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
986 int laststate; /*!< SUBSCRIBE: Last known extension state */
987 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
989 struct ast_dsp *vad; /*!< Voice Activation Detection dsp */
991 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
992 Used in peerpoke, mwi subscriptions */
993 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
994 struct ast_rtp *rtp; /*!< RTP Session */
995 struct ast_rtp *vrtp; /*!< Video RTP session */
996 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
997 struct sip_history_head *history; /*!< History of this SIP dialog */
998 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
999 struct sip_pvt *next; /*!< Next dialog in chain */
1000 struct sip_invite_param *options; /*!< Options for INVITE */
1001 int autoframing;
1002 } *iflist = NULL;
1004 #define FLAG_RESPONSE (1 << 0)
1005 #define FLAG_FATAL (1 << 1)
1007 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */
1008 struct sip_pkt {
1009 struct sip_pkt *next; /*!< Next packet in linked list */
1010 int retrans; /*!< Retransmission number */
1011 int method; /*!< SIP method for this packet */
1012 int seqno; /*!< Sequence number */
1013 unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */
1014 struct sip_pvt *owner; /*!< Owner AST call */
1015 int retransid; /*!< Retransmission ID */
1016 int timer_a; /*!< SIP timer A, retransmission timer */
1017 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
1018 int packetlen; /*!< Length of packet */
1019 char data[0];
1022 /*! \brief Structure for SIP user data. User's place calls to us */
1023 struct sip_user {
1024 /* Users who can access various contexts */
1025 ASTOBJ_COMPONENTS(struct sip_user);
1026 char secret[80]; /*!< Password */
1027 char md5secret[80]; /*!< Password in md5 */
1028 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1029 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
1030 char cid_num[80]; /*!< Caller ID num */
1031 char cid_name[80]; /*!< Caller ID name */
1032 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
1033 char language[MAX_LANGUAGE]; /*!< Default language for this user */
1034 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1035 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1036 char useragent[256]; /*!< User agent in SIP request */
1037 struct ast_codec_pref prefs; /*!< codec prefs */
1038 ast_group_t callgroup; /*!< Call group */
1039 ast_group_t pickupgroup; /*!< Pickup Group */
1040 unsigned int sipoptions; /*!< Supported SIP options */
1041 struct ast_flags flags[2]; /*!< SIP_ flags */
1042 int amaflags; /*!< AMA flags for billing */
1043 int callingpres; /*!< Calling id presentation */
1044 int capability; /*!< Codec capability */
1045 int inUse; /*!< Number of calls in use */
1046 int call_limit; /*!< Limit of concurrent calls */
1047 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1048 struct ast_ha *ha; /*!< ACL setting */
1049 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1050 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1051 int autoframing;
1054 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1055 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1056 struct sip_peer {
1057 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
1058 /*!< peer->name is the unique name of this object */
1059 char secret[80]; /*!< Password */
1060 char md5secret[80]; /*!< Password in MD5 */
1061 struct sip_auth *auth; /*!< Realm authentication list */
1062 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1063 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1064 char username[80]; /*!< Temporary username until registration */
1065 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1066 int amaflags; /*!< AMA Flags (for billing) */
1067 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1068 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1069 char fromuser[80]; /*!< From: user when calling this peer */
1070 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1071 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1072 char cid_num[80]; /*!< Caller ID num */
1073 char cid_name[80]; /*!< Caller ID name */
1074 int callingpres; /*!< Calling id presentation */
1075 int inUse; /*!< Number of calls in use */
1076 int inRinging; /*!< Number of calls ringing */
1077 int onHold; /*!< Peer has someone on hold */
1078 int call_limit; /*!< Limit of concurrent calls */
1079 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1080 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1081 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
1082 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1083 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1084 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1085 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1086 struct ast_codec_pref prefs; /*!< codec prefs */
1087 int lastmsgssent;
1088 time_t lastmsgcheck; /*!< Last time we checked for MWI */
1089 unsigned int sipoptions; /*!< Supported SIP options */
1090 struct ast_flags flags[2]; /*!< SIP_ flags */
1091 int expire; /*!< When to expire this peer registration */
1092 int capability; /*!< Codec capability */
1093 int rtptimeout; /*!< RTP timeout */
1094 int rtpholdtimeout; /*!< RTP Hold Timeout */
1095 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1096 ast_group_t callgroup; /*!< Call group */
1097 ast_group_t pickupgroup; /*!< Pickup group */
1098 struct sockaddr_in addr; /*!< IP address of peer */
1099 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1101 /* Qualification */
1102 struct sip_pvt *call; /*!< Call pointer */
1103 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1104 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1105 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1106 struct timeval ps; /*!< Ping send time */
1108 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1109 struct ast_ha *ha; /*!< Access control list */
1110 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1111 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1112 int lastmsg;
1113 int autoframing;
1118 /*! \brief Registrations with other SIP proxies */
1119 struct sip_registry {
1120 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1121 AST_DECLARE_STRING_FIELDS(
1122 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1123 AST_STRING_FIELD(realm); /*!< Authorization realm */
1124 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1125 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1126 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1127 AST_STRING_FIELD(domain); /*!< Authorization domain */
1128 AST_STRING_FIELD(username); /*!< Who we are registering as */
1129 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1130 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1131 AST_STRING_FIELD(secret); /*!< Password in clear text */
1132 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1133 AST_STRING_FIELD(contact); /*!< Contact extension */
1134 AST_STRING_FIELD(random);
1136 int portno; /*!< Optional port override */
1137 int expire; /*!< Sched ID of expiration */
1138 int regattempts; /*!< Number of attempts (since the last success) */
1139 int timeout; /*!< sched id of sip_reg_timeout */
1140 int refresh; /*!< How often to refresh */
1141 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1142 enum sipregistrystate regstate; /*!< Registration state (see above) */
1143 time_t regtime; /*!< Last succesful registration time */
1144 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1145 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1146 struct sockaddr_in us; /*!< Who the server thinks we are */
1147 int noncecount; /*!< Nonce-count */
1148 char lastmsg[256]; /*!< Last Message sent/received */
1151 /* --- Linked lists of various objects --------*/
1153 /*! \brief The user list: Users and friends */
1154 static struct ast_user_list {
1155 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1156 } userl;
1158 /*! \brief The peer list: Peers and Friends */
1159 static struct ast_peer_list {
1160 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1161 } peerl;
1163 /*! \brief The register list: Other SIP proxys we register with and place calls to */
1164 static struct ast_register_list {
1165 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1166 int recheck;
1167 } regl;
1169 static void temp_pvt_cleanup(void *);
1171 /*! \brief A per-thread temporary pvt structure */
1172 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1174 /*! \todo Move the sip_auth list to AST_LIST */
1175 static struct sip_auth *authl = NULL; /*!< Authentication list for realm authentication */
1178 /* --- Sockets and networking --------------*/
1179 static int sipsock = -1; /*!< Main socket for SIP network communication */
1180 static struct sockaddr_in bindaddr = { 0, }; /*!< The address we bind to */
1181 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1182 static char externhost[MAXHOSTNAMELEN]; /*!< External host name (possibly with dynamic DNS and DHCP */
1183 static time_t externexpire = 0; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1184 static int externrefresh = 10;
1185 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1186 static struct in_addr __ourip;
1187 static struct sockaddr_in outboundproxyip;
1188 static int ourport;
1189 static struct sockaddr_in debugaddr;
1191 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1193 /*---------------------------- Forward declarations of functions in chan_sip.c */
1194 /*! \note This is added to help splitting up chan_sip.c into several files
1195 in coming releases */
1197 /*--- PBX interface functions */
1198 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1199 static int sip_devicestate(void *data);
1200 static int sip_sendtext(struct ast_channel *ast, const char *text);
1201 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1202 static int sip_hangup(struct ast_channel *ast);
1203 static int sip_answer(struct ast_channel *ast);
1204 static struct ast_frame *sip_read(struct ast_channel *ast);
1205 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1206 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1207 static int sip_transfer(struct ast_channel *ast, const char *dest);
1208 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1209 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1210 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1212 /*--- Transmitting responses and requests */
1213 static int sipsock_read(int *id, int fd, short events, void *ignore);
1214 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
1215 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
1216 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1217 static int retrans_pkt(void *data);
1218 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
1219 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);
1220 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1221 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1222 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1223 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1224 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1225 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);
1226 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1227 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1228 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1229 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1230 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1231 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
1232 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1233 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1234 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1235 static int transmit_refer(struct sip_pvt *p, const char *dest);
1236 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1237 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1238 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1239 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1240 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1241 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1242 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1243 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1244 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1245 static int does_peer_need_mwi(struct sip_peer *peer);
1247 /*--- Dialog management */
1248 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1249 int useglobal_nat, const int intended_method);
1250 static int __sip_autodestruct(void *data);
1251 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1252 static void sip_cancel_destroy(struct sip_pvt *p);
1253 static void sip_destroy(struct sip_pvt *p);
1254 static void __sip_destroy(struct sip_pvt *p, int lockowner);
1255 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1256 static void __sip_pretend_ack(struct sip_pvt *p);
1257 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1258 static int auto_congest(void *nothing);
1259 static int update_call_counter(struct sip_pvt *fup, int event);
1260 static int hangup_sip2cause(int cause);
1261 static const char *hangup_cause2sip(int cause);
1262 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1263 static void free_old_route(struct sip_route *route);
1264 static void list_route(struct sip_route *route);
1265 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1266 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1267 struct sip_request *req, char *uri);
1268 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1269 static void check_pendings(struct sip_pvt *p);
1270 static void *sip_park_thread(void *stuff);
1271 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1272 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1274 /*--- Codec handling / SDP */
1275 static void try_suggested_sip_codec(struct sip_pvt *p);
1276 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1277 static const char *get_sdp(struct sip_request *req, const char *name);
1278 static int find_sdp(struct sip_request *req);
1279 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
1280 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1281 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1282 int debug, int *min_packet_size);
1283 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1284 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1285 int debug);
1286 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p);
1288 /*--- Authentication stuff */
1289 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1290 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1291 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1292 const char *secret, const char *md5secret, int sipmethod,
1293 char *uri, enum xmittype reliable, int ignore);
1294 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1295 int sipmethod, char *uri, enum xmittype reliable,
1296 struct sockaddr_in *sin, struct sip_peer **authpeer);
1297 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1299 /*--- Domain handling */
1300 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1301 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1302 static void clear_sip_domains(void);
1304 /*--- SIP realm authentication */
1305 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
1306 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1307 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1309 /*--- Misc functions */
1310 static int sip_do_reload(enum channelreloadreason reason);
1311 static int reload_config(enum channelreloadreason reason);
1312 static int expire_register(void *data);
1313 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1314 static void *do_monitor(void *data);
1315 static int restart_monitor(void);
1316 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1317 static void sip_destroy(struct sip_pvt *p);
1318 static int sip_addrcmp(char *name, struct sockaddr_in *sin); /* Support for peer matching */
1319 static int sip_refer_allocate(struct sip_pvt *p);
1320 static void ast_quiet_chan(struct ast_channel *chan);
1321 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1323 /*--- Device monitoring and Device/extension state handling */
1324 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1325 static int sip_devicestate(void *data);
1326 static int sip_poke_noanswer(void *data);
1327 static int sip_poke_peer(struct sip_peer *peer);
1328 static void sip_poke_all_peers(void);
1329 static void sip_peer_hold(struct sip_pvt *p, int hold);
1331 /*--- Applications, functions, CLI and manager command helpers */
1332 static const char *sip_nat_mode(const struct sip_pvt *p);
1333 static int sip_show_inuse(int fd, int argc, char *argv[]);
1334 static char *transfermode2str(enum transfermodes mode) attribute_const;
1335 static char *nat2str(int nat) attribute_const;
1336 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1337 static int sip_show_users(int fd, int argc, char *argv[]);
1338 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1339 static int sip_show_peers(int fd, int argc, char *argv[]);
1340 static int sip_show_objects(int fd, int argc, char *argv[]);
1341 static void print_group(int fd, ast_group_t group, int crlf);
1342 static const char *dtmfmode2str(int mode) attribute_const;
1343 static const char *insecure2str(int port, int invite) attribute_const;
1344 static void cleanup_stale_contexts(char *new, char *old);
1345 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1346 static const char *domain_mode_to_text(const enum domain_mode mode);
1347 static int sip_show_domains(int fd, int argc, char *argv[]);
1348 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1349 static int sip_show_peer(int fd, int argc, char *argv[]);
1350 static int sip_show_user(int fd, int argc, char *argv[]);
1351 static int sip_show_registry(int fd, int argc, char *argv[]);
1352 static int sip_show_settings(int fd, int argc, char *argv[]);
1353 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1354 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1355 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1356 static int sip_show_channels(int fd, int argc, char *argv[]);
1357 static int sip_show_subscriptions(int fd, int argc, char *argv[]);
1358 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1359 static char *complete_sipch(const char *line, const char *word, int pos, int state);
1360 static char *complete_sip_peer(const char *word, int state, int flags2);
1361 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1362 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state);
1363 static char *complete_sip_user(const char *word, int state, int flags2);
1364 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
1365 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1366 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state);
1367 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state);
1368 static int sip_show_channel(int fd, int argc, char *argv[]);
1369 static int sip_show_history(int fd, int argc, char *argv[]);
1370 static int sip_do_debug_ip(int fd, int argc, char *argv[]);
1371 static int sip_do_debug_peer(int fd, int argc, char *argv[]);
1372 static int sip_do_debug(int fd, int argc, char *argv[]);
1373 static int sip_no_debug(int fd, int argc, char *argv[]);
1374 static int sip_notify(int fd, int argc, char *argv[]);
1375 static int sip_do_history(int fd, int argc, char *argv[]);
1376 static int sip_no_history(int fd, int argc, char *argv[]);
1377 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
1378 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1379 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1380 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1381 static int sip_dtmfmode(struct ast_channel *chan, void *data);
1382 static int sip_addheader(struct ast_channel *chan, void *data);
1383 static int sip_do_reload(enum channelreloadreason reason);
1384 static int sip_reload(int fd, int argc, char *argv[]);
1386 /*--- Debugging
1387 Functions for enabling debug per IP or fully, or enabling history logging for
1388 a SIP dialog
1390 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1391 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1392 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1393 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1394 static void sip_dump_history(struct sip_pvt *dialog);
1396 /*--- Device object handling */
1397 static struct sip_peer *temp_peer(const char *name);
1398 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1399 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
1400 static int update_call_counter(struct sip_pvt *fup, int event);
1401 static void sip_destroy_peer(struct sip_peer *peer);
1402 static void sip_destroy_user(struct sip_user *user);
1403 static int sip_poke_peer(struct sip_peer *peer);
1404 static int sip_poke_peer_s(void *data);
1405 static void set_peer_defaults(struct sip_peer *peer);
1406 static struct sip_peer *temp_peer(const char *name);
1407 static void register_peer_exten(struct sip_peer *peer, int onoff);
1408 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
1409 static struct sip_user *find_user(const char *name, int realtime);
1410 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1411 static int expire_register(void *data);
1412 static void reg_source_db(struct sip_peer *peer);
1413 static void destroy_association(struct sip_peer *peer);
1414 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1416 /* Realtime device support */
1417 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
1418 static struct sip_user *realtime_user(const char *username);
1419 static void update_peer(struct sip_peer *p, int expiry);
1420 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
1421 static int sip_prune_realtime(int fd, int argc, char *argv[]);
1423 /*--- Internal UA client handling (outbound registrations) */
1424 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
1425 static void sip_registry_destroy(struct sip_registry *reg);
1426 static int sip_register(char *value, int lineno);
1427 static char *regstate2str(enum sipregistrystate regstate) attribute_const;
1428 static int sip_reregister(void *data);
1429 static int __sip_do_register(struct sip_registry *r);
1430 static int sip_reg_timeout(void *data);
1431 static void sip_send_all_registers(void);
1433 /*--- Parsing SIP requests and responses */
1434 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1435 static int determine_firstline_parts(struct sip_request *req);
1436 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1437 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1438 static int find_sip_method(const char *msg);
1439 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1440 static void parse_request(struct sip_request *req);
1441 static const char *get_header(const struct sip_request *req, const char *name);
1442 static char *referstatus2str(enum referstatus rstatus) attribute_pure;
1443 static int method_match(enum sipmethod id, const char *name);
1444 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1445 static char *get_in_brackets(char *tmp);
1446 static const char *find_alias(const char *name, const char *_default);
1447 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1448 static int lws2sws(char *msgbuf, int len);
1449 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1450 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1451 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1452 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1453 static int set_address_from_contact(struct sip_pvt *pvt);
1454 static void check_via(struct sip_pvt *p, struct sip_request *req);
1455 static char *get_calleridname(const char *input, char *output, size_t outputsize);
1456 static int get_rpid_num(const char *input, char *output, int maxlen);
1457 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
1458 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1459 static int get_msg_text(char *buf, int len, struct sip_request *req);
1460 static void free_old_route(struct sip_route *route);
1461 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1463 /*--- Constructing requests and responses */
1464 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1465 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1466 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1467 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1468 static int init_resp(struct sip_request *resp, const char *msg);
1469 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1470 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1471 static void build_via(struct sip_pvt *p);
1472 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1473 static int create_addr(struct sip_pvt *dialog, const char *opeer);
1474 static char *generate_random_string(char *buf, size_t size);
1475 static void build_callid_pvt(struct sip_pvt *pvt);
1476 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1477 static void make_our_tag(char *tagbuf, size_t len);
1478 static int add_header(struct sip_request *req, const char *var, const char *value);
1479 static int add_header_contentLength(struct sip_request *req, int len);
1480 static int add_line(struct sip_request *req, const char *line);
1481 static int add_text(struct sip_request *req, const char *text);
1482 static int add_digit(struct sip_request *req, char digit, unsigned int duration);
1483 static int add_vidupdate(struct sip_request *req);
1484 static void add_route(struct sip_request *req, struct sip_route *route);
1485 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1486 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1487 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1488 static void set_destination(struct sip_pvt *p, char *uri);
1489 static void append_date(struct sip_request *req);
1490 static void build_contact(struct sip_pvt *p);
1491 static void build_rpid(struct sip_pvt *p);
1493 /*------Request handling functions */
1494 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1495 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);
1496 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock);
1497 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1498 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1499 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1500 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1501 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1502 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1503 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1504 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1505 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1506 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
1508 /*------Response handling functions */
1509 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1510 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1511 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
1512 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
1514 /*----- RTP interface functions */
1515 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
1516 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1517 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1518 static int sip_get_codec(struct ast_channel *chan);
1519 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
1521 /*------ T38 Support --------- */
1522 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite); /*!< T38 negotiation helper function */
1523 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1524 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p);
1525 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1526 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1528 /*! \brief Definition of this channel for PBX channel registration */
1529 static const struct ast_channel_tech sip_tech = {
1530 .type = "SIP",
1531 .description = "Session Initiation Protocol (SIP)",
1532 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1533 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1534 .requester = sip_request_call,
1535 .devicestate = sip_devicestate,
1536 .call = sip_call,
1537 .hangup = sip_hangup,
1538 .answer = sip_answer,
1539 .read = sip_read,
1540 .write = sip_write,
1541 .write_video = sip_write,
1542 .indicate = sip_indicate,
1543 .transfer = sip_transfer,
1544 .fixup = sip_fixup,
1545 .send_digit_begin = sip_senddigit_begin,
1546 .send_digit_end = sip_senddigit_end,
1547 .bridge = ast_rtp_bridge,
1548 .send_text = sip_sendtext,
1551 /*! \brief This version of the sip channel tech has no send_digit_begin
1552 * callback. This is for use with channels using SIP INFO DTMF so that
1553 * the core knows that the channel doesn't want DTMF BEGIN frames. */
1554 static const struct ast_channel_tech sip_tech_info = {
1555 .type = "SIP",
1556 .description = "Session Initiation Protocol (SIP)",
1557 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1558 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1559 .requester = sip_request_call,
1560 .devicestate = sip_devicestate,
1561 .call = sip_call,
1562 .hangup = sip_hangup,
1563 .answer = sip_answer,
1564 .read = sip_read,
1565 .write = sip_write,
1566 .write_video = sip_write,
1567 .indicate = sip_indicate,
1568 .transfer = sip_transfer,
1569 .fixup = sip_fixup,
1570 .send_digit_end = sip_senddigit_end,
1571 .bridge = ast_rtp_bridge,
1572 .send_text = sip_sendtext,
1575 /**--- some list management macros. **/
1577 #define UNLINK(element, head, prev) do { \
1578 if (prev) \
1579 (prev)->next = (element)->next; \
1580 else \
1581 (head) = (element)->next; \
1582 } while (0)
1584 /*! \brief Interface structure with callbacks used to connect to RTP module */
1585 static struct ast_rtp_protocol sip_rtp = {
1586 type: "SIP",
1587 get_rtp_info: sip_get_rtp_peer,
1588 get_vrtp_info: sip_get_vrtp_peer,
1589 set_rtp_peer: sip_set_rtp_peer,
1590 get_codec: sip_get_codec,
1593 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1594 static struct ast_udptl_protocol sip_udptl = {
1595 type: "SIP",
1596 get_udptl_info: sip_get_udptl_peer,
1597 set_udptl_peer: sip_set_udptl_peer,
1600 /*! \brief Convert transfer status to string */
1601 static char *referstatus2str(enum referstatus rstatus)
1603 int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
1604 int x;
1606 for (x = 0; x < i; x++) {
1607 if (referstatusstrings[x].status == rstatus)
1608 return (char *) referstatusstrings[x].text;
1610 return "";
1613 /*! \brief Initialize the initital request packet in the pvt structure.
1614 This packet is used for creating replies and future requests in
1615 a dialog */
1616 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
1618 if (p->initreq.headers && option_debug) {
1619 ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
1621 /* Use this as the basis */
1622 copy_request(&p->initreq, req);
1623 parse_request(&p->initreq);
1624 if (ast_test_flag(req, SIP_PKT_DEBUG))
1625 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
1628 static void sip_alreadygone(struct sip_pvt *dialog)
1630 if (option_debug > 2)
1631 ast_log(LOG_DEBUG, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
1632 ast_set_flag(&dialog->flags[0], SIP_ALREADYGONE);
1636 /*! \brief returns true if 'name' (with optional trailing whitespace)
1637 * matches the sip method 'id'.
1638 * Strictly speaking, SIP methods are case SENSITIVE, but we do
1639 * a case-insensitive comparison to be more tolerant.
1640 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1642 static int method_match(enum sipmethod id, const char *name)
1644 int len = strlen(sip_methods[id].text);
1645 int l_name = name ? strlen(name) : 0;
1646 /* true if the string is long enough, and ends with whitespace, and matches */
1647 return (l_name >= len && name[len] < 33 &&
1648 !strncasecmp(sip_methods[id].text, name, len));
1651 /*! \brief find_sip_method: Find SIP method from header */
1652 static int find_sip_method(const char *msg)
1654 int i, res = 0;
1656 if (ast_strlen_zero(msg))
1657 return 0;
1658 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
1659 if (method_match(i, msg))
1660 res = sip_methods[i].id;
1662 return res;
1665 /*! \brief Parse supported header in incoming packet */
1666 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
1668 char *next, *sep;
1669 char *temp;
1670 unsigned int profile = 0;
1671 int i, found;
1673 if (ast_strlen_zero(supported) )
1674 return 0;
1675 temp = ast_strdupa(supported);
1677 if (option_debug > 2 && sipdebug)
1678 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1680 for (next = temp; next; next = sep) {
1681 found = FALSE;
1682 if ( (sep = strchr(next, ',')) != NULL)
1683 *sep++ = '\0';
1684 next = ast_skip_blanks(next);
1685 if (option_debug > 2 && sipdebug)
1686 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1687 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
1688 if (!strcasecmp(next, sip_options[i].text)) {
1689 profile |= sip_options[i].id;
1690 found = TRUE;
1691 if (option_debug > 2 && sipdebug)
1692 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1693 break;
1696 if (!found && option_debug > 2 && sipdebug) {
1697 if (!strncasecmp(next, "x-", 2))
1698 ast_log(LOG_DEBUG, "Found private SIP option, not supported: %s\n", next);
1699 else
1700 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1704 if (pvt)
1705 pvt->sipoptions = profile;
1706 return profile;
1709 /*! \brief See if we pass debug IP filter */
1710 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
1712 if (!sipdebug)
1713 return 0;
1714 if (debugaddr.sin_addr.s_addr) {
1715 if (((ntohs(debugaddr.sin_port) != 0)
1716 && (debugaddr.sin_port != addr->sin_port))
1717 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1718 return 0;
1720 return 1;
1723 /*! \brief The real destination address for a write */
1724 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
1726 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
1729 /*! \brief Display SIP nat mode */
1730 static const char *sip_nat_mode(const struct sip_pvt *p)
1732 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
1735 /*! \brief Test PVT for debugging output */
1736 static inline int sip_debug_test_pvt(struct sip_pvt *p)
1738 if (!sipdebug)
1739 return 0;
1740 return sip_debug_test_addr(sip_real_dst(p));
1743 /*! \brief Transmit SIP message */
1744 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1746 int res;
1747 const struct sockaddr_in *dst = sip_real_dst(p);
1748 res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
1750 if (res != len)
1751 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));
1752 return res;
1756 /*! \brief Build a Via header for a request */
1757 static void build_via(struct sip_pvt *p)
1759 /* Work around buggy UNIDEN UIP200 firmware */
1760 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1762 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1763 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1764 ast_inet_ntoa(p->ourip), ourport, p->branch, rport);
1767 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1769 * Using the localaddr structure built up with localnet statements in sip.conf
1770 * apply it to their address to see if we need to substitute our
1771 * externip or can get away with our internal bindaddr
1773 static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1775 struct sockaddr_in theirs, ours;
1777 /* Get our local information */
1778 ast_ouraddrfor(them, us);
1779 theirs.sin_addr = *them;
1780 ours.sin_addr = *us;
1782 if (localaddr && externip.sin_addr.s_addr &&
1783 (ast_apply_ha(localaddr, &theirs)) &&
1784 (!ast_apply_ha(localaddr, &ours))) {
1785 if (externexpire && time(NULL) >= externexpire) {
1786 struct ast_hostent ahp;
1787 struct hostent *hp;
1789 externexpire = time(NULL) + externrefresh;
1790 if ((hp = ast_gethostbyname(externhost, &ahp))) {
1791 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1792 } else
1793 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1795 *us = externip.sin_addr;
1796 if (option_debug) {
1797 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n",
1798 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
1800 } else if (bindaddr.sin_addr.s_addr)
1801 *us = bindaddr.sin_addr;
1802 return AST_SUCCESS;
1805 /*! \brief Append to SIP dialog history
1806 \return Always returns 0 */
1807 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1809 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1810 __attribute__ ((format (printf, 2, 3)));
1812 /*! \brief Append to SIP dialog history with arg list */
1813 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1815 char buf[80], *c = buf; /* max history length */
1816 struct sip_history *hist;
1817 int l;
1819 vsnprintf(buf, sizeof(buf), fmt, ap);
1820 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1821 l = strlen(buf) + 1;
1822 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1823 return;
1824 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1825 free(hist);
1826 return;
1828 memcpy(hist->event, buf, l);
1829 AST_LIST_INSERT_TAIL(p->history, hist, list);
1832 /*! \brief Append to SIP dialog history with arg list */
1833 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1835 va_list ap;
1837 if (!p)
1838 return;
1839 va_start(ap, fmt);
1840 append_history_va(p, fmt, ap);
1841 va_end(ap);
1843 return;
1846 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
1847 static int retrans_pkt(void *data)
1849 struct sip_pkt *pkt = data, *prev, *cur = NULL;
1850 int reschedule = DEFAULT_RETRANS;
1852 /* Lock channel PVT */
1853 ast_mutex_lock(&pkt->owner->lock);
1855 if (pkt->retrans < MAX_RETRANS) {
1856 pkt->retrans++;
1857 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
1858 if (sipdebug && option_debug > 3)
1859 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);
1860 } else {
1861 int siptimer_a;
1863 if (sipdebug && option_debug > 3)
1864 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1865 if (!pkt->timer_a)
1866 pkt->timer_a = 2 ;
1867 else
1868 pkt->timer_a = 2 * pkt->timer_a;
1870 /* For non-invites, a maximum of 4 secs */
1871 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
1872 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1873 siptimer_a = 4000;
1875 /* Reschedule re-transmit */
1876 reschedule = siptimer_a;
1877 if (option_debug > 3)
1878 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);
1881 if (sip_debug_test_pvt(pkt->owner)) {
1882 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
1883 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
1884 pkt->retrans, sip_nat_mode(pkt->owner),
1885 ast_inet_ntoa(dst->sin_addr),
1886 ntohs(dst->sin_port), pkt->data);
1889 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1890 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1891 ast_mutex_unlock(&pkt->owner->lock);
1892 return reschedule;
1894 /* Too many retries */
1895 if (pkt->owner && pkt->method != SIP_OPTIONS) {
1896 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1897 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");
1898 } else {
1899 if ((pkt->method == SIP_OPTIONS) && sipdebug)
1900 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1902 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1904 pkt->retransid = -1;
1906 if (ast_test_flag(pkt, FLAG_FATAL)) {
1907 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
1908 ast_mutex_unlock(&pkt->owner->lock); /* SIP_PVT, not channel */
1909 usleep(1);
1910 ast_mutex_lock(&pkt->owner->lock);
1912 if (pkt->owner->owner) {
1913 sip_alreadygone(pkt->owner);
1914 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1915 ast_queue_hangup(pkt->owner->owner);
1916 ast_channel_unlock(pkt->owner->owner);
1917 } else {
1918 /* If no channel owner, destroy now */
1920 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
1921 if (pkt->method != SIP_OPTIONS)
1922 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
1925 /* In any case, go ahead and remove the packet */
1926 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
1927 if (cur == pkt)
1928 break;
1930 if (cur) {
1931 if (prev)
1932 prev->next = cur->next;
1933 else
1934 pkt->owner->packets = cur->next;
1935 ast_mutex_unlock(&pkt->owner->lock);
1936 free(cur);
1937 pkt = NULL;
1938 } else
1939 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
1940 if (pkt)
1941 ast_mutex_unlock(&pkt->owner->lock);
1942 return 0;
1945 /*! \brief Transmit packet with retransmits
1946 \return 0 on success, -1 on failure to allocate packet
1948 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
1950 struct sip_pkt *pkt;
1951 int siptimer_a = DEFAULT_RETRANS;
1953 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
1954 return AST_FAILURE;
1955 memcpy(pkt->data, data, len);
1956 pkt->method = sipmethod;
1957 pkt->packetlen = len;
1958 pkt->next = p->packets;
1959 pkt->owner = p;
1960 pkt->seqno = seqno;
1961 if (resp)
1962 ast_set_flag(pkt, FLAG_RESPONSE);
1963 pkt->data[len] = '\0';
1964 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
1965 if (fatal)
1966 ast_set_flag(pkt, FLAG_FATAL);
1967 if (pkt->timer_t1)
1968 siptimer_a = pkt->timer_t1 * 2;
1970 /* Schedule retransmission */
1971 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
1972 if (option_debug > 3 && sipdebug)
1973 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt->retransid);
1974 pkt->next = p->packets;
1975 p->packets = pkt;
1977 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
1978 if (sipmethod == SIP_INVITE) {
1979 /* Note this is a pending invite */
1980 p->pendinginvite = seqno;
1982 return AST_SUCCESS;
1985 /*! \brief Kill a SIP dialog (called by scheduler) */
1986 static int __sip_autodestruct(void *data)
1988 struct sip_pvt *p = data;
1990 /* If this is a subscription, tell the phone that we got a timeout */
1991 if (p->subscribed) {
1992 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */
1993 p->subscribed = NONE;
1994 append_history(p, "Subscribestatus", "timeout");
1995 if (option_debug > 2)
1996 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
1997 return 10000; /* Reschedule this destruction so that we know that it's gone */
2000 /* If we're destroying a subscription, dereference peer object too */
2001 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
2002 ASTOBJ_UNREF(p->relatedpeer,sip_destroy_peer);
2004 /* Reset schedule ID */
2005 p->autokillid = -1;
2007 if (option_debug)
2008 ast_log(LOG_DEBUG, "Auto destroying SIP dialog '%s'\n", p->callid);
2009 append_history(p, "AutoDestroy", "%s", p->callid);
2010 if (p->owner) {
2011 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
2012 ast_queue_hangup(p->owner);
2013 } else if (p->refer) {
2014 if (option_debug > 2)
2015 ast_log(LOG_DEBUG, "Finally hanging up channel after transfer: %s\n", p->callid);
2016 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2017 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
2018 } else
2019 sip_destroy(p);
2020 return 0;
2023 /*! \brief Schedule destruction of SIP dialog */
2024 static void sip_scheddestroy(struct sip_pvt *p, int ms)
2026 if (ms < 0) {
2027 if (p->timer_t1 == 0)
2028 p->timer_t1 = 500; /* Set timer T1 if not set (RFC 3261) */
2029 ms = p->timer_t1 * 64;
2031 if (sip_debug_test_pvt(p))
2032 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
2033 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
2034 append_history(p, "SchedDestroy", "%d ms", ms);
2036 if (p->autokillid > -1)
2037 ast_sched_del(sched, p->autokillid);
2038 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
2041 /*! \brief Cancel destruction of SIP dialog */
2042 static void sip_cancel_destroy(struct sip_pvt *p)
2044 if (p->autokillid > -1) {
2045 ast_sched_del(sched, p->autokillid);
2046 append_history(p, "CancelDestroy", "");
2047 p->autokillid = -1;
2051 /*! \brief Acknowledges receipt of a packet and stops retransmission */
2052 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2054 struct sip_pkt *cur, *prev = NULL;
2056 /* Just in case... */
2057 char *msg;
2058 int res = FALSE;
2060 msg = sip_methods[sipmethod].text;
2062 ast_mutex_lock(&p->lock);
2063 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
2064 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
2065 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
2066 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
2067 if (!resp && (seqno == p->pendinginvite)) {
2068 if (option_debug)
2069 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
2070 p->pendinginvite = 0;
2072 /* this is our baby */
2073 res = TRUE;
2074 UNLINK(cur, p->packets, prev);
2075 if (cur->retransid > -1) {
2076 if (sipdebug && option_debug > 3)
2077 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
2078 ast_sched_del(sched, cur->retransid);
2079 cur->retransid = -1;
2081 free(cur);
2082 break;
2085 ast_mutex_unlock(&p->lock);
2086 if (option_debug)
2087 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
2090 /*! \brief Pretend to ack all packets
2091 * maybe the lock on p is not strictly necessary but there might be a race */
2092 static void __sip_pretend_ack(struct sip_pvt *p)
2094 struct sip_pkt *cur = NULL;
2096 while (p->packets) {
2097 int method;
2098 if (cur == p->packets) {
2099 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
2100 return;
2102 cur = p->packets;
2103 method = (cur->method) ? cur->method : find_sip_method(cur->data);
2104 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method);
2108 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2109 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2111 struct sip_pkt *cur;
2112 int res = -1;
2114 for (cur = p->packets; cur; cur = cur->next) {
2115 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
2116 (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
2117 /* this is our baby */
2118 if (cur->retransid > -1) {
2119 if (option_debug > 3 && sipdebug)
2120 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
2121 ast_sched_del(sched, cur->retransid);
2122 cur->retransid = -1;
2124 res = 0;
2125 break;
2128 if (option_debug)
2129 ast_log(LOG_DEBUG, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
2130 return res;
2134 /*! \brief Copy SIP request, parse it */
2135 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2137 memset(dst, 0, sizeof(*dst));
2138 memcpy(dst->data, src->data, sizeof(dst->data));
2139 dst->len = src->len;
2140 parse_request(dst);
2143 /*! \brief add a blank line if no body */
2144 static void add_blank(struct sip_request *req)
2146 if (!req->lines) {
2147 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2148 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2149 req->len += strlen(req->data + req->len);
2153 /*! \brief Transmit response on SIP request*/
2154 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2156 int res;
2158 add_blank(req);
2159 if (sip_debug_test_pvt(p)) {
2160 const struct sockaddr_in *dst = sip_real_dst(p);
2162 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
2163 reliable ? "Reliably " : "", sip_nat_mode(p),
2164 ast_inet_ntoa(dst->sin_addr),
2165 ntohs(dst->sin_port), req->data);
2167 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2168 struct sip_request tmp;
2169 parse_copy(&tmp, req);
2170 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
2171 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
2173 res = (reliable) ?
2174 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2175 __sip_xmit(p, req->data, req->len);
2176 if (res > 0)
2177 return 0;
2178 return res;
2181 /*! \brief Send SIP Request to the other part of the dialogue */
2182 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2184 int res;
2186 add_blank(req);
2187 if (sip_debug_test_pvt(p)) {
2188 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
2189 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);
2190 else
2191 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);
2193 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2194 struct sip_request tmp;
2195 parse_copy(&tmp, req);
2196 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
2198 res = (reliable) ?
2199 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method) :
2200 __sip_xmit(p, req->data, req->len);
2201 return res;
2204 /*! \brief Locate closing quote in a string, skipping escaped quotes.
2205 * optionally with a limit on the search.
2206 * start must be past the first quote.
2208 static const char *find_closing_quote(const char *start, const char *lim)
2210 char last_char = '\0';
2211 const char *s;
2212 for (s = start; *s && s != lim; last_char = *s++) {
2213 if (*s == '"' && last_char != '\\')
2214 break;
2216 return s;
2219 /*! \brief Pick out text in brackets from character string
2220 \return pointer to terminated stripped string
2221 \param tmp input string that will be modified
2222 Examples:
2224 "foo" <bar> valid input, returns bar
2225 foo returns the whole string
2226 < "foo ... > returns the string between brackets
2227 < "foo... bogus (missing closing bracket), returns the whole string
2228 XXX maybe should still skip the opening bracket
2230 static char *get_in_brackets(char *tmp)
2232 const char *parse = tmp;
2233 char *first_bracket;
2236 * Skip any quoted text until we find the part in brackets.
2237 * On any error give up and return the full string.
2239 while ( (first_bracket = strchr(parse, '<')) ) {
2240 char *first_quote = strchr(parse, '"');
2242 if (!first_quote || first_quote > first_bracket)
2243 break; /* no need to look at quoted part */
2244 /* the bracket is within quotes, so ignore it */
2245 parse = find_closing_quote(first_quote + 1, NULL);
2246 if (!*parse) { /* not found, return full string ? */
2247 /* XXX or be robust and return in-bracket part ? */
2248 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
2249 break;
2251 parse++;
2253 if (first_bracket) {
2254 char *second_bracket = strchr(first_bracket + 1, '>');
2255 if (second_bracket) {
2256 *second_bracket = '\0';
2257 tmp = first_bracket + 1;
2258 } else {
2259 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
2262 return tmp;
2265 /*! \brief Send SIP MESSAGE text within a call
2266 Called from PBX core sendtext() application */
2267 static int sip_sendtext(struct ast_channel *ast, const char *text)
2269 struct sip_pvt *p = ast->tech_pvt;
2270 int debug = sip_debug_test_pvt(p);
2272 if (debug)
2273 ast_verbose("Sending text %s on %s\n", text, ast->name);
2274 if (!p)
2275 return -1;
2276 if (ast_strlen_zero(text))
2277 return 0;
2278 if (debug)
2279 ast_verbose("Really sending text %s on %s\n", text, ast->name);
2280 transmit_message_with_text(p, text);
2281 return 0;
2284 /*! \brief Update peer object in realtime storage
2285 If the Asterisk system name is set in asterisk.conf, we will use
2286 that name and store that in the "regserver" field in the sippeers
2287 table to facilitate multi-server setups.
2289 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
2291 char port[10];
2292 char ipaddr[INET_ADDRSTRLEN];
2293 char regseconds[20];
2295 char *sysname = ast_config_AST_SYSTEM_NAME;
2296 char *syslabel = NULL;
2298 time_t nowtime = time(NULL) + expirey;
2299 const char *fc = fullcontact ? "fullcontact" : NULL;
2301 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
2302 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2303 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2305 if (ast_strlen_zero(sysname)) /* No system name, disable this */
2306 sysname = NULL;
2307 else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME))
2308 syslabel = "regserver";
2310 if (fc)
2311 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2312 "port", port, "regseconds", regseconds,
2313 "username", username, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
2314 else
2315 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2316 "port", port, "regseconds", regseconds,
2317 "username", username, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
2320 /*! \brief Automatically add peer extension to dial plan */
2321 static void register_peer_exten(struct sip_peer *peer, int onoff)
2323 char multi[256];
2324 char *stringp, *ext, *context;
2326 /* XXX note that global_regcontext is both a global 'enable' flag and
2327 * the name of the global regexten context, if not specified
2328 * individually.
2330 if (ast_strlen_zero(global_regcontext))
2331 return;
2333 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
2334 stringp = multi;
2335 while ((ext = strsep(&stringp, "&"))) {
2336 if ((context = strchr(ext, '@'))) {
2337 *context++ = '\0'; /* split ext@context */
2338 if (!ast_context_find(context)) {
2339 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
2340 continue;
2342 } else {
2343 context = global_regcontext;
2345 if (onoff)
2346 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2347 ast_strdup(peer->name), ast_free, "SIP");
2348 else
2349 ast_context_remove_extension(context, ext, 1, NULL);
2353 /*! \brief Destroy peer object from memory */
2354 static void sip_destroy_peer(struct sip_peer *peer)
2356 if (option_debug > 2)
2357 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
2359 /* Delete it, it needs to disappear */
2360 if (peer->call)
2361 sip_destroy(peer->call);
2363 if (peer->mwipvt) /* We have an active subscription, delete it */
2364 sip_destroy(peer->mwipvt);
2366 if (peer->chanvars) {
2367 ast_variables_destroy(peer->chanvars);
2368 peer->chanvars = NULL;
2370 if (peer->expire > -1)
2371 ast_sched_del(sched, peer->expire);
2373 if (peer->pokeexpire > -1)
2374 ast_sched_del(sched, peer->pokeexpire);
2375 register_peer_exten(peer, FALSE);
2376 ast_free_ha(peer->ha);
2377 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
2378 apeerobjs--;
2379 else if (ast_test_flag(&peer->flags[0], SIP_REALTIME))
2380 rpeerobjs--;
2381 else
2382 speerobjs--;
2383 clear_realm_authentication(peer->auth);
2384 peer->auth = NULL;
2385 free(peer);
2388 /*! \brief Update peer data in database (if used) */
2389 static void update_peer(struct sip_peer *p, int expiry)
2391 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2392 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
2393 (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
2394 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
2399 /*! \brief realtime_peer: Get peer from realtime storage
2400 * Checks the "sippeers" realtime family from extconfig.conf
2401 * \todo Consider adding check of port address when matching here to follow the same
2402 * algorithm as for static peers. Will we break anything by adding that?
2404 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
2406 struct sip_peer *peer;
2407 struct ast_variable *var = NULL;
2408 struct ast_variable *tmp;
2409 char ipaddr[INET_ADDRSTRLEN];
2411 /* First check on peer name */
2412 if (newpeername)
2413 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
2414 else if (sin) { /* Then check on IP address for dynamic peers */
2415 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2416 var = ast_load_realtime("sippeers", "host", ipaddr, NULL); /* First check for fixed IP hosts */
2417 if (!var)
2418 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, NULL); /* Then check for registred hosts */
2421 if (!var)
2422 return NULL;
2424 for (tmp = var; tmp; tmp = tmp->next) {
2425 /* If this is type=user, then skip this object. */
2426 if (!strcasecmp(tmp->name, "type") &&
2427 !strcasecmp(tmp->value, "user")) {
2428 ast_variables_destroy(var);
2429 return NULL;
2430 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
2431 newpeername = tmp->value;
2435 if (!newpeername) { /* Did not find peer in realtime */
2436 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
2437 ast_variables_destroy(var);
2438 return NULL;
2441 /* Peer found in realtime, now build it in memory */
2442 peer = build_peer(newpeername, var, NULL, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2443 if (!peer) {
2444 ast_variables_destroy(var);
2445 return NULL;
2448 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2449 /* Cache peer */
2450 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
2451 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
2452 if (peer->expire > -1) {
2453 ast_sched_del(sched, peer->expire);
2455 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
2457 ASTOBJ_CONTAINER_LINK(&peerl,peer);
2458 } else {
2459 ast_set_flag(&peer->flags[0], SIP_REALTIME);
2461 ast_variables_destroy(var);
2463 return peer;
2466 /*! \brief Support routine for find_peer */
2467 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
2469 /* We know name is the first field, so we can cast */
2470 struct sip_peer *p = (struct sip_peer *) name;
2471 return !(!inaddrcmp(&p->addr, sin) ||
2472 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
2473 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
2476 /*! \brief Locate peer by name or ip address
2477 * This is used on incoming SIP message to find matching peer on ip
2478 or outgoing message to find matching peer on name */
2479 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
2481 struct sip_peer *p = NULL;
2483 if (peer)
2484 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
2485 else
2486 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
2488 if (!p && realtime)
2489 p = realtime_peer(peer, sin);
2491 return p;
2494 /*! \brief Remove user object from in-memory storage */
2495 static void sip_destroy_user(struct sip_user *user)
2497 if (option_debug > 2)
2498 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
2499 ast_free_ha(user->ha);
2500 if (user->chanvars) {
2501 ast_variables_destroy(user->chanvars);
2502 user->chanvars = NULL;
2504 if (ast_test_flag(&user->flags[0], SIP_REALTIME))
2505 ruserobjs--;
2506 else
2507 suserobjs--;
2508 free(user);
2511 /*! \brief Load user from realtime storage
2512 * Loads user from "sipusers" category in realtime (extconfig.conf)
2513 * Users are matched on From: user name (the domain in skipped) */
2514 static struct sip_user *realtime_user(const char *username)
2516 struct ast_variable *var;
2517 struct ast_variable *tmp;
2518 struct sip_user *user = NULL;
2520 var = ast_load_realtime("sipusers", "name", username, NULL);
2522 if (!var)
2523 return NULL;
2525 for (tmp = var; tmp; tmp = tmp->next) {
2526 if (!strcasecmp(tmp->name, "type") &&
2527 !strcasecmp(tmp->value, "peer")) {
2528 ast_variables_destroy(var);
2529 return NULL;
2533 user = build_user(username, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2535 if (!user) { /* No user found */
2536 ast_variables_destroy(var);
2537 return NULL;
2540 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2541 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2542 suserobjs++;
2543 ASTOBJ_CONTAINER_LINK(&userl,user);
2544 } else {
2545 /* Move counter from s to r... */
2546 suserobjs--;
2547 ruserobjs++;
2548 ast_set_flag(&user->flags[0], SIP_REALTIME);
2550 ast_variables_destroy(var);
2551 return user;
2554 /*! \brief Locate user by name
2555 * Locates user by name (From: sip uri user name part) first
2556 * from in-memory list (static configuration) then from
2557 * realtime storage (defined in extconfig.conf) */
2558 static struct sip_user *find_user(const char *name, int realtime)
2560 struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
2561 if (!u && realtime)
2562 u = realtime_user(name);
2563 return u;
2566 /*! \brief Set nat mode on the various data sockets */
2567 static void do_setnat(struct sip_pvt *p, int natflags)
2569 const char *mode = natflags ? "On" : "Off";
2571 if (p->rtp) {
2572 if (option_debug)
2573 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", mode);
2574 ast_rtp_setnat(p->rtp, natflags);
2576 if (p->vrtp) {
2577 if (option_debug)
2578 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", mode);
2579 ast_rtp_setnat(p->vrtp, natflags);
2581 if (p->udptl) {
2582 if (option_debug)
2583 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", mode);
2584 ast_udptl_setnat(p->udptl, natflags);
2588 /*! \brief Create address structure from peer reference.
2589 * return -1 on error, 0 on success.
2591 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
2593 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
2594 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
2595 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
2596 dialog->recv = dialog->sa;
2597 } else
2598 return -1;
2600 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
2601 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
2602 dialog->capability = peer->capability;
2603 if ((!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(dialog->capability & AST_FORMAT_VIDEO_MASK)) && dialog->vrtp) {
2604 ast_rtp_destroy(dialog->vrtp);
2605 dialog->vrtp = NULL;
2607 dialog->prefs = peer->prefs;
2608 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
2609 dialog->t38.capability = global_t38_capability;
2610 if (dialog->udptl) {
2611 if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_FEC )
2612 dialog->t38.capability |= T38FAX_UDP_EC_FEC;
2613 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
2614 dialog->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
2615 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_NONE )
2616 dialog->t38.capability |= T38FAX_UDP_EC_NONE;
2617 dialog->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
2618 if (option_debug > 1)
2619 ast_log(LOG_DEBUG,"Our T38 capability (%d)\n", dialog->t38.capability);
2621 dialog->t38.jointcapability = dialog->t38.capability;
2622 } else if (dialog->udptl) {
2623 ast_udptl_destroy(dialog->udptl);
2624 dialog->udptl = NULL;
2626 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE );
2628 if (dialog->rtp) {
2629 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
2630 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
2631 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
2632 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
2633 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
2634 /* Set Frame packetization */
2635 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
2636 dialog->autoframing = peer->autoframing;
2638 if (dialog->vrtp) {
2639 ast_rtp_setdtmf(dialog->vrtp, 0);
2640 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
2641 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
2642 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
2643 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
2646 ast_string_field_set(dialog, peername, peer->username);
2647 ast_string_field_set(dialog, authname, peer->username);
2648 ast_string_field_set(dialog, username, peer->username);
2649 ast_string_field_set(dialog, peersecret, peer->secret);
2650 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
2651 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
2652 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
2653 ast_string_field_set(dialog, tohost, peer->tohost);
2654 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
2655 if (!dialog->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
2656 char *tmpcall;
2657 char *c;
2658 tmpcall = ast_strdupa(dialog->callid);
2659 c = strchr(tmpcall, '@');
2660 if (c) {
2661 *c = '\0';
2662 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
2665 if (ast_strlen_zero(dialog->tohost))
2666 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
2667 if (!ast_strlen_zero(peer->fromdomain))
2668 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
2669 if (!ast_strlen_zero(peer->fromuser))
2670 ast_string_field_set(dialog, fromuser, peer->fromuser);
2671 dialog->maxtime = peer->maxms;
2672 dialog->callgroup = peer->callgroup;
2673 dialog->pickupgroup = peer->pickupgroup;
2674 dialog->allowtransfer = peer->allowtransfer;
2675 /* Set timer T1 to RTT for this peer (if known by qualify=) */
2676 /* Minimum is settable or default to 100 ms */
2677 if (peer->maxms && peer->lastms)
2678 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
2679 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
2680 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
2681 dialog->noncodeccapability |= AST_RTP_DTMF;
2682 else
2683 dialog->noncodeccapability &= ~AST_RTP_DTMF;
2684 ast_string_field_set(dialog, context, peer->context);
2685 dialog->rtptimeout = peer->rtptimeout;
2686 if (peer->call_limit)
2687 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
2688 dialog->maxcallbitrate = peer->maxcallbitrate;
2690 return 0;
2693 /*! \brief create address structure from peer name
2694 * Or, if peer not found, find it in the global DNS
2695 * returns TRUE (-1) on failure, FALSE on success */
2696 static int create_addr(struct sip_pvt *dialog, const char *opeer)
2698 struct hostent *hp;
2699 struct ast_hostent ahp;
2700 struct sip_peer *p;
2701 char *port;
2702 int portno;
2703 char host[MAXHOSTNAMELEN], *hostn;
2704 char peer[256];
2706 ast_copy_string(peer, opeer, sizeof(peer));
2707 port = strchr(peer, ':');
2708 if (port)
2709 *port++ = '\0';
2710 dialog->sa.sin_family = AF_INET;
2711 dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
2712 p = find_peer(peer, NULL, 1);
2714 if (p) {
2715 int res = create_addr_from_peer(dialog, p);
2716 ASTOBJ_UNREF(p, sip_destroy_peer);
2717 return res;
2719 hostn = peer;
2720 portno = port ? atoi(port) : STANDARD_SIP_PORT;
2721 if (srvlookup) {
2722 char service[MAXHOSTNAMELEN];
2723 int tportno;
2724 int ret;
2726 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
2727 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
2728 if (ret > 0) {
2729 hostn = host;
2730 portno = tportno;
2733 hp = ast_gethostbyname(hostn, &ahp);
2734 if (!hp) {
2735 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2736 return -1;
2738 ast_string_field_set(dialog, tohost, peer);
2739 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
2740 dialog->sa.sin_port = htons(portno);
2741 dialog->recv = dialog->sa;
2742 return 0;
2745 /*! \brief Scheduled congestion on a call */
2746 static int auto_congest(void *nothing)
2748 struct sip_pvt *p = nothing;
2750 ast_mutex_lock(&p->lock);
2751 p->initid = -1;
2752 if (p->owner) {
2753 /* XXX fails on possible deadlock */
2754 if (!ast_channel_trylock(p->owner)) {
2755 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
2756 append_history(p, "Cong", "Auto-congesting (timer)");
2757 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
2758 ast_channel_unlock(p->owner);
2761 ast_mutex_unlock(&p->lock);
2762 return 0;
2766 /*! \brief Initiate SIP call from PBX
2767 * used from the dial() application */
2768 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2770 int res;
2771 struct sip_pvt *p;
2772 struct varshead *headp;
2773 struct ast_var_t *current;
2774 const char *referer = NULL; /* SIP refererer */
2776 p = ast->tech_pvt;
2777 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2778 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2779 return -1;
2782 /* Check whether there is vxml_url, distinctive ring variables */
2783 headp=&ast->varshead;
2784 AST_LIST_TRAVERSE(headp,current,entries) {
2785 /* Check whether there is a VXML_URL variable */
2786 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2787 p->options->vxml_url = ast_var_value(current);
2788 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
2789 p->options->uri_options = ast_var_value(current);
2790 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
2791 /* Check whether there is a ALERT_INFO variable */
2792 p->options->distinctive_ring = ast_var_value(current);
2793 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2794 /* Check whether there is a variable with a name starting with SIPADDHEADER */
2795 p->options->addsipheaders = 1;
2796 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
2797 /* This is a transfered call */
2798 p->options->transfer = 1;
2799 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
2800 /* This is the referer */
2801 referer = ast_var_value(current);
2802 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
2803 /* We're replacing a call. */
2804 p->options->replaces = ast_var_value(current);
2805 } else if (!strcasecmp(ast_var_name(current), "T38CALL")) {
2806 p->t38.state = T38_LOCAL_DIRECT;
2807 if (option_debug)
2808 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
2813 res = 0;
2814 ast_set_flag(&p->flags[0], SIP_OUTGOING);
2816 if (p->options->transfer) {
2817 char buf[BUFSIZ/2];
2819 if (referer) {
2820 if (sipdebug && option_debug > 2)
2821 ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->username, referer);
2822 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
2823 } else
2824 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
2825 ast_string_field_set(p, cid_name, buf);
2827 if (option_debug)
2828 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
2830 res = update_call_counter(p, INC_CALL_RINGING);
2831 if ( res != -1 ) {
2832 p->callingpres = ast->cid.cid_pres;
2833 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
2834 p->jointnoncodeccapability = p->noncodeccapability;
2836 /* If there are no audio formats left to offer, punt */
2837 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
2838 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
2839 res = -1;
2840 } else {
2841 p->t38.jointcapability = p->t38.capability;
2842 if (option_debug > 1)
2843 ast_log(LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
2844 transmit_invite(p, SIP_INVITE, 1, 2);
2845 p->invitestate = INV_CALLING;
2847 /* Initialize auto-congest time */
2848 p->initid = ast_sched_add(sched, p->maxtime ? (p->maxtime * 4) : SIP_TRANS_TIMEOUT, auto_congest, p);
2851 return res;
2854 /*! \brief Destroy registry object
2855 Objects created with the register= statement in static configuration */
2856 static void sip_registry_destroy(struct sip_registry *reg)
2858 /* Really delete */
2859 if (option_debug > 2)
2860 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
2862 if (reg->call) {
2863 /* Clear registry before destroying to ensure
2864 we don't get reentered trying to grab the registry lock */
2865 reg->call->registry = NULL;
2866 if (option_debug > 2)
2867 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
2868 sip_destroy(reg->call);
2870 if (reg->expire > -1)
2871 ast_sched_del(sched, reg->expire);
2872 if (reg->timeout > -1)
2873 ast_sched_del(sched, reg->timeout);
2874 ast_string_field_free_pools(reg);
2875 regobjs--;
2876 free(reg);
2880 /*! \brief Execute destruction of SIP dialog structure, release memory */
2881 static void __sip_destroy(struct sip_pvt *p, int lockowner)
2883 struct sip_pvt *cur, *prev = NULL;
2884 struct sip_pkt *cp;
2886 if (sip_debug_test_pvt(p) || option_debug > 2)
2887 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
2889 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT)) {
2890 update_call_counter(p, DEC_CALL_LIMIT);
2891 if (option_debug > 1)
2892 ast_log(LOG_DEBUG, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
2895 /* Remove link from peer to subscription of MWI */
2896 if (p->relatedpeer && p->relatedpeer->mwipvt)
2897 p->relatedpeer->mwipvt = NULL;
2899 if (dumphistory)
2900 sip_dump_history(p);
2902 if (p->options)
2903 free(p->options);
2905 if (p->stateid > -1)
2906 ast_extension_state_del(p->stateid, NULL);
2907 if (p->initid > -1)
2908 ast_sched_del(sched, p->initid);
2909 if (p->autokillid > -1)
2910 ast_sched_del(sched, p->autokillid);
2912 if (p->rtp)
2913 ast_rtp_destroy(p->rtp);
2914 if (p->vrtp)
2915 ast_rtp_destroy(p->vrtp);
2916 if (p->udptl)
2917 ast_udptl_destroy(p->udptl);
2918 if (p->refer)
2919 free(p->refer);
2920 if (p->route) {
2921 free_old_route(p->route);
2922 p->route = NULL;
2924 if (p->registry) {
2925 if (p->registry->call == p)
2926 p->registry->call = NULL;
2927 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
2930 /* Unlink us from the owner if we have one */
2931 if (p->owner) {
2932 if (lockowner)
2933 ast_channel_lock(p->owner);
2934 if (option_debug)
2935 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
2936 p->owner->tech_pvt = NULL;
2937 if (lockowner)
2938 ast_channel_unlock(p->owner);
2940 /* Clear history */
2941 if (p->history) {
2942 struct sip_history *hist;
2943 while( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) )
2944 free(hist);
2945 free(p->history);
2946 p->history = NULL;
2949 for (prev = NULL, cur = iflist; cur; prev = cur, cur = cur->next) {
2950 if (cur == p) {
2951 UNLINK(cur, iflist, prev);
2952 break;
2955 if (!cur) {
2956 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
2957 return;
2960 /* remove all current packets in this dialog */
2961 while((cp = p->packets)) {
2962 p->packets = p->packets->next;
2963 if (cp->retransid > -1)
2964 ast_sched_del(sched, cp->retransid);
2965 free(cp);
2967 if (p->chanvars) {
2968 ast_variables_destroy(p->chanvars);
2969 p->chanvars = NULL;
2971 ast_mutex_destroy(&p->lock);
2973 ast_string_field_free_pools(p);
2975 free(p);
2978 /*! \brief update_call_counter: Handle call_limit for SIP users
2979 * Setting a call-limit will cause calls above the limit not to be accepted.
2981 * Remember that for a type=friend, there's one limit for the user and
2982 * another for the peer, not a combined call limit.
2983 * This will cause unexpected behaviour in subscriptions, since a "friend"
2984 * is *two* devices in Asterisk, not one.
2986 * Thought: For realtime, we should propably update storage with inuse counter...
2988 * \return 0 if call is ok (no call limit, below treshold)
2989 * -1 on rejection of call
2992 static int update_call_counter(struct sip_pvt *fup, int event)
2994 char name[256];
2995 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
2996 int outgoing = ast_test_flag(&fup->flags[1], SIP_PAGE2_OUTGOING_CALL);
2997 struct sip_user *u = NULL;
2998 struct sip_peer *p = NULL;
3000 if (option_debug > 2)
3001 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
3002 /* Test if we need to check call limits, in order to avoid
3003 realtime lookups if we do not need it */
3004 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT))
3005 return 0;
3007 ast_copy_string(name, fup->username, sizeof(name));
3009 /* Check the list of users only for incoming calls */
3010 if (global_limitonpeers == FALSE && !outgoing && (u = find_user(name, 1))) {
3011 inuse = &u->inUse;
3012 call_limit = &u->call_limit;
3013 inringing = NULL;
3014 } else if ( (p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, 1) ) ) { /* Try to find peer */
3015 inuse = &p->inUse;
3016 call_limit = &p->call_limit;
3017 inringing = &p->inRinging;
3018 ast_copy_string(name, fup->peername, sizeof(name));
3020 if (!p && !u) {
3021 if (option_debug > 1)
3022 ast_log(LOG_DEBUG, "%s is not a local device, no call limit\n", name);
3023 return 0;
3026 switch(event) {
3027 /* incoming and outgoing affects the inUse counter */
3028 case DEC_CALL_LIMIT:
3029 if ( *inuse > 0 ) {
3030 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
3031 (*inuse)--;
3032 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
3034 } else {
3035 *inuse = 0;
3037 if (inringing) {
3038 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3039 if (*inringing > 0)
3040 (*inringing)--;
3041 else
3042 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", fup->peername);
3043 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3046 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && global_notifyhold)
3047 sip_peer_hold(fup, 0);
3048 if (option_debug > 1 || sipdebug) {
3049 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
3051 break;
3053 case INC_CALL_RINGING:
3054 case INC_CALL_LIMIT:
3055 if (*call_limit > 0 ) {
3056 if (*inuse >= *call_limit) {
3057 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);
3058 if (u)
3059 ASTOBJ_UNREF(u, sip_destroy_user);
3060 else
3061 ASTOBJ_UNREF(p, sip_destroy_peer);
3062 return -1;
3065 if (inringing && (event == INC_CALL_RINGING)) {
3066 if (!ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3067 (*inringing)++;
3068 ast_set_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3071 /* Continue */
3072 (*inuse)++;
3073 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
3074 if (option_debug > 1 || sipdebug) {
3075 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
3077 break;
3079 case DEC_CALL_RINGING:
3080 if (inringing) {
3081 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3082 if (*inringing > 0)
3083 (*inringing)--;
3084 else
3085 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", p->name);
3086 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3089 break;
3091 default:
3092 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
3094 if (p) {
3095 ast_device_state_changed("SIP/%s", p->name);
3096 ASTOBJ_UNREF(p, sip_destroy_peer);
3097 } else /* u must be set */
3098 ASTOBJ_UNREF(u, sip_destroy_user);
3099 return 0;
3102 /*! \brief Destroy SIP call structure */
3103 static void sip_destroy(struct sip_pvt *p)
3105 ast_mutex_lock(&iflock);
3106 if (option_debug > 2)
3107 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
3108 __sip_destroy(p, 1);
3109 ast_mutex_unlock(&iflock);
3112 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
3113 static int hangup_sip2cause(int cause)
3115 /* Possible values taken from causes.h */
3117 switch(cause) {
3118 case 401: /* Unauthorized */
3119 return AST_CAUSE_CALL_REJECTED;
3120 case 403: /* Not found */
3121 return AST_CAUSE_CALL_REJECTED;
3122 case 404: /* Not found */
3123 return AST_CAUSE_UNALLOCATED;
3124 case 405: /* Method not allowed */
3125 return AST_CAUSE_INTERWORKING;
3126 case 407: /* Proxy authentication required */
3127 return AST_CAUSE_CALL_REJECTED;
3128 case 408: /* No reaction */
3129 return AST_CAUSE_NO_USER_RESPONSE;
3130 case 409: /* Conflict */
3131 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
3132 case 410: /* Gone */
3133 return AST_CAUSE_UNALLOCATED;
3134 case 411: /* Length required */
3135 return AST_CAUSE_INTERWORKING;
3136 case 413: /* Request entity too large */
3137 return AST_CAUSE_INTERWORKING;
3138 case 414: /* Request URI too large */
3139 return AST_CAUSE_INTERWORKING;
3140 case 415: /* Unsupported media type */
3141 return AST_CAUSE_INTERWORKING;
3142 case 420: /* Bad extension */
3143 return AST_CAUSE_NO_ROUTE_DESTINATION;
3144 case 480: /* No answer */
3145 return AST_CAUSE_NO_ANSWER;
3146 case 481: /* No answer */
3147 return AST_CAUSE_INTERWORKING;
3148 case 482: /* Loop detected */
3149 return AST_CAUSE_INTERWORKING;
3150 case 483: /* Too many hops */
3151 return AST_CAUSE_NO_ANSWER;
3152 case 484: /* Address incomplete */
3153 return AST_CAUSE_INVALID_NUMBER_FORMAT;
3154 case 485: /* Ambigous */
3155 return AST_CAUSE_UNALLOCATED;
3156 case 486: /* Busy everywhere */
3157 return AST_CAUSE_BUSY;
3158 case 487: /* Request terminated */
3159 return AST_CAUSE_INTERWORKING;
3160 case 488: /* No codecs approved */
3161 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3162 case 491: /* Request pending */
3163 return AST_CAUSE_INTERWORKING;
3164 case 493: /* Undecipherable */
3165 return AST_CAUSE_INTERWORKING;
3166 case 500: /* Server internal failure */
3167 return AST_CAUSE_FAILURE;
3168 case 501: /* Call rejected */
3169 return AST_CAUSE_FACILITY_REJECTED;
3170 case 502:
3171 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
3172 case 503: /* Service unavailable */
3173 return AST_CAUSE_CONGESTION;
3174 case 504: /* Gateway timeout */
3175 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
3176 case 505: /* SIP version not supported */
3177 return AST_CAUSE_INTERWORKING;
3178 case 600: /* Busy everywhere */
3179 return AST_CAUSE_USER_BUSY;
3180 case 603: /* Decline */
3181 return AST_CAUSE_CALL_REJECTED;
3182 case 604: /* Does not exist anywhere */
3183 return AST_CAUSE_UNALLOCATED;
3184 case 606: /* Not acceptable */
3185 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3186 default:
3187 return AST_CAUSE_NORMAL;
3189 /* Never reached */
3190 return 0;
3193 /*! \brief Convert Asterisk hangup causes to SIP codes
3194 \verbatim
3195 Possible values from causes.h
3196 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
3197 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
3199 In addition to these, a lot of PRI codes is defined in causes.h
3200 ...should we take care of them too ?
3202 Quote RFC 3398
3204 ISUP Cause value SIP response
3205 ---------------- ------------
3206 1 unallocated number 404 Not Found
3207 2 no route to network 404 Not found
3208 3 no route to destination 404 Not found
3209 16 normal call clearing --- (*)
3210 17 user busy 486 Busy here
3211 18 no user responding 408 Request Timeout
3212 19 no answer from the user 480 Temporarily unavailable
3213 20 subscriber absent 480 Temporarily unavailable
3214 21 call rejected 403 Forbidden (+)
3215 22 number changed (w/o diagnostic) 410 Gone
3216 22 number changed (w/ diagnostic) 301 Moved Permanently
3217 23 redirection to new destination 410 Gone
3218 26 non-selected user clearing 404 Not Found (=)
3219 27 destination out of order 502 Bad Gateway
3220 28 address incomplete 484 Address incomplete
3221 29 facility rejected 501 Not implemented
3222 31 normal unspecified 480 Temporarily unavailable
3223 \endverbatim
3225 static const char *hangup_cause2sip(int cause)
3227 switch (cause) {
3228 case AST_CAUSE_UNALLOCATED: /* 1 */
3229 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
3230 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
3231 return "404 Not Found";
3232 case AST_CAUSE_CONGESTION: /* 34 */
3233 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
3234 return "503 Service Unavailable";
3235 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
3236 return "408 Request Timeout";
3237 case AST_CAUSE_NO_ANSWER: /* 19 */
3238 return "480 Temporarily unavailable";
3239 case AST_CAUSE_CALL_REJECTED: /* 21 */
3240 return "403 Forbidden";
3241 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
3242 return "410 Gone";
3243 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
3244 return "480 Temporarily unavailable";
3245 case AST_CAUSE_INVALID_NUMBER_FORMAT:
3246 return "484 Address incomplete";
3247 case AST_CAUSE_USER_BUSY:
3248 return "486 Busy here";
3249 case AST_CAUSE_FAILURE:
3250 return "500 Server internal failure";
3251 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
3252 return "501 Not Implemented";
3253 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
3254 return "503 Service Unavailable";
3255 /* Used in chan_iax2 */
3256 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
3257 return "502 Bad Gateway";
3258 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
3259 return "488 Not Acceptable Here";
3261 case AST_CAUSE_NOTDEFINED:
3262 default:
3263 if (option_debug)
3264 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
3265 return NULL;
3268 /* Never reached */
3269 return 0;
3273 /*! \brief sip_hangup: Hangup SIP call
3274 * Part of PBX interface, called from ast_hangup */
3275 static int sip_hangup(struct ast_channel *ast)
3277 struct sip_pvt *p = ast->tech_pvt;
3278 int needcancel = FALSE;
3279 int needdestroy = 0;
3280 struct ast_channel *oldowner = ast;
3282 if (!p) {
3283 if (option_debug)
3284 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
3285 return 0;
3288 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
3289 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT)) {
3290 if (option_debug && sipdebug)
3291 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
3292 update_call_counter(p, DEC_CALL_LIMIT);
3294 if (option_debug >3)
3295 ast_log(LOG_DEBUG, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
3296 if (p->autokillid > -1)
3297 sip_cancel_destroy(p);
3298 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3299 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
3300 ast_clear_flag(&p->flags[0], SIP_NEEDDESTROY);
3301 p->owner->tech_pvt = NULL;
3302 p->owner = NULL; /* Owner will be gone after we return, so take it away */
3303 return 0;
3305 if (option_debug) {
3306 if (ast_test_flag(ast, AST_FLAG_ZOMBIE) && p->refer && option_debug)
3307 ast_log(LOG_DEBUG, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
3308 else {
3309 if (option_debug)
3310 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
3313 if (option_debug && ast_test_flag(ast, AST_FLAG_ZOMBIE))
3314 ast_log(LOG_DEBUG, "Hanging up zombie call. Be scared.\n");
3316 ast_mutex_lock(&p->lock);
3317 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT)) {
3318 if (option_debug && sipdebug)
3319 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
3320 update_call_counter(p, DEC_CALL_LIMIT);
3323 /* Determine how to disconnect */
3324 if (p->owner != ast) {
3325 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
3326 ast_mutex_unlock(&p->lock);
3327 return 0;
3329 /* If the call is not UP, we need to send CANCEL instead of BYE */
3330 if (ast->_state == AST_STATE_RING || ast->_state == AST_STATE_RINGING || (p->invitestate < INV_COMPLETED && ast->_state != AST_STATE_UP)) {
3331 needcancel = TRUE;
3332 if (option_debug > 3)
3333 ast_log(LOG_DEBUG, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
3336 /* Disconnect */
3337 if (p->vad)
3338 ast_dsp_free(p->vad);
3340 p->owner = NULL;
3341 ast->tech_pvt = NULL;
3343 ast_module_unref(ast_module_info->self);
3345 /* Do not destroy this pvt until we have timeout or
3346 get an answer to the BYE or INVITE/CANCEL
3347 If we get no answer during retransmit period, drop the call anyway.
3348 (Sorry, mother-in-law, you can't deny a hangup by sending
3349 603 declined to BYE...)
3351 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE))
3352 needdestroy = 1; /* Set destroy flag at end of this function */
3353 else if (p->invitestate != INV_CALLING)
3354 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3356 /* Start the process if it's not already started */
3357 if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
3358 if (needcancel) { /* Outgoing call, not up */
3359 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3360 /* stop retransmitting an INVITE that has not received a response */
3361 __sip_pretend_ack(p);
3363 /* if we can't send right now, mark it pending */
3364 if (p->invitestate == INV_CALLING) {
3365 /* We can't send anything in CALLING state */
3366 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3367 /* Do we need a timer here if we don't hear from them at all? */
3368 } else {
3369 /* Send a new request: CANCEL */
3370 transmit_request(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, FALSE);
3371 /* Actually don't destroy us yet, wait for the 487 on our original
3372 INVITE, but do set an autodestruct just in case we never get it. */
3373 needdestroy = 0;
3374 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3376 if ( p->initid != -1 ) {
3377 /* channel still up - reverse dec of inUse counter
3378 only if the channel is not auto-congested */
3379 update_call_counter(p, INC_CALL_LIMIT);
3381 } else { /* Incoming call, not up */
3382 const char *res;
3383 if (ast->hangupcause && (res = hangup_cause2sip(ast->hangupcause)))
3384 transmit_response_reliable(p, res, &p->initreq);
3385 else
3386 transmit_response_reliable(p, "603 Declined", &p->initreq);
3388 } else { /* Call is in UP state, send BYE */
3389 if (!p->pendinginvite) {
3390 char *audioqos = "";
3391 char *videoqos = "";
3392 if (p->rtp)
3393 audioqos = ast_rtp_get_quality(p->rtp);
3394 if (p->vrtp)
3395 videoqos = ast_rtp_get_quality(p->vrtp);
3396 /* Send a hangup */
3397 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3399 /* Get RTCP quality before end of call */
3400 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
3401 if (p->rtp)
3402 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
3403 if (p->vrtp)
3404 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
3406 if (p->rtp && oldowner)
3407 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
3408 if (p->vrtp && oldowner)
3409 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
3410 } else {
3411 /* Note we will need a BYE when this all settles out
3412 but we can't send one while we have "INVITE" outstanding. */
3413 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3414 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
3415 sip_cancel_destroy(p);
3419 if (needdestroy)
3420 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
3421 ast_mutex_unlock(&p->lock);
3422 return 0;
3425 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
3426 static void try_suggested_sip_codec(struct sip_pvt *p)
3428 int fmt;
3429 const char *codec;
3431 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
3432 if (!codec)
3433 return;
3435 fmt = ast_getformatbyname(codec);
3436 if (fmt) {
3437 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
3438 if (p->jointcapability & fmt) {
3439 p->jointcapability &= fmt;
3440 p->capability &= fmt;
3441 } else
3442 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
3443 } else
3444 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
3445 return;
3448 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
3449 * Part of PBX interface */
3450 static int sip_answer(struct ast_channel *ast)
3452 int res = 0;
3453 struct sip_pvt *p = ast->tech_pvt;
3455 ast_mutex_lock(&p->lock);
3456 if (ast->_state != AST_STATE_UP) {
3457 try_suggested_sip_codec(p);
3459 ast_setstate(ast, AST_STATE_UP);
3460 if (option_debug)
3461 ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name);
3462 if (p->t38.state == T38_PEER_DIRECT) {
3463 p->t38.state = T38_ENABLED;
3464 if (option_debug > 1)
3465 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
3466 res = transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
3467 } else
3468 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
3470 ast_mutex_unlock(&p->lock);
3471 return res;
3474 /*! \brief Send frame to media channel (rtp) */
3475 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
3477 struct sip_pvt *p = ast->tech_pvt;
3478 int res = 0;
3480 switch (frame->frametype) {
3481 case AST_FRAME_VOICE:
3482 if (!(frame->subclass & ast->nativeformats)) {
3483 char s1[512], s2[512], s3[512];
3484 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
3485 frame->subclass,
3486 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
3487 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
3488 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
3489 ast->readformat,
3490 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
3491 ast->writeformat);
3492 return 0;
3494 if (p) {
3495 ast_mutex_lock(&p->lock);
3496 if (p->rtp) {
3497 /* If channel is not up, activate early media session */
3498 if ((ast->_state != AST_STATE_UP) &&
3499 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3500 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3501 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3502 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3504 p->lastrtptx = time(NULL);
3505 res = ast_rtp_write(p->rtp, frame);
3507 ast_mutex_unlock(&p->lock);
3509 break;
3510 case AST_FRAME_VIDEO:
3511 if (p) {
3512 ast_mutex_lock(&p->lock);
3513 if (p->vrtp) {
3514 /* Activate video early media */
3515 if ((ast->_state != AST_STATE_UP) &&
3516 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3517 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3518 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3519 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3521 p->lastrtptx = time(NULL);
3522 res = ast_rtp_write(p->vrtp, frame);
3524 ast_mutex_unlock(&p->lock);
3526 break;
3527 case AST_FRAME_IMAGE:
3528 return 0;
3529 break;
3530 case AST_FRAME_MODEM:
3531 if (p) {
3532 ast_mutex_lock(&p->lock);
3533 /* UDPTL requires two-way communication, so early media is not needed here.
3534 we simply forget the frames if we get modem frames before the bridge is up.
3535 Fax will re-transmit.
3537 if (p->udptl && ast->_state == AST_STATE_UP)
3538 res = ast_udptl_write(p->udptl, frame);
3539 ast_mutex_unlock(&p->lock);
3541 break;
3542 default:
3543 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
3544 return 0;
3547 return res;
3550 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
3551 Basically update any ->owner links */
3552 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
3554 int ret = -1;
3555 struct sip_pvt *p;
3557 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE) && option_debug)
3558 ast_log(LOG_DEBUG, "New channel is zombie\n");
3559 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE) && option_debug)
3560 ast_log(LOG_DEBUG, "Old channel is zombie\n");
3562 if (!newchan || !newchan->tech_pvt) {
3563 if (!newchan)
3564 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
3565 else
3566 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
3567 return -1;
3569 p = newchan->tech_pvt;
3571 if (!p) {
3572 ast_log(LOG_WARNING, "No pvt after masquerade. Strange things may happen\n");
3573 return -1;
3576 ast_mutex_lock(&p->lock);
3577 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
3578 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
3579 if (p->owner != oldchan)
3580 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
3581 else {
3582 p->owner = newchan;
3583 ret = 0;
3585 if (option_debug > 2)
3586 ast_log(LOG_DEBUG, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
3588 ast_mutex_unlock(&p->lock);
3589 return ret;
3592 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
3594 struct sip_pvt *p = ast->tech_pvt;
3595 int res = 0;
3597 ast_mutex_lock(&p->lock);
3598 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
3599 case SIP_DTMF_INBAND:
3600 res = -1; /* Tell Asterisk to generate inband indications */
3601 break;
3602 case SIP_DTMF_RFC2833:
3603 if (p->rtp)
3604 ast_rtp_senddigit_begin(p->rtp, digit);
3605 break;
3606 default:
3607 break;
3609 ast_mutex_unlock(&p->lock);
3611 return res;
3614 /*! \brief Send DTMF character on SIP channel
3615 within one call, we're able to transmit in many methods simultaneously */
3616 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
3618 struct sip_pvt *p = ast->tech_pvt;
3619 int res = 0;
3621 ast_mutex_lock(&p->lock);
3622 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
3623 case SIP_DTMF_INFO:
3624 transmit_info_with_digit(p, digit, duration);
3625 break;
3626 case SIP_DTMF_RFC2833:
3627 if (p->rtp)
3628 ast_rtp_senddigit_end(p->rtp, digit);
3629 break;
3630 case SIP_DTMF_INBAND:
3631 res = -1; /* Tell Asterisk to stop inband indications */
3632 break;
3634 ast_mutex_unlock(&p->lock);
3636 return res;
3639 /*! \brief Transfer SIP call */
3640 static int sip_transfer(struct ast_channel *ast, const char *dest)
3642 struct sip_pvt *p = ast->tech_pvt;
3643 int res;
3645 if (dest == NULL) /* functions below do not take a NULL */
3646 dest = "";
3647 ast_mutex_lock(&p->lock);
3648 if (ast->_state == AST_STATE_RING)
3649 res = sip_sipredirect(p, dest);
3650 else
3651 res = transmit_refer(p, dest);
3652 ast_mutex_unlock(&p->lock);
3653 return res;
3656 /*! \brief Play indication to user
3657 * With SIP a lot of indications is sent as messages, letting the device play
3658 the indication - busy signal, congestion etc
3659 \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
3661 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
3663 struct sip_pvt *p = ast->tech_pvt;
3664 int res = 0;
3666 ast_mutex_lock(&p->lock);
3667 switch(condition) {
3668 case AST_CONTROL_RINGING:
3669 if (ast->_state == AST_STATE_RING) {
3670 p->invitestate = INV_EARLY_MEDIA;
3671 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
3672 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
3673 /* Send 180 ringing if out-of-band seems reasonable */
3674 transmit_response(p, "180 Ringing", &p->initreq);
3675 ast_set_flag(&p->flags[0], SIP_RINGING);
3676 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
3677 break;
3678 } else {
3679 /* Well, if it's not reasonable, just send in-band */
3682 res = -1;
3683 break;
3684 case AST_CONTROL_BUSY:
3685 if (ast->_state != AST_STATE_UP) {
3686 transmit_response(p, "486 Busy Here", &p->initreq);
3687 p->invitestate = INV_COMPLETED;
3688 sip_alreadygone(p);
3689 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
3690 break;
3692 res = -1;
3693 break;
3694 case AST_CONTROL_CONGESTION:
3695 if (ast->_state != AST_STATE_UP) {
3696 transmit_response(p, "503 Service Unavailable", &p->initreq);
3697 p->invitestate = INV_COMPLETED;
3698 sip_alreadygone(p);
3699 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
3700 break;
3702 res = -1;
3703 break;
3704 case AST_CONTROL_PROCEEDING:
3705 if ((ast->_state != AST_STATE_UP) &&
3706 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3707 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3708 transmit_response(p, "100 Trying", &p->initreq);
3709 p->invitestate = INV_PROCEEDING;
3710 break;
3712 res = -1;
3713 break;
3714 case AST_CONTROL_PROGRESS:
3715 if ((ast->_state != AST_STATE_UP) &&
3716 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3717 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3718 p->invitestate = INV_EARLY_MEDIA;
3719 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3720 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3721 break;
3723 res = -1;
3724 break;
3725 case AST_CONTROL_HOLD:
3726 ast_moh_start(ast, data, p->mohinterpret);
3727 break;
3728 case AST_CONTROL_UNHOLD:
3729 ast_moh_stop(ast);
3730 break;
3731 case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
3732 if (p->vrtp && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
3733 transmit_info_with_vidupdate(p);
3734 /* ast_rtcp_send_h261fur(p->vrtp); */
3735 } else
3736 res = -1;
3737 break;
3738 case -1:
3739 res = -1;
3740 break;
3741 default:
3742 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
3743 res = -1;
3744 break;
3746 ast_mutex_unlock(&p->lock);
3747 return res;
3752 /*! \brief Initiate a call in the SIP channel
3753 called from sip_request_call (calls from the pbx ) for outbound channels
3754 and from handle_request_invite for inbound channels
3757 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
3759 struct ast_channel *tmp;
3760 struct ast_variable *v = NULL;
3761 int fmt;
3762 int what;
3763 int needvideo = 0;
3765 const char *my_name; /* pick a good name */
3767 if (title)
3768 my_name = title;
3769 else if ( (my_name = strchr(i->fromdomain,':')) )
3770 my_name++; /* skip ':' */
3771 else
3772 my_name = i->fromdomain;
3774 ast_mutex_unlock(&i->lock);
3775 /* Don't hold a sip pvt lock while we allocate a channel */
3776 tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, "SIP/%s-%08x", my_name, (int)(long) i);
3779 if (!tmp) {
3780 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
3781 return NULL;
3783 ast_mutex_lock(&i->lock);
3785 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO)
3786 tmp->tech = &sip_tech_info;
3787 else
3788 tmp->tech = &sip_tech;
3790 /* Select our native format based on codec preference until we receive
3791 something from another device to the contrary. */
3792 if (i->jointcapability) /* The joint capabilities of us and peer */
3793 what = i->jointcapability;
3794 else if (i->capability) /* Our configured capability for this peer */
3795 what = i->capability;
3796 else
3797 what = global_capability; /* Global codec support */
3799 /* Set the native formats for audio and merge in video */
3800 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
3801 if (option_debug > 2) {
3802 char buf[BUFSIZ];
3803 ast_log(LOG_DEBUG, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, BUFSIZ, tmp->nativeformats));
3804 ast_log(LOG_DEBUG, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, BUFSIZ, i->jointcapability));
3805 ast_log(LOG_DEBUG, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, BUFSIZ, i->capability));
3806 ast_log(LOG_DEBUG, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, BUFSIZ, ast_codec_choose(&i->prefs, what, 1)));
3807 if (i->prefcodec)
3808 ast_log(LOG_DEBUG, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, BUFSIZ, i->prefcodec));
3811 /* XXX Why are we choosing a codec from the native formats?? */
3812 fmt = ast_best_codec(tmp->nativeformats);
3814 /* If we have a prefcodec setting, we have an inbound channel that set a
3815 preferred format for this call. Otherwise, we check the jointcapability
3816 We also check for vrtp. If it's not there, we are not allowed do any video anyway.
3818 if (i->vrtp) {
3819 if (i->prefcodec)
3820 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK; /* Outbound call */
3821 else
3822 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK; /* Inbound call */
3825 if (option_debug > 2) {
3826 if (needvideo)
3827 ast_log(LOG_DEBUG, "This channel can handle video! HOLLYWOOD next!\n");
3828 else
3829 ast_log(LOG_DEBUG, "This channel will not be able to handle video.\n");
3834 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
3835 i->vad = ast_dsp_new();
3836 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
3837 if (global_relaxdtmf)
3838 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
3840 if (i->rtp) {
3841 tmp->fds[0] = ast_rtp_fd(i->rtp);
3842 tmp->fds[1] = ast_rtcp_fd(i->rtp);
3844 if (needvideo && i->vrtp) {
3845 tmp->fds[2] = ast_rtp_fd(i->vrtp);
3846 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
3848 if (i->udptl) {
3849 tmp->fds[5] = ast_udptl_fd(i->udptl);
3851 if (state == AST_STATE_RING)
3852 tmp->rings = 1;
3853 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
3854 tmp->writeformat = fmt;
3855 tmp->rawwriteformat = fmt;
3856 tmp->readformat = fmt;
3857 tmp->rawreadformat = fmt;
3858 tmp->tech_pvt = i;
3860 tmp->callgroup = i->callgroup;
3861 tmp->pickupgroup = i->pickupgroup;
3862 tmp->cid.cid_pres = i->callingpres;
3863 if (!ast_strlen_zero(i->accountcode))
3864 ast_string_field_set(tmp, accountcode, i->accountcode);
3865 if (i->amaflags)
3866 tmp->amaflags = i->amaflags;
3867 if (!ast_strlen_zero(i->language))
3868 ast_string_field_set(tmp, language, i->language);
3869 i->owner = tmp;
3870 ast_module_ref(ast_module_info->self);
3871 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
3872 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
3874 /* Don't use ast_set_callerid() here because it will
3875 * generate an unnecessary NewCallerID event */
3876 tmp->cid.cid_num = ast_strdup(i->cid_num);
3877 tmp->cid.cid_ani = ast_strdup(i->cid_num);
3878 tmp->cid.cid_name = ast_strdup(i->cid_name);
3879 if (!ast_strlen_zero(i->rdnis))
3880 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
3882 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
3883 tmp->cid.cid_dnid = ast_strdup(i->exten);
3885 tmp->priority = 1;
3886 if (!ast_strlen_zero(i->uri))
3887 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
3888 if (!ast_strlen_zero(i->domain))
3889 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
3890 if (!ast_strlen_zero(i->useragent))
3891 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
3892 if (!ast_strlen_zero(i->callid))
3893 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
3894 if (i->rtp)
3895 ast_jb_configure(tmp, &global_jbconf);
3896 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
3897 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
3898 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
3899 ast_hangup(tmp);
3900 tmp = NULL;
3902 /* Set channel variables for this call from configuration */
3903 for (v = i->chanvars ; v ; v = v->next)
3904 pbx_builtin_setvar_helper(tmp,v->name,v->value);
3906 if (!ast_test_flag(&i->flags[0], SIP_NO_HISTORY))
3907 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
3909 return tmp;
3912 /*! \brief Reads one line of SIP message body */
3913 static char *get_body_by_line(const char *line, const char *name, int nameLen)
3915 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=')
3916 return ast_skip_blanks(line + nameLen + 1);
3918 return "";
3921 /*! \brief Lookup 'name' in the SDP starting
3922 * at the 'start' line. Returns the matching line, and 'start'
3923 * is updated with the next line number.
3925 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
3927 int len = strlen(name);
3929 while (*start < req->sdp_end) {
3930 const char *r = get_body_by_line(req->line[(*start)++], name, len);
3931 if (r[0] != '\0')
3932 return r;
3935 return "";
3938 /*! \brief Get a line from an SDP message body */
3939 static const char *get_sdp(struct sip_request *req, const char *name)
3941 int dummy = 0;
3943 return get_sdp_iterate(&dummy, req, name);
3946 /*! \brief Get a specific line from the message body */
3947 static char *get_body(struct sip_request *req, char *name)
3949 int x;
3950 int len = strlen(name);
3951 char *r;
3953 for (x = 0; x < req->lines; x++) {
3954 r = get_body_by_line(req->line[x], name, len);
3955 if (r[0] != '\0')
3956 return r;
3959 return "";
3962 /*! \brief Find compressed SIP alias */
3963 static const char *find_alias(const char *name, const char *_default)
3965 /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
3966 static const struct cfalias {
3967 char * const fullname;
3968 char * const shortname;
3969 } aliases[] = {
3970 { "Content-Type", "c" },
3971 { "Content-Encoding", "e" },
3972 { "From", "f" },
3973 { "Call-ID", "i" },
3974 { "Contact", "m" },
3975 { "Content-Length", "l" },
3976 { "Subject", "s" },
3977 { "To", "t" },
3978 { "Supported", "k" },
3979 { "Refer-To", "r" },
3980 { "Referred-By", "b" },
3981 { "Allow-Events", "u" },
3982 { "Event", "o" },
3983 { "Via", "v" },
3984 { "Accept-Contact", "a" },
3985 { "Reject-Contact", "j" },
3986 { "Request-Disposition", "d" },
3987 { "Session-Expires", "x" },
3988 { "Identity", "y" },
3989 { "Identity-Info", "n" },
3991 int x;
3993 for (x=0; x<sizeof(aliases) / sizeof(aliases[0]); x++)
3994 if (!strcasecmp(aliases[x].fullname, name))
3995 return aliases[x].shortname;
3997 return _default;
4000 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
4002 int pass;
4005 * Technically you can place arbitrary whitespace both before and after the ':' in
4006 * a header, although RFC3261 clearly says you shouldn't before, and place just
4007 * one afterwards. If you shouldn't do it, what absolute idiot decided it was
4008 * a good idea to say you can do it, and if you can do it, why in the hell would.
4009 * you say you shouldn't.
4010 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
4011 * and we always allow spaces after that for compatibility.
4013 for (pass = 0; name && pass < 2;pass++) {
4014 int x, len = strlen(name);
4015 for (x=*start; x<req->headers; x++) {
4016 if (!strncasecmp(req->header[x], name, len)) {
4017 char *r = req->header[x] + len; /* skip name */
4018 if (pedanticsipchecking)
4019 r = ast_skip_blanks(r);
4021 if (*r == ':') {
4022 *start = x+1;
4023 return ast_skip_blanks(r+1);
4027 if (pass == 0) /* Try aliases */
4028 name = find_alias(name, NULL);
4031 /* Don't return NULL, so get_header is always a valid pointer */
4032 return "";
4035 /*! \brief Get header from SIP request */
4036 static const char *get_header(const struct sip_request *req, const char *name)
4038 int start = 0;
4039 return __get_header(req, name, &start);
4042 /*! \brief Read RTP from network */
4043 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
4045 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
4046 struct ast_frame *f;
4048 if (!p->rtp) {
4049 /* We have no RTP allocated for this channel */
4050 return &ast_null_frame;
4053 switch(ast->fdno) {
4054 case 0:
4055 f = ast_rtp_read(p->rtp); /* RTP Audio */
4056 break;
4057 case 1:
4058 f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
4059 break;
4060 case 2:
4061 f = ast_rtp_read(p->vrtp); /* RTP Video */
4062 break;
4063 case 3:
4064 f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
4065 break;
4066 case 5:
4067 f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
4068 break;
4069 default:
4070 f = &ast_null_frame;
4072 /* Don't forward RFC2833 if we're not supposed to */
4073 if (f && (f->frametype == AST_FRAME_DTMF) &&
4074 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833))
4075 return &ast_null_frame;
4077 /* We already hold the channel lock */
4078 if (!p->owner || f->frametype != AST_FRAME_VOICE)
4079 return f;
4081 if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
4082 if (!(f->subclass & p->jointcapability)) {
4083 if (option_debug) {
4084 ast_log(LOG_DEBUG, "Bogus frame of format '%s' received from '%s'!\n",
4085 ast_getformatname(f->subclass), p->owner->name);
4087 return &ast_null_frame;
4089 if (option_debug)
4090 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
4091 p->owner->nativeformats = (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
4092 ast_set_read_format(p->owner, p->owner->readformat);
4093 ast_set_write_format(p->owner, p->owner->writeformat);
4096 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
4097 f = ast_dsp_process(p->owner, p->vad, f);
4098 if (f && f->frametype == AST_FRAME_DTMF) {
4099 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && f->subclass == 'f') {
4100 if (option_debug)
4101 ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
4102 *faxdetect = 1;
4103 } else if (option_debug) {
4104 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
4109 return f;
4112 /*! \brief Read SIP RTP from channel */
4113 static struct ast_frame *sip_read(struct ast_channel *ast)
4115 struct ast_frame *fr;
4116 struct sip_pvt *p = ast->tech_pvt;
4117 int faxdetected = FALSE;
4119 ast_mutex_lock(&p->lock);
4120 fr = sip_rtp_read(ast, p, &faxdetected);
4121 p->lastrtprx = time(NULL);
4123 /* If we are NOT bridged to another channel, and we have detected fax tone we issue T38 re-invite to a peer */
4124 /* 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 */
4125 if (faxdetected && ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && (p->t38.state == T38_DISABLED) && !(ast_bridged_channel(ast))) {
4126 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
4127 if (!p->pendinginvite) {
4128 if (option_debug > 2)
4129 ast_log(LOG_DEBUG, "Sending reinvite on SIP (%s) for T.38 negotiation.\n",ast->name);
4130 p->t38.state = T38_LOCAL_REINVITE;
4131 transmit_reinvite_with_t38_sdp(p);
4132 if (option_debug > 1)
4133 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, ast->name);
4135 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
4136 if (option_debug > 2)
4137 ast_log(LOG_DEBUG, "Deferring reinvite on SIP (%s) - it will be re-negotiated for T.38\n", ast->name);
4138 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
4142 ast_mutex_unlock(&p->lock);
4143 return fr;
4147 /*! \brief Generate 32 byte random string for callid's etc */
4148 static char *generate_random_string(char *buf, size_t size)
4150 long val[4];
4151 int x;
4153 for (x=0; x<4; x++)
4154 val[x] = ast_random();
4155 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
4157 return buf;
4160 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
4161 static void build_callid_pvt(struct sip_pvt *pvt)
4163 char buf[33];
4165 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip));
4167 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
4171 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
4172 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
4174 char buf[33];
4176 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
4178 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
4181 /*! \brief Make our SIP dialog tag */
4182 static void make_our_tag(char *tagbuf, size_t len)
4184 snprintf(tagbuf, len, "as%08lx", ast_random());
4187 /*! \brief Allocate SIP_PVT structure and set defaults */
4188 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
4189 int useglobal_nat, const int intended_method)
4191 struct sip_pvt *p;
4193 if (!(p = ast_calloc(1, sizeof(*p))))
4194 return NULL;
4196 if (ast_string_field_init(p, 512)) {
4197 free(p);
4198 return NULL;
4201 ast_mutex_init(&p->lock);
4203 p->method = intended_method;
4204 p->initid = -1;
4205 p->autokillid = -1;
4206 p->subscribed = NONE;
4207 p->stateid = -1;
4208 p->prefs = default_prefs; /* Set default codecs for this call */
4210 if (intended_method != SIP_OPTIONS) /* Peerpoke has it's own system */
4211 p->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
4213 if (sin) {
4214 p->sa = *sin;
4215 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
4216 p->ourip = __ourip;
4217 } else
4218 p->ourip = __ourip;
4220 /* Copy global flags to this PVT at setup. */
4221 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
4222 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
4224 ast_set2_flag(&p->flags[0], !recordhistory, SIP_NO_HISTORY);
4226 p->branch = ast_random();
4227 make_our_tag(p->tag, sizeof(p->tag));
4228 p->ocseq = INITIAL_CSEQ;
4230 if (sip_methods[intended_method].need_rtp) {
4231 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
4232 /* If the global videosupport flag is on, we always create a RTP interface for video */
4233 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
4234 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
4235 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
4236 p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
4237 if (!p->rtp || (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)) {
4238 ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n",
4239 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video" : "", strerror(errno));
4240 ast_mutex_destroy(&p->lock);
4241 if (p->chanvars) {
4242 ast_variables_destroy(p->chanvars);
4243 p->chanvars = NULL;
4245 free(p);
4246 return NULL;
4248 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
4249 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
4250 ast_rtp_settos(p->rtp, global_tos_audio);
4251 ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
4252 ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
4253 ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
4254 if (p->vrtp) {
4255 ast_rtp_settos(p->vrtp, global_tos_video);
4256 ast_rtp_setdtmf(p->vrtp, 0);
4257 ast_rtp_setdtmfcompensate(p->vrtp, 0);
4258 ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
4259 ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
4260 ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
4262 if (p->udptl)
4263 ast_udptl_settos(p->udptl, global_tos_audio);
4264 p->maxcallbitrate = default_maxcallbitrate;
4267 if (useglobal_nat && sin) {
4268 /* Setup NAT structure according to global settings if we have an address */
4269 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
4270 p->recv = *sin;
4271 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
4274 if (p->method != SIP_REGISTER)
4275 ast_string_field_set(p, fromdomain, default_fromdomain);
4276 build_via(p);
4277 if (!callid)
4278 build_callid_pvt(p);
4279 else
4280 ast_string_field_set(p, callid, callid);
4281 /* Assign default music on hold class */
4282 ast_string_field_set(p, mohinterpret, default_mohinterpret);
4283 ast_string_field_set(p, mohsuggest, default_mohsuggest);
4284 p->capability = global_capability;
4285 p->allowtransfer = global_allowtransfer;
4286 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
4287 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
4288 p->noncodeccapability |= AST_RTP_DTMF;
4289 if (p->udptl) {
4290 p->t38.capability = global_t38_capability;
4291 if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY)
4292 p->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
4293 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_FEC)
4294 p->t38.capability |= T38FAX_UDP_EC_FEC;
4295 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_NONE)
4296 p->t38.capability |= T38FAX_UDP_EC_NONE;
4297 p->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
4298 p->t38.jointcapability = p->t38.capability;
4300 ast_string_field_set(p, context, default_context);
4302 /* Add to active dialog list */
4303 ast_mutex_lock(&iflock);
4304 p->next = iflist;
4305 iflist = p;
4306 ast_mutex_unlock(&iflock);
4307 if (option_debug)
4308 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");
4309 return p;
4312 /*! \brief Connect incoming SIP message to current dialog or create new dialog structure
4313 Called by handle_request, sipsock_read */
4314 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
4316 struct sip_pvt *p = NULL;
4317 char *tag = ""; /* note, tag is never NULL */
4318 char totag[128];
4319 char fromtag[128];
4320 const char *callid = get_header(req, "Call-ID");
4321 const char *from = get_header(req, "From");
4322 const char *to = get_header(req, "To");
4323 const char *cseq = get_header(req, "Cseq");
4325 /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
4326 /* get_header always returns non-NULL so we must use ast_strlen_zero() */
4327 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
4328 ast_strlen_zero(from) || ast_strlen_zero(cseq))
4329 return NULL; /* Invalid packet */
4331 if (pedanticsipchecking) {
4332 /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
4333 we need more to identify a branch - so we have to check branch, from
4334 and to tags to identify a call leg.
4335 For Asterisk to behave correctly, you need to turn on pedanticsipchecking
4336 in sip.conf
4338 if (gettag(req, "To", totag, sizeof(totag)))
4339 ast_set_flag(req, SIP_PKT_WITH_TOTAG); /* Used in handle_request/response */
4340 gettag(req, "From", fromtag, sizeof(fromtag));
4342 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
4344 if (option_debug > 4 )
4345 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);
4348 ast_mutex_lock(&iflock);
4349 for (p = iflist; p; p = p->next) {
4350 /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
4351 int found = FALSE;
4352 if (req->method == SIP_REGISTER)
4353 found = (!strcmp(p->callid, callid));
4354 else
4355 found = (!strcmp(p->callid, callid) &&
4356 (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ;
4358 if (option_debug > 4)
4359 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);
4361 /* If we get a new request within an existing to-tag - check the to tag as well */
4362 if (pedanticsipchecking && found && req->method != SIP_RESPONSE) { /* SIP Request */
4363 if (p->tag[0] == '\0' && totag[0]) {
4364 /* We have no to tag, but they have. Wrong dialog */
4365 found = FALSE;
4366 } else if (totag[0]) { /* Both have tags, compare them */
4367 if (strcmp(totag, p->tag)) {
4368 found = FALSE; /* This is not our packet */
4371 if (!found && option_debug > 4)
4372 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);
4376 if (found) {
4377 /* Found the call */
4378 ast_mutex_lock(&p->lock);
4379 ast_mutex_unlock(&iflock);
4380 return p;
4383 ast_mutex_unlock(&iflock);
4385 /* See if the method is capable of creating a dialog */
4386 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
4387 if (intended_method == SIP_REFER) {
4388 /* We do support REFER, but not outside of a dialog yet */
4389 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
4390 } else if (intended_method == SIP_NOTIFY) {
4391 /* We do not support out-of-dialog NOTIFY either,
4392 like voicemail notification, so cancel that early */
4393 transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
4394 } else {
4395 /* Ok, time to create a new SIP dialog object, a pvt */
4396 if ((p = sip_alloc(callid, sin, 1, intended_method))) {
4397 /* Ok, we've created a dialog, let's go and process it */
4398 ast_mutex_lock(&p->lock);
4399 } else {
4400 /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
4401 getting a dialog from sip_alloc.
4403 Without a dialog we can't retransmit and handle ACKs and all that, but at least
4404 send an error message.
4406 Sorry, we apologize for the inconvienience
4408 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
4409 if (option_debug > 3)
4410 ast_log(LOG_DEBUG, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
4413 return p;
4414 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
4415 /* A method we do not support, let's take it on the volley */
4416 transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
4417 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
4418 /* This is a request outside of a dialog that we don't know about
4419 ...never reply to an ACK!
4421 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
4423 /* We do not respond to responses for dialogs that we don't know about, we just drop
4424 the session quickly */
4426 return p;
4429 /*! \brief Parse register=> line in sip.conf and add to registry */
4430 static int sip_register(char *value, int lineno)
4432 struct sip_registry *reg;
4433 int portnum = 0;
4434 char username[256] = "";
4435 char *hostname=NULL, *secret=NULL, *authuser=NULL;
4436 char *porta=NULL;
4437 char *contact=NULL;
4439 if (!value)
4440 return -1;
4441 ast_copy_string(username, value, sizeof(username));
4442 /* First split around the last '@' then parse the two components. */
4443 hostname = strrchr(username, '@'); /* allow @ in the first part */
4444 if (hostname)
4445 *hostname++ = '\0';
4446 if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
4447 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
4448 return -1;
4450 /* split user[:secret[:authuser]] */
4451 secret = strchr(username, ':');
4452 if (secret) {
4453 *secret++ = '\0';
4454 authuser = strchr(secret, ':');
4455 if (authuser)
4456 *authuser++ = '\0';
4458 /* split host[:port][/contact] */
4459 contact = strchr(hostname, '/');
4460 if (contact)
4461 *contact++ = '\0';
4462 if (ast_strlen_zero(contact))
4463 contact = "s";
4464 porta = strchr(hostname, ':');
4465 if (porta) {
4466 *porta++ = '\0';
4467 portnum = atoi(porta);
4468 if (portnum == 0) {
4469 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
4470 return -1;
4473 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
4474 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
4475 return -1;
4478 if (ast_string_field_init(reg, 256)) {
4479 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
4480 free(reg);
4481 return -1;
4484 regobjs++;
4485 ASTOBJ_INIT(reg);
4486 ast_string_field_set(reg, contact, contact);
4487 if (username)
4488 ast_string_field_set(reg, username, username);
4489 if (hostname)
4490 ast_string_field_set(reg, hostname, hostname);
4491 if (authuser)
4492 ast_string_field_set(reg, authuser, authuser);
4493 if (secret)
4494 ast_string_field_set(reg, secret, secret);
4495 reg->expire = -1;
4496 reg->timeout = -1;
4497 reg->refresh = default_expiry;
4498 reg->portno = portnum;
4499 reg->callid_valid = FALSE;
4500 reg->ocseq = INITIAL_CSEQ;
4501 ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
4502 ASTOBJ_UNREF(reg,sip_registry_destroy);
4503 return 0;
4506 /*! \brief Parse multiline SIP headers into one header
4507 This is enabled if pedanticsipchecking is enabled */
4508 static int lws2sws(char *msgbuf, int len)
4510 int h = 0, t = 0;
4511 int lws = 0;
4513 for (; h < len;) {
4514 /* Eliminate all CRs */
4515 if (msgbuf[h] == '\r') {
4516 h++;
4517 continue;
4519 /* Check for end-of-line */
4520 if (msgbuf[h] == '\n') {
4521 /* Check for end-of-message */
4522 if (h + 1 == len)
4523 break;
4524 /* Check for a continuation line */
4525 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
4526 /* Merge continuation line */
4527 h++;
4528 continue;
4530 /* Propagate LF and start new line */
4531 msgbuf[t++] = msgbuf[h++];
4532 lws = 0;
4533 continue;
4535 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
4536 if (lws) {
4537 h++;
4538 continue;
4540 msgbuf[t++] = msgbuf[h++];
4541 lws = 1;
4542 continue;
4544 msgbuf[t++] = msgbuf[h++];
4545 if (lws)
4546 lws = 0;
4548 msgbuf[t] = '\0';
4549 return t;
4552 /*! \brief Parse a SIP message
4553 \note this function is used both on incoming and outgoing packets
4555 static void parse_request(struct sip_request *req)
4557 /* Divide fields by NULL's */
4558 char *c;
4559 int f = 0;
4561 c = req->data;
4563 /* First header starts immediately */
4564 req->header[f] = c;
4565 while(*c) {
4566 if (*c == '\n') {
4567 /* We've got a new header */
4568 *c = 0;
4570 if (sipdebug && option_debug > 3)
4571 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
4572 if (ast_strlen_zero(req->header[f])) {
4573 /* Line by itself means we're now in content */
4574 c++;
4575 break;
4577 if (f >= SIP_MAX_HEADERS - 1) {
4578 ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n");
4579 } else
4580 f++;
4581 req->header[f] = c + 1;
4582 } else if (*c == '\r') {
4583 /* Ignore but eliminate \r's */
4584 *c = 0;
4586 c++;
4588 /* Check for last header */
4589 if (!ast_strlen_zero(req->header[f])) {
4590 if (sipdebug && option_debug > 3)
4591 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
4592 f++;
4594 req->headers = f;
4595 /* Now we process any mime content */
4596 f = 0;
4597 req->line[f] = c;
4598 while(*c) {
4599 if (*c == '\n') {
4600 /* We've got a new line */
4601 *c = 0;
4602 if (sipdebug && option_debug > 3)
4603 ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
4604 if (f >= SIP_MAX_LINES - 1) {
4605 ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n");
4606 } else
4607 f++;
4608 req->line[f] = c + 1;
4609 } else if (*c == '\r') {
4610 /* Ignore and eliminate \r's */
4611 *c = 0;
4613 c++;
4615 /* Check for last line */
4616 if (!ast_strlen_zero(req->line[f]))
4617 f++;
4618 req->lines = f;
4619 if (*c)
4620 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
4621 /* Split up the first line parts */
4622 determine_firstline_parts(req);
4626 \brief Determine whether a SIP message contains an SDP in its body
4627 \param req the SIP request to process
4628 \return 1 if SDP found, 0 if not found
4630 Also updates req->sdp_start and req->sdp_end to indicate where the SDP
4631 lives in the message body.
4633 static int find_sdp(struct sip_request *req)
4635 const char *content_type;
4636 const char *search;
4637 char *boundary;
4638 unsigned int x;
4639 int boundaryisquoted = FALSE;
4641 content_type = get_header(req, "Content-Type");
4643 /* if the body contains only SDP, this is easy */
4644 if (!strcasecmp(content_type, "application/sdp")) {
4645 req->sdp_start = 0;
4646 req->sdp_end = req->lines;
4647 return 1;
4650 /* if it's not multipart/mixed, there cannot be an SDP */
4651 if (strncasecmp(content_type, "multipart/mixed", 15))
4652 return 0;
4654 /* if there is no boundary marker, it's invalid */
4655 if (!(search = strcasestr(content_type, ";boundary=")))
4656 return 0;
4658 search += 10;
4659 if (ast_strlen_zero(search))
4660 return 0;
4662 /* If the boundary is quoted with ", remove quote */
4663 if (*search == '\"') {
4664 search++;
4665 boundaryisquoted = TRUE;
4668 /* make a duplicate of the string, with two extra characters
4669 at the beginning */
4670 boundary = ast_strdupa(search - 2);
4671 boundary[0] = boundary[1] = '-';
4673 /* Remove final quote */
4674 if (boundaryisquoted)
4675 boundary[strlen(boundary) - 1] = '\0';
4677 /* search for the boundary marker, but stop when there are not enough
4678 lines left for it, the Content-Type header and at least one line of
4679 body */
4680 for (x = 0; x < (req->lines - 2); x++) {
4681 if (!strncasecmp(req->line[x], boundary, strlen(boundary)) &&
4682 !strcasecmp(req->line[x + 1], "Content-Type: application/sdp")) {
4683 x += 2;
4684 req->sdp_start = x;
4686 /* search for the end of the body part */
4687 for ( ; x < req->lines; x++) {
4688 if (!strncasecmp(req->line[x], boundary, strlen(boundary)))
4689 break;
4691 req->sdp_end = x;
4692 return 1;
4696 return 0;
4699 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
4700 If offer is rejected, we will not change any properties of the call
4701 Return 0 on success, a negative value on errors.
4702 Must be called after find_sdp().
4704 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
4706 const char *m; /* SDP media offer */
4707 const char *c;
4708 const char *a;
4709 char host[258];
4710 int len = -1;
4711 int portno = -1; /*!< RTP Audio port number */
4712 int vportno = -1; /*!< RTP Video port number */
4713 int udptlportno = -1;
4714 int peert38capability = 0;
4715 char s[256];
4716 int old = 0;
4718 /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
4719 int peercapability = 0, peernoncodeccapability = 0;
4720 int vpeercapability = 0, vpeernoncodeccapability = 0;
4721 struct sockaddr_in sin; /*!< media socket address */
4722 struct sockaddr_in vsin; /*!< Video socket address */
4724 const char *codecs;
4725 struct hostent *hp; /*!< RTP Audio host IP */
4726 struct hostent *vhp = NULL; /*!< RTP video host IP */
4727 struct ast_hostent audiohp;
4728 struct ast_hostent videohp;
4729 int codec;
4730 int destiterator = 0;
4731 int iterator;
4732 int sendonly = 0;
4733 int numberofports;
4734 struct ast_rtp *newaudiortp, *newvideortp; /* Buffers for codec handling */
4735 int newjointcapability; /* Negotiated capability */
4736 int newpeercapability;
4737 int newnoncodeccapability;
4738 int numberofmediastreams = 0;
4739 int debug = sip_debug_test_pvt(p);
4741 int found_rtpmap_codecs[32];
4742 int last_rtpmap_codec=0;
4744 if (!p->rtp) {
4745 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
4746 return -1;
4749 /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
4750 newaudiortp = alloca(ast_rtp_alloc_size());
4751 memset(newaudiortp, 0, ast_rtp_alloc_size());
4752 ast_rtp_new_init(newaudiortp);
4753 ast_rtp_pt_clear(newaudiortp);
4755 newvideortp = alloca(ast_rtp_alloc_size());
4756 memset(newvideortp, 0, ast_rtp_alloc_size());
4757 ast_rtp_new_init(newvideortp);
4758 ast_rtp_pt_clear(newvideortp);
4760 /* Update our last rtprx when we receive an SDP, too */
4761 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
4764 /* Try to find first media stream */
4765 m = get_sdp(req, "m");
4766 destiterator = req->sdp_start;
4767 c = get_sdp_iterate(&destiterator, req, "c");
4768 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
4769 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
4770 return -1;
4773 /* Check for IPv4 address (not IPv6 yet) */
4774 if (sscanf(c, "IN IP4 %256s", host) != 1) {
4775 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
4776 return -1;
4779 /* XXX This could block for a long time, and block the main thread! XXX */
4780 hp = ast_gethostbyname(host, &audiohp);
4781 if (!hp) {
4782 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
4783 return -1;
4785 vhp = hp; /* Copy to video address as default too */
4787 iterator = req->sdp_start;
4788 ast_set_flag(&p->flags[0], SIP_NOVIDEO);
4791 /* Find media streams in this SDP offer */
4792 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
4793 int x;
4794 int audio = FALSE;
4796 numberofports = 1;
4797 if ((sscanf(m, "audio %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
4798 (sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
4799 audio = TRUE;
4800 numberofmediastreams++;
4801 /* Found audio stream in this media definition */
4802 portno = x;
4803 /* Scan through the RTP payload types specified in a "m=" line: */
4804 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
4805 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
4806 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
4807 return -1;
4809 if (debug)
4810 ast_verbose("Found RTP audio format %d\n", codec);
4811 ast_rtp_set_m_type(newaudiortp, codec);
4813 } else if ((sscanf(m, "video %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
4814 (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
4815 /* If it is not audio - is it video ? */
4816 ast_clear_flag(&p->flags[0], SIP_NOVIDEO);
4817 numberofmediastreams++;
4818 vportno = x;
4819 /* Scan through the RTP payload types specified in a "m=" line: */
4820 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
4821 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
4822 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
4823 return -1;
4825 if (debug)
4826 ast_verbose("Found RTP video format %d\n", codec);
4827 ast_rtp_set_m_type(newvideortp, codec);
4829 } else if (p->udptl && ( (sscanf(m, "image %d udptl t38%n", &x, &len) == 1) ||
4830 (sscanf(m, "image %d UDPTL t38%n", &x, &len) == 1) )) {
4831 if (debug)
4832 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
4833 udptlportno = x;
4834 numberofmediastreams++;
4836 if (p->owner && p->lastinvite) {
4837 p->t38.state = T38_PEER_REINVITE; /* T38 Offered in re-invite from remote party */
4838 if (option_debug > 1)
4839 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>" );
4840 } else {
4841 p->t38.state = T38_PEER_DIRECT; /* T38 Offered directly from peer in first invite */
4842 if (option_debug > 1)
4843 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
4845 } else
4846 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
4847 if (numberofports > 1)
4848 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
4851 /* Check for Media-description-level-address for audio */
4852 c = get_sdp_iterate(&destiterator, req, "c");
4853 if (!ast_strlen_zero(c)) {
4854 if (sscanf(c, "IN IP4 %256s", host) != 1) {
4855 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
4856 } else {
4857 /* XXX This could block for a long time, and block the main thread! XXX */
4858 if (audio) {
4859 if ( !(hp = ast_gethostbyname(host, &audiohp)))
4860 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in secondary c= line, '%s'\n", c);
4861 } else if (!(vhp = ast_gethostbyname(host, &videohp)))
4862 ast_log(LOG_WARNING, "Unable to lookup RTP video host in secondary c= line, '%s'\n", c);
4867 if (portno == -1 && vportno == -1 && udptlportno == -1)
4868 /* No acceptable offer found in SDP - we have no ports */
4869 /* Do not change RTP or VRTP if this is a re-invite */
4870 return -2;
4872 if (numberofmediastreams > 2)
4873 /* We have too many fax, audio and/or video media streams, fail this offer */
4874 return -3;
4876 /* RTP addresses and ports for audio and video */
4877 sin.sin_family = AF_INET;
4878 vsin.sin_family = AF_INET;
4879 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
4880 if (vhp)
4881 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
4883 /* Setup UDPTL port number */
4884 if (p->udptl) {
4885 if (udptlportno > 0) {
4886 sin.sin_port = htons(udptlportno);
4887 ast_udptl_set_peer(p->udptl, &sin);
4888 if (debug)
4889 ast_log(LOG_DEBUG,"Peer T.38 UDPTL is at port %s:%d\n",ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
4890 } else {
4891 ast_udptl_stop(p->udptl);
4892 if (debug)
4893 ast_log(LOG_DEBUG, "Peer doesn't provide T.38 UDPTL\n");
4898 if (p->rtp) {
4899 if (portno > 0) {
4900 sin.sin_port = htons(portno);
4901 ast_rtp_set_peer(p->rtp, &sin);
4902 if (debug)
4903 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
4904 } else {
4905 if (udptlportno > 0) {
4906 if (debug)
4907 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session. Callid %s\n", p->callid);
4908 } else {
4909 ast_rtp_stop(p->rtp);
4910 if (debug)
4911 ast_verbose("Peer doesn't provide audio. Callid %s\n", p->callid);
4915 /* Setup video port number */
4916 if (vportno != -1)
4917 vsin.sin_port = htons(vportno);
4919 /* Next, scan through each "a=rtpmap:" line, noting each
4920 * specified RTP payload type (with corresponding MIME subtype):
4922 /* XXX This needs to be done per media stream, since it's media stream specific */
4923 iterator = req->sdp_start;
4924 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
4925 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
4926 if (option_debug > 1) {
4927 int breakout = FALSE;
4929 /* If we're debugging, check for unsupported sdp options */
4930 if (!strncasecmp(a, "rtcp:", (size_t) 5)) {
4931 if (debug)
4932 ast_verbose("Got unsupported a:rtcp in SDP offer \n");
4933 breakout = TRUE;
4934 } else if (!strncasecmp(a, "fmtp:", (size_t) 5)) {
4935 /* Format parameters: Not supported */
4936 /* Note: This is used for codec parameters, like bitrate for
4937 G722 and video formats for H263 and H264
4938 See RFC2327 for an example */
4939 if (debug)
4940 ast_verbose("Got unsupported a:fmtp in SDP offer \n");
4941 breakout = TRUE;
4942 } else if (!strncasecmp(a, "framerate:", (size_t) 10)) {
4943 /* Video stuff: Not supported */
4944 if (debug)
4945 ast_verbose("Got unsupported a:framerate in SDP offer \n");
4946 breakout = TRUE;
4947 } else if (!strncasecmp(a, "maxprate:", (size_t) 9)) {
4948 /* Video stuff: Not supported */
4949 if (debug)
4950 ast_verbose("Got unsupported a:maxprate in SDP offer \n");
4951 breakout = TRUE;
4952 } else if (!strncasecmp(a, "crypto:", (size_t) 7)) {
4953 /* SRTP stuff, not yet supported */
4954 if (debug)
4955 ast_verbose("Got unsupported a:crypto in SDP offer \n");
4956 breakout = TRUE;
4958 if (breakout) /* We have a match, skip to next header */
4959 continue;
4961 if (!strcasecmp(a, "sendonly")) {
4962 sendonly = 1;
4963 continue;
4964 } else if (!strcasecmp(a, "inactive")) {
4965 sendonly = 2;
4966 continue;
4967 } else if (!strcasecmp(a, "sendrecv")) {
4968 sendonly = 0;
4969 continue;
4970 } else if (strlen(a) > 5 && !strncasecmp(a, "ptime", 5)) {
4971 char *tmp = strrchr(a, ':');
4972 long int framing = 0;
4973 if (tmp) {
4974 tmp++;
4975 framing = strtol(tmp, NULL, 10);
4976 if (framing == LONG_MIN || framing == LONG_MAX) {
4977 framing = 0;
4978 if (option_debug)
4979 ast_log(LOG_DEBUG, "Can't read framing from SDP: %s\n", a);
4982 if (framing && last_rtpmap_codec) {
4983 if (p->autoframing) {
4984 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
4985 int codec_n;
4986 int format = 0;
4987 for (codec_n = 0; codec_n < last_rtpmap_codec; codec_n++) {
4988 format = ast_rtp_codec_getformat(found_rtpmap_codecs[codec_n]);
4989 if (!format) /* non-codec or not found */
4990 continue;
4991 if (option_debug)
4992 ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
4993 ast_codec_pref_setsize(pref, format, framing);
4995 ast_rtp_codec_setpref(p->rtp, pref);
4998 memset(&found_rtpmap_codecs, 0, sizeof(found_rtpmap_codecs));
4999 last_rtpmap_codec = 0;
5000 continue;
5001 } else if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) == 2) {
5002 /* We have a rtpmap to handle */
5003 if (debug)
5004 ast_verbose("Found description format %s for ID %d\n", mimeSubtype, codec);
5005 found_rtpmap_codecs[last_rtpmap_codec] = codec;
5006 last_rtpmap_codec++;
5008 /* Note: should really look at the 'freq' and '#chans' params too */
5009 ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
5010 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0);
5011 if (p->vrtp)
5012 ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0);
5016 if (udptlportno != -1) {
5017 int found = 0, x;
5019 old = 0;
5021 /* Scan trough the a= lines for T38 attributes and set apropriate fileds */
5022 iterator = req->sdp_start;
5023 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
5024 if ((sscanf(a, "T38FaxMaxBuffer:%d", &x) == 1)) {
5025 found = 1;
5026 if (option_debug > 2)
5027 ast_log(LOG_DEBUG, "MaxBufferSize:%d\n",x);
5028 } else if ((sscanf(a, "T38MaxBitRate:%d", &x) == 1)) {
5029 found = 1;
5030 if (option_debug > 2)
5031 ast_log(LOG_DEBUG,"T38MaxBitRate: %d\n",x);
5032 switch (x) {
5033 case 14400:
5034 peert38capability |= T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5035 break;
5036 case 12000:
5037 peert38capability |= T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5038 break;
5039 case 9600:
5040 peert38capability |= T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5041 break;
5042 case 7200:
5043 peert38capability |= T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
5044 break;
5045 case 4800:
5046 peert38capability |= T38FAX_RATE_4800 | T38FAX_RATE_2400;
5047 break;
5048 case 2400:
5049 peert38capability |= T38FAX_RATE_2400;
5050 break;
5052 } else if ((sscanf(a, "T38FaxVersion:%d", &x) == 1)) {
5053 found = 1;
5054 if (option_debug > 2)
5055 ast_log(LOG_DEBUG, "FaxVersion: %d\n",x);
5056 if (x == 0)
5057 peert38capability |= T38FAX_VERSION_0;
5058 else if (x == 1)
5059 peert38capability |= T38FAX_VERSION_1;
5060 } else if ((sscanf(a, "T38FaxMaxDatagram:%d", &x) == 1)) {
5061 found = 1;
5062 if (option_debug > 2)
5063 ast_log(LOG_DEBUG, "FaxMaxDatagram: %d\n",x);
5064 ast_udptl_set_far_max_datagram(p->udptl, x);
5065 ast_udptl_set_local_max_datagram(p->udptl, x);
5066 } else if ((sscanf(a, "T38FaxFillBitRemoval:%d", &x) == 1)) {
5067 found = 1;
5068 if (option_debug > 2)
5069 ast_log(LOG_DEBUG, "FillBitRemoval: %d\n",x);
5070 if (x == 1)
5071 peert38capability |= T38FAX_FILL_BIT_REMOVAL;
5072 } else if ((sscanf(a, "T38FaxTranscodingMMR:%d", &x) == 1)) {
5073 found = 1;
5074 if (option_debug > 2)
5075 ast_log(LOG_DEBUG, "Transcoding MMR: %d\n",x);
5076 if (x == 1)
5077 peert38capability |= T38FAX_TRANSCODING_MMR;
5079 if ((sscanf(a, "T38FaxTranscodingJBIG:%d", &x) == 1)) {
5080 found = 1;
5081 if (option_debug > 2)
5082 ast_log(LOG_DEBUG, "Transcoding JBIG: %d\n",x);
5083 if (x == 1)
5084 peert38capability |= T38FAX_TRANSCODING_JBIG;
5085 } else if ((sscanf(a, "T38FaxRateManagement:%s", s) == 1)) {
5086 found = 1;
5087 if (option_debug > 2)
5088 ast_log(LOG_DEBUG, "RateMangement: %s\n", s);
5089 if (!strcasecmp(s, "localTCF"))
5090 peert38capability |= T38FAX_RATE_MANAGEMENT_LOCAL_TCF;
5091 else if (!strcasecmp(s, "transferredTCF"))
5092 peert38capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
5093 } else if ((sscanf(a, "T38FaxUdpEC:%s", s) == 1)) {
5094 found = 1;
5095 if (option_debug > 2)
5096 ast_log(LOG_DEBUG, "UDP EC: %s\n", s);
5097 if (!strcasecmp(s, "t38UDPRedundancy")) {
5098 peert38capability |= T38FAX_UDP_EC_REDUNDANCY;
5099 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
5100 } else if (!strcasecmp(s, "t38UDPFEC")) {
5101 peert38capability |= T38FAX_UDP_EC_FEC;
5102 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
5103 } else {
5104 peert38capability |= T38FAX_UDP_EC_NONE;
5105 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
5109 if (found) { /* Some cisco equipment returns nothing beside c= and m= lines in 200 OK T38 SDP */
5110 p->t38.peercapability = peert38capability;
5111 p->t38.jointcapability = (peert38capability & 255); /* Put everything beside supported speeds settings */
5112 peert38capability &= (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400);
5113 p->t38.jointcapability |= (peert38capability & p->t38.capability); /* Put the lower of our's and peer's speed */
5115 if (debug)
5116 ast_log(LOG_DEBUG, "Our T38 capability = (%d), peer T38 capability (%d), joint T38 capability (%d)\n",
5117 p->t38.capability,
5118 p->t38.peercapability,
5119 p->t38.jointcapability);
5120 } else {
5121 p->t38.state = T38_DISABLED;
5122 if (option_debug > 2)
5123 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
5126 /* Now gather all of the codecs that we are asked for: */
5127 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
5128 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
5130 newjointcapability = p->capability & (peercapability | vpeercapability);
5131 newpeercapability = (peercapability | vpeercapability);
5132 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
5135 if (debug) {
5136 /* shame on whoever coded this.... */
5137 char s1[BUFSIZ], s2[BUFSIZ], s3[BUFSIZ], s4[BUFSIZ];
5139 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
5140 ast_getformatname_multiple(s1, BUFSIZ, p->capability),
5141 ast_getformatname_multiple(s2, BUFSIZ, newpeercapability),
5142 ast_getformatname_multiple(s3, BUFSIZ, vpeercapability),
5143 ast_getformatname_multiple(s4, BUFSIZ, newjointcapability));
5145 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
5146 ast_rtp_lookup_mime_multiple(s1, BUFSIZ, p->noncodeccapability, 0, 0),
5147 ast_rtp_lookup_mime_multiple(s2, BUFSIZ, peernoncodeccapability, 0, 0),
5148 ast_rtp_lookup_mime_multiple(s3, BUFSIZ, newnoncodeccapability, 0, 0));
5150 if (!newjointcapability) {
5151 /* If T.38 was not negotiated either, totally bail out... */
5152 if (!p->t38.jointcapability) {
5153 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
5154 /* Do NOT Change current setting */
5155 return -1;
5156 } else {
5157 if (option_debug > 2)
5158 ast_log(LOG_DEBUG, "Have T.38 but no audio codecs, accepting offer anyway\n");
5159 return 0;
5163 /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
5164 they are acceptable */
5165 p->jointcapability = newjointcapability; /* Our joint codec profile for this call */
5166 p->peercapability = newpeercapability; /* The other sides capability in latest offer */
5167 p->jointnoncodeccapability = newnoncodeccapability; /* DTMF capabilities */
5169 ast_rtp_pt_copy(p->rtp, newaudiortp);
5170 if (p->vrtp)
5171 ast_rtp_pt_copy(p->vrtp, newvideortp);
5173 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
5174 ast_clear_flag(&p->flags[0], SIP_DTMF);
5175 if (newnoncodeccapability & AST_RTP_DTMF) {
5176 /* XXX Would it be reasonable to drop the DSP at this point? XXX */
5177 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
5178 /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
5179 ast_rtp_setdtmf(p->rtp, 1);
5180 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
5181 } else {
5182 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
5186 /* Setup audio port number */
5187 if (p->rtp && sin.sin_port) {
5188 ast_rtp_set_peer(p->rtp, &sin);
5189 if (debug)
5190 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
5193 /* Setup video port number */
5194 if (p->vrtp && vsin.sin_port) {
5195 ast_rtp_set_peer(p->vrtp, &vsin);
5196 if (debug)
5197 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
5200 /* Ok, we're going with this offer */
5201 if (option_debug > 1) {
5202 char buf[BUFSIZ];
5203 ast_log(LOG_DEBUG, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, BUFSIZ, p->jointcapability));
5206 if (!p->owner) /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
5207 return 0;
5209 if (option_debug > 3)
5210 ast_log(LOG_DEBUG, "We have an owner, now see if we need to change this call\n");
5212 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
5213 if (debug) {
5214 char s1[BUFSIZ], s2[BUFSIZ];
5215 ast_log(LOG_DEBUG, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
5216 ast_getformatname_multiple(s1, BUFSIZ, p->jointcapability),
5217 ast_getformatname_multiple(s2, BUFSIZ, p->owner->nativeformats));
5219 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability);
5220 ast_set_read_format(p->owner, p->owner->readformat);
5221 ast_set_write_format(p->owner, p->owner->writeformat);
5224 if (sin.sin_addr.s_addr && !sendonly) {
5225 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
5226 /* Activate a re-invite */
5227 ast_queue_frame(p->owner, &ast_null_frame);
5228 } else if (!sin.sin_addr.s_addr || sendonly) {
5229 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
5230 S_OR(p->mohsuggest, NULL),
5231 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
5232 if (sendonly)
5233 ast_rtp_stop(p->rtp);
5234 /* RTCP needs to go ahead, even if we're on hold!!! */
5235 /* Activate a re-invite */
5236 ast_queue_frame(p->owner, &ast_null_frame);
5239 /* Manager Hold and Unhold events must be generated, if necessary */
5240 if (sin.sin_addr.s_addr && !sendonly) {
5241 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
5242 append_history(p, "Unhold", "%s", req->data);
5243 if (global_callevents)
5244 manager_event(EVENT_FLAG_CALL, "Unhold",
5245 "Channel: %s\r\n"
5246 "Uniqueid: %s\r\n",
5247 p->owner->name,
5248 p->owner->uniqueid);
5249 if (global_notifyhold)
5250 sip_peer_hold(p, 0);
5252 ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
5253 } else if (!sin.sin_addr.s_addr || sendonly ) {
5254 /* No address for RTP, we're on hold */
5255 append_history(p, "Hold", "%s", req->data);
5257 if (global_callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
5258 manager_event(EVENT_FLAG_CALL, "Hold",
5259 "Channel: %s\r\n"
5260 "Uniqueid: %s\r\n",
5261 p->owner->name,
5262 p->owner->uniqueid);
5264 if (sendonly == 1) /* One directional hold (sendonly/recvonly) */
5265 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
5266 else if (sendonly == 2) /* Inactive stream */
5267 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
5268 if (global_notifyhold)
5269 sip_peer_hold(p, 1);
5272 return 0;
5276 /*! \brief Add header to SIP message */
5277 static int add_header(struct sip_request *req, const char *var, const char *value)
5279 int maxlen = sizeof(req->data) - 4 - req->len; /* 4 bytes are for two \r\n ? */
5281 if (req->headers == SIP_MAX_HEADERS) {
5282 ast_log(LOG_WARNING, "Out of SIP header space\n");
5283 return -1;
5286 if (req->lines) {
5287 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
5288 return -1;
5291 if (maxlen <= 0) {
5292 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
5293 return -1;
5296 req->header[req->headers] = req->data + req->len;
5298 if (compactheaders)
5299 var = find_alias(var, var);
5301 snprintf(req->header[req->headers], maxlen, "%s: %s\r\n", var, value);
5302 req->len += strlen(req->header[req->headers]);
5303 req->headers++;
5304 if (req->headers < SIP_MAX_HEADERS)
5305 req->headers++;
5306 else
5307 ast_log(LOG_WARNING, "Out of SIP header space... Will generate broken SIP message\n");
5309 return 0;
5312 /*! \brief Add 'Content-Length' header to SIP message */
5313 static int add_header_contentLength(struct sip_request *req, int len)
5315 char clen[10];
5317 snprintf(clen, sizeof(clen), "%d", len);
5318 return add_header(req, "Content-Length", clen);
5321 /*! \brief Add content (not header) to SIP message */
5322 static int add_line(struct sip_request *req, const char *line)
5324 if (req->lines == SIP_MAX_LINES) {
5325 ast_log(LOG_WARNING, "Out of SIP line space\n");
5326 return -1;
5328 if (!req->lines) {
5329 /* Add extra empty return */
5330 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
5331 req->len += strlen(req->data + req->len);
5333 if (req->len >= sizeof(req->data) - 4) {
5334 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
5335 return -1;
5337 req->line[req->lines] = req->data + req->len;
5338 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
5339 req->len += strlen(req->line[req->lines]);
5340 req->lines++;
5341 return 0;
5344 /*! \brief Copy one header field from one request to another */
5345 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
5347 const char *tmp = get_header(orig, field);
5349 if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
5350 return add_header(req, field, tmp);
5351 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
5352 return -1;
5355 /*! \brief Copy all headers from one request to another */
5356 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
5358 int start = 0;
5359 int copied = 0;
5360 for (;;) {
5361 const char *tmp = __get_header(orig, field, &start);
5363 if (ast_strlen_zero(tmp))
5364 break;
5365 /* Add what we're responding to */
5366 add_header(req, field, tmp);
5367 copied++;
5369 return copied ? 0 : -1;
5372 /*! \brief Copy SIP VIA Headers from the request to the response
5373 \note If the client indicates that it wishes to know the port we received from,
5374 it adds ;rport without an argument to the topmost via header. We need to
5375 add the port number (from our point of view) to that parameter.
5376 We always add ;received=<ip address> to the topmost via header.
5377 Received: RFC 3261, rport RFC 3581 */
5378 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
5380 int copied = 0;
5381 int start = 0;
5383 for (;;) {
5384 char new[256];
5385 const char *oh = __get_header(orig, field, &start);
5387 if (ast_strlen_zero(oh))
5388 break;
5390 if (!copied) { /* Only check for empty rport in topmost via header */
5391 char leftmost[256], *others, *rport;
5393 /* Only work on leftmost value */
5394 ast_copy_string(leftmost, oh, sizeof(leftmost));
5395 others = strchr(leftmost, ',');
5396 if (others)
5397 *others++ = '\0';
5399 /* Find ;rport; (empty request) */
5400 rport = strstr(leftmost, ";rport");
5401 if (rport && *(rport+6) == '=')
5402 rport = NULL; /* We already have a parameter to rport */
5404 /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting) */
5405 if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
5406 /* We need to add received port - rport */
5407 char *end;
5409 rport = strstr(leftmost, ";rport");
5411 if (rport) {
5412 end = strchr(rport + 1, ';');
5413 if (end)
5414 memmove(rport, end, strlen(end) + 1);
5415 else
5416 *rport = '\0';
5419 /* Add rport to first VIA header if requested */
5420 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
5421 leftmost, ast_inet_ntoa(p->recv.sin_addr),
5422 ntohs(p->recv.sin_port),
5423 others ? "," : "", others ? others : "");
5424 } else {
5425 /* We should *always* add a received to the topmost via */
5426 snprintf(new, sizeof(new), "%s;received=%s%s%s",
5427 leftmost, ast_inet_ntoa(p->recv.sin_addr),
5428 others ? "," : "", others ? others : "");
5430 oh = new; /* the header to copy */
5431 } /* else add the following via headers untouched */
5432 add_header(req, field, oh);
5433 copied++;
5435 if (!copied) {
5436 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
5437 return -1;
5439 return 0;
5442 /*! \brief Add route header into request per learned route */
5443 static void add_route(struct sip_request *req, struct sip_route *route)
5445 char r[BUFSIZ*2], *p;
5446 int n, rem = sizeof(r);
5448 if (!route)
5449 return;
5451 p = r;
5452 for (;route ; route = route->next) {
5453 n = strlen(route->hop);
5454 if (rem < n+3) /* we need room for ",<route>" */
5455 break;
5456 if (p != r) { /* add a separator after fist route */
5457 *p++ = ',';
5458 --rem;
5460 *p++ = '<';
5461 ast_copy_string(p, route->hop, rem); /* cannot fail */
5462 p += n;
5463 *p++ = '>';
5464 rem -= (n+2);
5466 *p = '\0';
5467 add_header(req, "Route", r);
5470 /*! \brief Set destination from SIP URI */
5471 static void set_destination(struct sip_pvt *p, char *uri)
5473 char *h, *maddr, hostname[256];
5474 int port, hn;
5475 struct hostent *hp;
5476 struct ast_hostent ahp;
5477 int debug=sip_debug_test_pvt(p);
5479 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
5480 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
5482 if (debug)
5483 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
5485 /* Find and parse hostname */
5486 h = strchr(uri, '@');
5487 if (h)
5488 ++h;
5489 else {
5490 h = uri;
5491 if (strncmp(h, "sip:", 4) == 0)
5492 h += 4;
5493 else if (strncmp(h, "sips:", 5) == 0)
5494 h += 5;
5496 hn = strcspn(h, ":;>") + 1;
5497 if (hn > sizeof(hostname))
5498 hn = sizeof(hostname);
5499 ast_copy_string(hostname, h, hn);
5500 /* XXX bug here if string has been trimmed to sizeof(hostname) */
5501 h += hn - 1;
5503 /* Is "port" present? if not default to STANDARD_SIP_PORT */
5504 if (*h == ':') {
5505 /* Parse port */
5506 ++h;
5507 port = strtol(h, &h, 10);
5509 else
5510 port = STANDARD_SIP_PORT;
5512 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
5513 maddr = strstr(h, "maddr=");
5514 if (maddr) {
5515 maddr += 6;
5516 hn = strspn(maddr, "0123456789.") + 1;
5517 if (hn > sizeof(hostname))
5518 hn = sizeof(hostname);
5519 ast_copy_string(hostname, maddr, hn);
5522 hp = ast_gethostbyname(hostname, &ahp);
5523 if (hp == NULL) {
5524 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
5525 return;
5527 p->sa.sin_family = AF_INET;
5528 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
5529 p->sa.sin_port = htons(port);
5530 if (debug)
5531 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
5534 /*! \brief Initialize SIP response, based on SIP request */
5535 static int init_resp(struct sip_request *resp, const char *msg)
5537 /* Initialize a response */
5538 memset(resp, 0, sizeof(*resp));
5539 resp->method = SIP_RESPONSE;
5540 resp->header[0] = resp->data;
5541 snprintf(resp->header[0], sizeof(resp->data), "SIP/2.0 %s\r\n", msg);
5542 resp->len = strlen(resp->header[0]);
5543 resp->headers++;
5544 return 0;
5547 /*! \brief Initialize SIP request */
5548 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
5550 /* Initialize a request */
5551 memset(req, 0, sizeof(*req));
5552 req->method = sipmethod;
5553 req->header[0] = req->data;
5554 snprintf(req->header[0], sizeof(req->data), "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
5555 req->len = strlen(req->header[0]);
5556 req->headers++;
5557 return 0;
5561 /*! \brief Prepare SIP response packet */
5562 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
5564 char newto[256];
5565 const char *ot;
5567 init_resp(resp, msg);
5568 copy_via_headers(p, resp, req, "Via");
5569 if (msg[0] == '2')
5570 copy_all_header(resp, req, "Record-Route");
5571 copy_header(resp, req, "From");
5572 ot = get_header(req, "To");
5573 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
5574 /* Add the proper tag if we don't have it already. If they have specified
5575 their tag, use it. Otherwise, use our own tag */
5576 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
5577 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
5578 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
5579 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
5580 else
5581 ast_copy_string(newto, ot, sizeof(newto));
5582 ot = newto;
5584 add_header(resp, "To", ot);
5585 copy_header(resp, req, "Call-ID");
5586 copy_header(resp, req, "CSeq");
5587 add_header(resp, "User-Agent", global_useragent);
5588 add_header(resp, "Allow", ALLOWED_METHODS);
5589 add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
5590 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
5591 /* For registration responses, we also need expiry and
5592 contact info */
5593 char tmp[256];
5595 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
5596 add_header(resp, "Expires", tmp);
5597 if (p->expiry) { /* Only add contact if we have an expiry time */
5598 char contact[256];
5599 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
5600 add_header(resp, "Contact", contact); /* Not when we unregister */
5602 } else if (msg[0] != '4' && p->our_contact[0]) {
5603 add_header(resp, "Contact", p->our_contact);
5605 return 0;
5608 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
5609 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
5611 struct sip_request *orig = &p->initreq;
5612 char stripped[80];
5613 char tmp[80];
5614 char newto[256];
5615 const char *c;
5616 const char *ot, *of;
5617 int is_strict = FALSE; /*!< Strict routing flag */
5619 memset(req, 0, sizeof(struct sip_request));
5621 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
5623 if (!seqno) {
5624 p->ocseq++;
5625 seqno = p->ocseq;
5628 if (newbranch) {
5629 p->branch ^= ast_random();
5630 build_via(p);
5633 /* Check for strict or loose router */
5634 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop,";lr") == NULL) {
5635 is_strict = TRUE;
5636 if (sipdebug)
5637 ast_log(LOG_DEBUG, "Strict routing enforced for session %s\n", p->callid);
5640 if (sipmethod == SIP_CANCEL)
5641 c = p->initreq.rlPart2; /* Use original URI */
5642 else if (sipmethod == SIP_ACK) {
5643 /* Use URI from Contact: in 200 OK (if INVITE)
5644 (we only have the contacturi on INVITEs) */
5645 if (!ast_strlen_zero(p->okcontacturi))
5646 c = is_strict ? p->route->hop : p->okcontacturi;
5647 else
5648 c = p->initreq.rlPart2;
5649 } else if (!ast_strlen_zero(p->okcontacturi))
5650 c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
5651 else if (!ast_strlen_zero(p->uri))
5652 c = p->uri;
5653 else {
5654 char *n;
5655 /* We have no URI, use To: or From: header as URI (depending on direction) */
5656 ast_copy_string(stripped, get_header(orig, (ast_test_flag(&p->flags[0], SIP_OUTGOING)) ? "To" : "From"),
5657 sizeof(stripped));
5658 n = get_in_brackets(stripped);
5659 c = strsep(&n, ";"); /* trim ; and beyond */
5661 init_req(req, sipmethod, c);
5663 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
5665 add_header(req, "Via", p->via);
5666 if (p->route) {
5667 set_destination(p, p->route->hop);
5668 add_route(req, is_strict ? p->route->next : p->route);
5671 ot = get_header(orig, "To");
5672 of = get_header(orig, "From");
5674 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
5675 as our original request, including tag (or presumably lack thereof) */
5676 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
5677 /* Add the proper tag if we don't have it already. If they have specified
5678 their tag, use it. Otherwise, use our own tag */
5679 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_strlen_zero(p->theirtag))
5680 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
5681 else if (!ast_test_flag(&p->flags[0], SIP_OUTGOING))
5682 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
5683 else
5684 snprintf(newto, sizeof(newto), "%s", ot);
5685 ot = newto;
5688 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
5689 add_header(req, "From", of);
5690 add_header(req, "To", ot);
5691 } else {
5692 add_header(req, "From", ot);
5693 add_header(req, "To", of);
5695 /* Do not add Contact for MESSAGE, BYE and Cancel requests */
5696 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
5697 add_header(req, "Contact", p->our_contact);
5699 copy_header(req, orig, "Call-ID");
5700 add_header(req, "CSeq", tmp);
5702 add_header(req, "User-Agent", global_useragent);
5703 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
5705 if (!ast_strlen_zero(p->rpid))
5706 add_header(req, "Remote-Party-ID", p->rpid);
5708 return 0;
5711 /*! \brief Base transmit response function */
5712 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
5714 struct sip_request resp;
5715 int seqno = 0;
5717 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
5718 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
5719 return -1;
5721 respprep(&resp, p, msg, req);
5722 add_header_contentLength(&resp, 0);
5723 /* If we are cancelling an incoming invite for some reason, add information
5724 about the reason why we are doing this in clear text */
5725 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
5726 char buf[10];
5728 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
5729 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
5730 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
5732 return send_response(p, &resp, reliable, seqno);
5735 static void temp_pvt_cleanup(void *data)
5737 struct sip_pvt *p = data;
5739 ast_string_field_free_pools(p);
5741 free(data);
5744 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
5745 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)
5747 struct sip_pvt *p = NULL;
5749 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
5750 ast_log(LOG_NOTICE, "Failed to get temporary pvt\n");
5751 return -1;
5754 /* if the structure was just allocated, initialize it */
5755 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
5756 ast_set_flag(&p->flags[0], SIP_NO_HISTORY);
5757 if (ast_string_field_init(p, 512))
5758 return -1;
5761 /* Initialize the bare minimum */
5762 p->method = intended_method;
5764 if (sin) {
5765 p->sa = *sin;
5766 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
5767 p->ourip = __ourip;
5768 } else
5769 p->ourip = __ourip;
5771 p->branch = ast_random();
5772 make_our_tag(p->tag, sizeof(p->tag));
5773 p->ocseq = INITIAL_CSEQ;
5775 if (useglobal_nat && sin) {
5776 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
5777 p->recv = *sin;
5778 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
5781 ast_string_field_set(p, fromdomain, default_fromdomain);
5782 build_via(p);
5783 ast_string_field_set(p, callid, callid);
5785 /* Use this temporary pvt structure to send the message */
5786 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
5788 /* Free the string fields, but not the pool space */
5789 ast_string_field_free_all(p);
5791 return 0;
5794 /*! \brief Transmit response, no retransmits */
5795 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
5797 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
5800 /*! \brief Transmit response, no retransmits */
5801 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
5803 struct sip_request resp;
5804 respprep(&resp, p, msg, req);
5805 append_date(&resp);
5806 add_header(&resp, "Unsupported", unsupported);
5807 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
5810 /*! \brief Transmit response, Make sure you get an ACK
5811 This is only used for responses to INVITEs, where we need to make sure we get an ACK
5813 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
5815 return __transmit_response(p, msg, req, XMIT_CRITICAL);
5818 /*! \brief Append date to SIP message */
5819 static void append_date(struct sip_request *req)
5821 char tmpdat[256];
5822 struct tm tm;
5823 time_t t = time(NULL);
5825 gmtime_r(&t, &tm);
5826 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
5827 add_header(req, "Date", tmpdat);
5830 /*! \brief Append date and content length before transmitting response */
5831 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
5833 struct sip_request resp;
5834 respprep(&resp, p, msg, req);
5835 append_date(&resp);
5836 add_header_contentLength(&resp, 0);
5837 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
5840 /*! \brief Append Accept header, content length before transmitting response */
5841 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
5843 struct sip_request resp;
5844 respprep(&resp, p, msg, req);
5845 add_header(&resp, "Accept", "application/sdp");
5846 add_header_contentLength(&resp, 0);
5847 return send_response(p, &resp, reliable, 0);
5850 /*! \brief Respond with authorization request */
5851 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)
5853 struct sip_request resp;
5854 char tmp[512];
5855 int seqno = 0;
5857 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
5858 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
5859 return -1;
5861 /* Stale means that they sent us correct authentication, but
5862 based it on an old challenge (nonce) */
5863 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
5864 respprep(&resp, p, msg, req);
5865 add_header(&resp, header, tmp);
5866 add_header_contentLength(&resp, 0);
5867 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
5868 return send_response(p, &resp, reliable, seqno);
5871 /*! \brief Add text body to SIP message */
5872 static int add_text(struct sip_request *req, const char *text)
5874 /* XXX Convert \n's to \r\n's XXX */
5875 add_header(req, "Content-Type", "text/plain");
5876 add_header_contentLength(req, strlen(text));
5877 add_line(req, text);
5878 return 0;
5881 /*! \brief Add DTMF INFO tone to sip message */
5882 /* Always adds default duration 250 ms, regardless of what came in over the line */
5883 static int add_digit(struct sip_request *req, char digit, unsigned int duration)
5885 char tmp[256];
5887 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
5888 add_header(req, "Content-Type", "application/dtmf-relay");
5889 add_header_contentLength(req, strlen(tmp));
5890 add_line(req, tmp);
5891 return 0;
5894 /*! \brief add XML encoded media control with update
5895 \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
5896 static int add_vidupdate(struct sip_request *req)
5898 const char *xml_is_a_huge_waste_of_space =
5899 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
5900 " <media_control>\r\n"
5901 " <vc_primitive>\r\n"
5902 " <to_encoder>\r\n"
5903 " <picture_fast_update>\r\n"
5904 " </picture_fast_update>\r\n"
5905 " </to_encoder>\r\n"
5906 " </vc_primitive>\r\n"
5907 " </media_control>\r\n";
5908 add_header(req, "Content-Type", "application/media_control+xml");
5909 add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
5910 add_line(req, xml_is_a_huge_waste_of_space);
5911 return 0;
5914 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
5915 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
5916 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
5917 int debug, int *min_packet_size)
5919 int rtp_code;
5920 struct ast_format_list fmt;
5923 if (debug)
5924 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
5925 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
5926 return;
5928 if (p->rtp) {
5929 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
5930 fmt = ast_codec_pref_getsize(pref, codec);
5931 } 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 */
5932 return;
5933 ast_build_string(m_buf, m_size, " %d", rtp_code);
5934 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
5935 ast_rtp_lookup_mime_subtype(1, codec,
5936 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
5937 sample_rate);
5938 if (codec == AST_FORMAT_G729A) {
5939 /* Indicate that we don't support VAD (G.729 annex B) */
5940 ast_build_string(a_buf, a_size, "a=fmtp:%d annexb=no\r\n", rtp_code);
5941 } else if (codec == AST_FORMAT_ILBC) {
5942 /* Add information about us using only 20/30 ms packetization */
5943 ast_build_string(a_buf, a_size, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
5946 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
5947 *min_packet_size = fmt.cur_ms;
5949 /* Our first codec packetization processed cannot be less than zero */
5950 if ((*min_packet_size) == 0 && fmt.cur_ms)
5951 *min_packet_size = fmt.cur_ms;
5954 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
5955 static int t38_get_rate(int t38cap)
5957 int maxrate = (t38cap & (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400));
5959 if (maxrate & T38FAX_RATE_14400) {
5960 if (option_debug > 1)
5961 ast_log(LOG_DEBUG, "T38MaxFaxRate 14400 found\n");
5962 return 14400;
5963 } else if (maxrate & T38FAX_RATE_12000) {
5964 if (option_debug > 1)
5965 ast_log(LOG_DEBUG, "T38MaxFaxRate 12000 found\n");
5966 return 12000;
5967 } else if (maxrate & T38FAX_RATE_9600) {
5968 if (option_debug > 1)
5969 ast_log(LOG_DEBUG, "T38MaxFaxRate 9600 found\n");
5970 return 9600;
5971 } else if (maxrate & T38FAX_RATE_7200) {
5972 if (option_debug > 1)
5973 ast_log(LOG_DEBUG, "T38MaxFaxRate 7200 found\n");
5974 return 7200;
5975 } else if (maxrate & T38FAX_RATE_4800) {
5976 if (option_debug > 1)
5977 ast_log(LOG_DEBUG, "T38MaxFaxRate 4800 found\n");
5978 return 4800;
5979 } else if (maxrate & T38FAX_RATE_2400) {
5980 if (option_debug > 1)
5981 ast_log(LOG_DEBUG, "T38MaxFaxRate 2400 found\n");
5982 return 2400;
5983 } else {
5984 if (option_debug > 1)
5985 ast_log(LOG_DEBUG, "Strange, T38MaxFaxRate NOT found in peers T38 SDP.\n");
5986 return 0;
5990 /*! \brief Add T.38 Session Description Protocol message */
5991 static int add_t38_sdp(struct sip_request *resp, struct sip_pvt *p)
5993 int len = 0;
5994 int x = 0;
5995 struct sockaddr_in udptlsin;
5996 char v[256] = "";
5997 char s[256] = "";
5998 char o[256] = "";
5999 char c[256] = "";
6000 char t[256] = "";
6001 char m_modem[256];
6002 char a_modem[1024];
6003 char *m_modem_next = m_modem;
6004 size_t m_modem_left = sizeof(m_modem);
6005 char *a_modem_next = a_modem;
6006 size_t a_modem_left = sizeof(a_modem);
6007 struct sockaddr_in udptldest = { 0, };
6008 int debug;
6010 debug = sip_debug_test_pvt(p);
6011 len = 0;
6012 if (!p->udptl) {
6013 ast_log(LOG_WARNING, "No way to add SDP without an UDPTL structure\n");
6014 return -1;
6017 if (!p->sessionid) {
6018 p->sessionid = getpid();
6019 p->sessionversion = p->sessionid;
6020 } else
6021 p->sessionversion++;
6023 /* Our T.38 end is */
6024 ast_udptl_get_us(p->udptl, &udptlsin);
6026 /* Determine T.38 UDPTL destination */
6027 if (p->udptlredirip.sin_addr.s_addr) {
6028 udptldest.sin_port = p->udptlredirip.sin_port;
6029 udptldest.sin_addr = p->udptlredirip.sin_addr;
6030 } else {
6031 udptldest.sin_addr = p->ourip;
6032 udptldest.sin_port = udptlsin.sin_port;
6035 if (debug)
6036 ast_log(LOG_DEBUG, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(udptlsin.sin_port));
6038 /* We break with the "recommendation" and send our IP, in order that our
6039 peer doesn't have to ast_gethostbyname() us */
6041 if (debug) {
6042 ast_log(LOG_DEBUG, "Our T38 capability (%d), peer T38 capability (%d), joint capability (%d)\n",
6043 p->t38.capability,
6044 p->t38.peercapability,
6045 p->t38.jointcapability);
6047 snprintf(v, sizeof(v), "v=0\r\n");
6048 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(udptldest.sin_addr));
6049 snprintf(s, sizeof(s), "s=session\r\n");
6050 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(udptldest.sin_addr));
6051 snprintf(t, sizeof(t), "t=0 0\r\n");
6052 ast_build_string(&m_modem_next, &m_modem_left, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
6054 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_0)
6055 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:0\r\n");
6056 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_1)
6057 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:1\r\n");
6058 if ((x = t38_get_rate(p->t38.jointcapability)))
6059 ast_build_string(&a_modem_next, &a_modem_left, "a=T38MaxBitRate:%d\r\n",x);
6060 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxFillBitRemoval:%d\r\n", (p->t38.jointcapability & T38FAX_FILL_BIT_REMOVAL) ? 1 : 0);
6061 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingMMR:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_MMR) ? 1 : 0);
6062 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingJBIG:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_JBIG) ? 1 : 0);
6063 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxRateManagement:%s\r\n", (p->t38.jointcapability & T38FAX_RATE_MANAGEMENT_LOCAL_TCF) ? "localTCF" : "transferredTCF");
6064 x = ast_udptl_get_local_max_datagram(p->udptl);
6065 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxBuffer:%d\r\n",x);
6066 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxDatagram:%d\r\n",x);
6067 if (p->t38.jointcapability != T38FAX_UDP_EC_NONE)
6068 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxUdpEC:%s\r\n", (p->t38.jointcapability & T38FAX_UDP_EC_REDUNDANCY) ? "t38UDPRedundancy" : "t38UDPFEC");
6069 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m_modem) + strlen(a_modem);
6070 add_header(resp, "Content-Type", "application/sdp");
6071 add_header_contentLength(resp, len);
6072 add_line(resp, v);
6073 add_line(resp, o);
6074 add_line(resp, s);
6075 add_line(resp, c);
6076 add_line(resp, t);
6077 add_line(resp, m_modem);
6078 add_line(resp, a_modem);
6080 /* Update lastrtprx when we send our SDP */
6081 p->lastrtprx = p->lastrtptx = time(NULL);
6083 return 0;
6087 /*! \brief Add RFC 2833 DTMF offer to SDP */
6088 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
6089 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
6090 int debug)
6092 int rtp_code;
6094 if (debug)
6095 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
6096 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
6097 return;
6099 ast_build_string(m_buf, m_size, " %d", rtp_code);
6100 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
6101 ast_rtp_lookup_mime_subtype(0, format, 0),
6102 sample_rate);
6103 if (format == AST_RTP_DTMF)
6104 /* Indicate we support DTMF and FLASH... */
6105 ast_build_string(a_buf, a_size, "a=fmtp:%d 0-16\r\n", rtp_code);
6108 #define SDP_SAMPLE_RATE(x) (x == AST_FORMAT_G722) ? 16000 : 8000
6110 /*! \brief Add Session Description Protocol message */
6111 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p)
6113 int len = 0;
6114 int alreadysent = 0;
6116 struct sockaddr_in sin;
6117 struct sockaddr_in vsin;
6118 struct sockaddr_in dest;
6119 struct sockaddr_in vdest = { 0, };
6121 /* SDP fields */
6122 char *version = "v=0\r\n"; /* Protocol version */
6123 char *subject = "s=session\r\n"; /* Subject of the session */
6124 char owner[256]; /* Session owner/creator */
6125 char connection[256]; /* Connection data */
6126 char *stime = "t=0 0\r\n"; /* Time the session is active */
6127 char bandwidth[256] = ""; /* Max bitrate */
6128 char *hold;
6129 char m_audio[256]; /* Media declaration line for audio */
6130 char m_video[256]; /* Media declaration line for video */
6131 char a_audio[1024]; /* Attributes for audio */
6132 char a_video[1024]; /* Attributes for video */
6133 char *m_audio_next = m_audio;
6134 char *m_video_next = m_video;
6135 size_t m_audio_left = sizeof(m_audio);
6136 size_t m_video_left = sizeof(m_video);
6137 char *a_audio_next = a_audio;
6138 char *a_video_next = a_video;
6139 size_t a_audio_left = sizeof(a_audio);
6140 size_t a_video_left = sizeof(a_video);
6142 int x;
6143 int capability;
6144 int needvideo = FALSE;
6145 int debug = sip_debug_test_pvt(p);
6146 int min_audio_packet_size = 0;
6147 int min_video_packet_size = 0;
6149 m_video[0] = '\0'; /* Reset the video media string if it's not needed */
6151 if (!p->rtp) {
6152 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
6153 return AST_FAILURE;
6156 /* Set RTP Session ID and version */
6157 if (!p->sessionid) {
6158 p->sessionid = getpid();
6159 p->sessionversion = p->sessionid;
6160 } else
6161 p->sessionversion++;
6163 /* Get our addresses */
6164 ast_rtp_get_us(p->rtp, &sin);
6165 if (p->vrtp)
6166 ast_rtp_get_us(p->vrtp, &vsin);
6168 /* Is this a re-invite to move the media out, then use the original offer from caller */
6169 if (p->redirip.sin_addr.s_addr) {
6170 dest.sin_port = p->redirip.sin_port;
6171 dest.sin_addr = p->redirip.sin_addr;
6172 } else {
6173 dest.sin_addr = p->ourip;
6174 dest.sin_port = sin.sin_port;
6177 capability = p->jointcapability;
6180 if (option_debug > 1) {
6181 char codecbuf[BUFSIZ];
6182 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");
6183 ast_log(LOG_DEBUG, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
6186 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
6187 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_RTP)) {
6188 ast_build_string(&m_audio_next, &m_audio_left, " %d", 191);
6189 ast_build_string(&a_audio_next, &a_audio_left, "a=rtpmap:%d %s/%d\r\n", 191, "t38", 8000);
6191 #endif
6193 /* Check if we need video in this call */
6194 if ((capability & AST_FORMAT_VIDEO_MASK) && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
6195 if (p->vrtp) {
6196 needvideo = TRUE;
6197 if (option_debug > 1)
6198 ast_log(LOG_DEBUG, "This call needs video offers!\n");
6199 } else if (option_debug > 1)
6200 ast_log(LOG_DEBUG, "This call needs video offers, but there's no video support enabled!\n");
6204 /* Ok, we need video. Let's add what we need for video and set codecs.
6205 Video is handled differently than audio since we can not transcode. */
6206 if (needvideo) {
6207 /* Determine video destination */
6208 if (p->vredirip.sin_addr.s_addr) {
6209 vdest.sin_addr = p->vredirip.sin_addr;
6210 vdest.sin_port = p->vredirip.sin_port;
6211 } else {
6212 vdest.sin_addr = p->ourip;
6213 vdest.sin_port = vsin.sin_port;
6215 ast_build_string(&m_video_next, &m_video_left, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
6217 /* Build max bitrate string */
6218 if (p->maxcallbitrate)
6219 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
6220 if (debug)
6221 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(vsin.sin_port));
6224 if (debug)
6225 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(sin.sin_port));
6227 /* Start building generic SDP headers */
6229 /* We break with the "recommendation" and send our IP, in order that our
6230 peer doesn't have to ast_gethostbyname() us */
6232 snprintf(owner, sizeof(owner), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
6233 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
6234 ast_build_string(&m_audio_next, &m_audio_left, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
6236 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR))
6237 hold = "a=recvonly\r\n";
6238 else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE))
6239 hold = "a=inactive\r\n";
6240 else
6241 hold = "a=sendrecv\r\n";
6243 /* Now, start adding audio codecs. These are added in this order:
6244 - First what was requested by the calling channel
6245 - Then preferences in order from sip.conf device config for this peer/user
6246 - Then other codecs in capabilities, including video
6249 /* Prefer the audio codec we were requested to use, first, no matter what
6250 Note that p->prefcodec can include video codecs, so mask them out
6252 if (capability & p->prefcodec) {
6253 int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
6255 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
6256 &m_audio_next, &m_audio_left,
6257 &a_audio_next, &a_audio_left,
6258 debug, &min_audio_packet_size);
6259 alreadysent |= codec;
6262 /* Start by sending our preferred audio codecs */
6263 for (x = 0; x < 32; x++) {
6264 int codec;
6266 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
6267 break;
6269 if (!(capability & codec))
6270 continue;
6272 if (alreadysent & codec)
6273 continue;
6275 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
6276 &m_audio_next, &m_audio_left,
6277 &a_audio_next, &a_audio_left,
6278 debug, &min_audio_packet_size);
6279 alreadysent |= codec;
6282 /* Now send any other common audio and video codecs, and non-codec formats: */
6283 for (x = 1; x <= (needvideo ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
6284 if (!(capability & x)) /* Codec not requested */
6285 continue;
6287 if (alreadysent & x) /* Already added to SDP */
6288 continue;
6290 if (x <= AST_FORMAT_MAX_AUDIO)
6291 add_codec_to_sdp(p, x, SDP_SAMPLE_RATE(x),
6292 &m_audio_next, &m_audio_left,
6293 &a_audio_next, &a_audio_left,
6294 debug, &min_audio_packet_size);
6295 else
6296 add_codec_to_sdp(p, x, 90000,
6297 &m_video_next, &m_video_left,
6298 &a_video_next, &a_video_left,
6299 debug, &min_video_packet_size);
6302 /* Now add DTMF RFC2833 telephony-event as a codec */
6303 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
6304 if (!(p->jointnoncodeccapability & x))
6305 continue;
6307 add_noncodec_to_sdp(p, x, 8000,
6308 &m_audio_next, &m_audio_left,
6309 &a_audio_next, &a_audio_left,
6310 debug);
6313 if (option_debug > 2)
6314 ast_log(LOG_DEBUG, "-- Done with adding codecs to SDP\n");
6316 if (!p->owner || !ast_internal_timing_enabled(p->owner))
6317 ast_build_string(&a_audio_next, &a_audio_left, "a=silenceSupp:off - - - -\r\n");
6319 if (min_audio_packet_size)
6320 ast_build_string(&a_audio_next, &a_audio_left, "a=ptime:%d\r\n", min_audio_packet_size);
6322 if (min_video_packet_size)
6323 ast_build_string(&a_video_next, &a_video_left, "a=ptime:%d\r\n", min_video_packet_size);
6325 if ((m_audio_left < 2) || (m_video_left < 2) || (a_audio_left == 0) || (a_video_left == 0))
6326 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
6328 ast_build_string(&m_audio_next, &m_audio_left, "\r\n");
6329 if (needvideo)
6330 ast_build_string(&m_video_next, &m_video_left, "\r\n");
6332 len = strlen(version) + strlen(subject) + strlen(owner) + strlen(connection) + strlen(stime) + strlen(m_audio) + strlen(a_audio) + strlen(hold);
6333 if (needvideo) /* only if video response is appropriate */
6334 len += strlen(m_video) + strlen(a_video) + strlen(bandwidth) + strlen(hold);
6336 add_header(resp, "Content-Type", "application/sdp");
6337 add_header_contentLength(resp, len);
6338 add_line(resp, version);
6339 add_line(resp, owner);
6340 add_line(resp, subject);
6341 add_line(resp, connection);
6342 if (needvideo) /* only if video response is appropriate */
6343 add_line(resp, bandwidth);
6344 add_line(resp, stime);
6345 add_line(resp, m_audio);
6346 add_line(resp, a_audio);
6347 add_line(resp, hold);
6348 if (needvideo) { /* only if video response is appropriate */
6349 add_line(resp, m_video);
6350 add_line(resp, a_video);
6351 add_line(resp, hold); /* Repeat hold for the video stream */
6354 /* Update lastrtprx when we send our SDP */
6355 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
6357 if (option_debug > 2) {
6358 char buf[BUFSIZ];
6359 ast_log(LOG_DEBUG, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, BUFSIZ, capability));
6362 return AST_SUCCESS;
6365 /*! \brief Used for 200 OK and 183 early media */
6366 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
6368 struct sip_request resp;
6369 int seqno;
6371 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
6372 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
6373 return -1;
6375 respprep(&resp, p, msg, req);
6376 if (p->udptl) {
6377 ast_udptl_offered_from_local(p->udptl, 0);
6378 add_t38_sdp(&resp, p);
6379 } else
6380 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
6381 if (retrans && !p->pendinginvite)
6382 p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
6383 return send_response(p, &resp, retrans, seqno);
6386 /*! \brief copy SIP request (mostly used to save request for responses) */
6387 static void copy_request(struct sip_request *dst, const struct sip_request *src)
6389 long offset;
6390 int x;
6391 offset = ((void *)dst) - ((void *)src);
6392 /* First copy stuff */
6393 memcpy(dst, src, sizeof(*dst));
6394 /* Now fix pointer arithmetic */
6395 for (x=0; x < src->headers; x++)
6396 dst->header[x] += offset;
6397 for (x=0; x < src->lines; x++)
6398 dst->line[x] += offset;
6401 /*! \brief Used for 200 OK and 183 early media */
6402 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
6404 struct sip_request resp;
6405 int seqno;
6406 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
6407 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
6408 return -1;
6410 respprep(&resp, p, msg, req);
6411 if (p->rtp) {
6412 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
6413 if (option_debug)
6414 ast_log(LOG_DEBUG, "Setting framing from config on incoming call\n");
6415 ast_rtp_codec_setpref(p->rtp, &p->prefs);
6417 try_suggested_sip_codec(p);
6418 add_sdp(&resp, p);
6419 } else
6420 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
6421 if (reliable && !p->pendinginvite)
6422 p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
6423 return send_response(p, &resp, reliable, seqno);
6426 /*! \brief Parse first line of incoming SIP request */
6427 static int determine_firstline_parts(struct sip_request *req)
6429 char *e = ast_skip_blanks(req->header[0]); /* there shouldn't be any */
6431 if (!*e)
6432 return -1;
6433 req->rlPart1 = e; /* method or protocol */
6434 e = ast_skip_nonblanks(e);
6435 if (*e)
6436 *e++ = '\0';
6437 /* Get URI or status code */
6438 e = ast_skip_blanks(e);
6439 if ( !*e )
6440 return -1;
6441 ast_trim_blanks(e);
6443 if (!strcasecmp(req->rlPart1, "SIP/2.0") ) { /* We have a response */
6444 if (strlen(e) < 3) /* status code is 3 digits */
6445 return -1;
6446 req->rlPart2 = e;
6447 } else { /* We have a request */
6448 if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
6449 ast_log(LOG_WARNING, "bogus uri in <> %s\n", e);
6450 e++;
6451 if (!*e)
6452 return -1;
6454 req->rlPart2 = e; /* URI */
6455 e = ast_skip_nonblanks(e);
6456 if (*e)
6457 *e++ = '\0';
6458 e = ast_skip_blanks(e);
6459 if (strcasecmp(e, "SIP/2.0") ) {
6460 ast_log(LOG_WARNING, "Bad request protocol %s\n", e);
6461 return -1;
6464 return 1;
6467 /*! \brief Transmit reinvite with SDP
6468 \note A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
6469 INVITE that opened the SIP dialogue
6470 We reinvite so that the audio stream (RTP) go directly between
6471 the SIP UAs. SIP Signalling stays with * in the path.
6473 static int transmit_reinvite_with_sdp(struct sip_pvt *p)
6475 struct sip_request req;
6477 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
6479 add_header(&req, "Allow", ALLOWED_METHODS);
6480 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6481 if (sipdebug)
6482 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
6483 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
6484 append_history(p, "ReInv", "Re-invite sent");
6485 add_sdp(&req, p);
6486 /* Use this as the basis */
6487 initialize_initreq(p, &req);
6488 p->lastinvite = p->ocseq;
6489 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Change direction of this dialog */
6490 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
6493 /*! \brief Transmit reinvite with T38 SDP
6494 We reinvite so that the T38 processing can take place.
6495 SIP Signalling stays with * in the path.
6497 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p)
6499 struct sip_request req;
6501 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
6503 add_header(&req, "Allow", ALLOWED_METHODS);
6504 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6505 if (sipdebug)
6506 add_header(&req, "X-asterisk-info", "SIP re-invite (T38 switchover)");
6507 ast_udptl_offered_from_local(p->udptl, 1);
6508 add_t38_sdp(&req, p);
6509 /* Use this as the basis */
6510 initialize_initreq(p, &req);
6511 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Change direction of this dialog */
6512 p->lastinvite = p->ocseq;
6513 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
6516 /*! \brief Check Contact: URI of SIP message */
6517 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
6519 char stripped[256];
6520 char *c;
6522 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
6523 c = get_in_brackets(stripped);
6524 c = strsep(&c, ";"); /* trim ; and beyond */
6525 if (!ast_strlen_zero(c))
6526 ast_string_field_set(p, uri, c);
6529 /*! \brief Build contact header - the contact header we send out */
6530 static void build_contact(struct sip_pvt *p)
6532 /* Construct Contact: header */
6533 if (ourport != STANDARD_SIP_PORT)
6534 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);
6535 else
6536 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip));
6539 /*! \brief Build the Remote Party-ID & From using callingpres options */
6540 static void build_rpid(struct sip_pvt *p)
6542 int send_pres_tags = TRUE;
6543 const char *privacy=NULL;
6544 const char *screen=NULL;
6545 char buf[256];
6546 const char *clid = default_callerid;
6547 const char *clin = NULL;
6548 const char *fromdomain;
6550 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
6551 return;
6553 if (p->owner && p->owner->cid.cid_num)
6554 clid = p->owner->cid.cid_num;
6555 if (p->owner && p->owner->cid.cid_name)
6556 clin = p->owner->cid.cid_name;
6557 if (ast_strlen_zero(clin))
6558 clin = clid;
6560 switch (p->callingpres) {
6561 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
6562 privacy = "off";
6563 screen = "no";
6564 break;
6565 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
6566 privacy = "off";
6567 screen = "yes";
6568 break;
6569 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
6570 privacy = "off";
6571 screen = "no";
6572 break;
6573 case AST_PRES_ALLOWED_NETWORK_NUMBER:
6574 privacy = "off";
6575 screen = "yes";
6576 break;
6577 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
6578 privacy = "full";
6579 screen = "no";
6580 break;
6581 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
6582 privacy = "full";
6583 screen = "yes";
6584 break;
6585 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
6586 privacy = "full";
6587 screen = "no";
6588 break;
6589 case AST_PRES_PROHIB_NETWORK_NUMBER:
6590 privacy = "full";
6591 screen = "yes";
6592 break;
6593 case AST_PRES_NUMBER_NOT_AVAILABLE:
6594 send_pres_tags = FALSE;
6595 break;
6596 default:
6597 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
6598 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
6599 privacy = "full";
6600 else
6601 privacy = "off";
6602 screen = "no";
6603 break;
6606 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip));
6608 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
6609 if (send_pres_tags)
6610 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
6611 ast_string_field_set(p, rpid, buf);
6613 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
6614 S_OR(p->fromuser, clid),
6615 fromdomain, p->tag);
6618 /*! \brief Initiate new SIP request to peer/user */
6619 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
6621 char invite_buf[256] = "";
6622 char *invite = invite_buf;
6623 size_t invite_max = sizeof(invite_buf);
6624 char from[256];
6625 char to[256];
6626 char tmp[BUFSIZ/2];
6627 char tmp2[BUFSIZ/2];
6628 const char *l = NULL, *n = NULL;
6629 const char *urioptions = "";
6631 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
6632 const char *s = p->username; /* being a string field, cannot be NULL */
6634 /* Test p->username against allowed characters in AST_DIGIT_ANY
6635 If it matches the allowed characters list, then sipuser = ";user=phone"
6636 If not, then sipuser = ""
6638 /* + is allowed in first position in a tel: uri */
6639 if (*s == '+')
6640 s++;
6641 for (; *s; s++) {
6642 if (!strchr(AST_DIGIT_ANYNUM, *s) )
6643 break;
6645 /* If we have only digits, add ;user=phone to the uri */
6646 if (*s)
6647 urioptions = ";user=phone";
6651 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
6653 if (p->owner) {
6654 l = p->owner->cid.cid_num;
6655 n = p->owner->cid.cid_name;
6657 /* if we are not sending RPID and user wants his callerid restricted */
6658 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
6659 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
6660 l = CALLERID_UNKNOWN;
6661 n = l;
6663 if (ast_strlen_zero(l))
6664 l = default_callerid;
6665 if (ast_strlen_zero(n))
6666 n = l;
6667 /* Allow user to be overridden */
6668 if (!ast_strlen_zero(p->fromuser))
6669 l = p->fromuser;
6670 else /* Save for any further attempts */
6671 ast_string_field_set(p, fromuser, l);
6673 /* Allow user to be overridden */
6674 if (!ast_strlen_zero(p->fromname))
6675 n = p->fromname;
6676 else /* Save for any further attempts */
6677 ast_string_field_set(p, fromname, n);
6679 if (pedanticsipchecking) {
6680 ast_uri_encode(n, tmp, sizeof(tmp), 0);
6681 n = tmp;
6682 ast_uri_encode(l, tmp2, sizeof(tmp2), 0);
6683 l = tmp2;
6686 if (ourport != STANDARD_SIP_PORT && ast_strlen_zero(p->fromdomain))
6687 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);
6688 else
6689 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)), p->tag);
6691 /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
6692 if (!ast_strlen_zero(p->fullcontact)) {
6693 /* If we have full contact, trust it */
6694 ast_build_string(&invite, &invite_max, "%s", p->fullcontact);
6695 } else {
6696 /* Otherwise, use the username while waiting for registration */
6697 ast_build_string(&invite, &invite_max, "sip:");
6698 if (!ast_strlen_zero(p->username)) {
6699 n = p->username;
6700 if (pedanticsipchecking) {
6701 ast_uri_encode(n, tmp, sizeof(tmp), 0);
6702 n = tmp;
6704 ast_build_string(&invite, &invite_max, "%s@", n);
6706 ast_build_string(&invite, &invite_max, "%s", p->tohost);
6707 if (ntohs(p->sa.sin_port) != STANDARD_SIP_PORT)
6708 ast_build_string(&invite, &invite_max, ":%d", ntohs(p->sa.sin_port));
6709 ast_build_string(&invite, &invite_max, "%s", urioptions);
6712 /* If custom URI options have been provided, append them */
6713 if (p->options && p->options->uri_options)
6714 ast_build_string(&invite, &invite_max, ";%s", p->options->uri_options);
6716 ast_string_field_set(p, uri, invite_buf);
6718 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
6719 /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
6720 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", p->uri, p->theirtag);
6721 } else if (p->options && p->options->vxml_url) {
6722 /* If there is a VXML URL append it to the SIP URL */
6723 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
6724 } else
6725 snprintf(to, sizeof(to), "<%s>", p->uri);
6727 init_req(req, sipmethod, p->uri);
6728 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
6730 add_header(req, "Via", p->via);
6731 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
6732 * OTOH, then we won't have anything in p->route anyway */
6733 /* Build Remote Party-ID and From */
6734 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
6735 build_rpid(p);
6736 add_header(req, "From", p->rpid_from);
6737 } else
6738 add_header(req, "From", from);
6739 add_header(req, "To", to);
6740 ast_string_field_set(p, exten, l);
6741 build_contact(p);
6742 add_header(req, "Contact", p->our_contact);
6743 add_header(req, "Call-ID", p->callid);
6744 add_header(req, "CSeq", tmp);
6745 add_header(req, "User-Agent", global_useragent);
6746 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
6747 if (!ast_strlen_zero(p->rpid))
6748 add_header(req, "Remote-Party-ID", p->rpid);
6751 /*! \brief Build REFER/INVITE/OPTIONS message and transmit it */
6752 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
6754 struct sip_request req;
6756 req.method = sipmethod;
6757 if (init) { /* Seems like init always is 2 */
6758 /* Bump branch even on initial requests */
6759 p->branch ^= ast_random();
6760 build_via(p);
6761 if (init > 1)
6762 initreqprep(&req, p, sipmethod);
6763 else
6764 reqprep(&req, p, sipmethod, 0, 1);
6765 } else
6766 reqprep(&req, p, sipmethod, 0, 1);
6768 if (p->options && p->options->auth)
6769 add_header(&req, p->options->authheader, p->options->auth);
6770 append_date(&req);
6771 if (sipmethod == SIP_REFER) { /* Call transfer */
6772 if (p->refer) {
6773 char buf[BUFSIZ];
6774 if (!ast_strlen_zero(p->refer->refer_to))
6775 add_header(&req, "Refer-To", p->refer->refer_to);
6776 if (!ast_strlen_zero(p->refer->referred_by)) {
6777 sprintf(buf, "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
6778 add_header(&req, "Referred-By", buf);
6782 /* This new INVITE is part of an attended transfer. Make sure that the
6783 other end knows and replace the current call with this new call */
6784 if (p->options && p->options->replaces && !ast_strlen_zero(p->options->replaces)) {
6785 add_header(&req, "Replaces", p->options->replaces);
6786 add_header(&req, "Require", "replaces");
6789 add_header(&req, "Allow", ALLOWED_METHODS);
6790 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6791 if (p->options && p->options->addsipheaders && p->owner) {
6792 struct ast_channel *ast = p->owner; /* The owner channel */
6793 struct varshead *headp = &ast->varshead;
6795 if (!headp)
6796 ast_log(LOG_WARNING,"No Headp for the channel...ooops!\n");
6797 else {
6798 const struct ast_var_t *current;
6799 AST_LIST_TRAVERSE(headp, current, entries) {
6800 /* SIPADDHEADER: Add SIP header to outgoing call */
6801 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
6802 char *content, *end;
6803 const char *header = ast_var_value(current);
6804 char *headdup = ast_strdupa(header);
6806 /* Strip of the starting " (if it's there) */
6807 if (*headdup == '"')
6808 headdup++;
6809 if ((content = strchr(headdup, ':'))) {
6810 *content++ = '\0';
6811 content = ast_skip_blanks(content); /* Skip white space */
6812 /* Strip the ending " (if it's there) */
6813 end = content + strlen(content) -1;
6814 if (*end == '"')
6815 *end = '\0';
6817 add_header(&req, headdup, content);
6818 if (sipdebug)
6819 ast_log(LOG_DEBUG, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
6825 if (sdp) {
6826 if (p->udptl && p->t38.state == T38_LOCAL_DIRECT) {
6827 ast_udptl_offered_from_local(p->udptl, 1);
6828 if (option_debug)
6829 ast_log(LOG_DEBUG, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
6830 add_t38_sdp(&req, p);
6831 } else if (p->rtp)
6832 add_sdp(&req, p);
6833 } else {
6834 add_header_contentLength(&req, 0);
6837 if (!p->initreq.headers)
6838 initialize_initreq(p, &req);
6839 p->lastinvite = p->ocseq;
6840 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
6843 /*! \brief Used in the SUBSCRIBE notification subsystem */
6844 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
6846 char tmp[4000], from[256], to[256];
6847 char *t = tmp, *c, *mfrom, *mto;
6848 size_t maxbytes = sizeof(tmp);
6849 struct sip_request req;
6850 char hint[AST_MAX_EXTENSION];
6851 char *statestring = "terminated";
6852 const struct cfsubscription_types *subscriptiontype;
6853 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
6854 char *pidfstate = "--";
6855 char *pidfnote= "Ready";
6857 memset(from, 0, sizeof(from));
6858 memset(to, 0, sizeof(to));
6859 memset(tmp, 0, sizeof(tmp));
6861 switch (state) {
6862 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
6863 statestring = (global_notifyringing) ? "early" : "confirmed";
6864 local_state = NOTIFY_INUSE;
6865 pidfstate = "busy";
6866 pidfnote = "Ringing";
6867 break;
6868 case AST_EXTENSION_RINGING:
6869 statestring = "early";
6870 local_state = NOTIFY_INUSE;
6871 pidfstate = "busy";
6872 pidfnote = "Ringing";
6873 break;
6874 case AST_EXTENSION_INUSE:
6875 statestring = "confirmed";
6876 local_state = NOTIFY_INUSE;
6877 pidfstate = "busy";
6878 pidfnote = "On the phone";
6879 break;
6880 case AST_EXTENSION_BUSY:
6881 statestring = "confirmed";
6882 local_state = NOTIFY_CLOSED;
6883 pidfstate = "busy";
6884 pidfnote = "On the phone";
6885 break;
6886 case AST_EXTENSION_UNAVAILABLE:
6887 statestring = "terminated";
6888 local_state = NOTIFY_CLOSED;
6889 pidfstate = "away";
6890 pidfnote = "Unavailable";
6891 break;
6892 case AST_EXTENSION_ONHOLD:
6893 statestring = "confirmed";
6894 local_state = NOTIFY_INUSE;
6895 pidfstate = "busy";
6896 pidfnote = "On Hold";
6897 break;
6898 case AST_EXTENSION_NOT_INUSE:
6899 default:
6900 /* Default setting */
6901 break;
6904 subscriptiontype = find_subscription_type(p->subscribed);
6906 /* Check which device/devices we are watching and if they are registered */
6907 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
6908 /* If they are not registered, we will override notification and show no availability */
6909 if (ast_device_state(hint) == AST_DEVICE_UNAVAILABLE) {
6910 local_state = NOTIFY_CLOSED;
6911 pidfstate = "away";
6912 pidfnote = "Not online";
6916 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
6917 c = get_in_brackets(from);
6918 if (strncmp(c, "sip:", 4)) {
6919 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
6920 return -1;
6922 mfrom = strsep(&c, ";"); /* trim ; and beyond */
6924 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
6925 c = get_in_brackets(to);
6926 if (strncmp(c, "sip:", 4)) {
6927 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
6928 return -1;
6930 mto = strsep(&c, ";"); /* trim ; and beyond */
6932 reqprep(&req, p, SIP_NOTIFY, 0, 1);
6935 add_header(&req, "Event", subscriptiontype->event);
6936 add_header(&req, "Content-Type", subscriptiontype->mediatype);
6937 switch(state) {
6938 case AST_EXTENSION_DEACTIVATED:
6939 if (timeout)
6940 add_header(&req, "Subscription-State", "terminated;reason=timeout");
6941 else {
6942 add_header(&req, "Subscription-State", "terminated;reason=probation");
6943 add_header(&req, "Retry-After", "60");
6945 break;
6946 case AST_EXTENSION_REMOVED:
6947 add_header(&req, "Subscription-State", "terminated;reason=noresource");
6948 break;
6949 default:
6950 if (p->expiry)
6951 add_header(&req, "Subscription-State", "active");
6952 else /* Expired */
6953 add_header(&req, "Subscription-State", "terminated;reason=timeout");
6955 switch (p->subscribed) {
6956 case XPIDF_XML:
6957 case CPIM_PIDF_XML:
6958 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
6959 ast_build_string(&t, &maxbytes, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
6960 ast_build_string(&t, &maxbytes, "<presence>\n");
6961 ast_build_string(&t, &maxbytes, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
6962 ast_build_string(&t, &maxbytes, "<atom id=\"%s\">\n", p->exten);
6963 ast_build_string(&t, &maxbytes, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
6964 ast_build_string(&t, &maxbytes, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
6965 ast_build_string(&t, &maxbytes, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
6966 ast_build_string(&t, &maxbytes, "</address>\n</atom>\n</presence>\n");
6967 break;
6968 case PIDF_XML: /* Eyebeam supports this format */
6969 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
6970 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);
6971 ast_build_string(&t, &maxbytes, "<pp:person><status>\n");
6972 if (pidfstate[0] != '-')
6973 ast_build_string(&t, &maxbytes, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
6974 ast_build_string(&t, &maxbytes, "</status></pp:person>\n");
6975 ast_build_string(&t, &maxbytes, "<note>%s</note>\n", pidfnote); /* Note */
6976 ast_build_string(&t, &maxbytes, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
6977 ast_build_string(&t, &maxbytes, "<contact priority=\"1\">%s</contact>\n", mto);
6978 if (pidfstate[0] == 'b') /* Busy? Still open ... */
6979 ast_build_string(&t, &maxbytes, "<status><basic>open</basic></status>\n");
6980 else
6981 ast_build_string(&t, &maxbytes, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
6982 ast_build_string(&t, &maxbytes, "</tuple>\n</presence>\n");
6983 break;
6984 case DIALOG_INFO_XML: /* SNOM subscribes in this format */
6985 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
6986 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);
6987 if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
6988 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
6989 else
6990 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\">\n", p->exten);
6991 ast_build_string(&t, &maxbytes, "<state>%s</state>\n", statestring);
6992 if (state == AST_EXTENSION_ONHOLD) {
6993 ast_build_string(&t, &maxbytes, "<local>\n<target uri=\"%s\">\n"
6994 "<param pname=\"+sip.rendering\" pvalue=\"no\">\n"
6995 "</target>\n</local>\n", mto);
6997 ast_build_string(&t, &maxbytes, "</dialog>\n</dialog-info>\n");
6998 break;
6999 case NONE:
7000 default:
7001 break;
7004 if (t > tmp + sizeof(tmp))
7005 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
7007 add_header_contentLength(&req, strlen(tmp));
7008 add_line(&req, tmp);
7010 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7013 /*! \brief Notify user of messages waiting in voicemail
7014 \note - Notification only works for registered peers with mailbox= definitions
7015 in sip.conf
7016 - We use the SIP Event package message-summary
7017 MIME type defaults to "application/simple-message-summary";
7019 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
7021 struct sip_request req;
7022 char tmp[500];
7023 char *t = tmp;
7024 size_t maxbytes = sizeof(tmp);
7026 initreqprep(&req, p, SIP_NOTIFY);
7027 add_header(&req, "Event", "message-summary");
7028 add_header(&req, "Content-Type", default_notifymime);
7030 ast_build_string(&t, &maxbytes, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
7031 ast_build_string(&t, &maxbytes, "Message-Account: sip:%s@%s\r\n",
7032 S_OR(vmexten, default_vmexten), S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)));
7033 /* Cisco has a bug in the SIP stack where it can't accept the
7034 (0/0) notification. This can temporarily be disabled in
7035 sip.conf with the "buggymwi" option */
7036 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)"));
7038 if (p->subscribed) {
7039 if (p->expiry)
7040 add_header(&req, "Subscription-State", "active");
7041 else /* Expired */
7042 add_header(&req, "Subscription-State", "terminated;reason=timeout");
7045 if (t > tmp + sizeof(tmp))
7046 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
7048 add_header_contentLength(&req, strlen(tmp));
7049 add_line(&req, tmp);
7051 if (!p->initreq.headers)
7052 initialize_initreq(p, &req);
7053 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7056 /*! \brief Transmit SIP request unreliably (only used in sip_notify subsystem) */
7057 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req)
7059 if (!p->initreq.headers) /* Initialize first request before sending */
7060 initialize_initreq(p, req);
7061 return send_request(p, req, XMIT_UNRELIABLE, p->ocseq);
7064 /*! \brief Notify a transferring party of the status of transfer */
7065 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
7067 struct sip_request req;
7068 char tmp[BUFSIZ/2];
7070 reqprep(&req, p, SIP_NOTIFY, 0, 1);
7071 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
7072 add_header(&req, "Event", tmp);
7073 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
7074 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
7075 add_header(&req, "Allow", ALLOWED_METHODS);
7076 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7078 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
7079 add_header_contentLength(&req, strlen(tmp));
7080 add_line(&req, tmp);
7082 if (!p->initreq.headers)
7083 initialize_initreq(p, &req);
7085 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7088 /*! \brief Convert registration state status to string */
7089 static char *regstate2str(enum sipregistrystate regstate)
7091 switch(regstate) {
7092 case REG_STATE_FAILED:
7093 return "Failed";
7094 case REG_STATE_UNREGISTERED:
7095 return "Unregistered";
7096 case REG_STATE_REGSENT:
7097 return "Request Sent";
7098 case REG_STATE_AUTHSENT:
7099 return "Auth. Sent";
7100 case REG_STATE_REGISTERED:
7101 return "Registered";
7102 case REG_STATE_REJECTED:
7103 return "Rejected";
7104 case REG_STATE_TIMEOUT:
7105 return "Timeout";
7106 case REG_STATE_NOAUTH:
7107 return "No Authentication";
7108 default:
7109 return "Unknown";
7113 /*! \brief Update registration with SIP Proxy */
7114 static int sip_reregister(void *data)
7116 /* if we are here, we know that we need to reregister. */
7117 struct sip_registry *r= ASTOBJ_REF((struct sip_registry *) data);
7119 /* if we couldn't get a reference to the registry object, punt */
7120 if (!r)
7121 return 0;
7123 if (r->call && !ast_test_flag(&r->call->flags[0], SIP_NO_HISTORY))
7124 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
7125 /* Since registry's are only added/removed by the the monitor thread, this
7126 may be overkill to reference/dereference at all here */
7127 if (sipdebug)
7128 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
7130 r->expire = -1;
7131 __sip_do_register(r);
7132 ASTOBJ_UNREF(r, sip_registry_destroy);
7133 return 0;
7136 /*! \brief Register with SIP proxy */
7137 static int __sip_do_register(struct sip_registry *r)
7139 int res;
7141 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
7142 return res;
7145 /*! \brief Registration timeout, register again */
7146 static int sip_reg_timeout(void *data)
7149 /* if we are here, our registration timed out, so we'll just do it over */
7150 struct sip_registry *r = ASTOBJ_REF((struct sip_registry *) data);
7151 struct sip_pvt *p;
7152 int res;
7154 /* if we couldn't get a reference to the registry object, punt */
7155 if (!r)
7156 return 0;
7158 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
7159 if (r->call) {
7160 /* Unlink us, destroy old call. Locking is not relevant here because all this happens
7161 in the single SIP manager thread. */
7162 p = r->call;
7163 if (p->registry)
7164 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
7165 r->call = NULL;
7166 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
7167 /* Pretend to ACK anything just in case */
7168 __sip_pretend_ack(p); /* XXX we need p locked, not sure we have */
7170 /* If we have a limit, stop registration and give up */
7171 if (global_regattempts_max && (r->regattempts > global_regattempts_max)) {
7172 /* Ok, enough is enough. Don't try any more */
7173 /* We could add an external notification here...
7174 steal it from app_voicemail :-) */
7175 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
7176 r->regstate = REG_STATE_FAILED;
7177 } else {
7178 r->regstate = REG_STATE_UNREGISTERED;
7179 r->timeout = -1;
7180 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
7182 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));
7183 ASTOBJ_UNREF(r, sip_registry_destroy);
7184 return 0;
7187 /*! \brief Transmit register to SIP proxy or UA */
7188 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
7190 struct sip_request req;
7191 char from[256];
7192 char to[256];
7193 char tmp[80];
7194 char addr[80];
7195 struct sip_pvt *p;
7197 /* exit if we are already in process with this registrar ?*/
7198 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
7199 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
7200 return 0;
7203 if (r->call) { /* We have a registration */
7204 if (!auth) {
7205 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
7206 return 0;
7207 } else {
7208 p = r->call;
7209 make_our_tag(p->tag, sizeof(p->tag)); /* create a new local tag for every register attempt */
7210 ast_string_field_free(p, theirtag); /* forget their old tag, so we don't match tags when getting response */
7212 } else {
7213 /* Build callid for registration if we haven't registered before */
7214 if (!r->callid_valid) {
7215 build_callid_registry(r, __ourip, default_fromdomain);
7216 r->callid_valid = TRUE;
7218 /* Allocate SIP packet for registration */
7219 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER))) {
7220 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
7221 return 0;
7223 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
7224 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
7225 /* Find address to hostname */
7226 if (create_addr(p, r->hostname)) {
7227 /* we have what we hope is a temporary network error,
7228 * probably DNS. We need to reschedule a registration try */
7229 sip_destroy(p);
7230 if (r->timeout > -1) {
7231 ast_sched_del(sched, r->timeout);
7232 r->timeout = ast_sched_add(sched, global_reg_timeout*1000, sip_reg_timeout, r);
7233 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
7234 } else {
7235 r->timeout = ast_sched_add(sched, global_reg_timeout*1000, sip_reg_timeout, r);
7236 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);
7238 r->regattempts++;
7239 return 0;
7241 /* Copy back Call-ID in case create_addr changed it */
7242 ast_string_field_set(r, callid, p->callid);
7243 if (r->portno)
7244 p->sa.sin_port = htons(r->portno);
7245 else /* Set registry port to the port set from the peer definition/srv or default */
7246 r->portno = ntohs(p->sa.sin_port);
7247 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
7248 r->call=p; /* Save pointer to SIP packet */
7249 p->registry = ASTOBJ_REF(r); /* Add pointer to registry in packet */
7250 if (!ast_strlen_zero(r->secret)) /* Secret (password) */
7251 ast_string_field_set(p, peersecret, r->secret);
7252 if (!ast_strlen_zero(r->md5secret))
7253 ast_string_field_set(p, peermd5secret, r->md5secret);
7254 /* User name in this realm
7255 - if authuser is set, use that, otherwise use username */
7256 if (!ast_strlen_zero(r->authuser)) {
7257 ast_string_field_set(p, peername, r->authuser);
7258 ast_string_field_set(p, authname, r->authuser);
7259 } else if (!ast_strlen_zero(r->username)) {
7260 ast_string_field_set(p, peername, r->username);
7261 ast_string_field_set(p, authname, r->username);
7262 ast_string_field_set(p, fromuser, r->username);
7264 if (!ast_strlen_zero(r->username))
7265 ast_string_field_set(p, username, r->username);
7266 /* Save extension in packet */
7267 ast_string_field_set(p, exten, r->contact);
7270 check which address we should use in our contact header
7271 based on whether the remote host is on the external or
7272 internal network so we can register through nat
7274 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
7275 p->ourip = bindaddr.sin_addr;
7276 build_contact(p);
7279 /* set up a timeout */
7280 if (auth == NULL) {
7281 if (r->timeout > -1) {
7282 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
7283 ast_sched_del(sched, r->timeout);
7285 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
7286 if (option_debug)
7287 ast_log(LOG_DEBUG, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
7290 if (strchr(r->username, '@')) {
7291 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
7292 if (!ast_strlen_zero(p->theirtag))
7293 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
7294 else
7295 snprintf(to, sizeof(to), "<sip:%s>", r->username);
7296 } else {
7297 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
7298 if (!ast_strlen_zero(p->theirtag))
7299 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
7300 else
7301 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
7304 /* Fromdomain is what we are registering to, regardless of actual
7305 host name from SRV */
7306 snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain, r->hostname));
7307 ast_string_field_set(p, uri, addr);
7309 p->branch ^= ast_random();
7311 init_req(&req, sipmethod, addr);
7313 /* Add to CSEQ */
7314 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
7315 p->ocseq = r->ocseq;
7317 build_via(p);
7318 add_header(&req, "Via", p->via);
7319 add_header(&req, "From", from);
7320 add_header(&req, "To", to);
7321 add_header(&req, "Call-ID", p->callid);
7322 add_header(&req, "CSeq", tmp);
7323 add_header(&req, "User-Agent", global_useragent);
7324 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
7327 if (auth) /* Add auth header */
7328 add_header(&req, authheader, auth);
7329 else if (!ast_strlen_zero(r->nonce)) {
7330 char digest[1024];
7332 /* We have auth data to reuse, build a digest header! */
7333 if (sipdebug)
7334 ast_log(LOG_DEBUG, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
7335 ast_string_field_set(p, realm, r->realm);
7336 ast_string_field_set(p, nonce, r->nonce);
7337 ast_string_field_set(p, domain, r->domain);
7338 ast_string_field_set(p, opaque, r->opaque);
7339 ast_string_field_set(p, qop, r->qop);
7340 r->noncecount++;
7341 p->noncecount = r->noncecount;
7343 memset(digest,0,sizeof(digest));
7344 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
7345 add_header(&req, "Authorization", digest);
7346 else
7347 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
7351 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
7352 add_header(&req, "Expires", tmp);
7353 add_header(&req, "Contact", p->our_contact);
7354 add_header(&req, "Event", "registration");
7355 add_header_contentLength(&req, 0);
7357 initialize_initreq(p, &req);
7358 if (sip_debug_test_pvt(p))
7359 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
7360 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
7361 r->regattempts++; /* Another attempt */
7362 if (option_debug > 3)
7363 ast_verbose("REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
7364 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
7367 /*! \brief Transmit text with SIP MESSAGE method */
7368 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
7370 struct sip_request req;
7372 reqprep(&req, p, SIP_MESSAGE, 0, 1);
7373 add_text(&req, text);
7374 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7377 /*! \brief Allocate SIP refer structure */
7378 static int sip_refer_allocate(struct sip_pvt *p)
7380 p->refer = ast_calloc(1, sizeof(struct sip_refer));
7381 return p->refer ? 1 : 0;
7384 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
7385 \note this is currently broken as we have no way of telling the dialplan
7386 engine whether a transfer succeeds or fails.
7387 \todo Fix the transfer() dialplan function so that a transfer may fail
7389 static int transmit_refer(struct sip_pvt *p, const char *dest)
7391 struct sip_request req = {
7392 .headers = 0,
7394 char from[256];
7395 const char *of;
7396 char *c;
7397 char referto[256];
7398 char *ttag, *ftag;
7399 char *theirtag = ast_strdupa(p->theirtag);
7401 if (option_debug || sipdebug)
7402 ast_log(LOG_DEBUG, "SIP transfer of %s to %s\n", p->callid, dest);
7404 /* Are we transfering an inbound or outbound call ? */
7405 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
7406 of = get_header(&p->initreq, "To");
7407 ttag = theirtag;
7408 ftag = p->tag;
7409 } else {
7410 of = get_header(&p->initreq, "From");
7411 ftag = theirtag;
7412 ttag = p->tag;
7415 ast_copy_string(from, of, sizeof(from));
7416 of = get_in_brackets(from);
7417 ast_string_field_set(p, from, of);
7418 if (strncmp(of, "sip:", 4))
7419 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
7420 else
7421 of += 4;
7422 /* Get just the username part */
7423 if ((c = strchr(dest, '@')))
7424 c = NULL;
7425 else if ((c = strchr(of, '@')))
7426 *c++ = '\0';
7427 if (c)
7428 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
7429 else
7430 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
7432 /* save in case we get 407 challenge */
7433 sip_refer_allocate(p);
7434 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
7435 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
7436 p->refer->status = REFER_SENT; /* Set refer status */
7438 reqprep(&req, p, SIP_REFER, 0, 1);
7439 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
7441 add_header(&req, "Refer-To", referto);
7442 add_header(&req, "Allow", ALLOWED_METHODS);
7443 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7444 if (!ast_strlen_zero(p->our_contact))
7445 add_header(&req, "Referred-By", p->our_contact);
7447 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7448 /* We should propably wait for a NOTIFY here until we ack the transfer */
7449 /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
7451 /*! \todo In theory, we should hang around and wait for a reply, before
7452 returning to the dial plan here. Don't know really how that would
7453 affect the transfer() app or the pbx, but, well, to make this
7454 useful we should have a STATUS code on transfer().
7459 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
7460 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
7462 struct sip_request req;
7464 reqprep(&req, p, SIP_INFO, 0, 1);
7465 add_digit(&req, digit, duration);
7466 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7469 /*! \brief Send SIP INFO with video update request */
7470 static int transmit_info_with_vidupdate(struct sip_pvt *p)
7472 struct sip_request req;
7474 reqprep(&req, p, SIP_INFO, 0, 1);
7475 add_vidupdate(&req);
7476 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7479 /*! \brief Transmit generic SIP request */
7480 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
7482 struct sip_request resp;
7484 if (sipmethod == SIP_ACK)
7485 p->invitestate = INV_CONFIRMED;
7487 reqprep(&resp, p, sipmethod, seqno, newbranch);
7488 add_header_contentLength(&resp, 0);
7489 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
7492 /*! \brief Transmit SIP request, auth added */
7493 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
7495 struct sip_request resp;
7497 reqprep(&resp, p, sipmethod, seqno, newbranch);
7498 if (!ast_strlen_zero(p->realm)) {
7499 char digest[1024];
7501 memset(digest, 0, sizeof(digest));
7502 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
7503 if (p->options && p->options->auth_type == PROXY_AUTH)
7504 add_header(&resp, "Proxy-Authorization", digest);
7505 else if (p->options && p->options->auth_type == WWW_AUTH)
7506 add_header(&resp, "Authorization", digest);
7507 else /* Default, to be backwards compatible (maybe being too careful, but leaving it for now) */
7508 add_header(&resp, "Proxy-Authorization", digest);
7509 } else
7510 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
7512 /* If we are hanging up and know a cause for that, send it in clear text to make
7513 debugging easier. */
7514 if (sipmethod == SIP_BYE && p->owner && p->owner->hangupcause) {
7515 char buf[10];
7517 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
7518 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
7519 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
7522 add_header_contentLength(&resp, 0);
7523 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
7526 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
7527 static void destroy_association(struct sip_peer *peer)
7529 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE)) {
7530 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
7531 ast_update_realtime("sippeers", "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "username", "", "regserver", "", NULL);
7532 else
7533 ast_db_del("SIP/Registry", peer->name);
7537 /*! \brief Expire registration of SIP peer */
7538 static int expire_register(void *data)
7540 struct sip_peer *peer = data;
7542 if (!peer) /* Hmmm. We have no peer. Weird. */
7543 return 0;
7545 memset(&peer->addr, 0, sizeof(peer->addr));
7547 destroy_association(peer); /* remove registration data from storage */
7549 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
7550 register_peer_exten(peer, FALSE); /* Remove regexten */
7551 peer->expire = -1;
7552 ast_device_state_changed("SIP/%s", peer->name);
7554 /* Do we need to release this peer from memory?
7555 Only for realtime peers and autocreated peers
7557 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT) ||
7558 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
7559 peer = ASTOBJ_CONTAINER_UNLINK(&peerl, peer); /* Remove from peer list */
7560 ASTOBJ_UNREF(peer, sip_destroy_peer); /* Remove from memory */
7563 return 0;
7566 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
7567 static int sip_poke_peer_s(void *data)
7569 struct sip_peer *peer = data;
7571 peer->pokeexpire = -1;
7572 sip_poke_peer(peer);
7573 return 0;
7576 /*! \brief Get registration details from Asterisk DB */
7577 static void reg_source_db(struct sip_peer *peer)
7579 char data[256];
7580 struct in_addr in;
7581 int expiry;
7582 int port;
7583 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
7585 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
7586 return;
7587 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
7588 return;
7590 scan = data;
7591 addr = strsep(&scan, ":");
7592 port_str = strsep(&scan, ":");
7593 expiry_str = strsep(&scan, ":");
7594 username = strsep(&scan, ":");
7595 contact = scan; /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
7597 if (!inet_aton(addr, &in))
7598 return;
7600 if (port_str)
7601 port = atoi(port_str);
7602 else
7603 return;
7605 if (expiry_str)
7606 expiry = atoi(expiry_str);
7607 else
7608 return;
7610 if (username)
7611 ast_copy_string(peer->username, username, sizeof(peer->username));
7612 if (contact)
7613 ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
7615 if (option_debug > 1)
7616 ast_log(LOG_DEBUG, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
7617 peer->name, peer->username, ast_inet_ntoa(in), port, expiry);
7619 memset(&peer->addr, 0, sizeof(peer->addr));
7620 peer->addr.sin_family = AF_INET;
7621 peer->addr.sin_addr = in;
7622 peer->addr.sin_port = htons(port);
7623 if (sipsock < 0) {
7624 /* SIP isn't up yet, so schedule a poke only, pretty soon */
7625 if (peer->pokeexpire > -1)
7626 ast_sched_del(sched, peer->pokeexpire);
7627 peer->pokeexpire = ast_sched_add(sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer);
7628 } else
7629 sip_poke_peer(peer);
7630 if (peer->expire > -1)
7631 ast_sched_del(sched, peer->expire);
7632 peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, peer);
7633 register_peer_exten(peer, TRUE);
7636 /*! \brief Save contact header for 200 OK on INVITE */
7637 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
7639 char contact[250];
7640 char *c;
7642 /* Look for brackets */
7643 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
7644 c = get_in_brackets(contact);
7646 /* Save full contact to call pvt for later bye or re-invite */
7647 ast_string_field_set(pvt, fullcontact, c);
7649 /* Save URI for later ACKs, BYE or RE-invites */
7650 ast_string_field_set(pvt, okcontacturi, c);
7652 /* We should return false for URI:s we can't handle,
7653 like sips:, tel:, mailto:,ldap: etc */
7654 return TRUE;
7657 /*! \brief Change the other partys IP address based on given contact */
7658 static int set_address_from_contact(struct sip_pvt *pvt)
7660 struct hostent *hp;
7661 struct ast_hostent ahp;
7662 int port;
7663 char *c, *host, *pt;
7664 char *contact;
7667 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
7668 /* NAT: Don't trust the contact field. Just use what they came to us
7669 with. */
7670 pvt->sa = pvt->recv;
7671 return 0;
7675 /* Work on a copy */
7676 contact = ast_strdupa(pvt->fullcontact);
7678 /* XXX this code is repeated all over */
7679 /* Make sure it's a SIP URL */
7680 if (strncasecmp(contact, "sip:", 4)) {
7681 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
7682 } else
7683 contact += 4;
7685 /* Ditch arguments */
7686 /* XXX this code is replicated also shortly below */
7687 contact = strsep(&contact, ";"); /* trim ; and beyond */
7689 /* Grab host */
7690 host = strchr(contact, '@');
7691 if (!host) { /* No username part */
7692 host = contact;
7693 c = NULL;
7694 } else {
7695 *host++ = '\0';
7697 pt = strchr(host, ':');
7698 if (pt) {
7699 *pt++ = '\0';
7700 port = atoi(pt);
7701 } else
7702 port = STANDARD_SIP_PORT;
7704 /* XXX This could block for a long time XXX */
7705 /* We should only do this if it's a name, not an IP */
7706 hp = ast_gethostbyname(host, &ahp);
7707 if (!hp) {
7708 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
7709 return -1;
7711 pvt->sa.sin_family = AF_INET;
7712 memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
7713 pvt->sa.sin_port = htons(port);
7715 return 0;
7719 /*! \brief Parse contact header and save registration (peer registration) */
7720 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
7722 char contact[BUFSIZ];
7723 char data[BUFSIZ];
7724 const char *expires = get_header(req, "Expires");
7725 int expiry = atoi(expires);
7726 char *curi, *n, *pt;
7727 int port;
7728 const char *useragent;
7729 struct hostent *hp;
7730 struct ast_hostent ahp;
7731 struct sockaddr_in oldsin;
7733 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
7735 if (ast_strlen_zero(expires)) { /* No expires header */
7736 expires = strcasestr(contact, ";expires=");
7737 if (expires) {
7738 /* XXX bug here, we overwrite the string */
7739 expires = strsep((char **) &expires, ";"); /* trim ; and beyond */
7740 if (sscanf(expires + 9, "%d", &expiry) != 1)
7741 expiry = default_expiry;
7742 } else {
7743 /* Nothing has been specified */
7744 expiry = default_expiry;
7748 /* Look for brackets */
7749 curi = contact;
7750 if (strchr(contact, '<') == NULL) /* No <, check for ; and strip it */
7751 strsep(&curi, ";"); /* This is Header options, not URI options */
7752 curi = get_in_brackets(contact);
7754 /* if they did not specify Contact: or Expires:, they are querying
7755 what we currently have stored as their contact address, so return
7758 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
7759 /* If we have an active registration, tell them when the registration is going to expire */
7760 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
7761 pvt->expiry = ast_sched_when(sched, peer->expire);
7762 return PARSE_REGISTER_QUERY;
7763 } else if (!strcasecmp(curi, "*") || !expiry) { /* Unregister this peer */
7764 /* This means remove all registrations and return OK */
7765 memset(&peer->addr, 0, sizeof(peer->addr));
7766 if (peer->expire > -1)
7767 ast_sched_del(sched, peer->expire);
7768 peer->expire = -1;
7770 destroy_association(peer);
7772 register_peer_exten(peer, 0); /* Add extension from regexten= setting in sip.conf */
7773 peer->fullcontact[0] = '\0';
7774 peer->useragent[0] = '\0';
7775 peer->sipoptions = 0;
7776 peer->lastms = 0;
7778 if (option_verbose > 2)
7779 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", peer->name);
7780 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
7781 return PARSE_REGISTER_UPDATE;
7784 /* Store whatever we got as a contact from the client */
7785 ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));
7787 /* For the 200 OK, we should use the received contact */
7788 ast_string_field_build(pvt, our_contact, "<%s>", curi);
7790 /* Make sure it's a SIP URL */
7791 if (strncasecmp(curi, "sip:", 4)) {
7792 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", curi);
7793 } else
7794 curi += 4;
7795 /* Ditch q */
7796 curi = strsep(&curi, ";");
7797 /* Grab host */
7798 n = strchr(curi, '@');
7799 if (!n) {
7800 n = curi;
7801 curi = NULL;
7802 } else
7803 *n++ = '\0';
7804 pt = strchr(n, ':');
7805 if (pt) {
7806 *pt++ = '\0';
7807 port = atoi(pt);
7808 } else
7809 port = STANDARD_SIP_PORT;
7810 oldsin = peer->addr;
7811 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
7812 /* XXX This could block for a long time XXX */
7813 hp = ast_gethostbyname(n, &ahp);
7814 if (!hp) {
7815 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
7816 return PARSE_REGISTER_FAILED;
7818 peer->addr.sin_family = AF_INET;
7819 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
7820 peer->addr.sin_port = htons(port);
7821 } else {
7822 /* Don't trust the contact field. Just use what they came to us
7823 with */
7824 peer->addr = pvt->recv;
7827 /* Save SIP options profile */
7828 peer->sipoptions = pvt->sipoptions;
7830 if (curi) /* Overwrite the default username from config at registration */
7831 ast_copy_string(peer->username, curi, sizeof(peer->username));
7832 else
7833 peer->username[0] = '\0';
7835 if (peer->expire > -1) {
7836 ast_sched_del(sched, peer->expire);
7837 peer->expire = -1;
7839 if (expiry > max_expiry)
7840 expiry = max_expiry;
7841 if (expiry < min_expiry)
7842 expiry = min_expiry;
7843 peer->expire = ast_test_flag(&peer->flags[0], SIP_REALTIME) ? -1 :
7844 ast_sched_add(sched, (expiry + 10) * 1000, expire_register, peer);
7845 pvt->expiry = expiry;
7846 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);
7847 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
7848 ast_db_put("SIP/Registry", peer->name, data);
7849 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
7851 /* Is this a new IP address for us? */
7852 if (inaddrcmp(&peer->addr, &oldsin)) {
7853 sip_poke_peer(peer);
7854 if (option_verbose > 2)
7855 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);
7856 register_peer_exten(peer, 1);
7859 /* Save User agent */
7860 useragent = get_header(req, "User-Agent");
7861 if (strcasecmp(useragent, peer->useragent)) { /* XXX copy if they are different ? */
7862 ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
7863 if (option_verbose > 3)
7864 ast_verbose(VERBOSE_PREFIX_3 "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
7866 return PARSE_REGISTER_UPDATE;
7869 /*! \brief Remove route from route list */
7870 static void free_old_route(struct sip_route *route)
7872 struct sip_route *next;
7874 while (route) {
7875 next = route->next;
7876 free(route);
7877 route = next;
7881 /*! \brief List all routes - mostly for debugging */
7882 static void list_route(struct sip_route *route)
7884 if (!route)
7885 ast_verbose("list_route: no route\n");
7886 else {
7887 for (;route; route = route->next)
7888 ast_verbose("list_route: hop: <%s>\n", route->hop);
7892 /*! \brief Build route list from Record-Route header */
7893 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
7895 struct sip_route *thishop, *head, *tail;
7896 int start = 0;
7897 int len;
7898 const char *rr, *contact, *c;
7900 /* Once a persistant route is set, don't fool with it */
7901 if (p->route && p->route_persistant) {
7902 if (option_debug)
7903 ast_log(LOG_DEBUG, "build_route: Retaining previous route: <%s>\n", p->route->hop);
7904 return;
7907 if (p->route) {
7908 free_old_route(p->route);
7909 p->route = NULL;
7912 p->route_persistant = backwards;
7914 /* Build a tailq, then assign it to p->route when done.
7915 * If backwards, we add entries from the head so they end up
7916 * in reverse order. However, we do need to maintain a correct
7917 * tail pointer because the contact is always at the end.
7919 head = NULL;
7920 tail = head;
7921 /* 1st we pass through all the hops in any Record-Route headers */
7922 for (;;) {
7923 /* Each Record-Route header */
7924 rr = __get_header(req, "Record-Route", &start);
7925 if (*rr == '\0')
7926 break;
7927 for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
7928 ++rr;
7929 len = strcspn(rr, ">") + 1;
7930 /* Make a struct route */
7931 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
7932 /* ast_calloc is not needed because all fields are initialized in this block */
7933 ast_copy_string(thishop->hop, rr, len);
7934 if (option_debug > 1)
7935 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
7936 /* Link in */
7937 if (backwards) {
7938 /* Link in at head so they end up in reverse order */
7939 thishop->next = head;
7940 head = thishop;
7941 /* If this was the first then it'll be the tail */
7942 if (!tail)
7943 tail = thishop;
7944 } else {
7945 thishop->next = NULL;
7946 /* Link in at the end */
7947 if (tail)
7948 tail->next = thishop;
7949 else
7950 head = thishop;
7951 tail = thishop;
7957 /* Only append the contact if we are dealing with a strict router */
7958 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop,";lr") == NULL) ) {
7959 /* 2nd append the Contact: if there is one */
7960 /* Can be multiple Contact headers, comma separated values - we just take the first */
7961 contact = get_header(req, "Contact");
7962 if (!ast_strlen_zero(contact)) {
7963 if (option_debug > 1)
7964 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
7965 /* Look for <: delimited address */
7966 c = strchr(contact, '<');
7967 if (c) {
7968 /* Take to > */
7969 ++c;
7970 len = strcspn(c, ">") + 1;
7971 } else {
7972 /* No <> - just take the lot */
7973 c = contact;
7974 len = strlen(contact) + 1;
7976 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
7977 /* ast_calloc is not needed because all fields are initialized in this block */
7978 ast_copy_string(thishop->hop, c, len);
7979 thishop->next = NULL;
7980 /* Goes at the end */
7981 if (tail)
7982 tail->next = thishop;
7983 else
7984 head = thishop;
7989 /* Store as new route */
7990 p->route = head;
7992 /* For debugging dump what we ended up with */
7993 if (sip_debug_test_pvt(p))
7994 list_route(p->route);
7998 /*! \brief Check user authorization from peer definition
7999 Some actions, like REGISTER and INVITEs from peers require
8000 authentication (if peer have secret set)
8001 \return 0 on success, non-zero on error
8003 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
8004 const char *secret, const char *md5secret, int sipmethod,
8005 char *uri, enum xmittype reliable, int ignore)
8007 const char *response = "407 Proxy Authentication Required";
8008 const char *reqheader = "Proxy-Authorization";
8009 const char *respheader = "Proxy-Authenticate";
8010 const char *authtoken;
8011 char a1_hash[256];
8012 char resp_hash[256]="";
8013 char tmp[BUFSIZ * 2]; /* Make a large enough buffer */
8014 char *c;
8015 int wrongnonce = FALSE;
8016 int good_response;
8017 const char *usednonce = p->randdata;
8019 /* table of recognised keywords, and their value in the digest */
8020 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
8021 struct x {
8022 const char *key;
8023 const char *s;
8024 } *i, keys[] = {
8025 [K_RESP] = { "response=", "" },
8026 [K_URI] = { "uri=", "" },
8027 [K_USER] = { "username=", "" },
8028 [K_NONCE] = { "nonce=", "" },
8029 [K_LAST] = { NULL, NULL}
8032 /* Always OK if no secret */
8033 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
8034 return AUTH_SUCCESSFUL;
8035 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
8036 /* On a REGISTER, we have to use 401 and its family of headers instead of 407 and its family
8037 of headers -- GO SIP! Whoo hoo! Two things that do the same thing but are used in
8038 different circumstances! What a surprise. */
8039 response = "401 Unauthorized";
8040 reqheader = "Authorization";
8041 respheader = "WWW-Authenticate";
8043 authtoken = get_header(req, reqheader);
8044 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
8045 /* This is a retransmitted invite/register/etc, don't reconstruct authentication
8046 information */
8047 if (!reliable) {
8048 /* Resend message if this was NOT a reliable delivery. Otherwise the
8049 retransmission should get it */
8050 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
8051 /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
8052 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8054 return AUTH_CHALLENGE_SENT;
8055 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
8056 /* We have no auth, so issue challenge and request authentication */
8057 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
8058 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
8059 /* Schedule auto destroy in 32 seconds */
8060 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8061 return AUTH_CHALLENGE_SENT;
8064 /* --- We have auth, so check it */
8066 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
8067 an example in the spec of just what it is you're doing a hash on. */
8070 /* Make a copy of the response and parse it */
8071 ast_copy_string(tmp, authtoken, sizeof(tmp));
8072 c = tmp;
8074 while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
8075 for (i = keys; i->key != NULL; i++) {
8076 const char *separator = ","; /* default */
8078 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
8079 continue;
8080 /* Found. Skip keyword, take text in quotes or up to the separator. */
8081 c += strlen(i->key);
8082 if (*c == '"') { /* in quotes. Skip first and look for last */
8083 c++;
8084 separator = "\"";
8086 i->s = c;
8087 strsep(&c, separator);
8088 break;
8090 if (i->key == NULL) /* not found, jump after space or comma */
8091 strsep(&c, " ,");
8094 /* Verify that digest username matches the username we auth as */
8095 if (strcmp(username, keys[K_USER].s)) {
8096 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
8097 username, keys[K_USER].s);
8098 /* Oops, we're trying something here */
8099 return AUTH_USERNAME_MISMATCH;
8102 /* Verify nonce from request matches our nonce. If not, send 401 with new nonce */
8103 if (strcasecmp(p->randdata, keys[K_NONCE].s)) { /* XXX it was 'n'casecmp ? */
8104 wrongnonce = TRUE;
8105 usednonce = keys[K_NONCE].s;
8108 if (!ast_strlen_zero(md5secret))
8109 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
8110 else {
8111 char a1[256];
8112 snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
8113 ast_md5_hash(a1_hash, a1);
8116 /* compute the expected response to compare with what we received */
8118 char a2[256];
8119 char a2_hash[256];
8120 char resp[256];
8122 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
8123 S_OR(keys[K_URI].s, uri));
8124 ast_md5_hash(a2_hash, a2);
8125 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
8126 ast_md5_hash(resp_hash, resp);
8129 good_response = keys[K_RESP].s &&
8130 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
8131 if (wrongnonce) {
8132 ast_string_field_build(p, randdata, "%08lx", ast_random());
8133 if (good_response) {
8134 if (sipdebug)
8135 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
8136 /* We got working auth token, based on stale nonce . */
8137 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
8138 } else {
8139 /* Everything was wrong, so give the device one more try with a new challenge */
8140 if (sipdebug)
8141 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
8142 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
8145 /* Schedule auto destroy in 32 seconds */
8146 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8147 return AUTH_CHALLENGE_SENT;
8149 if (good_response) {
8150 append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
8151 return AUTH_SUCCESSFUL;
8154 /* Ok, we have a bad username/secret pair */
8155 /* Challenge again, and again, and again */
8156 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
8157 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
8159 return AUTH_CHALLENGE_SENT;
8162 /*! \brief Change onhold state of a peer using a pvt structure */
8163 static void sip_peer_hold(struct sip_pvt *p, int hold)
8165 struct sip_peer *peer = find_peer(p->peername, NULL, 1);
8167 if (!peer)
8168 return;
8170 /* If they put someone on hold, increment the value... otherwise decrement it */
8171 if (hold)
8172 peer->onHold++;
8173 else
8174 peer->onHold--;
8176 /* Request device state update */
8177 ast_device_state_changed("SIP/%s", peer->name);
8179 return;
8182 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
8183 \note If you add an "hint" priority to the extension in the dial plan,
8184 you will get notifications on device state changes */
8185 static int cb_extensionstate(char *context, char* exten, int state, void *data)
8187 struct sip_pvt *p = data;
8189 switch(state) {
8190 case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
8191 case AST_EXTENSION_REMOVED: /* Extension is gone */
8192 if (p->autokillid > -1)
8193 sip_cancel_destroy(p); /* Remove subscription expiry for renewals */
8194 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); /* Delete subscription in 32 secs */
8195 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);
8196 p->stateid = -1;
8197 p->subscribed = NONE;
8198 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
8199 break;
8200 default: /* Tell user */
8201 p->laststate = state;
8202 break;
8204 if (p->subscribed != NONE) /* Only send state NOTIFY if we know the format */
8205 transmit_state_notify(p, state, 1, FALSE);
8207 if (option_verbose > 1)
8208 ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %s for Notify User %s\n", exten, ast_extension_state2str(state), p->username);
8209 return 0;
8212 /*! \brief Send a fake 401 Unauthorized response when the administrator
8213 wants to hide the names of local users/peers from fishers
8215 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable)
8217 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
8218 transmit_response_with_auth(p, "401 Unauthorized", req, p->randdata, reliable, "WWW-Authenticate", 0);
8221 /*! \brief Verify registration of user
8222 - Registration is done in several steps, first a REGISTER without auth
8223 to get a challenge (nonce) then a second one with auth
8224 - Registration requests are only matched with peers that are marked as "dynamic"
8226 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
8227 struct sip_request *req, char *uri)
8229 enum check_auth_result res = AUTH_NOT_FOUND;
8230 struct sip_peer *peer;
8231 char tmp[256];
8232 char *name, *c;
8233 char *t;
8234 char *domain;
8236 /* Terminate URI */
8237 t = uri;
8238 while(*t && (*t > 32) && (*t != ';'))
8239 t++;
8240 *t = '\0';
8242 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
8243 if (pedanticsipchecking)
8244 ast_uri_decode(tmp);
8246 c = get_in_brackets(tmp);
8247 c = strsep(&c, ";"); /* Ditch ;user=phone */
8249 if (!strncmp(c, "sip:", 4)) {
8250 name = c + 4;
8251 } else {
8252 name = c;
8253 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
8256 /* Strip off the domain name */
8257 if ((c = strchr(name, '@'))) {
8258 *c++ = '\0';
8259 domain = c;
8260 if ((c = strchr(domain, ':'))) /* Remove :port */
8261 *c = '\0';
8262 if (!AST_LIST_EMPTY(&domain_list)) {
8263 if (!check_sip_domain(domain, NULL, 0)) {
8264 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
8265 return AUTH_UNKNOWN_DOMAIN;
8270 ast_string_field_set(p, exten, name);
8271 build_contact(p);
8272 peer = find_peer(name, NULL, 1);
8273 if (!(peer && ast_apply_ha(peer->ha, sin))) {
8274 /* Peer fails ACL check */
8275 if (peer)
8276 ASTOBJ_UNREF(peer, sip_destroy_peer);
8277 peer = NULL;
8279 if (peer) {
8280 /* Set Frame packetization */
8281 if (p->rtp) {
8282 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
8283 p->autoframing = peer->autoframing;
8285 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
8286 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
8287 } else {
8288 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
8289 transmit_response(p, "100 Trying", req);
8290 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, ast_test_flag(req, SIP_PKT_IGNORE)))) {
8291 sip_cancel_destroy(p);
8293 /* We have a succesful registration attemp with proper authentication,
8294 now, update the peer */
8295 switch (parse_register_contact(p, peer, req)) {
8296 case PARSE_REGISTER_FAILED:
8297 ast_log(LOG_WARNING, "Failed to parse contact info\n");
8298 transmit_response_with_date(p, "400 Bad Request", req);
8299 peer->lastmsgssent = -1;
8300 res = 0;
8301 break;
8302 case PARSE_REGISTER_QUERY:
8303 transmit_response_with_date(p, "200 OK", req);
8304 peer->lastmsgssent = -1;
8305 res = 0;
8306 break;
8307 case PARSE_REGISTER_UPDATE:
8308 update_peer(peer, p->expiry);
8309 /* Say OK and ask subsystem to retransmit msg counter */
8310 transmit_response_with_date(p, "200 OK", req);
8311 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
8312 peer->lastmsgssent = -1;
8313 res = 0;
8314 break;
8319 if (!peer && autocreatepeer) {
8320 /* Create peer if we have autocreate mode enabled */
8321 peer = temp_peer(name);
8322 if (peer) {
8323 ASTOBJ_CONTAINER_LINK(&peerl, peer);
8324 sip_cancel_destroy(p);
8325 switch (parse_register_contact(p, peer, req)) {
8326 case PARSE_REGISTER_FAILED:
8327 ast_log(LOG_WARNING, "Failed to parse contact info\n");
8328 transmit_response_with_date(p, "400 Bad Request", req);
8329 peer->lastmsgssent = -1;
8330 res = 0;
8331 break;
8332 case PARSE_REGISTER_QUERY:
8333 transmit_response_with_date(p, "200 OK", req);
8334 peer->lastmsgssent = -1;
8335 res = 0;
8336 break;
8337 case PARSE_REGISTER_UPDATE:
8338 /* Say OK and ask subsystem to retransmit msg counter */
8339 transmit_response_with_date(p, "200 OK", req);
8340 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
8341 peer->lastmsgssent = -1;
8342 res = 0;
8343 break;
8347 if (!res) {
8348 ast_device_state_changed("SIP/%s", peer->name);
8350 if (res < 0) {
8351 switch (res) {
8352 case AUTH_SECRET_FAILED:
8353 /* Wrong password in authentication. Go away, don't try again until you fixed it */
8354 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
8355 break;
8356 case AUTH_USERNAME_MISMATCH:
8357 /* Username and digest username does not match.
8358 Asterisk uses the From: username for authentication. We need the
8359 users to use the same authentication user name until we support
8360 proper authentication by digest auth name */
8361 transmit_response(p, "403 Authentication user name does not match account name", &p->initreq);
8362 break;
8363 case AUTH_NOT_FOUND:
8364 if (global_alwaysauthreject) {
8365 transmit_fake_auth_response(p, &p->initreq, 1);
8366 } else {
8367 /* URI not found */
8368 transmit_response(p, "404 Not found", &p->initreq);
8370 break;
8371 default:
8372 break;
8374 if (option_debug > 1) {
8375 const char *reason = "";
8377 switch (res) {
8378 case AUTH_SECRET_FAILED:
8379 reason = "Bad password";
8380 break;
8381 case AUTH_USERNAME_MISMATCH:
8382 reason = "Bad digest user";
8383 break;
8384 case AUTH_NOT_FOUND:
8385 reason = "Peer not found";
8386 break;
8387 default:
8388 break;
8390 ast_log(LOG_DEBUG, "SIP REGISTER attempt failed for %s : %s\n",
8391 peer->name, reason);
8394 if (peer)
8395 ASTOBJ_UNREF(peer, sip_destroy_peer);
8397 return res;
8400 /*! \brief Get referring dnis */
8401 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
8403 char tmp[256], *c, *a;
8404 struct sip_request *req;
8406 req = oreq;
8407 if (!req)
8408 req = &p->initreq;
8409 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
8410 if (ast_strlen_zero(tmp))
8411 return 0;
8412 c = get_in_brackets(tmp);
8413 if (strncmp(c, "sip:", 4)) {
8414 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", c);
8415 return -1;
8417 c += 4;
8418 a = c;
8419 strsep(&a, "@;"); /* trim anything after @ or ; */
8420 if (sip_debug_test_pvt(p))
8421 ast_verbose("RDNIS is %s\n", c);
8422 ast_string_field_set(p, rdnis, c);
8424 return 0;
8427 /*! \brief Find out who the call is for
8428 We use the INVITE uri to find out
8430 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
8432 char tmp[256] = "", *uri, *a;
8433 char tmpf[256] = "", *from;
8434 struct sip_request *req;
8435 char *colon;
8437 req = oreq;
8438 if (!req)
8439 req = &p->initreq;
8441 /* Find the request URI */
8442 if (req->rlPart2)
8443 ast_copy_string(tmp, req->rlPart2, sizeof(tmp));
8445 if (pedanticsipchecking)
8446 ast_uri_decode(tmp);
8448 uri = get_in_brackets(tmp);
8450 if (strncmp(uri, "sip:", 4)) {
8451 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
8452 return -1;
8454 uri += 4;
8456 /* Now find the From: caller ID and name */
8457 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
8458 if (!ast_strlen_zero(tmpf)) {
8459 if (pedanticsipchecking)
8460 ast_uri_decode(tmpf);
8461 from = get_in_brackets(tmpf);
8462 } else {
8463 from = NULL;
8466 if (!ast_strlen_zero(from)) {
8467 if (strncmp(from, "sip:", 4)) {
8468 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
8469 return -1;
8471 from += 4;
8472 if ((a = strchr(from, '@')))
8473 *a++ = '\0';
8474 else
8475 a = from; /* just a domain */
8476 from = strsep(&from, ";"); /* Remove userinfo options */
8477 a = strsep(&a, ";"); /* Remove URI options */
8478 ast_string_field_set(p, fromdomain, a);
8481 /* Skip any options and find the domain */
8483 /* Get the target domain */
8484 if ((a = strchr(uri, '@'))) {
8485 *a++ = '\0';
8486 } else { /* No username part */
8487 a = uri;
8488 uri = "s"; /* Set extension to "s" */
8490 colon = strchr(a, ':'); /* Remove :port */
8491 if (colon)
8492 *colon = '\0';
8494 uri = strsep(&uri, ";"); /* Remove userinfo options */
8495 a = strsep(&a, ";"); /* Remove URI options */
8497 ast_string_field_set(p, domain, a);
8499 if (!AST_LIST_EMPTY(&domain_list)) {
8500 char domain_context[AST_MAX_EXTENSION];
8502 domain_context[0] = '\0';
8503 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
8504 if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
8505 if (option_debug)
8506 ast_log(LOG_DEBUG, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
8507 return -2;
8510 /* If we have a context defined, overwrite the original context */
8511 if (!ast_strlen_zero(domain_context))
8512 ast_string_field_set(p, context, domain_context);
8515 if (sip_debug_test_pvt(p))
8516 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
8518 /* Check the dialplan for the username part of the request URI,
8519 the domain will be stored in the SIPDOMAIN variable
8520 Return 0 if we have a matching extension */
8521 if (ast_exists_extension(NULL, p->context, uri, 1, from) ||
8522 !strcmp(uri, ast_pickup_ext())) {
8523 if (!oreq)
8524 ast_string_field_set(p, exten, uri);
8525 return 0;
8528 /* Return 1 for pickup extension or overlap dialling support (if we support it) */
8529 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
8530 ast_canmatch_extension(NULL, p->context, uri, 1, from)) ||
8531 !strncmp(uri, ast_pickup_ext(), strlen(uri))) {
8532 return 1;
8535 return -1;
8538 /*! \brief Lock interface lock and find matching pvt lock
8539 - Their tag is fromtag, our tag is to-tag
8540 - This means that in some transactions, totag needs to be their tag :-)
8541 depending upon the direction
8543 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
8545 struct sip_pvt *sip_pvt_ptr;
8547 ast_mutex_lock(&iflock);
8549 if (option_debug > 3 && totag)
8550 ast_log(LOG_DEBUG, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
8552 /* Search interfaces and find the match */
8553 for (sip_pvt_ptr = iflist; sip_pvt_ptr; sip_pvt_ptr = sip_pvt_ptr->next) {
8554 if (!strcmp(sip_pvt_ptr->callid, callid)) {
8555 int match = 1;
8556 char *ourtag = sip_pvt_ptr->tag;
8558 /* Go ahead and lock it (and its owner) before returning */
8559 ast_mutex_lock(&sip_pvt_ptr->lock);
8561 /* Check if tags match. If not, this is not the call we want
8562 (With a forking SIP proxy, several call legs share the
8563 call id, but have different tags)
8565 if (pedanticsipchecking && (strcmp(fromtag, sip_pvt_ptr->theirtag) || strcmp(totag, ourtag)))
8566 match = 0;
8568 if (!match) {
8569 ast_mutex_unlock(&sip_pvt_ptr->lock);
8570 continue;
8573 if (option_debug > 3 && totag)
8574 ast_log(LOG_DEBUG, "Matched %s call - their tag is %s Our tag is %s\n",
8575 ast_test_flag(&sip_pvt_ptr->flags[0], SIP_OUTGOING) ? "OUTGOING": "INCOMING",
8576 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
8578 /* deadlock avoidance... */
8579 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
8580 ast_mutex_unlock(&sip_pvt_ptr->lock);
8581 usleep(1);
8582 ast_mutex_lock(&sip_pvt_ptr->lock);
8584 break;
8587 ast_mutex_unlock(&iflock);
8588 if (option_debug > 3 && !sip_pvt_ptr)
8589 ast_log(LOG_DEBUG, "Found no match for callid %s to-tag %s from-tag %s\n", callid, totag, fromtag);
8590 return sip_pvt_ptr;
8593 /*! \brief Call transfer support (the REFER method)
8594 * Extracts Refer headers into pvt dialog structure */
8595 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
8598 const char *p_referred_by = NULL;
8599 char *h_refer_to = NULL;
8600 char *h_referred_by = NULL;
8601 char *refer_to;
8602 const char *p_refer_to;
8603 char *referred_by_uri = NULL;
8604 char *ptr;
8605 struct sip_request *req = NULL;
8606 const char *transfer_context = NULL;
8607 struct sip_refer *referdata;
8610 req = outgoing_req;
8611 referdata = transferer->refer;
8613 if (!req)
8614 req = &transferer->initreq;
8616 p_refer_to = get_header(req, "Refer-To");
8617 if (ast_strlen_zero(p_refer_to)) {
8618 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
8619 return -2; /* Syntax error */
8621 h_refer_to = ast_strdupa(p_refer_to);
8622 refer_to = get_in_brackets(h_refer_to);
8623 if (pedanticsipchecking)
8624 ast_uri_decode(refer_to);
8626 if (strncasecmp(refer_to, "sip:", 4)) {
8627 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
8628 return -3;
8630 refer_to += 4; /* Skip sip: */
8632 /* Get referred by header if it exists */
8633 p_referred_by = get_header(req, "Referred-By");
8634 if (!ast_strlen_zero(p_referred_by)) {
8635 char *lessthan;
8636 h_referred_by = ast_strdupa(p_referred_by);
8637 if (pedanticsipchecking)
8638 ast_uri_decode(h_referred_by);
8640 /* Store referrer's caller ID name */
8641 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
8642 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
8643 *(lessthan - 1) = '\0'; /* Space */
8646 referred_by_uri = get_in_brackets(h_referred_by);
8647 if(strncasecmp(referred_by_uri, "sip:", 4)) {
8648 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
8649 referred_by_uri = (char *) NULL;
8650 } else {
8651 referred_by_uri += 4; /* Skip sip: */
8655 /* Check for arguments in the refer_to header */
8656 if ((ptr = strchr(refer_to, '?'))) { /* Search for arguments */
8657 *ptr++ = '\0';
8658 if (!strncasecmp(ptr, "REPLACES=", 9)) {
8659 char *to = NULL, *from = NULL;
8661 /* This is an attended transfer */
8662 referdata->attendedtransfer = 1;
8663 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
8664 ast_uri_decode(referdata->replaces_callid);
8665 if ((ptr = strchr(referdata->replaces_callid, ';'))) /* Find options */ {
8666 *ptr++ = '\0';
8669 if (ptr) {
8670 /* Find the different tags before we destroy the string */
8671 to = strcasestr(ptr, "to-tag=");
8672 from = strcasestr(ptr, "from-tag=");
8675 /* Grab the to header */
8676 if (to) {
8677 ptr = to + 7;
8678 if ((to = strchr(ptr, '&')))
8679 *to = '\0';
8680 if ((to = strchr(ptr, ';')))
8681 *to = '\0';
8682 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
8685 if (from) {
8686 ptr = from + 9;
8687 if ((to = strchr(ptr, '&')))
8688 *to = '\0';
8689 if ((to = strchr(ptr, ';')))
8690 *to = '\0';
8691 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
8694 if (option_debug > 1) {
8695 if (!pedanticsipchecking)
8696 ast_log(LOG_DEBUG,"Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
8697 else
8698 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>" );
8703 if ((ptr = strchr(refer_to, '@'))) { /* Separate domain */
8704 char *urioption;
8706 *ptr++ = '\0';
8707 if ((urioption = strchr(ptr, ';')))
8708 *urioption++ = '\0';
8709 /* Save the domain for the dial plan */
8710 ast_copy_string(referdata->refer_to_domain, ptr, sizeof(referdata->refer_to_domain));
8711 if (urioption)
8712 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
8715 if ((ptr = strchr(refer_to, ';'))) /* Remove options */
8716 *ptr = '\0';
8717 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
8719 if (referred_by_uri) {
8720 if ((ptr = strchr(referred_by_uri, ';'))) /* Remove options */
8721 *ptr = '\0';
8722 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
8723 } else {
8724 referdata->referred_by[0] = '\0';
8727 /* Determine transfer context */
8728 if (transferer->owner) /* Mimic behaviour in res_features.c */
8729 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
8731 /* By default, use the context in the channel sending the REFER */
8732 if (ast_strlen_zero(transfer_context)) {
8733 transfer_context = S_OR(transferer->owner->macrocontext,
8734 S_OR(transferer->context, default_context));
8737 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
8739 /* Either an existing extension or the parking extension */
8740 if (ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
8741 if (sip_debug_test_pvt(transferer)) {
8742 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
8744 /* We are ready to transfer to the extension */
8745 return 0;
8747 if (sip_debug_test_pvt(transferer))
8748 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
8750 /* Failure, we can't find this extension */
8751 return -1;
8755 /*! \brief Call transfer support (old way, deprecated by the IETF)--*/
8756 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
8758 char tmp[256] = "", *c, *a;
8759 struct sip_request *req = oreq ? oreq : &p->initreq;
8760 struct sip_refer *referdata = p->refer;
8761 const char *transfer_context = NULL;
8763 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
8764 c = get_in_brackets(tmp);
8766 if (pedanticsipchecking)
8767 ast_uri_decode(c);
8769 if (strncmp(c, "sip:", 4)) {
8770 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
8771 return -1;
8773 c += 4;
8774 if ((a = strchr(c, ';'))) /* Remove arguments */
8775 *a = '\0';
8777 if ((a = strchr(c, '@'))) { /* Separate Domain */
8778 *a++ = '\0';
8779 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
8782 if (sip_debug_test_pvt(p))
8783 ast_verbose("Looking for %s in %s\n", c, p->context);
8785 if (p->owner) /* Mimic behaviour in res_features.c */
8786 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
8788 /* By default, use the context in the channel sending the REFER */
8789 if (ast_strlen_zero(transfer_context)) {
8790 transfer_context = S_OR(p->owner->macrocontext,
8791 S_OR(p->context, default_context));
8793 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
8794 /* This is a blind transfer */
8795 if (option_debug)
8796 ast_log(LOG_DEBUG,"SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
8797 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
8798 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
8799 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
8800 referdata->refer_call = NULL;
8801 /* Set new context */
8802 ast_string_field_set(p, context, transfer_context);
8803 return 0;
8804 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
8805 return 1;
8808 return -1;
8810 /*! \brief check Via: header for hostname, port and rport request/answer */
8811 static void check_via(struct sip_pvt *p, struct sip_request *req)
8813 char via[256];
8814 char *c, *pt;
8815 struct hostent *hp;
8816 struct ast_hostent ahp;
8818 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
8820 /* Work on the leftmost value of the topmost Via header */
8821 c = strchr(via, ',');
8822 if (c)
8823 *c = '\0';
8825 /* Check for rport */
8826 c = strstr(via, ";rport");
8827 if (c && (c[6] != '=')) /* rport query, not answer */
8828 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
8830 c = strchr(via, ';');
8831 if (c)
8832 *c = '\0';
8834 c = strchr(via, ' ');
8835 if (c) {
8836 *c = '\0';
8837 c = ast_skip_blanks(c+1);
8838 if (strcasecmp(via, "SIP/2.0/UDP")) {
8839 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
8840 return;
8842 pt = strchr(c, ':');
8843 if (pt)
8844 *pt++ = '\0'; /* remember port pointer */
8845 hp = ast_gethostbyname(c, &ahp);
8846 if (!hp) {
8847 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
8848 return;
8850 memset(&p->sa, 0, sizeof(p->sa));
8851 p->sa.sin_family = AF_INET;
8852 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
8853 p->sa.sin_port = htons(pt ? atoi(pt) : STANDARD_SIP_PORT);
8855 if (sip_debug_test_pvt(p)) {
8856 const struct sockaddr_in *dst = sip_real_dst(p);
8857 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
8862 /*! \brief Get caller id name from SIP headers */
8863 static char *get_calleridname(const char *input, char *output, size_t outputsize)
8865 const char *end = strchr(input,'<'); /* first_bracket */
8866 const char *tmp = strchr(input,'"'); /* first quote */
8867 int bytes = 0;
8868 int maxbytes = outputsize - 1;
8870 if (!end || end == input) /* we require a part in brackets */
8871 return NULL;
8873 end--; /* move just before "<" */
8875 if (tmp && tmp <= end) {
8876 /* The quote (tmp) precedes the bracket (end+1).
8877 * Find the matching quote and return the content.
8879 end = strchr(tmp+1, '"');
8880 if (!end)
8881 return NULL;
8882 bytes = (int) (end - tmp);
8883 /* protect the output buffer */
8884 if (bytes > maxbytes)
8885 bytes = maxbytes;
8886 ast_copy_string(output, tmp + 1, bytes);
8887 } else {
8888 /* No quoted string, or it is inside brackets. */
8889 /* clear the empty characters in the begining*/
8890 input = ast_skip_blanks(input);
8891 /* clear the empty characters in the end */
8892 while(*end && *end < 33 && end > input)
8893 end--;
8894 if (end >= input) {
8895 bytes = (int) (end - input) + 2;
8896 /* protect the output buffer */
8897 if (bytes > maxbytes)
8898 bytes = maxbytes;
8899 ast_copy_string(output, input, bytes);
8900 } else
8901 return NULL;
8903 return output;
8906 /*! \brief Get caller id number from Remote-Party-ID header field
8907 * Returns true if number should be restricted (privacy setting found)
8908 * output is set to NULL if no number found
8910 static int get_rpid_num(const char *input, char *output, int maxlen)
8912 char *start;
8913 char *end;
8915 start = strchr(input,':');
8916 if (!start) {
8917 output[0] = '\0';
8918 return 0;
8920 start++;
8922 /* we found "number" */
8923 ast_copy_string(output,start,maxlen);
8924 output[maxlen-1] = '\0';
8926 end = strchr(output,'@');
8927 if (end)
8928 *end = '\0';
8929 else
8930 output[0] = '\0';
8931 if (strstr(input,"privacy=full") || strstr(input,"privacy=uri"))
8932 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
8934 return 0;
8938 /*! \brief Check if matching user or peer is defined
8939 Match user on From: user name and peer on IP/port
8940 This is used on first invite (not re-invites) and subscribe requests
8941 \return 0 on success, non-zero on failure
8943 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
8944 int sipmethod, char *uri, enum xmittype reliable,
8945 struct sockaddr_in *sin, struct sip_peer **authpeer)
8947 struct sip_user *user = NULL;
8948 struct sip_peer *peer;
8949 char from[256], *c;
8950 char *of;
8951 char rpid_num[50];
8952 const char *rpid;
8953 enum check_auth_result res = AUTH_SUCCESSFUL;
8954 char *t;
8955 char calleridname[50];
8956 int debug=sip_debug_test_addr(sin);
8957 struct ast_variable *tmpvar = NULL, *v = NULL;
8958 char *uri2 = ast_strdupa(uri);
8960 /* Terminate URI */
8961 t = uri2;
8962 while (*t && *t > 32 && *t != ';')
8963 t++;
8964 *t = '\0';
8965 ast_copy_string(from, get_header(req, "From"), sizeof(from)); /* XXX bug in original code, overwrote string */
8966 if (pedanticsipchecking)
8967 ast_uri_decode(from);
8968 /* XXX here tries to map the username for invite things */
8969 memset(calleridname, 0, sizeof(calleridname));
8970 get_calleridname(from, calleridname, sizeof(calleridname));
8971 if (calleridname[0])
8972 ast_string_field_set(p, cid_name, calleridname);
8974 rpid = get_header(req, "Remote-Party-ID");
8975 memset(rpid_num, 0, sizeof(rpid_num));
8976 if (!ast_strlen_zero(rpid))
8977 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
8979 of = get_in_brackets(from);
8980 if (ast_strlen_zero(p->exten)) {
8981 t = uri2;
8982 if (!strncmp(t, "sip:", 4))
8983 t+= 4;
8984 ast_string_field_set(p, exten, t);
8985 t = strchr(p->exten, '@');
8986 if (t)
8987 *t = '\0';
8988 if (ast_strlen_zero(p->our_contact))
8989 build_contact(p);
8991 /* save the URI part of the From header */
8992 ast_string_field_set(p, from, of);
8993 if (strncmp(of, "sip:", 4)) {
8994 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
8995 } else
8996 of += 4;
8997 /* Get just the username part */
8998 if ((c = strchr(of, '@'))) {
8999 char *tmp;
9000 *c = '\0';
9001 if ((c = strchr(of, ':')))
9002 *c = '\0';
9003 tmp = ast_strdupa(of);
9004 if (ast_is_shrinkable_phonenumber(tmp))
9005 ast_shrink_phone_number(tmp);
9006 ast_string_field_set(p, cid_num, tmp);
9008 if (ast_strlen_zero(of))
9009 return AUTH_SUCCESSFUL;
9011 if (!authpeer) /* If we are looking for a peer, don't check the user objects (or realtime) */
9012 user = find_user(of, 1);
9014 /* Find user based on user name in the from header */
9015 if (user && ast_apply_ha(user->ha, sin)) {
9016 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
9017 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9018 /* copy channel vars */
9019 for (v = user->chanvars ; v ; v = v->next) {
9020 if ((tmpvar = ast_variable_new(v->name, v->value))) {
9021 tmpvar->next = p->chanvars;
9022 p->chanvars = tmpvar;
9025 p->prefs = user->prefs;
9026 /* Set Frame packetization */
9027 if (p->rtp) {
9028 ast_rtp_codec_setpref(p->rtp, &p->prefs);
9029 p->autoframing = user->autoframing;
9031 /* replace callerid if rpid found, and not restricted */
9032 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
9033 char *tmp;
9034 if (*calleridname)
9035 ast_string_field_set(p, cid_name, calleridname);
9036 tmp = ast_strdupa(rpid_num);
9037 if (ast_is_shrinkable_phonenumber(tmp))
9038 ast_shrink_phone_number(tmp);
9039 ast_string_field_set(p, cid_num, tmp);
9042 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE) );
9044 if (!(res = check_auth(p, req, user->name, user->secret, user->md5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
9045 sip_cancel_destroy(p);
9046 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
9047 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9048 /* Copy SIP extensions profile from INVITE */
9049 if (p->sipoptions)
9050 user->sipoptions = p->sipoptions;
9052 /* If we have a call limit, set flag */
9053 if (user->call_limit)
9054 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
9055 if (!ast_strlen_zero(user->context))
9056 ast_string_field_set(p, context, user->context);
9057 if (!ast_strlen_zero(user->cid_num) && !ast_strlen_zero(p->cid_num)) {
9058 char *tmp = ast_strdupa(user->cid_num);
9059 if (ast_is_shrinkable_phonenumber(tmp))
9060 ast_shrink_phone_number(tmp);
9061 ast_string_field_set(p, cid_num, tmp);
9063 if (!ast_strlen_zero(user->cid_name) && !ast_strlen_zero(p->cid_num))
9064 ast_string_field_set(p, cid_name, user->cid_name);
9065 ast_string_field_set(p, username, user->name);
9066 ast_string_field_set(p, peername, user->name);
9067 ast_string_field_set(p, peersecret, user->secret);
9068 ast_string_field_set(p, peermd5secret, user->md5secret);
9069 ast_string_field_set(p, subscribecontext, user->subscribecontext);
9070 ast_string_field_set(p, accountcode, user->accountcode);
9071 ast_string_field_set(p, language, user->language);
9072 ast_string_field_set(p, mohsuggest, user->mohsuggest);
9073 ast_string_field_set(p, mohinterpret, user->mohinterpret);
9074 p->allowtransfer = user->allowtransfer;
9075 p->amaflags = user->amaflags;
9076 p->callgroup = user->callgroup;
9077 p->pickupgroup = user->pickupgroup;
9078 if (user->callingpres) /* User callingpres setting will override RPID header */
9079 p->callingpres = user->callingpres;
9081 /* Set default codec settings for this call */
9082 p->capability = user->capability; /* User codec choice */
9083 p->jointcapability = user->capability; /* Our codecs */
9084 if (p->peercapability) /* AND with peer's codecs */
9085 p->jointcapability &= p->peercapability;
9086 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
9087 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
9088 p->noncodeccapability |= AST_RTP_DTMF;
9089 else
9090 p->noncodeccapability &= ~AST_RTP_DTMF;
9091 if (p->t38.peercapability)
9092 p->t38.jointcapability &= p->t38.peercapability;
9093 p->maxcallbitrate = user->maxcallbitrate;
9094 /* If we do not support video, remove video from call structure */
9095 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
9096 ast_rtp_destroy(p->vrtp);
9097 p->vrtp = NULL;
9100 if (user && debug)
9101 ast_verbose("Found user '%s'\n", user->name);
9102 } else {
9103 if (user) {
9104 if (!authpeer && debug)
9105 ast_verbose("Found user '%s', but fails host access\n", user->name);
9106 ASTOBJ_UNREF(user,sip_destroy_user);
9108 user = NULL;
9111 if (!user) {
9112 /* If we didn't find a user match, check for peers */
9113 if (sipmethod == SIP_SUBSCRIBE)
9114 /* For subscribes, match on peer name only */
9115 peer = find_peer(of, NULL, 1);
9116 else
9117 /* Look for peer based on the IP address we received data from */
9118 /* If peer is registered from this IP address or have this as a default
9119 IP address, this call is from the peer
9121 peer = find_peer(NULL, &p->recv, 1);
9123 if (peer) {
9124 /* Set Frame packetization */
9125 if (p->rtp) {
9126 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
9127 p->autoframing = peer->autoframing;
9129 if (debug)
9130 ast_verbose("Found peer '%s'\n", peer->name);
9132 /* Take the peer */
9133 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
9134 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9136 /* Copy SIP extensions profile to peer */
9137 if (p->sipoptions)
9138 peer->sipoptions = p->sipoptions;
9140 /* replace callerid if rpid found, and not restricted */
9141 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
9142 char *tmp = ast_strdupa(rpid_num);
9143 if (*calleridname)
9144 ast_string_field_set(p, cid_name, calleridname);
9145 if (ast_is_shrinkable_phonenumber(tmp))
9146 ast_shrink_phone_number(tmp);
9147 ast_string_field_set(p, cid_num, tmp);
9149 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
9151 ast_string_field_set(p, peersecret, peer->secret);
9152 ast_string_field_set(p, peermd5secret, peer->md5secret);
9153 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
9154 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
9155 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
9156 if (peer->callingpres) /* Peer calling pres setting will override RPID */
9157 p->callingpres = peer->callingpres;
9158 if (peer->maxms && peer->lastms)
9159 p->timer_t1 = peer->lastms;
9160 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
9161 /* Pretend there is no required authentication */
9162 ast_string_field_free(p, peersecret);
9163 ast_string_field_free(p, peermd5secret);
9165 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
9166 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
9167 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9168 /* If we have a call limit, set flag */
9169 if (peer->call_limit)
9170 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
9171 ast_string_field_set(p, peername, peer->name);
9172 ast_string_field_set(p, authname, peer->name);
9174 /* copy channel vars */
9175 for (v = peer->chanvars ; v ; v = v->next) {
9176 if ((tmpvar = ast_variable_new(v->name, v->value))) {
9177 tmpvar->next = p->chanvars;
9178 p->chanvars = tmpvar;
9181 if (authpeer) {
9182 (*authpeer) = ASTOBJ_REF(peer); /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
9185 if (!ast_strlen_zero(peer->username)) {
9186 ast_string_field_set(p, username, peer->username);
9187 /* Use the default username for authentication on outbound calls */
9188 /* XXX this takes the name from the caller... can we override ? */
9189 ast_string_field_set(p, authname, peer->username);
9191 if (!ast_strlen_zero(peer->cid_num) && !ast_strlen_zero(p->cid_num)) {
9192 char *tmp = ast_strdupa(peer->cid_num);
9193 if (ast_is_shrinkable_phonenumber(tmp))
9194 ast_shrink_phone_number(tmp);
9195 ast_string_field_set(p, cid_num, tmp);
9197 if (!ast_strlen_zero(peer->cid_name) && !ast_strlen_zero(p->cid_name))
9198 ast_string_field_set(p, cid_name, peer->cid_name);
9199 ast_string_field_set(p, fullcontact, peer->fullcontact);
9200 if (!ast_strlen_zero(peer->context))
9201 ast_string_field_set(p, context, peer->context);
9202 ast_string_field_set(p, peersecret, peer->secret);
9203 ast_string_field_set(p, peermd5secret, peer->md5secret);
9204 ast_string_field_set(p, language, peer->language);
9205 ast_string_field_set(p, accountcode, peer->accountcode);
9206 p->amaflags = peer->amaflags;
9207 p->callgroup = peer->callgroup;
9208 p->pickupgroup = peer->pickupgroup;
9209 p->capability = peer->capability;
9210 p->prefs = peer->prefs;
9211 p->jointcapability = peer->capability;
9212 if (p->peercapability)
9213 p->jointcapability &= p->peercapability;
9214 p->maxcallbitrate = peer->maxcallbitrate;
9215 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
9216 ast_rtp_destroy(p->vrtp);
9217 p->vrtp = NULL;
9219 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
9220 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
9221 p->noncodeccapability |= AST_RTP_DTMF;
9222 else
9223 p->noncodeccapability &= ~AST_RTP_DTMF;
9224 if (p->t38.peercapability)
9225 p->t38.jointcapability &= p->t38.peercapability;
9227 ASTOBJ_UNREF(peer, sip_destroy_peer);
9228 } else {
9229 if (debug)
9230 ast_verbose("Found no matching peer or user for '%s:%d'\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
9232 /* do we allow guests? */
9233 if (!global_allowguest) {
9234 if (global_alwaysauthreject)
9235 res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
9236 else
9237 res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
9243 if (user)
9244 ASTOBJ_UNREF(user, sip_destroy_user);
9245 return res;
9248 /*! \brief Find user
9249 If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
9251 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
9253 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
9256 /*! \brief Get text out of a SIP MESSAGE packet */
9257 static int get_msg_text(char *buf, int len, struct sip_request *req)
9259 int x;
9260 int y;
9262 buf[0] = '\0';
9263 y = len - strlen(buf) - 5;
9264 if (y < 0)
9265 y = 0;
9266 for (x=0;x<req->lines;x++) {
9267 strncat(buf, req->line[x], y); /* safe */
9268 y -= strlen(req->line[x]) + 1;
9269 if (y < 0)
9270 y = 0;
9271 if (y != 0)
9272 strcat(buf, "\n"); /* safe */
9274 return 0;
9278 /*! \brief Receive SIP MESSAGE method messages
9279 \note We only handle messages within current calls currently
9280 Reference: RFC 3428 */
9281 static void receive_message(struct sip_pvt *p, struct sip_request *req)
9283 char buf[1024];
9284 struct ast_frame f;
9285 const char *content_type = get_header(req, "Content-Type");
9287 if (strcmp(content_type, "text/plain")) { /* No text/plain attachment */
9288 transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
9289 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
9290 return;
9293 if (get_msg_text(buf, sizeof(buf), req)) {
9294 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
9295 transmit_response(p, "202 Accepted", req);
9296 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
9297 return;
9300 if (p->owner) {
9301 if (sip_debug_test_pvt(p))
9302 ast_verbose("Message received: '%s'\n", buf);
9303 memset(&f, 0, sizeof(f));
9304 f.frametype = AST_FRAME_TEXT;
9305 f.subclass = 0;
9306 f.offset = 0;
9307 f.data = buf;
9308 f.datalen = strlen(buf);
9309 ast_queue_frame(p->owner, &f);
9310 transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
9311 } else { /* Message outside of a call, we do not support that */
9312 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);
9313 transmit_response(p, "405 Method Not Allowed", req); /* Good enough, or? */
9315 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
9316 return;
9319 /*! \brief CLI Command to show calls within limits set by call_limit */
9320 static int sip_show_inuse(int fd, int argc, char *argv[])
9322 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
9323 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
9324 char ilimits[40];
9325 char iused[40];
9326 int showall = FALSE;
9328 if (argc < 3)
9329 return RESULT_SHOWUSAGE;
9331 if (argc == 4 && !strcmp(argv[3],"all"))
9332 showall = TRUE;
9334 ast_cli(fd, FORMAT, "* User name", "In use", "Limit");
9335 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
9336 ASTOBJ_RDLOCK(iterator);
9337 if (iterator->call_limit)
9338 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
9339 else
9340 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
9341 snprintf(iused, sizeof(iused), "%d", iterator->inUse);
9342 if (showall || iterator->call_limit)
9343 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
9344 ASTOBJ_UNLOCK(iterator);
9345 } while (0) );
9347 ast_cli(fd, FORMAT, "* Peer name", "In use", "Limit");
9349 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
9350 ASTOBJ_RDLOCK(iterator);
9351 if (iterator->call_limit)
9352 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
9353 else
9354 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
9355 snprintf(iused, sizeof(iused), "%d/%d", iterator->inUse, iterator->inRinging);
9356 if (showall || iterator->call_limit)
9357 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
9358 ASTOBJ_UNLOCK(iterator);
9359 } while (0) );
9361 return RESULT_SUCCESS;
9362 #undef FORMAT
9363 #undef FORMAT2
9366 /*! \brief Convert transfer mode to text string */
9367 static char *transfermode2str(enum transfermodes mode)
9369 if (mode == TRANSFER_OPENFORALL)
9370 return "open";
9371 else if (mode == TRANSFER_CLOSED)
9372 return "closed";
9373 return "strict";
9376 /*! \brief Convert NAT setting to text string */
9377 static char *nat2str(int nat)
9379 switch(nat) {
9380 case SIP_NAT_NEVER:
9381 return "No";
9382 case SIP_NAT_ROUTE:
9383 return "Route";
9384 case SIP_NAT_ALWAYS:
9385 return "Always";
9386 case SIP_NAT_RFC3581:
9387 return "RFC3581";
9388 default:
9389 return "Unknown";
9393 /*! \brief Report Peer status in character string
9394 * \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
9396 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
9398 int res = 0;
9399 if (peer->maxms) {
9400 if (peer->lastms < 0) {
9401 ast_copy_string(status, "UNREACHABLE", statuslen);
9402 } else if (peer->lastms > peer->maxms) {
9403 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
9404 res = 1;
9405 } else if (peer->lastms) {
9406 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
9407 res = 1;
9408 } else {
9409 ast_copy_string(status, "UNKNOWN", statuslen);
9411 } else {
9412 ast_copy_string(status, "Unmonitored", statuslen);
9413 /* Checking if port is 0 */
9414 res = -1;
9416 return res;
9419 /*! \brief CLI Command 'SIP Show Users' */
9420 static int sip_show_users(int fd, int argc, char *argv[])
9422 regex_t regexbuf;
9423 int havepattern = FALSE;
9425 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
9427 switch (argc) {
9428 case 5:
9429 if (!strcasecmp(argv[3], "like")) {
9430 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
9431 return RESULT_SHOWUSAGE;
9432 havepattern = TRUE;
9433 } else
9434 return RESULT_SHOWUSAGE;
9435 case 3:
9436 break;
9437 default:
9438 return RESULT_SHOWUSAGE;
9441 ast_cli(fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
9442 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
9443 ASTOBJ_RDLOCK(iterator);
9445 if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
9446 ASTOBJ_UNLOCK(iterator);
9447 continue;
9450 ast_cli(fd, FORMAT, iterator->name,
9451 iterator->secret,
9452 iterator->accountcode,
9453 iterator->context,
9454 iterator->ha ? "Yes" : "No",
9455 nat2str(ast_test_flag(&iterator->flags[0], SIP_NAT)));
9456 ASTOBJ_UNLOCK(iterator);
9457 } while (0)
9460 if (havepattern)
9461 regfree(&regexbuf);
9463 return RESULT_SUCCESS;
9464 #undef FORMAT
9467 static char mandescr_show_peers[] =
9468 "Description: Lists SIP peers in text format with details on current status.\n"
9469 "Variables: \n"
9470 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
9472 /*! \brief Show SIP peers in the manager API */
9473 /* Inspired from chan_iax2 */
9474 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
9476 const char *id = astman_get_header(m,"ActionID");
9477 const char *a[] = {"sip", "show", "peers"};
9478 char idtext[256] = "";
9479 int total = 0;
9481 if (!ast_strlen_zero(id))
9482 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
9484 astman_send_ack(s, m, "Peer status list will follow");
9485 /* List the peers in separate manager events */
9486 _sip_show_peers(-1, &total, s, m, 3, a);
9487 /* Send final confirmation */
9488 astman_append(s,
9489 "Event: PeerlistComplete\r\n"
9490 "ListItems: %d\r\n"
9491 "%s"
9492 "\r\n", total, idtext);
9493 return 0;
9496 /*! \brief CLI Show Peers command */
9497 static int sip_show_peers(int fd, int argc, char *argv[])
9499 return _sip_show_peers(fd, NULL, NULL, NULL, argc, (const char **) argv);
9502 /*! \brief _sip_show_peers: Execute sip show peers command */
9503 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
9505 regex_t regexbuf;
9506 int havepattern = FALSE;
9508 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %-10s\n"
9509 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %-10s\n"
9511 char name[256];
9512 int total_peers = 0;
9513 int peers_mon_online = 0;
9514 int peers_mon_offline = 0;
9515 int peers_unmon_offline = 0;
9516 int peers_unmon_online = 0;
9517 const char *id;
9518 char idtext[256] = "";
9519 int realtimepeers;
9521 realtimepeers = ast_check_realtime("sippeers");
9523 if (s) { /* Manager - get ActionID */
9524 id = astman_get_header(m,"ActionID");
9525 if (!ast_strlen_zero(id))
9526 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
9529 switch (argc) {
9530 case 5:
9531 if (!strcasecmp(argv[3], "like")) {
9532 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
9533 return RESULT_SHOWUSAGE;
9534 havepattern = TRUE;
9535 } else
9536 return RESULT_SHOWUSAGE;
9537 case 3:
9538 break;
9539 default:
9540 return RESULT_SHOWUSAGE;
9543 if (!s) /* Normal list */
9544 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
9546 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
9547 char status[20] = "";
9548 char srch[2000];
9549 char pstatus;
9551 ASTOBJ_RDLOCK(iterator);
9553 if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
9554 ASTOBJ_UNLOCK(iterator);
9555 continue;
9558 if (!ast_strlen_zero(iterator->username) && !s)
9559 snprintf(name, sizeof(name), "%s/%s", iterator->name, iterator->username);
9560 else
9561 ast_copy_string(name, iterator->name, sizeof(name));
9563 pstatus = peer_status(iterator, status, sizeof(status));
9564 if (pstatus == 1)
9565 peers_mon_online++;
9566 else if (pstatus == 0)
9567 peers_mon_offline++;
9568 else {
9569 if (iterator->addr.sin_port == 0)
9570 peers_unmon_offline++;
9571 else
9572 peers_unmon_online++;
9575 snprintf(srch, sizeof(srch), FORMAT, name,
9576 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
9577 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ", /* Dynamic or not? */
9578 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
9579 iterator->ha ? " A " : " ", /* permit/deny */
9580 ntohs(iterator->addr.sin_port), status,
9581 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
9583 if (!s) {/* Normal CLI list */
9584 ast_cli(fd, FORMAT, name,
9585 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
9586 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ", /* Dynamic or not? */
9587 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
9588 iterator->ha ? " A " : " ", /* permit/deny */
9590 ntohs(iterator->addr.sin_port), status,
9591 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
9592 } else { /* Manager format */
9593 /* The names here need to be the same as other channels */
9594 astman_append(s,
9595 "Event: PeerEntry\r\n%s"
9596 "Channeltype: SIP\r\n"
9597 "ObjectName: %s\r\n"
9598 "ChanObjectType: peer\r\n" /* "peer" or "user" */
9599 "IPaddress: %s\r\n"
9600 "IPport: %d\r\n"
9601 "Dynamic: %s\r\n"
9602 "Natsupport: %s\r\n"
9603 "VideoSupport: %s\r\n"
9604 "ACL: %s\r\n"
9605 "Status: %s\r\n"
9606 "RealtimeDevice: %s\r\n\r\n",
9607 idtext,
9608 iterator->name,
9609 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "-none-",
9610 ntohs(iterator->addr.sin_port),
9611 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no", /* Dynamic or not? */
9612 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? "yes" : "no", /* NAT=yes? */
9613 ast_test_flag(&iterator->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no", /* VIDEOSUPPORT=yes? */
9614 iterator->ha ? "yes" : "no", /* permit/deny */
9615 status,
9616 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "yes":"no") : "no");
9619 ASTOBJ_UNLOCK(iterator);
9621 total_peers++;
9622 } while(0) );
9624 if (!s)
9625 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
9626 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
9628 if (havepattern)
9629 regfree(&regexbuf);
9631 if (total)
9632 *total = total_peers;
9635 return RESULT_SUCCESS;
9636 #undef FORMAT
9637 #undef FORMAT2
9640 /*! \brief List all allocated SIP Objects (realtime or static) */
9641 static int sip_show_objects(int fd, int argc, char *argv[])
9643 char tmp[256];
9644 if (argc != 3)
9645 return RESULT_SHOWUSAGE;
9646 ast_cli(fd, "-= User objects: %d static, %d realtime =-\n\n", suserobjs, ruserobjs);
9647 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &userl);
9648 ast_cli(fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
9649 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &peerl);
9650 ast_cli(fd, "-= Registry objects: %d =-\n\n", regobjs);
9651 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &regl);
9652 return RESULT_SUCCESS;
9654 /*! \brief Print call group and pickup group */
9655 static void print_group(int fd, ast_group_t group, int crlf)
9657 char buf[256];
9658 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
9661 /*! \brief Convert DTMF mode to printable string */
9662 static const char *dtmfmode2str(int mode)
9664 switch (mode) {
9665 case SIP_DTMF_RFC2833:
9666 return "rfc2833";
9667 case SIP_DTMF_INFO:
9668 return "info";
9669 case SIP_DTMF_INBAND:
9670 return "inband";
9671 case SIP_DTMF_AUTO:
9672 return "auto";
9674 return "<error>";
9677 /*! \brief Convert Insecure setting to printable string */
9678 static const char *insecure2str(int port, int invite)
9680 if (port && invite)
9681 return "port,invite";
9682 else if (port)
9683 return "port";
9684 else if (invite)
9685 return "invite";
9686 else
9687 return "no";
9690 /*! \brief Destroy disused contexts between reloads
9691 Only used in reload_config so the code for regcontext doesn't get ugly
9693 static void cleanup_stale_contexts(char *new, char *old)
9695 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
9697 while ((oldcontext = strsep(&old, "&"))) {
9698 stalecontext = '\0';
9699 ast_copy_string(newlist, new, sizeof(newlist));
9700 stringp = newlist;
9701 while ((newcontext = strsep(&stringp, "&"))) {
9702 if (strcmp(newcontext, oldcontext) == 0) {
9703 /* This is not the context you're looking for */
9704 stalecontext = '\0';
9705 break;
9706 } else if (strcmp(newcontext, oldcontext)) {
9707 stalecontext = oldcontext;
9711 if (stalecontext)
9712 ast_context_destroy(ast_context_find(stalecontext), "SIP");
9716 /*! \brief Remove temporary realtime objects from memory (CLI) */
9717 static int sip_prune_realtime(int fd, int argc, char *argv[])
9719 struct sip_peer *peer;
9720 struct sip_user *user;
9721 int pruneuser = FALSE;
9722 int prunepeer = FALSE;
9723 int multi = FALSE;
9724 char *name = NULL;
9725 regex_t regexbuf;
9727 switch (argc) {
9728 case 4:
9729 if (!strcasecmp(argv[3], "user"))
9730 return RESULT_SHOWUSAGE;
9731 if (!strcasecmp(argv[3], "peer"))
9732 return RESULT_SHOWUSAGE;
9733 if (!strcasecmp(argv[3], "like"))
9734 return RESULT_SHOWUSAGE;
9735 if (!strcasecmp(argv[3], "all")) {
9736 multi = TRUE;
9737 pruneuser = prunepeer = TRUE;
9738 } else {
9739 pruneuser = prunepeer = TRUE;
9740 name = argv[3];
9742 break;
9743 case 5:
9744 if (!strcasecmp(argv[4], "like"))
9745 return RESULT_SHOWUSAGE;
9746 if (!strcasecmp(argv[3], "all"))
9747 return RESULT_SHOWUSAGE;
9748 if (!strcasecmp(argv[3], "like")) {
9749 multi = TRUE;
9750 name = argv[4];
9751 pruneuser = prunepeer = TRUE;
9752 } else if (!strcasecmp(argv[3], "user")) {
9753 pruneuser = TRUE;
9754 if (!strcasecmp(argv[4], "all"))
9755 multi = TRUE;
9756 else
9757 name = argv[4];
9758 } else if (!strcasecmp(argv[3], "peer")) {
9759 prunepeer = TRUE;
9760 if (!strcasecmp(argv[4], "all"))
9761 multi = TRUE;
9762 else
9763 name = argv[4];
9764 } else
9765 return RESULT_SHOWUSAGE;
9766 break;
9767 case 6:
9768 if (strcasecmp(argv[4], "like"))
9769 return RESULT_SHOWUSAGE;
9770 if (!strcasecmp(argv[3], "user")) {
9771 pruneuser = TRUE;
9772 name = argv[5];
9773 } else if (!strcasecmp(argv[3], "peer")) {
9774 prunepeer = TRUE;
9775 name = argv[5];
9776 } else
9777 return RESULT_SHOWUSAGE;
9778 break;
9779 default:
9780 return RESULT_SHOWUSAGE;
9783 if (multi && name) {
9784 if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
9785 return RESULT_SHOWUSAGE;
9788 if (multi) {
9789 if (prunepeer) {
9790 int pruned = 0;
9792 ASTOBJ_CONTAINER_WRLOCK(&peerl);
9793 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
9794 ASTOBJ_RDLOCK(iterator);
9795 if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
9796 ASTOBJ_UNLOCK(iterator);
9797 continue;
9799 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
9800 ASTOBJ_MARK(iterator);
9801 pruned++;
9803 ASTOBJ_UNLOCK(iterator);
9804 } while (0) );
9805 if (pruned) {
9806 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
9807 ast_cli(fd, "%d peers pruned.\n", pruned);
9808 } else
9809 ast_cli(fd, "No peers found to prune.\n");
9810 ASTOBJ_CONTAINER_UNLOCK(&peerl);
9812 if (pruneuser) {
9813 int pruned = 0;
9815 ASTOBJ_CONTAINER_WRLOCK(&userl);
9816 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
9817 ASTOBJ_RDLOCK(iterator);
9818 if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
9819 ASTOBJ_UNLOCK(iterator);
9820 continue;
9822 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
9823 ASTOBJ_MARK(iterator);
9824 pruned++;
9826 ASTOBJ_UNLOCK(iterator);
9827 } while (0) );
9828 if (pruned) {
9829 ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, sip_destroy_user);
9830 ast_cli(fd, "%d users pruned.\n", pruned);
9831 } else
9832 ast_cli(fd, "No users found to prune.\n");
9833 ASTOBJ_CONTAINER_UNLOCK(&userl);
9835 } else {
9836 if (prunepeer) {
9837 if ((peer = ASTOBJ_CONTAINER_FIND_UNLINK(&peerl, name))) {
9838 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
9839 ast_cli(fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
9840 ASTOBJ_CONTAINER_LINK(&peerl, peer);
9841 } else
9842 ast_cli(fd, "Peer '%s' pruned.\n", name);
9843 ASTOBJ_UNREF(peer, sip_destroy_peer);
9844 } else
9845 ast_cli(fd, "Peer '%s' not found.\n", name);
9847 if (pruneuser) {
9848 if ((user = ASTOBJ_CONTAINER_FIND_UNLINK(&userl, name))) {
9849 if (!ast_test_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
9850 ast_cli(fd, "User '%s' is not a Realtime user, cannot be pruned.\n", name);
9851 ASTOBJ_CONTAINER_LINK(&userl, user);
9852 } else
9853 ast_cli(fd, "User '%s' pruned.\n", name);
9854 ASTOBJ_UNREF(user, sip_destroy_user);
9855 } else
9856 ast_cli(fd, "User '%s' not found.\n", name);
9860 return RESULT_SUCCESS;
9863 /*! \brief Print codec list from preference to CLI/manager */
9864 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
9866 int x, codec;
9868 for(x = 0; x < 32 ; x++) {
9869 codec = ast_codec_pref_index(pref, x);
9870 if (!codec)
9871 break;
9872 ast_cli(fd, "%s", ast_getformatname(codec));
9873 ast_cli(fd, ":%d", pref->framing[x]);
9874 if (x < 31 && ast_codec_pref_index(pref, x + 1))
9875 ast_cli(fd, ",");
9877 if (!x)
9878 ast_cli(fd, "none");
9881 /*! \brief Print domain mode to cli */
9882 static const char *domain_mode_to_text(const enum domain_mode mode)
9884 switch (mode) {
9885 case SIP_DOMAIN_AUTO:
9886 return "[Automatic]";
9887 case SIP_DOMAIN_CONFIG:
9888 return "[Configured]";
9891 return "";
9894 /*! \brief CLI command to list local domains */
9895 static int sip_show_domains(int fd, int argc, char *argv[])
9897 struct domain *d;
9898 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
9900 if (AST_LIST_EMPTY(&domain_list)) {
9901 ast_cli(fd, "SIP Domain support not enabled.\n\n");
9902 return RESULT_SUCCESS;
9903 } else {
9904 ast_cli(fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
9905 AST_LIST_LOCK(&domain_list);
9906 AST_LIST_TRAVERSE(&domain_list, d, list)
9907 ast_cli(fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
9908 domain_mode_to_text(d->mode));
9909 AST_LIST_UNLOCK(&domain_list);
9910 ast_cli(fd, "\n");
9911 return RESULT_SUCCESS;
9914 #undef FORMAT
9916 static char mandescr_show_peer[] =
9917 "Description: Show one SIP peer with details on current status.\n"
9918 "Variables: \n"
9919 " Peer: <name> The peer name you want to check.\n"
9920 " ActionID: <id> Optional action ID for this AMI transaction.\n";
9922 /*! \brief Show SIP peers in the manager API */
9923 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
9925 const char *id = astman_get_header(m,"ActionID");
9926 const char *a[4];
9927 const char *peer;
9928 int ret;
9930 peer = astman_get_header(m,"Peer");
9931 if (ast_strlen_zero(peer)) {
9932 astman_send_error(s, m, "Peer: <name> missing.\n");
9933 return 0;
9935 a[0] = "sip";
9936 a[1] = "show";
9937 a[2] = "peer";
9938 a[3] = peer;
9940 if (!ast_strlen_zero(id))
9941 astman_append(s, "ActionID: %s\r\n",id);
9942 ret = _sip_show_peer(1, -1, s, m, 4, a);
9943 astman_append(s, "\r\n\r\n" );
9944 return ret;
9949 /*! \brief Show one peer in detail */
9950 static int sip_show_peer(int fd, int argc, char *argv[])
9952 return _sip_show_peer(0, fd, NULL, NULL, argc, (const char **) argv);
9955 /*! \brief Show one peer in detail (main function) */
9956 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
9958 char status[30] = "";
9959 char cbuf[256];
9960 struct sip_peer *peer;
9961 char codec_buf[512];
9962 struct ast_codec_pref *pref;
9963 struct ast_variable *v;
9964 struct sip_auth *auth;
9965 int x = 0, codec = 0, load_realtime;
9966 int realtimepeers;
9968 realtimepeers = ast_check_realtime("sippeers");
9970 if (argc < 4)
9971 return RESULT_SHOWUSAGE;
9973 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
9974 peer = find_peer(argv[3], NULL, load_realtime);
9975 if (s) { /* Manager */
9976 if (peer)
9977 astman_append(s, "Response: Success\r\n");
9978 else {
9979 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.\n", argv[3]);
9980 astman_send_error(s, m, cbuf);
9981 return 0;
9984 if (peer && type==0 ) { /* Normal listing */
9985 ast_cli(fd,"\n\n");
9986 ast_cli(fd, " * Name : %s\n", peer->name);
9987 if (realtimepeers) { /* Realtime is enabled */
9988 ast_cli(fd, " Realtime peer: %s\n", ast_test_flag(&peer->flags[0], SIP_REALTIME) ? "Yes, cached" : "No");
9990 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
9991 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
9992 for (auth = peer->auth; auth; auth = auth->next) {
9993 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
9994 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
9996 ast_cli(fd, " Context : %s\n", peer->context);
9997 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
9998 ast_cli(fd, " Language : %s\n", peer->language);
9999 if (!ast_strlen_zero(peer->accountcode))
10000 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
10001 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
10002 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
10003 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
10004 if (!ast_strlen_zero(peer->fromuser))
10005 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
10006 if (!ast_strlen_zero(peer->fromdomain))
10007 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
10008 ast_cli(fd, " Callgroup : ");
10009 print_group(fd, peer->callgroup, 0);
10010 ast_cli(fd, " Pickupgroup : ");
10011 print_group(fd, peer->pickupgroup, 0);
10012 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
10013 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
10014 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
10015 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
10016 ast_cli(fd, " Dynamic : %s\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Yes":"No"));
10017 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
10018 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
10019 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
10020 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)));
10021 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
10022 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
10023 ast_cli(fd, " T38 pt UDPTL : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL)?"Yes":"No");
10024 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10025 ast_cli(fd, " T38 pt RTP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_RTP)?"Yes":"No");
10026 ast_cli(fd, " T38 pt TCP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_TCP)?"Yes":"No");
10027 #endif
10028 ast_cli(fd, " CanReinvite : %s\n", ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Yes":"No");
10029 ast_cli(fd, " PromiscRedir : %s\n", ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Yes":"No");
10030 ast_cli(fd, " User=Phone : %s\n", ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Yes":"No");
10031 ast_cli(fd, " Video Support: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Yes":"No");
10032 ast_cli(fd, " Trust RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_TRUSTRPID) ? "Yes" : "No");
10033 ast_cli(fd, " Send RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_SENDRPID) ? "Yes" : "No");
10034 ast_cli(fd, " Subscriptions: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
10035 ast_cli(fd, " Overlap dial : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
10037 /* - is enumerated */
10038 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
10039 ast_cli(fd, " LastMsg : %d\n", peer->lastmsg);
10040 ast_cli(fd, " ToHost : %s\n", peer->tohost);
10041 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));
10042 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
10043 if (!ast_strlen_zero(global_regcontext))
10044 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
10045 ast_cli(fd, " Def. Username: %s\n", peer->username);
10046 ast_cli(fd, " SIP Options : ");
10047 if (peer->sipoptions) {
10048 int lastoption = -1;
10049 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
10050 if (sip_options[x].id != lastoption) {
10051 if (peer->sipoptions & sip_options[x].id)
10052 ast_cli(fd, "%s ", sip_options[x].text);
10053 lastoption = x;
10056 } else
10057 ast_cli(fd, "(none)");
10059 ast_cli(fd, "\n");
10060 ast_cli(fd, " Codecs : ");
10061 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
10062 ast_cli(fd, "%s\n", codec_buf);
10063 ast_cli(fd, " Codec Order : (");
10064 print_codec_to_cli(fd, &peer->prefs);
10065 ast_cli(fd, ")\n");
10067 ast_cli(fd, " Auto-Framing: %s \n", peer->autoframing ? "Yes" : "No");
10068 ast_cli(fd, " Status : ");
10069 peer_status(peer, status, sizeof(status));
10070 ast_cli(fd, "%s\n",status);
10071 ast_cli(fd, " Useragent : %s\n", peer->useragent);
10072 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
10073 if (peer->chanvars) {
10074 ast_cli(fd, " Variables :\n");
10075 for (v = peer->chanvars ; v ; v = v->next)
10076 ast_cli(fd, " %s = %s\n", v->name, v->value);
10078 ast_cli(fd,"\n");
10079 ASTOBJ_UNREF(peer,sip_destroy_peer);
10080 } else if (peer && type == 1) { /* manager listing */
10081 char buf[256];
10082 astman_append(s, "Channeltype: SIP\r\n");
10083 astman_append(s, "ObjectName: %s\r\n", peer->name);
10084 astman_append(s, "ChanObjectType: peer\r\n");
10085 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
10086 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
10087 astman_append(s, "Context: %s\r\n", peer->context);
10088 astman_append(s, "Language: %s\r\n", peer->language);
10089 if (!ast_strlen_zero(peer->accountcode))
10090 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
10091 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
10092 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
10093 if (!ast_strlen_zero(peer->fromuser))
10094 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
10095 if (!ast_strlen_zero(peer->fromdomain))
10096 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
10097 astman_append(s, "Callgroup: ");
10098 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->callgroup));
10099 astman_append(s, "Pickupgroup: ");
10100 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->pickupgroup));
10101 astman_append(s, "VoiceMailbox: %s\r\n", peer->mailbox);
10102 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
10103 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
10104 astman_append(s, "Call limit: %d\r\n", peer->call_limit);
10105 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
10106 astman_append(s, "Dynamic: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Y":"N"));
10107 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
10108 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched,peer->expire));
10109 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)));
10110 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
10111 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
10112 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
10113 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
10114 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
10115 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
10117 /* - is enumerated */
10118 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
10119 astman_append(s, "SIPLastMsg: %d\r\n", peer->lastmsg);
10120 astman_append(s, "ToHost: %s\r\n", peer->tohost);
10121 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));
10122 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));
10123 astman_append(s, "Default-Username: %s\r\n", peer->username);
10124 if (!ast_strlen_zero(global_regcontext))
10125 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
10126 astman_append(s, "Codecs: ");
10127 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
10128 astman_append(s, "%s\r\n", codec_buf);
10129 astman_append(s, "CodecOrder: ");
10130 pref = &peer->prefs;
10131 for(x = 0; x < 32 ; x++) {
10132 codec = ast_codec_pref_index(pref,x);
10133 if (!codec)
10134 break;
10135 astman_append(s, "%s", ast_getformatname(codec));
10136 if (x < 31 && ast_codec_pref_index(pref,x+1))
10137 astman_append(s, ",");
10140 astman_append(s, "\r\n");
10141 astman_append(s, "Status: ");
10142 peer_status(peer, status, sizeof(status));
10143 astman_append(s, "%s\r\n", status);
10144 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
10145 astman_append(s, "Reg-Contact : %s\r\n", peer->fullcontact);
10146 if (peer->chanvars) {
10147 for (v = peer->chanvars ; v ; v = v->next) {
10148 astman_append(s, "ChanVariable:\n");
10149 astman_append(s, " %s,%s\r\n", v->name, v->value);
10153 ASTOBJ_UNREF(peer,sip_destroy_peer);
10155 } else {
10156 ast_cli(fd,"Peer %s not found.\n", argv[3]);
10157 ast_cli(fd,"\n");
10160 return RESULT_SUCCESS;
10163 /*! \brief Show one user in detail */
10164 static int sip_show_user(int fd, int argc, char *argv[])
10166 char cbuf[256];
10167 struct sip_user *user;
10168 struct ast_variable *v;
10169 int load_realtime;
10171 if (argc < 4)
10172 return RESULT_SHOWUSAGE;
10174 /* Load from realtime storage? */
10175 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
10177 user = find_user(argv[3], load_realtime);
10178 if (user) {
10179 ast_cli(fd,"\n\n");
10180 ast_cli(fd, " * Name : %s\n", user->name);
10181 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
10182 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
10183 ast_cli(fd, " Context : %s\n", user->context);
10184 ast_cli(fd, " Language : %s\n", user->language);
10185 if (!ast_strlen_zero(user->accountcode))
10186 ast_cli(fd, " Accountcode : %s\n", user->accountcode);
10187 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
10188 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
10189 ast_cli(fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
10190 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
10191 ast_cli(fd, " Call limit : %d\n", user->call_limit);
10192 ast_cli(fd, " Callgroup : ");
10193 print_group(fd, user->callgroup, 0);
10194 ast_cli(fd, " Pickupgroup : ");
10195 print_group(fd, user->pickupgroup, 0);
10196 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
10197 ast_cli(fd, " ACL : %s\n", (user->ha?"Yes":"No"));
10198 ast_cli(fd, " Codec Order : (");
10199 print_codec_to_cli(fd, &user->prefs);
10200 ast_cli(fd, ")\n");
10202 ast_cli(fd, " Auto-Framing: %s \n", user->autoframing ? "Yes" : "No");
10203 if (user->chanvars) {
10204 ast_cli(fd, " Variables :\n");
10205 for (v = user->chanvars ; v ; v = v->next)
10206 ast_cli(fd, " %s = %s\n", v->name, v->value);
10208 ast_cli(fd,"\n");
10209 ASTOBJ_UNREF(user,sip_destroy_user);
10210 } else {
10211 ast_cli(fd,"User %s not found.\n", argv[3]);
10212 ast_cli(fd,"\n");
10215 return RESULT_SUCCESS;
10218 /*! \brief Show SIP Registry (registrations with other SIP proxies */
10219 static int sip_show_registry(int fd, int argc, char *argv[])
10221 #define FORMAT2 "%-30.30s %-12.12s %8.8s %-20.20s %-25.25s\n"
10222 #define FORMAT "%-30.30s %-12.12s %8d %-20.20s %-25.25s\n"
10223 char host[80];
10224 char tmpdat[256];
10225 struct tm tm;
10228 if (argc != 3)
10229 return RESULT_SHOWUSAGE;
10230 ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State", "Reg.Time");
10231 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
10232 ASTOBJ_RDLOCK(iterator);
10233 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
10234 if (iterator->regtime) {
10235 ast_localtime(&iterator->regtime, &tm, NULL);
10236 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
10237 } else {
10238 tmpdat[0] = 0;
10240 ast_cli(fd, FORMAT, host, iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
10241 ASTOBJ_UNLOCK(iterator);
10242 } while(0));
10243 return RESULT_SUCCESS;
10244 #undef FORMAT
10245 #undef FORMAT2
10248 /*! \brief List global settings for the SIP channel */
10249 static int sip_show_settings(int fd, int argc, char *argv[])
10251 int realtimepeers;
10252 int realtimeusers;
10253 char codec_buf[BUFSIZ];
10255 realtimepeers = ast_check_realtime("sippeers");
10256 realtimeusers = ast_check_realtime("sipusers");
10258 if (argc != 3)
10259 return RESULT_SHOWUSAGE;
10260 ast_cli(fd, "\n\nGlobal Settings:\n");
10261 ast_cli(fd, "----------------\n");
10262 ast_cli(fd, " SIP Port: %d\n", ntohs(bindaddr.sin_port));
10263 ast_cli(fd, " Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
10264 ast_cli(fd, " Videosupport: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "Yes" : "No");
10265 ast_cli(fd, " AutoCreatePeer: %s\n", autocreatepeer ? "Yes" : "No");
10266 ast_cli(fd, " Allow unknown access: %s\n", global_allowguest ? "Yes" : "No");
10267 ast_cli(fd, " Allow subscriptions: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
10268 ast_cli(fd, " Allow overlap dialing: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
10269 ast_cli(fd, " Promsic. redir: %s\n", ast_test_flag(&global_flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
10270 ast_cli(fd, " SIP domain support: %s\n", AST_LIST_EMPTY(&domain_list) ? "No" : "Yes");
10271 ast_cli(fd, " Call to non-local dom.: %s\n", allow_external_domains ? "Yes" : "No");
10272 ast_cli(fd, " URI user is phone no: %s\n", ast_test_flag(&global_flags[0], SIP_USEREQPHONE) ? "Yes" : "No");
10273 ast_cli(fd, " Our auth realm %s\n", global_realm);
10274 ast_cli(fd, " Realm. auth: %s\n", authl ? "Yes": "No");
10275 ast_cli(fd, " Always auth rejects: %s\n", global_alwaysauthreject ? "Yes" : "No");
10276 ast_cli(fd, " Call limit peers only: %s\n", global_limitonpeers ? "Yes" : "No");
10277 ast_cli(fd, " Direct RTP setup: %s\n", global_directrtpsetup ? "Yes" : "No");
10278 ast_cli(fd, " User Agent: %s\n", global_useragent);
10279 ast_cli(fd, " MWI checking interval: %d secs\n", global_mwitime);
10280 ast_cli(fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
10281 ast_cli(fd, " Caller ID: %s\n", default_callerid);
10282 ast_cli(fd, " From: Domain: %s\n", default_fromdomain);
10283 ast_cli(fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
10284 ast_cli(fd, " Call Events: %s\n", global_callevents ? "On" : "Off");
10285 ast_cli(fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
10286 ast_cli(fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
10287 ast_cli(fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
10288 ast_cli(fd, " T38 fax pt UDPTL: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_UDPTL) ? "Yes" : "No");
10289 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10290 ast_cli(fd, " T38 fax pt RTP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_RTP) ? "Yes" : "No");
10291 ast_cli(fd, " T38 fax pt TCP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_TCP) ? "Yes" : "No");
10292 #endif
10293 ast_cli(fd, " RFC2833 Compensation: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE) ? "Yes" : "No");
10294 if (!realtimepeers && !realtimeusers)
10295 ast_cli(fd, " SIP realtime: Disabled\n" );
10296 else
10297 ast_cli(fd, " SIP realtime: Enabled\n" );
10299 ast_cli(fd, "\nGlobal Signalling Settings:\n");
10300 ast_cli(fd, "---------------------------\n");
10301 ast_cli(fd, " Codecs: ");
10302 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
10303 ast_cli(fd, "%s\n", codec_buf);
10304 ast_cli(fd, " Codec Order: ");
10305 print_codec_to_cli(fd, &default_prefs);
10306 ast_cli(fd, "\n");
10307 ast_cli(fd, " T1 minimum: %d\n", global_t1min);
10308 ast_cli(fd, " Relax DTMF: %s\n", global_relaxdtmf ? "Yes" : "No");
10309 ast_cli(fd, " Compact SIP headers: %s\n", compactheaders ? "Yes" : "No");
10310 ast_cli(fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
10311 ast_cli(fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
10312 ast_cli(fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
10313 ast_cli(fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
10314 ast_cli(fd, " DNS SRV lookup: %s\n", srvlookup ? "Yes" : "No");
10315 ast_cli(fd, " Pedantic SIP support: %s\n", pedanticsipchecking ? "Yes" : "No");
10316 ast_cli(fd, " Reg. min duration %d secs\n", min_expiry);
10317 ast_cli(fd, " Reg. max duration: %d secs\n", max_expiry);
10318 ast_cli(fd, " Reg. default duration: %d secs\n", default_expiry);
10319 ast_cli(fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
10320 ast_cli(fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
10321 ast_cli(fd, " Notify ringing state: %s\n", global_notifyringing ? "Yes" : "No");
10322 ast_cli(fd, " Notify hold state: %s\n", global_notifyhold ? "Yes" : "No");
10323 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(global_allowtransfer));
10324 ast_cli(fd, " Max Call Bitrate: %d kbps\r\n", default_maxcallbitrate);
10325 ast_cli(fd, " Auto-Framing: %s \r\n", global_autoframing ? "Yes" : "No");
10326 ast_cli(fd, "\nDefault Settings:\n");
10327 ast_cli(fd, "-----------------\n");
10328 ast_cli(fd, " Context: %s\n", default_context);
10329 ast_cli(fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
10330 ast_cli(fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
10331 ast_cli(fd, " Qualify: %d\n", default_qualify);
10332 ast_cli(fd, " Use ClientCode: %s\n", ast_test_flag(&global_flags[0], SIP_USECLIENTCODE) ? "Yes" : "No");
10333 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" );
10334 ast_cli(fd, " Language: %s\n", S_OR(default_language, "(Defaults to English)"));
10335 ast_cli(fd, " MOH Interpret: %s\n", default_mohinterpret);
10336 ast_cli(fd, " MOH Suggest: %s\n", default_mohsuggest);
10337 ast_cli(fd, " Voice Mail Extension: %s\n", default_vmexten);
10340 if (realtimepeers || realtimeusers) {
10341 ast_cli(fd, "\nRealtime SIP Settings:\n");
10342 ast_cli(fd, "----------------------\n");
10343 ast_cli(fd, " Realtime Peers: %s\n", realtimepeers ? "Yes" : "No");
10344 ast_cli(fd, " Realtime Users: %s\n", realtimeusers ? "Yes" : "No");
10345 ast_cli(fd, " Cache Friends: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? "Yes" : "No");
10346 ast_cli(fd, " Update: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) ? "Yes" : "No");
10347 ast_cli(fd, " Ignore Reg. Expire: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) ? "Yes" : "No");
10348 ast_cli(fd, " Save sys. name: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME) ? "Yes" : "No");
10349 ast_cli(fd, " Auto Clear: %d\n", global_rtautoclear);
10351 ast_cli(fd, "\n----\n");
10352 return RESULT_SUCCESS;
10355 /*! \brief Show subscription type in string format */
10356 static const char *subscription_type2str(enum subscriptiontype subtype)
10358 int i;
10360 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10361 if (subscription_types[i].type == subtype) {
10362 return subscription_types[i].text;
10365 return subscription_types[0].text;
10368 /*! \brief Find subscription type in array */
10369 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
10371 int i;
10373 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10374 if (subscription_types[i].type == subtype) {
10375 return &subscription_types[i];
10378 return &subscription_types[0];
10381 /*! \brief Show active SIP channels */
10382 static int sip_show_channels(int fd, int argc, char *argv[])
10384 return __sip_show_channels(fd, argc, argv, 0);
10387 /*! \brief Show active SIP subscriptions */
10388 static int sip_show_subscriptions(int fd, int argc, char *argv[])
10390 return __sip_show_channels(fd, argc, argv, 1);
10393 /*! \brief SIP show channels CLI (main function) */
10394 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions)
10396 #define FORMAT3 "%-15.15s %-10.10s %-11.11s %-15.15s %-13.13s %-15.15s %-10.10s\n"
10397 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-4.4s %-7.7s %-15.15s\n"
10398 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-4.4s %-3.3s %-3.3s %-15.15s %-10.10s\n"
10399 struct sip_pvt *cur;
10400 int numchans = 0;
10401 char *referstatus = NULL;
10403 if (argc != 3)
10404 return RESULT_SHOWUSAGE;
10405 ast_mutex_lock(&iflock);
10406 cur = iflist;
10407 if (!subscriptions)
10408 ast_cli(fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Seq (Tx/Rx)", "Format", "Hold", "Last Message");
10409 else
10410 ast_cli(fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox");
10411 for (; cur; cur = cur->next) {
10412 referstatus = "";
10413 if (cur->refer) { /* SIP transfer in progress */
10414 referstatus = referstatus2str(cur->refer->status);
10416 if (cur->subscribed == NONE && !subscriptions) {
10417 ast_cli(fd, FORMAT, ast_inet_ntoa(cur->sa.sin_addr),
10418 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10419 cur->callid,
10420 cur->ocseq, cur->icseq,
10421 ast_getformatname(cur->owner ? cur->owner->nativeformats : 0),
10422 ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD) ? "Yes" : "No",
10423 ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY) ? "(d)" : "",
10424 cur->lastmsg ,
10425 referstatus
10427 numchans++;
10429 if (cur->subscribed != NONE && subscriptions) {
10430 ast_cli(fd, FORMAT3, ast_inet_ntoa(cur->sa.sin_addr),
10431 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10432 cur->callid,
10433 /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
10434 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
10435 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
10436 subscription_type2str(cur->subscribed),
10437 cur->subscribed == MWI_NOTIFICATION ? (cur->relatedpeer ? cur->relatedpeer->mailbox : "<none>") : "<none>"
10439 numchans++;
10442 ast_mutex_unlock(&iflock);
10443 if (!subscriptions)
10444 ast_cli(fd, "%d active SIP channel%s\n", numchans, (numchans != 1) ? "s" : "");
10445 else
10446 ast_cli(fd, "%d active SIP subscription%s\n", numchans, (numchans != 1) ? "s" : "");
10447 return RESULT_SUCCESS;
10448 #undef FORMAT
10449 #undef FORMAT2
10450 #undef FORMAT3
10453 /*! \brief Support routine for 'sip show channel' CLI */
10454 static char *complete_sipch(const char *line, const char *word, int pos, int state)
10456 int which=0;
10457 struct sip_pvt *cur;
10458 char *c = NULL;
10459 int wordlen = strlen(word);
10461 ast_mutex_lock(&iflock);
10462 for (cur = iflist; cur; cur = cur->next) {
10463 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
10464 c = ast_strdup(cur->callid);
10465 break;
10468 ast_mutex_unlock(&iflock);
10469 return c;
10472 /*! \brief Do completion on peer name */
10473 static char *complete_sip_peer(const char *word, int state, int flags2)
10475 char *result = NULL;
10476 int wordlen = strlen(word);
10477 int which = 0;
10479 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !result, do {
10480 /* locking of the object is not required because only the name and flags are being compared */
10481 if (!strncasecmp(word, iterator->name, wordlen) &&
10482 (!flags2 || ast_test_flag(&iterator->flags[1], flags2)) &&
10483 ++which > state)
10484 result = ast_strdup(iterator->name);
10485 } while(0) );
10486 return result;
10489 /*! \brief Support routine for 'sip show peer' CLI */
10490 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
10492 if (pos == 3)
10493 return complete_sip_peer(word, state, 0);
10495 return NULL;
10498 /*! \brief Support routine for 'sip debug peer' CLI */
10499 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state)
10501 if (pos == 3)
10502 return complete_sip_peer(word, state, 0);
10504 return NULL;
10507 /*! \brief Do completion on user name */
10508 static char *complete_sip_user(const char *word, int state, int flags2)
10510 char *result = NULL;
10511 int wordlen = strlen(word);
10512 int which = 0;
10514 ASTOBJ_CONTAINER_TRAVERSE(&userl, !result, do {
10515 /* locking of the object is not required because only the name and flags are being compared */
10516 if (!strncasecmp(word, iterator->name, wordlen)) {
10517 if (flags2 && !ast_test_flag(&iterator->flags[1], flags2))
10518 continue;
10519 if (++which > state) {
10520 result = ast_strdup(iterator->name);
10523 } while(0) );
10524 return result;
10527 /*! \brief Support routine for 'sip show user' CLI */
10528 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
10530 if (pos == 3)
10531 return complete_sip_user(word, state, 0);
10533 return NULL;
10536 /*! \brief Support routine for 'sip notify' CLI */
10537 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
10539 char *c = NULL;
10541 if (pos == 2) {
10542 int which = 0;
10543 char *cat = NULL;
10544 int wordlen = strlen(word);
10546 /* do completion for notify type */
10548 if (!notify_types)
10549 return NULL;
10551 while ( (cat = ast_category_browse(notify_types, cat)) ) {
10552 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
10553 c = ast_strdup(cat);
10554 break;
10557 return c;
10560 if (pos > 2)
10561 return complete_sip_peer(word, state, 0);
10563 return NULL;
10566 /*! \brief Support routine for 'sip prune realtime peer' CLI */
10567 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state)
10569 if (pos == 4)
10570 return complete_sip_peer(word, state, SIP_PAGE2_RTCACHEFRIENDS);
10571 return NULL;
10574 /*! \brief Support routine for 'sip prune realtime user' CLI */
10575 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state)
10577 if (pos == 4)
10578 return complete_sip_user(word, state, SIP_PAGE2_RTCACHEFRIENDS);
10580 return NULL;
10583 /*! \brief Show details of one active dialog */
10584 static int sip_show_channel(int fd, int argc, char *argv[])
10586 struct sip_pvt *cur;
10587 size_t len;
10588 int found = 0;
10590 if (argc != 4)
10591 return RESULT_SHOWUSAGE;
10592 len = strlen(argv[3]);
10593 ast_mutex_lock(&iflock);
10594 for (cur = iflist; cur; cur = cur->next) {
10595 if (!strncasecmp(cur->callid, argv[3], len)) {
10596 char formatbuf[BUFSIZ/2];
10597 ast_cli(fd,"\n");
10598 if (cur->subscribed != NONE)
10599 ast_cli(fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
10600 else
10601 ast_cli(fd, " * SIP Call\n");
10602 ast_cli(fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
10603 ast_cli(fd, " Call-ID: %s\n", cur->callid);
10604 ast_cli(fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
10605 ast_cli(fd, " Our Codec Capability: %d\n", cur->capability);
10606 ast_cli(fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
10607 ast_cli(fd, " Their Codec Capability: %d\n", cur->peercapability);
10608 ast_cli(fd, " Joint Codec Capability: %d\n", cur->jointcapability);
10609 ast_cli(fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
10610 ast_cli(fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
10611 ast_cli(fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
10612 ast_cli(fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
10613 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
10614 ast_cli(fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
10615 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)" );
10616 ast_cli(fd, " Our Tag: %s\n", cur->tag);
10617 ast_cli(fd, " Their Tag: %s\n", cur->theirtag);
10618 ast_cli(fd, " SIP User agent: %s\n", cur->useragent);
10619 if (!ast_strlen_zero(cur->username))
10620 ast_cli(fd, " Username: %s\n", cur->username);
10621 if (!ast_strlen_zero(cur->peername))
10622 ast_cli(fd, " Peername: %s\n", cur->peername);
10623 if (!ast_strlen_zero(cur->uri))
10624 ast_cli(fd, " Original uri: %s\n", cur->uri);
10625 if (!ast_strlen_zero(cur->cid_num))
10626 ast_cli(fd, " Caller-ID: %s\n", cur->cid_num);
10627 ast_cli(fd, " Need Destroy: %d\n", ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY));
10628 ast_cli(fd, " Last Message: %s\n", cur->lastmsg);
10629 ast_cli(fd, " Promiscuous Redir: %s\n", ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
10630 ast_cli(fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
10631 ast_cli(fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
10632 ast_cli(fd, " SIP Options: ");
10633 if (cur->sipoptions) {
10634 int x;
10635 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
10636 if (cur->sipoptions & sip_options[x].id)
10637 ast_cli(fd, "%s ", sip_options[x].text);
10639 } else
10640 ast_cli(fd, "(none)\n");
10641 ast_cli(fd, "\n\n");
10642 found++;
10645 ast_mutex_unlock(&iflock);
10646 if (!found)
10647 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
10648 return RESULT_SUCCESS;
10651 /*! \brief Show history details of one dialog */
10652 static int sip_show_history(int fd, int argc, char *argv[])
10654 struct sip_pvt *cur;
10655 size_t len;
10656 int found = 0;
10658 if (argc != 4)
10659 return RESULT_SHOWUSAGE;
10660 if (!recordhistory)
10661 ast_cli(fd, "\n***Note: History recording is currently DISABLED. Use 'sip history' to ENABLE.\n");
10662 len = strlen(argv[3]);
10663 ast_mutex_lock(&iflock);
10664 for (cur = iflist; cur; cur = cur->next) {
10665 if (!strncasecmp(cur->callid, argv[3], len)) {
10666 struct sip_history *hist;
10667 int x = 0;
10669 ast_cli(fd,"\n");
10670 if (cur->subscribed != NONE)
10671 ast_cli(fd, " * Subscription\n");
10672 else
10673 ast_cli(fd, " * SIP Call\n");
10674 if (cur->history)
10675 AST_LIST_TRAVERSE(cur->history, hist, list)
10676 ast_cli(fd, "%d. %s\n", ++x, hist->event);
10677 if (x == 0)
10678 ast_cli(fd, "Call '%s' has no history\n", cur->callid);
10679 found++;
10682 ast_mutex_unlock(&iflock);
10683 if (!found)
10684 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
10685 return RESULT_SUCCESS;
10688 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
10689 static void sip_dump_history(struct sip_pvt *dialog)
10691 int x = 0;
10692 struct sip_history *hist;
10693 static int errmsg = 0;
10695 if (!dialog)
10696 return;
10698 if (!option_debug && !sipdebug) {
10699 if (!errmsg) {
10700 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
10701 errmsg = 1;
10703 return;
10706 ast_log(LOG_DEBUG, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
10707 if (dialog->subscribed)
10708 ast_log(LOG_DEBUG, " * Subscription\n");
10709 else
10710 ast_log(LOG_DEBUG, " * SIP Call\n");
10711 if (dialog->history)
10712 AST_LIST_TRAVERSE(dialog->history, hist, list)
10713 ast_log(LOG_DEBUG, " %-3.3d. %s\n", ++x, hist->event);
10714 if (!x)
10715 ast_log(LOG_DEBUG, "Call '%s' has no history\n", dialog->callid);
10716 ast_log(LOG_DEBUG, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
10720 /*! \brief Receive SIP INFO Message
10721 \note Doesn't read the duration of the DTMF signal */
10722 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
10724 char buf[1024];
10725 unsigned int event;
10726 const char *c = get_header(req, "Content-Type");
10728 /* Need to check the media/type */
10729 if (!strcasecmp(c, "application/dtmf-relay") ||
10730 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
10731 unsigned int duration = 0;
10733 /* Try getting the "signal=" part */
10734 if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
10735 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
10736 transmit_response(p, "200 OK", req); /* Should return error */
10737 return;
10738 } else {
10739 ast_copy_string(buf, c, sizeof(buf));
10742 if (!ast_strlen_zero((c = get_body(req, "Duration"))))
10743 duration = atoi(c);
10744 if (!duration)
10745 duration = 100; /* 100 ms */
10747 if (!p->owner) { /* not a PBX call */
10748 transmit_response(p, "481 Call leg/transaction does not exist", req);
10749 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
10750 return;
10753 if (ast_strlen_zero(buf)) {
10754 transmit_response(p, "200 OK", req);
10755 return;
10758 if (buf[0] == '*')
10759 event = 10;
10760 else if (buf[0] == '#')
10761 event = 11;
10762 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
10763 event = 12 + buf[0] - 'A';
10764 else
10765 event = atoi(buf);
10766 if (event == 16) {
10767 /* send a FLASH event */
10768 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
10769 ast_queue_frame(p->owner, &f);
10770 if (sipdebug)
10771 ast_verbose("* DTMF-relay event received: FLASH\n");
10772 } else {
10773 /* send a DTMF event */
10774 struct ast_frame f = { AST_FRAME_DTMF, };
10775 if (event < 10) {
10776 f.subclass = '0' + event;
10777 } else if (event < 11) {
10778 f.subclass = '*';
10779 } else if (event < 12) {
10780 f.subclass = '#';
10781 } else if (event < 16) {
10782 f.subclass = 'A' + (event - 12);
10784 f.len = duration;
10785 ast_queue_frame(p->owner, &f);
10786 if (sipdebug)
10787 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
10789 transmit_response(p, "200 OK", req);
10790 return;
10791 } else if (!strcasecmp(c, "application/media_control+xml")) {
10792 /* Eh, we'll just assume it's a fast picture update for now */
10793 if (p->owner)
10794 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
10795 transmit_response(p, "200 OK", req);
10796 return;
10797 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
10798 /* Client code (from SNOM phone) */
10799 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
10800 if (p->owner && p->owner->cdr)
10801 ast_cdr_setuserfield(p->owner, c);
10802 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
10803 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
10804 transmit_response(p, "200 OK", req);
10805 } else {
10806 transmit_response(p, "403 Unauthorized", req);
10808 return;
10810 /* Other type of INFO message, not really understood by Asterisk */
10811 /* if (get_msg_text(buf, sizeof(buf), req)) { */
10813 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
10814 transmit_response(p, "415 Unsupported media type", req);
10815 return;
10818 /*! \brief Enable SIP Debugging in CLI */
10819 static int sip_do_debug_ip(int fd, int argc, char *argv[])
10821 struct hostent *hp;
10822 struct ast_hostent ahp;
10823 int port = 0;
10824 char *p, *arg;
10826 /* sip set debug ip <ip> */
10827 if (argc != 5)
10828 return RESULT_SHOWUSAGE;
10829 p = arg = argv[4];
10830 strsep(&p, ":");
10831 if (p)
10832 port = atoi(p);
10833 hp = ast_gethostbyname(arg, &ahp);
10834 if (hp == NULL)
10835 return RESULT_SHOWUSAGE;
10837 debugaddr.sin_family = AF_INET;
10838 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
10839 debugaddr.sin_port = htons(port);
10840 if (port == 0)
10841 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
10842 else
10843 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
10845 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
10847 return RESULT_SUCCESS;
10850 /*! \brief sip_do_debug_peer: Turn on SIP debugging with peer mask */
10851 static int sip_do_debug_peer(int fd, int argc, char *argv[])
10853 struct sip_peer *peer;
10854 if (argc != 5)
10855 return RESULT_SHOWUSAGE;
10856 peer = find_peer(argv[4], NULL, 1);
10857 if (peer) {
10858 if (peer->addr.sin_addr.s_addr) {
10859 debugaddr.sin_family = AF_INET;
10860 debugaddr.sin_addr = peer->addr.sin_addr;
10861 debugaddr.sin_port = peer->addr.sin_port;
10862 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
10863 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
10864 } else
10865 ast_cli(fd, "Unable to get IP address of peer '%s'\n", argv[4]);
10866 ASTOBJ_UNREF(peer,sip_destroy_peer);
10867 } else
10868 ast_cli(fd, "No such peer '%s'\n", argv[4]);
10869 return RESULT_SUCCESS;
10872 /*! \brief Turn on SIP debugging (CLI command) */
10873 static int sip_do_debug(int fd, int argc, char *argv[])
10875 int oldsipdebug = sipdebug_console;
10876 if (argc != 3) {
10877 if (argc != 5)
10878 return RESULT_SHOWUSAGE;
10879 else if (strcmp(argv[3], "ip") == 0)
10880 return sip_do_debug_ip(fd, argc, argv);
10881 else if (strcmp(argv[3], "peer") == 0)
10882 return sip_do_debug_peer(fd, argc, argv);
10883 else
10884 return RESULT_SHOWUSAGE;
10886 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
10887 memset(&debugaddr, 0, sizeof(debugaddr));
10888 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
10889 return RESULT_SUCCESS;
10892 static int sip_do_debug_deprecated(int fd, int argc, char *argv[])
10894 int oldsipdebug = sipdebug_console;
10895 char *newargv[6] = { "sip", "set", "debug", NULL };
10896 if (argc != 2) {
10897 if (argc != 4)
10898 return RESULT_SHOWUSAGE;
10899 else if (strcmp(argv[2], "ip") == 0) {
10900 newargv[3] = argv[2];
10901 newargv[4] = argv[3];
10902 return sip_do_debug_ip(fd, argc + 1, newargv);
10903 } else if (strcmp(argv[2], "peer") == 0) {
10904 newargv[3] = argv[2];
10905 newargv[4] = argv[3];
10906 return sip_do_debug_peer(fd, argc + 1, newargv);
10907 } else
10908 return RESULT_SHOWUSAGE;
10910 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
10911 memset(&debugaddr, 0, sizeof(debugaddr));
10912 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
10913 return RESULT_SUCCESS;
10916 /*! \brief Cli command to send SIP notify to peer */
10917 static int sip_notify(int fd, int argc, char *argv[])
10919 struct ast_variable *varlist;
10920 int i;
10922 if (argc < 4)
10923 return RESULT_SHOWUSAGE;
10925 if (!notify_types) {
10926 ast_cli(fd, "No %s file found, or no types listed there\n", notify_config);
10927 return RESULT_FAILURE;
10930 varlist = ast_variable_browse(notify_types, argv[2]);
10932 if (!varlist) {
10933 ast_cli(fd, "Unable to find notify type '%s'\n", argv[2]);
10934 return RESULT_FAILURE;
10937 for (i = 3; i < argc; i++) {
10938 struct sip_pvt *p;
10939 struct sip_request req;
10940 struct ast_variable *var;
10942 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY))) {
10943 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
10944 return RESULT_FAILURE;
10947 if (create_addr(p, argv[i])) {
10948 /* Maybe they're not registered, etc. */
10949 sip_destroy(p);
10950 ast_cli(fd, "Could not create address for '%s'\n", argv[i]);
10951 continue;
10954 initreqprep(&req, p, SIP_NOTIFY);
10956 for (var = varlist; var; var = var->next)
10957 add_header(&req, var->name, var->value);
10959 /* Recalculate our side, and recalculate Call ID */
10960 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
10961 p->ourip = __ourip;
10962 build_via(p);
10963 build_callid_pvt(p);
10964 ast_cli(fd, "Sending NOTIFY of type '%s' to '%s'\n", argv[2], argv[i]);
10965 transmit_sip_request(p, &req);
10966 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
10969 return RESULT_SUCCESS;
10972 /*! \brief Disable SIP Debugging in CLI */
10973 static int sip_no_debug(int fd, int argc, char *argv[])
10975 if (argc != 4)
10976 return RESULT_SHOWUSAGE;
10977 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
10978 ast_cli(fd, "SIP Debugging Disabled\n");
10979 return RESULT_SUCCESS;
10982 static int sip_no_debug_deprecated(int fd, int argc, char *argv[])
10984 if (argc != 3)
10985 return RESULT_SHOWUSAGE;
10986 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
10987 ast_cli(fd, "SIP Debugging Disabled\n");
10988 return RESULT_SUCCESS;
10991 /*! \brief Enable SIP History logging (CLI) */
10992 static int sip_do_history(int fd, int argc, char *argv[])
10994 if (argc != 2) {
10995 return RESULT_SHOWUSAGE;
10997 recordhistory = TRUE;
10998 ast_cli(fd, "SIP History Recording Enabled (use 'sip show history')\n");
10999 return RESULT_SUCCESS;
11002 /*! \brief Disable SIP History logging (CLI) */
11003 static int sip_no_history(int fd, int argc, char *argv[])
11005 if (argc != 3) {
11006 return RESULT_SHOWUSAGE;
11008 recordhistory = FALSE;
11009 ast_cli(fd, "SIP History Recording Disabled\n");
11010 return RESULT_SUCCESS;
11013 /*! \brief Authenticate for outbound registration */
11014 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader)
11016 char digest[1024];
11017 p->authtries++;
11018 memset(digest,0,sizeof(digest));
11019 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
11020 /* There's nothing to use for authentication */
11021 /* No digest challenge in request */
11022 if (sip_debug_test_pvt(p) && p->registry)
11023 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
11024 /* No old challenge */
11025 return -1;
11027 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
11028 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
11029 if (sip_debug_test_pvt(p) && p->registry)
11030 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
11031 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
11034 /*! \brief Add authentication on outbound SIP packet */
11035 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init)
11037 char digest[1024];
11039 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
11040 return -2;
11042 p->authtries++;
11043 if (option_debug > 1)
11044 ast_log(LOG_DEBUG, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
11045 memset(digest, 0, sizeof(digest));
11046 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
11047 /* No way to authenticate */
11048 return -1;
11050 /* Now we have a reply digest */
11051 p->options->auth = digest;
11052 p->options->authheader = respheader;
11053 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
11056 /*! \brief reply to authentication for outbound registrations
11057 \return Returns -1 if we have no auth
11058 \note This is used for register= servers in sip.conf, SIP proxies we register
11059 with for receiving calls from. */
11060 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
11062 char tmp[512];
11063 char *c;
11064 char oldnonce[256];
11066 /* table of recognised keywords, and places where they should be copied */
11067 const struct x {
11068 const char *key;
11069 int field_index;
11070 } *i, keys[] = {
11071 { "realm=", ast_string_field_index(p, realm) },
11072 { "nonce=", ast_string_field_index(p, nonce) },
11073 { "opaque=", ast_string_field_index(p, opaque) },
11074 { "qop=", ast_string_field_index(p, qop) },
11075 { "domain=", ast_string_field_index(p, domain) },
11076 { NULL, 0 },
11079 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
11080 if (ast_strlen_zero(tmp))
11081 return -1;
11082 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
11083 ast_log(LOG_WARNING, "missing Digest.\n");
11084 return -1;
11086 c = tmp + strlen("Digest ");
11087 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
11088 while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
11089 for (i = keys; i->key != NULL; i++) {
11090 char *src, *separator;
11091 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
11092 continue;
11093 /* Found. Skip keyword, take text in quotes or up to the separator. */
11094 c += strlen(i->key);
11095 if (*c == '"') {
11096 src = ++c;
11097 separator = "\"";
11098 } else {
11099 src = c;
11100 separator = ",";
11102 strsep(&c, separator); /* clear separator and move ptr */
11103 ast_string_field_index_set(p, i->field_index, src);
11104 break;
11106 if (i->key == NULL) /* not found, try ',' */
11107 strsep(&c, ",");
11109 /* Reset nonce count */
11110 if (strcmp(p->nonce, oldnonce))
11111 p->noncecount = 0;
11113 /* Save auth data for following registrations */
11114 if (p->registry) {
11115 struct sip_registry *r = p->registry;
11117 if (strcmp(r->nonce, p->nonce)) {
11118 ast_string_field_set(r, realm, p->realm);
11119 ast_string_field_set(r, nonce, p->nonce);
11120 ast_string_field_set(r, domain, p->domain);
11121 ast_string_field_set(r, opaque, p->opaque);
11122 ast_string_field_set(r, qop, p->qop);
11123 r->noncecount = 0;
11126 return build_reply_digest(p, sipmethod, digest, digest_len);
11129 /*! \brief Build reply digest
11130 \return Returns -1 if we have no auth
11131 \note Build digest challenge for authentication of peers (for registration)
11132 and users (for calls). Also used for authentication of CANCEL and BYE
11134 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
11136 char a1[256];
11137 char a2[256];
11138 char a1_hash[256];
11139 char a2_hash[256];
11140 char resp[256];
11141 char resp_hash[256];
11142 char uri[256];
11143 char cnonce[80];
11144 const char *username;
11145 const char *secret;
11146 const char *md5secret;
11147 struct sip_auth *auth = NULL; /* Realm authentication */
11149 if (!ast_strlen_zero(p->domain))
11150 ast_copy_string(uri, p->domain, sizeof(uri));
11151 else if (!ast_strlen_zero(p->uri))
11152 ast_copy_string(uri, p->uri, sizeof(uri));
11153 else
11154 snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, ast_inet_ntoa(p->sa.sin_addr));
11156 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
11158 /* Check if we have separate auth credentials */
11159 if ((auth = find_realm_authentication(authl, p->realm))) {
11160 ast_log(LOG_WARNING, "use realm [%s] from peer [%s][%s]\n",
11161 auth->username, p->peername, p->username);
11162 username = auth->username;
11163 secret = auth->secret;
11164 md5secret = auth->md5secret;
11165 if (sipdebug)
11166 ast_log(LOG_DEBUG,"Using realm %s authentication for call %s\n", p->realm, p->callid);
11167 } else {
11168 /* No authentication, use peer or register= config */
11169 username = p->authname;
11170 secret = p->peersecret;
11171 md5secret = p->peermd5secret;
11173 if (ast_strlen_zero(username)) /* We have no authentication */
11174 return -1;
11176 /* Calculate SIP digest response */
11177 snprintf(a1,sizeof(a1),"%s:%s:%s", username, p->realm, secret);
11178 snprintf(a2,sizeof(a2),"%s:%s", sip_methods[method].text, uri);
11179 if (!ast_strlen_zero(md5secret))
11180 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
11181 else
11182 ast_md5_hash(a1_hash,a1);
11183 ast_md5_hash(a2_hash,a2);
11185 p->noncecount++;
11186 if (!ast_strlen_zero(p->qop))
11187 snprintf(resp,sizeof(resp),"%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
11188 else
11189 snprintf(resp,sizeof(resp),"%s:%s:%s", a1_hash, p->nonce, a2_hash);
11190 ast_md5_hash(resp_hash, resp);
11191 /* XXX We hard code our qop to "auth" for now. XXX */
11192 if (!ast_strlen_zero(p->qop))
11193 snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\", opaque=\"%s\", qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, p->opaque, cnonce, p->noncecount);
11194 else
11195 snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\", opaque=\"%s\"", username, p->realm, uri, p->nonce, resp_hash, p->opaque);
11197 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
11199 return 0;
11202 static char show_domains_usage[] =
11203 "Usage: sip show domains\n"
11204 " Lists all configured SIP local domains.\n"
11205 " Asterisk only responds to SIP messages to local domains.\n";
11207 static char notify_usage[] =
11208 "Usage: sip notify <type> <peer> [<peer>...]\n"
11209 " Send a NOTIFY message to a SIP peer or peers\n"
11210 " Message types are defined in sip_notify.conf\n";
11212 static char show_users_usage[] =
11213 "Usage: sip show users [like <pattern>]\n"
11214 " Lists all known SIP users.\n"
11215 " Optional regular expression pattern is used to filter the user list.\n";
11217 static char show_user_usage[] =
11218 "Usage: sip show user <name> [load]\n"
11219 " Shows all details on one SIP user and the current status.\n"
11220 " Option \"load\" forces lookup of peer in realtime storage.\n";
11222 static char show_inuse_usage[] =
11223 "Usage: sip show inuse [all]\n"
11224 " List all SIP users and peers usage counters and limits.\n"
11225 " Add option \"all\" to show all devices, not only those with a limit.\n";
11227 static char show_channels_usage[] =
11228 "Usage: sip show channels\n"
11229 " Lists all currently active SIP channels.\n";
11231 static char show_channel_usage[] =
11232 "Usage: sip show channel <channel>\n"
11233 " Provides detailed status on a given SIP channel.\n";
11235 static char show_history_usage[] =
11236 "Usage: sip show history <channel>\n"
11237 " Provides detailed dialog history on a given SIP channel.\n";
11239 static char show_peers_usage[] =
11240 "Usage: sip show peers [like <pattern>]\n"
11241 " Lists all known SIP peers.\n"
11242 " Optional regular expression pattern is used to filter the peer list.\n";
11244 static char show_peer_usage[] =
11245 "Usage: sip show peer <name> [load]\n"
11246 " Shows all details on one SIP peer and the current status.\n"
11247 " Option \"load\" forces lookup of peer in realtime storage.\n";
11249 static char prune_realtime_usage[] =
11250 "Usage: sip prune realtime [peer|user] [<name>|all|like <pattern>]\n"
11251 " Prunes object(s) from the cache.\n"
11252 " Optional regular expression pattern is used to filter the objects.\n";
11254 static char show_reg_usage[] =
11255 "Usage: sip show registry\n"
11256 " Lists all registration requests and status.\n";
11258 static char debug_usage[] =
11259 "Usage: sip set debug\n"
11260 " Enables dumping of SIP packets for debugging purposes\n\n"
11261 " sip set debug ip <host[:PORT]>\n"
11262 " Enables dumping of SIP packets to and from host.\n\n"
11263 " sip set debug peer <peername>\n"
11264 " Enables dumping of SIP packets to and from host.\n"
11265 " Require peer to be registered.\n";
11267 static char no_debug_usage[] =
11268 "Usage: sip set debug off\n"
11269 " Disables dumping of SIP packets for debugging purposes\n";
11271 static char no_history_usage[] =
11272 "Usage: sip history off\n"
11273 " Disables recording of SIP dialog history for debugging purposes\n";
11275 static char history_usage[] =
11276 "Usage: sip history\n"
11277 " Enables recording of SIP dialog history for debugging purposes.\n"
11278 "Use 'sip show history' to view the history of a call number.\n";
11280 static char sip_reload_usage[] =
11281 "Usage: sip reload\n"
11282 " Reloads SIP configuration from sip.conf\n";
11284 static char show_subscriptions_usage[] =
11285 "Usage: sip show subscriptions\n"
11286 " Lists active SIP subscriptions for extension states\n";
11288 static char show_objects_usage[] =
11289 "Usage: sip show objects\n"
11290 " Lists status of known SIP objects\n";
11292 static char show_settings_usage[] =
11293 "Usage: sip show settings\n"
11294 " Provides detailed list of the configuration of the SIP channel.\n";
11296 /*! \brief Read SIP header (dialplan function) */
11297 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len)
11299 struct sip_pvt *p;
11300 const char *content = NULL;
11301 AST_DECLARE_APP_ARGS(args,
11302 AST_APP_ARG(header);
11303 AST_APP_ARG(number);
11305 int i, number, start = 0;
11307 if (ast_strlen_zero(data)) {
11308 ast_log(LOG_WARNING, "This function requires a header name.\n");
11309 return -1;
11312 ast_channel_lock(chan);
11313 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
11314 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
11315 ast_channel_unlock(chan);
11316 return -1;
11319 AST_STANDARD_APP_ARGS(args, data);
11320 if (!args.number) {
11321 number = 1;
11322 } else {
11323 sscanf(args.number, "%d", &number);
11324 if (number < 1)
11325 number = 1;
11328 p = chan->tech_pvt;
11330 /* If there is no private structure, this channel is no longer alive */
11331 if (!p) {
11332 ast_channel_unlock(chan);
11333 return -1;
11336 for (i = 0; i < number; i++)
11337 content = __get_header(&p->initreq, args.header, &start);
11339 if (ast_strlen_zero(content)) {
11340 ast_channel_unlock(chan);
11341 return -1;
11344 ast_copy_string(buf, content, len);
11345 ast_channel_unlock(chan);
11347 return 0;
11350 static struct ast_custom_function sip_header_function = {
11351 .name = "SIP_HEADER",
11352 .synopsis = "Gets the specified SIP header",
11353 .syntax = "SIP_HEADER(<name>[,<number>])",
11354 .desc = "Since there are several headers (such as Via) which can occur multiple\n"
11355 "times, SIP_HEADER takes an optional second argument to specify which header with\n"
11356 "that name to retrieve. Headers start at offset 1.\n",
11357 .read = func_header_read,
11360 /*! \brief Dial plan function to check if domain is local */
11361 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11363 if (ast_strlen_zero(data)) {
11364 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
11365 return -1;
11367 if (check_sip_domain(data, NULL, 0))
11368 ast_copy_string(buf, data, len);
11369 else
11370 buf[0] = '\0';
11371 return 0;
11374 static struct ast_custom_function checksipdomain_function = {
11375 .name = "CHECKSIPDOMAIN",
11376 .synopsis = "Checks if domain is a local domain",
11377 .syntax = "CHECKSIPDOMAIN(<domain|IP>)",
11378 .read = func_check_sipdomain,
11379 .desc = "This function checks if the domain in the argument is configured\n"
11380 "as a local SIP domain that this Asterisk server is configured to handle.\n"
11381 "Returns the domain name if it is locally handled, otherwise an empty string.\n"
11382 "Check the domain= configuration in sip.conf\n",
11385 /*! \brief ${SIPPEER()} Dialplan function - reads peer data */
11386 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11388 struct sip_peer *peer;
11389 char *colname;
11391 if ((colname = strchr(data, ':'))) /*! \todo Will be deprecated after 1.4 */
11392 *colname++ = '\0';
11393 else if ((colname = strchr(data, '|')))
11394 *colname++ = '\0';
11395 else
11396 colname = "ip";
11398 if (!(peer = find_peer(data, NULL, 1)))
11399 return -1;
11401 if (!strcasecmp(colname, "ip")) {
11402 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
11403 } else if (!strcasecmp(colname, "status")) {
11404 peer_status(peer, buf, len);
11405 } else if (!strcasecmp(colname, "language")) {
11406 ast_copy_string(buf, peer->language, len);
11407 } else if (!strcasecmp(colname, "regexten")) {
11408 ast_copy_string(buf, peer->regexten, len);
11409 } else if (!strcasecmp(colname, "limit")) {
11410 snprintf(buf, len, "%d", peer->call_limit);
11411 } else if (!strcasecmp(colname, "curcalls")) {
11412 snprintf(buf, len, "%d", peer->inUse);
11413 } else if (!strcasecmp(colname, "accountcode")) {
11414 ast_copy_string(buf, peer->accountcode, len);
11415 } else if (!strcasecmp(colname, "useragent")) {
11416 ast_copy_string(buf, peer->useragent, len);
11417 } else if (!strcasecmp(colname, "mailbox")) {
11418 ast_copy_string(buf, peer->mailbox, len);
11419 } else if (!strcasecmp(colname, "context")) {
11420 ast_copy_string(buf, peer->context, len);
11421 } else if (!strcasecmp(colname, "expire")) {
11422 snprintf(buf, len, "%d", peer->expire);
11423 } else if (!strcasecmp(colname, "dynamic")) {
11424 ast_copy_string(buf, (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no"), len);
11425 } else if (!strcasecmp(colname, "callerid_name")) {
11426 ast_copy_string(buf, peer->cid_name, len);
11427 } else if (!strcasecmp(colname, "callerid_num")) {
11428 ast_copy_string(buf, peer->cid_num, len);
11429 } else if (!strcasecmp(colname, "codecs")) {
11430 ast_getformatname_multiple(buf, len -1, peer->capability);
11431 } else if (!strncasecmp(colname, "codec[", 6)) {
11432 char *codecnum;
11433 int index = 0, codec = 0;
11435 codecnum = colname + 6; /* move past the '[' */
11436 codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
11437 index = atoi(codecnum);
11438 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
11439 ast_copy_string(buf, ast_getformatname(codec), len);
11443 ASTOBJ_UNREF(peer, sip_destroy_peer);
11445 return 0;
11448 /*! \brief Structure to declare a dialplan function: SIPPEER */
11449 struct ast_custom_function sippeer_function = {
11450 .name = "SIPPEER",
11451 .synopsis = "Gets SIP peer information",
11452 .syntax = "SIPPEER(<peername>[|item])",
11453 .read = function_sippeer,
11454 .desc = "Valid items are:\n"
11455 "- ip (default) The IP address.\n"
11456 "- mailbox The configured mailbox.\n"
11457 "- context The configured context.\n"
11458 "- expire The epoch time of the next expire.\n"
11459 "- dynamic Is it dynamic? (yes/no).\n"
11460 "- callerid_name The configured Caller ID name.\n"
11461 "- callerid_num The configured Caller ID number.\n"
11462 "- codecs The configured codecs.\n"
11463 "- status Status (if qualify=yes).\n"
11464 "- regexten Registration extension\n"
11465 "- limit Call limit (call-limit)\n"
11466 "- curcalls Current amount of calls \n"
11467 " Only available if call-limit is set\n"
11468 "- language Default language for peer\n"
11469 "- accountcode Account code for this peer\n"
11470 "- useragent Current user agent id for peer\n"
11471 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
11472 "\n"
11475 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
11476 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11478 struct sip_pvt *p;
11480 *buf = 0;
11482 if (!data) {
11483 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
11484 return -1;
11487 ast_channel_lock(chan);
11488 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
11489 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
11490 ast_channel_unlock(chan);
11491 return -1;
11494 p = chan->tech_pvt;
11496 /* If there is no private structure, this channel is no longer alive */
11497 if (!p) {
11498 ast_channel_unlock(chan);
11499 return -1;
11502 if (!strcasecmp(data, "peerip")) {
11503 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
11504 } else if (!strcasecmp(data, "recvip")) {
11505 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
11506 } else if (!strcasecmp(data, "from")) {
11507 ast_copy_string(buf, p->from, len);
11508 } else if (!strcasecmp(data, "uri")) {
11509 ast_copy_string(buf, p->uri, len);
11510 } else if (!strcasecmp(data, "useragent")) {
11511 ast_copy_string(buf, p->useragent, len);
11512 } else if (!strcasecmp(data, "peername")) {
11513 ast_copy_string(buf, p->peername, len);
11514 } else if (!strcasecmp(data, "t38passthrough")) {
11515 if (p->t38.state == T38_DISABLED)
11516 ast_copy_string(buf, "0", sizeof("0"));
11517 else /* T38 is offered or enabled in this call */
11518 ast_copy_string(buf, "1", sizeof("1"));
11519 } else {
11520 ast_channel_unlock(chan);
11521 return -1;
11523 ast_channel_unlock(chan);
11525 return 0;
11528 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
11529 static struct ast_custom_function sipchaninfo_function = {
11530 .name = "SIPCHANINFO",
11531 .synopsis = "Gets the specified SIP parameter from the current channel",
11532 .syntax = "SIPCHANINFO(item)",
11533 .read = function_sipchaninfo_read,
11534 .desc = "Valid items are:\n"
11535 "- peerip The IP address of the peer.\n"
11536 "- recvip The source IP address of the peer.\n"
11537 "- from The URI from the From: header.\n"
11538 "- uri The URI from the Contact: header.\n"
11539 "- useragent The useragent.\n"
11540 "- peername The name of the peer.\n"
11541 "- t38passthrough 1 if T38 is offered or enabled in this channel, otherwise 0\n"
11544 /*! \brief Parse 302 Moved temporalily response */
11545 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
11547 char tmp[256];
11548 char *s, *e;
11549 char *domain;
11551 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
11552 s = get_in_brackets(tmp);
11553 s = strsep(&s, ";"); /* strip ; and beyond */
11554 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
11555 if (!strncasecmp(s, "sip:", 4))
11556 s += 4;
11557 e = strchr(s, '/');
11558 if (e)
11559 *e = '\0';
11560 if (option_debug)
11561 ast_log(LOG_DEBUG, "Found promiscuous redirection to 'SIP/%s'\n", s);
11562 if (p->owner)
11563 ast_string_field_build(p->owner, call_forward, "SIP/%s", s);
11564 } else {
11565 e = strchr(tmp, '@');
11566 if (e) {
11567 *e++ = '\0';
11568 domain = e;
11569 } else {
11570 /* No username part */
11571 domain = tmp;
11573 e = strchr(tmp, '/');
11574 if (e)
11575 *e = '\0';
11576 if (!strncasecmp(s, "sip:", 4))
11577 s += 4;
11578 if (option_debug > 1)
11579 ast_log(LOG_DEBUG, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
11580 if (p->owner) {
11581 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
11582 ast_string_field_set(p->owner, call_forward, s);
11587 /*! \brief Check pending actions on SIP call */
11588 static void check_pendings(struct sip_pvt *p)
11590 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
11591 /* if we can't BYE, then this is really a pending CANCEL */
11592 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
11593 transmit_request(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, FALSE);
11594 /* Actually don't destroy us yet, wait for the 487 on our original
11595 INVITE, but do set an autodestruct just in case we never get it. */
11596 else
11597 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
11598 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
11599 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11600 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
11601 if (option_debug)
11602 ast_log(LOG_DEBUG, "Sending pending reinvite on '%s'\n", p->callid);
11603 /* Didn't get to reinvite yet, so do it now */
11604 transmit_reinvite_with_sdp(p);
11605 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
11609 /*! \brief Handle SIP response to INVITE dialogue */
11610 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
11612 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
11613 int res = 0;
11614 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
11615 struct ast_channel *bridgepeer = NULL;
11617 if (option_debug > 3) {
11618 if (reinvite)
11619 ast_log(LOG_DEBUG, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
11620 else
11621 ast_log(LOG_DEBUG, "SIP response %d to standard invite\n", resp);
11624 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) { /* This call is already gone */
11625 if (option_debug)
11626 ast_log(LOG_DEBUG, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
11627 return;
11630 /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
11631 if (p->initid > -1) {
11632 /* Don't auto congest anymore since we've gotten something useful back */
11633 ast_sched_del(sched, p->initid);
11634 p->initid = -1;
11637 /* RFC3261 says we must treat every 1xx response (but not 100)
11638 that we don't recognize as if it was 183.
11640 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 183)
11641 resp = 183;
11643 /* Any response between 100 and 199 is PROCEEDING */
11644 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
11645 p->invitestate = INV_PROCEEDING;
11647 /* Final response, not 200 ? */
11648 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
11649 p->invitestate = INV_COMPLETED;
11652 switch (resp) {
11653 case 100: /* Trying */
11654 case 101: /* Dialog establishment */
11655 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11656 sip_cancel_destroy(p);
11657 check_pendings(p);
11658 break;
11660 case 180: /* 180 Ringing */
11661 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11662 sip_cancel_destroy(p);
11663 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
11664 ast_queue_control(p->owner, AST_CONTROL_RINGING);
11665 if (p->owner->_state != AST_STATE_UP) {
11666 ast_setstate(p->owner, AST_STATE_RINGING);
11669 if (find_sdp(req)) {
11670 p->invitestate = INV_EARLY_MEDIA;
11671 res = process_sdp(p, req);
11672 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
11673 /* Queue a progress frame only if we have SDP in 180 */
11674 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
11677 check_pendings(p);
11678 break;
11680 case 183: /* Session progress */
11681 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11682 sip_cancel_destroy(p);
11683 /* Ignore 183 Session progress without SDP */
11684 if (find_sdp(req)) {
11685 p->invitestate = INV_EARLY_MEDIA;
11686 res = process_sdp(p, req);
11687 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
11688 /* Queue a progress frame */
11689 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
11692 check_pendings(p);
11693 break;
11695 case 200: /* 200 OK on invite - someone's answering our call */
11696 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11697 sip_cancel_destroy(p);
11698 p->authtries = 0;
11699 if (find_sdp(req)) {
11700 if ((res = process_sdp(p, req)) && !ast_test_flag(req, SIP_PKT_IGNORE))
11701 if (!reinvite)
11702 /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
11703 /* For re-invites, we try to recover */
11704 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
11707 /* Parse contact header for continued conversation */
11708 /* When we get 200 OK, we know which device (and IP) to contact for this call */
11709 /* This is important when we have a SIP proxy between us and the phone */
11710 if (outgoing) {
11711 update_call_counter(p, DEC_CALL_RINGING);
11712 parse_ok_contact(p, req);
11713 if(set_address_from_contact(p)) {
11714 /* Bad contact - we don't know how to reach this device */
11715 /* We need to ACK, but then send a bye */
11716 /* OEJ: Possible issue that may need a check:
11717 If we have a proxy route between us and the device,
11718 should we care about resolving the contact
11719 or should we just send it?
11721 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11722 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
11725 /* Save Record-Route for any later requests we make on this dialogue */
11726 build_route(p, req, 1);
11729 if (p->owner && (p->owner->_state == AST_STATE_UP) && (bridgepeer = ast_bridged_channel(p->owner))) { /* if this is a re-invite */
11730 struct sip_pvt *bridgepvt = NULL;
11732 if (!bridgepeer->tech) {
11733 ast_log(LOG_WARNING, "Ooooh.. no tech! That's REALLY bad\n");
11734 break;
11736 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
11737 bridgepvt = (struct sip_pvt*)(bridgepeer->tech_pvt);
11738 if (bridgepvt->udptl) {
11739 if (p->t38.state == T38_PEER_REINVITE) {
11740 sip_handle_t38_reinvite(bridgepeer, p, 0);
11741 ast_rtp_set_rtptimers_onhold(p->rtp);
11742 if (p->vrtp)
11743 ast_rtp_set_rtptimers_onhold(p->vrtp); /* Turn off RTP timers while we send fax */
11744 } else if (p->t38.state == T38_DISABLED && bridgepeer && (bridgepvt->t38.state == T38_ENABLED)) {
11745 ast_log(LOG_WARNING, "RTP re-inivte after T38 session not handled yet !\n");
11746 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
11747 /* XXXX Should we really destroy this session here, without any response at all??? */
11748 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11750 } else {
11751 if (option_debug > 1)
11752 ast_log(LOG_DEBUG, "Strange... The other side of the bridge does not have a udptl struct\n");
11753 ast_mutex_lock(&bridgepvt->lock);
11754 bridgepvt->t38.state = T38_DISABLED;
11755 ast_mutex_unlock(&bridgepvt->lock);
11756 if (option_debug)
11757 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->tech->type);
11758 p->t38.state = T38_DISABLED;
11759 if (option_debug > 1)
11760 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11762 } else {
11763 /* Other side is not a SIP channel */
11764 if (option_debug > 1)
11765 ast_log(LOG_DEBUG, "Strange... The other side of the bridge is not a SIP channel\n");
11766 p->t38.state = T38_DISABLED;
11767 if (option_debug > 1)
11768 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11771 if ((p->t38.state == T38_LOCAL_REINVITE) || (p->t38.state == T38_LOCAL_DIRECT)) {
11772 /* If there was T38 reinvite and we are supposed to answer with 200 OK than this should set us to T38 negotiated mode */
11773 p->t38.state = T38_ENABLED;
11774 if (option_debug)
11775 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11778 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
11779 if (!reinvite) {
11780 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
11781 } else { /* RE-invite */
11782 ast_queue_frame(p->owner, &ast_null_frame);
11784 } else {
11785 /* It's possible we're getting an 200 OK after we've tried to disconnect
11786 by sending CANCEL */
11787 /* First send ACK, then send bye */
11788 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11789 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
11791 /* If I understand this right, the branch is different for a non-200 ACK only */
11792 p->invitestate = INV_TERMINATED;
11793 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
11794 check_pendings(p);
11795 break;
11796 case 407: /* Proxy authentication */
11797 case 401: /* Www auth */
11798 /* First we ACK */
11799 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11800 if (p->options)
11801 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
11803 /* Then we AUTH */
11804 ast_string_field_free(p, theirtag); /* forget their old tag, so we don't match tags when getting response */
11805 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
11806 char *authenticate = (resp == 401 ? "WWW-Authenticate" : "Proxy-Authenticate");
11807 char *authorization = (resp == 401 ? "Authorization" : "Proxy-Authorization");
11808 if (p->authtries < MAX_AUTHTRIES)
11809 p->invitestate = INV_CALLING;
11810 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, authenticate, authorization, SIP_INVITE, 1)) {
11811 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
11812 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11813 sip_alreadygone(p);
11814 if (p->owner)
11815 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11818 break;
11820 case 403: /* Forbidden */
11821 /* First we ACK */
11822 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11823 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
11824 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner)
11825 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11826 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11827 sip_alreadygone(p);
11828 break;
11830 case 404: /* Not found */
11831 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11832 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
11833 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11834 sip_alreadygone(p);
11835 break;
11837 case 481: /* Call leg does not exist */
11838 /* Could be REFER caused INVITE with replaces */
11839 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
11840 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11841 if (p->owner)
11842 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11843 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11844 break;
11845 case 487: /* Cancelled transaction */
11846 /* We have sent CANCEL on an outbound INVITE
11847 This transaction is already scheduled to be killed by sip_hangup().
11849 transmit_request(p, SIP_ACK, seqno, 0, 0);
11850 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
11851 ast_queue_hangup(p->owner);
11852 else if (!ast_test_flag(req, SIP_PKT_IGNORE))
11853 update_call_counter(p, DEC_CALL_LIMIT);
11854 break;
11855 case 488: /* Not acceptable here */
11856 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11857 if (reinvite && p->udptl) {
11858 /* If this is a T.38 call, we should go back to
11859 audio. If this is an audio call - something went
11860 terribly wrong since we don't renegotiate codecs,
11861 only IP/port .
11863 p->t38.state = T38_DISABLED;
11864 /* Try to reset RTP timers */
11865 ast_rtp_set_rtptimers_onhold(p->rtp);
11866 ast_log(LOG_ERROR, "Got error on T.38 re-invite. Bad configuration. Peer needs to have T.38 disabled.\n");
11868 /*! \bug Is there any way we can go back to the audio call on both
11869 sides here?
11871 /* While figuring that out, hangup the call */
11872 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
11873 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11874 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11875 } else {
11876 /* We can't set up this call, so give up */
11877 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
11878 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11879 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11881 break;
11882 case 491: /* Pending */
11883 /* we really should have to wait a while, then retransmit */
11884 /* We should support the retry-after at some point */
11885 /* At this point, we treat this as a congestion */
11886 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11887 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
11888 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11889 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11890 break;
11892 case 501: /* Not implemented */
11893 transmit_request(p, SIP_ACK, seqno, 0, 0);
11894 if (p->owner)
11895 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11896 break;
11900 /* \brief Handle SIP response in REFER transaction
11901 We've sent a REFER, now handle responses to it
11903 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
11905 char *auth = "Proxy-Authenticate";
11906 char *auth2 = "Proxy-Authorization";
11908 /* If no refer structure exists, then do nothing */
11909 if (!p->refer)
11910 return;
11912 switch (resp) {
11913 case 202: /* Transfer accepted */
11914 /* We need to do something here */
11915 /* The transferee is now sending INVITE to target */
11916 p->refer->status = REFER_ACCEPTED;
11917 /* Now wait for next message */
11918 if (option_debug > 2)
11919 ast_log(LOG_DEBUG, "Got 202 accepted on transfer\n");
11920 /* We should hang along, waiting for NOTIFY's here */
11921 break;
11923 case 401: /* Not www-authorized on SIP method */
11924 case 407: /* Proxy auth */
11925 if (ast_strlen_zero(p->authname)) {
11926 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
11927 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
11928 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11930 if (resp == 401) {
11931 auth = "WWW-Authenticate";
11932 auth2 = "Authorization";
11934 if ((p->authtries > 1) || do_proxy_auth(p, req, auth, auth2, SIP_REFER, 0)) {
11935 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
11936 p->refer->status = REFER_NOAUTH;
11937 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11939 break;
11940 case 481: /* Call leg does not exist */
11942 /* A transfer with Replaces did not work */
11943 /* OEJ: We should Set flag, cancel the REFER, go back
11944 to original call - but right now we can't */
11945 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
11946 if (p->owner)
11947 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11948 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11949 break;
11951 case 500: /* Server error */
11952 case 501: /* Method not implemented */
11953 /* Return to the current call onhold */
11954 /* Status flag needed to be reset */
11955 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
11956 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11957 p->refer->status = REFER_FAILED;
11958 break;
11959 case 603: /* Transfer declined */
11960 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
11961 p->refer->status = REFER_FAILED;
11962 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11963 break;
11967 /*! \brief Handle responses on REGISTER to services */
11968 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
11970 int expires, expires_ms;
11971 struct sip_registry *r;
11972 r=p->registry;
11974 switch (resp) {
11975 case 401: /* Unauthorized */
11976 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "WWW-Authenticate", "Authorization")) {
11977 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
11978 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11980 break;
11981 case 403: /* Forbidden */
11982 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
11983 if (global_regattempts_max)
11984 p->registry->regattempts = global_regattempts_max+1;
11985 ast_sched_del(sched, r->timeout);
11986 r->timeout = -1;
11987 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11988 break;
11989 case 404: /* Not found */
11990 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username,p->registry->hostname);
11991 if (global_regattempts_max)
11992 p->registry->regattempts = global_regattempts_max+1;
11993 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11994 r->call = NULL;
11995 ast_sched_del(sched, r->timeout);
11996 r->timeout = -1;
11997 break;
11998 case 407: /* Proxy auth */
11999 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization")) {
12000 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
12001 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12003 break;
12004 case 479: /* SER: Not able to process the URI - address is wrong in register*/
12005 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username,p->registry->hostname);
12006 if (global_regattempts_max)
12007 p->registry->regattempts = global_regattempts_max+1;
12008 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12009 r->call = NULL;
12010 ast_sched_del(sched, r->timeout);
12011 r->timeout = -1;
12012 break;
12013 case 200: /* 200 OK */
12014 if (!r) {
12015 ast_log(LOG_WARNING, "Got 200 OK on REGISTER that isn't a register\n");
12016 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12017 return 0;
12020 r->regstate = REG_STATE_REGISTERED;
12021 r->regtime = time(NULL); /* Reset time of last succesful registration */
12022 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
12023 r->regattempts = 0;
12024 if (option_debug)
12025 ast_log(LOG_DEBUG, "Registration successful\n");
12026 if (r->timeout > -1) {
12027 if (option_debug)
12028 ast_log(LOG_DEBUG, "Cancelling timeout %d\n", r->timeout);
12029 ast_sched_del(sched, r->timeout);
12031 r->timeout=-1;
12032 r->call = NULL;
12033 p->registry = NULL;
12034 /* Let this one hang around until we have all the responses */
12035 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12036 /* ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); */
12038 /* set us up for re-registering */
12039 /* figure out how long we got registered for */
12040 if (r->expire > -1)
12041 ast_sched_del(sched, r->expire);
12042 /* according to section 6.13 of RFC, contact headers override
12043 expires headers, so check those first */
12044 expires = 0;
12046 /* XXX todo: try to save the extra call */
12047 if (!ast_strlen_zero(get_header(req, "Contact"))) {
12048 const char *contact = NULL;
12049 const char *tmptmp = NULL;
12050 int start = 0;
12051 for(;;) {
12052 contact = __get_header(req, "Contact", &start);
12053 /* this loop ensures we get a contact header about our register request */
12054 if(!ast_strlen_zero(contact)) {
12055 if( (tmptmp=strstr(contact, p->our_contact))) {
12056 contact=tmptmp;
12057 break;
12059 } else
12060 break;
12062 tmptmp = strcasestr(contact, "expires=");
12063 if (tmptmp) {
12064 if (sscanf(tmptmp + 8, "%d;", &expires) != 1)
12065 expires = 0;
12069 if (!expires)
12070 expires=atoi(get_header(req, "expires"));
12071 if (!expires)
12072 expires=default_expiry;
12074 expires_ms = expires * 1000;
12075 if (expires <= EXPIRY_GUARD_LIMIT)
12076 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT),EXPIRY_GUARD_MIN);
12077 else
12078 expires_ms -= EXPIRY_GUARD_SECS * 1000;
12079 if (sipdebug)
12080 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
12082 r->refresh= (int) expires_ms / 1000;
12084 /* Schedule re-registration before we expire */
12085 r->expire=ast_sched_add(sched, expires_ms, sip_reregister, r);
12086 ASTOBJ_UNREF(r, sip_registry_destroy);
12088 return 1;
12091 /*! \brief Handle qualification responses (OPTIONS) */
12092 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
12094 struct sip_peer *peer = p->relatedpeer;
12095 int statechanged, is_reachable, was_reachable;
12096 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
12099 * Compute the response time to a ping (goes in peer->lastms.)
12100 * -1 means did not respond, 0 means unknown,
12101 * 1..maxms is a valid response, >maxms means late response.
12103 if (pingtime < 1) /* zero = unknown, so round up to 1 */
12104 pingtime = 1;
12106 /* Now determine new state and whether it has changed.
12107 * Use some helper variables to simplify the writing
12108 * of the expressions.
12110 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
12111 is_reachable = pingtime <= peer->maxms;
12112 statechanged = peer->lastms == 0 /* yes, unknown before */
12113 || was_reachable != is_reachable;
12115 peer->lastms = pingtime;
12116 peer->call = NULL;
12117 if (statechanged) {
12118 const char *s = is_reachable ? "Reachable" : "Lagged";
12120 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
12121 peer->name, s, pingtime, peer->maxms);
12122 ast_device_state_changed("SIP/%s", peer->name);
12123 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
12124 "Peer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
12125 peer->name, s, pingtime);
12128 if (peer->pokeexpire > -1)
12129 ast_sched_del(sched, peer->pokeexpire);
12130 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12132 /* Try again eventually */
12133 peer->pokeexpire = ast_sched_add(sched,
12134 is_reachable ? DEFAULT_FREQ_OK : DEFAULT_FREQ_NOTOK,
12135 sip_poke_peer_s, peer);
12138 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
12139 static void stop_media_flows(struct sip_pvt *p)
12141 /* Immediately stop RTP, VRTP and UDPTL as applicable */
12142 if (p->rtp)
12143 ast_rtp_stop(p->rtp);
12144 if (p->vrtp)
12145 ast_rtp_stop(p->vrtp);
12146 if (p->udptl)
12147 ast_udptl_stop(p->udptl);
12150 /*! \brief Handle SIP response in dialogue */
12151 /* XXX only called by handle_request */
12152 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
12154 struct ast_channel *owner;
12155 int sipmethod;
12156 int res = 1;
12157 const char *c = get_header(req, "Cseq");
12158 const char *msg = strchr(c, ' ');
12160 if (!msg)
12161 msg = "";
12162 else
12163 msg++;
12164 sipmethod = find_sip_method(msg);
12166 owner = p->owner;
12167 if (owner)
12168 owner->hangupcause = hangup_sip2cause(resp);
12170 /* Acknowledge whatever it is destined for */
12171 if ((resp >= 100) && (resp <= 199))
12172 __sip_semi_ack(p, seqno, 0, sipmethod);
12173 else
12174 __sip_ack(p, seqno, 0, sipmethod);
12176 /* Get their tag if we haven't already */
12177 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
12178 char tag[128];
12180 gettag(req, "To", tag, sizeof(tag));
12181 ast_string_field_set(p, theirtag, tag);
12183 if (p->relatedpeer && p->method == SIP_OPTIONS) {
12184 /* We don't really care what the response is, just that it replied back.
12185 Well, as long as it's not a 100 response... since we might
12186 need to hang around for something more "definitive" */
12187 if (resp != 100)
12188 handle_response_peerpoke(p, resp, req);
12189 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12190 switch(resp) {
12191 case 100: /* 100 Trying */
12192 case 101: /* 101 Dialog establishment */
12193 if (sipmethod == SIP_INVITE)
12194 handle_response_invite(p, resp, rest, req, seqno);
12195 break;
12196 case 183: /* 183 Session Progress */
12197 if (sipmethod == SIP_INVITE)
12198 handle_response_invite(p, resp, rest, req, seqno);
12199 break;
12200 case 180: /* 180 Ringing */
12201 if (sipmethod == SIP_INVITE)
12202 handle_response_invite(p, resp, rest, req, seqno);
12203 break;
12204 case 200: /* 200 OK */
12205 p->authtries = 0; /* Reset authentication counter */
12206 if (sipmethod == SIP_MESSAGE) {
12207 /* We successfully transmitted a message */
12208 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12209 } else if (sipmethod == SIP_INVITE) {
12210 handle_response_invite(p, resp, rest, req, seqno);
12211 } else if (sipmethod == SIP_NOTIFY) {
12212 /* They got the notify, this is the end */
12213 if (p->owner) {
12214 if (!p->refer) {
12215 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
12216 ast_queue_hangup(p->owner);
12217 } else if (option_debug > 3)
12218 ast_log(LOG_DEBUG, "Got OK on REFER Notify message\n");
12219 } else {
12220 if (p->subscribed == NONE)
12221 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12223 } else if (sipmethod == SIP_REGISTER)
12224 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12225 else if (sipmethod == SIP_BYE) /* Ok, we're ready to go */
12226 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12227 break;
12228 case 202: /* Transfer accepted */
12229 if (sipmethod == SIP_REFER)
12230 handle_response_refer(p, resp, rest, req, seqno);
12231 break;
12232 case 401: /* Not www-authorized on SIP method */
12233 if (sipmethod == SIP_INVITE)
12234 handle_response_invite(p, resp, rest, req, seqno);
12235 else if (sipmethod == SIP_REFER)
12236 handle_response_refer(p, resp, rest, req, seqno);
12237 else if (p->registry && sipmethod == SIP_REGISTER)
12238 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12239 else {
12240 ast_log(LOG_WARNING, "Got authentication request (401) on unknown %s to '%s'\n", sip_methods[sipmethod].text, get_header(req, "To"));
12241 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12243 break;
12244 case 403: /* Forbidden - we failed authentication */
12245 if (sipmethod == SIP_INVITE)
12246 handle_response_invite(p, resp, rest, req, seqno);
12247 else if (p->registry && sipmethod == SIP_REGISTER)
12248 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12249 else {
12250 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
12251 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12253 break;
12254 case 404: /* Not found */
12255 if (p->registry && sipmethod == SIP_REGISTER)
12256 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12257 else if (sipmethod == SIP_INVITE)
12258 handle_response_invite(p, resp, rest, req, seqno);
12259 else if (owner)
12260 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12261 break;
12262 case 407: /* Proxy auth required */
12263 if (sipmethod == SIP_INVITE)
12264 handle_response_invite(p, resp, rest, req, seqno);
12265 else if (sipmethod == SIP_REFER)
12266 handle_response_refer(p, resp, rest, req, seqno);
12267 else if (p->registry && sipmethod == SIP_REGISTER)
12268 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12269 else if (sipmethod == SIP_BYE) {
12270 if (ast_strlen_zero(p->authname))
12271 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12272 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12273 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12274 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", sipmethod, 0)) {
12275 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
12276 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12278 } else /* We can't handle this, giving up in a bad way */
12279 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12281 break;
12282 case 481: /* Call leg does not exist */
12283 if (sipmethod == SIP_INVITE) {
12284 handle_response_invite(p, resp, rest, req, seqno);
12285 } else if (sipmethod == SIP_REFER) {
12286 handle_response_refer(p, resp, rest, req, seqno);
12287 } else if (sipmethod == SIP_BYE) {
12288 /* The other side has no transaction to bye,
12289 just assume it's all right then */
12290 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12291 } else if (sipmethod == SIP_CANCEL) {
12292 /* The other side has no transaction to cancel,
12293 just assume it's all right then */
12294 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12295 } else {
12296 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12297 /* Guessing that this is not an important request */
12299 break;
12300 case 487:
12301 if (sipmethod == SIP_INVITE)
12302 handle_response_invite(p, resp, rest, req, seqno);
12303 break;
12304 case 488: /* Not acceptable here - codec error */
12305 if (sipmethod == SIP_INVITE)
12306 handle_response_invite(p, resp, rest, req, seqno);
12307 break;
12308 case 491: /* Pending */
12309 if (sipmethod == SIP_INVITE)
12310 handle_response_invite(p, resp, rest, req, seqno);
12311 else {
12312 if (option_debug)
12313 ast_log(LOG_DEBUG, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
12314 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12316 break;
12317 case 501: /* Not Implemented */
12318 if (sipmethod == SIP_INVITE)
12319 handle_response_invite(p, resp, rest, req, seqno);
12320 else if (sipmethod == SIP_REFER)
12321 handle_response_refer(p, resp, rest, req, seqno);
12322 else
12323 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
12324 break;
12325 case 603: /* Declined transfer */
12326 if (sipmethod == SIP_REFER) {
12327 handle_response_refer(p, resp, rest, req, seqno);
12328 break;
12330 /* Fallthrough */
12331 default:
12332 if ((resp >= 300) && (resp < 700)) {
12333 /* Fatal response */
12334 if ((option_verbose > 2) && (resp != 487))
12335 ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
12337 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
12339 /* XXX Locking issues?? XXX */
12340 switch(resp) {
12341 case 300: /* Multiple Choices */
12342 case 301: /* Moved permenantly */
12343 case 302: /* Moved temporarily */
12344 case 305: /* Use Proxy */
12345 parse_moved_contact(p, req);
12346 /* Fall through */
12347 case 486: /* Busy here */
12348 case 600: /* Busy everywhere */
12349 case 603: /* Decline */
12350 if (p->owner)
12351 ast_queue_control(p->owner, AST_CONTROL_BUSY);
12352 break;
12353 case 482: /*
12354 \note SIP is incapable of performing a hairpin call, which
12355 is yet another failure of not having a layer 2 (again, YAY
12356 IETF for thinking ahead). So we treat this as a call
12357 forward and hope we end up at the right place... */
12358 if (option_debug)
12359 ast_log(LOG_DEBUG, "Hairpin detected, setting up call forward for what it's worth\n");
12360 if (p->owner)
12361 ast_string_field_build(p->owner, call_forward,
12362 "Local/%s@%s", p->username, p->context);
12363 /* Fall through */
12364 case 480: /* Temporarily Unavailable */
12365 case 404: /* Not Found */
12366 case 410: /* Gone */
12367 case 400: /* Bad Request */
12368 case 500: /* Server error */
12369 if (sipmethod == SIP_REFER) {
12370 handle_response_refer(p, resp, rest, req, seqno);
12371 break;
12373 /* Fall through */
12374 case 503: /* Service Unavailable */
12375 case 504: /* Server Timeout */
12376 if (owner)
12377 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12378 break;
12379 default:
12380 /* Send hangup */
12381 if (owner)
12382 ast_queue_hangup(p->owner);
12383 break;
12385 /* ACK on invite */
12386 if (sipmethod == SIP_INVITE)
12387 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12388 sip_alreadygone(p);
12389 if (!p->owner)
12390 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12391 } else if ((resp >= 100) && (resp < 200)) {
12392 if (sipmethod == SIP_INVITE) {
12393 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12394 sip_cancel_destroy(p);
12395 if (find_sdp(req))
12396 process_sdp(p, req);
12397 if (p->owner) {
12398 /* Queue a progress frame */
12399 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
12402 } else
12403 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));
12405 } else {
12406 /* Responses to OUTGOING SIP requests on INCOMING calls
12407 get handled here. As well as out-of-call message responses */
12408 if (ast_test_flag(req, SIP_PKT_DEBUG))
12409 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
12411 if (sipmethod == SIP_INVITE && resp == 200) {
12412 /* Tags in early session is replaced by the tag in 200 OK, which is
12413 the final reply to our INVITE */
12414 char tag[128];
12416 gettag(req, "To", tag, sizeof(tag));
12417 ast_string_field_set(p, theirtag, tag);
12420 switch(resp) {
12421 case 200:
12422 if (sipmethod == SIP_INVITE) {
12423 handle_response_invite(p, resp, rest, req, seqno);
12424 } else if (sipmethod == SIP_CANCEL) {
12425 if (option_debug)
12426 ast_log(LOG_DEBUG, "Got 200 OK on CANCEL\n");
12428 /* Wait for 487, then destroy */
12429 } else if (sipmethod == SIP_NOTIFY) {
12430 /* They got the notify, this is the end */
12431 if (p->owner) {
12432 if (p->refer) {
12433 if (option_debug)
12434 ast_log(LOG_DEBUG, "Got 200 OK on NOTIFY for transfer\n");
12435 } else
12436 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
12437 /* ast_queue_hangup(p->owner); Disabled */
12438 } else {
12439 if (!p->subscribed && !p->refer)
12440 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12442 } else if (sipmethod == SIP_BYE)
12443 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12444 else if (sipmethod == SIP_MESSAGE)
12445 /* We successfully transmitted a message */
12446 /* XXX Why destroy this pvt after message transfer? Bad */
12447 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12448 else if (sipmethod == SIP_BYE)
12449 /* Ok, we're ready to go */
12450 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12451 break;
12452 case 202: /* Transfer accepted */
12453 if (sipmethod == SIP_REFER)
12454 handle_response_refer(p, resp, rest, req, seqno);
12455 break;
12456 case 401: /* www-auth */
12457 case 407:
12458 if (sipmethod == SIP_REFER)
12459 handle_response_refer(p, resp, rest, req, seqno);
12460 else if (sipmethod == SIP_INVITE)
12461 handle_response_invite(p, resp, rest, req, seqno);
12462 else if (sipmethod == SIP_BYE) {
12463 char *auth, *auth2;
12465 auth = (resp == 407 ? "Proxy-Authenticate" : "WWW-Authenticate");
12466 auth2 = (resp == 407 ? "Proxy-Authorization" : "Authorization");
12467 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, auth, auth2, sipmethod, 0)) {
12468 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
12469 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12472 break;
12473 case 481: /* Call leg does not exist */
12474 if (sipmethod == SIP_INVITE) {
12475 /* Re-invite failed */
12476 handle_response_invite(p, resp, rest, req, seqno);
12477 } else if (sipmethod == SIP_BYE) {
12478 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12479 } else if (sipdebug) {
12480 ast_log (LOG_DEBUG, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
12482 break;
12483 case 501: /* Not Implemented */
12484 if (sipmethod == SIP_INVITE)
12485 handle_response_invite(p, resp, rest, req, seqno);
12486 else if (sipmethod == SIP_REFER)
12487 handle_response_refer(p, resp, rest, req, seqno);
12488 break;
12489 case 603: /* Declined transfer */
12490 if (sipmethod == SIP_REFER) {
12491 handle_response_refer(p, resp, rest, req, seqno);
12492 break;
12494 /* Fallthrough */
12495 default: /* Errors without handlers */
12496 if ((resp >= 100) && (resp < 200)) {
12497 if (sipmethod == SIP_INVITE) { /* re-invite */
12498 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12499 sip_cancel_destroy(p);
12502 if ((resp >= 300) && (resp < 700)) {
12503 if ((option_verbose > 2) && (resp != 487))
12504 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));
12505 switch(resp) {
12506 case 488: /* Not acceptable here - codec error */
12507 case 603: /* Decline */
12508 case 500: /* Server error */
12509 case 503: /* Service Unavailable */
12510 case 504: /* Server timeout */
12512 if (sipmethod == SIP_INVITE) { /* re-invite failed */
12513 sip_cancel_destroy(p);
12515 break;
12518 break;
12524 /*! \brief Park SIP call support function
12525 Starts in a new thread, then parks the call
12526 XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
12527 audio can't be heard before hangup
12529 static void *sip_park_thread(void *stuff)
12531 struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
12532 struct sip_dual *d;
12533 struct sip_request req;
12534 int ext;
12535 int res;
12537 d = stuff;
12538 transferee = d->chan1;
12539 transferer = d->chan2;
12540 copy_request(&req, &d->req);
12541 free(d);
12543 if (!transferee || !transferer) {
12544 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
12545 return NULL;
12547 if (option_debug > 3)
12548 ast_log(LOG_DEBUG, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
12550 ast_channel_lock(transferee);
12551 if (ast_do_masquerade(transferee)) {
12552 ast_log(LOG_WARNING, "Masquerade failed.\n");
12553 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
12554 ast_channel_unlock(transferee);
12555 return NULL;
12557 ast_channel_unlock(transferee);
12559 res = ast_park_call(transferee, transferer, 0, &ext);
12562 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
12563 if (!res) {
12564 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
12565 } else {
12566 /* Then tell the transferer what happened */
12567 sprintf(buf, "Call parked on extension '%d'", ext);
12568 transmit_message_with_text(transferer->tech_pvt, buf);
12570 #endif
12572 /* Any way back to the current call??? */
12573 /* Transmit response to the REFER request */
12574 transmit_response(transferer->tech_pvt, "202 Accepted", &req);
12575 if (!res) {
12576 /* Transfer succeeded */
12577 append_history(transferer->tech_pvt, "SIPpark","Parked call on %d", ext);
12578 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
12579 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
12580 ast_hangup(transferer); /* This will cause a BYE */
12581 if (option_debug)
12582 ast_log(LOG_DEBUG, "SIP Call parked on extension '%d'\n", ext);
12583 } else {
12584 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
12585 append_history(transferer->tech_pvt, "SIPpark","Parking failed\n");
12586 if (option_debug)
12587 ast_log(LOG_DEBUG, "SIP Call parked failed \n");
12588 /* Do not hangup call */
12590 return NULL;
12593 /*! \brief Park a call using the subsystem in res_features.c
12594 This is executed in a separate thread
12596 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
12598 struct sip_dual *d;
12599 struct ast_channel *transferee, *transferer;
12600 /* Chan2m: The transferer, chan1m: The transferee */
12601 pthread_t th;
12603 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "Parking/%s", chan1->name);
12604 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "SIPPeer/%s", chan2->name);
12605 if ((!transferer) || (!transferee)) {
12606 if (transferee) {
12607 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
12608 ast_hangup(transferee);
12610 if (transferer) {
12611 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
12612 ast_hangup(transferer);
12614 return -1;
12617 /* Make formats okay */
12618 transferee->readformat = chan1->readformat;
12619 transferee->writeformat = chan1->writeformat;
12621 /* Prepare for taking over the channel */
12622 ast_channel_masquerade(transferee, chan1);
12624 /* Setup the extensions and such */
12625 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
12626 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
12627 transferee->priority = chan1->priority;
12629 /* We make a clone of the peer channel too, so we can play
12630 back the announcement */
12632 /* Make formats okay */
12633 transferer->readformat = chan2->readformat;
12634 transferer->writeformat = chan2->writeformat;
12636 /* Prepare for taking over the channel */
12637 ast_channel_masquerade(transferer, chan2);
12639 /* Setup the extensions and such */
12640 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
12641 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
12642 transferer->priority = chan2->priority;
12644 ast_channel_lock(transferer);
12645 if (ast_do_masquerade(transferer)) {
12646 ast_log(LOG_WARNING, "Masquerade failed :(\n");
12647 ast_channel_unlock(transferer);
12648 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
12649 ast_hangup(transferer);
12650 return -1;
12652 ast_channel_unlock(transferer);
12653 if (!transferer || !transferee) {
12654 if (!transferer) {
12655 if (option_debug)
12656 ast_log(LOG_DEBUG, "No transferer channel, giving up parking\n");
12658 if (!transferee) {
12659 if (option_debug)
12660 ast_log(LOG_DEBUG, "No transferee channel, giving up parking\n");
12662 return -1;
12664 if ((d = ast_calloc(1, sizeof(*d)))) {
12665 pthread_attr_t attr;
12667 pthread_attr_init(&attr);
12668 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
12670 /* Save original request for followup */
12671 copy_request(&d->req, req);
12672 d->chan1 = transferee; /* Transferee */
12673 d->chan2 = transferer; /* Transferer */
12674 d->seqno = seqno;
12675 if (ast_pthread_create_background(&th, &attr, sip_park_thread, d) < 0) {
12676 /* Could not start thread */
12677 free(d); /* We don't need it anymore. If thread is created, d will be free'd
12678 by sip_park_thread() */
12679 pthread_attr_destroy(&attr);
12680 return 0;
12682 pthread_attr_destroy(&attr);
12684 return -1;
12687 /*! \brief Turn off generator data
12688 XXX Does this function belong in the SIP channel?
12690 static void ast_quiet_chan(struct ast_channel *chan)
12692 if (chan && chan->_state == AST_STATE_UP) {
12693 if (chan->generatordata)
12694 ast_deactivate_generator(chan);
12698 /*! \brief Attempt transfer of SIP call
12699 This fix for attended transfers on a local PBX */
12700 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
12702 int res = 0;
12703 struct ast_channel *peera = NULL,
12704 *peerb = NULL,
12705 *peerc = NULL,
12706 *peerd = NULL;
12709 /* We will try to connect the transferee with the target and hangup
12710 all channels to the transferer */
12711 if (option_debug > 3) {
12712 ast_log(LOG_DEBUG, "Sip transfer:--------------------\n");
12713 if (transferer->chan1)
12714 ast_log(LOG_DEBUG, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
12715 else
12716 ast_log(LOG_DEBUG, "-- No transferer first channel - odd??? \n");
12717 if (target->chan1)
12718 ast_log(LOG_DEBUG, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
12719 else
12720 ast_log(LOG_DEBUG, "-- No target first channel ---\n");
12721 if (transferer->chan2)
12722 ast_log(LOG_DEBUG, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
12723 else
12724 ast_log(LOG_DEBUG, "-- No bridged call to transferee\n");
12725 if (target->chan2)
12726 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)");
12727 else
12728 ast_log(LOG_DEBUG, "-- No target second channel ---\n");
12729 ast_log(LOG_DEBUG, "-- END Sip transfer:--------------------\n");
12731 if (transferer->chan2) { /* We have a bridge on the transferer's channel */
12732 peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
12733 peerb = target->chan1; /* Transferer - PBX -> target channel - This will get lost in masq */
12734 peerc = transferer->chan2; /* Asterisk to Transferee */
12735 peerd = target->chan2; /* Asterisk to Target */
12736 if (option_debug > 2)
12737 ast_log(LOG_DEBUG, "SIP transfer: Four channels to handle\n");
12738 } else if (target->chan2) { /* Transferer has no bridge (IVR), but transferee */
12739 peera = target->chan1; /* Transferer to PBX -> target channel */
12740 peerb = transferer->chan1; /* Transferer to IVR*/
12741 peerc = target->chan2; /* Asterisk to Target */
12742 peerd = transferer->chan2; /* Nothing */
12743 if (option_debug > 2)
12744 ast_log(LOG_DEBUG, "SIP transfer: Three channels to handle\n");
12747 if (peera && peerb && peerc && (peerb != peerc)) {
12748 ast_quiet_chan(peera); /* Stop generators */
12749 ast_quiet_chan(peerb);
12750 ast_quiet_chan(peerc);
12751 if (peerd)
12752 ast_quiet_chan(peerd);
12754 /* Fix CDRs so they're attached to the remaining channel */
12755 if (peera->cdr && peerb->cdr)
12756 peerb->cdr = ast_cdr_append(peerb->cdr, peera->cdr);
12757 else if (peera->cdr)
12758 peerb->cdr = peera->cdr;
12759 peera->cdr = NULL;
12761 if (peerb->cdr && peerc->cdr)
12762 peerb->cdr = ast_cdr_append(peerb->cdr, peerc->cdr);
12763 else if (peerc->cdr)
12764 peerb->cdr = peerc->cdr;
12765 peerc->cdr = NULL;
12767 if (option_debug > 3)
12768 ast_log(LOG_DEBUG, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
12769 if (ast_channel_masquerade(peerb, peerc)) {
12770 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
12771 res = -1;
12772 } else
12773 ast_log(LOG_DEBUG, "SIP transfer: Succeeded to masquerade channels.\n");
12774 return res;
12775 } else {
12776 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
12777 if (transferer->chan1)
12778 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
12779 if (target->chan1)
12780 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
12781 return -1;
12783 return 0;
12786 /*! \brief Get tag from packet
12788 * \return Returns the pointer to the provided tag buffer,
12789 * or NULL if the tag was not found.
12791 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
12793 const char *thetag;
12795 if (!tagbuf)
12796 return NULL;
12797 tagbuf[0] = '\0'; /* reset the buffer */
12798 thetag = get_header(req, header);
12799 thetag = strcasestr(thetag, ";tag=");
12800 if (thetag) {
12801 thetag += 5;
12802 ast_copy_string(tagbuf, thetag, tagbufsize);
12803 return strsep(&tagbuf, ";");
12805 return NULL;
12808 /*! \brief Handle incoming notifications */
12809 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
12811 /* This is mostly a skeleton for future improvements */
12812 /* Mostly created to return proper answers on notifications on outbound REFER's */
12813 int res = 0;
12814 const char *event = get_header(req, "Event");
12815 char *eventid = NULL;
12816 char *sep;
12818 if( (sep = strchr(event, ';')) ) { /* XXX bug here - overwriting string ? */
12819 *sep++ = '\0';
12820 eventid = sep;
12823 if (option_debug > 1 && sipdebug)
12824 ast_log(LOG_DEBUG, "Got NOTIFY Event: %s\n", event);
12826 if (strcmp(event, "refer")) {
12827 /* We don't understand this event. */
12828 /* Here's room to implement incoming voicemail notifications :-) */
12829 transmit_response(p, "489 Bad event", req);
12830 res = -1;
12831 } else {
12832 /* Save nesting depth for now, since there might be other events we will
12833 support in the future */
12835 /* Handle REFER notifications */
12837 char buf[1024];
12838 char *cmd, *code;
12839 int respcode;
12840 int success = TRUE;
12842 /* EventID for each transfer... EventID is basically the REFER cseq
12844 We are getting notifications on a call that we transfered
12845 We should hangup when we are getting a 200 OK in a sipfrag
12846 Check if we have an owner of this event */
12848 /* Check the content type */
12849 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
12850 /* We need a sipfrag */
12851 transmit_response(p, "400 Bad request", req);
12852 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12853 return -1;
12856 /* Get the text of the attachment */
12857 if (get_msg_text(buf, sizeof(buf), req)) {
12858 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
12859 transmit_response(p, "400 Bad request", req);
12860 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12861 return -1;
12865 From the RFC...
12866 A minimal, but complete, implementation can respond with a single
12867 NOTIFY containing either the body:
12868 SIP/2.0 100 Trying
12870 if the subscription is pending, the body:
12871 SIP/2.0 200 OK
12872 if the reference was successful, the body:
12873 SIP/2.0 503 Service Unavailable
12874 if the reference failed, or the body:
12875 SIP/2.0 603 Declined
12877 if the REFER request was accepted before approval to follow the
12878 reference could be obtained and that approval was subsequently denied
12879 (see Section 2.4.7).
12881 If there are several REFERs in the same dialog, we need to
12882 match the ID of the event header...
12884 if (option_debug > 2)
12885 ast_log(LOG_DEBUG, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
12886 cmd = ast_skip_blanks(buf);
12887 code = cmd;
12888 /* We are at SIP/2.0 */
12889 while(*code && (*code > 32)) { /* Search white space */
12890 code++;
12892 *code++ = '\0';
12893 code = ast_skip_blanks(code);
12894 sep = code;
12895 sep++;
12896 while(*sep && (*sep > 32)) { /* Search white space */
12897 sep++;
12899 *sep++ = '\0'; /* Response string */
12900 respcode = atoi(code);
12901 switch (respcode) {
12902 case 100: /* Trying: */
12903 case 101: /* dialog establishment */
12904 /* Don't do anything yet */
12905 break;
12906 case 183: /* Ringing: */
12907 /* Don't do anything yet */
12908 break;
12909 case 200: /* OK: The new call is up, hangup this call */
12910 /* Hangup the call that we are replacing */
12911 break;
12912 case 301: /* Moved permenantly */
12913 case 302: /* Moved temporarily */
12914 /* Do we get the header in the packet in this case? */
12915 success = FALSE;
12916 break;
12917 case 503: /* Service Unavailable: The new call failed */
12918 /* Cancel transfer, continue the call */
12919 success = FALSE;
12920 break;
12921 case 603: /* Declined: Not accepted */
12922 /* Cancel transfer, continue the current call */
12923 success = FALSE;
12924 break;
12926 if (!success) {
12927 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
12930 /* Confirm that we received this packet */
12931 transmit_response(p, "200 OK", req);
12934 if (!p->lastinvite)
12935 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12937 return res;
12940 /*! \brief Handle incoming OPTIONS request */
12941 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
12943 int res;
12945 res = get_destination(p, req);
12946 build_contact(p);
12947 /* XXX Should we authenticate OPTIONS? XXX */
12948 if (ast_strlen_zero(p->context))
12949 ast_string_field_set(p, context, default_context);
12950 if (res < 0)
12951 transmit_response_with_allow(p, "404 Not Found", req, 0);
12952 else
12953 transmit_response_with_allow(p, "200 OK", req, 0);
12954 /* Destroy if this OPTIONS was the opening request, but not if
12955 it's in the middle of a normal call flow. */
12956 if (!p->lastinvite)
12957 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12959 return res;
12962 /*! \brief Handle the transfer part of INVITE with a replaces: header,
12963 meaning a target pickup or an attended transfer */
12964 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin)
12966 struct ast_frame *f;
12967 int earlyreplace = 0;
12968 int oneleggedreplace = 0; /* Call with no bridge, propably IVR or voice message */
12969 struct ast_channel *c = p->owner; /* Our incoming call */
12970 struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
12971 struct ast_channel *targetcall; /* The bridge to the take-over target */
12973 /* Check if we're in ring state */
12974 if (replacecall->_state == AST_STATE_RING)
12975 earlyreplace = 1;
12977 /* Check if we have a bridge */
12978 if (!(targetcall = ast_bridged_channel(replacecall))) {
12979 /* We have no bridge */
12980 if (!earlyreplace) {
12981 if (option_debug > 1)
12982 ast_log(LOG_DEBUG, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
12983 oneleggedreplace = 1;
12986 if (option_debug > 3 && targetcall && targetcall->_state == AST_STATE_RINGING)
12987 ast_log(LOG_DEBUG, "SIP transfer: Target channel is in ringing state\n");
12989 if (option_debug > 3) {
12990 if (targetcall)
12991 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);
12992 else
12993 ast_log(LOG_DEBUG, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
12996 if (ignore) {
12997 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
12998 /* We should answer something here. If we are here, the
12999 call we are replacing exists, so an accepted
13000 can't harm */
13001 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
13002 /* Do something more clever here */
13003 ast_channel_unlock(c);
13004 ast_mutex_unlock(&p->refer->refer_call->lock);
13005 return 1;
13007 if (!c) {
13008 /* What to do if no channel ??? */
13009 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
13010 transmit_response_reliable(p, "503 Service Unavailable", req);
13011 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
13012 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13013 ast_mutex_unlock(&p->refer->refer_call->lock);
13014 return 1;
13016 append_history(p, "Xfer", "INVITE/Replace received");
13017 /* We have three channels to play with
13018 channel c: New incoming call
13019 targetcall: Call from PBX to target
13020 p->refer->refer_call: SIP pvt dialog from transferer to pbx.
13021 replacecall: The owner of the previous
13022 We need to masq C into refer_call to connect to
13023 targetcall;
13024 If we are talking to internal audio stream, target call is null.
13027 /* Fake call progress */
13028 transmit_response(p, "100 Trying", req);
13029 ast_setstate(c, AST_STATE_RING);
13031 /* Masquerade the new call into the referred call to connect to target call
13032 Targetcall is not touched by the masq */
13034 /* Answer the incoming call and set channel to UP state */
13035 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
13036 ast_setstate(c, AST_STATE_UP);
13038 /* Stop music on hold and other generators */
13039 ast_quiet_chan(replacecall);
13040 ast_quiet_chan(targetcall);
13041 if (option_debug > 3)
13042 ast_log(LOG_DEBUG, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
13043 /* Unlock clone, but not original (replacecall) */
13044 ast_channel_unlock(c);
13046 /* Unlock PVT */
13047 ast_mutex_unlock(&p->refer->refer_call->lock);
13049 /* Make sure that the masq does not free our PVT for the old call */
13050 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
13052 /* Prepare the masquerade - if this does not happen, we will be gone */
13053 if(ast_channel_masquerade(replacecall, c))
13054 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
13055 else if (option_debug > 3)
13056 ast_log(LOG_DEBUG, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
13058 /* The masquerade will happen as soon as someone reads a frame from the channel */
13060 /* C should now be in place of replacecall */
13061 /* ast_read needs to lock channel */
13062 ast_channel_unlock(c);
13064 if (earlyreplace || oneleggedreplace ) {
13065 /* Force the masq to happen */
13066 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
13067 ast_frfree(f);
13068 f = NULL;
13069 if (option_debug > 3)
13070 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from RING channel!\n");
13071 } else {
13072 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from RING channel \n");
13074 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13075 ast_channel_unlock(replacecall);
13076 } else { /* Bridged call, UP channel */
13077 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
13078 /* Masq ok */
13079 ast_frfree(f);
13080 f = NULL;
13081 if (option_debug > 2)
13082 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from channel! Masq done.\n");
13083 } else {
13084 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from channel. Transfer failed\n");
13086 ast_channel_unlock(replacecall);
13088 ast_mutex_unlock(&p->refer->refer_call->lock);
13090 ast_setstate(c, AST_STATE_DOWN);
13091 if (option_debug > 3) {
13092 struct ast_channel *test;
13093 ast_log(LOG_DEBUG, "After transfer:----------------------------\n");
13094 ast_log(LOG_DEBUG, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
13095 if (replacecall)
13096 ast_log(LOG_DEBUG, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
13097 if (p->owner) {
13098 ast_log(LOG_DEBUG, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
13099 test = ast_bridged_channel(p->owner);
13100 if (test)
13101 ast_log(LOG_DEBUG, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
13102 else
13103 ast_log(LOG_DEBUG, " -- No call bridged to C->owner \n");
13104 } else
13105 ast_log(LOG_DEBUG, " -- No channel yet \n");
13106 ast_log(LOG_DEBUG, "End After transfer:----------------------------\n");
13109 ast_channel_unlock(p->owner); /* Unlock new owner */
13110 ast_mutex_unlock(&p->lock); /* Unlock SIP structure */
13112 /* The call should be down with no ast_channel, so hang it up */
13113 c->tech_pvt = NULL;
13114 ast_hangup(c);
13115 return 0;
13119 /*! \brief Handle incoming INVITE request
13120 \note If the INVITE has a Replaces header, it is part of an
13121 * attended transfer. If so, we do not go through the dial
13122 * plan but tries to find the active call and masquerade
13123 * into it
13125 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)
13127 int res = 1;
13128 int gotdest;
13129 const char *p_replaces;
13130 char *replace_id = NULL;
13131 const char *required;
13132 unsigned int required_profile = 0;
13133 struct ast_channel *c = NULL; /* New channel */
13135 /* Find out what they support */
13136 if (!p->sipoptions) {
13137 const char *supported = get_header(req, "Supported");
13138 if (!ast_strlen_zero(supported))
13139 parse_sip_options(p, supported);
13142 /* Find out what they require */
13143 required = get_header(req, "Require");
13144 if (!ast_strlen_zero(required)) {
13145 required_profile = parse_sip_options(NULL, required);
13146 if (required_profile && required_profile != SIP_OPT_REPLACES) {
13147 /* At this point we only support REPLACES */
13148 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
13149 ast_log(LOG_WARNING,"Received SIP INVITE with unsupported required extension: %s\n", required);
13150 p->invitestate = INV_COMPLETED;
13151 if (!p->lastinvite)
13152 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13153 return -1;
13157 /* Check if this is a loop */
13158 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->owner->_state != AST_STATE_UP)) {
13159 /* This is a call to ourself. Send ourselves an error code and stop
13160 processing immediately, as SIP really has no good mechanism for
13161 being able to call yourself */
13162 /* If pedantic is on, we need to check the tags. If they're different, this is
13163 in fact a forked call through a SIP proxy somewhere. */
13164 transmit_response(p, "482 Loop Detected", req);
13165 p->invitestate = INV_COMPLETED;
13166 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13167 return 0;
13170 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->pendinginvite) {
13171 /* We already have a pending invite. Sorry. You are on hold. */
13172 transmit_response(p, "491 Request Pending", req);
13173 if (option_debug)
13174 ast_log(LOG_DEBUG, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
13175 /* Don't destroy dialog here */
13176 return 0;
13179 p_replaces = get_header(req, "Replaces");
13180 if (!ast_strlen_zero(p_replaces)) {
13181 /* We have a replaces header */
13182 char *ptr;
13183 char *fromtag = NULL;
13184 char *totag = NULL;
13185 char *start, *to;
13186 int error = 0;
13188 if (p->owner) {
13189 if (option_debug > 2)
13190 ast_log(LOG_DEBUG, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
13191 transmit_response(p, "400 Bad request", req); /* The best way to not not accept the transfer */
13192 /* Do not destroy existing call */
13193 return -1;
13196 if (sipdebug && option_debug > 2)
13197 ast_log(LOG_DEBUG, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
13198 /* Create a buffer we can manipulate */
13199 replace_id = ast_strdupa(p_replaces);
13200 ast_uri_decode(replace_id);
13202 if (!p->refer && !sip_refer_allocate(p)) {
13203 transmit_response(p, "500 Server Internal Error", req);
13204 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
13205 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13206 p->invitestate = INV_COMPLETED;
13207 return -1;
13210 /* Todo: (When we find phones that support this)
13211 if the replaces header contains ";early-only"
13212 we can only replace the call in early
13213 stage, not after it's up.
13215 If it's not in early mode, 486 Busy.
13218 /* Skip leading whitespace */
13219 replace_id = ast_skip_blanks(replace_id);
13221 start = replace_id;
13222 while ( (ptr = strsep(&start, ";")) ) {
13223 ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
13224 if ( (to = strcasestr(ptr, "to-tag=") ) )
13225 totag = to + 7; /* skip the keyword */
13226 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
13227 fromtag = to + 9; /* skip the keyword */
13228 fromtag = strsep(&fromtag, "&"); /* trim what ? */
13232 if (sipdebug && option_debug > 3)
13233 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>");
13236 /* Try to find call that we are replacing
13237 If we have a Replaces header, we need to cancel that call if we succeed with this call
13239 if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
13240 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
13241 transmit_response(p, "481 Call Leg Does Not Exist (Replaces)", req);
13242 error = 1;
13245 /* At this point, bot the pvt and the owner of the call to be replaced is locked */
13247 /* The matched call is the call from the transferer to Asterisk .
13248 We want to bridge the bridged part of the call to the
13249 incoming invite, thus taking over the refered call */
13251 if (p->refer->refer_call == p) {
13252 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
13253 p->refer->refer_call = NULL;
13254 transmit_response(p, "400 Bad request", req); /* The best way to not not accept the transfer */
13255 error = 1;
13258 if (!error && !p->refer->refer_call->owner) {
13259 /* Oops, someting wrong anyway, no owner, no call */
13260 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
13261 /* Check for better return code */
13262 transmit_response(p, "481 Call Leg Does Not Exist (Replace)", req);
13263 error = 1;
13266 if (!error && p->refer->refer_call->owner->_state != AST_STATE_RING && p->refer->refer_call->owner->_state != AST_STATE_UP ) {
13267 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
13268 transmit_response(p, "603 Declined (Replaces)", req);
13269 error = 1;
13272 if (error) { /* Give up this dialog */
13273 append_history(p, "Xfer", "INVITE/Replace Failed.");
13274 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13275 ast_mutex_unlock(&p->lock);
13276 if (p->refer->refer_call) {
13277 ast_mutex_unlock(&p->refer->refer_call->lock);
13278 ast_channel_unlock(p->refer->refer_call->owner);
13280 p->invitestate = INV_COMPLETED;
13281 return -1;
13286 /* Check if this is an INVITE that sets up a new dialog or
13287 a re-invite in an existing dialog */
13289 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
13290 int newcall = (p->initreq.headers ? TRUE : FALSE);
13292 sip_cancel_destroy(p);
13293 /* This also counts as a pending invite */
13294 p->pendinginvite = seqno;
13295 check_via(p, req);
13297 copy_request(&p->initreq, req); /* Save this INVITE as the transaction basis */
13298 if (!p->owner) { /* Not a re-invite */
13299 if (debug)
13300 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
13301 if (newcall)
13302 append_history(p, "Invite", "New call: %s", p->callid);
13303 parse_ok_contact(p, req);
13304 } else { /* Re-invite on existing call */
13305 ast_clear_flag(&p->flags[0], SIP_OUTGOING); /* This is now an inbound dialog */
13306 /* Handle SDP here if we already have an owner */
13307 if (find_sdp(req)) {
13308 if (process_sdp(p, req)) {
13309 transmit_response(p, "488 Not acceptable here", req);
13310 if (!p->lastinvite)
13311 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13312 return -1;
13314 } else {
13315 p->jointcapability = p->capability;
13316 if (option_debug)
13317 ast_log(LOG_DEBUG, "Hm.... No sdp for the moment\n");
13319 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) /* This is a response, note what it was for */
13320 append_history(p, "ReInv", "Re-invite received");
13322 } else if (debug)
13323 ast_verbose("Ignoring this INVITE request\n");
13326 if (!p->lastinvite && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner) {
13327 /* This is a new invite */
13328 /* Handle authentication if this is our first invite */
13329 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
13330 if (res == AUTH_CHALLENGE_SENT) {
13331 p->invitestate = INV_COMPLETED; /* Needs to restart in another INVITE transaction */
13332 return 0;
13334 if (res < 0) { /* Something failed in authentication */
13335 if (res == AUTH_FAKE_AUTH) {
13336 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
13337 transmit_fake_auth_response(p, req, 1);
13338 } else {
13339 ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
13340 transmit_response_reliable(p, "403 Forbidden", req);
13342 p->invitestate = INV_COMPLETED;
13343 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13344 ast_string_field_free(p, theirtag);
13345 return 0;
13348 /* We have a succesful authentication, process the SDP portion if there is one */
13349 if (find_sdp(req)) {
13350 if (process_sdp(p, req)) {
13351 /* Unacceptable codecs */
13352 transmit_response_reliable(p, "488 Not acceptable here", req);
13353 p->invitestate = INV_COMPLETED;
13354 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13355 if (option_debug)
13356 ast_log(LOG_DEBUG, "No compatible codecs for this SIP call.\n");
13357 return -1;
13359 } else { /* No SDP in invite, call control session */
13360 p->jointcapability = p->capability;
13361 if (option_debug > 1)
13362 ast_log(LOG_DEBUG, "No SDP in Invite, third party call control\n");
13365 /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
13366 /* This seems redundant ... see !p-owner above */
13367 if (p->owner)
13368 ast_queue_frame(p->owner, &ast_null_frame);
13371 /* Initialize the context if it hasn't been already */
13372 if (ast_strlen_zero(p->context))
13373 ast_string_field_set(p, context, default_context);
13376 /* Check number of concurrent calls -vs- incoming limit HERE */
13377 if (option_debug)
13378 ast_log(LOG_DEBUG, "Checking SIP call limits for device %s\n", p->username);
13379 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
13380 if (res < 0) {
13381 ast_log(LOG_NOTICE, "Failed to place call for user %s, too many calls\n", p->username);
13382 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
13383 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13384 p->invitestate = INV_COMPLETED;
13386 return 0;
13388 gotdest = get_destination(p, NULL); /* Get destination right away */
13389 get_rdnis(p, NULL); /* Get redirect information */
13390 extract_uri(p, req); /* Get the Contact URI */
13391 build_contact(p); /* Build our contact header */
13393 if (p->rtp) {
13394 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
13395 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
13398 if (!replace_id && gotdest) { /* No matching extension found */
13399 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
13400 transmit_response_reliable(p, "484 Address Incomplete", req);
13401 else
13402 transmit_response_reliable(p, "404 Not Found", req);
13403 p->invitestate = INV_COMPLETED;
13404 update_call_counter(p, DEC_CALL_LIMIT);
13405 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13406 return 0;
13407 } else {
13408 /* If no extension was specified, use the s one */
13409 /* Basically for calling to IP/Host name only */
13410 if (ast_strlen_zero(p->exten))
13411 ast_string_field_set(p, exten, "s");
13412 /* Initialize our tag */
13414 make_our_tag(p->tag, sizeof(p->tag));
13416 /* First invitation - create the channel */
13417 c = sip_new(p, AST_STATE_DOWN, S_OR(p->username, NULL));
13418 *recount = 1;
13420 /* Save Record-Route for any later requests we make on this dialogue */
13421 build_route(p, req, 0);
13423 if (c) {
13424 /* Pre-lock the call */
13425 ast_channel_lock(c);
13428 } else {
13429 if (option_debug > 1 && sipdebug) {
13430 if (!ast_test_flag(req, SIP_PKT_IGNORE))
13431 ast_log(LOG_DEBUG, "Got a SIP re-invite for call %s\n", p->callid);
13432 else
13433 ast_log(LOG_DEBUG, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
13435 c = p->owner;
13438 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
13439 p->lastinvite = seqno;
13441 if (replace_id) { /* Attended transfer or call pickup - we're the target */
13442 /* Go and take over the target call */
13443 if (sipdebug && option_debug > 3)
13444 ast_log(LOG_DEBUG, "Sending this call to the invite/replcaes handler %s\n", p->callid);
13445 return handle_invite_replaces(p, req, debug, ast_test_flag(req, SIP_PKT_IGNORE), seqno, sin);
13449 if (c) { /* We have a call -either a new call or an old one (RE-INVITE) */
13450 switch(c->_state) {
13451 case AST_STATE_DOWN:
13452 if (option_debug > 1)
13453 ast_log(LOG_DEBUG, "%s: New call is still down.... Trying... \n", c->name);
13454 transmit_response(p, "100 Trying", req);
13455 p->invitestate = INV_PROCEEDING;
13456 ast_setstate(c, AST_STATE_RING);
13457 if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
13458 enum ast_pbx_result res;
13460 res = ast_pbx_start(c);
13462 switch(res) {
13463 case AST_PBX_FAILED:
13464 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
13465 p->invitestate = INV_COMPLETED;
13466 if (ast_test_flag(req, SIP_PKT_IGNORE))
13467 transmit_response(p, "503 Unavailable", req);
13468 else
13469 transmit_response_reliable(p, "503 Unavailable", req);
13470 break;
13471 case AST_PBX_CALL_LIMIT:
13472 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
13473 p->invitestate = INV_COMPLETED;
13474 if (ast_test_flag(req, SIP_PKT_IGNORE))
13475 transmit_response(p, "480 Temporarily Unavailable", req);
13476 else
13477 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
13478 break;
13479 case AST_PBX_SUCCESS:
13480 /* nothing to do */
13481 break;
13484 if (res) {
13486 /* Unlock locks so ast_hangup can do its magic */
13487 ast_mutex_unlock(&c->lock);
13488 ast_mutex_unlock(&p->lock);
13489 ast_hangup(c);
13490 ast_mutex_lock(&p->lock);
13491 c = NULL;
13493 } else { /* Pickup call in call group */
13494 ast_channel_unlock(c);
13495 if (ast_pickup_call(c)) {
13496 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
13497 if (ast_test_flag(req, SIP_PKT_IGNORE))
13498 transmit_response(p, "503 Unavailable", req); /* OEJ - Right answer? */
13499 else
13500 transmit_response_reliable(p, "503 Unavailable", req);
13501 sip_alreadygone(p);
13502 /* Unlock locks so ast_hangup can do its magic */
13503 ast_mutex_unlock(&p->lock);
13504 c->hangupcause = AST_CAUSE_CALL_REJECTED;
13505 } else {
13506 ast_mutex_unlock(&p->lock);
13507 ast_setstate(c, AST_STATE_DOWN);
13508 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
13510 p->invitestate = INV_COMPLETED;
13511 ast_hangup(c);
13512 ast_mutex_lock(&p->lock);
13513 c = NULL;
13515 break;
13516 case AST_STATE_RING:
13517 transmit_response(p, "100 Trying", req);
13518 p->invitestate = INV_PROCEEDING;
13519 break;
13520 case AST_STATE_RINGING:
13521 transmit_response(p, "180 Ringing", req);
13522 p->invitestate = INV_PROCEEDING;
13523 break;
13524 case AST_STATE_UP:
13525 if (option_debug > 1)
13526 ast_log(LOG_DEBUG, "%s: This call is UP.... \n", c->name);
13528 if (p->t38.state == T38_PEER_REINVITE) {
13529 struct ast_channel *bridgepeer = NULL;
13530 struct sip_pvt *bridgepvt = NULL;
13532 if ((bridgepeer = ast_bridged_channel(p->owner))) {
13533 /* 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*/
13534 /*! XXX: we should also check here does the other side supports t38 at all !!! XXX */
13535 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
13536 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
13537 if (bridgepvt->t38.state == T38_DISABLED) {
13538 if (bridgepvt->udptl) { /* If everything is OK with other side's udptl struct */
13539 /* Send re-invite to the bridged channel */
13540 sip_handle_t38_reinvite(bridgepeer, p, 1);
13541 } else { /* Something is wrong with peers udptl struct */
13542 ast_log(LOG_WARNING, "Strange... The other side of the bridge don't have udptl struct\n");
13543 ast_mutex_lock(&bridgepvt->lock);
13544 bridgepvt->t38.state = T38_DISABLED;
13545 ast_mutex_unlock(&bridgepvt->lock);
13546 if (option_debug > 1)
13547 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->name);
13548 if (ast_test_flag(req, SIP_PKT_IGNORE))
13549 transmit_response(p, "488 Not acceptable here", req);
13550 else
13551 transmit_response_reliable(p, "488 Not acceptable here", req);
13554 } else {
13555 /* The other side is already setup for T.38 most likely so we need to acknowledge this too */
13556 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
13557 p->t38.state = T38_ENABLED;
13558 if (option_debug)
13559 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
13561 } else {
13562 /* Other side is not a SIP channel */
13563 if (ast_test_flag(req, SIP_PKT_IGNORE))
13564 transmit_response(p, "488 Not acceptable here", req);
13565 else
13566 transmit_response_reliable(p, "488 Not acceptable here", req);
13567 p->t38.state = T38_DISABLED;
13568 if (option_debug > 1)
13569 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
13571 if (!p->lastinvite) /* Only destroy if this is *not* a re-invite */
13572 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13574 } else {
13575 /* we are not bridged in a call */
13576 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
13577 p->t38.state = T38_ENABLED;
13578 if (option_debug)
13579 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
13581 } else if (p->t38.state == T38_DISABLED) { /* Channel doesn't have T38 offered or enabled */
13582 int sendok = TRUE;
13584 /* If we are bridged to a channel that has T38 enabled than this is a case of RTP re-invite after T38 session */
13585 /* so handle it here (re-invite other party to RTP) */
13586 struct ast_channel *bridgepeer = NULL;
13587 struct sip_pvt *bridgepvt = NULL;
13588 if ((bridgepeer = ast_bridged_channel(p->owner))) {
13589 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
13590 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
13591 /* Does the bridged peer have T38 ? */
13592 if (bridgepvt->t38.state == T38_ENABLED) {
13593 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
13594 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
13595 if (ast_test_flag(req, SIP_PKT_IGNORE))
13596 transmit_response(p, "488 Not Acceptable Here (unsupported)", req);
13597 else
13598 transmit_response_reliable(p, "488 Not Acceptable Here (unsupported)", req);
13599 sendok = FALSE;
13601 /* No bridged peer with T38 enabled*/
13604 /* Respond to normal re-invite */
13605 if (sendok)
13606 transmit_response_with_sdp(p, "200 OK", req, XMIT_CRITICAL);
13609 p->invitestate = INV_TERMINATED;
13610 break;
13611 default:
13612 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
13613 transmit_response(p, "100 Trying", req);
13614 break;
13616 } else {
13617 if (p && (p->autokillid == -1)) {
13618 const char *msg;
13620 if (!p->jointcapability)
13621 msg = "488 Not Acceptable Here (codec error)";
13622 else {
13623 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
13624 msg = "503 Unavailable";
13626 if (ast_test_flag(req, SIP_PKT_IGNORE))
13627 transmit_response(p, msg, req);
13628 else
13629 transmit_response_reliable(p, msg, req);
13630 p->invitestate = INV_COMPLETED;
13631 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13634 return res;
13637 /*! \brief Find all call legs and bridge transferee with target
13638 * called from handle_request_refer */
13639 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
13641 struct sip_dual target; /* Chan 1: Call from tranferer to Asterisk */
13642 /* Chan 2: Call from Asterisk to target */
13643 int res = 0;
13644 struct sip_pvt *targetcall_pvt;
13646 /* Check if the call ID of the replaces header does exist locally */
13647 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
13648 transferer->refer->replaces_callid_fromtag))) {
13649 if (transferer->refer->localtransfer) {
13650 /* We did not find the refered call. Sorry, can't accept then */
13651 transmit_response(transferer, "202 Accepted", req);
13652 /* Let's fake a response from someone else in order
13653 to follow the standard */
13654 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
13655 append_history(transferer, "Xfer", "Refer failed");
13656 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
13657 transferer->refer->status = REFER_FAILED;
13658 return -1;
13660 /* Fall through for remote transfers that we did not find locally */
13661 if (option_debug > 2)
13662 ast_log(LOG_DEBUG, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
13663 return 0;
13666 /* Ok, we can accept this transfer */
13667 transmit_response(transferer, "202 Accepted", req);
13668 append_history(transferer, "Xfer", "Refer accepted");
13669 if (!targetcall_pvt->owner) { /* No active channel */
13670 if (option_debug > 3)
13671 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No owner of target call\n");
13672 /* Cancel transfer */
13673 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
13674 append_history(transferer, "Xfer", "Refer failed");
13675 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
13676 transferer->refer->status = REFER_FAILED;
13677 ast_mutex_unlock(&targetcall_pvt->lock);
13678 ast_channel_unlock(current->chan1);
13679 ast_channel_unlock(targetcall_pvt->owner);
13680 return -1;
13683 /* We have a channel, find the bridge */
13684 target.chan1 = targetcall_pvt->owner; /* Transferer to Asterisk */
13685 target.chan2 = ast_bridged_channel(targetcall_pvt->owner); /* Asterisk to target */
13687 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
13688 /* Wrong state of new channel */
13689 if (option_debug > 3) {
13690 if (target.chan2)
13691 ast_log(LOG_DEBUG, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
13692 else if (target.chan1->_state != AST_STATE_RING)
13693 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No target channel\n");
13694 else
13695 ast_log(LOG_DEBUG, "SIP attended transfer: Attempting transfer in ringing state\n");
13699 /* Transfer */
13700 if (option_debug > 3 && sipdebug) {
13701 if (current->chan2) /* We have two bridges */
13702 ast_log(LOG_DEBUG, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
13703 else /* One bridge, propably transfer of IVR/voicemail etc */
13704 ast_log(LOG_DEBUG, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
13707 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
13709 /* Perform the transfer */
13710 res = attempt_transfer(current, &target);
13711 ast_mutex_unlock(&targetcall_pvt->lock);
13712 if (res) {
13713 /* Failed transfer */
13714 /* Could find better message, but they will get the point */
13715 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy", TRUE);
13716 append_history(transferer, "Xfer", "Refer failed");
13717 if (targetcall_pvt->owner)
13718 ast_channel_unlock(targetcall_pvt->owner);
13719 /* Right now, we have to hangup, sorry. Bridge is destroyed */
13720 ast_hangup(transferer->owner);
13721 } else {
13722 /* Transfer succeeded! */
13724 /* Tell transferer that we're done. */
13725 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
13726 append_history(transferer, "Xfer", "Refer succeeded");
13727 transferer->refer->status = REFER_200OK;
13728 if (targetcall_pvt->owner) {
13729 if (option_debug)
13730 ast_log(LOG_DEBUG, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
13731 ast_channel_unlock(targetcall_pvt->owner);
13734 return 1;
13738 /*! \brief Handle incoming REFER request */
13739 /*! \page SIP_REFER SIP transfer Support (REFER)
13741 REFER is used for call transfer in SIP. We get a REFER
13742 to place a new call with an INVITE somwhere and then
13743 keep the transferor up-to-date of the transfer. If the
13744 transfer fails, get back on line with the orginal call.
13746 - REFER can be sent outside or inside of a dialog.
13747 Asterisk only accepts REFER inside of a dialog.
13749 - If we get a replaces header, it is an attended transfer
13751 \par Blind transfers
13752 The transferor provides the transferee
13753 with the transfer targets contact. The signalling between
13754 transferer or transferee should not be cancelled, so the
13755 call is recoverable if the transfer target can not be reached
13756 by the transferee.
13758 In this case, Asterisk receives a TRANSFER from
13759 the transferor, thus is the transferee. We should
13760 try to set up a call to the contact provided
13761 and if that fails, re-connect the current session.
13762 If the new call is set up, we issue a hangup.
13763 In this scenario, we are following section 5.2
13764 in the SIP CC Transfer draft. (Transfer without
13765 a GRUU)
13767 \par Transfer with consultation hold
13768 In this case, the transferor
13769 talks to the transfer target before the transfer takes place.
13770 This is implemented with SIP hold and transfer.
13771 Note: The invite From: string could indicate a transfer.
13772 (Section 6. Transfer with consultation hold)
13773 The transferor places the transferee on hold, starts a call
13774 with the transfer target to alert them to the impending
13775 transfer, terminates the connection with the target, then
13776 proceeds with the transfer (as in Blind transfer above)
13778 \par Attended transfer
13779 The transferor places the transferee
13780 on hold, calls the transfer target to alert them,
13781 places the target on hold, then proceeds with the transfer
13782 using a Replaces header field in the Refer-to header. This
13783 will force the transfee to send an Invite to the target,
13784 with a replaces header that instructs the target to
13785 hangup the call between the transferor and the target.
13786 In this case, the Refer/to: uses the AOR address. (The same
13787 URI that the transferee used to establish the session with
13788 the transfer target (To: ). The Require: replaces header should
13789 be in the INVITE to avoid the wrong UA in a forked SIP proxy
13790 scenario to answer and have no call to replace with.
13792 The referred-by header is *NOT* required, but if we get it,
13793 can be copied into the INVITE to the transfer target to
13794 inform the target about the transferor
13796 "Any REFER request has to be appropriately authenticated.".
13798 We can't destroy dialogs, since we want the call to continue.
13801 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock)
13803 struct sip_dual current; /* Chan1: Call between asterisk and transferer */
13804 /* Chan2: Call between asterisk and transferee */
13806 int res = 0;
13808 if (ast_test_flag(req, SIP_PKT_DEBUG))
13809 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");
13811 if (!p->owner) {
13812 /* This is a REFER outside of an existing SIP dialog */
13813 /* We can't handle that, so decline it */
13814 if (option_debug > 2)
13815 ast_log(LOG_DEBUG, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
13816 transmit_response(p, "603 Declined (No dialog)", req);
13817 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
13818 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
13819 sip_alreadygone(p);
13820 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13822 return 0;
13826 /* Check if transfer is allowed from this device */
13827 if (p->allowtransfer == TRANSFER_CLOSED ) {
13828 /* Transfer not allowed, decline */
13829 transmit_response(p, "603 Declined (policy)", req);
13830 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
13831 /* Do not destroy SIP session */
13832 return 0;
13835 if(!ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
13836 /* Already have a pending REFER */
13837 transmit_response(p, "491 Request pending", req);
13838 append_history(p, "Xfer", "Refer failed. Request pending.");
13839 return 0;
13842 /* Allocate memory for call transfer data */
13843 if (!p->refer && !sip_refer_allocate(p)) {
13844 transmit_response(p, "500 Internal Server Error", req);
13845 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
13846 return -3;
13849 res = get_refer_info(p, req); /* Extract headers */
13851 p->refer->status = REFER_SENT;
13853 if (res != 0) {
13854 switch (res) {
13855 case -2: /* Syntax error */
13856 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
13857 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
13858 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
13859 ast_log(LOG_DEBUG, "SIP transfer to black hole can't be handled (no refer-to: )\n");
13860 break;
13861 case -3:
13862 transmit_response(p, "603 Declined (Non sip: uri)", req);
13863 append_history(p, "Xfer", "Refer failed. Non SIP uri");
13864 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
13865 ast_log(LOG_DEBUG, "SIP transfer to non-SIP uri denied\n");
13866 break;
13867 default:
13868 /* Refer-to extension not found, fake a failed transfer */
13869 transmit_response(p, "202 Accepted", req);
13870 append_history(p, "Xfer", "Refer failed. Bad extension.");
13871 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
13872 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
13873 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
13874 ast_log(LOG_DEBUG, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
13875 break;
13877 return 0;
13879 if (ast_strlen_zero(p->context))
13880 ast_string_field_set(p, context, default_context);
13882 /* If we do not support SIP domains, all transfers are local */
13883 if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
13884 p->refer->localtransfer = 1;
13885 if (sipdebug && option_debug > 2)
13886 ast_log(LOG_DEBUG, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
13887 } else if (AST_LIST_EMPTY(&domain_list)) {
13888 /* This PBX don't bother with SIP domains, so all transfers are local */
13889 p->refer->localtransfer = 1;
13890 } else
13891 if (sipdebug && option_debug > 2)
13892 ast_log(LOG_DEBUG, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
13894 /* Is this a repeat of a current request? Ignore it */
13895 /* Don't know what else to do right now. */
13896 if (ignore)
13897 return res;
13899 /* If this is a blind transfer, we have the following
13900 channels to work with:
13901 - chan1, chan2: The current call between transferer and transferee (2 channels)
13902 - target_channel: A new call from the transferee to the target (1 channel)
13903 We need to stay tuned to what happens in order to be able
13904 to bring back the call to the transferer */
13906 /* If this is a attended transfer, we should have all call legs within reach:
13907 - chan1, chan2: The call between the transferer and transferee (2 channels)
13908 - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
13909 We want to bridge chan2 with targetcall_pvt!
13911 The replaces call id in the refer message points
13912 to the call leg between Asterisk and the transferer.
13913 So we need to connect the target and the transferee channel
13914 and hangup the two other channels silently
13916 If the target is non-local, the call ID could be on a remote
13917 machine and we need to send an INVITE with replaces to the
13918 target. We basically handle this as a blind transfer
13919 and let the sip_call function catch that we need replaces
13920 header in the INVITE.
13924 /* Get the transferer's channel */
13925 current.chan1 = p->owner;
13927 /* Find the other part of the bridge (2) - transferee */
13928 current.chan2 = ast_bridged_channel(current.chan1);
13930 if (sipdebug && option_debug > 2)
13931 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>");
13933 if (!current.chan2 && !p->refer->attendedtransfer) {
13934 /* No bridged channel, propably IVR or echo or similar... */
13935 /* Guess we should masquerade or something here */
13936 /* Until we figure it out, refuse transfer of such calls */
13937 if (sipdebug && option_debug > 2)
13938 ast_log(LOG_DEBUG,"Refused SIP transfer on non-bridged channel.\n");
13939 p->refer->status = REFER_FAILED;
13940 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
13941 transmit_response(p, "603 Declined", req);
13942 return -1;
13945 if (current.chan2) {
13946 if (sipdebug && option_debug > 3)
13947 ast_log(LOG_DEBUG, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
13949 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
13952 ast_set_flag(&p->flags[0], SIP_GOTREFER);
13954 /* Attended transfer: Find all call legs and bridge transferee with target*/
13955 if (p->refer->attendedtransfer) {
13956 if ((res = local_attended_transfer(p, &current, req, seqno)))
13957 return res; /* We're done with the transfer */
13958 /* Fall through for remote transfers that we did not find locally */
13959 if (sipdebug && option_debug > 3)
13960 ast_log(LOG_DEBUG, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
13961 /* Fallthrough if we can't find the call leg internally */
13965 /* Parking a call */
13966 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
13967 /* Must release c's lock now, because it will not longer be accessible after the transfer! */
13968 *nounlock = 1;
13969 ast_channel_unlock(current.chan1);
13970 copy_request(&current.req, req);
13971 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
13972 p->refer->status = REFER_200OK;
13973 append_history(p, "Xfer", "REFER to call parking.");
13974 if (sipdebug && option_debug > 3)
13975 ast_log(LOG_DEBUG, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
13976 sip_park(current.chan2, current.chan1, req, seqno);
13977 return res;
13980 /* Blind transfers and remote attended xfers */
13981 transmit_response(p, "202 Accepted", req);
13983 if (current.chan1 && current.chan2) {
13984 if (option_debug > 2)
13985 ast_log(LOG_DEBUG, "chan1->name: %s\n", current.chan1->name);
13986 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
13988 if (current.chan2) {
13989 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
13990 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
13991 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
13992 /* One for the new channel */
13993 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
13994 /* Attended transfer to remote host, prepare headers for the INVITE */
13995 if (p->refer->referred_by)
13996 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
13998 /* Generate a Replaces string to be used in the INVITE during attended transfer */
13999 if (p->refer->replaces_callid && !ast_strlen_zero(p->refer->replaces_callid)) {
14000 char tempheader[BUFSIZ];
14001 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
14002 p->refer->replaces_callid_totag ? ";to-tag=" : "",
14003 p->refer->replaces_callid_totag,
14004 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
14005 p->refer->replaces_callid_fromtag);
14006 if (current.chan2)
14007 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
14009 /* Must release lock now, because it will not longer
14010 be accessible after the transfer! */
14011 *nounlock = 1;
14012 ast_channel_unlock(current.chan1);
14013 ast_channel_unlock(current.chan2);
14015 /* Connect the call */
14017 /* FAKE ringing if not attended transfer */
14018 if (!p->refer->attendedtransfer)
14019 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
14021 /* For blind transfer, this will lead to a new call */
14022 /* For attended transfer to remote host, this will lead to
14023 a new SIP call with a replaces header, if the dial plan allows it
14025 if (!current.chan2) {
14026 /* We have no bridge, so we're talking with Asterisk somehow */
14027 /* We need to masquerade this call */
14028 /* What to do to fix this situation:
14029 * Set up the new call in a new channel
14030 * Let the new channel masq into this channel
14031 Please add that code here :-)
14033 p->refer->status = REFER_FAILED;
14034 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
14035 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14036 append_history(p, "Xfer", "Refer failed (only bridged calls).");
14037 return -1;
14039 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
14041 /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
14042 servers - generate an INVITE with Replaces. Either way, let the dial plan decided */
14043 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
14045 if (!res) {
14046 /* Success - we have a new channel */
14047 if (option_debug > 2)
14048 ast_log(LOG_DEBUG, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
14049 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
14050 if (p->refer->localtransfer)
14051 p->refer->status = REFER_200OK;
14052 if (p->owner)
14053 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
14054 append_history(p, "Xfer", "Refer succeeded.");
14055 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14056 /* Do not hangup call, the other side do that when we say 200 OK */
14057 /* We could possibly implement a timer here, auto congestion */
14058 res = 0;
14059 } else {
14060 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
14061 if (option_debug > 2)
14062 ast_log(LOG_DEBUG, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
14063 append_history(p, "Xfer", "Refer failed.");
14064 /* Failure of some kind */
14065 p->refer->status = REFER_FAILED;
14066 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
14067 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14068 res = -1;
14070 return res;
14073 /*! \brief Handle incoming CANCEL request */
14074 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
14077 check_via(p, req);
14078 sip_alreadygone(p);
14079 p->invitestate = INV_CANCELLED;
14081 if (p->owner && p->owner->_state == AST_STATE_UP) {
14082 /* This call is up, cancel is ignored, we need a bye */
14083 transmit_response(p, "200 OK", req);
14084 if (option_debug)
14085 ast_log(LOG_DEBUG, "Got CANCEL on an answered call. Ignoring... \n");
14086 return 0;
14088 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
14090 if (p->owner)
14091 ast_queue_hangup(p->owner);
14092 else
14093 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14094 if (p->initreq.len > 0) {
14095 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
14096 transmit_response(p, "200 OK", req);
14097 return 1;
14098 } else {
14099 transmit_response(p, "481 Call Leg Does Not Exist", req);
14100 return 0;
14104 /*! \brief Handle incoming BYE request */
14105 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
14107 struct ast_channel *c=NULL;
14108 int res;
14109 struct ast_channel *bridged_to;
14111 /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
14112 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner)
14113 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
14115 p->invitestate = INV_TERMINATED;
14117 copy_request(&p->initreq, req);
14118 check_via(p, req);
14119 sip_alreadygone(p);
14121 /* Get RTCP quality before end of call */
14122 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY) || p->owner) {
14123 char *audioqos, *videoqos;
14124 if (p->rtp) {
14125 audioqos = ast_rtp_get_quality(p->rtp);
14126 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
14127 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
14128 if (p->owner)
14129 pbx_builtin_setvar_helper(p->owner, "RTPAUDIOQOS", audioqos);
14131 if (p->vrtp) {
14132 videoqos = ast_rtp_get_quality(p->vrtp);
14133 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
14134 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
14135 if (p->owner)
14136 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
14140 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
14142 if (!ast_strlen_zero(get_header(req, "Also"))) {
14143 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
14144 ast_inet_ntoa(p->recv.sin_addr));
14145 if (ast_strlen_zero(p->context))
14146 ast_string_field_set(p, context, default_context);
14147 res = get_also_info(p, req);
14148 if (!res) {
14149 c = p->owner;
14150 if (c) {
14151 bridged_to = ast_bridged_channel(c);
14152 if (bridged_to) {
14153 /* Don't actually hangup here... */
14154 ast_queue_control(c, AST_CONTROL_UNHOLD);
14155 ast_async_goto(bridged_to, p->context, p->refer->refer_to,1);
14156 } else
14157 ast_queue_hangup(p->owner);
14159 } else {
14160 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
14161 if (p->owner)
14162 ast_queue_hangup(p->owner);
14164 } else if (p->owner) {
14165 ast_queue_hangup(p->owner);
14166 if (option_debug > 2)
14167 ast_log(LOG_DEBUG, "Received bye, issuing owner hangup\n");
14168 } else {
14169 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14170 if (option_debug > 2)
14171 ast_log(LOG_DEBUG, "Received bye, no owner, selfdestruct soon.\n");
14173 transmit_response(p, "200 OK", req);
14175 return 1;
14178 /*! \brief Handle incoming MESSAGE request */
14179 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
14181 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
14182 if (ast_test_flag(req, SIP_PKT_DEBUG))
14183 ast_verbose("Receiving message!\n");
14184 receive_message(p, req);
14185 } else
14186 transmit_response(p, "202 Accepted", req);
14187 return 1;
14190 /*! \brief Handle incoming SUBSCRIBE request */
14191 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
14193 int gotdest;
14194 int res = 0;
14195 int firststate = AST_EXTENSION_REMOVED;
14196 struct sip_peer *authpeer = NULL;
14197 const char *eventheader = get_header(req, "Event"); /* Get Event package name */
14198 const char *accept = get_header(req, "Accept");
14199 int resubscribe = (p->subscribed != NONE);
14200 char *temp, *event;
14202 if (p->initreq.headers) {
14203 /* We already have a dialog */
14204 if (p->initreq.method != SIP_SUBSCRIBE) {
14205 /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
14206 /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
14207 transmit_response(p, "403 Forbidden (within dialog)", req);
14208 /* Do not destroy session, since we will break the call if we do */
14209 if (option_debug)
14210 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);
14211 return 0;
14212 } else if (ast_test_flag(req, SIP_PKT_DEBUG)) {
14213 if (option_debug) {
14214 if (resubscribe)
14215 ast_log(LOG_DEBUG, "Got a re-subscribe on existing subscription %s\n", p->callid);
14216 else
14217 ast_log(LOG_DEBUG, "Got a new subscription %s (possibly with auth)\n", p->callid);
14222 /* Check if we have a global disallow setting on subscriptions.
14223 if so, we don't have to check peer/user settings after auth, which saves a lot of processing
14225 if (!global_allowsubscribe) {
14226 transmit_response(p, "403 Forbidden (policy)", req);
14227 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14228 return 0;
14231 if (!ast_test_flag(req, SIP_PKT_IGNORE) && !resubscribe) { /* Set up dialog, new subscription */
14232 /* Use this as the basis */
14233 if (ast_test_flag(req, SIP_PKT_DEBUG))
14234 ast_verbose("Creating new subscription\n");
14236 copy_request(&p->initreq, req);
14237 check_via(p, req);
14238 } else if (ast_test_flag(req, SIP_PKT_DEBUG) && ast_test_flag(req, SIP_PKT_IGNORE))
14239 ast_verbose("Ignoring this SUBSCRIBE request\n");
14241 /* Find parameters to Event: header value and remove them for now */
14242 if (ast_strlen_zero(eventheader)) {
14243 transmit_response(p, "489 Bad Event", req);
14244 if (option_debug > 1)
14245 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: <none>\n");
14246 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14247 return 0;
14250 if ( (strchr(eventheader, ';'))) {
14251 event = ast_strdupa(eventheader); /* Since eventheader is a const, we can't change it */
14252 temp = strchr(event, ';');
14253 *temp = '\0'; /* Remove any options for now */
14254 /* We might need to use them later :-) */
14255 } else
14256 event = (char *) eventheader; /* XXX is this legal ? */
14258 /* Handle authentication */
14259 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
14260 /* if an authentication response was sent, we are done here */
14261 if (res == AUTH_CHALLENGE_SENT) {
14262 if (authpeer)
14263 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14264 return 0;
14266 if (res < 0) {
14267 if (res == AUTH_FAKE_AUTH) {
14268 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
14269 transmit_fake_auth_response(p, req, 1);
14270 } else {
14271 ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
14272 transmit_response_reliable(p, "403 Forbidden", req);
14274 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14275 if (authpeer)
14276 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14277 return 0;
14280 /* Check if this user/peer is allowed to subscribe at all */
14281 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
14282 transmit_response(p, "403 Forbidden (policy)", req);
14283 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14284 if (authpeer)
14285 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14286 return 0;
14289 /* Get destination right away */
14290 gotdest = get_destination(p, NULL);
14292 /* Initialize the context if it hasn't been already;
14293 note this is done _after_ handling any domain lookups,
14294 because the context specified there is for calls, not
14295 subscriptions
14297 if (!ast_strlen_zero(p->subscribecontext))
14298 ast_string_field_set(p, context, p->subscribecontext);
14299 else if (ast_strlen_zero(p->context))
14300 ast_string_field_set(p, context, default_context);
14302 build_contact(p);
14303 if (gotdest) {
14304 transmit_response(p, "404 Not Found", req);
14305 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14306 if (authpeer)
14307 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14308 return 0;
14311 /* Initialize tag for new subscriptions */
14312 if (ast_strlen_zero(p->tag))
14313 make_our_tag(p->tag, sizeof(p->tag));
14315 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
14316 if (authpeer) /* No need for authpeer here */
14317 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14319 /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
14320 /* Polycom phones only handle xpidf+xml, even if they say they can
14321 handle pidf+xml as well
14323 if (strstr(p->useragent, "Polycom")) {
14324 p->subscribed = XPIDF_XML;
14325 } else if (strstr(accept, "application/pidf+xml")) {
14326 p->subscribed = PIDF_XML; /* RFC 3863 format */
14327 } else if (strstr(accept, "application/dialog-info+xml")) {
14328 p->subscribed = DIALOG_INFO_XML;
14329 /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
14330 } else if (strstr(accept, "application/cpim-pidf+xml")) {
14331 p->subscribed = CPIM_PIDF_XML; /* RFC 3863 format */
14332 } else if (strstr(accept, "application/xpidf+xml")) {
14333 p->subscribed = XPIDF_XML; /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
14334 } else {
14335 /* Can't find a format for events that we know about */
14336 transmit_response(p, "489 Bad Event", req);
14337 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14338 return 0;
14340 } else if (!strcmp(event, "message-summary")) {
14341 if (!ast_strlen_zero(accept) && strcmp(accept, "application/simple-message-summary")) {
14342 /* Format requested that we do not support */
14343 transmit_response(p, "406 Not Acceptable", req);
14344 if (option_debug > 1)
14345 ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", accept);
14346 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14347 if (authpeer) /* No need for authpeer here */
14348 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14349 return 0;
14351 /* Looks like they actually want a mailbox status
14352 This version of Asterisk supports mailbox subscriptions
14353 The subscribed URI needs to exist in the dial plan
14354 In most devices, this is configurable to the voicemailmain extension you use
14356 if (!authpeer || ast_strlen_zero(authpeer->mailbox)) {
14357 transmit_response(p, "404 Not found (no mailbox)", req);
14358 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14359 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
14360 if (authpeer) /* No need for authpeer here */
14361 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14362 return 0;
14365 p->subscribed = MWI_NOTIFICATION;
14366 if (authpeer->mwipvt && authpeer->mwipvt != p) /* Destroy old PVT if this is a new one */
14367 /* We only allow one subscription per peer */
14368 sip_destroy(authpeer->mwipvt);
14369 authpeer->mwipvt = p; /* Link from peer to pvt */
14370 p->relatedpeer = authpeer; /* Link from pvt to peer */
14371 } else { /* At this point, Asterisk does not understand the specified event */
14372 transmit_response(p, "489 Bad Event", req);
14373 if (option_debug > 1)
14374 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: %s\n", event);
14375 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14376 if (authpeer) /* No need for authpeer here */
14377 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14378 return 0;
14381 if (p->subscribed != MWI_NOTIFICATION && !resubscribe)
14382 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, p);
14384 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
14385 p->lastinvite = seqno;
14386 if (p && !ast_test_flag(&p->flags[0], SIP_NEEDDESTROY)) {
14387 p->expiry = atoi(get_header(req, "Expires"));
14389 /* check if the requested expiry-time is within the approved limits from sip.conf */
14390 if (p->expiry > max_expiry)
14391 p->expiry = max_expiry;
14392 if (p->expiry < min_expiry && p->expiry > 0)
14393 p->expiry = min_expiry;
14395 if (sipdebug || option_debug > 1) {
14396 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
14397 ast_log(LOG_DEBUG, "Adding subscription for mailbox notification - peer %s Mailbox %s\n", p->relatedpeer->name, p->relatedpeer->mailbox);
14398 else
14399 ast_log(LOG_DEBUG, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
14401 if (p->autokillid > -1)
14402 sip_cancel_destroy(p); /* Remove subscription expiry for renewals */
14403 if (p->expiry > 0)
14404 sip_scheddestroy(p, (p->expiry + 10) * 1000); /* Set timer for destruction of call at expiration */
14406 if (p->subscribed == MWI_NOTIFICATION) {
14407 transmit_response(p, "200 OK", req);
14408 if (p->relatedpeer) { /* Send first notification */
14409 ASTOBJ_WRLOCK(p->relatedpeer);
14410 sip_send_mwi_to_peer(p->relatedpeer);
14411 ASTOBJ_UNLOCK(p->relatedpeer);
14413 } else {
14414 struct sip_pvt *p_old;
14416 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
14418 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));
14419 transmit_response(p, "404 Not found", req);
14420 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14421 return 0;
14424 transmit_response(p, "200 OK", req);
14425 transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
14426 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
14427 /* hide the 'complete' exten/context in the refer_to field for later display */
14428 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
14430 /* remove any old subscription from this peer for the same exten/context,
14431 as the peer has obviously forgotten about it and it's wasteful to wait
14432 for it to expire and send NOTIFY messages to the peer only to have them
14433 ignored (or generate errors)
14435 ast_mutex_lock(&iflock);
14436 for (p_old = iflist; p_old; p_old = p_old->next) {
14437 if (p_old == p)
14438 continue;
14439 if (p_old->initreq.method != SIP_SUBSCRIBE)
14440 continue;
14441 if (p_old->subscribed == NONE)
14442 continue;
14443 ast_mutex_lock(&p_old->lock);
14444 if (!strcmp(p_old->username, p->username)) {
14445 if (!strcmp(p_old->exten, p->exten) &&
14446 !strcmp(p_old->context, p->context)) {
14447 ast_set_flag(&p_old->flags[0], SIP_NEEDDESTROY);
14448 ast_mutex_unlock(&p_old->lock);
14449 break;
14452 ast_mutex_unlock(&p_old->lock);
14454 ast_mutex_unlock(&iflock);
14456 if (!p->expiry)
14457 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14459 return 1;
14462 /*! \brief Handle incoming REGISTER request */
14463 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
14465 enum check_auth_result res;
14467 /* Use this as the basis */
14468 if (ast_test_flag(req, SIP_PKT_DEBUG))
14469 ast_verbose("Using latest REGISTER request as basis request\n");
14470 copy_request(&p->initreq, req);
14471 check_via(p, req);
14472 if ((res = register_verify(p, sin, req, e)) < 0) {
14473 const char *reason = "";
14475 switch (res) {
14476 case AUTH_SECRET_FAILED:
14477 reason = "Wrong password";
14478 break;
14479 case AUTH_USERNAME_MISMATCH:
14480 reason = "Username/auth name mismatch";
14481 break;
14482 case AUTH_NOT_FOUND:
14483 reason = "No matching peer found";
14484 break;
14485 case AUTH_UNKNOWN_DOMAIN:
14486 reason = "Not a local domain";
14487 break;
14488 default:
14489 break;
14491 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
14492 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
14493 reason);
14495 if (res < 1) {
14496 /* Destroy the session, but keep us around for just a bit in case they don't
14497 get our 200 OK */
14498 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14500 append_history(p, "RegRequest", "%s : Account %s", res ? "Failed": "Succeeded", get_header(req, "To"));
14501 return res;
14504 /*! \brief Handle incoming SIP requests (methods)
14505 \note This is where all incoming requests go first */
14506 /* called with p and p->owner locked */
14507 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
14509 /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
14510 relatively static */
14511 const char *cmd;
14512 const char *cseq;
14513 const char *useragent;
14514 int seqno;
14515 int len;
14516 int ignore = FALSE;
14517 int respid;
14518 int res = 0;
14519 int debug = sip_debug_test_pvt(p);
14520 char *e;
14521 int error = 0;
14523 /* Get Method and Cseq */
14524 cseq = get_header(req, "Cseq");
14525 cmd = req->header[0];
14527 /* Must have Cseq */
14528 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
14529 ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
14530 error = 1;
14532 if (!error && sscanf(cseq, "%d%n", &seqno, &len) != 1) {
14533 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
14534 error = 1;
14536 if (error) {
14537 if (!p->initreq.headers) /* New call */
14538 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); /* Make sure we destroy this dialog */
14539 return -1;
14541 /* Get the command XXX */
14543 cmd = req->rlPart1;
14544 e = req->rlPart2;
14546 /* Save useragent of the client */
14547 useragent = get_header(req, "User-Agent");
14548 if (!ast_strlen_zero(useragent))
14549 ast_string_field_set(p, useragent, useragent);
14551 /* Find out SIP method for incoming request */
14552 if (req->method == SIP_RESPONSE) { /* Response to our request */
14553 /* Response to our request -- Do some sanity checks */
14554 if (!p->initreq.headers) {
14555 if (option_debug)
14556 ast_log(LOG_DEBUG, "That's odd... Got a response on a call we dont know about. Cseq %d Cmd %s\n", seqno, cmd);
14557 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14558 return 0;
14559 } else if (p->ocseq && (p->ocseq < seqno)) {
14560 if (option_debug)
14561 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
14562 return -1;
14563 } else if (p->ocseq && (p->ocseq != seqno)) {
14564 /* ignore means "don't do anything with it" but still have to
14565 respond appropriately */
14566 ignore = TRUE;
14567 ast_set_flag(req, SIP_PKT_IGNORE);
14568 ast_set_flag(req, SIP_PKT_IGNORE_RESP);
14569 append_history(p, "Ignore", "Ignoring this retransmit\n");
14572 e = ast_skip_blanks(e);
14573 if (sscanf(e, "%d %n", &respid, &len) != 1) {
14574 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
14575 } else {
14576 /* More SIP ridiculousness, we have to ignore bogus contacts in 100 etc responses */
14577 if ((respid == 200) || ((respid >= 300) && (respid <= 399)))
14578 extract_uri(p, req);
14579 handle_response(p, respid, e + len, req, ignore, seqno);
14581 return 0;
14584 /* New SIP request coming in
14585 (could be new request in existing SIP dialog as well...)
14588 p->method = req->method; /* Find out which SIP method they are using */
14589 if (option_debug > 3)
14590 ast_log(LOG_DEBUG, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
14592 if (p->icseq && (p->icseq > seqno)) {
14593 if (option_debug)
14594 ast_log(LOG_DEBUG, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
14595 if (req->method != SIP_ACK)
14596 transmit_response(p, "503 Server error", req); /* We must respond according to RFC 3261 sec 12.2 */
14597 return -1;
14598 } else if (p->icseq &&
14599 p->icseq == seqno &&
14600 req->method != SIP_ACK &&
14601 (p->method != SIP_CANCEL || ast_test_flag(&p->flags[0], SIP_ALREADYGONE))) {
14602 /* ignore means "don't do anything with it" but still have to
14603 respond appropriately. We do this if we receive a repeat of
14604 the last sequence number */
14605 ignore = 2;
14606 ast_set_flag(req, SIP_PKT_IGNORE);
14607 ast_set_flag(req, SIP_PKT_IGNORE_REQ);
14608 if (option_debug > 2)
14609 ast_log(LOG_DEBUG, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
14612 if (seqno >= p->icseq)
14613 /* Next should follow monotonically (but not necessarily
14614 incrementally -- thanks again to the genius authors of SIP --
14615 increasing */
14616 p->icseq = seqno;
14618 /* Find their tag if we haven't got it */
14619 if (ast_strlen_zero(p->theirtag)) {
14620 char tag[128];
14622 gettag(req, "From", tag, sizeof(tag));
14623 ast_string_field_set(p, theirtag, tag);
14625 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
14627 if (pedanticsipchecking) {
14628 /* If this is a request packet without a from tag, it's not
14629 correct according to RFC 3261 */
14630 /* Check if this a new request in a new dialog with a totag already attached to it,
14631 RFC 3261 - section 12.2 - and we don't want to mess with recovery */
14632 if (!p->initreq.headers && ast_test_flag(req, SIP_PKT_WITH_TOTAG)) {
14633 /* If this is a first request and it got a to-tag, it is not for us */
14634 if (!ast_test_flag(req, SIP_PKT_IGNORE) && req->method == SIP_INVITE) {
14635 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
14636 /* Will cease to exist after ACK */
14637 } else if (req->method != SIP_ACK) {
14638 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
14639 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14641 return res;
14645 /* Handle various incoming SIP methods in requests */
14646 switch (p->method) {
14647 case SIP_OPTIONS:
14648 res = handle_request_options(p, req);
14649 break;
14650 case SIP_INVITE:
14651 res = handle_request_invite(p, req, debug, seqno, sin, recount, e);
14652 break;
14653 case SIP_REFER:
14654 res = handle_request_refer(p, req, debug, ignore, seqno, nounlock);
14655 break;
14656 case SIP_CANCEL:
14657 res = handle_request_cancel(p, req);
14658 break;
14659 case SIP_BYE:
14660 res = handle_request_bye(p, req);
14661 break;
14662 case SIP_MESSAGE:
14663 res = handle_request_message(p, req);
14664 break;
14665 case SIP_SUBSCRIBE:
14666 res = handle_request_subscribe(p, req, sin, seqno, e);
14667 break;
14668 case SIP_REGISTER:
14669 res = handle_request_register(p, req, sin, e);
14670 break;
14671 case SIP_INFO:
14672 if (ast_test_flag(req, SIP_PKT_DEBUG))
14673 ast_verbose("Receiving INFO!\n");
14674 if (!ignore)
14675 handle_request_info(p, req);
14676 else /* if ignoring, transmit response */
14677 transmit_response(p, "200 OK", req);
14678 break;
14679 case SIP_NOTIFY:
14680 res = handle_request_notify(p, req, sin, seqno, e);
14681 break;
14682 case SIP_ACK:
14683 /* Make sure we don't ignore this */
14684 if (seqno == p->pendinginvite) {
14685 p->invitestate = INV_TERMINATED;
14686 p->pendinginvite = 0;
14687 __sip_ack(p, seqno, FLAG_RESPONSE, 0);
14688 if (find_sdp(req)) {
14689 if (process_sdp(p, req))
14690 return -1;
14692 check_pendings(p);
14694 /* Got an ACK that we did not match. Ignore silently */
14695 if (!p->lastinvite && ast_strlen_zero(p->randdata))
14696 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14697 break;
14698 default:
14699 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
14700 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
14701 cmd, ast_inet_ntoa(p->sa.sin_addr));
14702 /* If this is some new method, and we don't have a call, destroy it now */
14703 if (!p->initreq.headers)
14704 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14705 break;
14707 return res;
14710 /*! \brief Read data from SIP socket
14711 \note sipsock_read locks the owner channel while we are processing the SIP message
14712 \return 1 on error, 0 on success
14713 \note Successful messages is connected to SIP call and forwarded to handle_request()
14715 static int sipsock_read(int *id, int fd, short events, void *ignore)
14717 struct sip_request req;
14718 struct sockaddr_in sin = { 0, };
14719 struct sip_pvt *p;
14720 int res;
14721 socklen_t len = sizeof(sin);
14722 int nounlock;
14723 int recount = 0;
14724 int lockretry;
14726 memset(&req, 0, sizeof(req));
14727 res = recvfrom(sipsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
14728 if (res < 0) {
14729 #if !defined(__FreeBSD__)
14730 if (errno == EAGAIN)
14731 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
14732 else
14733 #endif
14734 if (errno != ECONNREFUSED)
14735 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
14736 return 1;
14738 if (option_debug && res == sizeof(req.data)) {
14739 ast_log(LOG_DEBUG, "Received packet exceeds buffer. Data is possibly lost\n");
14740 req.data[sizeof(req.data) - 1] = '\0';
14741 } else
14742 req.data[res] = '\0';
14743 req.len = res;
14744 if(sip_debug_test_addr(&sin)) /* Set the debug flag early on packet level */
14745 ast_set_flag(&req, SIP_PKT_DEBUG);
14746 if (pedanticsipchecking)
14747 req.len = lws2sws(req.data, req.len); /* Fix multiline headers */
14748 if (ast_test_flag(&req, SIP_PKT_DEBUG))
14749 ast_verbose("\n<--- SIP read from %s:%d --->\n%s\n<------------->\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), req.data);
14751 parse_request(&req);
14752 req.method = find_sip_method(req.rlPart1);
14754 if (ast_test_flag(&req, SIP_PKT_DEBUG))
14755 ast_verbose("--- (%d headers %d lines)%s ---\n", req.headers, req.lines, (req.headers + req.lines == 0) ? " Nat keepalive" : "");
14757 if (req.headers < 2) /* Must have at least two headers */
14758 return 1;
14760 /* Process request, with netlock held, and with usual deadlock avoidance */
14761 for (lockretry = 100; lockretry > 0; lockretry--) {
14762 ast_mutex_lock(&netlock);
14764 /* Find the active SIP dialog or create a new one */
14765 p = find_call(&req, &sin, req.method); /* returns p locked */
14766 if (p == NULL) {
14767 if (option_debug)
14768 ast_log(LOG_DEBUG, "Invalid SIP message - rejected , no callid, len %d\n", req.len);
14769 ast_mutex_unlock(&netlock);
14770 return 1;
14772 /* Go ahead and lock the owner if it has one -- we may need it */
14773 /* becaues this is deadlock-prone, we need to try and unlock if failed */
14774 if (!p->owner || !ast_channel_trylock(p->owner))
14775 break; /* locking succeeded */
14776 if (option_debug)
14777 ast_log(LOG_DEBUG, "Failed to grab owner channel lock, trying again. (SIP call %s)\n", p->callid);
14778 ast_mutex_unlock(&p->lock);
14779 ast_mutex_unlock(&netlock);
14780 /* Sleep for a very short amount of time */
14781 usleep(1);
14783 p->recv = sin;
14785 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) /* This is a request or response, note what it was for */
14786 append_history(p, "Rx", "%s / %s / %s", req.data, get_header(&req, "CSeq"), req.rlPart2);
14788 if (!lockretry) {
14789 ast_log(LOG_ERROR, "We could NOT get the channel lock for %s! \n", S_OR(p->owner->name, "- no channel name ??? - "));
14790 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
14791 if (req.method != SIP_ACK)
14792 transmit_response(p, "503 Server error", &req); /* We must respond according to RFC 3261 sec 12.2 */
14793 /* XXX We could add retry-after to make sure they come back */
14794 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
14795 return 1;
14797 nounlock = 0;
14798 if (handle_request(p, &req, &sin, &recount, &nounlock) == -1) {
14799 /* Request failed */
14800 if (option_debug)
14801 ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
14804 if (p->owner && !nounlock)
14805 ast_channel_unlock(p->owner);
14806 ast_mutex_unlock(&p->lock);
14807 ast_mutex_unlock(&netlock);
14808 if (recount)
14809 ast_update_use_count();
14811 return 1;
14814 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
14815 static int sip_send_mwi_to_peer(struct sip_peer *peer)
14817 /* Called with peerl lock, but releases it */
14818 struct sip_pvt *p;
14819 int newmsgs, oldmsgs;
14821 /* Check for messages */
14822 ast_app_inboxcount(peer->mailbox, &newmsgs, &oldmsgs);
14824 peer->lastmsgcheck = time(NULL);
14826 /* Return now if it's the same thing we told them last time */
14827 if (((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)) == peer->lastmsgssent) {
14828 return 0;
14832 peer->lastmsgssent = ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs));
14834 if (peer->mwipvt) {
14835 /* Base message on subscription */
14836 p = peer->mwipvt;
14837 } else {
14838 /* Build temporary dialog for this message */
14839 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY)))
14840 return -1;
14841 if (create_addr_from_peer(p, peer)) {
14842 /* Maybe they're not registered, etc. */
14843 sip_destroy(p);
14844 return 0;
14846 /* Recalculate our side, and recalculate Call ID */
14847 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
14848 p->ourip = __ourip;
14849 build_via(p);
14850 build_callid_pvt(p);
14851 /* Destroy this session after 32 secs */
14852 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14854 /* Send MWI */
14855 ast_set_flag(&p->flags[0], SIP_OUTGOING);
14856 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
14857 return 0;
14860 /*! \brief Check whether peer needs a new MWI notification check */
14861 static int does_peer_need_mwi(struct sip_peer *peer)
14863 time_t t = time(NULL);
14865 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
14866 !peer->mwipvt) { /* We don't have a subscription */
14867 peer->lastmsgcheck = t; /* Reset timer */
14868 return FALSE;
14871 if (!ast_strlen_zero(peer->mailbox) && (t - peer->lastmsgcheck) > global_mwitime)
14872 return TRUE;
14874 return FALSE;
14878 /*! \brief The SIP monitoring thread
14879 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
14880 (and thus do not have a separate thread) indefinitely
14882 static void *do_monitor(void *data)
14884 int res;
14885 struct sip_pvt *sip;
14886 struct sip_peer *peer = NULL;
14887 time_t t;
14888 int fastrestart = FALSE;
14889 int lastpeernum = -1;
14890 int curpeernum;
14891 int reloading;
14893 /* Add an I/O event to our SIP UDP socket */
14894 if (sipsock > -1)
14895 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
14897 /* From here on out, we die whenever asked */
14898 for(;;) {
14899 /* Check for a reload request */
14900 ast_mutex_lock(&sip_reload_lock);
14901 reloading = sip_reloading;
14902 sip_reloading = FALSE;
14903 ast_mutex_unlock(&sip_reload_lock);
14904 if (reloading) {
14905 if (option_verbose > 0)
14906 ast_verbose(VERBOSE_PREFIX_1 "Reloading SIP\n");
14907 sip_do_reload(sip_reloadreason);
14909 /* Change the I/O fd of our UDP socket */
14910 if (sipsock > -1)
14911 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
14913 /* Check for interfaces needing to be killed */
14914 ast_mutex_lock(&iflock);
14915 restartsearch:
14916 t = time(NULL);
14917 /* don't scan the interface list if it hasn't been a reasonable period
14918 of time since the last time we did it (when MWI is being sent, we can
14919 get back to this point every millisecond or less)
14921 for (sip = iflist; !fastrestart && sip; sip = sip->next) {
14922 ast_mutex_lock(&sip->lock);
14923 /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
14924 if (sip->rtp && sip->owner &&
14925 (sip->owner->_state == AST_STATE_UP) &&
14926 !sip->redirip.sin_addr.s_addr) {
14927 if (sip->lastrtptx &&
14928 ast_rtp_get_rtpkeepalive(sip->rtp) &&
14929 (t > sip->lastrtptx + ast_rtp_get_rtpkeepalive(sip->rtp))) {
14930 /* Need to send an empty RTP packet */
14931 sip->lastrtptx = time(NULL);
14932 ast_rtp_sendcng(sip->rtp, 0);
14934 if (sip->lastrtprx &&
14935 (ast_rtp_get_rtptimeout(sip->rtp) || ast_rtp_get_rtpholdtimeout(sip->rtp)) &&
14936 (t > sip->lastrtprx + ast_rtp_get_rtptimeout(sip->rtp))) {
14937 /* Might be a timeout now -- see if we're on hold */
14938 struct sockaddr_in sin;
14939 ast_rtp_get_peer(sip->rtp, &sin);
14940 if (sin.sin_addr.s_addr ||
14941 (ast_rtp_get_rtpholdtimeout(sip->rtp) &&
14942 (t > sip->lastrtprx + ast_rtp_get_rtpholdtimeout(sip->rtp)))) {
14943 /* Needs a hangup */
14944 if (ast_rtp_get_rtptimeout(sip->rtp)) {
14945 while (sip->owner && ast_channel_trylock(sip->owner)) {
14946 ast_mutex_unlock(&sip->lock);
14947 usleep(1);
14948 ast_mutex_lock(&sip->lock);
14950 if (sip->owner) {
14951 if (!(ast_rtp_get_bridged(sip->rtp))) {
14952 ast_log(LOG_NOTICE,
14953 "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
14954 sip->owner->name,
14955 (long) (t - sip->lastrtprx));
14956 /* Issue a softhangup */
14957 ast_softhangup_nolock(sip->owner, AST_SOFTHANGUP_DEV);
14958 } else
14959 ast_log(LOG_NOTICE, "'%s' will not be disconnected in %ld seconds because it is directly bridged to another RTP stream\n", sip->owner->name, (long) (t - sip->lastrtprx));
14960 ast_channel_unlock(sip->owner);
14961 /* forget the timeouts for this call, since a hangup
14962 has already been requested and we don't want to
14963 repeatedly request hangups
14965 ast_rtp_set_rtptimeout(sip->rtp, 0);
14966 ast_rtp_set_rtpholdtimeout(sip->rtp, 0);
14967 if (sip->vrtp) {
14968 ast_rtp_set_rtptimeout(sip->vrtp, 0);
14969 ast_rtp_set_rtpholdtimeout(sip->vrtp, 0);
14976 /* If we have sessions that needs to be destroyed, do it now */
14977 if (ast_test_flag(&sip->flags[0], SIP_NEEDDESTROY) && !sip->packets &&
14978 !sip->owner) {
14979 ast_mutex_unlock(&sip->lock);
14980 __sip_destroy(sip, 1);
14981 goto restartsearch;
14983 ast_mutex_unlock(&sip->lock);
14985 ast_mutex_unlock(&iflock);
14987 pthread_testcancel();
14988 /* Wait for sched or io */
14989 res = ast_sched_wait(sched);
14990 if ((res < 0) || (res > 1000))
14991 res = 1000;
14992 /* If we might need to send more mailboxes, don't wait long at all.*/
14993 if (fastrestart)
14994 res = 1;
14995 res = ast_io_wait(io, res);
14996 if (option_debug && res > 20)
14997 ast_log(LOG_DEBUG, "chan_sip: ast_io_wait ran %d all at once\n", res);
14998 ast_mutex_lock(&monlock);
14999 if (res >= 0) {
15000 res = ast_sched_runq(sched);
15001 if (option_debug && res >= 20)
15002 ast_log(LOG_DEBUG, "chan_sip: ast_sched_runq ran %d all at once\n", res);
15005 /* Send MWI notifications to peers - static and cached realtime peers */
15006 t = time(NULL);
15007 fastrestart = FALSE;
15008 curpeernum = 0;
15009 peer = NULL;
15010 /* Find next peer that needs mwi */
15011 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !peer, do {
15012 if ((curpeernum > lastpeernum) && does_peer_need_mwi(iterator)) {
15013 fastrestart = TRUE;
15014 lastpeernum = curpeernum;
15015 peer = ASTOBJ_REF(iterator);
15017 curpeernum++;
15018 } while (0)
15020 /* Send MWI to the peer */
15021 if (peer) {
15022 ASTOBJ_WRLOCK(peer);
15023 sip_send_mwi_to_peer(peer);
15024 ASTOBJ_UNLOCK(peer);
15025 ASTOBJ_UNREF(peer,sip_destroy_peer);
15026 } else {
15027 /* Reset where we come from */
15028 lastpeernum = -1;
15030 ast_mutex_unlock(&monlock);
15032 /* Never reached */
15033 return NULL;
15037 /*! \brief Start the channel monitor thread */
15038 static int restart_monitor(void)
15040 /* If we're supposed to be stopped -- stay stopped */
15041 if (monitor_thread == AST_PTHREADT_STOP)
15042 return 0;
15043 ast_mutex_lock(&monlock);
15044 if (monitor_thread == pthread_self()) {
15045 ast_mutex_unlock(&monlock);
15046 ast_log(LOG_WARNING, "Cannot kill myself\n");
15047 return -1;
15049 if (monitor_thread != AST_PTHREADT_NULL) {
15050 /* Wake up the thread */
15051 pthread_kill(monitor_thread, SIGURG);
15052 } else {
15053 /* Start a new monitor */
15054 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
15055 ast_mutex_unlock(&monlock);
15056 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
15057 return -1;
15060 ast_mutex_unlock(&monlock);
15061 return 0;
15064 /*! \brief React to lack of answer to Qualify poke */
15065 static int sip_poke_noanswer(void *data)
15067 struct sip_peer *peer = data;
15069 peer->pokeexpire = -1;
15070 if (peer->lastms > -1) {
15071 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
15072 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
15074 if (peer->call)
15075 sip_destroy(peer->call);
15076 peer->call = NULL;
15077 peer->lastms = -1;
15078 ast_device_state_changed("SIP/%s", peer->name);
15079 /* Try again quickly */
15080 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
15081 return 0;
15084 /*! \brief Check availability of peer, also keep NAT open
15085 \note This is done with the interval in qualify= configuration option
15086 Default is 2 seconds */
15087 static int sip_poke_peer(struct sip_peer *peer)
15089 struct sip_pvt *p;
15091 if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
15092 /* IF we have no IP, or this isn't to be monitored, return
15093 imeediately after clearing things out */
15094 if (peer->pokeexpire > -1)
15095 ast_sched_del(sched, peer->pokeexpire);
15096 peer->lastms = 0;
15097 peer->pokeexpire = -1;
15098 peer->call = NULL;
15099 return 0;
15101 if (peer->call) {
15102 if (sipdebug)
15103 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
15104 sip_destroy(peer->call);
15106 if (!(p = peer->call = sip_alloc(NULL, NULL, 0, SIP_OPTIONS)))
15107 return -1;
15109 p->sa = peer->addr;
15110 p->recv = peer->addr;
15111 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
15112 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15114 /* Send OPTIONs to peer's fullcontact */
15115 if (!ast_strlen_zero(peer->fullcontact))
15116 ast_string_field_set(p, fullcontact, peer->fullcontact);
15118 if (!ast_strlen_zero(peer->tohost))
15119 ast_string_field_set(p, tohost, peer->tohost);
15120 else
15121 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
15123 /* Recalculate our side, and recalculate Call ID */
15124 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
15125 p->ourip = __ourip;
15126 build_via(p);
15127 build_callid_pvt(p);
15129 if (peer->pokeexpire > -1)
15130 ast_sched_del(sched, peer->pokeexpire);
15131 p->relatedpeer = peer;
15132 ast_set_flag(&p->flags[0], SIP_OUTGOING);
15133 #ifdef VOCAL_DATA_HACK
15134 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
15135 transmit_invite(p, SIP_INVITE, 0, 2);
15136 #else
15137 transmit_invite(p, SIP_OPTIONS, 0, 2);
15138 #endif
15139 gettimeofday(&peer->ps, NULL);
15140 peer->pokeexpire = ast_sched_add(sched, DEFAULT_MAXMS * 2, sip_poke_noanswer, peer);
15142 return 0;
15145 /*! \brief Part of PBX channel interface
15146 \note
15147 \par Return values:---
15149 If we have qualify on and the device is not reachable, regardless of registration
15150 state we return AST_DEVICE_UNAVAILABLE
15152 For peers with call limit:
15153 - not registered AST_DEVICE_UNAVAILABLE
15154 - registered, no call AST_DEVICE_NOT_INUSE
15155 - registered, active calls AST_DEVICE_INUSE
15156 - registered, call limit reached AST_DEVICE_BUSY
15157 - registered, onhold AST_DEVICE_ONHOLD
15158 - registered, ringing AST_DEVICE_RINGING
15160 For peers without call limit:
15161 - not registered AST_DEVICE_UNAVAILABLE
15162 - registered AST_DEVICE_NOT_INUSE
15163 - fixed IP (!dynamic) AST_DEVICE_NOT_INUSE
15165 Peers that does not have a known call and can't be reached by OPTIONS
15166 - unreachable AST_DEVICE_UNAVAILABLE
15168 If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
15169 out a state by walking the channel list.
15171 The queue system (\ref app_queue.c) treats a member as "active"
15172 if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
15174 When placing a call to the queue member, queue system sets a member to busy if
15175 != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
15178 static int sip_devicestate(void *data)
15180 char *host;
15181 char *tmp;
15183 struct hostent *hp;
15184 struct ast_hostent ahp;
15185 struct sip_peer *p;
15187 int res = AST_DEVICE_INVALID;
15189 /* make sure data is not null. Maybe unnecessary, but better be safe */
15190 host = ast_strdupa(data ? data : "");
15191 if ((tmp = strchr(host, '@')))
15192 host = tmp + 1;
15194 if (option_debug > 2)
15195 ast_log(LOG_DEBUG, "Checking device state for peer %s\n", host);
15197 if ((p = find_peer(host, NULL, 1))) {
15198 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
15199 /* we have an address for the peer */
15201 /* Check status in this order
15202 - Hold
15203 - Ringing
15204 - Busy (enforced only by call limit)
15205 - Inuse (we have a call)
15206 - Unreachable (qualify)
15207 If we don't find any of these state, report AST_DEVICE_NOT_INUSE
15208 for registered devices */
15210 if (p->onHold)
15211 /* First check for hold or ring states */
15212 res = AST_DEVICE_ONHOLD;
15213 else if (p->inRinging) {
15214 if (p->inRinging == p->inUse)
15215 res = AST_DEVICE_RINGING;
15216 else
15217 res = AST_DEVICE_RINGINUSE;
15218 } else if (p->call_limit && (p->inUse == p->call_limit))
15219 /* check call limit */
15220 res = AST_DEVICE_BUSY;
15221 else if (p->call_limit && p->inUse)
15222 /* Not busy, but we do have a call */
15223 res = AST_DEVICE_INUSE;
15224 else if (p->maxms && (p->lastms > p->maxms))
15225 /* We don't have a call. Are we reachable at all? Requires qualify= */
15226 res = AST_DEVICE_UNAVAILABLE;
15227 else /* Default reply if we're registered and have no other data */
15228 res = AST_DEVICE_NOT_INUSE;
15229 } else {
15230 /* there is no address, it's unavailable */
15231 res = AST_DEVICE_UNAVAILABLE;
15233 ASTOBJ_UNREF(p,sip_destroy_peer);
15234 } else {
15235 hp = ast_gethostbyname(host, &ahp);
15236 if (hp)
15237 res = AST_DEVICE_UNKNOWN;
15240 return res;
15243 /*! \brief PBX interface function -build SIP pvt structure
15244 SIP calls initiated by the PBX arrive here */
15245 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
15247 int oldformat;
15248 struct sip_pvt *p;
15249 struct ast_channel *tmpc = NULL;
15250 char *ext, *host;
15251 char tmp[256];
15252 char *dest = data;
15254 oldformat = format;
15255 if (!(format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1))) {
15256 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));
15257 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL; /* Can't find codec to connect to host */
15258 return NULL;
15260 if (option_debug)
15261 ast_log(LOG_DEBUG, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
15263 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE))) {
15264 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", (char *)data);
15265 *cause = AST_CAUSE_SWITCH_CONGESTION;
15266 return NULL;
15269 ast_set_flag(&p->flags[1], SIP_PAGE2_OUTGOING_CALL);
15271 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
15272 sip_destroy(p);
15273 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
15274 *cause = AST_CAUSE_SWITCH_CONGESTION;
15275 return NULL;
15278 ast_copy_string(tmp, dest, sizeof(tmp));
15279 host = strchr(tmp, '@');
15280 if (host) {
15281 *host++ = '\0';
15282 ext = tmp;
15283 } else {
15284 ext = strchr(tmp, '/');
15285 if (ext)
15286 *ext++ = '\0';
15287 host = tmp;
15290 if (create_addr(p, host)) {
15291 *cause = AST_CAUSE_UNREGISTERED;
15292 if (option_debug > 2)
15293 ast_log(LOG_DEBUG, "Cant create SIP call - target device not registred\n");
15294 sip_destroy(p);
15295 return NULL;
15297 if (ast_strlen_zero(p->peername) && ext)
15298 ast_string_field_set(p, peername, ext);
15299 /* Recalculate our side, and recalculate Call ID */
15300 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
15301 p->ourip = __ourip;
15302 build_via(p);
15303 build_callid_pvt(p);
15305 /* We have an extension to call, don't use the full contact here */
15306 /* This to enable dialing registered peers with extension dialling,
15307 like SIP/peername/extension
15308 SIP/peername will still use the full contact */
15309 if (ext) {
15310 ast_string_field_set(p, username, ext);
15311 ast_string_field_free(p, fullcontact);
15313 #if 0
15314 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
15315 #endif
15316 p->prefcodec = oldformat; /* Format for this call */
15317 ast_mutex_lock(&p->lock);
15318 tmpc = sip_new(p, AST_STATE_DOWN, host); /* Place the call */
15319 ast_mutex_unlock(&p->lock);
15320 if (!tmpc)
15321 sip_destroy(p);
15322 ast_update_use_count();
15323 restart_monitor();
15324 return tmpc;
15328 \brief Handle flag-type options common to configuration of devices - users and peers
15329 \param flags array of two struct ast_flags
15330 \param mask array of two struct ast_flags
15331 \param v linked list of config variables to process
15332 \returns non-zero if any config options were handled, zero otherwise
15334 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
15336 int res = 0;
15337 static int dep_insecure_very = 0;
15338 static int dep_insecure_yes = 0;
15340 if (!strcasecmp(v->name, "trustrpid")) {
15341 ast_set_flag(&mask[0], SIP_TRUSTRPID);
15342 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
15343 res = 1;
15344 } else if (!strcasecmp(v->name, "sendrpid")) {
15345 ast_set_flag(&mask[0], SIP_SENDRPID);
15346 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
15347 res = 1;
15348 } else if (!strcasecmp(v->name, "g726nonstandard")) {
15349 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
15350 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
15351 res = 1;
15352 } else if (!strcasecmp(v->name, "useclientcode")) {
15353 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
15354 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
15355 res = 1;
15356 } else if (!strcasecmp(v->name, "dtmfmode")) {
15357 ast_set_flag(&mask[0], SIP_DTMF);
15358 ast_clear_flag(&flags[0], SIP_DTMF);
15359 if (!strcasecmp(v->value, "inband"))
15360 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
15361 else if (!strcasecmp(v->value, "rfc2833"))
15362 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
15363 else if (!strcasecmp(v->value, "info"))
15364 ast_set_flag(&flags[0], SIP_DTMF_INFO);
15365 else if (!strcasecmp(v->value, "auto"))
15366 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
15367 else {
15368 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
15369 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
15371 res = 1;
15372 } else if (!strcasecmp(v->name, "nat")) {
15373 ast_set_flag(&mask[0], SIP_NAT);
15374 ast_clear_flag(&flags[0], SIP_NAT);
15375 if (!strcasecmp(v->value, "never"))
15376 ast_set_flag(&flags[0], SIP_NAT_NEVER);
15377 else if (!strcasecmp(v->value, "route"))
15378 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
15379 else if (ast_true(v->value))
15380 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
15381 else
15382 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
15383 res = 1;
15384 } else if (!strcasecmp(v->name, "canreinvite")) {
15385 ast_set_flag(&mask[0], SIP_REINVITE);
15386 ast_clear_flag(&flags[0], SIP_REINVITE);
15387 if (ast_true(v->value)) {
15388 ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
15389 } else if (!ast_false(v->value)) {
15390 char buf[64];
15391 char *word, *next = buf;
15393 ast_copy_string(buf, v->value, sizeof(buf));
15394 while ((word = strsep(&next, ","))) {
15395 if (!strcasecmp(word, "update")) {
15396 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
15397 } else if (!strcasecmp(word, "nonat")) {
15398 ast_set_flag(&flags[0], SIP_CAN_REINVITE);
15399 ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
15400 } else {
15401 ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
15405 res = 1;
15406 } else if (!strcasecmp(v->name, "insecure")) {
15407 ast_set_flag(&mask[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
15408 ast_clear_flag(&flags[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
15409 if (!strcasecmp(v->value, "very")) {
15410 ast_set_flag(&flags[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
15411 if (!dep_insecure_very) {
15412 ast_log(LOG_WARNING, "insecure=very at line %d is deprecated; use insecure=port,invite instead\n", v->lineno);
15413 dep_insecure_very = 1;
15416 else if (ast_true(v->value)) {
15417 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
15418 if (!dep_insecure_yes) {
15419 ast_log(LOG_WARNING, "insecure=%s at line %d is deprecated; use insecure=port instead\n", v->value, v->lineno);
15420 dep_insecure_yes = 1;
15423 else if (!ast_false(v->value)) {
15424 char buf[64];
15425 char *word, *next;
15427 ast_copy_string(buf, v->value, sizeof(buf));
15428 next = buf;
15429 while ((word = strsep(&next, ","))) {
15430 if (!strcasecmp(word, "port"))
15431 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
15432 else if (!strcasecmp(word, "invite"))
15433 ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
15434 else
15435 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", v->value, v->lineno);
15438 res = 1;
15439 } else if (!strcasecmp(v->name, "progressinband")) {
15440 ast_set_flag(&mask[0], SIP_PROG_INBAND);
15441 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
15442 if (ast_true(v->value))
15443 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
15444 else if (strcasecmp(v->value, "never"))
15445 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
15446 res = 1;
15447 } else if (!strcasecmp(v->name, "promiscredir")) {
15448 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
15449 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
15450 res = 1;
15451 } else if (!strcasecmp(v->name, "videosupport")) {
15452 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
15453 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
15454 res = 1;
15455 } else if (!strcasecmp(v->name, "allowoverlap")) {
15456 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
15457 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
15458 res = 1;
15459 } else if (!strcasecmp(v->name, "allowsubscribe")) {
15460 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
15461 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
15462 res = 1;
15463 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
15464 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_UDPTL);
15465 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_UDPTL);
15466 res = 1;
15467 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
15468 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
15469 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_RTP);
15470 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_RTP);
15471 res = 1;
15472 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
15473 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_TCP);
15474 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_TCP);
15475 res = 1;
15476 #endif
15477 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
15478 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
15479 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
15480 res = 1;
15481 } else if (!strcasecmp(v->name, "buggymwi")) {
15482 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
15483 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
15484 res = 1;
15487 return res;
15490 /*! \brief Add SIP domain to list of domains we are responsible for */
15491 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
15493 struct domain *d;
15495 if (ast_strlen_zero(domain)) {
15496 ast_log(LOG_WARNING, "Zero length domain.\n");
15497 return 1;
15500 if (!(d = ast_calloc(1, sizeof(*d))))
15501 return 0;
15503 ast_copy_string(d->domain, domain, sizeof(d->domain));
15505 if (!ast_strlen_zero(context))
15506 ast_copy_string(d->context, context, sizeof(d->context));
15508 d->mode = mode;
15510 AST_LIST_LOCK(&domain_list);
15511 AST_LIST_INSERT_TAIL(&domain_list, d, list);
15512 AST_LIST_UNLOCK(&domain_list);
15514 if (sipdebug)
15515 ast_log(LOG_DEBUG, "Added local SIP domain '%s'\n", domain);
15517 return 1;
15520 /*! \brief check_sip_domain: Check if domain part of uri is local to our server */
15521 static int check_sip_domain(const char *domain, char *context, size_t len)
15523 struct domain *d;
15524 int result = 0;
15526 AST_LIST_LOCK(&domain_list);
15527 AST_LIST_TRAVERSE(&domain_list, d, list) {
15528 if (strcasecmp(d->domain, domain))
15529 continue;
15531 if (len && !ast_strlen_zero(d->context))
15532 ast_copy_string(context, d->context, len);
15534 result = 1;
15535 break;
15537 AST_LIST_UNLOCK(&domain_list);
15539 return result;
15542 /*! \brief Clear our domain list (at reload) */
15543 static void clear_sip_domains(void)
15545 struct domain *d;
15547 AST_LIST_LOCK(&domain_list);
15548 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
15549 free(d);
15550 AST_LIST_UNLOCK(&domain_list);
15554 /*! \brief Add realm authentication in list */
15555 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno)
15557 char authcopy[256];
15558 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
15559 char *stringp;
15560 struct sip_auth *a, *b, *auth;
15562 if (ast_strlen_zero(configuration))
15563 return authlist;
15565 if (option_debug)
15566 ast_log(LOG_DEBUG, "Auth config :: %s\n", configuration);
15568 ast_copy_string(authcopy, configuration, sizeof(authcopy));
15569 stringp = authcopy;
15571 username = stringp;
15572 realm = strrchr(stringp, '@');
15573 if (realm)
15574 *realm++ = '\0';
15575 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
15576 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
15577 return authlist;
15579 stringp = username;
15580 username = strsep(&stringp, ":");
15581 if (username) {
15582 secret = strsep(&stringp, ":");
15583 if (!secret) {
15584 stringp = username;
15585 md5secret = strsep(&stringp,"#");
15588 if (!(auth = ast_calloc(1, sizeof(*auth))))
15589 return authlist;
15591 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
15592 ast_copy_string(auth->username, username, sizeof(auth->username));
15593 if (secret)
15594 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
15595 if (md5secret)
15596 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
15598 /* find the end of the list */
15599 for (b = NULL, a = authlist; a ; b = a, a = a->next)
15601 if (b)
15602 b->next = auth; /* Add structure add end of list */
15603 else
15604 authlist = auth;
15606 if (option_verbose > 2)
15607 ast_verbose("Added authentication for realm %s\n", realm);
15609 return authlist;
15613 /*! \brief Clear realm authentication list (at reload) */
15614 static int clear_realm_authentication(struct sip_auth *authlist)
15616 struct sip_auth *a = authlist;
15617 struct sip_auth *b;
15619 while (a) {
15620 b = a;
15621 a = a->next;
15622 free(b);
15625 return 1;
15628 /*! \brief Find authentication for a specific realm */
15629 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
15631 struct sip_auth *a;
15633 for (a = authlist; a; a = a->next) {
15634 if (!strcasecmp(a->realm, realm))
15635 break;
15638 return a;
15641 /*! \brief Initiate a SIP user structure from configuration (configuration or realtime) */
15642 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime)
15644 struct sip_user *user;
15645 int format;
15646 struct ast_ha *oldha = NULL;
15647 char *varname = NULL, *varval = NULL;
15648 struct ast_variable *tmpvar = NULL;
15649 struct ast_flags userflags[2] = {{(0)}};
15650 struct ast_flags mask[2] = {{(0)}};
15653 if (!(user = ast_calloc(1, sizeof(*user))))
15654 return NULL;
15656 suserobjs++;
15657 ASTOBJ_INIT(user);
15658 ast_copy_string(user->name, name, sizeof(user->name));
15659 oldha = user->ha;
15660 user->ha = NULL;
15661 ast_copy_flags(&user->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
15662 ast_copy_flags(&user->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15663 user->capability = global_capability;
15664 user->allowtransfer = global_allowtransfer;
15665 user->maxcallbitrate = default_maxcallbitrate;
15666 user->autoframing = global_autoframing;
15667 user->prefs = default_prefs;
15668 /* set default context */
15669 strcpy(user->context, default_context);
15670 strcpy(user->language, default_language);
15671 strcpy(user->mohinterpret, default_mohinterpret);
15672 strcpy(user->mohsuggest, default_mohsuggest);
15673 for (; v; v = v->next) {
15674 if (handle_common_options(&userflags[0], &mask[0], v))
15675 continue;
15677 if (!strcasecmp(v->name, "context")) {
15678 ast_copy_string(user->context, v->value, sizeof(user->context));
15679 } else if (!strcasecmp(v->name, "subscribecontext")) {
15680 ast_copy_string(user->subscribecontext, v->value, sizeof(user->subscribecontext));
15681 } else if (!strcasecmp(v->name, "setvar")) {
15682 varname = ast_strdupa(v->value);
15683 if ((varval = strchr(varname,'='))) {
15684 *varval++ = '\0';
15685 if ((tmpvar = ast_variable_new(varname, varval))) {
15686 tmpvar->next = user->chanvars;
15687 user->chanvars = tmpvar;
15690 } else if (!strcasecmp(v->name, "permit") ||
15691 !strcasecmp(v->name, "deny")) {
15692 user->ha = ast_append_ha(v->name, v->value, user->ha);
15693 } else if (!strcasecmp(v->name, "allowtransfer")) {
15694 user->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
15695 } else if (!strcasecmp(v->name, "secret")) {
15696 ast_copy_string(user->secret, v->value, sizeof(user->secret));
15697 } else if (!strcasecmp(v->name, "md5secret")) {
15698 ast_copy_string(user->md5secret, v->value, sizeof(user->md5secret));
15699 } else if (!strcasecmp(v->name, "callerid")) {
15700 ast_callerid_split(v->value, user->cid_name, sizeof(user->cid_name), user->cid_num, sizeof(user->cid_num));
15701 } else if (!strcasecmp(v->name, "fullname")) {
15702 ast_copy_string(user->cid_name, v->value, sizeof(user->cid_name));
15703 } else if (!strcasecmp(v->name, "cid_number")) {
15704 ast_copy_string(user->cid_num, v->value, sizeof(user->cid_num));
15705 } else if (!strcasecmp(v->name, "callgroup")) {
15706 user->callgroup = ast_get_group(v->value);
15707 } else if (!strcasecmp(v->name, "pickupgroup")) {
15708 user->pickupgroup = ast_get_group(v->value);
15709 } else if (!strcasecmp(v->name, "language")) {
15710 ast_copy_string(user->language, v->value, sizeof(user->language));
15711 } else if (!strcasecmp(v->name, "mohinterpret")
15712 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
15713 ast_copy_string(user->mohinterpret, v->value, sizeof(user->mohinterpret));
15714 } else if (!strcasecmp(v->name, "mohsuggest")) {
15715 ast_copy_string(user->mohsuggest, v->value, sizeof(user->mohsuggest));
15716 } else if (!strcasecmp(v->name, "accountcode")) {
15717 ast_copy_string(user->accountcode, v->value, sizeof(user->accountcode));
15718 } else if (!strcasecmp(v->name, "call-limit")) {
15719 user->call_limit = atoi(v->value);
15720 if (user->call_limit < 0)
15721 user->call_limit = 0;
15722 } else if (!strcasecmp(v->name, "amaflags")) {
15723 format = ast_cdr_amaflags2int(v->value);
15724 if (format < 0) {
15725 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
15726 } else {
15727 user->amaflags = format;
15729 } else if (!strcasecmp(v->name, "allow")) {
15730 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
15731 } else if (!strcasecmp(v->name, "disallow")) {
15732 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 0);
15733 } else if (!strcasecmp(v->name, "autoframing")) {
15734 user->autoframing = ast_true(v->value);
15735 } else if (!strcasecmp(v->name, "callingpres")) {
15736 user->callingpres = ast_parse_caller_presentation(v->value);
15737 if (user->callingpres == -1)
15738 user->callingpres = atoi(v->value);
15739 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
15740 user->maxcallbitrate = atoi(v->value);
15741 if (user->maxcallbitrate < 0)
15742 user->maxcallbitrate = default_maxcallbitrate;
15745 ast_copy_flags(&user->flags[0], &userflags[0], mask[0].flags);
15746 ast_copy_flags(&user->flags[1], &userflags[1], mask[1].flags);
15747 if (ast_test_flag(&user->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
15748 global_allowsubscribe = TRUE; /* No global ban any more */
15749 ast_free_ha(oldha);
15750 return user;
15753 /*! \brief Set peer defaults before configuring specific configurations */
15754 static void set_peer_defaults(struct sip_peer *peer)
15756 if (peer->expire == 0) {
15757 /* Don't reset expire or port time during reload
15758 if we have an active registration
15760 peer->expire = -1;
15761 peer->pokeexpire = -1;
15762 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
15764 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
15765 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15766 strcpy(peer->context, default_context);
15767 strcpy(peer->subscribecontext, default_subscribecontext);
15768 strcpy(peer->language, default_language);
15769 strcpy(peer->mohinterpret, default_mohinterpret);
15770 strcpy(peer->mohsuggest, default_mohsuggest);
15771 peer->addr.sin_family = AF_INET;
15772 peer->defaddr.sin_family = AF_INET;
15773 peer->capability = global_capability;
15774 peer->maxcallbitrate = default_maxcallbitrate;
15775 peer->rtptimeout = global_rtptimeout;
15776 peer->rtpholdtimeout = global_rtpholdtimeout;
15777 peer->rtpkeepalive = global_rtpkeepalive;
15778 peer->allowtransfer = global_allowtransfer;
15779 peer->autoframing = global_autoframing;
15780 strcpy(peer->vmexten, default_vmexten);
15781 peer->secret[0] = '\0';
15782 peer->md5secret[0] = '\0';
15783 peer->cid_num[0] = '\0';
15784 peer->cid_name[0] = '\0';
15785 peer->fromdomain[0] = '\0';
15786 peer->fromuser[0] = '\0';
15787 peer->regexten[0] = '\0';
15788 peer->mailbox[0] = '\0';
15789 peer->callgroup = 0;
15790 peer->pickupgroup = 0;
15791 peer->maxms = default_qualify;
15792 peer->prefs = default_prefs;
15795 /*! \brief Create temporary peer (used in autocreatepeer mode) */
15796 static struct sip_peer *temp_peer(const char *name)
15798 struct sip_peer *peer;
15800 if (!(peer = ast_calloc(1, sizeof(*peer))))
15801 return NULL;
15803 apeerobjs++;
15804 ASTOBJ_INIT(peer);
15805 set_peer_defaults(peer);
15807 ast_copy_string(peer->name, name, sizeof(peer->name));
15809 ast_set_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT);
15810 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
15811 peer->prefs = default_prefs;
15812 reg_source_db(peer);
15814 return peer;
15817 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
15818 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
15820 struct sip_peer *peer = NULL;
15821 struct ast_ha *oldha = NULL;
15822 int obproxyfound=0;
15823 int found=0;
15824 int firstpass=1;
15825 int format=0; /* Ama flags */
15826 time_t regseconds = 0;
15827 char *varname = NULL, *varval = NULL;
15828 struct ast_variable *tmpvar = NULL;
15829 struct ast_flags peerflags[2] = {{(0)}};
15830 struct ast_flags mask[2] = {{(0)}};
15833 if (!realtime)
15834 /* Note we do NOT use find_peer here, to avoid realtime recursion */
15835 /* We also use a case-sensitive comparison (unlike find_peer) so
15836 that case changes made to the peer name will be properly handled
15837 during reload
15839 peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);
15841 if (peer) {
15842 /* Already in the list, remove it and it will be added back (or FREE'd) */
15843 found++;
15844 if (!(peer->objflags & ASTOBJ_FLAG_MARKED))
15845 firstpass = 0;
15846 } else {
15847 if (!(peer = ast_calloc(1, sizeof(*peer))))
15848 return NULL;
15850 if (realtime)
15851 rpeerobjs++;
15852 else
15853 speerobjs++;
15854 ASTOBJ_INIT(peer);
15856 /* Note that our peer HAS had its reference count incrased */
15857 if (firstpass) {
15858 peer->lastmsgssent = -1;
15859 oldha = peer->ha;
15860 peer->ha = NULL;
15861 set_peer_defaults(peer); /* Set peer defaults */
15863 if (!found && name)
15864 ast_copy_string(peer->name, name, sizeof(peer->name));
15866 /* If we have channel variables, remove them (reload) */
15867 if (peer->chanvars) {
15868 ast_variables_destroy(peer->chanvars);
15869 peer->chanvars = NULL;
15870 /* XXX should unregister ? */
15872 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
15873 if (handle_common_options(&peerflags[0], &mask[0], v))
15874 continue;
15875 if (realtime && !strcasecmp(v->name, "regseconds")) {
15876 ast_get_time_t(v->value, &regseconds, 0, NULL);
15877 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
15878 inet_aton(v->value, &(peer->addr.sin_addr));
15879 } else if (realtime && !strcasecmp(v->name, "name"))
15880 ast_copy_string(peer->name, v->value, sizeof(peer->name));
15881 else if (realtime && !strcasecmp(v->name, "fullcontact")) {
15882 ast_copy_string(peer->fullcontact, v->value, sizeof(peer->fullcontact));
15883 ast_set_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT);
15884 } else if (!strcasecmp(v->name, "secret"))
15885 ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
15886 else if (!strcasecmp(v->name, "md5secret"))
15887 ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
15888 else if (!strcasecmp(v->name, "auth"))
15889 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
15890 else if (!strcasecmp(v->name, "callerid")) {
15891 ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
15892 } else if (!strcasecmp(v->name, "fullname")) {
15893 ast_copy_string(peer->cid_name, v->value, sizeof(peer->cid_name));
15894 } else if (!strcasecmp(v->name, "cid_number")) {
15895 ast_copy_string(peer->cid_num, v->value, sizeof(peer->cid_num));
15896 } else if (!strcasecmp(v->name, "context")) {
15897 ast_copy_string(peer->context, v->value, sizeof(peer->context));
15898 } else if (!strcasecmp(v->name, "subscribecontext")) {
15899 ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
15900 } else if (!strcasecmp(v->name, "fromdomain")) {
15901 ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
15902 } else if (!strcasecmp(v->name, "usereqphone")) {
15903 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
15904 } else if (!strcasecmp(v->name, "fromuser")) {
15905 ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
15906 } else if (!strcasecmp(v->name, "host") || !strcasecmp(v->name, "outboundproxy")) {
15907 if (!strcasecmp(v->value, "dynamic")) {
15908 if (!strcasecmp(v->name, "outboundproxy") || obproxyfound) {
15909 ast_log(LOG_WARNING, "You can't have a dynamic outbound proxy, you big silly head at line %d.\n", v->lineno);
15910 } else {
15911 /* They'll register with us */
15912 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
15913 if (!found) {
15914 /* Initialize stuff iff we're not found, otherwise
15915 we keep going with what we had */
15916 memset(&peer->addr.sin_addr, 0, 4);
15917 if (peer->addr.sin_port) {
15918 /* If we've already got a port, make it the default rather than absolute */
15919 peer->defaddr.sin_port = peer->addr.sin_port;
15920 peer->addr.sin_port = 0;
15924 } else {
15925 /* Non-dynamic. Make sure we become that way if we're not */
15926 if (peer->expire > -1)
15927 ast_sched_del(sched, peer->expire);
15928 peer->expire = -1;
15929 ast_clear_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
15930 if (!obproxyfound || !strcasecmp(v->name, "outboundproxy")) {
15931 if (ast_get_ip_or_srv(&peer->addr, v->value, srvlookup ? "_sip._udp" : NULL)) {
15932 ASTOBJ_UNREF(peer, sip_destroy_peer);
15933 return NULL;
15936 if (!strcasecmp(v->name, "outboundproxy"))
15937 obproxyfound=1;
15938 else {
15939 ast_copy_string(peer->tohost, v->value, sizeof(peer->tohost));
15940 if (!peer->addr.sin_port)
15941 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
15944 } else if (!strcasecmp(v->name, "defaultip")) {
15945 if (ast_get_ip(&peer->defaddr, v->value)) {
15946 ASTOBJ_UNREF(peer, sip_destroy_peer);
15947 return NULL;
15949 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
15950 peer->ha = ast_append_ha(v->name, v->value, peer->ha);
15951 } else if (!strcasecmp(v->name, "port")) {
15952 if (!realtime && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC))
15953 peer->defaddr.sin_port = htons(atoi(v->value));
15954 else
15955 peer->addr.sin_port = htons(atoi(v->value));
15956 } else if (!strcasecmp(v->name, "callingpres")) {
15957 peer->callingpres = ast_parse_caller_presentation(v->value);
15958 if (peer->callingpres == -1)
15959 peer->callingpres = atoi(v->value);
15960 } else if (!strcasecmp(v->name, "username")) {
15961 ast_copy_string(peer->username, v->value, sizeof(peer->username));
15962 } else if (!strcasecmp(v->name, "language")) {
15963 ast_copy_string(peer->language, v->value, sizeof(peer->language));
15964 } else if (!strcasecmp(v->name, "regexten")) {
15965 ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
15966 } else if (!strcasecmp(v->name, "call-limit") || !strcasecmp(v->name, "incominglimit")) {
15967 peer->call_limit = atoi(v->value);
15968 if (peer->call_limit < 0)
15969 peer->call_limit = 0;
15970 } else if (!strcasecmp(v->name, "amaflags")) {
15971 format = ast_cdr_amaflags2int(v->value);
15972 if (format < 0) {
15973 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
15974 } else {
15975 peer->amaflags = format;
15977 } else if (!strcasecmp(v->name, "accountcode")) {
15978 ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
15979 } else if (!strcasecmp(v->name, "mohinterpret")
15980 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
15981 ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
15982 } else if (!strcasecmp(v->name, "mohsuggest")) {
15983 ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
15984 } else if (!strcasecmp(v->name, "mailbox")) {
15985 ast_copy_string(peer->mailbox, v->value, sizeof(peer->mailbox));
15986 } else if (!strcasecmp(v->name, "subscribemwi")) {
15987 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
15988 } else if (!strcasecmp(v->name, "vmexten")) {
15989 ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
15990 } else if (!strcasecmp(v->name, "callgroup")) {
15991 peer->callgroup = ast_get_group(v->value);
15992 } else if (!strcasecmp(v->name, "allowtransfer")) {
15993 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
15994 } else if (!strcasecmp(v->name, "pickupgroup")) {
15995 peer->pickupgroup = ast_get_group(v->value);
15996 } else if (!strcasecmp(v->name, "allow")) {
15997 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
15998 } else if (!strcasecmp(v->name, "disallow")) {
15999 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
16000 } else if (!strcasecmp(v->name, "autoframing")) {
16001 peer->autoframing = ast_true(v->value);
16002 } else if (!strcasecmp(v->name, "rtptimeout")) {
16003 if ((sscanf(v->value, "%d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
16004 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16005 peer->rtptimeout = global_rtptimeout;
16007 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
16008 if ((sscanf(v->value, "%d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
16009 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16010 peer->rtpholdtimeout = global_rtpholdtimeout;
16012 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
16013 if ((sscanf(v->value, "%d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
16014 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
16015 peer->rtpkeepalive = global_rtpkeepalive;
16017 } else if (!strcasecmp(v->name, "setvar")) {
16018 /* Set peer channel variable */
16019 varname = ast_strdupa(v->value);
16020 if ((varval = strchr(varname, '='))) {
16021 *varval++ = '\0';
16022 if ((tmpvar = ast_variable_new(varname, varval))) {
16023 tmpvar->next = peer->chanvars;
16024 peer->chanvars = tmpvar;
16027 } else if (!strcasecmp(v->name, "qualify")) {
16028 if (!strcasecmp(v->value, "no")) {
16029 peer->maxms = 0;
16030 } else if (!strcasecmp(v->value, "yes")) {
16031 peer->maxms = DEFAULT_MAXMS;
16032 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
16033 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);
16034 peer->maxms = 0;
16036 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
16037 peer->maxcallbitrate = atoi(v->value);
16038 if (peer->maxcallbitrate < 0)
16039 peer->maxcallbitrate = default_maxcallbitrate;
16042 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && realtime) {
16043 time_t nowtime = time(NULL);
16045 if ((nowtime - regseconds) > 0) {
16046 destroy_association(peer);
16047 memset(&peer->addr, 0, sizeof(peer->addr));
16048 if (option_debug)
16049 ast_log(LOG_DEBUG, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
16052 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
16053 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
16054 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
16055 global_allowsubscribe = TRUE; /* No global ban any more */
16056 if (!found && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && !ast_test_flag(&peer->flags[0], SIP_REALTIME))
16057 reg_source_db(peer);
16058 ASTOBJ_UNMARK(peer);
16059 ast_free_ha(oldha);
16060 return peer;
16063 /*! \brief Re-read SIP.conf config file
16064 \note This function reloads all config data, except for
16065 active peers (with registrations). They will only
16066 change configuration data at restart, not at reload.
16067 SIP debug and recordhistory state will not change
16069 static int reload_config(enum channelreloadreason reason)
16071 struct ast_config *cfg, *ucfg;
16072 struct ast_variable *v;
16073 struct sip_peer *peer;
16074 struct sip_user *user;
16075 struct ast_hostent ahp;
16076 char *cat, *stringp, *context, *oldregcontext;
16077 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
16078 struct hostent *hp;
16079 int format;
16080 struct ast_flags dummy[2];
16081 int auto_sip_domains = FALSE;
16082 struct sockaddr_in old_bindaddr = bindaddr;
16083 int registry_count = 0, peer_count = 0, user_count = 0;
16084 unsigned int temp_tos = 0;
16085 struct ast_flags debugflag = {0};
16087 cfg = ast_config_load(config);
16089 /* We *must* have a config file otherwise stop immediately */
16090 if (!cfg) {
16091 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
16092 return -1;
16095 /* Initialize copy of current global_regcontext for later use in removing stale contexts */
16096 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
16097 oldregcontext = oldcontexts;
16099 /* Clear all flags before setting default values */
16100 /* Preserve debugging settings for console */
16101 ast_copy_flags(&debugflag, &global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
16102 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
16103 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
16104 ast_copy_flags(&global_flags[1], &debugflag, SIP_PAGE2_DEBUG_CONSOLE);
16106 /* Reset IP addresses */
16107 memset(&bindaddr, 0, sizeof(bindaddr));
16108 memset(&localaddr, 0, sizeof(localaddr));
16109 memset(&externip, 0, sizeof(externip));
16110 memset(&default_prefs, 0 , sizeof(default_prefs));
16111 outboundproxyip.sin_port = htons(STANDARD_SIP_PORT);
16112 outboundproxyip.sin_family = AF_INET; /* Type of address: IPv4 */
16113 ourport = STANDARD_SIP_PORT;
16114 srvlookup = DEFAULT_SRVLOOKUP;
16115 global_tos_sip = DEFAULT_TOS_SIP;
16116 global_tos_audio = DEFAULT_TOS_AUDIO;
16117 global_tos_video = DEFAULT_TOS_VIDEO;
16118 externhost[0] = '\0'; /* External host name (for behind NAT DynDNS support) */
16119 externexpire = 0; /* Expiration for DNS re-issuing */
16120 externrefresh = 10;
16121 memset(&outboundproxyip, 0, sizeof(outboundproxyip));
16123 /* Reset channel settings to default before re-configuring */
16124 allow_external_domains = DEFAULT_ALLOW_EXT_DOM; /* Allow external invites */
16125 global_regcontext[0] = '\0';
16126 expiry = DEFAULT_EXPIRY;
16127 global_notifyringing = DEFAULT_NOTIFYRINGING;
16128 global_limitonpeers = FALSE;
16129 global_directrtpsetup = FALSE; /* Experimental feature, disabled by default */
16130 global_notifyhold = FALSE;
16131 global_alwaysauthreject = 0;
16132 global_allowsubscribe = FALSE;
16133 ast_copy_string(global_useragent, DEFAULT_USERAGENT, sizeof(global_useragent));
16134 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
16135 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME))
16136 ast_copy_string(global_realm, DEFAULT_REALM, sizeof(global_realm));
16137 else
16138 ast_copy_string(global_realm, ast_config_AST_SYSTEM_NAME, sizeof(global_realm));
16139 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
16140 compactheaders = DEFAULT_COMPACTHEADERS;
16141 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
16142 global_regattempts_max = 0;
16143 pedanticsipchecking = DEFAULT_PEDANTIC;
16144 global_mwitime = DEFAULT_MWITIME;
16145 autocreatepeer = DEFAULT_AUTOCREATEPEER;
16146 global_autoframing = 0;
16147 global_allowguest = DEFAULT_ALLOWGUEST;
16148 global_rtptimeout = 0;
16149 global_rtpholdtimeout = 0;
16150 global_rtpkeepalive = 0;
16151 global_allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
16152 global_rtautoclear = 120;
16153 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE); /* Default for peers, users: TRUE */
16154 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP); /* Default for peers, users: TRUE */
16155 ast_set_flag(&global_flags[1], SIP_PAGE2_RTUPDATE);
16157 /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for peers and users */
16158 ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
16159 default_subscribecontext[0] = '\0';
16160 default_language[0] = '\0';
16161 default_fromdomain[0] = '\0';
16162 default_qualify = DEFAULT_QUALIFY;
16163 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
16164 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
16165 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
16166 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
16167 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833); /*!< Default DTMF setting: RFC2833 */
16168 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581); /*!< NAT support if requested by device with rport */
16169 ast_set_flag(&global_flags[0], SIP_CAN_REINVITE); /*!< Allow re-invites */
16171 /* Debugging settings, always default to off */
16172 dumphistory = FALSE;
16173 recordhistory = FALSE;
16174 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
16176 /* Misc settings for the channel */
16177 global_relaxdtmf = FALSE;
16178 global_callevents = FALSE;
16179 global_t1min = DEFAULT_T1MIN;
16181 /* Copy the default jb config over global_jbconf */
16182 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
16184 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT);
16186 /* Read the [general] config section of sip.conf (or from realtime config) */
16187 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
16188 if (handle_common_options(&global_flags[0], &dummy[0], v))
16189 continue;
16190 /* handle jb conf */
16191 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
16192 continue;
16194 /* Create the interface list */
16195 if (!strcasecmp(v->name, "context")) {
16196 ast_copy_string(default_context, v->value, sizeof(default_context));
16197 } else if (!strcasecmp(v->name, "allowguest")) {
16198 global_allowguest = ast_true(v->value) ? 1 : 0;
16199 } else if (!strcasecmp(v->name, "realm")) {
16200 ast_copy_string(global_realm, v->value, sizeof(global_realm));
16201 } else if (!strcasecmp(v->name, "useragent")) {
16202 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
16203 if (option_debug)
16204 ast_log(LOG_DEBUG, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
16205 } else if (!strcasecmp(v->name, "allowtransfer")) {
16206 global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
16207 } else if (!strcasecmp(v->name, "rtcachefriends")) {
16208 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
16209 } else if (!strcasecmp(v->name, "rtsavesysname")) {
16210 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTSAVE_SYSNAME);
16211 } else if (!strcasecmp(v->name, "rtupdate")) {
16212 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTUPDATE);
16213 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
16214 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_IGNOREREGEXPIRE);
16215 } else if (!strcasecmp(v->name, "t1min")) {
16216 global_t1min = atoi(v->value);
16217 } else if (!strcasecmp(v->name, "rtautoclear")) {
16218 int i = atoi(v->value);
16219 if (i > 0)
16220 global_rtautoclear = i;
16221 else
16222 i = 0;
16223 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
16224 } else if (!strcasecmp(v->name, "usereqphone")) {
16225 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
16226 } else if (!strcasecmp(v->name, "relaxdtmf")) {
16227 global_relaxdtmf = ast_true(v->value);
16228 } else if (!strcasecmp(v->name, "checkmwi")) {
16229 if ((sscanf(v->value, "%d", &global_mwitime) != 1) || (global_mwitime < 0)) {
16230 ast_log(LOG_WARNING, "'%s' is not a valid MWI time setting at line %d. Using default (10).\n", v->value, v->lineno);
16231 global_mwitime = DEFAULT_MWITIME;
16233 } else if (!strcasecmp(v->name, "vmexten")) {
16234 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
16235 } else if (!strcasecmp(v->name, "rtptimeout")) {
16236 if ((sscanf(v->value, "%d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
16237 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16238 global_rtptimeout = 0;
16240 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
16241 if ((sscanf(v->value, "%d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
16242 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16243 global_rtpholdtimeout = 0;
16245 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
16246 if ((sscanf(v->value, "%d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
16247 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
16248 global_rtpkeepalive = 0;
16250 } else if (!strcasecmp(v->name, "compactheaders")) {
16251 compactheaders = ast_true(v->value);
16252 } else if (!strcasecmp(v->name, "notifymimetype")) {
16253 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
16254 } else if (!strcasecmp(v->name, "limitonpeers")) {
16255 global_limitonpeers = ast_true(v->value);
16256 } else if (!strcasecmp(v->name, "directrtpsetup")) {
16257 global_directrtpsetup = ast_true(v->value);
16258 } else if (!strcasecmp(v->name, "notifyringing")) {
16259 global_notifyringing = ast_true(v->value);
16260 } else if (!strcasecmp(v->name, "notifyhold")) {
16261 global_notifyhold = ast_true(v->value);
16262 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
16263 global_alwaysauthreject = ast_true(v->value);
16264 } else if (!strcasecmp(v->name, "mohinterpret")
16265 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
16266 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
16267 } else if (!strcasecmp(v->name, "mohsuggest")) {
16268 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
16269 } else if (!strcasecmp(v->name, "language")) {
16270 ast_copy_string(default_language, v->value, sizeof(default_language));
16271 } else if (!strcasecmp(v->name, "regcontext")) {
16272 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
16273 stringp = newcontexts;
16274 /* Let's remove any contexts that are no longer defined in regcontext */
16275 cleanup_stale_contexts(stringp, oldregcontext);
16276 /* Create contexts if they don't exist already */
16277 while ((context = strsep(&stringp, "&"))) {
16278 if (!ast_context_find(context))
16279 ast_context_create(NULL, context,"SIP");
16281 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
16282 } else if (!strcasecmp(v->name, "callerid")) {
16283 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
16284 } else if (!strcasecmp(v->name, "fromdomain")) {
16285 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
16286 } else if (!strcasecmp(v->name, "outboundproxy")) {
16287 if (ast_get_ip_or_srv(&outboundproxyip, v->value, srvlookup ? "_sip._udp" : NULL) < 0)
16288 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", v->value);
16289 } else if (!strcasecmp(v->name, "outboundproxyport")) {
16290 /* Port needs to be after IP */
16291 sscanf(v->value, "%d", &format);
16292 outboundproxyip.sin_port = htons(format);
16293 } else if (!strcasecmp(v->name, "autocreatepeer")) {
16294 autocreatepeer = ast_true(v->value);
16295 } else if (!strcasecmp(v->name, "srvlookup")) {
16296 srvlookup = ast_true(v->value);
16297 } else if (!strcasecmp(v->name, "pedantic")) {
16298 pedanticsipchecking = ast_true(v->value);
16299 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
16300 max_expiry = atoi(v->value);
16301 if (max_expiry < 1)
16302 max_expiry = DEFAULT_MAX_EXPIRY;
16303 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
16304 min_expiry = atoi(v->value);
16305 if (min_expiry < 1)
16306 min_expiry = DEFAULT_MIN_EXPIRY;
16307 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
16308 default_expiry = atoi(v->value);
16309 if (default_expiry < 1)
16310 default_expiry = DEFAULT_DEFAULT_EXPIRY;
16311 } else if (!strcasecmp(v->name, "sipdebug")) { /* XXX maybe ast_set2_flags ? */
16312 if (ast_true(v->value))
16313 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
16314 } else if (!strcasecmp(v->name, "dumphistory")) {
16315 dumphistory = ast_true(v->value);
16316 } else if (!strcasecmp(v->name, "recordhistory")) {
16317 recordhistory = ast_true(v->value);
16318 } else if (!strcasecmp(v->name, "registertimeout")) {
16319 global_reg_timeout = atoi(v->value);
16320 if (global_reg_timeout < 1)
16321 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
16322 } else if (!strcasecmp(v->name, "registerattempts")) {
16323 global_regattempts_max = atoi(v->value);
16324 } else if (!strcasecmp(v->name, "bindaddr")) {
16325 if (!(hp = ast_gethostbyname(v->value, &ahp))) {
16326 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
16327 } else {
16328 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
16330 } else if (!strcasecmp(v->name, "localnet")) {
16331 struct ast_ha *na;
16332 if (!(na = ast_append_ha("d", v->value, localaddr)))
16333 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
16334 else
16335 localaddr = na;
16336 } else if (!strcasecmp(v->name, "localmask")) {
16337 ast_log(LOG_WARNING, "Use of localmask is no long supported -- use localnet with mask syntax\n");
16338 } else if (!strcasecmp(v->name, "externip")) {
16339 if (!(hp = ast_gethostbyname(v->value, &ahp)))
16340 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
16341 else
16342 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
16343 externexpire = 0;
16344 } else if (!strcasecmp(v->name, "externhost")) {
16345 ast_copy_string(externhost, v->value, sizeof(externhost));
16346 if (!(hp = ast_gethostbyname(externhost, &ahp)))
16347 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
16348 else
16349 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
16350 externexpire = time(NULL);
16351 } else if (!strcasecmp(v->name, "externrefresh")) {
16352 if (sscanf(v->value, "%d", &externrefresh) != 1) {
16353 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
16354 externrefresh = 10;
16356 } else if (!strcasecmp(v->name, "allow")) {
16357 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 1);
16358 } else if (!strcasecmp(v->name, "disallow")) {
16359 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 0);
16360 } else if (!strcasecmp(v->name, "autoframing")) {
16361 global_autoframing = ast_true(v->value);
16362 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
16363 allow_external_domains = ast_true(v->value);
16364 } else if (!strcasecmp(v->name, "autodomain")) {
16365 auto_sip_domains = ast_true(v->value);
16366 } else if (!strcasecmp(v->name, "domain")) {
16367 char *domain = ast_strdupa(v->value);
16368 char *context = strchr(domain, ',');
16370 if (context)
16371 *context++ = '\0';
16373 if (option_debug && ast_strlen_zero(context))
16374 ast_log(LOG_DEBUG, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
16375 if (ast_strlen_zero(domain))
16376 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
16377 else
16378 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, context ? ast_strip(context) : "");
16379 } else if (!strcasecmp(v->name, "register")) {
16380 if (sip_register(v->value, v->lineno) == 0)
16381 registry_count++;
16382 } else if (!strcasecmp(v->name, "tos")) {
16383 if (!ast_str2tos(v->value, &temp_tos)) {
16384 global_tos_sip = temp_tos;
16385 global_tos_audio = temp_tos;
16386 global_tos_video = temp_tos;
16387 ast_log(LOG_WARNING, "tos value at line %d is deprecated. See doc/ip-tos.txt for more information.\n", v->lineno);
16388 } else
16389 ast_log(LOG_WARNING, "Invalid tos value at line %d, See doc/ip-tos.txt for more information.\n", v->lineno);
16390 } else if (!strcasecmp(v->name, "tos_sip")) {
16391 if (ast_str2tos(v->value, &global_tos_sip))
16392 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, recommended value is 'cs3'. See doc/ip-tos.txt.\n", v->lineno);
16393 } else if (!strcasecmp(v->name, "tos_audio")) {
16394 if (ast_str2tos(v->value, &global_tos_audio))
16395 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, recommended value is 'ef'. See doc/ip-tos.txt.\n", v->lineno);
16396 } else if (!strcasecmp(v->name, "tos_video")) {
16397 if (ast_str2tos(v->value, &global_tos_video))
16398 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, recommended value is 'af41'. See doc/ip-tos.txt.\n", v->lineno);
16399 } else if (!strcasecmp(v->name, "bindport")) {
16400 if (sscanf(v->value, "%d", &ourport) == 1) {
16401 bindaddr.sin_port = htons(ourport);
16402 } else {
16403 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
16405 } else if (!strcasecmp(v->name, "qualify")) {
16406 if (!strcasecmp(v->value, "no")) {
16407 default_qualify = 0;
16408 } else if (!strcasecmp(v->value, "yes")) {
16409 default_qualify = DEFAULT_MAXMS;
16410 } else if (sscanf(v->value, "%d", &default_qualify) != 1) {
16411 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
16412 default_qualify = 0;
16414 } else if (!strcasecmp(v->name, "callevents")) {
16415 global_callevents = ast_true(v->value);
16416 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
16417 default_maxcallbitrate = atoi(v->value);
16418 if (default_maxcallbitrate < 0)
16419 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
16423 if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
16424 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
16425 allow_external_domains = 1;
16428 /* Build list of authentication to various SIP realms, i.e. service providers */
16429 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
16430 /* Format for authentication is auth = username:password@realm */
16431 if (!strcasecmp(v->name, "auth"))
16432 authl = add_realm_authentication(authl, v->value, v->lineno);
16435 ucfg = ast_config_load("users.conf");
16436 if (ucfg) {
16437 struct ast_variable *gen;
16438 int genhassip, genregistersip;
16439 const char *hassip, *registersip;
16441 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
16442 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
16443 gen = ast_variable_browse(ucfg, "general");
16444 cat = ast_category_browse(ucfg, NULL);
16445 while (cat) {
16446 if (strcasecmp(cat, "general")) {
16447 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
16448 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
16449 if (ast_true(hassip) || (!hassip && genhassip)) {
16450 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
16451 if (peer) {
16452 ASTOBJ_CONTAINER_LINK(&peerl,peer);
16453 ASTOBJ_UNREF(peer, sip_destroy_peer);
16454 peer_count++;
16457 if (ast_true(registersip) || (!registersip && genregistersip)) {
16458 char tmp[256];
16459 const char *host = ast_variable_retrieve(ucfg, cat, "host");
16460 const char *username = ast_variable_retrieve(ucfg, cat, "username");
16461 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
16462 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
16463 if (!host)
16464 host = ast_variable_retrieve(ucfg, "general", "host");
16465 if (!username)
16466 username = ast_variable_retrieve(ucfg, "general", "username");
16467 if (!secret)
16468 secret = ast_variable_retrieve(ucfg, "general", "secret");
16469 if (!contact)
16470 contact = "s";
16471 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
16472 if (!ast_strlen_zero(secret))
16473 snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
16474 else
16475 snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
16476 if (sip_register(tmp, 0) == 0)
16477 registry_count++;
16481 cat = ast_category_browse(ucfg, cat);
16483 ast_config_destroy(ucfg);
16487 /* Load peers, users and friends */
16488 cat = NULL;
16489 while ( (cat = ast_category_browse(cfg, cat)) ) {
16490 const char *utype;
16491 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
16492 continue;
16493 utype = ast_variable_retrieve(cfg, cat, "type");
16494 if (!utype) {
16495 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
16496 continue;
16497 } else {
16498 int is_user = 0, is_peer = 0;
16499 if (!strcasecmp(utype, "user"))
16500 is_user = 1;
16501 else if (!strcasecmp(utype, "friend"))
16502 is_user = is_peer = 1;
16503 else if (!strcasecmp(utype, "peer"))
16504 is_peer = 1;
16505 else {
16506 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
16507 continue;
16509 if (is_user) {
16510 user = build_user(cat, ast_variable_browse(cfg, cat), 0);
16511 if (user) {
16512 ASTOBJ_CONTAINER_LINK(&userl,user);
16513 ASTOBJ_UNREF(user, sip_destroy_user);
16514 user_count++;
16517 if (is_peer) {
16518 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
16519 if (peer) {
16520 ASTOBJ_CONTAINER_LINK(&peerl,peer);
16521 ASTOBJ_UNREF(peer, sip_destroy_peer);
16522 peer_count++;
16527 if (ast_find_ourip(&__ourip, bindaddr)) {
16528 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
16529 return 0;
16531 if (!ntohs(bindaddr.sin_port))
16532 bindaddr.sin_port = ntohs(STANDARD_SIP_PORT);
16533 bindaddr.sin_family = AF_INET;
16534 ast_mutex_lock(&netlock);
16535 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
16536 close(sipsock);
16537 sipsock = -1;
16539 if (sipsock < 0) {
16540 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
16541 if (sipsock < 0) {
16542 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
16543 return -1;
16544 } else {
16545 /* Allow SIP clients on the same host to access us: */
16546 const int reuseFlag = 1;
16548 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
16549 (const char*)&reuseFlag,
16550 sizeof reuseFlag);
16552 ast_enable_packet_fragmentation(sipsock);
16554 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
16555 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
16556 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
16557 strerror(errno));
16558 close(sipsock);
16559 sipsock = -1;
16560 } else {
16561 if (option_verbose > 1) {
16562 ast_verbose(VERBOSE_PREFIX_2 "SIP Listening on %s:%d\n",
16563 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
16564 ast_verbose(VERBOSE_PREFIX_2 "Using SIP TOS: %s\n", ast_tos2str(global_tos_sip));
16566 if (setsockopt(sipsock, IPPROTO_IP, IP_TOS, &global_tos_sip, sizeof(global_tos_sip)))
16567 ast_log(LOG_WARNING, "Unable to set SIP TOS to %s\n", ast_tos2str(global_tos_sip));
16571 ast_mutex_unlock(&netlock);
16573 /* Add default domains - host name, IP address and IP:port */
16574 /* Only do this if user added any sip domain with "localdomains" */
16575 /* In order to *not* break backwards compatibility */
16576 /* Some phones address us at IP only, some with additional port number */
16577 if (auto_sip_domains) {
16578 char temp[MAXHOSTNAMELEN];
16580 /* First our default IP address */
16581 if (bindaddr.sin_addr.s_addr)
16582 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
16583 else
16584 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
16586 /* Our extern IP address, if configured */
16587 if (externip.sin_addr.s_addr)
16588 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
16590 /* Extern host name (NAT traversal support) */
16591 if (!ast_strlen_zero(externhost))
16592 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
16594 /* Our host name */
16595 if (!gethostname(temp, sizeof(temp)))
16596 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
16599 /* Release configuration from memory */
16600 ast_config_destroy(cfg);
16602 /* Load the list of manual NOTIFY types to support */
16603 if (notify_types)
16604 ast_config_destroy(notify_types);
16605 notify_types = ast_config_load(notify_config);
16607 /* Done, tell the manager */
16608 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\r\n", channelreloadreason2txt(reason), registry_count, peer_count, user_count);
16610 return 0;
16613 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
16615 struct sip_pvt *p;
16616 struct ast_udptl *udptl = NULL;
16618 p = chan->tech_pvt;
16619 if (!p)
16620 return NULL;
16622 ast_mutex_lock(&p->lock);
16623 if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
16624 udptl = p->udptl;
16625 ast_mutex_unlock(&p->lock);
16626 return udptl;
16629 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
16631 struct sip_pvt *p;
16633 p = chan->tech_pvt;
16634 if (!p)
16635 return -1;
16636 ast_mutex_lock(&p->lock);
16637 if (udptl)
16638 ast_udptl_get_peer(udptl, &p->udptlredirip);
16639 else
16640 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
16641 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
16642 if (!p->pendinginvite) {
16643 if (option_debug > 2) {
16644 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);
16646 transmit_reinvite_with_t38_sdp(p);
16647 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
16648 if (option_debug > 2) {
16649 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);
16651 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
16654 /* Reset lastrtprx timer */
16655 p->lastrtprx = p->lastrtptx = time(NULL);
16656 ast_mutex_unlock(&p->lock);
16657 return 0;
16660 /*! \brief Handle T38 reinvite
16661 \todo Make sure we don't destroy the call if we can't handle the re-invite.
16662 Nothing should be changed until we have processed the SDP and know that we
16663 can handle it.
16665 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite)
16667 struct sip_pvt *p;
16668 int flag = 0;
16670 p = chan->tech_pvt;
16671 if (!p || !pvt->udptl)
16672 return -1;
16674 /* Setup everything on the other side like offered/responded from first side */
16675 ast_mutex_lock(&p->lock);
16677 /*! \todo check if this is not set earlier when setting up the PVT. If not
16678 maybe it should move there. */
16679 p->t38.jointcapability = p->t38.peercapability = pvt->t38.jointcapability;
16681 ast_udptl_set_far_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
16682 ast_udptl_set_local_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
16683 ast_udptl_set_error_correction_scheme(p->udptl, ast_udptl_get_error_correction_scheme(pvt->udptl));
16685 if (reinvite) { /* If we are handling sending re-invite to the other side of the bridge */
16686 /*! \note The SIP_CAN_REINVITE flag is for RTP media redirects,
16687 not really T38 re-invites which are different. In this
16688 case it's used properly, to see if we can reinvite over
16689 NAT
16691 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
16692 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
16693 flag =1;
16694 } else {
16695 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
16697 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
16698 if (!p->pendinginvite) {
16699 if (option_debug > 2) {
16700 if (flag)
16701 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));
16702 else
16703 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));
16705 transmit_reinvite_with_t38_sdp(p);
16706 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
16707 if (option_debug > 2) {
16708 if (flag)
16709 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));
16710 else
16711 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));
16713 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
16716 /* Reset lastrtprx timer */
16717 p->lastrtprx = p->lastrtptx = time(NULL);
16718 ast_mutex_unlock(&p->lock);
16719 return 0;
16720 } else { /* If we are handling sending 200 OK to the other side of the bridge */
16721 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
16722 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
16723 flag = 1;
16724 } else {
16725 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
16727 if (option_debug > 2) {
16728 if (flag)
16729 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));
16730 else
16731 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));
16733 pvt->t38.state = T38_ENABLED;
16734 p->t38.state = T38_ENABLED;
16735 if (option_debug > 1) {
16736 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", pvt->t38.state, pvt->owner ? pvt->owner->name : "<none>");
16737 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
16739 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
16740 p->lastrtprx = p->lastrtptx = time(NULL);
16741 ast_mutex_unlock(&p->lock);
16742 return 0;
16747 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
16748 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
16750 struct sip_pvt *p = NULL;
16751 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
16753 if (!(p = chan->tech_pvt))
16754 return AST_RTP_GET_FAILED;
16756 ast_mutex_lock(&p->lock);
16757 if (!(p->rtp)) {
16758 ast_mutex_unlock(&p->lock);
16759 return AST_RTP_GET_FAILED;
16762 *rtp = p->rtp;
16764 if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT))
16765 res = AST_RTP_TRY_PARTIAL;
16766 else if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
16767 res = AST_RTP_TRY_NATIVE;
16768 else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
16769 res = AST_RTP_GET_FAILED;
16771 ast_mutex_unlock(&p->lock);
16773 return res;
16776 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
16777 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
16779 struct sip_pvt *p = NULL;
16780 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
16782 if (!(p = chan->tech_pvt))
16783 return AST_RTP_GET_FAILED;
16785 ast_mutex_lock(&p->lock);
16786 if (!(p->vrtp)) {
16787 ast_mutex_unlock(&p->lock);
16788 return AST_RTP_GET_FAILED;
16791 *rtp = p->vrtp;
16793 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
16794 res = AST_RTP_TRY_NATIVE;
16796 ast_mutex_unlock(&p->lock);
16798 return res;
16801 /*! \brief Set the RTP peer for this call */
16802 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
16804 struct sip_pvt *p;
16805 int changed = 0;
16807 p = chan->tech_pvt;
16808 if (!p)
16809 return -1;
16811 /* Disable early RTP bridge */
16812 if (chan->_state != AST_STATE_UP && !global_directrtpsetup) /* We are in early state */
16813 return 0;
16815 ast_mutex_lock(&p->lock);
16816 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) {
16817 /* If we're destroyed, don't bother */
16818 ast_mutex_unlock(&p->lock);
16819 return 0;
16822 /* if this peer cannot handle reinvites of the media stream to devices
16823 that are known to be behind a NAT, then stop the process now
16825 if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
16826 ast_mutex_unlock(&p->lock);
16827 return 0;
16830 if (rtp) {
16831 changed |= ast_rtp_get_peer(rtp, &p->redirip);
16832 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
16833 memset(&p->redirip, 0, sizeof(p->redirip));
16834 changed = 1;
16836 if (vrtp) {
16837 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
16838 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
16839 memset(&p->vredirip, 0, sizeof(p->vredirip));
16840 changed = 1;
16842 if (codecs && (p->redircodecs != codecs)) {
16843 p->redircodecs = codecs;
16844 changed = 1;
16846 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
16847 if (chan->_state != AST_STATE_UP) { /* We are in early state */
16848 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
16849 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
16850 if (option_debug)
16851 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));
16852 } else if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
16853 if (option_debug > 2) {
16854 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));
16856 transmit_reinvite_with_sdp(p);
16857 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
16858 if (option_debug > 2) {
16859 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));
16861 /* We have a pending Invite. Send re-invite when we're done with the invite */
16862 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
16865 /* Reset lastrtprx timer */
16866 p->lastrtprx = p->lastrtptx = time(NULL);
16867 ast_mutex_unlock(&p->lock);
16868 return 0;
16871 static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
16872 static char *descrip_dtmfmode = "SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
16873 static char *app_dtmfmode = "SIPDtmfMode";
16875 static char *app_sipaddheader = "SIPAddHeader";
16876 static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
16878 static char *descrip_sipaddheader = ""
16879 " SIPAddHeader(Header: Content)\n"
16880 "Adds a header to a SIP call placed with DIAL.\n"
16881 "Remember to user the X-header if you are adding non-standard SIP\n"
16882 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
16883 "Adding the wrong headers may jeopardize the SIP dialog.\n"
16884 "Always returns 0\n";
16887 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
16888 static int sip_dtmfmode(struct ast_channel *chan, void *data)
16890 struct sip_pvt *p;
16891 char *mode;
16892 if (data)
16893 mode = (char *)data;
16894 else {
16895 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
16896 return 0;
16898 ast_channel_lock(chan);
16899 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
16900 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
16901 ast_channel_unlock(chan);
16902 return 0;
16904 p = chan->tech_pvt;
16905 if (!p) {
16906 ast_channel_unlock(chan);
16907 return 0;
16909 ast_mutex_lock(&p->lock);
16910 if (!strcasecmp(mode,"info")) {
16911 ast_clear_flag(&p->flags[0], SIP_DTMF);
16912 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
16913 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
16914 } else if (!strcasecmp(mode,"rfc2833")) {
16915 ast_clear_flag(&p->flags[0], SIP_DTMF);
16916 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
16917 p->jointnoncodeccapability |= AST_RTP_DTMF;
16918 } else if (!strcasecmp(mode,"inband")) {
16919 ast_clear_flag(&p->flags[0], SIP_DTMF);
16920 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
16921 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
16922 } else
16923 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n",mode);
16924 if (p->rtp)
16925 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
16926 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
16927 if (!p->vad) {
16928 p->vad = ast_dsp_new();
16929 ast_dsp_set_features(p->vad, DSP_FEATURE_DTMF_DETECT);
16931 } else {
16932 if (p->vad) {
16933 ast_dsp_free(p->vad);
16934 p->vad = NULL;
16937 ast_mutex_unlock(&p->lock);
16938 ast_channel_unlock(chan);
16939 return 0;
16942 /*! \brief Add a SIP header to an outbound INVITE */
16943 static int sip_addheader(struct ast_channel *chan, void *data)
16945 int no = 0;
16946 int ok = FALSE;
16947 char varbuf[30];
16948 char *inbuf = (char *) data;
16950 if (ast_strlen_zero(inbuf)) {
16951 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
16952 return 0;
16954 ast_channel_lock(chan);
16956 /* Check for headers */
16957 while (!ok && no <= 50) {
16958 no++;
16959 snprintf(varbuf, sizeof(varbuf), "_SIPADDHEADER%.2d", no);
16961 /* Compare without the leading underscore */
16962 if( (pbx_builtin_getvar_helper(chan, (const char *) varbuf + 1) == (const char *) NULL) )
16963 ok = TRUE;
16965 if (ok) {
16966 pbx_builtin_setvar_helper (chan, varbuf, inbuf);
16967 if (sipdebug)
16968 ast_log(LOG_DEBUG,"SIP Header added \"%s\" as %s\n", inbuf, varbuf);
16969 } else {
16970 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
16972 ast_channel_unlock(chan);
16973 return 0;
16976 /*! \brief Transfer call before connect with a 302 redirect
16977 \note Called by the transfer() dialplan application through the sip_transfer()
16978 pbx interface function if the call is in ringing state
16979 \todo Fix this function so that we wait for reply to the REFER and
16980 react to errors, denials or other issues the other end might have.
16982 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
16984 char *cdest;
16985 char *extension, *host, *port;
16986 char tmp[80];
16988 cdest = ast_strdupa(dest);
16990 extension = strsep(&cdest, "@");
16991 host = strsep(&cdest, ":");
16992 port = strsep(&cdest, ":");
16993 if (ast_strlen_zero(extension)) {
16994 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
16995 return 0;
16998 /* we'll issue the redirect message here */
16999 if (!host) {
17000 char *localtmp;
17001 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
17002 if (ast_strlen_zero(tmp)) {
17003 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
17004 return 0;
17006 if ((localtmp = strstr(tmp, "sip:")) && (localtmp = strchr(localtmp, '@'))) {
17007 char lhost[80], lport[80];
17008 memset(lhost, 0, sizeof(lhost));
17009 memset(lport, 0, sizeof(lport));
17010 localtmp++;
17011 /* This is okey because lhost and lport are as big as tmp */
17012 sscanf(localtmp, "%[^<>:; ]:%[^<>:; ]", lhost, lport);
17013 if (ast_strlen_zero(lhost)) {
17014 ast_log(LOG_ERROR, "Can't find the host address\n");
17015 return 0;
17017 host = ast_strdupa(lhost);
17018 if (!ast_strlen_zero(lport)) {
17019 port = ast_strdupa(lport);
17024 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
17025 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
17027 sip_scheddestroy(p, 32000); /* Make sure we stop send this reply. */
17029 /* hangup here */
17030 return -1;
17033 /*! \brief Return SIP UA's codec (part of the RTP interface) */
17034 static int sip_get_codec(struct ast_channel *chan)
17036 struct sip_pvt *p = chan->tech_pvt;
17037 return p->peercapability;
17040 /*! \brief Send a poke to all known peers
17041 Space them out 100 ms apart
17042 XXX We might have a cool algorithm for this or use random - any suggestions?
17044 static void sip_poke_all_peers(void)
17046 int ms = 0;
17048 if (!speerobjs) /* No peers, just give up */
17049 return;
17051 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
17052 ASTOBJ_WRLOCK(iterator);
17053 if (iterator->pokeexpire > -1)
17054 ast_sched_del(sched, iterator->pokeexpire);
17055 ms += 100;
17056 iterator->pokeexpire = ast_sched_add(sched, ms, sip_poke_peer_s, iterator);
17057 ASTOBJ_UNLOCK(iterator);
17058 } while (0)
17062 /*! \brief Send all known registrations */
17063 static void sip_send_all_registers(void)
17065 int ms;
17066 int regspacing;
17067 if (!regobjs)
17068 return;
17069 regspacing = default_expiry * 1000/regobjs;
17070 if (regspacing > 100)
17071 regspacing = 100;
17072 ms = regspacing;
17073 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
17074 ASTOBJ_WRLOCK(iterator);
17075 if (iterator->expire > -1)
17076 ast_sched_del(sched, iterator->expire);
17077 ms += regspacing;
17078 iterator->expire = ast_sched_add(sched, ms, sip_reregister, iterator);
17079 ASTOBJ_UNLOCK(iterator);
17080 } while (0)
17084 /*! \brief Reload module */
17085 static int sip_do_reload(enum channelreloadreason reason)
17087 if (option_debug > 3)
17088 ast_log(LOG_DEBUG, "--------------- SIP reload started\n");
17090 clear_realm_authentication(authl);
17091 clear_sip_domains();
17092 authl = NULL;
17094 /* First, destroy all outstanding registry calls */
17095 /* This is needed, since otherwise active registry entries will not be destroyed */
17096 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
17097 ASTOBJ_RDLOCK(iterator);
17098 if (iterator->call) {
17099 if (option_debug > 2)
17100 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
17101 /* This will also remove references to the registry */
17102 sip_destroy(iterator->call);
17104 ASTOBJ_UNLOCK(iterator);
17106 } while(0));
17108 /* Then, actually destroy users and registry */
17109 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
17110 if (option_debug > 3)
17111 ast_log(LOG_DEBUG, "--------------- Done destroying user list\n");
17112 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
17113 if (option_debug > 3)
17114 ast_log(LOG_DEBUG, "--------------- Done destroying registry list\n");
17115 ASTOBJ_CONTAINER_MARKALL(&peerl);
17116 reload_config(reason);
17118 /* Prune peers who still are supposed to be deleted */
17119 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
17120 if (option_debug > 3)
17121 ast_log(LOG_DEBUG, "--------------- Done destroying pruned peers\n");
17123 /* Send qualify (OPTIONS) to all peers */
17124 sip_poke_all_peers();
17126 /* Register with all services */
17127 sip_send_all_registers();
17129 if (option_debug > 3)
17130 ast_log(LOG_DEBUG, "--------------- SIP reload done\n");
17132 return 0;
17135 /*! \brief Force reload of module from cli */
17136 static int sip_reload(int fd, int argc, char *argv[])
17138 ast_mutex_lock(&sip_reload_lock);
17139 if (sip_reloading)
17140 ast_verbose("Previous SIP reload not yet done\n");
17141 else {
17142 sip_reloading = TRUE;
17143 if (fd)
17144 sip_reloadreason = CHANNEL_CLI_RELOAD;
17145 else
17146 sip_reloadreason = CHANNEL_MODULE_RELOAD;
17148 ast_mutex_unlock(&sip_reload_lock);
17149 restart_monitor();
17151 return 0;
17154 /*! \brief Part of Asterisk module interface */
17155 static int reload(void)
17157 return sip_reload(0, 0, NULL);
17160 static struct ast_cli_entry cli_sip_debug_deprecated =
17161 { { "sip", "debug", NULL },
17162 sip_do_debug_deprecated, "Enable SIP debugging",
17163 debug_usage };
17165 static struct ast_cli_entry cli_sip_no_debug_deprecated =
17166 { { "sip", "no", "debug", NULL },
17167 sip_no_debug_deprecated, "Disable SIP debugging",
17168 debug_usage };
17170 static struct ast_cli_entry cli_sip[] = {
17171 { { "sip", "show", "channels", NULL },
17172 sip_show_channels, "List active SIP channels",
17173 show_channels_usage },
17175 { { "sip", "show", "domains", NULL },
17176 sip_show_domains, "List our local SIP domains.",
17177 show_domains_usage },
17179 { { "sip", "show", "inuse", NULL },
17180 sip_show_inuse, "List all inuse/limits",
17181 show_inuse_usage },
17183 { { "sip", "show", "objects", NULL },
17184 sip_show_objects, "List all SIP object allocations",
17185 show_objects_usage },
17187 { { "sip", "show", "peers", NULL },
17188 sip_show_peers, "List defined SIP peers",
17189 show_peers_usage },
17191 { { "sip", "show", "registry", NULL },
17192 sip_show_registry, "List SIP registration status",
17193 show_reg_usage },
17195 { { "sip", "show", "settings", NULL },
17196 sip_show_settings, "Show SIP global settings",
17197 show_settings_usage },
17199 { { "sip", "show", "subscriptions", NULL },
17200 sip_show_subscriptions, "List active SIP subscriptions",
17201 show_subscriptions_usage },
17203 { { "sip", "show", "users", NULL },
17204 sip_show_users, "List defined SIP users",
17205 show_users_usage },
17207 { { "sip", "notify", NULL },
17208 sip_notify, "Send a notify packet to a SIP peer",
17209 notify_usage, complete_sipnotify },
17211 { { "sip", "show", "channel", NULL },
17212 sip_show_channel, "Show detailed SIP channel info",
17213 show_channel_usage, complete_sipch },
17215 { { "sip", "show", "history", NULL },
17216 sip_show_history, "Show SIP dialog history",
17217 show_history_usage, complete_sipch },
17219 { { "sip", "show", "peer", NULL },
17220 sip_show_peer, "Show details on specific SIP peer",
17221 show_peer_usage, complete_sip_show_peer },
17223 { { "sip", "show", "user", NULL },
17224 sip_show_user, "Show details on specific SIP user",
17225 show_user_usage, complete_sip_show_user },
17227 { { "sip", "prune", "realtime", NULL },
17228 sip_prune_realtime, "Prune cached Realtime object(s)",
17229 prune_realtime_usage },
17231 { { "sip", "prune", "realtime", "peer", NULL },
17232 sip_prune_realtime, "Prune cached Realtime peer(s)",
17233 prune_realtime_usage, complete_sip_prune_realtime_peer },
17235 { { "sip", "prune", "realtime", "user", NULL },
17236 sip_prune_realtime, "Prune cached Realtime user(s)",
17237 prune_realtime_usage, complete_sip_prune_realtime_user },
17239 { { "sip", "set", "debug", NULL },
17240 sip_do_debug, "Enable SIP debugging",
17241 debug_usage, NULL, &cli_sip_debug_deprecated },
17243 { { "sip", "set", "debug", "ip", NULL },
17244 sip_do_debug, "Enable SIP debugging on IP",
17245 debug_usage },
17247 { { "sip", "set", "debug", "peer", NULL },
17248 sip_do_debug, "Enable SIP debugging on Peername",
17249 debug_usage, complete_sip_debug_peer },
17251 { { "sip", "set", "debug", "off", NULL },
17252 sip_no_debug, "Disable SIP debugging",
17253 no_debug_usage, NULL, &cli_sip_no_debug_deprecated },
17255 { { "sip", "history", NULL },
17256 sip_do_history, "Enable SIP history",
17257 history_usage },
17259 { { "sip", "history", "off", NULL },
17260 sip_no_history, "Disable SIP history",
17261 no_history_usage },
17263 { { "sip", "reload", NULL },
17264 sip_reload, "Reload SIP configuration",
17265 sip_reload_usage },
17268 /*! \brief PBX load module - initialization */
17269 static int load_module(void)
17271 ASTOBJ_CONTAINER_INIT(&userl); /* User object list */
17272 ASTOBJ_CONTAINER_INIT(&peerl); /* Peer object list */
17273 ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list */
17275 if (!(sched = sched_context_create())) {
17276 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
17277 return AST_MODULE_LOAD_FAILURE;
17280 if (!(io = io_context_create())) {
17281 ast_log(LOG_ERROR, "Unable to create I/O context\n");
17282 sched_context_destroy(sched);
17283 return AST_MODULE_LOAD_FAILURE;
17286 sip_reloadreason = CHANNEL_MODULE_LOAD;
17288 if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
17289 return AST_MODULE_LOAD_DECLINE;
17291 /* Make sure we can register our sip channel type */
17292 if (ast_channel_register(&sip_tech)) {
17293 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
17294 io_context_destroy(io);
17295 sched_context_destroy(sched);
17296 return AST_MODULE_LOAD_FAILURE;
17299 /* Register all CLI functions for SIP */
17300 ast_cli_register_multiple(cli_sip, sizeof(cli_sip)/ sizeof(struct ast_cli_entry));
17302 /* Tell the RTP subdriver that we're here */
17303 ast_rtp_proto_register(&sip_rtp);
17305 /* Tell the UDPTL subdriver that we're here */
17306 ast_udptl_proto_register(&sip_udptl);
17308 /* Register dialplan applications */
17309 ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
17310 ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
17312 /* Register dialplan functions */
17313 ast_custom_function_register(&sip_header_function);
17314 ast_custom_function_register(&sippeer_function);
17315 ast_custom_function_register(&sipchaninfo_function);
17316 ast_custom_function_register(&checksipdomain_function);
17318 /* Register manager commands */
17319 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM, manager_sip_show_peers,
17320 "List SIP peers (text format)", mandescr_show_peers);
17321 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM, manager_sip_show_peer,
17322 "Show SIP peer (text format)", mandescr_show_peer);
17324 sip_poke_all_peers();
17325 sip_send_all_registers();
17327 /* And start the monitor for the first time */
17328 restart_monitor();
17330 return AST_MODULE_LOAD_SUCCESS;
17333 /*! \brief PBX unload module API */
17334 static int unload_module(void)
17336 struct sip_pvt *p, *pl;
17338 /* First, take us out of the channel type list */
17339 ast_channel_unregister(&sip_tech);
17341 /* Unregister dial plan functions */
17342 ast_custom_function_unregister(&sipchaninfo_function);
17343 ast_custom_function_unregister(&sippeer_function);
17344 ast_custom_function_unregister(&sip_header_function);
17345 ast_custom_function_unregister(&checksipdomain_function);
17347 /* Unregister dial plan applications */
17348 ast_unregister_application(app_dtmfmode);
17349 ast_unregister_application(app_sipaddheader);
17351 /* Unregister CLI commands */
17352 ast_cli_unregister_multiple(cli_sip, sizeof(cli_sip) / sizeof(struct ast_cli_entry));
17354 /* Disconnect from the RTP subsystem */
17355 ast_rtp_proto_unregister(&sip_rtp);
17357 /* Disconnect from UDPTL */
17358 ast_udptl_proto_unregister(&sip_udptl);
17360 /* Unregister AMI actions */
17361 ast_manager_unregister("SIPpeers");
17362 ast_manager_unregister("SIPshowpeer");
17364 ast_mutex_lock(&iflock);
17365 /* Hangup all interfaces if they have an owner */
17366 for (p = iflist; p ; p = p->next) {
17367 if (p->owner)
17368 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
17370 ast_mutex_unlock(&iflock);
17372 ast_mutex_lock(&monlock);
17373 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
17374 pthread_cancel(monitor_thread);
17375 pthread_kill(monitor_thread, SIGURG);
17376 pthread_join(monitor_thread, NULL);
17378 monitor_thread = AST_PTHREADT_STOP;
17379 ast_mutex_unlock(&monlock);
17381 ast_mutex_lock(&iflock);
17382 /* Destroy all the interfaces and free their memory */
17383 p = iflist;
17384 while (p) {
17385 pl = p;
17386 p = p->next;
17387 __sip_destroy(pl, TRUE);
17389 iflist = NULL;
17390 ast_mutex_unlock(&iflock);
17392 /* Free memory for local network address mask */
17393 ast_free_ha(localaddr);
17395 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
17396 ASTOBJ_CONTAINER_DESTROY(&userl);
17397 ASTOBJ_CONTAINER_DESTROYALL(&peerl, sip_destroy_peer);
17398 ASTOBJ_CONTAINER_DESTROY(&peerl);
17399 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
17400 ASTOBJ_CONTAINER_DESTROY(&regl);
17402 clear_realm_authentication(authl);
17403 clear_sip_domains();
17404 close(sipsock);
17405 sched_context_destroy(sched);
17407 return 0;
17410 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
17411 .load = load_module,
17412 .unload = unload_module,
17413 .reload = reload,