don't try to get the length of the string in the ast_dynamic_str object unless we...
[asterisk-bristuff.git] / channels / chan_sip.c
blob68417ffb74bf7f31837ffc85630524ddc902de32
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/lock.h"
122 #include "asterisk/sched.h"
123 #include "asterisk/io.h"
124 #include "asterisk/rtp.h"
125 #include "asterisk/udptl.h"
126 #include "asterisk/acl.h"
127 #include "asterisk/manager.h"
128 #include "asterisk/callerid.h"
129 #include "asterisk/cli.h"
130 #include "asterisk/app.h"
131 #include "asterisk/musiconhold.h"
132 #include "asterisk/dsp.h"
133 #include "asterisk/features.h"
134 #include "asterisk/acl.h"
135 #include "asterisk/srv.h"
136 #include "asterisk/astdb.h"
137 #include "asterisk/causes.h"
138 #include "asterisk/utils.h"
139 #include "asterisk/file.h"
140 #include "asterisk/astobj.h"
141 #include "asterisk/dnsmgr.h"
142 #include "asterisk/devicestate.h"
143 #include "asterisk/linkedlists.h"
144 #include "asterisk/stringfields.h"
145 #include "asterisk/monitor.h"
146 #include "asterisk/localtime.h"
147 #include "asterisk/abstract_jb.h"
148 #include "asterisk/compiler.h"
150 #ifndef FALSE
151 #define FALSE 0
152 #endif
154 #ifndef TRUE
155 #define TRUE 1
156 #endif
158 #define VIDEO_CODEC_MASK 0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
159 #ifndef IPTOS_MINCOST
160 #define IPTOS_MINCOST 0x02
161 #endif
163 /* #define VOCAL_DATA_HACK */
165 #define DEFAULT_DEFAULT_EXPIRY 120
166 #define DEFAULT_MIN_EXPIRY 60
167 #define DEFAULT_MAX_EXPIRY 3600
168 #define DEFAULT_REGISTRATION_TIMEOUT 20
169 #define DEFAULT_MAX_FORWARDS "70"
171 /* guard limit must be larger than guard secs */
172 /* guard min must be < 1000, and should be >= 250 */
173 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
174 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
175 EXPIRY_GUARD_SECS */
176 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
177 GUARD_PCT turns out to be lower than this, it
178 will use this time instead.
179 This is in milliseconds. */
180 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
181 below EXPIRY_GUARD_LIMIT */
182 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
184 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
185 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
186 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
187 static int expiry = DEFAULT_EXPIRY;
189 #ifndef MAX
190 #define MAX(a,b) ((a) > (b) ? (a) : (b))
191 #endif
193 #define CALLERID_UNKNOWN "Unknown"
195 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
196 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
197 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
199 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
200 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
201 #define SIP_TRANS_TIMEOUT 32000 /*!< SIP request timeout (rfc 3261) 64*T1
202 \todo Use known T1 for timeout (peerpoke)
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";
224 static int usecnt = 0;
227 #define RTP 1
228 #define NO_RTP 0
230 /*! \brief Authorization scheme for call transfers
231 \note Not a bitfield flag, since there are plans for other modes,
232 like "only allow transfers for authenticated devices" */
233 enum transfermodes {
234 TRANSFER_OPENFORALL, /*!< Allow all SIP transfers */
235 TRANSFER_CLOSED, /*!< Allow no SIP transfers */
239 enum sip_result {
240 AST_SUCCESS = 0,
241 AST_FAILURE = -1,
244 /* Do _NOT_ make any changes to this enum, or the array following it;
245 if you think you are doing the right thing, you are probably
246 not doing the right thing. If you think there are changes
247 needed, get someone else to review them first _before_
248 submitting a patch. If these two lists do not match properly
249 bad things will happen.
252 enum xmittype {
253 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
254 If it fails, it's critical and will cause a teardown of the session */
255 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
256 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
259 enum parse_register_result {
260 PARSE_REGISTER_FAILED,
261 PARSE_REGISTER_UPDATE,
262 PARSE_REGISTER_QUERY,
265 enum subscriptiontype {
266 NONE = 0,
267 TIMEOUT,
268 XPIDF_XML,
269 DIALOG_INFO_XML,
270 CPIM_PIDF_XML,
271 PIDF_XML,
272 MWI_NOTIFICATION
275 static const struct cfsubscription_types {
276 enum subscriptiontype type;
277 const char * const event;
278 const char * const mediatype;
279 const char * const text;
280 } subscription_types[] = {
281 { NONE, "-", "unknown", "unknown" },
282 /* RFC 4235: SIP Dialog event package */
283 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
284 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
285 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
286 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
287 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
290 /*! \brief SIP Request methods known by Asterisk */
291 enum sipmethod {
292 SIP_UNKNOWN, /* Unknown response */
293 SIP_RESPONSE, /* Not request, response to outbound request */
294 SIP_REGISTER,
295 SIP_OPTIONS,
296 SIP_NOTIFY,
297 SIP_INVITE,
298 SIP_ACK,
299 SIP_PRACK, /* Not supported at all */
300 SIP_BYE,
301 SIP_REFER,
302 SIP_SUBSCRIBE,
303 SIP_MESSAGE,
304 SIP_UPDATE, /* We can send UPDATE; but not accept it */
305 SIP_INFO,
306 SIP_CANCEL,
307 SIP_PUBLISH, /* Not supported at all */
310 /*! \brief Authentication types - proxy or www authentication
311 \note Endpoints, like Asterisk, should always use WWW authentication to
312 allow multiple authentications in the same call - to the proxy and
313 to the end point.
315 enum sip_auth_type {
316 PROXY_AUTH,
317 WWW_AUTH,
320 /*! \brief Authentication result from check_auth* functions */
321 enum check_auth_result {
322 AUTH_SUCCESSFUL = 0,
323 AUTH_CHALLENGE_SENT = 1,
324 AUTH_SECRET_FAILED = -1,
325 AUTH_USERNAME_MISMATCH = -2,
326 AUTH_NOT_FOUND = -3,
327 AUTH_FAKE_AUTH = -4,
328 AUTH_UNKNOWN_DOMAIN = -5,
331 /* States for outbound registrations (with register= lines in sip.conf */
332 enum sipregistrystate {
333 REG_STATE_UNREGISTERED = 0, /*!< We are not registred */
334 REG_STATE_REGSENT, /*!< Registration request sent */
335 REG_STATE_AUTHSENT, /*!< We have tried to authenticate */
336 REG_STATE_REGISTERED, /*!< Registred and done */
337 REG_STATE_REJECTED, /*!< Registration rejected */
338 REG_STATE_TIMEOUT, /*!< Registration timed out */
339 REG_STATE_NOAUTH, /*!< We have no accepted credentials */
340 REG_STATE_FAILED, /*!< Registration failed after several tries */
344 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
345 static const struct cfsip_methods {
346 enum sipmethod id;
347 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
348 char * const text;
349 } sip_methods[] = {
350 { SIP_UNKNOWN, RTP, "-UNKNOWN-" },
351 { SIP_RESPONSE, NO_RTP, "SIP/2.0" },
352 { SIP_REGISTER, NO_RTP, "REGISTER" },
353 { SIP_OPTIONS, NO_RTP, "OPTIONS" },
354 { SIP_NOTIFY, NO_RTP, "NOTIFY" },
355 { SIP_INVITE, RTP, "INVITE" },
356 { SIP_ACK, NO_RTP, "ACK" },
357 { SIP_PRACK, NO_RTP, "PRACK" },
358 { SIP_BYE, NO_RTP, "BYE" },
359 { SIP_REFER, NO_RTP, "REFER" },
360 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE" },
361 { SIP_MESSAGE, NO_RTP, "MESSAGE" },
362 { SIP_UPDATE, NO_RTP, "UPDATE" },
363 { SIP_INFO, NO_RTP, "INFO" },
364 { SIP_CANCEL, NO_RTP, "CANCEL" },
365 { SIP_PUBLISH, NO_RTP, "PUBLISH" }
368 /*! Define SIP option tags, used in Require: and Supported: headers
369 We need to be aware of these properties in the phones to use
370 the replace: header. We should not do that without knowing
371 that the other end supports it...
372 This is nothing we can configure, we learn by the dialog
373 Supported: header on the REGISTER (peer) or the INVITE
374 (other devices)
375 We are not using many of these today, but will in the future.
376 This is documented in RFC 3261
378 #define SUPPORTED 1
379 #define NOT_SUPPORTED 0
381 #define SIP_OPT_REPLACES (1 << 0)
382 #define SIP_OPT_100REL (1 << 1)
383 #define SIP_OPT_TIMER (1 << 2)
384 #define SIP_OPT_EARLY_SESSION (1 << 3)
385 #define SIP_OPT_JOIN (1 << 4)
386 #define SIP_OPT_PATH (1 << 5)
387 #define SIP_OPT_PREF (1 << 6)
388 #define SIP_OPT_PRECONDITION (1 << 7)
389 #define SIP_OPT_PRIVACY (1 << 8)
390 #define SIP_OPT_SDP_ANAT (1 << 9)
391 #define SIP_OPT_SEC_AGREE (1 << 10)
392 #define SIP_OPT_EVENTLIST (1 << 11)
393 #define SIP_OPT_GRUU (1 << 12)
394 #define SIP_OPT_TARGET_DIALOG (1 << 13)
395 #define SIP_OPT_NOREFERSUB (1 << 14)
396 #define SIP_OPT_HISTINFO (1 << 15)
397 #define SIP_OPT_RESPRIORITY (1 << 16)
399 /*! \brief List of well-known SIP options. If we get this in a require,
400 we should check the list and answer accordingly. */
401 static const struct cfsip_options {
402 int id; /*!< Bitmap ID */
403 int supported; /*!< Supported by Asterisk ? */
404 char * const text; /*!< Text id, as in standard */
405 } sip_options[] = { /* XXX used in 3 places */
406 /* RFC3891: Replaces: header for transfer */
407 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
408 /* One version of Polycom firmware has the wrong label */
409 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
410 /* RFC3262: PRACK 100% reliability */
411 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
412 /* RFC4028: SIP Session Timers */
413 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
414 /* RFC3959: SIP Early session support */
415 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
416 /* RFC3911: SIP Join header support */
417 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
418 /* RFC3327: Path support */
419 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
420 /* RFC3840: Callee preferences */
421 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
422 /* RFC3312: Precondition support */
423 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
424 /* RFC3323: Privacy with proxies*/
425 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
426 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
427 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
428 /* RFC3329: Security agreement mechanism */
429 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
430 /* SIMPLE events: draft-ietf-simple-event-list-07.txt */
431 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
432 /* GRUU: Globally Routable User Agent URI's */
433 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
434 /* Target-dialog: draft-ietf-sip-target-dialog-03.txt */
435 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
436 /* Disable the REFER subscription, RFC 4488 */
437 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
438 /* ietf-sip-history-info-06.txt */
439 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
440 /* ietf-sip-resource-priority-10.txt */
441 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
445 /*! \brief SIP Methods we support */
446 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
448 /*! \brief SIP Extensions we support */
449 #define SUPPORTED_EXTENSIONS "replaces"
452 /* Default values, set and reset in reload_config before reading configuration */
453 /* These are default values in the source. There are other recommended values in the
454 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
455 yet encouraging new behaviour on new installations
457 #define DEFAULT_SIP_PORT 5060 /*!< From RFC 3261 (former 2543) */
458 #define DEFAULT_CONTEXT "default"
459 #define DEFAULT_MOHINTERPRET "default"
460 #define DEFAULT_MOHSUGGEST ""
461 #define DEFAULT_VMEXTEN "asterisk"
462 #define DEFAULT_CALLERID "asterisk"
463 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
464 #define DEFAULT_MWITIME 10
465 #define DEFAULT_ALLOWGUEST TRUE
466 #define DEFAULT_SRVLOOKUP FALSE /*!< Recommended setting is ON */
467 #define DEFAULT_COMPACTHEADERS FALSE
468 #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. */
469 #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. */
470 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
471 #define DEFAULT_ALLOW_EXT_DOM TRUE
472 #define DEFAULT_REALM "asterisk"
473 #define DEFAULT_NOTIFYRINGING TRUE
474 #define DEFAULT_PEDANTIC FALSE
475 #define DEFAULT_AUTOCREATEPEER FALSE
476 #define DEFAULT_QUALIFY FALSE
477 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
478 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
479 #ifndef DEFAULT_USERAGENT
480 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
481 #endif
484 /* Default setttings are used as a channel setting and as a default when
485 configuring devices */
486 static char default_context[AST_MAX_CONTEXT];
487 static char default_subscribecontext[AST_MAX_CONTEXT];
488 static char default_language[MAX_LANGUAGE];
489 static char default_callerid[AST_MAX_EXTENSION];
490 static char default_fromdomain[AST_MAX_EXTENSION];
491 static char default_notifymime[AST_MAX_EXTENSION];
492 static int default_qualify; /*!< Default Qualify= setting */
493 static char default_vmexten[AST_MAX_EXTENSION];
494 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
495 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
496 * a bridged channel on hold */
497 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
498 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
500 /* Global settings only apply to the channel */
501 static int global_rtautoclear;
502 static int global_notifyringing; /*!< Send notifications on ringing */
503 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
504 static int srvlookup; /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
505 static int pedanticsipchecking; /*!< Extra checking ? Default off */
506 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
507 static int global_relaxdtmf; /*!< Relax DTMF */
508 static int global_rtptimeout; /*!< Time out call if no RTP */
509 static int global_rtpholdtimeout;
510 static int global_rtpkeepalive; /*!< Send RTP keepalives */
511 static int global_reg_timeout;
512 static int global_regattempts_max; /*!< Registration attempts before giving up */
513 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
514 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
515 the global setting is in globals_flags[1] */
516 static int global_mwitime; /*!< Time between MWI checks for peers */
517 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
518 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
519 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
520 static int compactheaders; /*!< send compact sip headers */
521 static int recordhistory; /*!< Record SIP history. Off by default */
522 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
523 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
524 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
525 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
526 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
527 static int global_callevents; /*!< Whether we send manager events or not */
528 static int global_t1min; /*!< T1 roundtrip time minimum */
529 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
531 /*! \brief Codecs that we support by default: */
532 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
533 static int noncodeccapability = AST_RTP_DTMF;
535 /* Object counters */
536 static int suserobjs = 0; /*!< Static users */
537 static int ruserobjs = 0; /*!< Realtime users */
538 static int speerobjs = 0; /*!< Statis peers */
539 static int rpeerobjs = 0; /*!< Realtime peers */
540 static int apeerobjs = 0; /*!< Autocreated peer objects */
541 static int regobjs = 0; /*!< Registry objects */
543 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
545 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
546 AST_MUTEX_DEFINE_STATIC(iflock);
548 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
549 when it's doing something critical. */
550 AST_MUTEX_DEFINE_STATIC(netlock);
552 AST_MUTEX_DEFINE_STATIC(monlock);
554 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
556 /*! \brief This is the thread for the monitor which checks for input on the channels
557 which are not currently in use. */
558 static pthread_t monitor_thread = AST_PTHREADT_NULL;
560 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
561 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
563 static struct sched_context *sched; /*!< The scheduling context */
564 static struct io_context *io; /*!< The IO context */
566 #define DEC_CALL_LIMIT 0
567 #define INC_CALL_LIMIT 1
568 #define DEC_CALL_RINGING 2
569 #define INC_CALL_RINGING 3
571 /*! \brief sip_request: The data grabbed from the UDP socket */
572 struct sip_request {
573 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
574 char *rlPart2; /*!< The Request URI or Response Status */
575 int len; /*!< Length */
576 int headers; /*!< # of SIP Headers */
577 int method; /*!< Method of this request */
578 int lines; /*!< Body Content */
579 unsigned int flags; /*!< SIP_PKT Flags for this packet */
580 char *header[SIP_MAX_HEADERS];
581 char *line[SIP_MAX_LINES];
582 char data[SIP_MAX_PACKET];
583 unsigned int sdp_start; /*!< the line number where the SDP begins */
584 unsigned int sdp_end; /*!< the line number where the SDP ends */
588 * A sip packet is stored into the data[] buffer, with the header followed
589 * by an empty line and the body of the message.
590 * On outgoing packets, data is accumulated in data[] with len reflecting
591 * the next available byte, headers and lines count the number of lines
592 * in both parts. There are no '\0' in data[0..len-1].
594 * On received packet, the input read from the socket is copied into data[],
595 * len is set and the string is NUL-terminated. Then a parser fills up
596 * the other fields -header[] and line[] to point to the lines of the
597 * message, rlPart1 and rlPart2 parse the first lnie as below:
599 * Requests have in the first line METHOD URI SIP/2.0
600 * rlPart1 = method; rlPart2 = uri;
601 * Responses have in the first line SIP/2.0 code description
602 * rlPart1 = SIP/2.0; rlPart2 = code + description;
606 /*! \brief structure used in transfers */
607 struct sip_dual {
608 struct ast_channel *chan1; /*!< First channel involved */
609 struct ast_channel *chan2; /*!< Second channel involved */
610 struct sip_request req; /*!< Request that caused the transfer (REFER) */
611 int seqno; /*!< Sequence number */
614 struct sip_pkt;
616 /*! \brief Parameters to the transmit_invite function */
617 struct sip_invite_param {
618 const char *distinctive_ring; /*!< Distinctive ring header */
619 int addsipheaders; /*!< Add extra SIP headers */
620 const char *uri_options; /*!< URI options to add to the URI */
621 const char *vxml_url; /*!< VXML url for Cisco phones */
622 char *auth; /*!< Authentication */
623 char *authheader; /*!< Auth header */
624 enum sip_auth_type auth_type; /*!< Authentication type */
625 const char *replaces; /*!< Replaces header for call transfers */
626 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
629 /*! \brief Structure to save routing information for a SIP session */
630 struct sip_route {
631 struct sip_route *next;
632 char hop[0];
635 /*! \brief Modes for SIP domain handling in the PBX */
636 enum domain_mode {
637 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
638 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
641 struct domain {
642 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
643 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
644 enum domain_mode mode; /*!< How did we find this domain? */
645 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
648 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
651 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
652 struct sip_history {
653 AST_LIST_ENTRY(sip_history) list;
654 char event[0]; /* actually more, depending on needs */
657 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
659 /*! \brief sip_auth: Creadentials for authentication to other SIP services */
660 struct sip_auth {
661 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
662 char username[256]; /*!< Username */
663 char secret[256]; /*!< Secret */
664 char md5secret[256]; /*!< MD5Secret */
665 struct sip_auth *next; /*!< Next auth structure in list */
668 /*--- Various flags for the flags field in the pvt structure */
669 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
670 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed by the monitor thread */
671 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
672 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
673 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
674 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
675 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
676 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
677 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
678 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
679 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
680 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
681 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
682 #define SIP_OUTGOING (1 << 13) /*!< Is this an outgoing call? */
683 #define SIP_CAN_BYE (1 << 14) /*!< Can we send BYE on this dialog? */
684 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 15) /*!< Do not hangup at first ast_hangup */
685 #define SIP_DTMF (3 << 16) /*!< DTMF Support: four settings, uses two bits */
686 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DTMF Support: RTP DTMF - "rfc2833" */
687 #define SIP_DTMF_INBAND (1 << 16) /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
688 #define SIP_DTMF_INFO (2 << 16) /*!< DTMF Support: SIP Info messages - "info" */
689 #define SIP_DTMF_AUTO (3 << 16) /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
690 /* NAT settings */
691 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
692 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
693 #define SIP_NAT_RFC3581 (1 << 18) /*!< NAT RFC3581 */
694 #define SIP_NAT_ROUTE (2 << 18) /*!< NAT Only ROUTE */
695 #define SIP_NAT_ALWAYS (3 << 18) /*!< NAT Both ROUTE and RFC3581 */
696 /* re-INVITE related settings */
697 #define SIP_REINVITE (7 << 20) /*!< three bits used */
698 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
699 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< allow media reinvite when new peer is behind NAT */
700 #define SIP_REINVITE_UPDATE (4 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
701 /* "insecure" settings */
702 #define SIP_INSECURE_PORT (1 << 23) /*!< don't require matching port for incoming requests */
703 #define SIP_INSECURE_INVITE (1 << 24) /*!< don't require authentication for incoming INVITEs */
704 /* Sending PROGRESS in-band settings */
705 #define SIP_PROG_INBAND (3 << 25) /*!< three settings, uses two bits */
706 #define SIP_PROG_INBAND_NEVER (0 << 25)
707 #define SIP_PROG_INBAND_NO (1 << 25)
708 #define SIP_PROG_INBAND_YES (2 << 25)
709 #define SIP_FREE_BIT (1 << 27) /*!< Undefined bit - not in use */
710 #define SIP_CALL_LIMIT (1 << 28) /*!< Call limit enforced for this call */
711 #define SIP_SENDRPID (1 << 29) /*!< Remote Party-ID Support */
712 #define SIP_INC_COUNT (1 << 30) /*!< Did this connection increment the counter of in-use calls? */
713 #define SIP_G726_NONSTANDARD (1 << 31) /*!< Use non-standard packing for G726-32 data */
715 #define SIP_FLAGS_TO_COPY \
716 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
717 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
718 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
720 /* a new page of flags */
721 /* realtime flags */
722 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
723 #define SIP_PAGE2_RTUPDATE (1 << 1)
724 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
725 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
726 #define SIP_PAGE2_RTSAVE_SYSNAME (1 << 5)
727 /* Space for addition of other realtime flags in the future */
728 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 10)
729 #define SIP_PAGE2_DEBUG (3 << 11)
730 #define SIP_PAGE2_DEBUG_CONFIG (1 << 11)
731 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 12)
732 #define SIP_PAGE2_DYNAMIC (1 << 13) /*!< Dynamic Peers register with Asterisk */
733 #define SIP_PAGE2_SELFDESTRUCT (1 << 14) /*!< Automatic peers need to destruct themselves */
734 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15)
735 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< Allow subscriptions from this peer? */
736 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< Allow overlap dialing ? */
737 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< Only issue MWI notification if subscribed to */
738 #define SIP_PAGE2_INC_RINGING (1 << 19) /*!< Did this connection increment the counter of in-use calls? */
739 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< T38 Fax Passthrough Support */
740 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< 20: T38 Fax Passthrough Support */
741 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< 21: T38 Fax Passthrough Support */
742 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< 22: T38 Fax Passthrough Support */
743 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< Call states */
744 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (1 << 23) /*!< 23: One directional hold */
745 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (2 << 24) /*!< 24: Inactive */
746 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 26)
748 #define SIP_PAGE2_FLAGS_TO_COPY \
749 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE)
751 /* SIP packet flags */
752 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
753 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
754 #define SIP_PKT_IGNORE (1 << 2) /*!< This is a re-transmit, ignore it */
755 #define SIP_PKT_IGNORE_RESP (1 << 3) /*!< Resp ignore - ??? */
756 #define SIP_PKT_IGNORE_REQ (1 << 4) /*!< Req ignore - ??? */
758 /* T.38 set of flags */
759 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
760 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
761 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
762 /* Rate management */
763 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
764 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
765 /* UDP Error correction */
766 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
767 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
768 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
769 /* T38 Spec version */
770 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
771 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
772 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
773 /* Maximum Fax Rate */
774 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
775 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
776 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
777 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
778 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
779 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
781 /*!< This is default: NO MMR and JBIG trancoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
782 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
784 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
785 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
786 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
788 /*! \brief T38 States for a call */
789 enum t38state {
790 T38_DISABLED = 0, /*! Not enabled */
791 T38_LOCAL_DIRECT, /*! Offered from local */
792 T38_LOCAL_REINVITE, /*! Offered from local - REINVITE */
793 T38_PEER_DIRECT, /*! Offered from peer */
794 T38_PEER_REINVITE, /*! Offered from peer - REINVITE */
795 T38_ENABLED /*! Negotiated (enabled) */
798 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
799 struct t38properties {
800 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
801 int capability; /*!< Our T38 capability */
802 int peercapability; /*!< Peers T38 capability */
803 int jointcapability; /*!< Supported T38 capability at both ends */
804 enum t38state state; /*!< T.38 state */
807 /*! \brief Parameters to know status of transfer */
808 enum referstatus {
809 REFER_IDLE, /*!< No REFER is in progress */
810 REFER_SENT, /*!< Sent REFER to transferee */
811 REFER_RECEIVED, /*!< Received REFER from transferer */
812 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING */
813 REFER_ACCEPTED, /*!< Accepted by transferee */
814 REFER_RINGING, /*!< Target Ringing */
815 REFER_200OK, /*!< Answered by transfer target */
816 REFER_FAILED, /*!< REFER declined - go on */
817 REFER_NOAUTH /*!< We had no auth for REFER */
820 static const struct c_referstatusstring {
821 enum referstatus status;
822 char *text;
823 } referstatusstrings[] = {
824 { REFER_IDLE, "<none>" },
825 { REFER_SENT, "Request sent" },
826 { REFER_RECEIVED, "Request received" },
827 { REFER_ACCEPTED, "Accepted" },
828 { REFER_RINGING, "Target ringing" },
829 { REFER_200OK, "Done" },
830 { REFER_FAILED, "Failed" },
831 { REFER_NOAUTH, "Failed - auth failure" }
834 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed */
835 /* OEJ: Should be moved to string fields */
836 struct sip_refer {
837 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
838 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
839 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
840 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
841 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
842 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
843 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
844 char replaces_callid[BUFSIZ]; /*!< Replace info: callid */
845 char replaces_callid_totag[BUFSIZ/2]; /*!< Replace info: to-tag */
846 char replaces_callid_fromtag[BUFSIZ/2]; /*!< Replace info: from-tag */
847 struct sip_pvt *refer_call; /*!< Call we are referring */
848 int attendedtransfer; /*!< Attended or blind transfer? */
849 int localtransfer; /*!< Transfer to local domain? */
850 enum referstatus status; /*!< REFER status */
853 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
854 static struct sip_pvt {
855 ast_mutex_t lock; /*!< Dialog private lock */
856 int method; /*!< SIP method that opened this dialog */
857 AST_DECLARE_STRING_FIELDS(
858 AST_STRING_FIELD(callid); /*!< Global CallID */
859 AST_STRING_FIELD(randdata); /*!< Random data */
860 AST_STRING_FIELD(accountcode); /*!< Account code */
861 AST_STRING_FIELD(realm); /*!< Authorization realm */
862 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
863 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
864 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
865 AST_STRING_FIELD(domain); /*!< Authorization domain */
866 AST_STRING_FIELD(from); /*!< The From: header */
867 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
868 AST_STRING_FIELD(exten); /*!< Extension where to start */
869 AST_STRING_FIELD(context); /*!< Context for this call */
870 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
871 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
872 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
873 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
874 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
875 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
876 AST_STRING_FIELD(language); /*!< Default language for this call */
877 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
878 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
879 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
880 AST_STRING_FIELD(theirtag); /*!< Their tag */
881 AST_STRING_FIELD(username); /*!< [user] name */
882 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
883 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
884 AST_STRING_FIELD(uri); /*!< Original requested URI */
885 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
886 AST_STRING_FIELD(peersecret); /*!< Password */
887 AST_STRING_FIELD(peermd5secret);
888 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
889 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
890 AST_STRING_FIELD(via); /*!< Via: header */
891 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
892 AST_STRING_FIELD(our_contact); /*!< Our contact header */
893 AST_STRING_FIELD(rpid); /*!< Our RPID header */
894 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
896 unsigned int ocseq; /*!< Current outgoing seqno */
897 unsigned int icseq; /*!< Current incoming seqno */
898 ast_group_t callgroup; /*!< Call group */
899 ast_group_t pickupgroup; /*!< Pickup group */
900 int lastinvite; /*!< Last Cseq of invite */
901 struct ast_flags flags[2]; /*!< SIP_ flags */
902 int timer_t1; /*!< SIP timer T1, ms rtt */
903 unsigned int sipoptions; /*!< Supported SIP options on the other end */
904 struct ast_codec_pref prefs; /*!< codec prefs */
905 int capability; /*!< Special capability (codec) */
906 int jointcapability; /*!< Supported capability at both ends (codecs ) */
907 int peercapability; /*!< Supported peer capability */
908 int prefcodec; /*!< Preferred codec (outbound only) */
909 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
910 int redircodecs; /*!< Redirect codecs */
911 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
912 struct t38properties t38; /*!< T38 settings */
913 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
914 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
915 int callingpres; /*!< Calling presentation */
916 int authtries; /*!< Times we've tried to authenticate */
917 int expiry; /*!< How long we take to expire */
918 long branch; /*!< The branch identifier of this session */
919 char tag[11]; /*!< Our tag for this session */
920 int sessionid; /*!< SDP Session ID */
921 int sessionversion; /*!< SDP Session Version */
922 struct sockaddr_in sa; /*!< Our peer */
923 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
924 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
925 time_t lastrtprx; /*!< Last RTP received */
926 time_t lastrtptx; /*!< Last RTP sent */
927 int rtptimeout; /*!< RTP timeout time */
928 int rtpholdtimeout; /*!< RTP timeout when on hold */
929 int rtpkeepalive; /*!< Send RTP packets for keepalive */
930 struct sockaddr_in recv; /*!< Received as */
931 struct in_addr ourip; /*!< Our IP */
932 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
933 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
934 int route_persistant; /*!< Is this the "real" route? */
935 struct sip_auth *peerauth; /*!< Realm authentication */
936 int noncecount; /*!< Nonce-count */
937 char lastmsg[256]; /*!< Last Message sent/received */
938 int amaflags; /*!< AMA Flags */
939 int pendinginvite; /*!< Any pending invite ? (seqno of this) */
940 struct sip_request initreq; /*!< Initial request that opened the SIP dialog */
942 int maxtime; /*!< Max time for first response */
943 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
944 int autokillid; /*!< Auto-kill ID (scheduler) */
945 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
946 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
947 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
948 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
949 int laststate; /*!< SUBSCRIBE: Last known extension state */
950 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
952 struct ast_dsp *vad; /*!< Voice Activation Detection dsp */
954 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
955 Used in peerpoke, mwi subscriptions */
956 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
957 struct ast_rtp *rtp; /*!< RTP Session */
958 struct ast_rtp *vrtp; /*!< Video RTP session */
959 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
960 struct sip_history_head *history; /*!< History of this SIP dialog */
961 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
962 struct sip_pvt *next; /*!< Next dialog in chain */
963 struct sip_invite_param *options; /*!< Options for INVITE */
964 } *iflist = NULL;
966 #define FLAG_RESPONSE (1 << 0)
967 #define FLAG_FATAL (1 << 1)
969 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */
970 struct sip_pkt {
971 struct sip_pkt *next; /*!< Next packet in linked list */
972 int retrans; /*!< Retransmission number */
973 int method; /*!< SIP method for this packet */
974 int seqno; /*!< Sequence number */
975 unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */
976 struct sip_pvt *owner; /*!< Owner AST call */
977 int retransid; /*!< Retransmission ID */
978 int timer_a; /*!< SIP timer A, retransmission timer */
979 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
980 int packetlen; /*!< Length of packet */
981 char data[0];
984 /*! \brief Structure for SIP user data. User's place calls to us */
985 struct sip_user {
986 /* Users who can access various contexts */
987 ASTOBJ_COMPONENTS(struct sip_user);
988 char secret[80]; /*!< Password */
989 char md5secret[80]; /*!< Password in md5 */
990 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
991 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
992 char cid_num[80]; /*!< Caller ID num */
993 char cid_name[80]; /*!< Caller ID name */
994 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
995 char language[MAX_LANGUAGE]; /*!< Default language for this user */
996 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
997 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
998 char useragent[256]; /*!< User agent in SIP request */
999 struct ast_codec_pref prefs; /*!< codec prefs */
1000 ast_group_t callgroup; /*!< Call group */
1001 ast_group_t pickupgroup; /*!< Pickup Group */
1002 unsigned int sipoptions; /*!< Supported SIP options */
1003 struct ast_flags flags[2]; /*!< SIP_ flags */
1004 int amaflags; /*!< AMA flags for billing */
1005 int callingpres; /*!< Calling id presentation */
1006 int capability; /*!< Codec capability */
1007 int inUse; /*!< Number of calls in use */
1008 int call_limit; /*!< Limit of concurrent calls */
1009 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1010 struct ast_ha *ha; /*!< ACL setting */
1011 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1012 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1015 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1016 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1017 struct sip_peer {
1018 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
1019 /*!< peer->name is the unique name of this object */
1020 char secret[80]; /*!< Password */
1021 char md5secret[80]; /*!< Password in MD5 */
1022 struct sip_auth *auth; /*!< Realm authentication list */
1023 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1024 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1025 char username[80]; /*!< Temporary username until registration */
1026 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1027 int amaflags; /*!< AMA Flags (for billing) */
1028 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1029 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1030 char fromuser[80]; /*!< From: user when calling this peer */
1031 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1032 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1033 char cid_num[80]; /*!< Caller ID num */
1034 char cid_name[80]; /*!< Caller ID name */
1035 int callingpres; /*!< Calling id presentation */
1036 int inUse; /*!< Number of calls in use */
1037 int inRinging; /*!< Number of calls ringing */
1038 int onHold; /*!< Peer has someone on hold */
1039 int call_limit; /*!< Limit of concurrent calls */
1040 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1041 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1042 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
1043 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1044 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1045 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1046 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1047 struct ast_codec_pref prefs; /*!< codec prefs */
1048 int lastmsgssent;
1049 time_t lastmsgcheck; /*!< Last time we checked for MWI */
1050 unsigned int sipoptions; /*!< Supported SIP options */
1051 struct ast_flags flags[2]; /*!< SIP_ flags */
1052 int expire; /*!< When to expire this peer registration */
1053 int capability; /*!< Codec capability */
1054 int rtptimeout; /*!< RTP timeout */
1055 int rtpholdtimeout; /*!< RTP Hold Timeout */
1056 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1057 ast_group_t callgroup; /*!< Call group */
1058 ast_group_t pickupgroup; /*!< Pickup group */
1059 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
1060 struct sockaddr_in addr; /*!< IP address of peer */
1061 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1063 /* Qualification */
1064 struct sip_pvt *call; /*!< Call pointer */
1065 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1066 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1067 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1068 struct timeval ps; /*!< Ping send time */
1070 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1071 struct ast_ha *ha; /*!< Access control list */
1072 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1073 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1074 int lastmsg;
1079 /*! \brief Registrations with other SIP proxies */
1080 struct sip_registry {
1081 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1082 AST_DECLARE_STRING_FIELDS(
1083 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1084 AST_STRING_FIELD(realm); /*!< Authorization realm */
1085 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1086 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1087 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1088 AST_STRING_FIELD(domain); /*!< Authorization domain */
1089 AST_STRING_FIELD(username); /*!< Who we are registering as */
1090 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1091 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1092 AST_STRING_FIELD(secret); /*!< Password in clear text */
1093 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1094 AST_STRING_FIELD(contact); /*!< Contact extension */
1095 AST_STRING_FIELD(random);
1097 int portno; /*!< Optional port override */
1098 int expire; /*!< Sched ID of expiration */
1099 int regattempts; /*!< Number of attempts (since the last success) */
1100 int timeout; /*!< sched id of sip_reg_timeout */
1101 int refresh; /*!< How often to refresh */
1102 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1103 enum sipregistrystate regstate; /*!< Registration state (see above) */
1104 time_t regtime; /*!< Last succesful registration time */
1105 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1106 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1107 struct sockaddr_in us; /*!< Who the server thinks we are */
1108 int noncecount; /*!< Nonce-count */
1109 char lastmsg[256]; /*!< Last Message sent/received */
1112 /* --- Linked lists of various objects --------*/
1114 /*! \brief The user list: Users and friends */
1115 static struct ast_user_list {
1116 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1117 } userl;
1119 /*! \brief The peer list: Peers and Friends */
1120 static struct ast_peer_list {
1121 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1122 } peerl;
1124 /*! \brief The register list: Other SIP proxys we register with and place calls to */
1125 static struct ast_register_list {
1126 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1127 int recheck;
1128 } regl;
1130 /*! \todo Move the sip_auth list to AST_LIST */
1131 static struct sip_auth *authl = NULL; /*!< Authentication list for realm authentication */
1134 /* --- Sockets and networking --------------*/
1135 static int sipsock = -1; /*!< Main socket for SIP network communication */
1136 static struct sockaddr_in bindaddr = { 0, }; /*!< The address we bind to */
1137 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1138 static char externhost[MAXHOSTNAMELEN]; /*!< External host name (possibly with dynamic DNS and DHCP */
1139 static time_t externexpire = 0; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1140 static int externrefresh = 10;
1141 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1142 static struct in_addr __ourip;
1143 static struct sockaddr_in outboundproxyip;
1144 static int ourport;
1145 static struct sockaddr_in debugaddr;
1147 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1149 /*---------------------------- Forward declarations of functions in chan_sip.c */
1150 /*! \note This is added to help splitting up chan_sip.c into several files
1151 in coming releases */
1153 /*--- PBX interface functions */
1154 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1155 static int sip_devicestate(void *data);
1156 static int sip_sendtext(struct ast_channel *ast, const char *text);
1157 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1158 static int sip_hangup(struct ast_channel *ast);
1159 static int sip_answer(struct ast_channel *ast);
1160 static struct ast_frame *sip_read(struct ast_channel *ast);
1161 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1162 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1163 static int sip_transfer(struct ast_channel *ast, const char *dest);
1164 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1165 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1166 static int sip_senddigit_end(struct ast_channel *ast, char digit);
1168 /*--- Transmitting responses and requests */
1169 static int sipsock_read(int *id, int fd, short events, void *ignore);
1170 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
1171 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
1172 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1173 static int retrans_pkt(void *data);
1174 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
1175 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1176 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1177 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1178 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1179 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1180 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);
1181 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1182 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1183 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1184 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1185 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1186 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
1187 static int transmit_info_with_digit(struct sip_pvt *p, const char digit);
1188 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1189 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1190 static int transmit_refer(struct sip_pvt *p, const char *dest);
1191 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1192 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1193 static int transmit_state_notify(struct sip_pvt *p, int state, int full);
1194 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1195 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1196 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1197 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1198 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1199 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1200 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1201 static int does_peer_need_mwi(struct sip_peer *peer);
1203 /*--- Dialog management */
1204 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1205 int useglobal_nat, const int intended_method);
1206 static int __sip_autodestruct(void *data);
1207 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1208 static void sip_cancel_destroy(struct sip_pvt *p);
1209 static void sip_destroy(struct sip_pvt *p);
1210 static void __sip_destroy(struct sip_pvt *p, int lockowner);
1211 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod, int reset);
1212 static void __sip_pretend_ack(struct sip_pvt *p);
1213 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1214 static int auto_congest(void *nothing);
1215 static int update_call_counter(struct sip_pvt *fup, int event);
1216 static int hangup_sip2cause(int cause);
1217 static const char *hangup_cause2sip(int cause);
1218 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1219 static void free_old_route(struct sip_route *route);
1220 static void list_route(struct sip_route *route);
1221 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1222 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1223 struct sip_request *req, char *uri);
1224 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1225 static void check_pendings(struct sip_pvt *p);
1226 static void *sip_park_thread(void *stuff);
1227 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1228 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1230 /*--- Codec handling / SDP */
1231 static void try_suggested_sip_codec(struct sip_pvt *p);
1232 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1233 static const char *get_sdp(struct sip_request *req, const char *name);
1234 static int find_sdp(struct sip_request *req);
1235 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
1236 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1237 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1238 int debug);
1239 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1240 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1241 int debug);
1242 static int add_sdp(struct sip_request *resp, struct sip_pvt *p);
1244 /*--- Authentication stuff */
1245 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
1246 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1247 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1248 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1249 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno); /* Add realm authentication in list */
1250 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm); /* Find authentication for a specific realm */
1251 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1252 const char *secret, const char *md5secret, int sipmethod,
1253 char *uri, enum xmittype reliable, int ignore);
1254 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1255 int sipmethod, char *uri, enum xmittype reliable,
1256 struct sockaddr_in *sin, struct sip_peer **authpeer);
1257 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1258 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
1259 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len);
1261 /*--- Domain handling */
1262 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1263 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1264 static void clear_sip_domains(void);
1266 /*--- SIP realm authentication */
1267 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
1268 static int clear_realm_authentication(struct sip_auth *authlist);
1269 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1271 /*--- Misc functions */
1272 static int sip_do_reload(enum channelreloadreason reason);
1273 static int reload_config(enum channelreloadreason reason);
1274 static int expire_register(void *data);
1275 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1276 static void *do_monitor(void *data);
1277 static int restart_monitor(void);
1278 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1279 static void sip_destroy(struct sip_pvt *p);
1280 static int sip_addrcmp(char *name, struct sockaddr_in *sin); /* Support for peer matching */
1281 static int sip_refer_allocate(struct sip_pvt *p);
1282 static void ast_quiet_chan(struct ast_channel *chan);
1283 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1285 /*--- Device monitoring and Device/extension state handling */
1286 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1287 static int sip_devicestate(void *data);
1288 static int sip_poke_noanswer(void *data);
1289 static int sip_poke_peer(struct sip_peer *peer);
1290 static void sip_poke_all_peers(void);
1291 static void sip_peer_hold(struct sip_pvt *p, int hold);
1293 /*--- Applications, functions, CLI and manager command helpers */
1294 static const char *sip_nat_mode(const struct sip_pvt *p);
1295 static int sip_show_inuse(int fd, int argc, char *argv[]);
1296 static char *transfermode2str(enum transfermodes mode) attribute_const;
1297 static char *nat2str(int nat) attribute_const;
1298 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1299 static int sip_show_users(int fd, int argc, char *argv[]);
1300 static int _sip_show_peers(int fd, int *total, struct mansession *s, struct message *m, int argc, char *argv[]);
1301 static int manager_sip_show_peers( struct mansession *s, struct message *m );
1302 static int sip_show_peers(int fd, int argc, char *argv[]);
1303 static int sip_show_objects(int fd, int argc, char *argv[]);
1304 static void print_group(int fd, unsigned int group, int crlf);
1305 static const char *dtmfmode2str(int mode) attribute_const;
1306 static const char *insecure2str(int port, int invite) attribute_const;
1307 static void cleanup_stale_contexts(char *new, char *old);
1308 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1309 static const char *domain_mode_to_text(const enum domain_mode mode);
1310 static int sip_show_domains(int fd, int argc, char *argv[]);
1311 static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[]);
1312 static int manager_sip_show_peer( struct mansession *s, struct message *m);
1313 static int sip_show_peer(int fd, int argc, char *argv[]);
1314 static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[]);
1315 static int sip_show_user(int fd, int argc, char *argv[]);
1316 static int sip_show_registry(int fd, int argc, char *argv[]);
1317 static int sip_show_settings(int fd, int argc, char *argv[]);
1318 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1319 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1320 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1321 static int sip_show_channels(int fd, int argc, char *argv[]);
1322 static int sip_show_subscriptions(int fd, int argc, char *argv[]);
1323 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1324 static char *complete_sipch(const char *line, const char *word, int pos, int state);
1325 static char *complete_sip_peer(const char *word, int state, int flags2);
1326 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1327 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state);
1328 static char *complete_sip_user(const char *word, int state, int flags2);
1329 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
1330 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1331 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state);
1332 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state);
1333 static int sip_show_channel(int fd, int argc, char *argv[]);
1334 static int sip_show_history(int fd, int argc, char *argv[]);
1335 static int sip_do_debug_ip(int fd, int argc, char *argv[]);
1336 static int sip_do_debug_peer(int fd, int argc, char *argv[]);
1337 static int sip_do_debug(int fd, int argc, char *argv[]);
1338 static int sip_no_debug(int fd, int argc, char *argv[]);
1339 static int sip_notify(int fd, int argc, char *argv[]);
1340 static int sip_do_history(int fd, int argc, char *argv[]);
1341 static int sip_no_history(int fd, int argc, char *argv[]);
1342 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
1343 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1344 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1345 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1346 static int sip_dtmfmode(struct ast_channel *chan, void *data);
1347 static int sip_addheader(struct ast_channel *chan, void *data);
1348 static int sip_do_reload(enum channelreloadreason reason);
1349 static int sip_reload(int fd, int argc, char *argv[]);
1351 /*--- Debugging
1352 Functions for enabling debug per IP or fully, or enabling history logging for
1353 a SIP dialog
1355 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1356 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1357 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1358 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1359 static void sip_dump_history(struct sip_pvt *dialog);
1361 /*--- Device object handling */
1362 static struct sip_peer *temp_peer(const char *name);
1363 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime);
1364 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
1365 static int update_call_counter(struct sip_pvt *fup, int event);
1366 static void sip_destroy_peer(struct sip_peer *peer);
1367 static void sip_destroy_user(struct sip_user *user);
1368 static int sip_poke_peer(struct sip_peer *peer);
1369 static void set_peer_defaults(struct sip_peer *peer);
1370 static struct sip_peer *temp_peer(const char *name);
1371 static void register_peer_exten(struct sip_peer *peer, int onoff);
1372 static void sip_destroy_peer(struct sip_peer *peer);
1373 static void sip_destroy_user(struct sip_user *user);
1374 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
1375 static struct sip_user *find_user(const char *name, int realtime);
1376 static int sip_poke_peer_s(void *data);
1377 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1378 static int expire_register(void *data);
1379 static void reg_source_db(struct sip_peer *peer);
1380 static void destroy_association(struct sip_peer *peer);
1381 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1383 /* Realtime device support */
1384 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
1385 static struct sip_user *realtime_user(const char *username);
1386 static void update_peer(struct sip_peer *p, int expiry);
1387 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
1388 static int sip_prune_realtime(int fd, int argc, char *argv[]);
1390 /*--- Internal UA client handling (outbound registrations) */
1391 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
1392 static void sip_registry_destroy(struct sip_registry *reg);
1393 static int sip_register(char *value, int lineno);
1394 static char *regstate2str(enum sipregistrystate regstate) attribute_const;
1395 static int sip_reregister(void *data);
1396 static int __sip_do_register(struct sip_registry *r);
1397 static int sip_reg_timeout(void *data);
1398 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader);
1399 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1400 static void sip_send_all_registers(void);
1402 /*--- Parsing SIP requests and responses */
1403 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1404 static int determine_firstline_parts(struct sip_request *req);
1405 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1406 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1407 static int find_sip_method(const char *msg);
1408 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1409 static void parse_request(struct sip_request *req);
1410 static const char *get_header(const struct sip_request *req, const char *name);
1411 static char *referstatus2str(enum referstatus rstatus) attribute_pure;
1412 static int method_match(enum sipmethod id, const char *name);
1413 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1414 static char *get_in_brackets(char *tmp);
1415 static const char *find_alias(const char *name, const char *_default);
1416 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1417 static const char *get_header(const struct sip_request *req, const char *name);
1418 static int lws2sws(char *msgbuf, int len);
1419 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1420 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1421 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1422 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1423 static int set_address_from_contact(struct sip_pvt *pvt);
1424 static void check_via(struct sip_pvt *p, struct sip_request *req);
1425 static char *get_calleridname(const char *input, char *output, size_t outputsize);
1426 static int get_rpid_num(const char *input, char *output, int maxlen);
1427 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
1428 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1429 static int get_msg_text(char *buf, int len, struct sip_request *req);
1430 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1431 static void free_old_route(struct sip_route *route);
1433 /*--- Constructing requests and responses */
1434 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1435 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1436 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1437 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1438 static int init_resp(struct sip_request *resp, const char *msg);
1439 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1440 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1441 static void build_via(struct sip_pvt *p);
1442 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1443 static int create_addr(struct sip_pvt *dialog, const char *opeer);
1444 static char *generate_random_string(char *buf, size_t size);
1445 static void build_callid_pvt(struct sip_pvt *pvt);
1446 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1447 static void make_our_tag(char *tagbuf, size_t len);
1448 static int add_header(struct sip_request *req, const char *var, const char *value);
1449 static int add_header_contentLength(struct sip_request *req, int len);
1450 static int add_line(struct sip_request *req, const char *line);
1451 static int add_text(struct sip_request *req, const char *text);
1452 static int add_digit(struct sip_request *req, char digit);
1453 static int add_vidupdate(struct sip_request *req);
1454 static void add_route(struct sip_request *req, struct sip_route *route);
1455 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1456 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1457 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1458 static void set_destination(struct sip_pvt *p, char *uri);
1459 static void append_date(struct sip_request *req);
1460 static void build_contact(struct sip_pvt *p);
1461 static void build_rpid(struct sip_pvt *p);
1463 /*------Request handling functions */
1464 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1465 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);
1466 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock);
1467 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1468 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1469 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1470 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1471 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1472 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1473 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1474 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1475 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1476 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1477 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
1479 /*------Response handling functions */
1480 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1481 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1482 static int handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req);
1483 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
1484 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
1486 /*----- RTP interface functions */
1487 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
1488 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1489 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1490 static int sip_get_codec(struct ast_channel *chan);
1491 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
1493 /*------ T38 Support --------- */
1494 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite); /*!< T38 negotiation helper function */
1495 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1496 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p);
1497 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1498 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1500 /*! \brief Definition of this channel for PBX channel registration */
1501 static const struct ast_channel_tech sip_tech = {
1502 .type = "SIP",
1503 .description = "Session Initiation Protocol (SIP)",
1504 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1505 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1506 .requester = sip_request_call,
1507 .devicestate = sip_devicestate,
1508 .call = sip_call,
1509 .hangup = sip_hangup,
1510 .answer = sip_answer,
1511 .read = sip_read,
1512 .write = sip_write,
1513 .write_video = sip_write,
1514 .indicate = sip_indicate,
1515 .transfer = sip_transfer,
1516 .fixup = sip_fixup,
1517 .send_digit_begin = sip_senddigit_begin,
1518 .send_digit_end = sip_senddigit_end,
1519 .bridge = ast_rtp_bridge,
1520 .send_text = sip_sendtext,
1523 /**--- some list management macros. **/
1525 #define UNLINK(element, head, prev) do { \
1526 if (prev) \
1527 (prev)->next = (element)->next; \
1528 else \
1529 (head) = (element)->next; \
1530 } while (0)
1532 /*! \brief Interface structure with callbacks used to connect to RTP module */
1533 static struct ast_rtp_protocol sip_rtp = {
1534 type: "SIP",
1535 get_rtp_info: sip_get_rtp_peer,
1536 get_vrtp_info: sip_get_vrtp_peer,
1537 set_rtp_peer: sip_set_rtp_peer,
1538 get_codec: sip_get_codec,
1541 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1542 static struct ast_udptl_protocol sip_udptl = {
1543 type: "SIP",
1544 get_udptl_info: sip_get_udptl_peer,
1545 set_udptl_peer: sip_set_udptl_peer,
1548 /*! \brief Convert transfer status to string */
1549 static char *referstatus2str(enum referstatus rstatus)
1551 int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
1552 int x;
1554 for (x = 0; x < i; x++) {
1555 if (referstatusstrings[x].status == rstatus)
1556 return (char *) referstatusstrings[x].text;
1558 return "";
1561 /*! \brief Initialize the initital request packet in the pvt structure.
1562 This packet is used for creating replies and future requests in
1563 a dialog */
1564 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
1566 if (p->initreq.headers) {
1567 ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
1569 /* Use this as the basis */
1570 copy_request(&p->initreq, req);
1571 parse_request(&p->initreq);
1572 if (ast_test_flag(req, SIP_PKT_DEBUG))
1573 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
1577 /*! \brief returns true if 'name' (with optional trailing whitespace)
1578 * matches the sip method 'id'.
1579 * Strictly speaking, SIP methods are case SENSITIVE, but we do
1580 * a case-insensitive comparison to be more tolerant.
1581 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1583 static int method_match(enum sipmethod id, const char *name)
1585 int len = strlen(sip_methods[id].text);
1586 int l_name = name ? strlen(name) : 0;
1587 /* true if the string is long enough, and ends with whitespace, and matches */
1588 return (l_name >= len && name[len] < 33 &&
1589 !strncasecmp(sip_methods[id].text, name, len));
1592 /*! \brief find_sip_method: Find SIP method from header */
1593 static int find_sip_method(const char *msg)
1595 int i, res = 0;
1597 if (ast_strlen_zero(msg))
1598 return 0;
1599 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
1600 if (method_match(i, msg))
1601 res = sip_methods[i].id;
1603 return res;
1606 /*! \brief Parse supported header in incoming packet */
1607 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
1609 char *next, *sep;
1610 char *temp = ast_strdupa(supported);
1611 unsigned int profile = 0;
1612 int i, found;
1614 if (ast_strlen_zero(supported) )
1615 return 0;
1617 if (option_debug > 2 && sipdebug)
1618 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1620 for (next = temp; next; next = sep) {
1621 found = FALSE;
1622 if ( (sep = strchr(next, ',')) != NULL)
1623 *sep++ = '\0';
1624 next = ast_skip_blanks(next);
1625 if (option_debug > 2 && sipdebug)
1626 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1627 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
1628 if (!strcasecmp(next, sip_options[i].text)) {
1629 profile |= sip_options[i].id;
1630 found = TRUE;
1631 if (option_debug > 2 && sipdebug)
1632 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1633 break;
1636 if (!found && option_debug > 2 && sipdebug) {
1637 if (!strncasecmp(next, "x-", 2))
1638 ast_log(LOG_DEBUG, "Found private SIP option, not supported: %s\n", next);
1639 else
1640 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1644 if (pvt)
1645 pvt->sipoptions = profile;
1646 return profile;
1649 /*! \brief See if we pass debug IP filter */
1650 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
1652 if (!sipdebug)
1653 return 0;
1654 if (debugaddr.sin_addr.s_addr) {
1655 if (((ntohs(debugaddr.sin_port) != 0)
1656 && (debugaddr.sin_port != addr->sin_port))
1657 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1658 return 0;
1660 return 1;
1663 /*! \brief The real destination address for a write */
1664 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
1666 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
1669 /*! \brief Display SIP nat mode */
1670 static const char *sip_nat_mode(const struct sip_pvt *p)
1672 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
1675 /*! \brief Test PVT for debugging output */
1676 static inline int sip_debug_test_pvt(struct sip_pvt *p)
1678 if (!sipdebug)
1679 return 0;
1680 return sip_debug_test_addr(sip_real_dst(p));
1683 /*! \brief Transmit SIP message */
1684 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1686 int res;
1687 const struct sockaddr_in *dst = sip_real_dst(p);
1688 res=sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
1690 if (res != len)
1691 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));
1692 return res;
1696 /*! \brief Build a Via header for a request */
1697 static void build_via(struct sip_pvt *p)
1699 /* Work around buggy UNIDEN UIP200 firmware */
1700 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1702 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1703 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1704 ast_inet_ntoa(p->ourip), ourport, p->branch, rport);
1707 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1709 * Using the localaddr structure built up with localnet statements in sip.conf
1710 * apply it to their address to see if we need to substitute our
1711 * externip or can get away with our internal bindaddr
1713 static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1715 struct sockaddr_in theirs, ours;
1717 /* Get our local information */
1718 ast_ouraddrfor(them, us);
1719 theirs.sin_addr = *them;
1720 ours.sin_addr = *us;
1722 if (localaddr && externip.sin_addr.s_addr &&
1723 ast_apply_ha(localaddr, &theirs) &&
1724 !ast_apply_ha(localaddr, &ours)) {
1725 if (externexpire && time(NULL) >= externexpire) {
1726 struct ast_hostent ahp;
1727 struct hostent *hp;
1729 externexpire = time(NULL) + externrefresh;
1730 if ((hp = ast_gethostbyname(externhost, &ahp))) {
1731 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1732 } else
1733 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1735 *us = externip.sin_addr;
1736 if (option_debug) {
1737 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n",
1738 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
1740 } else if (bindaddr.sin_addr.s_addr)
1741 *us = bindaddr.sin_addr;
1742 return AST_SUCCESS;
1745 /*! \brief Append to SIP dialog history
1746 \return Always returns 0 */
1747 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1749 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1750 __attribute__ ((format (printf, 2, 3)));
1752 /*! \brief Append to SIP dialog history with arg list */
1753 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1755 char buf[80], *c = buf; /* max history length */
1756 struct sip_history *hist;
1757 int l;
1759 vsnprintf(buf, sizeof(buf), fmt, ap);
1760 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1761 l = strlen(buf) + 1;
1762 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1763 return;
1764 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1765 free(hist);
1766 return;
1768 memcpy(hist->event, buf, l);
1769 AST_LIST_INSERT_TAIL(p->history, hist, list);
1772 /*! \brief Append to SIP dialog history with arg list */
1773 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1775 va_list ap;
1777 if (!recordhistory || !p)
1778 return;
1779 va_start(ap, fmt);
1780 append_history_va(p, fmt, ap);
1781 va_end(ap);
1783 return;
1786 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
1787 static int retrans_pkt(void *data)
1789 struct sip_pkt *pkt = data, *prev, *cur = NULL;
1790 int reschedule = DEFAULT_RETRANS;
1792 /* Lock channel PVT */
1793 ast_mutex_lock(&pkt->owner->lock);
1795 if (pkt->retrans < MAX_RETRANS) {
1796 pkt->retrans++;
1797 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
1798 if (sipdebug && option_debug > 3)
1799 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);
1800 } else {
1801 int siptimer_a;
1803 if (sipdebug && option_debug > 3)
1804 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1805 if (!pkt->timer_a)
1806 pkt->timer_a = 2 ;
1807 else
1808 pkt->timer_a = 2 * pkt->timer_a;
1810 /* For non-invites, a maximum of 4 secs */
1811 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
1812 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1813 siptimer_a = 4000;
1815 /* Reschedule re-transmit */
1816 reschedule = siptimer_a;
1817 if (option_debug > 3)
1818 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);
1821 if (sip_debug_test_pvt(pkt->owner)) {
1822 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
1823 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
1824 pkt->retrans, sip_nat_mode(pkt->owner),
1825 ast_inet_ntoa(dst->sin_addr),
1826 ntohs(dst->sin_port), pkt->data);
1829 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1830 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1831 ast_mutex_unlock(&pkt->owner->lock);
1832 return reschedule;
1834 /* Too many retries */
1835 if (pkt->owner && pkt->method != SIP_OPTIONS) {
1836 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1837 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");
1838 } else {
1839 if ((pkt->method == SIP_OPTIONS) && sipdebug)
1840 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1842 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1844 pkt->retransid = -1;
1846 if (ast_test_flag(pkt, FLAG_FATAL)) {
1847 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
1848 ast_mutex_unlock(&pkt->owner->lock); /* SIP_PVT, not channel */
1849 usleep(1);
1850 ast_mutex_lock(&pkt->owner->lock);
1852 if (pkt->owner->owner) {
1853 ast_set_flag(&pkt->owner->flags[0], SIP_ALREADYGONE);
1854 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1855 ast_queue_hangup(pkt->owner->owner);
1856 ast_channel_unlock(pkt->owner->owner);
1857 } else {
1858 /* If no channel owner, destroy now */
1859 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
1862 /* In any case, go ahead and remove the packet */
1863 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
1864 if (cur == pkt)
1865 break;
1867 if (cur) {
1868 if (prev)
1869 prev->next = cur->next;
1870 else
1871 pkt->owner->packets = cur->next;
1872 ast_mutex_unlock(&pkt->owner->lock);
1873 free(cur);
1874 pkt = NULL;
1875 } else
1876 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
1877 if (pkt)
1878 ast_mutex_unlock(&pkt->owner->lock);
1879 return 0;
1882 /*! \brief Transmit packet with retransmits
1883 \return 0 on success, -1 on failure to allocate packet
1885 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
1887 struct sip_pkt *pkt;
1888 int siptimer_a = DEFAULT_RETRANS;
1890 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
1891 return AST_FAILURE;
1892 memcpy(pkt->data, data, len);
1893 pkt->method = sipmethod;
1894 pkt->packetlen = len;
1895 pkt->next = p->packets;
1896 pkt->owner = p;
1897 pkt->seqno = seqno;
1898 pkt->flags = resp;
1899 pkt->data[len] = '\0';
1900 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
1901 if (fatal)
1902 ast_set_flag(pkt, FLAG_FATAL);
1903 if (pkt->timer_t1)
1904 siptimer_a = pkt->timer_t1 * 2;
1906 /* Schedule retransmission */
1907 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
1908 if (option_debug > 3 && sipdebug)
1909 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt->retransid);
1910 pkt->next = p->packets;
1911 p->packets = pkt;
1913 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
1914 if (sipmethod == SIP_INVITE) {
1915 /* Note this is a pending invite */
1916 p->pendinginvite = seqno;
1918 return AST_SUCCESS;
1921 /*! \brief Kill a SIP dialog (called by scheduler) */
1922 static int __sip_autodestruct(void *data)
1924 struct sip_pvt *p = data;
1926 /* If this is a subscription, tell the phone that we got a timeout */
1927 if (p->subscribed) {
1928 p->subscribed = TIMEOUT;
1929 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1); /* Send last notification */
1930 p->subscribed = NONE;
1931 append_history(p, "Subscribestatus", "timeout");
1932 if (option_debug > 2)
1933 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
1934 return 10000; /* Reschedule this destruction so that we know that it's gone */
1937 /* Reset schedule ID */
1938 p->autokillid = -1;
1940 if (option_debug)
1941 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
1942 append_history(p, "AutoDestroy", "%s", p->callid);
1943 if (p->owner) {
1944 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
1945 ast_queue_hangup(p->owner);
1946 } else if (p->refer) {
1947 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
1948 } else {
1949 sip_destroy(p);
1951 return 0;
1954 /*! \brief Schedule destruction of SIP call */
1955 static void sip_scheddestroy(struct sip_pvt *p, int ms)
1957 if (sip_debug_test_pvt(p))
1958 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
1959 if (recordhistory)
1960 append_history(p, "SchedDestroy", "%d ms", ms);
1962 if (p->autokillid > -1)
1963 ast_sched_del(sched, p->autokillid);
1964 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
1967 /*! \brief Cancel destruction of SIP dialog */
1968 static void sip_cancel_destroy(struct sip_pvt *p)
1970 if (p->autokillid > -1) {
1971 ast_sched_del(sched, p->autokillid);
1972 append_history(p, "CancelDestroy", "");
1973 p->autokillid = -1;
1977 /*! \brief Acknowledges receipt of a packet and stops retransmission */
1978 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod, int reset)
1980 struct sip_pkt *cur, *prev = NULL;
1982 /* Just in case... */
1983 char *msg;
1984 int res = FALSE;
1986 msg = sip_methods[sipmethod].text;
1988 ast_mutex_lock(&p->lock);
1989 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
1990 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1991 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
1992 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1993 if (!resp && (seqno == p->pendinginvite)) {
1994 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
1995 p->pendinginvite = 0;
1997 /* this is our baby */
1998 res = TRUE;
1999 UNLINK(cur, p->packets, prev);
2000 if (cur->retransid > -1) {
2001 if (sipdebug && option_debug > 3)
2002 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
2003 ast_sched_del(sched, cur->retransid);
2005 if (!reset)
2006 free(cur);
2007 break;
2010 ast_mutex_unlock(&p->lock);
2011 if (option_debug)
2012 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
2015 /*! \brief Pretend to ack all packets
2016 * maybe the lock on p is not strictly necessary but there might be a race */
2017 static void __sip_pretend_ack(struct sip_pvt *p)
2019 struct sip_pkt *cur = NULL;
2021 while (p->packets) {
2022 int method;
2023 if (cur == p->packets) {
2024 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
2025 return;
2027 cur = p->packets;
2028 method = (cur->method) ? cur->method : find_sip_method(cur->data);
2029 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method, FALSE);
2033 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2034 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2036 struct sip_pkt *cur;
2037 int res = -1;
2039 for (cur = p->packets; cur; cur = cur->next) {
2040 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
2041 (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
2042 /* this is our baby */
2043 if (cur->retransid > -1) {
2044 if (option_debug > 3 && sipdebug)
2045 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
2046 ast_sched_del(sched, cur->retransid);
2048 cur->retransid = -1;
2049 res = 0;
2050 break;
2053 if (option_debug)
2054 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");
2055 return res;
2059 /*! \brief Copy SIP request, parse it */
2060 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2062 memset(dst, 0, sizeof(*dst));
2063 memcpy(dst->data, src->data, sizeof(dst->data));
2064 dst->len = src->len;
2065 parse_request(dst);
2068 /* add a blank line if no body */
2069 static void add_blank(struct sip_request *req)
2071 if (!req->lines) {
2072 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2073 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2074 req->len += strlen(req->data + req->len);
2078 /*! \brief Transmit response on SIP request*/
2079 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2081 int res;
2083 add_blank(req);
2084 if (sip_debug_test_pvt(p)) {
2085 const struct sockaddr_in *dst = sip_real_dst(p);
2087 ast_verbose("%sTransmitting (%s) to %s:%d:\n%s\n---\n",
2088 reliable ? "Reliably " : "", sip_nat_mode(p),
2089 ast_inet_ntoa(dst->sin_addr),
2090 ntohs(dst->sin_port), req->data);
2092 if (recordhistory) {
2093 struct sip_request tmp;
2094 parse_copy(&tmp, req);
2095 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
2096 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
2098 res = (reliable) ?
2099 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2100 __sip_xmit(p, req->data, req->len);
2101 if (res > 0)
2102 return 0;
2103 return res;
2106 /*! \brief Send SIP Request to the other part of the dialogue */
2107 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2109 int res;
2111 add_blank(req);
2112 if (sip_debug_test_pvt(p)) {
2113 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
2114 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);
2115 else
2116 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);
2118 if (recordhistory) {
2119 struct sip_request tmp;
2120 parse_copy(&tmp, req);
2121 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
2123 res = (reliable) ?
2124 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method) :
2125 __sip_xmit(p, req->data, req->len);
2126 return res;
2129 /*! \brief Pick out text in brackets from character string
2130 \return pointer to terminated stripped string
2131 \param tmp input string that will be modified */
2132 static char *get_in_brackets(char *tmp)
2134 char *parse;
2135 char *first_quote;
2136 char *first_bracket;
2137 char *second_bracket;
2138 char last_char;
2140 parse = tmp;
2141 for (;;) {
2142 first_quote = strchr(parse, '"');
2143 first_bracket = strchr(parse, '<');
2144 if (first_quote && first_bracket && (first_quote < first_bracket)) {
2145 last_char = '\0';
2146 for (parse = first_quote + 1; *parse; parse++) {
2147 if ((*parse == '"') && (last_char != '\\'))
2148 break;
2149 last_char = *parse;
2151 if (!*parse) {
2152 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
2153 return tmp;
2155 parse++;
2156 continue;
2158 if (first_bracket) {
2159 second_bracket = strchr(first_bracket + 1, '>');
2160 if (second_bracket) {
2161 *second_bracket = '\0';
2162 return first_bracket + 1;
2163 } else {
2164 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
2165 return tmp;
2168 return tmp;
2172 /*! \brief Send SIP MESSAGE text within a call
2173 Called from PBX core sendtext() application */
2174 static int sip_sendtext(struct ast_channel *ast, const char *text)
2176 struct sip_pvt *p = ast->tech_pvt;
2177 int debug = sip_debug_test_pvt(p);
2179 if (debug)
2180 ast_verbose("Sending text %s on %s\n", text, ast->name);
2181 if (!p)
2182 return -1;
2183 if (ast_strlen_zero(text))
2184 return 0;
2185 if (debug)
2186 ast_verbose("Really sending text %s on %s\n", text, ast->name);
2187 transmit_message_with_text(p, text);
2188 return 0;
2191 /*! \brief Update peer object in realtime storage
2192 If the Asterisk system name is set in asterisk.conf, we will use
2193 that name and store that in the "regserver" field in the sippeers
2194 table to facilitate multi-server setups.
2196 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
2198 char port[10];
2199 char ipaddr[INET_ADDRSTRLEN];
2200 char regseconds[20];
2202 char *sysname = ast_config_AST_SYSTEM_NAME;
2203 char *syslabel = NULL;
2205 time_t nowtime = time(NULL) + expirey;
2206 const char *fc = fullcontact ? "fullcontact" : NULL;
2208 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
2209 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2210 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2212 if (ast_strlen_zero(sysname)) /* No system name, disable this */
2213 sysname = NULL;
2214 else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME))
2215 syslabel = "regserver";
2217 if (fc)
2218 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2219 "port", port, "regseconds", regseconds,
2220 "username", username, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
2221 else
2222 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2223 "port", port, "regseconds", regseconds,
2224 "username", username, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
2227 /*! \brief Automatically add peer extension to dial plan */
2228 static void register_peer_exten(struct sip_peer *peer, int onoff)
2230 char multi[256];
2231 char *stringp, *ext, *context;
2233 /* XXX note that global_regcontext is both a global 'enable' flag and
2234 * the name of the global regexten context, if not specified
2235 * individually.
2237 if (ast_strlen_zero(global_regcontext))
2238 return;
2240 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
2241 stringp = multi;
2242 while ((ext = strsep(&stringp, "&"))) {
2243 if ((context = strchr(ext, '@'))) {
2244 *context++ = '\0'; /* split ext@context */
2245 if (!ast_context_find(context)) {
2246 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
2247 continue;
2249 } else {
2250 context = global_regcontext;
2252 if (onoff)
2253 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2254 ast_strdup(peer->name), ast_free, "SIP");
2255 else
2256 ast_context_remove_extension(context, ext, 1, NULL);
2260 /*! \brief Destroy peer object from memory */
2261 static void sip_destroy_peer(struct sip_peer *peer)
2263 if (option_debug > 2)
2264 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
2266 /* Delete it, it needs to disappear */
2267 if (peer->call)
2268 sip_destroy(peer->call);
2270 if (peer->mwipvt) /* We have an active subscription, delete it */
2271 sip_destroy(peer->mwipvt);
2273 if (peer->chanvars) {
2274 ast_variables_destroy(peer->chanvars);
2275 peer->chanvars = NULL;
2277 if (peer->expire > -1)
2278 ast_sched_del(sched, peer->expire);
2279 if (peer->pokeexpire > -1)
2280 ast_sched_del(sched, peer->pokeexpire);
2281 register_peer_exten(peer, FALSE);
2282 ast_free_ha(peer->ha);
2283 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
2284 apeerobjs--;
2285 else if (ast_test_flag(&peer->flags[0], SIP_REALTIME))
2286 rpeerobjs--;
2287 else
2288 speerobjs--;
2289 clear_realm_authentication(peer->auth);
2290 peer->auth = NULL;
2291 if (peer->dnsmgr)
2292 ast_dnsmgr_release(peer->dnsmgr);
2293 free(peer);
2296 /*! \brief Update peer data in database (if used) */
2297 static void update_peer(struct sip_peer *p, int expiry)
2299 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2300 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
2301 (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
2302 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
2307 /*! \brief realtime_peer: Get peer from realtime storage
2308 * Checks the "sippeers" realtime family from extconfig.conf
2309 * \todo Consider adding check of port address when matching here to follow the same
2310 * algorithm as for static peers. Will we break anything by adding that?
2312 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
2314 struct sip_peer *peer;
2315 struct ast_variable *var = NULL;
2316 struct ast_variable *tmp;
2317 char ipaddr[INET_ADDRSTRLEN];
2319 /* First check on peer name */
2320 if (newpeername)
2321 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
2322 else if (sin) { /* Then check on IP address for dynamic peers */
2323 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2324 var = ast_load_realtime("sippeers", "host", ipaddr, NULL); /* First check for fixed IP hosts */
2325 if (!var)
2326 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, NULL); /* Then check for registred hosts */
2329 if (!var)
2330 return NULL;
2332 for (tmp = var; tmp; tmp = tmp->next) {
2333 /* If this is type=user, then skip this object. */
2334 if (!strcasecmp(tmp->name, "type") &&
2335 !strcasecmp(tmp->value, "user")) {
2336 ast_variables_destroy(var);
2337 return NULL;
2338 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
2339 newpeername = tmp->value;
2343 if (!newpeername) { /* Did not find peer in realtime */
2344 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
2345 ast_variables_destroy(var);
2346 return NULL;
2349 /* Peer found in realtime, now build it in memory */
2350 peer = build_peer(newpeername, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2351 if (!peer) {
2352 ast_variables_destroy(var);
2353 return NULL;
2356 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2357 /* Cache peer */
2358 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
2359 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
2360 if (peer->expire > -1) {
2361 ast_sched_del(sched, peer->expire);
2363 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
2365 ASTOBJ_CONTAINER_LINK(&peerl,peer);
2366 } else {
2367 ast_set_flag(&peer->flags[0], SIP_REALTIME);
2369 ast_variables_destroy(var);
2371 return peer;
2374 /*! \brief Support routine for find_peer */
2375 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
2377 /* We know name is the first field, so we can cast */
2378 struct sip_peer *p = (struct sip_peer *) name;
2379 return !(!inaddrcmp(&p->addr, sin) ||
2380 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
2381 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
2384 /*! \brief Locate peer by name or ip address
2385 * This is used on incoming SIP message to find matching peer on ip
2386 or outgoing message to find matching peer on name */
2387 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
2389 struct sip_peer *p = NULL;
2391 if (peer)
2392 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
2393 else
2394 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
2396 if (!p && realtime) {
2397 p = realtime_peer(peer, sin);
2399 return p;
2402 /*! \brief Remove user object from in-memory storage */
2403 static void sip_destroy_user(struct sip_user *user)
2405 if (option_debug > 2)
2406 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
2407 ast_free_ha(user->ha);
2408 if (user->chanvars) {
2409 ast_variables_destroy(user->chanvars);
2410 user->chanvars = NULL;
2412 if (ast_test_flag(&user->flags[0], SIP_REALTIME))
2413 ruserobjs--;
2414 else
2415 suserobjs--;
2416 free(user);
2419 /*! \brief Load user from realtime storage
2420 * Loads user from "sipusers" category in realtime (extconfig.conf)
2421 * Users are matched on From: user name (the domain in skipped) */
2422 static struct sip_user *realtime_user(const char *username)
2424 struct ast_variable *var;
2425 struct ast_variable *tmp;
2426 struct sip_user *user = NULL;
2428 var = ast_load_realtime("sipusers", "name", username, NULL);
2430 if (!var)
2431 return NULL;
2433 for (tmp = var; tmp; tmp = tmp->next) {
2434 if (!strcasecmp(tmp->name, "type") &&
2435 !strcasecmp(tmp->value, "peer")) {
2436 ast_variables_destroy(var);
2437 return NULL;
2441 user = build_user(username, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2443 if (!user) { /* No user found */
2444 ast_variables_destroy(var);
2445 return NULL;
2448 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2449 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2450 suserobjs++;
2451 ASTOBJ_CONTAINER_LINK(&userl,user);
2452 } else {
2453 /* Move counter from s to r... */
2454 suserobjs--;
2455 ruserobjs++;
2456 ast_set_flag(&user->flags[0], SIP_REALTIME);
2458 ast_variables_destroy(var);
2459 return user;
2462 /*! \brief Locate user by name
2463 * Locates user by name (From: sip uri user name part) first
2464 * from in-memory list (static configuration) then from
2465 * realtime storage (defined in extconfig.conf) */
2466 static struct sip_user *find_user(const char *name, int realtime)
2468 struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
2469 if (!u && realtime)
2470 u = realtime_user(name);
2471 return u;
2474 /*! \brief Create address structure from peer reference.
2475 * return -1 on error, 0 on success.
2477 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer)
2479 int natflags;
2481 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
2482 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
2483 r->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
2484 r->recv = r->sa;
2485 } else {
2486 return -1;
2489 ast_copy_flags(&r->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
2490 ast_copy_flags(&r->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
2491 r->capability = peer->capability;
2492 if (!ast_test_flag(&r->flags[1], SIP_PAGE2_VIDEOSUPPORT) && r->vrtp) {
2493 ast_rtp_destroy(r->vrtp);
2494 r->vrtp = NULL;
2496 r->prefs = peer->prefs;
2497 if (ast_test_flag(&r->flags[1], SIP_PAGE2_T38SUPPORT)) {
2498 r->t38.capability = global_t38_capability;
2499 if (r->udptl) {
2500 if (ast_udptl_get_error_correction_scheme(r->udptl) == UDPTL_ERROR_CORRECTION_FEC )
2501 r->t38.capability |= T38FAX_UDP_EC_FEC;
2502 else if (ast_udptl_get_error_correction_scheme(r->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
2503 r->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
2504 else if (ast_udptl_get_error_correction_scheme(r->udptl) == UDPTL_ERROR_CORRECTION_NONE )
2505 r->t38.capability |= T38FAX_UDP_EC_NONE;
2506 r->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
2507 if (option_debug > 1)
2508 ast_log(LOG_DEBUG,"Our T38 capability (%d)\n", r->t38.capability);
2510 r->t38.jointcapability = r->t38.capability;
2511 } else if (r->udptl) {
2512 ast_udptl_destroy(r->udptl);
2513 r->udptl = NULL;
2515 natflags = ast_test_flag(&r->flags[0], SIP_NAT) & SIP_NAT_ROUTE;
2516 if (r->rtp) {
2517 if (option_debug)
2518 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", natflags ? "On" : "Off");
2519 ast_rtp_setnat(r->rtp, natflags);
2520 ast_rtp_setdtmf(r->rtp, ast_test_flag(&r->flags[0], SIP_DTMF) != SIP_DTMF_INFO);
2521 ast_rtp_setdtmfcompensate(r->rtp, ast_test_flag(&r->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
2523 if (r->vrtp) {
2524 if (option_debug)
2525 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", natflags ? "On" : "Off");
2526 ast_rtp_setnat(r->vrtp, natflags);
2527 ast_rtp_setdtmf(r->vrtp, 0);
2528 ast_rtp_setdtmfcompensate(r->vrtp, 0);
2530 if (r->udptl) {
2531 if (option_debug)
2532 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", natflags ? "On" : "Off");
2533 ast_udptl_setnat(r->udptl, natflags);
2535 ast_string_field_set(r, peername, peer->username);
2536 ast_string_field_set(r, authname, peer->username);
2537 ast_string_field_set(r, username, peer->username);
2538 ast_string_field_set(r, peersecret, peer->secret);
2539 ast_string_field_set(r, peermd5secret, peer->md5secret);
2540 ast_string_field_set(r, tohost, peer->tohost);
2541 ast_string_field_set(r, fullcontact, peer->fullcontact);
2542 if (!r->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
2543 char *tmpcall;
2544 char *c;
2545 tmpcall = ast_strdupa(r->callid);
2546 c = strchr(tmpcall, '@');
2547 if (c) {
2548 *c = '\0';
2549 ast_string_field_build(r, callid, "%s@%s", tmpcall, peer->fromdomain);
2552 if (ast_strlen_zero(r->tohost))
2553 ast_string_field_set(r, tohost, ast_inet_ntoa(r->sa.sin_addr));
2554 if (!ast_strlen_zero(peer->fromdomain))
2555 ast_string_field_set(r, fromdomain, peer->fromdomain);
2556 if (!ast_strlen_zero(peer->fromuser))
2557 ast_string_field_set(r, fromuser, peer->fromuser);
2558 r->maxtime = peer->maxms;
2559 r->callgroup = peer->callgroup;
2560 r->pickupgroup = peer->pickupgroup;
2561 r->allowtransfer = peer->allowtransfer;
2562 /* Set timer T1 to RTT for this peer (if known by qualify=) */
2563 /* Minimum is settable or default to 100 ms */
2564 if (peer->maxms && peer->lastms)
2565 r->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
2566 if ((ast_test_flag(&r->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
2567 (ast_test_flag(&r->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
2568 r->noncodeccapability |= AST_RTP_DTMF;
2569 else
2570 r->noncodeccapability &= ~AST_RTP_DTMF;
2571 ast_string_field_set(r, context, peer->context);
2572 r->rtptimeout = peer->rtptimeout;
2573 r->rtpholdtimeout = peer->rtpholdtimeout;
2574 r->rtpkeepalive = peer->rtpkeepalive;
2575 if (peer->call_limit)
2576 ast_set_flag(&r->flags[0], SIP_CALL_LIMIT);
2577 r->maxcallbitrate = peer->maxcallbitrate;
2579 return 0;
2582 /*! \brief create address structure from peer name
2583 * Or, if peer not found, find it in the global DNS
2584 * returns TRUE (-1) on failure, FALSE on success */
2585 static int create_addr(struct sip_pvt *dialog, const char *opeer)
2587 struct hostent *hp;
2588 struct ast_hostent ahp;
2589 struct sip_peer *p;
2590 char *port;
2591 int portno;
2592 char host[MAXHOSTNAMELEN], *hostn;
2593 char peer[256];
2595 ast_copy_string(peer, opeer, sizeof(peer));
2596 port = strchr(peer, ':');
2597 if (port)
2598 *port++ = '\0';
2599 dialog->sa.sin_family = AF_INET;
2600 dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
2601 p = find_peer(peer, NULL, 1);
2603 if (p) {
2604 int res = create_addr_from_peer(dialog, p);
2605 ASTOBJ_UNREF(p, sip_destroy_peer);
2606 return res;
2608 hostn = peer;
2609 portno = port ? atoi(port) : DEFAULT_SIP_PORT;
2610 if (srvlookup) {
2611 char service[MAXHOSTNAMELEN];
2612 int tportno;
2613 int ret;
2615 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
2616 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
2617 if (ret > 0) {
2618 hostn = host;
2619 portno = tportno;
2622 hp = ast_gethostbyname(hostn, &ahp);
2623 if (!hp) {
2624 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2625 return -1;
2627 ast_string_field_set(dialog, tohost, peer);
2628 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
2629 dialog->sa.sin_port = htons(portno);
2630 dialog->recv = dialog->sa;
2631 return 0;
2634 /*! \brief Scheduled congestion on a call */
2635 static int auto_congest(void *nothing)
2637 struct sip_pvt *p = nothing;
2639 ast_mutex_lock(&p->lock);
2640 p->initid = -1;
2641 if (p->owner) {
2642 /* XXX fails on possible deadlock */
2643 if (!ast_channel_trylock(p->owner)) {
2644 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
2645 append_history(p, "Cong", "Auto-congesting (timer)");
2646 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
2647 ast_channel_unlock(p->owner);
2650 ast_mutex_unlock(&p->lock);
2651 return 0;
2655 /*! \brief Initiate SIP call from PBX
2656 * used from the dial() application */
2657 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2659 int res;
2660 struct sip_pvt *p;
2661 struct varshead *headp;
2662 struct ast_var_t *current;
2663 const char *referer = NULL; /* SIP refererer */
2665 p = ast->tech_pvt;
2666 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2667 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2668 return -1;
2671 /* Check whether there is vxml_url, distinctive ring variables */
2672 headp=&ast->varshead;
2673 AST_LIST_TRAVERSE(headp,current,entries) {
2674 /* Check whether there is a VXML_URL variable */
2675 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2676 p->options->vxml_url = ast_var_value(current);
2677 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
2678 p->options->uri_options = ast_var_value(current);
2679 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
2680 /* Check whether there is a ALERT_INFO variable */
2681 p->options->distinctive_ring = ast_var_value(current);
2682 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2683 /* Check whether there is a variable with a name starting with SIPADDHEADER */
2684 p->options->addsipheaders = 1;
2685 } else if (!strcasecmp(ast_var_name(current),"SIPTRANSFER")) {
2686 /* This is a transfered call */
2687 p->options->transfer = 1;
2688 } else if (!strcasecmp(ast_var_name(current),"SIPTRANSFER_REFERER")) {
2689 /* This is the referer */
2690 referer = ast_var_value(current);
2691 } else if (!strcasecmp(ast_var_name(current),"SIPTRANSFER_REPLACES")) {
2692 /* We're replacing a call. */
2693 p->options->replaces = ast_var_value(current);
2694 } else if (!strcasecmp(ast_var_name(current),"T38CALL")) {
2695 p->t38.state = T38_LOCAL_DIRECT;
2696 if (option_debug)
2697 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
2702 res = 0;
2703 ast_set_flag(&p->flags[0], SIP_OUTGOING);
2705 if (p->options->transfer) {
2706 char buf[BUFSIZ/2];
2708 if (referer) {
2709 if (sipdebug && option_debug > 2)
2710 ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->username, referer);
2711 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
2712 } else {
2713 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
2715 ast_string_field_set(p, cid_name, buf);
2717 if (option_debug)
2718 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
2720 res = update_call_counter(p, INC_CALL_RINGING);
2721 if ( res != -1 ) {
2722 p->callingpres = ast->cid.cid_pres;
2723 p->jointcapability = p->capability;
2724 p->t38.jointcapability = p->t38.capability;
2725 if (option_debug)
2726 ast_log(LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
2727 transmit_invite(p, SIP_INVITE, 1, 2);
2728 if (p->maxtime) {
2729 /* Initialize auto-congest time */
2730 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
2731 } else {
2732 p->initid = ast_sched_add(sched, SIP_TRANS_TIMEOUT, auto_congest, p);
2735 return res;
2738 /*! \brief Destroy registry object
2739 Objects created with the register= statement in static configuration */
2740 static void sip_registry_destroy(struct sip_registry *reg)
2742 /* Really delete */
2743 if (option_debug > 2)
2744 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
2746 if (reg->call) {
2747 /* Clear registry before destroying to ensure
2748 we don't get reentered trying to grab the registry lock */
2749 reg->call->registry = NULL;
2750 if (option_debug > 2)
2751 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
2752 sip_destroy(reg->call);
2754 if (reg->expire > -1)
2755 ast_sched_del(sched, reg->expire);
2756 if (reg->timeout > -1)
2757 ast_sched_del(sched, reg->timeout);
2758 ast_string_field_free_all(reg);
2759 regobjs--;
2760 free(reg);
2764 /*! \brief Execute destruction of SIP dialog structure, release memory */
2765 static void __sip_destroy(struct sip_pvt *p, int lockowner)
2767 struct sip_pvt *cur, *prev = NULL;
2768 struct sip_pkt *cp;
2770 if (sip_debug_test_pvt(p) || option_debug > 2)
2771 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
2773 /* Remove link from peer to subscription of MWI */
2774 if (p->relatedpeer && p->relatedpeer->mwipvt)
2775 p->relatedpeer->mwipvt = NULL;
2777 if (dumphistory)
2778 sip_dump_history(p);
2780 if (p->options)
2781 free(p->options);
2783 if (p->stateid > -1)
2784 ast_extension_state_del(p->stateid, NULL);
2785 if (p->initid > -1)
2786 ast_sched_del(sched, p->initid);
2787 if (p->autokillid > -1)
2788 ast_sched_del(sched, p->autokillid);
2790 if (p->rtp)
2791 ast_rtp_destroy(p->rtp);
2792 if (p->vrtp)
2793 ast_rtp_destroy(p->vrtp);
2794 if (p->udptl)
2795 ast_udptl_destroy(p->udptl);
2796 if (p->refer)
2797 free(p->refer);
2798 if (p->route) {
2799 free_old_route(p->route);
2800 p->route = NULL;
2802 if (p->registry) {
2803 if (p->registry->call == p)
2804 p->registry->call = NULL;
2805 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
2808 /* Unlink us from the owner if we have one */
2809 if (p->owner) {
2810 if (lockowner)
2811 ast_channel_lock(p->owner);
2812 if (option_debug)
2813 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
2814 p->owner->tech_pvt = NULL;
2815 if (lockowner)
2816 ast_channel_unlock(p->owner);
2818 /* Clear history */
2819 if (p->history) {
2820 struct sip_history *hist;
2821 while( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) )
2822 free(hist);
2823 free(p->history);
2824 p->history = NULL;
2827 for (prev = NULL, cur = iflist; cur; prev = cur, cur = cur->next) {
2828 if (cur == p) {
2829 UNLINK(cur, iflist, prev);
2830 break;
2833 if (!cur) {
2834 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
2835 return;
2838 /* remove all current packets in this dialog */
2839 while((cp = p->packets)) {
2840 p->packets = p->packets->next;
2841 if (cp->retransid > -1)
2842 ast_sched_del(sched, cp->retransid);
2843 free(cp);
2845 if (p->chanvars) {
2846 ast_variables_destroy(p->chanvars);
2847 p->chanvars = NULL;
2849 ast_mutex_destroy(&p->lock);
2851 ast_string_field_free_all(p);
2853 free(p);
2856 /*! \brief update_call_counter: Handle call_limit for SIP users
2857 * Setting a call-limit will cause calls above the limit not to be accepted.
2859 * Remember that for a type=friend, there's one limit for the user and
2860 * another for the peer, not a combined call limit.
2861 * This will cause unexpected behaviour in subscriptions, since a "friend"
2862 * is *two* devices in Asterisk, not one.
2864 * Thought: For realtime, we should propably update storage with inuse counter...
2866 * \return 0 if call is ok (no call limit, below treshold)
2867 * -1 on rejection of call
2870 static int update_call_counter(struct sip_pvt *fup, int event)
2872 char name[256];
2873 int *inuse, *call_limit, *inringing = NULL;
2874 int outgoing = ast_test_flag(&fup->flags[0], SIP_OUTGOING);
2875 struct sip_user *u = NULL;
2876 struct sip_peer *p = NULL;
2878 if (option_debug > 2)
2879 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
2880 /* Test if we need to check call limits, in order to avoid
2881 realtime lookups if we do not need it */
2882 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT))
2883 return 0;
2885 ast_copy_string(name, fup->username, sizeof(name));
2887 /* Check the list of users */
2888 if (!outgoing) /* Only check users for incoming calls */
2889 u = find_user(name, 1);
2891 if (u) {
2892 inuse = &u->inUse;
2893 call_limit = &u->call_limit;
2894 p = NULL;
2895 } else {
2896 /* Try to find peer */
2897 if (!p)
2898 p = find_peer(fup->peername, NULL, 1);
2899 if (p) {
2900 inuse = &p->inUse;
2901 call_limit = &p->call_limit;
2902 inringing = &p->inRinging;
2903 ast_copy_string(name, fup->peername, sizeof(name));
2904 } else {
2905 if (option_debug > 1)
2906 ast_log(LOG_DEBUG, "%s is not a local device, no call limit\n", name);
2907 return 0;
2910 switch(event) {
2911 /* incoming and outgoing affects the inUse counter */
2912 case DEC_CALL_LIMIT:
2913 if ( *inuse > 0 ) {
2914 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT))
2915 (*inuse)--;
2916 } else {
2917 *inuse = 0;
2919 if (inringing) {
2920 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
2921 if (*inringing > 0)
2922 (*inringing)--;
2923 else
2924 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", fup->peername);
2925 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
2928 if (option_debug > 1 || sipdebug) {
2929 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
2931 break;
2932 case INC_CALL_RINGING:
2933 case INC_CALL_LIMIT:
2934 if (*call_limit > 0 ) {
2935 if (*inuse >= *call_limit) {
2936 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);
2937 if (u)
2938 ASTOBJ_UNREF(u, sip_destroy_user);
2939 else
2940 ASTOBJ_UNREF(p, sip_destroy_peer);
2941 return -1;
2944 if (inringing && (event == INC_CALL_RINGING)) {
2945 if (!ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
2946 (*inringing)++;
2947 ast_set_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
2950 /* Continue */
2951 (*inuse)++;
2952 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
2953 if (option_debug > 1 || sipdebug) {
2954 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
2956 break;
2957 case DEC_CALL_RINGING:
2958 if (inringing) {
2959 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
2960 if (*inringing > 0)
2961 (*inringing)--;
2962 else
2963 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", p->name);
2964 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
2967 break;
2968 default:
2969 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
2971 if (p)
2972 ast_device_state_changed("SIP/%s", p->name);
2973 if (u)
2974 ASTOBJ_UNREF(u, sip_destroy_user);
2975 else
2976 ASTOBJ_UNREF(p, sip_destroy_peer);
2977 return 0;
2980 /*! \brief Destroy SIP call structure */
2981 static void sip_destroy(struct sip_pvt *p)
2983 ast_mutex_lock(&iflock);
2984 if (option_debug > 2)
2985 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
2986 __sip_destroy(p, 1);
2987 ast_mutex_unlock(&iflock);
2990 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
2991 static int hangup_sip2cause(int cause)
2993 /* Possible values taken from causes.h */
2995 switch(cause) {
2996 case 401: /* Unauthorized */
2997 return AST_CAUSE_CALL_REJECTED;
2998 case 403: /* Not found */
2999 return AST_CAUSE_CALL_REJECTED;
3000 case 404: /* Not found */
3001 return AST_CAUSE_UNALLOCATED;
3002 case 405: /* Method not allowed */
3003 return AST_CAUSE_INTERWORKING;
3004 case 407: /* Proxy authentication required */
3005 return AST_CAUSE_CALL_REJECTED;
3006 case 408: /* No reaction */
3007 return AST_CAUSE_NO_USER_RESPONSE;
3008 case 409: /* Conflict */
3009 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
3010 case 410: /* Gone */
3011 return AST_CAUSE_UNALLOCATED;
3012 case 411: /* Length required */
3013 return AST_CAUSE_INTERWORKING;
3014 case 413: /* Request entity too large */
3015 return AST_CAUSE_INTERWORKING;
3016 case 414: /* Request URI too large */
3017 return AST_CAUSE_INTERWORKING;
3018 case 415: /* Unsupported media type */
3019 return AST_CAUSE_INTERWORKING;
3020 case 420: /* Bad extension */
3021 return AST_CAUSE_NO_ROUTE_DESTINATION;
3022 case 480: /* No answer */
3023 return AST_CAUSE_NO_ANSWER;
3024 case 481: /* No answer */
3025 return AST_CAUSE_INTERWORKING;
3026 case 482: /* Loop detected */
3027 return AST_CAUSE_INTERWORKING;
3028 case 483: /* Too many hops */
3029 return AST_CAUSE_NO_ANSWER;
3030 case 484: /* Address incomplete */
3031 return AST_CAUSE_INVALID_NUMBER_FORMAT;
3032 case 485: /* Ambigous */
3033 return AST_CAUSE_UNALLOCATED;
3034 case 486: /* Busy everywhere */
3035 return AST_CAUSE_BUSY;
3036 case 487: /* Request terminated */
3037 return AST_CAUSE_INTERWORKING;
3038 case 488: /* No codecs approved */
3039 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3040 case 491: /* Request pending */
3041 return AST_CAUSE_INTERWORKING;
3042 case 493: /* Undecipherable */
3043 return AST_CAUSE_INTERWORKING;
3044 case 500: /* Server internal failure */
3045 return AST_CAUSE_FAILURE;
3046 case 501: /* Call rejected */
3047 return AST_CAUSE_FACILITY_REJECTED;
3048 case 502:
3049 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
3050 case 503: /* Service unavailable */
3051 return AST_CAUSE_CONGESTION;
3052 case 504: /* Gateway timeout */
3053 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
3054 case 505: /* SIP version not supported */
3055 return AST_CAUSE_INTERWORKING;
3056 case 600: /* Busy everywhere */
3057 return AST_CAUSE_USER_BUSY;
3058 case 603: /* Decline */
3059 return AST_CAUSE_CALL_REJECTED;
3060 case 604: /* Does not exist anywhere */
3061 return AST_CAUSE_UNALLOCATED;
3062 case 606: /* Not acceptable */
3063 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3064 default:
3065 return AST_CAUSE_NORMAL;
3067 /* Never reached */
3068 return 0;
3071 /*! \brief Convert Asterisk hangup causes to SIP codes
3072 \verbatim
3073 Possible values from causes.h
3074 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
3075 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
3077 In addition to these, a lot of PRI codes is defined in causes.h
3078 ...should we take care of them too ?
3080 Quote RFC 3398
3082 ISUP Cause value SIP response
3083 ---------------- ------------
3084 1 unallocated number 404 Not Found
3085 2 no route to network 404 Not found
3086 3 no route to destination 404 Not found
3087 16 normal call clearing --- (*)
3088 17 user busy 486 Busy here
3089 18 no user responding 408 Request Timeout
3090 19 no answer from the user 480 Temporarily unavailable
3091 20 subscriber absent 480 Temporarily unavailable
3092 21 call rejected 403 Forbidden (+)
3093 22 number changed (w/o diagnostic) 410 Gone
3094 22 number changed (w/ diagnostic) 301 Moved Permanently
3095 23 redirection to new destination 410 Gone
3096 26 non-selected user clearing 404 Not Found (=)
3097 27 destination out of order 502 Bad Gateway
3098 28 address incomplete 484 Address incomplete
3099 29 facility rejected 501 Not implemented
3100 31 normal unspecified 480 Temporarily unavailable
3101 \endverbatim
3103 static const char *hangup_cause2sip(int cause)
3105 switch (cause) {
3106 case AST_CAUSE_UNALLOCATED: /* 1 */
3107 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
3108 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
3109 return "404 Not Found";
3110 case AST_CAUSE_CONGESTION: /* 34 */
3111 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
3112 return "503 Service Unavailable";
3113 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
3114 return "408 Request Timeout";
3115 case AST_CAUSE_NO_ANSWER: /* 19 */
3116 return "480 Temporarily unavailable";
3117 case AST_CAUSE_CALL_REJECTED: /* 21 */
3118 return "403 Forbidden";
3119 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
3120 return "410 Gone";
3121 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
3122 return "480 Temporarily unavailable";
3123 case AST_CAUSE_INVALID_NUMBER_FORMAT:
3124 return "484 Address incomplete";
3125 case AST_CAUSE_USER_BUSY:
3126 return "486 Busy here";
3127 case AST_CAUSE_FAILURE:
3128 return "500 Server internal failure";
3129 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
3130 return "501 Not Implemented";
3131 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
3132 return "503 Service Unavailable";
3133 /* Used in chan_iax2 */
3134 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
3135 return "502 Bad Gateway";
3136 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
3137 return "488 Not Acceptable Here";
3139 case AST_CAUSE_NOTDEFINED:
3140 default:
3141 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
3142 return NULL;
3145 /* Never reached */
3146 return 0;
3150 /*! \brief sip_hangup: Hangup SIP call
3151 * Part of PBX interface, called from ast_hangup */
3152 static int sip_hangup(struct ast_channel *ast)
3154 struct sip_pvt *p = ast->tech_pvt;
3155 int needcancel = FALSE;
3156 int needdestroy = 0;
3157 struct ast_channel *oldowner = ast;
3159 if (!p) {
3160 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
3161 return 0;
3164 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
3165 if (option_debug >3)
3166 ast_log(LOG_DEBUG, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
3167 if (p->autokillid > -1)
3168 sip_cancel_destroy(p);
3169 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
3170 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
3171 ast_clear_flag(&p->flags[0], SIP_NEEDDESTROY);
3172 p->owner->tech_pvt = NULL;
3173 p->owner = NULL; /* Owner will be gone after we return, so take it away */
3174 return 0;
3176 if (option_debug) {
3177 if (ast_test_flag(ast, AST_FLAG_ZOMBIE) && p->refer && option_debug)
3178 ast_log(LOG_DEBUG, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
3179 else
3180 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
3182 if (option_debug && ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
3183 ast_log(LOG_DEBUG, "Hanging up zombie call. Be scared.\n");
3186 ast_mutex_lock(&p->lock);
3187 if (option_debug && sipdebug)
3188 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
3189 update_call_counter(p, DEC_CALL_LIMIT);
3191 /* Determine how to disconnect */
3192 if (p->owner != ast) {
3193 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
3194 ast_mutex_unlock(&p->lock);
3195 return 0;
3197 /* If the call is not UP, we need to send CANCEL instead of BYE */
3198 if (ast->_state != AST_STATE_UP) {
3199 needcancel = TRUE;
3200 if (option_debug > 3)
3201 ast_log(LOG_DEBUG, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
3204 /* Disconnect */
3205 if (p->vad)
3206 ast_dsp_free(p->vad);
3208 p->owner = NULL;
3209 ast->tech_pvt = NULL;
3211 ast_atomic_fetchadd_int(&usecnt, -1);
3212 ast_update_use_count();
3214 /* Do not destroy this pvt until we have timeout or
3215 get an answer to the BYE or INVITE/CANCEL
3216 If we get no answer during retransmit period, drop the call anyway.
3217 (Sorry, mother-in-law, you can't deny a hangup by sending
3218 603 declined to BYE...)
3220 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE))
3221 needdestroy = 1; /* Set destroy flag at end of this function */
3222 else
3223 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
3225 /* Start the process if it's not already started */
3226 if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
3227 if (needcancel) { /* Outgoing call, not up */
3228 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3229 /* stop retransmitting an INVITE that has not received a response */
3230 __sip_pretend_ack(p);
3232 /* if we can't send right now, mark it pending */
3233 if (!ast_test_flag(&p->flags[0], SIP_CAN_BYE)) {
3234 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3235 /* Do we need a timer here if we don't hear from them at all? */
3236 } else {
3237 /* Send a new request: CANCEL */
3238 transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, FALSE);
3239 /* Actually don't destroy us yet, wait for the 487 on our original
3240 INVITE, but do set an autodestruct just in case we never get it. */
3241 needdestroy = 0;
3242 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
3244 if ( p->initid != -1 ) {
3245 /* channel still up - reverse dec of inUse counter
3246 only if the channel is not auto-congested */
3247 update_call_counter(p, INC_CALL_LIMIT);
3249 } else { /* Incoming call, not up */
3250 const char *res;
3251 if (ast->hangupcause && (res = hangup_cause2sip(ast->hangupcause)))
3252 transmit_response_reliable(p, res, &p->initreq);
3253 else
3254 transmit_response_reliable(p, "603 Declined", &p->initreq);
3256 } else { /* Call is in UP state, send BYE */
3257 if (!p->pendinginvite) {
3258 char *audioqos = "";
3259 char *videoqos = "";
3260 if (p->rtp)
3261 audioqos = ast_rtp_get_quality(p->rtp);
3262 if (p->vrtp)
3263 videoqos = ast_rtp_get_quality(p->vrtp);
3264 /* Send a hangup */
3265 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3267 /* Get RTCP quality before end of call */
3268 if (recordhistory) {
3269 if (p->rtp)
3270 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
3271 if (p->vrtp)
3272 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
3274 if (p->rtp && oldowner)
3275 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
3276 if (p->vrtp && oldowner)
3277 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
3278 } else {
3279 /* Note we will need a BYE when this all settles out
3280 but we can't send one while we have "INVITE" outstanding. */
3281 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3282 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
3286 if (needdestroy)
3287 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
3288 ast_mutex_unlock(&p->lock);
3289 return 0;
3292 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
3293 static void try_suggested_sip_codec(struct sip_pvt *p)
3295 int fmt;
3296 const char *codec;
3298 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
3299 if (!codec)
3300 return;
3302 fmt = ast_getformatbyname(codec);
3303 if (fmt) {
3304 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
3305 if (p->jointcapability & fmt) {
3306 p->jointcapability &= fmt;
3307 p->capability &= fmt;
3308 } else
3309 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
3310 } else
3311 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
3312 return;
3315 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
3316 * Part of PBX interface */
3317 static int sip_answer(struct ast_channel *ast)
3319 int res = 0;
3320 struct sip_pvt *p = ast->tech_pvt;
3322 ast_mutex_lock(&p->lock);
3323 if (ast->_state != AST_STATE_UP) {
3324 try_suggested_sip_codec(p);
3326 ast_setstate(ast, AST_STATE_UP);
3327 if (option_debug)
3328 ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name);
3329 if (p->t38.state == T38_PEER_DIRECT) {
3330 p->t38.state = T38_ENABLED;
3331 if (option_debug > 1)
3332 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
3333 res = transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
3334 } else {
3335 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
3338 ast_mutex_unlock(&p->lock);
3339 return res;
3342 /*! \brief Send frame to media channel (rtp) */
3343 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
3345 struct sip_pvt *p = ast->tech_pvt;
3346 int res = 0;
3348 switch (frame->frametype) {
3349 case AST_FRAME_VOICE:
3350 if (!(frame->subclass & ast->nativeformats)) {
3351 char s1[512], s2[512], s3[512];
3352 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
3353 frame->subclass,
3354 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
3355 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
3356 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
3357 ast->readformat,
3358 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
3359 ast->writeformat);
3360 return 0;
3362 if (p) {
3363 ast_mutex_lock(&p->lock);
3364 if (p->rtp) {
3365 /* If channel is not up, activate early media session */
3366 if ((ast->_state != AST_STATE_UP) &&
3367 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3368 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3369 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3370 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3372 p->lastrtptx = time(NULL);
3373 res = ast_rtp_write(p->rtp, frame);
3375 ast_mutex_unlock(&p->lock);
3377 break;
3378 case AST_FRAME_VIDEO:
3379 if (p) {
3380 ast_mutex_lock(&p->lock);
3381 if (p->vrtp) {
3382 /* Activate video early media */
3383 if ((ast->_state != AST_STATE_UP) &&
3384 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3385 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3386 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3387 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3389 p->lastrtptx = time(NULL);
3390 res = ast_rtp_write(p->vrtp, frame);
3392 ast_mutex_unlock(&p->lock);
3394 break;
3395 case AST_FRAME_IMAGE:
3396 return 0;
3397 break;
3398 case AST_FRAME_MODEM:
3399 if (p) {
3400 ast_mutex_lock(&p->lock);
3401 if (p->udptl) {
3402 if ((ast->_state != AST_STATE_UP) &&
3403 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3404 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3405 transmit_response_with_t38_sdp(p, "183 Session Progress", &p->initreq, XMIT_RELIABLE);
3406 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3408 res = ast_udptl_write(p->udptl, frame);
3410 ast_mutex_unlock(&p->lock);
3412 break;
3413 default:
3414 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
3415 return 0;
3418 return res;
3421 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
3422 Basically update any ->owner links */
3423 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
3425 int ret = -1;
3426 struct sip_pvt *p;
3428 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
3429 ast_log(LOG_DEBUG, "New channel is zombie\n");
3430 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
3431 ast_log(LOG_DEBUG, "Old channel is zombie\n");
3433 if (!newchan || !newchan->tech_pvt) {
3434 if (!newchan)
3435 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
3436 else
3437 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
3438 return -1;
3440 p = newchan->tech_pvt;
3442 ast_mutex_lock(&p->lock);
3443 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
3444 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
3445 if (p->owner != oldchan)
3446 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
3447 else {
3448 p->owner = newchan;
3449 ret = 0;
3451 if (option_debug > 2)
3452 ast_log(LOG_DEBUG, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
3454 ast_mutex_unlock(&p->lock);
3455 return ret;
3458 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
3460 struct sip_pvt *p = ast->tech_pvt;
3461 int res = 0;
3463 ast_mutex_lock(&p->lock);
3464 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
3465 case SIP_DTMF_INBAND:
3466 res = -1; /* Tell Asterisk to generate inband indications */
3467 break;
3468 case SIP_DTMF_RFC2833:
3469 if (p->rtp)
3470 ast_rtp_senddigit_begin(p->rtp, digit);
3471 break;
3472 default:
3473 break;
3475 ast_mutex_unlock(&p->lock);
3477 return res;
3480 /*! \brief Send DTMF character on SIP channel
3481 within one call, we're able to transmit in many methods simultaneously */
3482 static int sip_senddigit_end(struct ast_channel *ast, char digit)
3484 struct sip_pvt *p = ast->tech_pvt;
3485 int res = 0;
3487 ast_mutex_lock(&p->lock);
3488 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
3489 case SIP_DTMF_INFO:
3490 transmit_info_with_digit(p, digit);
3491 break;
3492 case SIP_DTMF_RFC2833:
3493 if (p->rtp)
3494 ast_rtp_senddigit_end(p->rtp, digit);
3495 break;
3496 case SIP_DTMF_INBAND:
3497 res = -1; /* Tell Asterisk to stop inband indications */
3498 break;
3500 ast_mutex_unlock(&p->lock);
3502 return res;
3505 /*! \brief Transfer SIP call */
3506 static int sip_transfer(struct ast_channel *ast, const char *dest)
3508 struct sip_pvt *p = ast->tech_pvt;
3509 int res;
3511 ast_mutex_lock(&p->lock);
3512 if (ast->_state == AST_STATE_RING)
3513 res = sip_sipredirect(p, dest);
3514 else
3515 res = transmit_refer(p, dest);
3516 ast_mutex_unlock(&p->lock);
3517 return res;
3520 /*! \brief Play indication to user
3521 * With SIP a lot of indications is sent as messages, letting the device play
3522 the indication - busy signal, congestion etc
3523 \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
3525 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
3527 struct sip_pvt *p = ast->tech_pvt;
3528 int res = 0;
3530 ast_mutex_lock(&p->lock);
3531 switch(condition) {
3532 case AST_CONTROL_RINGING:
3533 if (ast->_state == AST_STATE_RING) {
3534 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
3535 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
3536 /* Send 180 ringing if out-of-band seems reasonable */
3537 transmit_response(p, "180 Ringing", &p->initreq);
3538 ast_set_flag(&p->flags[0], SIP_RINGING);
3539 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
3540 break;
3541 } else {
3542 /* Well, if it's not reasonable, just send in-band */
3545 res = -1;
3546 break;
3547 case AST_CONTROL_BUSY:
3548 if (ast->_state != AST_STATE_UP) {
3549 transmit_response(p, "486 Busy Here", &p->initreq);
3550 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
3551 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
3552 break;
3554 res = -1;
3555 break;
3556 case AST_CONTROL_CONGESTION:
3557 if (ast->_state != AST_STATE_UP) {
3558 transmit_response(p, "503 Service Unavailable", &p->initreq);
3559 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
3560 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
3561 break;
3563 res = -1;
3564 break;
3565 case AST_CONTROL_PROCEEDING:
3566 if ((ast->_state != AST_STATE_UP) &&
3567 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3568 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3569 transmit_response(p, "100 Trying", &p->initreq);
3570 break;
3572 res = -1;
3573 break;
3574 case AST_CONTROL_PROGRESS:
3575 if ((ast->_state != AST_STATE_UP) &&
3576 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3577 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3578 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3579 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3580 break;
3582 res = -1;
3583 break;
3584 case AST_CONTROL_HOLD:
3585 ast_moh_start(ast, data, p->mohinterpret);
3586 break;
3587 case AST_CONTROL_UNHOLD:
3588 ast_moh_stop(ast);
3589 break;
3590 case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
3591 if (p->vrtp && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
3592 transmit_info_with_vidupdate(p);
3593 /* ast_rtcp_send_h261fur(p->vrtp); */
3594 } else
3595 res = -1;
3596 break;
3597 case -1:
3598 res = -1;
3599 break;
3600 default:
3601 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
3602 res = -1;
3603 break;
3605 ast_mutex_unlock(&p->lock);
3606 return res;
3611 /*! \brief Initiate a call in the SIP channel
3612 called from sip_request_call (calls from the pbx ) for outbound channels
3613 and from handle_request_invite for inbound channels
3616 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
3618 struct ast_channel *tmp;
3619 struct ast_variable *v = NULL;
3620 int fmt;
3621 int what;
3622 int needvideo = 0;
3624 ast_mutex_unlock(&i->lock);
3625 /* Don't hold a sip pvt lock while we allocate a channel */
3626 tmp = ast_channel_alloc(1);
3627 ast_mutex_lock(&i->lock);
3628 if (!tmp) {
3629 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
3630 return NULL;
3632 tmp->tech = &sip_tech;
3634 /* Select our native format based on codec preference until we receive
3635 something from another device to the contrary. */
3636 if (i->jointcapability) /* The joint capabilities of us and peer */
3637 what = i->jointcapability;
3638 else if (i->capability) /* Our configured capability for this peer */
3639 what = i->capability;
3640 else
3641 what = global_capability; /* Global codec support */
3643 /* Set the native formats for audio and merge in video */
3644 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
3645 if (option_debug > 2) {
3646 char buf[BUFSIZ];
3647 ast_log(LOG_DEBUG, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, BUFSIZ, tmp->nativeformats));
3648 ast_log(LOG_DEBUG, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, BUFSIZ, i->jointcapability));
3649 ast_log(LOG_DEBUG, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, BUFSIZ, i->capability));
3650 ast_log(LOG_DEBUG, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, BUFSIZ, ast_codec_choose(&i->prefs, what, 1)));
3651 if (i->prefcodec)
3652 ast_log(LOG_DEBUG, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, BUFSIZ, i->prefcodec));
3655 /* XXX Why are we choosing a codec from the native formats?? */
3656 fmt = ast_best_codec(tmp->nativeformats);
3658 /* If we have a prefcodec setting, we have an inbound channel that set a
3659 preferred format for this call. Otherwise, we check the jointcapability
3660 We also check for vrtp. If it's not there, we are not allowed do any video anyway.
3662 if (i->vrtp) {
3663 if (i->prefcodec)
3664 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK; /* Outbound call */
3665 else
3666 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK; /* Inbound call */
3669 if (option_debug > 2) {
3670 if (needvideo)
3671 ast_log(LOG_DEBUG, "This channel can handle video! HOLLYWOOD next!\n");
3672 else
3673 ast_log(LOG_DEBUG, "This channel will not be able to handle video.\n");
3677 if (title)
3678 ast_string_field_build(tmp, name, "SIP/%s-%08x", title, (int)(long) i);
3679 else if (strchr(i->fromdomain,':'))
3680 ast_string_field_build(tmp, name, "SIP/%s-%08x", strchr(i->fromdomain,':') + 1, (int)(long) i);
3681 else
3682 ast_string_field_build(tmp, name, "SIP/%s-%08x", i->fromdomain, (int)(long) i);
3684 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
3685 i->vad = ast_dsp_new();
3686 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
3687 if (global_relaxdtmf)
3688 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
3690 if (i->rtp) {
3691 tmp->fds[0] = ast_rtp_fd(i->rtp);
3692 tmp->fds[1] = ast_rtcp_fd(i->rtp);
3694 if (needvideo && i->vrtp) {
3695 tmp->fds[2] = ast_rtp_fd(i->vrtp);
3696 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
3698 if (i->udptl) {
3699 tmp->fds[5] = ast_udptl_fd(i->udptl);
3701 if (state == AST_STATE_RING)
3702 tmp->rings = 1;
3703 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
3704 tmp->writeformat = fmt;
3705 tmp->rawwriteformat = fmt;
3706 tmp->readformat = fmt;
3707 tmp->rawreadformat = fmt;
3708 tmp->tech_pvt = i;
3710 tmp->callgroup = i->callgroup;
3711 tmp->pickupgroup = i->pickupgroup;
3712 tmp->cid.cid_pres = i->callingpres;
3713 if (!ast_strlen_zero(i->accountcode))
3714 ast_string_field_set(tmp, accountcode, i->accountcode);
3715 if (i->amaflags)
3716 tmp->amaflags = i->amaflags;
3717 if (!ast_strlen_zero(i->language))
3718 ast_string_field_set(tmp, language, i->language);
3719 i->owner = tmp;
3720 ast_atomic_fetchadd_int(&usecnt, 1);
3721 ast_update_use_count();
3722 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
3723 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
3725 /* Don't use ast_set_callerid() here because it will
3726 * generate a NewCallerID event before the NewChannel event */
3727 tmp->cid.cid_num = ast_strdup(i->cid_num);
3728 tmp->cid.cid_ani = ast_strdup(i->cid_num);
3729 tmp->cid.cid_name = ast_strdup(i->cid_name);
3730 if (!ast_strlen_zero(i->rdnis))
3731 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
3733 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
3734 tmp->cid.cid_dnid = ast_strdup(i->exten);
3736 tmp->priority = 1;
3737 if (!ast_strlen_zero(i->uri))
3738 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
3739 if (!ast_strlen_zero(i->domain))
3740 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
3741 if (!ast_strlen_zero(i->useragent))
3742 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
3743 if (!ast_strlen_zero(i->callid))
3744 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
3745 ast_setstate(tmp, state);
3746 if (i->rtp)
3747 ast_jb_configure(tmp, &global_jbconf);
3748 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
3749 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
3750 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
3751 ast_hangup(tmp);
3752 tmp = NULL;
3754 /* Set channel variables for this call from configuration */
3755 for (v = i->chanvars ; v ; v = v->next)
3756 pbx_builtin_setvar_helper(tmp,v->name,v->value);
3758 if (recordhistory)
3759 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
3761 return tmp;
3764 /*! \brief Reads one line of SIP message body */
3765 static char *get_body_by_line(const char *line, const char *name, int nameLen)
3767 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=')
3768 return ast_skip_blanks(line + nameLen + 1);
3770 return "";
3773 /*! \brief Lookup 'name' in the SDP starting
3774 * at the 'start' line. Returns the matching line, and 'start'
3775 * is updated with the next line number.
3777 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
3779 int len = strlen(name);
3781 while (*start < req->sdp_end) {
3782 const char *r = get_body_by_line(req->line[(*start)++], name, len);
3783 if (r[0] != '\0')
3784 return r;
3787 return "";
3790 /*! \brief Get a line from an SDP message body */
3791 static const char *get_sdp(struct sip_request *req, const char *name)
3793 int dummy = 0;
3795 return get_sdp_iterate(&dummy, req, name);
3798 /*! \brief Get a specific line from the message body */
3799 static char *get_body(struct sip_request *req, char *name)
3801 int x;
3802 int len = strlen(name);
3803 char *r;
3805 for (x = 0; x < req->lines; x++) {
3806 r = get_body_by_line(req->line[x], name, len);
3807 if (r[0] != '\0')
3808 return r;
3811 return "";
3814 /*! \brief Find compressed SIP alias */
3815 static const char *find_alias(const char *name, const char *_default)
3817 /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
3818 static const struct cfalias {
3819 char * const fullname;
3820 char * const shortname;
3821 } aliases[] = {
3822 { "Content-Type", "c" },
3823 { "Content-Encoding", "e" },
3824 { "From", "f" },
3825 { "Call-ID", "i" },
3826 { "Contact", "m" },
3827 { "Content-Length", "l" },
3828 { "Subject", "s" },
3829 { "To", "t" },
3830 { "Supported", "k" },
3831 { "Refer-To", "r" },
3832 { "Referred-By", "b" },
3833 { "Allow-Events", "u" },
3834 { "Event", "o" },
3835 { "Via", "v" },
3836 { "Accept-Contact", "a" },
3837 { "Reject-Contact", "j" },
3838 { "Request-Disposition", "d" },
3839 { "Session-Expires", "x" },
3841 int x;
3843 for (x=0; x<sizeof(aliases) / sizeof(aliases[0]); x++)
3844 if (!strcasecmp(aliases[x].fullname, name))
3845 return aliases[x].shortname;
3847 return _default;
3850 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
3852 int pass;
3855 * Technically you can place arbitrary whitespace both before and after the ':' in
3856 * a header, although RFC3261 clearly says you shouldn't before, and place just
3857 * one afterwards. If you shouldn't do it, what absolute idiot decided it was
3858 * a good idea to say you can do it, and if you can do it, why in the hell would.
3859 * you say you shouldn't.
3860 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
3861 * and we always allow spaces after that for compatibility.
3863 for (pass = 0; name && pass < 2;pass++) {
3864 int x, len = strlen(name);
3865 for (x=*start; x<req->headers; x++) {
3866 if (!strncasecmp(req->header[x], name, len)) {
3867 char *r = req->header[x] + len; /* skip name */
3868 if (pedanticsipchecking)
3869 r = ast_skip_blanks(r);
3871 if (*r == ':') {
3872 *start = x+1;
3873 return ast_skip_blanks(r+1);
3877 if (pass == 0) /* Try aliases */
3878 name = find_alias(name, NULL);
3881 /* Don't return NULL, so get_header is always a valid pointer */
3882 return "";
3885 /*! \brief Get header from SIP request */
3886 static const char *get_header(const struct sip_request *req, const char *name)
3888 int start = 0;
3889 return __get_header(req, name, &start);
3892 /*! \brief Read RTP from network */
3893 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
3895 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
3896 struct ast_frame *f;
3898 if (!p->rtp) {
3899 /* We have no RTP allocated for this channel */
3900 return &ast_null_frame;
3903 switch(ast->fdno) {
3904 case 0:
3905 f = ast_rtp_read(p->rtp); /* RTP Audio */
3906 break;
3907 case 1:
3908 f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
3909 break;
3910 case 2:
3911 f = ast_rtp_read(p->vrtp); /* RTP Video */
3912 break;
3913 case 3:
3914 f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
3915 break;
3916 case 5:
3917 f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
3918 break;
3919 default:
3920 f = &ast_null_frame;
3922 /* Don't forward RFC2833 if we're not supposed to */
3923 if (f && (f->frametype == AST_FRAME_DTMF) &&
3924 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833))
3925 return &ast_null_frame;
3927 if (p->owner) {
3928 /* We already hold the channel lock */
3929 if (f->frametype == AST_FRAME_VOICE) {
3930 if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
3931 if (option_debug)
3932 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
3933 p->owner->nativeformats = (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
3934 ast_set_read_format(p->owner, p->owner->readformat);
3935 ast_set_write_format(p->owner, p->owner->writeformat);
3937 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
3938 f = ast_dsp_process(p->owner, p->vad, f);
3939 if (f && f->frametype == AST_FRAME_DTMF) {
3940 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && f->subclass == 'f') {
3941 if (option_debug)
3942 ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
3943 *faxdetect = 1;
3944 } else if (option_debug) {
3945 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
3951 return f;
3954 /*! \brief Read SIP RTP from channel */
3955 static struct ast_frame *sip_read(struct ast_channel *ast)
3957 struct ast_frame *fr;
3958 struct sip_pvt *p = ast->tech_pvt;
3959 int faxdetected = FALSE;
3961 ast_mutex_lock(&p->lock);
3962 fr = sip_rtp_read(ast, p, &faxdetected);
3963 p->lastrtprx = time(NULL);
3965 /* If we are NOT bridged to another channel, and we have detected fax tone we issue T38 re-invite to a peer */
3966 /* 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 */
3967 if (faxdetected && ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && (p->t38.state == T38_DISABLED) && !(ast_bridged_channel(ast))) {
3968 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
3969 if (!p->pendinginvite) {
3970 if (option_debug > 2)
3971 ast_log(LOG_DEBUG, "Sending reinvite on SIP (%s) for T.38 negotiation.\n",ast->name);
3972 p->t38.state = T38_LOCAL_REINVITE;
3973 transmit_reinvite_with_t38_sdp(p);
3974 if (option_debug > 1)
3975 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s", p->t38.state, ast->name);
3977 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
3978 if (option_debug > 2)
3979 ast_log(LOG_DEBUG, "Deferring reinvite on SIP (%s) - it will be re-negotiated for T.38\n", ast->name);
3980 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
3984 ast_mutex_unlock(&p->lock);
3985 return fr;
3989 /*! \brief Generate 32 byte random string for callid's etc */
3990 static char *generate_random_string(char *buf, size_t size)
3992 long val[4];
3993 int x;
3995 for (x=0; x<4; x++)
3996 val[x] = ast_random();
3997 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
3999 return buf;
4002 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
4003 static void build_callid_pvt(struct sip_pvt *pvt)
4005 char buf[33];
4007 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip));
4009 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
4013 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
4014 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
4016 char buf[33];
4018 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
4020 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
4023 /*! \brief Make our SIP dialog tag */
4024 static void make_our_tag(char *tagbuf, size_t len)
4026 snprintf(tagbuf, len, "as%08lx", ast_random());
4029 /*! \brief Allocate SIP_PVT structure and set defaults */
4030 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
4031 int useglobal_nat, const int intended_method)
4033 struct sip_pvt *p;
4035 if (!(p = ast_calloc(1, sizeof(*p))))
4036 return NULL;
4038 if (ast_string_field_init(p, 512)) {
4039 free(p);
4040 return NULL;
4043 ast_mutex_init(&p->lock);
4045 p->method = intended_method;
4046 p->initid = -1;
4047 p->autokillid = -1;
4048 p->subscribed = NONE;
4049 p->stateid = -1;
4050 p->prefs = default_prefs; /* Set default codecs for this call */
4052 if (intended_method != SIP_OPTIONS) /* Peerpoke has it's own system */
4053 p->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
4055 if (sin) {
4056 p->sa = *sin;
4057 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
4058 p->ourip = __ourip;
4059 } else
4060 p->ourip = __ourip;
4062 /* Copy global flags to this PVT at setup. */
4063 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
4064 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
4066 p->branch = ast_random();
4067 make_our_tag(p->tag, sizeof(p->tag));
4068 p->ocseq = INITIAL_CSEQ;
4070 if (sip_methods[intended_method].need_rtp) {
4071 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
4072 /* If the global videosupport flag is on, we always create a RTP interface for video */
4073 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
4074 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
4075 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
4076 p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
4077 if (!p->rtp || (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)) {
4078 ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n",
4079 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video" : "", strerror(errno));
4080 ast_mutex_destroy(&p->lock);
4081 if (p->chanvars) {
4082 ast_variables_destroy(p->chanvars);
4083 p->chanvars = NULL;
4085 free(p);
4086 return NULL;
4088 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_INFO);
4089 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
4090 ast_rtp_settos(p->rtp, global_tos_audio);
4091 if (p->vrtp) {
4092 ast_rtp_settos(p->vrtp, global_tos_video);
4093 ast_rtp_setdtmf(p->vrtp, 0);
4094 ast_rtp_setdtmfcompensate(p->vrtp, 0);
4096 if (p->udptl)
4097 ast_udptl_settos(p->udptl, global_tos_audio);
4098 p->rtptimeout = global_rtptimeout;
4099 p->rtpholdtimeout = global_rtpholdtimeout;
4100 p->rtpkeepalive = global_rtpkeepalive;
4101 p->maxcallbitrate = default_maxcallbitrate;
4104 if (useglobal_nat && sin) {
4105 int natflags;
4106 /* Setup NAT structure according to global settings if we have an address */
4107 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
4108 p->recv = *sin;
4109 natflags = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE;
4110 if (p->rtp)
4111 ast_rtp_setnat(p->rtp, natflags);
4112 if (p->vrtp)
4113 ast_rtp_setnat(p->vrtp, natflags);
4114 if (p->udptl)
4115 ast_udptl_setnat(p->udptl, natflags);
4118 if (p->method != SIP_REGISTER)
4119 ast_string_field_set(p, fromdomain, default_fromdomain);
4120 build_via(p);
4121 if (!callid)
4122 build_callid_pvt(p);
4123 else
4124 ast_string_field_set(p, callid, callid);
4125 /* Assign default music on hold class */
4126 ast_string_field_set(p, mohinterpret, default_mohinterpret);
4127 ast_string_field_set(p, mohsuggest, default_mohsuggest);
4128 p->capability = global_capability;
4129 p->allowtransfer = global_allowtransfer;
4130 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
4131 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
4132 p->noncodeccapability |= AST_RTP_DTMF;
4133 if (p->udptl) {
4134 p->t38.capability = global_t38_capability;
4135 if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY)
4136 p->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
4137 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_FEC)
4138 p->t38.capability |= T38FAX_UDP_EC_FEC;
4139 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_NONE)
4140 p->t38.capability |= T38FAX_UDP_EC_NONE;
4141 p->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
4142 p->t38.jointcapability = p->t38.capability;
4144 ast_string_field_set(p, context, default_context);
4146 /* Add to active dialog list */
4147 ast_mutex_lock(&iflock);
4148 p->next = iflist;
4149 iflist = p;
4150 ast_mutex_unlock(&iflock);
4151 if (option_debug)
4152 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");
4153 return p;
4156 /*! \brief Connect incoming SIP message to current dialog or create new dialog structure
4157 Called by handle_request, sipsock_read */
4158 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
4160 struct sip_pvt *p;
4161 char *tag = ""; /* note, tag is never NULL */
4162 char totag[128];
4163 char fromtag[128];
4164 const char *callid = get_header(req, "Call-ID");
4165 const char *from = get_header(req, "From");
4166 const char *to = get_header(req, "To");
4167 const char *cseq = get_header(req, "Cseq");
4169 if (!callid || !to || !from || !cseq) /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
4170 return NULL; /* Invalid packet */
4172 if (pedanticsipchecking) {
4173 /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
4174 we need more to identify a branch - so we have to check branch, from
4175 and to tags to identify a call leg.
4176 For Asterisk to behave correctly, you need to turn on pedanticsipchecking
4177 in sip.conf
4179 if (gettag(req, "To", totag, sizeof(totag)))
4180 ast_set_flag(req, SIP_PKT_WITH_TOTAG); /* Used in handle_request/response */
4181 gettag(req, "From", fromtag, sizeof(fromtag));
4183 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
4185 if (option_debug > 4 )
4186 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);
4189 ast_mutex_lock(&iflock);
4190 for (p = iflist; p; p = p->next) {
4191 /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
4192 int found = FALSE;
4193 if (req->method == SIP_REGISTER)
4194 found = (!strcmp(p->callid, callid));
4195 else
4196 found = (!strcmp(p->callid, callid) &&
4197 (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ;
4199 if (option_debug > 4)
4200 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);
4202 /* If we get a new request within an existing to-tag - check the to tag as well */
4203 if (pedanticsipchecking && found && req->method != SIP_RESPONSE) { /* SIP Request */
4204 if (p->tag[0] == '\0' && totag[0]) {
4205 /* We have no to tag, but they have. Wrong dialog */
4206 found = FALSE;
4207 } else if (totag[0]) { /* Both have tags, compare them */
4208 if (strcmp(totag, p->tag)) {
4209 found = FALSE; /* This is not our packet */
4212 if (!found && option_debug > 4)
4213 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);
4217 if (found) {
4218 /* Found the call */
4219 ast_mutex_lock(&p->lock);
4220 ast_mutex_unlock(&iflock);
4221 return p;
4224 ast_mutex_unlock(&iflock);
4225 /* Allocate new call */
4226 if ((p = sip_alloc(callid, sin, 1, intended_method)))
4227 ast_mutex_lock(&p->lock);
4228 return p;
4231 /*! \brief Parse register=> line in sip.conf and add to registry */
4232 static int sip_register(char *value, int lineno)
4234 struct sip_registry *reg;
4235 char copy[256];
4236 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
4237 char *porta=NULL;
4238 char *contact=NULL;
4239 char *stringp=NULL;
4241 if (!value)
4242 return -1;
4243 ast_copy_string(copy, value, sizeof(copy));
4244 stringp=copy;
4245 username = stringp;
4246 hostname = strrchr(stringp, '@');
4247 if (hostname)
4248 *hostname++ = '\0';
4249 if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
4250 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
4251 return -1;
4253 stringp = username;
4254 username = strsep(&stringp, ":");
4255 if (username) {
4256 secret = strsep(&stringp, ":");
4257 if (secret)
4258 authuser = strsep(&stringp, ":");
4260 stringp = hostname;
4261 hostname = strsep(&stringp, "/");
4262 if (hostname)
4263 contact = strsep(&stringp, "/");
4264 if (ast_strlen_zero(contact))
4265 contact = "s";
4266 stringp=hostname;
4267 hostname = strsep(&stringp, ":");
4268 porta = strsep(&stringp, ":");
4270 if (porta && !atoi(porta)) {
4271 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
4272 return -1;
4274 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
4275 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
4276 return -1;
4279 if (ast_string_field_init(reg, 256)) {
4280 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
4281 free(reg);
4282 return -1;
4285 regobjs++;
4286 ASTOBJ_INIT(reg);
4287 ast_string_field_set(reg, contact, contact);
4288 if (username)
4289 ast_string_field_set(reg, username, username);
4290 if (hostname)
4291 ast_string_field_set(reg, hostname, hostname);
4292 if (authuser)
4293 ast_string_field_set(reg, authuser, authuser);
4294 if (secret)
4295 ast_string_field_set(reg, secret, secret);
4296 reg->expire = -1;
4297 reg->timeout = -1;
4298 reg->refresh = default_expiry;
4299 reg->portno = porta ? atoi(porta) : 0;
4300 reg->callid_valid = FALSE;
4301 reg->ocseq = INITIAL_CSEQ;
4302 ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
4303 ASTOBJ_UNREF(reg,sip_registry_destroy);
4304 return 0;
4307 /*! \brief Parse multiline SIP headers into one header
4308 This is enabled if pedanticsipchecking is enabled */
4309 static int lws2sws(char *msgbuf, int len)
4311 int h = 0, t = 0;
4312 int lws = 0;
4314 for (; h < len;) {
4315 /* Eliminate all CRs */
4316 if (msgbuf[h] == '\r') {
4317 h++;
4318 continue;
4320 /* Check for end-of-line */
4321 if (msgbuf[h] == '\n') {
4322 /* Check for end-of-message */
4323 if (h + 1 == len)
4324 break;
4325 /* Check for a continuation line */
4326 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
4327 /* Merge continuation line */
4328 h++;
4329 continue;
4331 /* Propagate LF and start new line */
4332 msgbuf[t++] = msgbuf[h++];
4333 lws = 0;
4334 continue;
4336 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
4337 if (lws) {
4338 h++;
4339 continue;
4341 msgbuf[t++] = msgbuf[h++];
4342 lws = 1;
4343 continue;
4345 msgbuf[t++] = msgbuf[h++];
4346 if (lws)
4347 lws = 0;
4349 msgbuf[t] = '\0';
4350 return t;
4353 /*! \brief Parse a SIP message
4354 \note this function is used both on incoming and outgoing packets
4356 static void parse_request(struct sip_request *req)
4358 /* Divide fields by NULL's */
4359 char *c;
4360 int f = 0;
4362 c = req->data;
4364 /* First header starts immediately */
4365 req->header[f] = c;
4366 while(*c) {
4367 if (*c == '\n') {
4368 /* We've got a new header */
4369 *c = 0;
4371 if (sipdebug && option_debug > 3)
4372 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
4373 if (ast_strlen_zero(req->header[f])) {
4374 /* Line by itself means we're now in content */
4375 c++;
4376 break;
4378 if (f >= SIP_MAX_HEADERS - 1) {
4379 ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n");
4380 } else
4381 f++;
4382 req->header[f] = c + 1;
4383 } else if (*c == '\r') {
4384 /* Ignore but eliminate \r's */
4385 *c = 0;
4387 c++;
4389 /* Check for last header */
4390 if (!ast_strlen_zero(req->header[f])) {
4391 if (sipdebug && option_debug > 3)
4392 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
4393 f++;
4395 req->headers = f;
4396 /* Now we process any mime content */
4397 f = 0;
4398 req->line[f] = c;
4399 while(*c) {
4400 if (*c == '\n') {
4401 /* We've got a new line */
4402 *c = 0;
4403 if (sipdebug && option_debug > 3)
4404 ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
4405 if (f >= SIP_MAX_LINES - 1) {
4406 ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n");
4407 } else
4408 f++;
4409 req->line[f] = c + 1;
4410 } else if (*c == '\r') {
4411 /* Ignore and eliminate \r's */
4412 *c = 0;
4414 c++;
4416 /* Check for last line */
4417 if (!ast_strlen_zero(req->line[f]))
4418 f++;
4419 req->lines = f;
4420 if (*c)
4421 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
4422 /* Split up the first line parts */
4423 determine_firstline_parts(req);
4427 \brief Determine whether a SIP message contains an SDP in its body
4428 \param req the SIP request to process
4429 \return 1 if SDP found, 0 if not found
4431 Also updates req->sdp_start and req->sdp_end to indicate where the SDP
4432 lives in the message body.
4434 static int find_sdp(struct sip_request *req)
4436 const char *content_type;
4437 const char *search;
4438 char *boundary;
4439 unsigned int x;
4441 content_type = get_header(req, "Content-Type");
4443 /* if the body contains only SDP, this is easy */
4444 if (!strcasecmp(content_type, "application/sdp")) {
4445 req->sdp_start = 0;
4446 req->sdp_end = req->lines;
4447 return 1;
4450 /* if it's not multipart/mixed, there cannot be an SDP */
4451 if (strncasecmp(content_type, "multipart/mixed", 15))
4452 return 0;
4454 /* if there is no boundary marker, it's invalid */
4455 if (!(search = strcasestr(content_type, ";boundary=")))
4456 return 0;
4458 search += 10;
4460 if (ast_strlen_zero(search))
4461 return 0;
4463 /* make a duplicate of the string, with two extra characters
4464 at the beginning */
4465 boundary = ast_strdupa(search - 2);
4466 boundary[0] = boundary[1] = '-';
4468 /* search for the boundary marker, but stop when there are not enough
4469 lines left for it, the Content-Type header and at least one line of
4470 body */
4471 for (x = 0; x < (req->lines - 2); x++) {
4472 if (!strncasecmp(req->line[x], boundary, strlen(boundary)) &&
4473 !strcasecmp(req->line[x + 1], "Content-Type: application/sdp")) {
4474 req->sdp_start = x + 2;
4475 /* search for the end of the body part */
4476 for ( ; x < req->lines; x++) {
4477 if (!strncasecmp(req->line[x], boundary, strlen(boundary)))
4478 break;
4480 req->sdp_end = x;
4481 return 1;
4485 return 0;
4488 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
4489 If offer is rejected, we will not change any properties of the call
4491 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
4493 const char *m; /* SDP media offer */
4494 const char *c;
4495 const char *a;
4496 char host[258];
4497 int len = -1;
4498 int portno = -1; /*!< RTP Audio port number */
4499 int vportno = -1; /*!< RTP Video port number */
4500 int udptlportno = -1;
4501 int peert38capability = 0;
4502 char s[256];
4503 int old = 0;
4505 /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
4506 int peercapability = 0, peernoncodeccapability = 0;
4507 int vpeercapability = 0, vpeernoncodeccapability = 0;
4508 struct sockaddr_in sin; /*!< media socket address */
4509 struct sockaddr_in vsin; /*!< Video socket address */
4511 const char *codecs;
4512 struct hostent *hp; /*!< RTP Audio host IP */
4513 struct hostent *vhp = NULL; /*!< RTP video host IP */
4514 struct ast_hostent audiohp;
4515 struct ast_hostent videohp;
4516 int codec;
4517 int destiterator = 0;
4518 int iterator;
4519 int sendonly = 0;
4520 int numberofports;
4521 struct ast_channel *bridgepeer = NULL;
4522 struct ast_rtp *newaudiortp, *newvideortp; /* Buffers for codec handling */
4523 int newjointcapability; /* Negotiated capability */
4524 int newpeercapability;
4525 int newnoncodeccapability;
4526 int numberofmediastreams = 0;
4527 int debug = sip_debug_test_pvt(p);
4529 if (!p->rtp) {
4530 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
4531 return -1;
4534 /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
4535 newaudiortp = alloca(ast_rtp_alloc_size());
4536 memset(newaudiortp, 0, ast_rtp_alloc_size());
4537 ast_rtp_pt_clear(newaudiortp);
4539 newvideortp = alloca(ast_rtp_alloc_size());
4540 memset(newvideortp, 0, ast_rtp_alloc_size());
4541 ast_rtp_pt_clear(newvideortp);
4543 /* Update our last rtprx when we receive an SDP, too */
4544 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
4547 /* Try to find first media stream */
4548 m = get_sdp(req, "m");
4549 destiterator = req->sdp_start;
4550 c = get_sdp_iterate(&destiterator, req, "c");
4551 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
4552 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
4553 return -1;
4556 /* Check for IPv4 address (not IPv6 yet) */
4557 if (sscanf(c, "IN IP4 %256s", host) != 1) {
4558 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
4559 return -1;
4562 /* XXX This could block for a long time, and block the main thread! XXX */
4563 hp = ast_gethostbyname(host, &audiohp);
4564 if (!hp) {
4565 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
4566 return -1;
4568 vhp = hp; /* Copy to video address as default too */
4570 iterator = req->sdp_start;
4571 ast_set_flag(&p->flags[0], SIP_NOVIDEO);
4574 /* Find media streams in this SDP offer */
4575 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
4576 int x;
4577 int audio = FALSE;
4579 numberofports = 1;
4580 if ((sscanf(m, "audio %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
4581 (sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
4582 audio = TRUE;
4583 numberofmediastreams++;
4584 /* Found audio stream in this media definition */
4585 portno = x;
4586 /* Scan through the RTP payload types specified in a "m=" line: */
4587 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
4588 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
4589 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
4590 return -1;
4592 if (debug)
4593 ast_verbose("Found RTP audio format %d\n", codec);
4594 ast_rtp_set_m_type(newaudiortp, codec);
4596 } else if ((sscanf(m, "video %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
4597 (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
4598 /* If it is not audio - is it video ? */
4599 ast_clear_flag(&p->flags[0], SIP_NOVIDEO);
4600 numberofmediastreams++;
4601 vportno = x;
4602 /* Scan through the RTP payload types specified in a "m=" line: */
4603 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
4604 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
4605 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
4606 return -1;
4608 if (debug)
4609 ast_verbose("Found RTP video format %d\n", codec);
4610 ast_rtp_set_m_type(newvideortp, codec);
4612 } else if (p->udptl && ((sscanf(m, "image %d udptl t38%n", &x, &len) == 1))) {
4613 if (debug)
4614 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
4615 udptlportno = x;
4616 numberofmediastreams++;
4618 if (p->owner && p->lastinvite) {
4619 p->t38.state = T38_PEER_REINVITE; /* T38 Offered in re-invite from remote party */
4620 if (option_debug > 1)
4621 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>" );
4622 } else {
4623 p->t38.state = T38_PEER_DIRECT; /* T38 Offered directly from peer in first invite */
4624 if (option_debug > 1)
4625 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
4627 } else
4628 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
4629 if (numberofports > 1)
4630 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
4633 /* Check for Media-description-level-address for audio */
4634 c = get_sdp_iterate(&destiterator, req, "c");
4635 if (!ast_strlen_zero(c)) {
4636 if (sscanf(c, "IN IP4 %256s", host) != 1) {
4637 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
4638 } else {
4639 /* XXX This could block for a long time, and block the main thread! XXX */
4640 if (audio) {
4641 if ( !(hp = ast_gethostbyname(host, &audiohp)))
4642 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in secondary c= line, '%s'\n", c);
4643 } else if (!(vhp = ast_gethostbyname(host, &videohp)))
4644 ast_log(LOG_WARNING, "Unable to lookup RTP video host in secondary c= line, '%s'\n", c);
4649 if (portno == -1 && vportno == -1 && udptlportno == -1)
4650 /* No acceptable offer found in SDP - we have no ports */
4651 /* Do not change RTP or VRTP if this is a re-invite */
4652 return -2;
4654 if (numberofmediastreams > 2)
4655 /* We have too many fax, audio and/or video media streams, fail this offer */
4656 return -3;
4658 /* RTP addresses and ports for audio and video */
4659 sin.sin_family = AF_INET;
4660 vsin.sin_family = AF_INET;
4661 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
4662 if (vhp)
4663 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
4665 if (p->rtp) {
4666 if (portno > 0) {
4667 sin.sin_port = htons(portno);
4668 ast_rtp_set_peer(p->rtp, &sin);
4669 if (debug)
4670 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
4671 } else {
4672 ast_rtp_stop(p->rtp);
4673 if (debug)
4674 ast_verbose("Peer doesn't provide audio\n");
4677 /* Setup video port number */
4678 if (vportno != -1)
4679 vsin.sin_port = htons(vportno);
4681 /* Setup UDPTL port number */
4682 if (p->udptl) {
4683 if (udptlportno > 0) {
4684 sin.sin_port = htons(udptlportno);
4685 ast_udptl_set_peer(p->udptl, &sin);
4686 if (debug)
4687 ast_log(LOG_DEBUG,"Peer T.38 UDPTL is at port %s:%d\n",ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
4688 } else {
4689 ast_udptl_stop(p->udptl);
4690 if (debug)
4691 ast_log(LOG_DEBUG, "Peer doesn't provide T.38 UDPTL\n");
4695 /* Next, scan through each "a=rtpmap:" line, noting each
4696 * specified RTP payload type (with corresponding MIME subtype):
4698 /* XXX This needs to be done per media stream, since it's media stream specific */
4699 iterator = req->sdp_start;
4700 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
4701 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
4702 if (option_debug > 1) {
4703 int breakout = FALSE;
4705 /* If we're debugging, check for unsupported sdp options */
4706 if (!strncasecmp(a, "rtcp:", (size_t) 5)) {
4707 if (debug)
4708 ast_verbose("Got unsupported a:rtcp in SDP offer \n");
4709 breakout = TRUE;
4710 } else if (!strncasecmp(a, "fmtp:", (size_t) 5)) {
4711 /* Format parameters: Not supported */
4712 /* Note: This is used for codec parameters, like bitrate for
4713 G722 and video formats for H263 and H264
4714 See RFC2327 for an example */
4715 if (debug)
4716 ast_verbose("Got unsupported a:fmtp in SDP offer \n");
4717 breakout = TRUE;
4718 } else if (!strncasecmp(a, "framerate:", (size_t) 10)) {
4719 /* Video stuff: Not supported */
4720 if (debug)
4721 ast_verbose("Got unsupported a:framerate in SDP offer \n");
4722 breakout = TRUE;
4723 } else if (!strncasecmp(a, "maxprate:", (size_t) 9)) {
4724 /* Video stuff: Not supported */
4725 if (debug)
4726 ast_verbose("Got unsupported a:maxprate in SDP offer \n");
4727 breakout = TRUE;
4728 } else if (!strncasecmp(a, "crypto:", (size_t) 7)) {
4729 /* SRTP stuff, not yet supported */
4730 if (debug)
4731 ast_verbose("Got unsupported a:crypto in SDP offer \n");
4732 breakout = TRUE;
4733 } else if (!strncasecmp(a, "ptime:", (size_t) 6)) {
4734 if (debug)
4735 ast_verbose("Got unsupported a:ptime in SDP offer \n");
4736 breakout = TRUE;
4738 if (breakout) /* We have a match, skip to next header */
4739 continue;
4741 if (!strcasecmp(a, "sendonly")) {
4742 sendonly = 1;
4743 continue;
4744 } else if (!strcasecmp(a, "inactive")) {
4745 sendonly = 2;
4746 continue;
4747 } else if (!strcasecmp(a, "sendrecv")) {
4748 sendonly = 0;
4749 continue;
4750 } else if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2)
4751 continue;
4752 /* We have a rtpmap to handle */
4753 if (debug)
4754 ast_verbose("Found description format %s for ID %d\n", mimeSubtype, codec);
4756 /* Note: should really look at the 'freq' and '#chans' params too */
4757 ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
4758 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0);
4759 if (p->vrtp)
4760 ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0);
4763 if (udptlportno != -1) {
4764 int found = 0, x;
4766 old = 0;
4768 /* Scan trough the a= lines for T38 attributes and set apropriate fileds */
4769 iterator = req->sdp_start;
4770 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
4771 if ((sscanf(a, "T38FaxMaxBuffer:%d", &x) == 1)) {
4772 found = 1;
4773 if (option_debug > 2)
4774 ast_log(LOG_DEBUG,"MaxBufferSize:%d\n",x);
4776 if ((sscanf(a, "T38MaxBitRate:%d", &x) == 1)) {
4777 found = 1;
4778 if (option_debug > 2)
4779 ast_log(LOG_DEBUG,"T38MaxBitRate: %d\n",x);
4780 switch (x) {
4781 case 14400:
4782 peert38capability |= T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
4783 break;
4784 case 12000:
4785 peert38capability |= T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
4786 break;
4787 case 9600:
4788 peert38capability |= T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
4789 break;
4790 case 7200:
4791 peert38capability |= T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
4792 break;
4793 case 4800:
4794 peert38capability |= T38FAX_RATE_4800 | T38FAX_RATE_2400;
4795 break;
4796 case 2400:
4797 peert38capability |= T38FAX_RATE_2400;
4798 break;
4801 if ((sscanf(a, "T38FaxVersion:%d", &x) == 1)) {
4802 found = 1;
4803 if (option_debug > 2)
4804 ast_log(LOG_DEBUG,"FaxVersion: %d\n",x);
4805 if (x == 0)
4806 peert38capability |= T38FAX_VERSION_0;
4807 else if (x == 1)
4808 peert38capability |= T38FAX_VERSION_1;
4810 if ((sscanf(a, "T38FaxMaxDatagram:%d", &x) == 1)) {
4811 found = 1;
4812 if (option_debug > 2)
4813 ast_log(LOG_DEBUG,"FaxMaxDatagram: %d\n",x);
4814 ast_udptl_set_far_max_datagram(p->udptl, x);
4815 ast_udptl_set_local_max_datagram(p->udptl, x);
4817 if ((sscanf(a, "T38FaxFillBitRemoval:%d", &x) == 1)) {
4818 found = 1;
4819 if (option_debug > 2)
4820 ast_log(LOG_DEBUG,"FillBitRemoval: %d\n",x);
4821 if (x == 1)
4822 peert38capability |= T38FAX_FILL_BIT_REMOVAL;
4824 if ((sscanf(a, "T38FaxTranscodingMMR:%d", &x) == 1)) {
4825 found = 1;
4826 if (option_debug > 2)
4827 ast_log(LOG_DEBUG,"Transcoding MMR: %d\n",x);
4828 if (x == 1)
4829 peert38capability |= T38FAX_TRANSCODING_MMR;
4831 if ((sscanf(a, "T38FaxTranscodingJBIG:%d", &x) == 1)) {
4832 found = 1;
4833 if (option_debug > 2)
4834 ast_log(LOG_DEBUG,"Transcoding JBIG: %d\n",x);
4835 if (x == 1)
4836 peert38capability |= T38FAX_TRANSCODING_JBIG;
4838 if ((sscanf(a, "T38FaxRateManagement:%s", s) == 1)) {
4839 found = 1;
4840 if (option_debug > 2)
4841 ast_log(LOG_DEBUG,"RateMangement: %s\n", s);
4842 if (!strcasecmp(s, "localTCF"))
4843 peert38capability |= T38FAX_RATE_MANAGEMENT_LOCAL_TCF;
4844 else if (!strcasecmp(s, "transferredTCF"))
4845 peert38capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
4847 if ((sscanf(a, "T38FaxUdpEC:%s", s) == 1)) {
4848 found = 1;
4849 if (option_debug > 2)
4850 ast_log(LOG_DEBUG,"UDP EC: %s\n", s);
4851 if (!strcasecmp(s, "t38UDPRedundancy")) {
4852 peert38capability |= T38FAX_UDP_EC_REDUNDANCY;
4853 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
4854 } else if (!strcasecmp(s, "t38UDPFEC")) {
4855 peert38capability |= T38FAX_UDP_EC_FEC;
4856 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
4857 } else {
4858 peert38capability |= T38FAX_UDP_EC_NONE;
4859 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
4863 if (found) { /* Some cisco equipment returns nothing beside c= and m= lines in 200 OK T38 SDP */
4864 p->t38.peercapability = peert38capability;
4865 p->t38.jointcapability = (peert38capability & 255); /* Put everything beside supported speeds settings */
4866 peert38capability &= (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400);
4867 p->t38.jointcapability |= (peert38capability & p->t38.capability); /* Put the lower of our's and peer's speed */
4869 if (debug)
4870 ast_log(LOG_DEBUG,"Our T38 capability = (%d), peer T38 capability (%d), joint T38 capability (%d)\n",
4871 p->t38.capability,
4872 p->t38.peercapability,
4873 p->t38.jointcapability);
4874 } else {
4875 p->t38.state = T38_DISABLED;
4876 if (option_debug > 2)
4877 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
4880 /* Now gather all of the codecs that we are asked for: */
4881 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
4882 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
4884 newjointcapability = p->capability & (peercapability | vpeercapability);
4885 newpeercapability = (peercapability | vpeercapability);
4886 newnoncodeccapability = noncodeccapability & peernoncodeccapability;
4889 if (debug) {
4890 /* shame on whoever coded this.... */
4891 char s1[BUFSIZ], s2[BUFSIZ], s3[BUFSIZ], s4[BUFSIZ];
4893 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
4894 ast_getformatname_multiple(s1, BUFSIZ, p->capability),
4895 ast_getformatname_multiple(s2, BUFSIZ, newpeercapability),
4896 ast_getformatname_multiple(s3, BUFSIZ, vpeercapability),
4897 ast_getformatname_multiple(s4, BUFSIZ, newjointcapability));
4899 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
4900 ast_rtp_lookup_mime_multiple(s1, BUFSIZ, noncodeccapability, 0, 0),
4901 ast_rtp_lookup_mime_multiple(s2, BUFSIZ, peernoncodeccapability, 0, 0),
4902 ast_rtp_lookup_mime_multiple(s3, BUFSIZ, newnoncodeccapability, 0, 0));
4904 if (!newjointcapability) {
4905 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
4906 /* Do NOT Change current setting */
4907 return -1;
4910 /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
4911 they are acceptable */
4912 p->jointcapability = newjointcapability; /* Our joint codec profile for this call */
4913 p->peercapability = newpeercapability; /* The other sides capability in latest offer */
4914 p->noncodeccapability = newnoncodeccapability; /* DTMF capabilities */
4916 ast_rtp_pt_copy(p->rtp, newaudiortp);
4917 if (p->vrtp)
4918 ast_rtp_pt_copy(p->vrtp, newvideortp);
4920 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
4921 ast_clear_flag(&p->flags[0], SIP_DTMF);
4922 if (newnoncodeccapability & AST_RTP_DTMF) {
4923 /* XXX Would it be reasonable to drop the DSP at this point? XXX */
4924 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
4925 } else {
4926 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
4930 /* Setup audio port number */
4931 if (p->rtp && sin.sin_port) {
4932 ast_rtp_set_peer(p->rtp, &sin);
4933 if (debug)
4934 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
4937 /* Setup video port number */
4938 if (p->vrtp && vsin.sin_port) {
4939 ast_rtp_set_peer(p->vrtp, &vsin);
4940 if (debug)
4941 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
4944 /* Ok, we're going with this offer */
4945 if (option_debug > 1) {
4946 char buf[BUFSIZ];
4947 ast_log(LOG_DEBUG, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, BUFSIZ, p->jointcapability));
4950 if (!p->owner) /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
4951 return 0;
4953 if (option_debug > 3)
4954 ast_log(LOG_DEBUG, "We have an owner, now see if we need to change this call\n");
4956 if (!(p->owner->nativeformats & p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
4957 if (debug) {
4958 char s1[BUFSIZ], s2[BUFSIZ];
4959 ast_log(LOG_DEBUG, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
4960 ast_getformatname_multiple(s1, BUFSIZ, p->jointcapability),
4961 ast_getformatname_multiple(s2, BUFSIZ, p->owner->nativeformats));
4963 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability);
4964 ast_set_read_format(p->owner, p->owner->readformat);
4965 ast_set_write_format(p->owner, p->owner->writeformat);
4968 /* Turn on/off music on hold if we are holding/unholding */
4969 if ((bridgepeer = ast_bridged_channel(p->owner))) {
4970 if (sin.sin_addr.s_addr && !sendonly) {
4971 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
4972 /* Activate a re-invite */
4973 ast_queue_frame(p->owner, &ast_null_frame);
4974 } else if (!sin.sin_addr.s_addr || sendonly) {
4975 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
4976 S_OR(p->mohsuggest, NULL),
4977 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
4978 if (sendonly)
4979 ast_rtp_stop(p->rtp);
4980 /* RTCP needs to go ahead, even if we're on hold!!! */
4981 /* Activate a re-invite */
4982 ast_queue_frame(p->owner, &ast_null_frame);
4986 /* Manager Hold and Unhold events must be generated, if necessary */
4987 if (sin.sin_addr.s_addr && !sendonly) {
4988 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
4989 append_history(p, "Unhold", "%s", req->data);
4990 if (global_callevents)
4991 manager_event(EVENT_FLAG_CALL, "Unhold",
4992 "Channel: %s\r\n"
4993 "Uniqueid: %s\r\n",
4994 p->owner->name,
4995 p->owner->uniqueid);
4996 sip_peer_hold(p, 0);
4998 ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
4999 } else if (!sin.sin_addr.s_addr || sendonly ) {
5000 /* No address for RTP, we're on hold */
5001 append_history(p, "Hold", "%s", req->data);
5003 if (global_callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
5004 manager_event(EVENT_FLAG_CALL, "Hold",
5005 "Channel: %s\r\n"
5006 "Uniqueid: %s\r\n",
5007 p->owner->name,
5008 p->owner->uniqueid);
5010 if (sendonly == 1) /* One directional hold (sendonly/recvonly) */
5011 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
5012 else if (sendonly == 2) /* Inactive stream */
5013 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
5014 sip_peer_hold(p, 1);
5017 return 0;
5021 /*! \brief Add header to SIP message */
5022 static int add_header(struct sip_request *req, const char *var, const char *value)
5024 int maxlen = sizeof(req->data) - 4 - req->len; /* 4 bytes are for two \r\n ? */
5026 if (req->headers == SIP_MAX_HEADERS) {
5027 ast_log(LOG_WARNING, "Out of SIP header space\n");
5028 return -1;
5031 if (req->lines) {
5032 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
5033 return -1;
5036 if (maxlen <= 0) {
5037 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
5038 return -1;
5041 req->header[req->headers] = req->data + req->len;
5043 if (compactheaders)
5044 var = find_alias(var, var);
5046 snprintf(req->header[req->headers], maxlen, "%s: %s\r\n", var, value);
5047 req->len += strlen(req->header[req->headers]);
5048 req->headers++;
5049 if (req->headers < SIP_MAX_HEADERS)
5050 req->headers++;
5051 else
5052 ast_log(LOG_WARNING, "Out of SIP header space... Will generate broken SIP message\n");
5054 return 0;
5057 /*! \brief Add 'Content-Length' header to SIP message */
5058 static int add_header_contentLength(struct sip_request *req, int len)
5060 char clen[10];
5062 snprintf(clen, sizeof(clen), "%d", len);
5063 return add_header(req, "Content-Length", clen);
5066 /*! \brief Add content (not header) to SIP message */
5067 static int add_line(struct sip_request *req, const char *line)
5069 if (req->lines == SIP_MAX_LINES) {
5070 ast_log(LOG_WARNING, "Out of SIP line space\n");
5071 return -1;
5073 if (!req->lines) {
5074 /* Add extra empty return */
5075 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
5076 req->len += strlen(req->data + req->len);
5078 if (req->len >= sizeof(req->data) - 4) {
5079 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
5080 return -1;
5082 req->line[req->lines] = req->data + req->len;
5083 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
5084 req->len += strlen(req->line[req->lines]);
5085 req->lines++;
5086 return 0;
5089 /*! \brief Copy one header field from one request to another */
5090 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
5092 const char *tmp = get_header(orig, field);
5094 if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
5095 return add_header(req, field, tmp);
5096 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
5097 return -1;
5100 /*! \brief Copy all headers from one request to another */
5101 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
5103 int start = 0;
5104 int copied = 0;
5105 for (;;) {
5106 const char *tmp = __get_header(orig, field, &start);
5108 if (ast_strlen_zero(tmp))
5109 break;
5110 /* Add what we're responding to */
5111 add_header(req, field, tmp);
5112 copied++;
5114 return copied ? 0 : -1;
5117 /*! \brief Copy SIP VIA Headers from the request to the response
5118 \note If the client indicates that it wishes to know the port we received from,
5119 it adds ;rport without an argument to the topmost via header. We need to
5120 add the port number (from our point of view) to that parameter.
5121 We always add ;received=<ip address> to the topmost via header.
5122 Received: RFC 3261, rport RFC 3581 */
5123 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
5125 int copied = 0;
5126 int start = 0;
5128 for (;;) {
5129 char new[256];
5130 const char *oh = __get_header(orig, field, &start);
5132 if (ast_strlen_zero(oh))
5133 break;
5135 if (!copied) { /* Only check for empty rport in topmost via header */
5136 char *rport;
5138 /* Find ;rport; (empty request) */
5139 rport = strstr(oh, ";rport");
5140 if (rport && *(rport+6) == '=')
5141 rport = NULL; /* We already have a parameter to rport */
5143 if (rport && ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) {
5144 /* We need to add received port - rport */
5145 char tmp[256], *end;
5147 ast_copy_string(tmp, oh, sizeof(tmp));
5149 rport = strstr(tmp, ";rport");
5151 if (rport) {
5152 end = strchr(rport + 1, ';');
5153 if (end)
5154 memmove(rport, end, strlen(end) + 1);
5155 else
5156 *rport = '\0';
5159 /* Add rport to first VIA header if requested */
5160 /* Whoo hoo! Now we can indicate port address translation too! Just
5161 another RFC (RFC3581). I'll leave the original comments in for
5162 posterity. */
5163 snprintf(new, sizeof(new), "%s;received=%s;rport=%d",
5164 tmp, ast_inet_ntoa(p->recv.sin_addr),
5165 ntohs(p->recv.sin_port));
5166 } else {
5167 /* We should *always* add a received to the topmost via */
5168 snprintf(new, sizeof(new), "%s;received=%s",
5169 oh, ast_inet_ntoa(p->recv.sin_addr));
5171 oh = new; /* the header to copy */
5172 } /* else add the following via headers untouched */
5173 add_header(req, field, oh);
5174 copied++;
5176 if (!copied) {
5177 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
5178 return -1;
5180 return 0;
5183 /*! \brief Add route header into request per learned route */
5184 static void add_route(struct sip_request *req, struct sip_route *route)
5186 char r[BUFSIZ*2], *p;
5187 int n, rem = sizeof(r);
5189 if (!route)
5190 return;
5192 p = r;
5193 for (;route ; route = route->next) {
5194 n = strlen(route->hop);
5195 if (rem < n+3) /* we need room for ",<route>" */
5196 break;
5197 if (p != r) { /* add a separator after fist route */
5198 *p++ = ',';
5199 --rem;
5201 *p++ = '<';
5202 ast_copy_string(p, route->hop, rem); /* cannot fail */
5203 p += n;
5204 *p++ = '>';
5205 rem -= (n+2);
5207 *p = '\0';
5208 add_header(req, "Route", r);
5211 /*! \brief Set destination from SIP URI */
5212 static void set_destination(struct sip_pvt *p, char *uri)
5214 char *h, *maddr, hostname[256];
5215 int port, hn;
5216 struct hostent *hp;
5217 struct ast_hostent ahp;
5218 int debug=sip_debug_test_pvt(p);
5220 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
5221 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
5223 if (debug)
5224 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
5226 /* Find and parse hostname */
5227 h = strchr(uri, '@');
5228 if (h)
5229 ++h;
5230 else {
5231 h = uri;
5232 if (strncmp(h, "sip:", 4) == 0)
5233 h += 4;
5234 else if (strncmp(h, "sips:", 5) == 0)
5235 h += 5;
5237 hn = strcspn(h, ":;>") + 1;
5238 if (hn > sizeof(hostname))
5239 hn = sizeof(hostname);
5240 ast_copy_string(hostname, h, hn);
5241 /* XXX bug here if string has been trimmed to sizeof(hostname) */
5242 h += hn - 1;
5244 /* Is "port" present? if not default to DEFAULT_SIP_PORT */
5245 if (*h == ':') {
5246 /* Parse port */
5247 ++h;
5248 port = strtol(h, &h, 10);
5250 else
5251 port = DEFAULT_SIP_PORT;
5253 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
5254 maddr = strstr(h, "maddr=");
5255 if (maddr) {
5256 maddr += 6;
5257 hn = strspn(maddr, "0123456789.") + 1;
5258 if (hn > sizeof(hostname))
5259 hn = sizeof(hostname);
5260 ast_copy_string(hostname, maddr, hn);
5263 hp = ast_gethostbyname(hostname, &ahp);
5264 if (hp == NULL) {
5265 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
5266 return;
5268 p->sa.sin_family = AF_INET;
5269 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
5270 p->sa.sin_port = htons(port);
5271 if (debug)
5272 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
5275 /*! \brief Initialize SIP response, based on SIP request */
5276 static int init_resp(struct sip_request *resp, const char *msg)
5278 /* Initialize a response */
5279 memset(resp, 0, sizeof(*resp));
5280 resp->method = SIP_RESPONSE;
5281 resp->header[0] = resp->data;
5282 snprintf(resp->header[0], sizeof(resp->data), "SIP/2.0 %s\r\n", msg);
5283 resp->len = strlen(resp->header[0]);
5284 resp->headers++;
5285 return 0;
5288 /*! \brief Initialize SIP request */
5289 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
5291 /* Initialize a request */
5292 memset(req, 0, sizeof(*req));
5293 req->method = sipmethod;
5294 req->header[0] = req->data;
5295 snprintf(req->header[0], sizeof(req->data), "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
5296 req->len = strlen(req->header[0]);
5297 req->headers++;
5298 return 0;
5302 /*! \brief Prepare SIP response packet */
5303 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
5305 char newto[256];
5306 const char *ot;
5308 init_resp(resp, msg);
5309 copy_via_headers(p, resp, req, "Via");
5310 if (msg[0] == '2')
5311 copy_all_header(resp, req, "Record-Route");
5312 copy_header(resp, req, "From");
5313 ot = get_header(req, "To");
5314 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
5315 /* Add the proper tag if we don't have it already. If they have specified
5316 their tag, use it. Otherwise, use our own tag */
5317 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
5318 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
5319 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
5320 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
5321 else
5322 ast_copy_string(newto, ot, sizeof(newto));
5323 ot = newto;
5325 add_header(resp, "To", ot);
5326 copy_header(resp, req, "Call-ID");
5327 copy_header(resp, req, "CSeq");
5328 add_header(resp, "User-Agent", global_useragent);
5329 add_header(resp, "Allow", ALLOWED_METHODS);
5330 add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
5331 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
5332 /* For registration responses, we also need expiry and
5333 contact info */
5334 char tmp[256];
5336 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
5337 add_header(resp, "Expires", tmp);
5338 if (p->expiry) { /* Only add contact if we have an expiry time */
5339 char contact[256];
5340 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
5341 add_header(resp, "Contact", contact); /* Not when we unregister */
5343 } else if (p->our_contact[0]) {
5344 add_header(resp, "Contact", p->our_contact);
5346 return 0;
5349 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
5350 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
5352 struct sip_request *orig = &p->initreq;
5353 char stripped[80];
5354 char tmp[80];
5355 char newto[256];
5356 const char *c;
5357 const char *ot, *of;
5358 int is_strict = FALSE; /*!< Strict routing flag */
5360 memset(req, 0, sizeof(struct sip_request));
5362 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
5364 if (!seqno) {
5365 p->ocseq++;
5366 seqno = p->ocseq;
5369 if (newbranch) {
5370 p->branch ^= ast_random();
5371 build_via(p);
5374 /* Check for strict or loose router */
5375 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop,";lr") == NULL) {
5376 is_strict = TRUE;
5377 if (sipdebug)
5378 ast_log(LOG_DEBUG, "Strict routing enforced for session %s\n", p->callid);
5381 if (sipmethod == SIP_CANCEL)
5382 c = p->initreq.rlPart2; /* Use original URI */
5383 else if (sipmethod == SIP_ACK) {
5384 /* Use URI from Contact: in 200 OK (if INVITE)
5385 (we only have the contacturi on INVITEs) */
5386 if (!ast_strlen_zero(p->okcontacturi))
5387 c = is_strict ? p->route->hop : p->okcontacturi;
5388 else
5389 c = p->initreq.rlPart2;
5390 } else if (!ast_strlen_zero(p->okcontacturi))
5391 c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
5392 else if (!ast_strlen_zero(p->uri))
5393 c = p->uri;
5394 else {
5395 char *n;
5396 /* We have no URI, use To: or From: header as URI (depending on direction) */
5397 ast_copy_string(stripped, get_header(orig, (ast_test_flag(&p->flags[0], SIP_OUTGOING)) ? "To" : "From"),
5398 sizeof(stripped));
5399 n = get_in_brackets(stripped);
5400 c = strsep(&n, ";"); /* trim ; and beyond */
5402 init_req(req, sipmethod, c);
5404 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
5406 add_header(req, "Via", p->via);
5407 if (p->route) {
5408 set_destination(p, p->route->hop);
5409 add_route(req, is_strict ? p->route->next : p->route);
5412 ot = get_header(orig, "To");
5413 of = get_header(orig, "From");
5415 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
5416 as our original request, including tag (or presumably lack thereof) */
5417 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
5418 /* Add the proper tag if we don't have it already. If they have specified
5419 their tag, use it. Otherwise, use our own tag */
5420 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_strlen_zero(p->theirtag))
5421 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
5422 else if (!ast_test_flag(&p->flags[0], SIP_OUTGOING))
5423 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
5424 else
5425 snprintf(newto, sizeof(newto), "%s", ot);
5426 ot = newto;
5429 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
5430 add_header(req, "From", of);
5431 add_header(req, "To", ot);
5432 } else {
5433 add_header(req, "From", ot);
5434 add_header(req, "To", of);
5436 add_header(req, "Contact", p->our_contact);
5437 copy_header(req, orig, "Call-ID");
5438 add_header(req, "CSeq", tmp);
5440 add_header(req, "User-Agent", global_useragent);
5441 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
5443 if (!ast_strlen_zero(p->rpid))
5444 add_header(req, "Remote-Party-ID", p->rpid);
5446 return 0;
5449 /*! \brief Base transmit response function */
5450 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
5452 struct sip_request resp;
5453 int seqno = 0;
5455 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
5456 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
5457 return -1;
5459 respprep(&resp, p, msg, req);
5460 add_header_contentLength(&resp, 0);
5461 /* If we are cancelling an incoming invite for some reason, add information
5462 about the reason why we are doing this in clear text */
5463 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
5464 char buf[10];
5466 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
5467 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
5468 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
5470 return send_response(p, &resp, reliable, seqno);
5473 /*! \brief Transmit response, no retransmits */
5474 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
5476 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
5479 /*! \brief Transmit response, no retransmits */
5480 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
5482 struct sip_request resp;
5483 respprep(&resp, p, msg, req);
5484 append_date(&resp);
5485 add_header(&resp, "Unsupported", unsupported);
5486 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
5489 /*! \brief Transmit response, Make sure you get an ACK
5490 This is only used for responses to INVITEs, where we need to make sure we get an ACK
5492 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
5494 return __transmit_response(p, msg, req, XMIT_CRITICAL);
5497 /*! \brief Append date to SIP message */
5498 static void append_date(struct sip_request *req)
5500 char tmpdat[256];
5501 struct tm tm;
5502 time_t t = time(NULL);
5504 gmtime_r(&t, &tm);
5505 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
5506 add_header(req, "Date", tmpdat);
5509 /*! \brief Append date and content length before transmitting response */
5510 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
5512 struct sip_request resp;
5513 respprep(&resp, p, msg, req);
5514 append_date(&resp);
5515 add_header_contentLength(&resp, 0);
5516 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
5519 /*! \brief Append Accept header, content length before transmitting response */
5520 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
5522 struct sip_request resp;
5523 respprep(&resp, p, msg, req);
5524 add_header(&resp, "Accept", "application/sdp");
5525 add_header_contentLength(&resp, 0);
5526 return send_response(p, &resp, reliable, 0);
5529 /*! \brief Respond with authorization request */
5530 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)
5532 struct sip_request resp;
5533 char tmp[512];
5534 int seqno = 0;
5536 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
5537 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
5538 return -1;
5540 /* Stale means that they sent us correct authentication, but
5541 based it on an old challenge (nonce) */
5542 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
5543 respprep(&resp, p, msg, req);
5544 add_header(&resp, header, tmp);
5545 add_header_contentLength(&resp, 0);
5546 return send_response(p, &resp, reliable, seqno);
5549 /*! \brief Add text body to SIP message */
5550 static int add_text(struct sip_request *req, const char *text)
5552 /* XXX Convert \n's to \r\n's XXX */
5553 add_header(req, "Content-Type", "text/plain");
5554 add_header_contentLength(req, strlen(text));
5555 add_line(req, text);
5556 return 0;
5559 /*! \brief Add DTMF INFO tone to sip message */
5560 /* Always adds default duration 250 ms, regardless of what came in over the line */
5561 static int add_digit(struct sip_request *req, char digit)
5563 char tmp[256];
5565 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
5566 add_header(req, "Content-Type", "application/dtmf-relay");
5567 add_header_contentLength(req, strlen(tmp));
5568 add_line(req, tmp);
5569 return 0;
5572 /*! \brief add XML encoded media control with update */
5573 /*! \note XML: The only way to turn 0 bits of information into a few hundred. */
5574 static int add_vidupdate(struct sip_request *req)
5576 const char *xml_is_a_huge_waste_of_space =
5577 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
5578 " <media_control>\r\n"
5579 " <vc_primitive>\r\n"
5580 " <to_encoder>\r\n"
5581 " <picture_fast_update>\r\n"
5582 " </picture_fast_update>\r\n"
5583 " </to_encoder>\r\n"
5584 " </vc_primitive>\r\n"
5585 " </media_control>\r\n";
5586 add_header(req, "Content-Type", "application/media_control+xml");
5587 add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
5588 add_line(req, xml_is_a_huge_waste_of_space);
5589 return 0;
5592 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
5593 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
5594 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
5595 int debug)
5597 int rtp_code;
5599 if (debug)
5600 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
5601 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
5602 return;
5604 ast_build_string(m_buf, m_size, " %d", rtp_code);
5605 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
5606 ast_rtp_lookup_mime_subtype(1, codec,
5607 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
5608 sample_rate);
5609 if (codec == AST_FORMAT_G729A) {
5610 /* Indicate that we don't support VAD (G.729 annex B) */
5611 ast_build_string(a_buf, a_size, "a=fmtp:%d annexb=no\r\n", rtp_code);
5612 } else if (codec == AST_FORMAT_ILBC) {
5613 /* Add information about us using only 20 ms packetization */
5614 ast_build_string(a_buf, a_size, "a=fmtp:%d mode=20\r\n", rtp_code);
5619 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
5620 static int t38_get_rate(int t38cap)
5622 int maxrate = (t38cap & (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400));
5624 if (maxrate & T38FAX_RATE_14400) {
5625 if (option_debug > 1)
5626 ast_log(LOG_DEBUG, "T38MaxFaxRate 14400 found\n");
5627 return 14400;
5628 } else if (maxrate & T38FAX_RATE_12000) {
5629 if (option_debug > 1)
5630 ast_log(LOG_DEBUG, "T38MaxFaxRate 12000 found\n");
5631 return 12000;
5632 } else if (maxrate & T38FAX_RATE_9600) {
5633 if (option_debug > 1)
5634 ast_log(LOG_DEBUG, "T38MaxFaxRate 9600 found\n");
5635 return 9600;
5636 } else if (maxrate & T38FAX_RATE_7200) {
5637 if (option_debug > 1)
5638 ast_log(LOG_DEBUG, "T38MaxFaxRate 7200 found\n");
5639 return 7200;
5640 } else if (maxrate & T38FAX_RATE_4800) {
5641 if (option_debug > 1)
5642 ast_log(LOG_DEBUG, "T38MaxFaxRate 4800 found\n");
5643 return 4800;
5644 } else if (maxrate & T38FAX_RATE_2400) {
5645 if (option_debug > 1)
5646 ast_log(LOG_DEBUG, "T38MaxFaxRate 2400 found\n");
5647 return 2400;
5648 } else {
5649 if (option_debug > 1)
5650 ast_log(LOG_DEBUG, "Strange, T38MaxFaxRate NOT found in peers T38 SDP.\n");
5651 return 0;
5655 /*! \brief Add T.38 Session Description Protocol message */
5656 static int add_t38_sdp(struct sip_request *resp, struct sip_pvt *p)
5658 int len = 0;
5659 int x = 0;
5660 struct sockaddr_in udptlsin;
5661 char v[256] = "";
5662 char s[256] = "";
5663 char o[256] = "";
5664 char c[256] = "";
5665 char t[256] = "";
5666 char m_modem[256];
5667 char a_modem[1024];
5668 char *m_modem_next = m_modem;
5669 size_t m_modem_left = sizeof(m_modem);
5670 char *a_modem_next = a_modem;
5671 size_t a_modem_left = sizeof(a_modem);
5672 struct sockaddr_in udptldest = { 0, };
5673 int debug;
5675 debug = sip_debug_test_pvt(p);
5676 len = 0;
5677 if (!p->udptl) {
5678 ast_log(LOG_WARNING, "No way to add SDP without an UDPTL structure\n");
5679 return -1;
5682 if (!p->sessionid) {
5683 p->sessionid = getpid();
5684 p->sessionversion = p->sessionid;
5685 } else
5686 p->sessionversion++;
5688 /* Our T.38 end is */
5689 ast_udptl_get_us(p->udptl, &udptlsin);
5691 /* Determine T.38 UDPTL destination */
5692 if (p->udptlredirip.sin_addr.s_addr) {
5693 udptldest.sin_port = p->udptlredirip.sin_port;
5694 udptldest.sin_addr = p->udptlredirip.sin_addr;
5695 } else {
5696 udptldest.sin_addr = p->ourip;
5697 udptldest.sin_port = udptlsin.sin_port;
5700 if (debug) {
5701 ast_log(LOG_DEBUG, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(udptlsin.sin_port));
5704 /* We break with the "recommendation" and send our IP, in order that our
5705 peer doesn't have to ast_gethostbyname() us */
5707 if (debug) {
5708 ast_log(LOG_DEBUG, "Our T38 capability (%d), peer T38 capability (%d), joint capability (%d)\n",
5709 p->t38.capability,
5710 p->t38.peercapability,
5711 p->t38.jointcapability);
5713 snprintf(v, sizeof(v), "v=0\r\n");
5714 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(udptldest.sin_addr));
5715 snprintf(s, sizeof(s), "s=session\r\n");
5716 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(udptldest.sin_addr));
5717 snprintf(t, sizeof(t), "t=0 0\r\n");
5718 ast_build_string(&m_modem_next, &m_modem_left, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
5720 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_0)
5721 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:0\r\n");
5722 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_1)
5723 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:1\r\n");
5724 if ((x = t38_get_rate(p->t38.jointcapability)))
5725 ast_build_string(&a_modem_next, &a_modem_left, "a=T38MaxBitRate:%d\r\n",x);
5726 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxFillBitRemoval:%d\r\n", (p->t38.jointcapability & T38FAX_FILL_BIT_REMOVAL) ? 1 : 0);
5727 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingMMR:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_MMR) ? 1 : 0);
5728 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingJBIG:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_JBIG) ? 1 : 0);
5729 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxRateManagement:%s\r\n", (p->t38.jointcapability & T38FAX_RATE_MANAGEMENT_LOCAL_TCF) ? "localTCF" : "transferredTCF");
5730 x = ast_udptl_get_local_max_datagram(p->udptl);
5731 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxBuffer:%d\r\n",x);
5732 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxDatagram:%d\r\n",x);
5733 if (p->t38.jointcapability != T38FAX_UDP_EC_NONE)
5734 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxUdpEC:%s\r\n", (p->t38.jointcapability & T38FAX_UDP_EC_REDUNDANCY) ? "t38UDPRedundancy" : "t38UDPFEC");
5735 if (p->udptl)
5736 len = strlen(m_modem) + strlen(a_modem);
5737 add_header(resp, "Content-Type", "application/sdp");
5738 add_header_contentLength(resp, len);
5739 add_line(resp, v);
5740 add_line(resp, o);
5741 add_line(resp, s);
5742 add_line(resp, c);
5743 add_line(resp, t);
5744 add_line(resp, m_modem);
5745 add_line(resp, a_modem);
5747 /* Update lastrtprx when we send our SDP */
5748 p->lastrtprx = p->lastrtptx = time(NULL);
5750 return 0;
5754 /*! \brief Add RFC 2833 DTMF offer to SDP */
5755 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
5756 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
5757 int debug)
5759 int rtp_code;
5761 if (debug)
5762 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
5763 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
5764 return;
5766 ast_build_string(m_buf, m_size, " %d", rtp_code);
5767 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
5768 ast_rtp_lookup_mime_subtype(0, format, 0),
5769 sample_rate);
5770 if (format == AST_RTP_DTMF)
5771 /* Indicate we support DTMF and FLASH... */
5772 ast_build_string(a_buf, a_size, "a=fmtp:%d 0-16\r\n", rtp_code);
5775 /*! \brief Add Session Description Protocol message */
5776 static int add_sdp(struct sip_request *resp, struct sip_pvt *p)
5778 int len = 0;
5779 int alreadysent = 0;
5781 struct sockaddr_in sin;
5782 struct sockaddr_in vsin;
5783 struct sockaddr_in dest;
5784 struct sockaddr_in vdest = { 0, };
5786 /* SDP fields */
5787 char *version = "v=0\r\n"; /* Protocol version */
5788 char *subject = "s=session\r\n"; /* Subject of the session */
5789 char owner[256]; /* Session owner/creator */
5790 char connection[256]; /* Connection data */
5791 char *stime = "t=0 0\r\n"; /* Time the session is active */
5792 char bandwidth[256] = ""; /* Max bitrate */
5793 char *hold;
5794 char m_audio[256]; /* Media declaration line for audio */
5795 char m_video[256]; /* Media declaration line for video */
5796 char a_audio[1024]; /* Attributes for audio */
5797 char a_video[1024]; /* Attributes for video */
5798 char *m_audio_next = m_audio;
5799 char *m_video_next = m_video;
5800 size_t m_audio_left = sizeof(m_audio);
5801 size_t m_video_left = sizeof(m_video);
5802 char *a_audio_next = a_audio;
5803 char *a_video_next = a_video;
5804 size_t a_audio_left = sizeof(a_audio);
5805 size_t a_video_left = sizeof(a_video);
5807 int x;
5808 int capability;
5809 int needvideo = FALSE;
5810 int debug = sip_debug_test_pvt(p);
5812 m_video[0] = '\0'; /* Reset the video media string if it's not needed */
5814 if (!p->rtp) {
5815 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
5816 return -1;
5819 /* Set RTP Session ID and version */
5820 if (!p->sessionid) {
5821 p->sessionid = getpid();
5822 p->sessionversion = p->sessionid;
5823 } else
5824 p->sessionversion++;
5826 /* Get our addresses */
5827 ast_rtp_get_us(p->rtp, &sin);
5828 if (p->vrtp)
5829 ast_rtp_get_us(p->vrtp, &vsin);
5831 /* Is this a re-invite to move the media out, then use the original offer from caller */
5832 if (p->redirip.sin_addr.s_addr) {
5833 dest.sin_port = p->redirip.sin_port;
5834 dest.sin_addr = p->redirip.sin_addr;
5835 if (p->redircodecs)
5836 capability = p->redircodecs;
5837 } else {
5838 dest.sin_addr = p->ourip;
5839 dest.sin_port = sin.sin_port;
5842 /* Ok, let's start working with codec selection here */
5843 capability = p->jointcapability;
5845 if (option_debug > 1) {
5846 char codecbuf[BUFSIZ];
5847 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");
5848 ast_log(LOG_DEBUG, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
5851 if ((ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_RTP))) {
5852 ast_build_string(&m_audio_next, &m_audio_left, " %d", 191);
5853 ast_build_string(&a_audio_next, &a_audio_left, "a=rtpmap:%d %s/%d\r\n", 191, "t38", 8000);
5856 /* Check if we need video in this call */
5857 if((capability & AST_FORMAT_VIDEO_MASK) && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
5858 if (p->vrtp) {
5859 needvideo = TRUE;
5860 if (option_debug > 1)
5861 ast_log(LOG_DEBUG, "This call needs video offers! \n");
5862 } else if (option_debug > 1)
5863 ast_log(LOG_DEBUG, "This call needs video offers, but there's no video support enabled ! \n");
5867 /* Ok, we need video. Let's add what we need for video and set codecs.
5868 Video is handled differently than audio since we can not transcode. */
5869 if (needvideo) {
5871 /* Determine video destination */
5872 if (p->vredirip.sin_addr.s_addr) {
5873 vdest.sin_addr = p->vredirip.sin_addr;
5874 vdest.sin_port = p->vredirip.sin_port;
5875 } else {
5876 vdest.sin_addr = p->ourip;
5877 vdest.sin_port = vsin.sin_port;
5879 ast_build_string(&m_video_next, &m_video_left, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
5881 /* Build max bitrate string */
5882 if (p->maxcallbitrate)
5883 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
5884 if (debug)
5885 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(vsin.sin_port));
5887 /* For video, we can't negotiate video offers. Let's compare the incoming call with what we got. */
5888 if (p->prefcodec) {
5889 int videocapability = (capability & p->prefcodec) & AST_FORMAT_VIDEO_MASK; /* Outbound call */
5891 /*! \todo XXX We need to select one codec, not many, since there's no transcoding */
5893 /* Now, merge this video capability into capability while removing unsupported codecs */
5894 if (!videocapability) {
5895 needvideo = FALSE;
5896 if (option_debug > 2)
5897 ast_log(LOG_DEBUG, "** No compatible video codecs... Disabling video.\n");
5900 /* Replace video capabilities with the new videocapability */
5901 capability = (capability & AST_FORMAT_AUDIO_MASK) | videocapability;
5903 if (option_debug > 4) {
5904 char codecbuf[BUFSIZ];
5905 if (videocapability)
5906 ast_log(LOG_DEBUG, "** Our video codec selection is: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), videocapability));
5907 ast_log(LOG_DEBUG, "** Capability now set to : %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability));
5911 if (debug)
5912 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(sin.sin_port));
5914 /* Start building generic SDP headers */
5916 /* We break with the "recommendation" and send our IP, in order that our
5917 peer doesn't have to ast_gethostbyname() us */
5919 snprintf(owner, sizeof(owner), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
5920 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
5921 ast_build_string(&m_audio_next, &m_audio_left, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
5923 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR))
5924 hold = "a=recvonly\r\n";
5925 else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE))
5926 hold = "a=inactive\r\n";
5927 else
5928 hold = "a=sendrecv\r\n";
5930 /* Now, start adding audio codecs. These are added in this order:
5931 - First what was requested by the calling channel
5932 - Then preferences in order from sip.conf device config for this peer/user
5933 - Then other codecs in capabilities, including video
5936 /* Prefer the audio codec we were requested to use, first, no matter what
5937 Note that p->prefcodec can include video codecs, so mask them out
5939 if (capability & p->prefcodec) {
5940 add_codec_to_sdp(p, p->prefcodec & AST_FORMAT_AUDIO_MASK, 8000,
5941 &m_audio_next, &m_audio_left,
5942 &a_audio_next, &a_audio_left,
5943 debug);
5944 alreadysent |= p->prefcodec & AST_FORMAT_AUDIO_MASK;
5948 /* Start by sending our preferred audio codecs */
5949 for (x = 0; x < 32; x++) {
5950 int pref_codec;
5952 if (!(pref_codec = ast_codec_pref_index(&p->prefs, x)))
5953 break;
5955 if (!(capability & pref_codec))
5956 continue;
5958 if (alreadysent & pref_codec)
5959 continue;
5961 add_codec_to_sdp(p, pref_codec, 8000,
5962 &m_audio_next, &m_audio_left,
5963 &a_audio_next, &a_audio_left,
5964 debug);
5965 alreadysent |= pref_codec;
5968 /* Now send any other common audio and video codecs, and non-codec formats: */
5969 for (x = 1; x <= (needvideo ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
5970 if (!(capability & x)) /* Codec not requested */
5971 continue;
5973 if (alreadysent & x) /* Already added to SDP */
5974 continue;
5976 if (x <= AST_FORMAT_MAX_AUDIO)
5977 add_codec_to_sdp(p, x, 8000,
5978 &m_audio_next, &m_audio_left,
5979 &a_audio_next, &a_audio_left,
5980 debug);
5981 else
5982 add_codec_to_sdp(p, x, 90000,
5983 &m_video_next, &m_video_left,
5984 &a_video_next, &a_video_left,
5985 debug);
5988 /* Now add DTMF RFC2833 telephony-event as a codec */
5989 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
5990 if (!(p->noncodeccapability & x))
5991 continue;
5993 add_noncodec_to_sdp(p, x, 8000,
5994 &m_audio_next, &m_audio_left,
5995 &a_audio_next, &a_audio_left,
5996 debug);
5999 if (option_debug > 2)
6000 ast_log(LOG_DEBUG, "-- Done with adding codecs to SDP\n");
6002 if(!ast_internal_timing_enabled(p->owner))
6003 ast_build_string(&a_audio_next, &a_audio_left, "a=silenceSupp:off - - - -\r\n");
6005 if ((m_audio_left < 2) || (m_video_left < 2) || (a_audio_left == 0) || (a_video_left == 0))
6006 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
6008 ast_build_string(&m_audio_next, &m_audio_left, "\r\n");
6009 if (needvideo)
6010 ast_build_string(&m_video_next, &m_video_left, "\r\n");
6012 len = strlen(version) + strlen(subject) + strlen(owner) + strlen(connection) + strlen(stime) + strlen(m_audio) + strlen(a_audio) + strlen(hold);
6013 if (needvideo) /* only if video response is appropriate */
6014 len += strlen(m_video) + strlen(a_video) + strlen(bandwidth) + strlen(hold);
6016 add_header(resp, "Content-Type", "application/sdp");
6017 add_header_contentLength(resp, len);
6018 add_line(resp, version);
6019 add_line(resp, owner);
6020 add_line(resp, subject);
6021 add_line(resp, connection);
6022 if (needvideo) /* only if video response is appropriate */
6023 add_line(resp, bandwidth);
6024 add_line(resp, stime);
6025 add_line(resp, m_audio);
6026 add_line(resp, a_audio);
6027 add_line(resp, hold);
6028 if (needvideo) { /* only if video response is appropriate */
6029 add_line(resp, m_video);
6030 add_line(resp, a_video);
6031 add_line(resp, hold); /* Repeat hold for the video stream */
6034 /* Update lastrtprx when we send our SDP */
6035 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
6037 if (option_debug > 2) {
6038 char buf[BUFSIZ];
6039 ast_log(LOG_DEBUG, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, BUFSIZ, capability));
6042 return 0;
6045 /*--- transmit_response_with_t38_sdp: Used for 200 OK and 183 early media ---*/
6046 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
6048 struct sip_request resp;
6049 int seqno;
6051 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
6052 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
6053 return -1;
6055 respprep(&resp, p, msg, req);
6056 if (p->udptl) {
6057 ast_udptl_offered_from_local(p->udptl, 0);
6058 add_t38_sdp(&resp, p);
6059 } else {
6060 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
6062 return send_response(p, &resp, retrans, seqno);
6065 /*! \brief copy SIP request (mostly used to save request for responses) */
6066 static void copy_request(struct sip_request *dst, const struct sip_request *src)
6068 long offset;
6069 int x;
6070 offset = ((void *)dst) - ((void *)src);
6071 /* First copy stuff */
6072 memcpy(dst, src, sizeof(*dst));
6073 /* Now fix pointer arithmetic */
6074 for (x=0; x < src->headers; x++)
6075 dst->header[x] += offset;
6076 for (x=0; x < src->lines; x++)
6077 dst->line[x] += offset;
6080 /*! \brief Used for 200 OK and 183 early media */
6081 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
6083 struct sip_request resp;
6084 int seqno;
6085 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
6086 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
6087 return -1;
6089 respprep(&resp, p, msg, req);
6090 if (p->rtp) {
6091 try_suggested_sip_codec(p);
6092 add_sdp(&resp, p);
6093 } else {
6094 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
6096 return send_response(p, &resp, reliable, seqno);
6099 /*! \brief Parse first line of incoming SIP request */
6100 static int determine_firstline_parts(struct sip_request *req)
6102 char *e = ast_skip_blanks(req->header[0]); /* there shouldn't be any */
6104 if (!*e)
6105 return -1;
6106 req->rlPart1 = e; /* method or protocol */
6107 e = ast_skip_nonblanks(e);
6108 if (*e)
6109 *e++ = '\0';
6110 /* Get URI or status code */
6111 e = ast_skip_blanks(e);
6112 if ( !*e )
6113 return -1;
6114 ast_trim_blanks(e);
6116 if (!strcasecmp(req->rlPart1, "SIP/2.0") ) { /* We have a response */
6117 if (strlen(e) < 3) /* status code is 3 digits */
6118 return -1;
6119 req->rlPart2 = e;
6120 } else { /* We have a request */
6121 if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
6122 ast_log(LOG_WARNING, "bogus uri in <> %s\n", e);
6123 e++;
6124 if (!*e)
6125 return -1;
6127 req->rlPart2 = e; /* URI */
6128 e = ast_skip_nonblanks(e);
6129 if (*e)
6130 *e++ = '\0';
6131 e = ast_skip_blanks(e);
6132 if (strcasecmp(e, "SIP/2.0") ) {
6133 ast_log(LOG_WARNING, "Bad request protocol %s\n", e);
6134 return -1;
6137 return 1;
6140 /*! \brief Transmit reinvite with SDP
6141 \note A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
6142 INVITE that opened the SIP dialogue
6143 We reinvite so that the audio stream (RTP) go directly between
6144 the SIP UAs. SIP Signalling stays with * in the path.
6146 static int transmit_reinvite_with_sdp(struct sip_pvt *p)
6148 struct sip_request req;
6150 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
6152 add_header(&req, "Allow", ALLOWED_METHODS);
6153 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6154 if (sipdebug)
6155 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
6156 if (recordhistory)
6157 append_history(p, "ReInv", "Re-invite sent");
6158 add_sdp(&req, p);
6159 /* Use this as the basis */
6160 initialize_initreq(p, &req);
6161 p->lastinvite = p->ocseq;
6162 return send_request(p, &req, 1, p->ocseq);
6165 /*! \brief Transmit reinvite with T38 SDP
6166 We reinvite so that the T38 processing can take place.
6167 SIP Signalling stays with * in the path.
6169 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p)
6171 struct sip_request req;
6173 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
6175 add_header(&req, "Allow", ALLOWED_METHODS);
6176 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6177 if (sipdebug)
6178 add_header(&req, "X-asterisk-info", "SIP re-invite (T38 switchover)");
6179 ast_udptl_offered_from_local(p->udptl, 1);
6180 add_t38_sdp(&req, p);
6181 /* Use this as the basis */
6182 initialize_initreq(p, &req);
6183 p->lastinvite = p->ocseq;
6184 return send_request(p, &req, 1, p->ocseq);
6187 /*! \brief Check Contact: URI of SIP message */
6188 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
6190 char stripped[256];
6191 char *c;
6193 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
6194 c = get_in_brackets(stripped);
6195 c = strsep(&c, ";"); /* trim ; and beyond */
6196 if (!ast_strlen_zero(c))
6197 ast_string_field_set(p, uri, c);
6200 /*! \brief Build contact header - the contact header we send out */
6201 static void build_contact(struct sip_pvt *p)
6203 /* Construct Contact: header */
6204 if (ourport != 5060) /* Needs to be 5060, according to the RFC */
6205 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);
6206 else
6207 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip));
6210 /*! \brief Build the Remote Party-ID & From using callingpres options */
6211 static void build_rpid(struct sip_pvt *p)
6213 int send_pres_tags = TRUE;
6214 const char *privacy=NULL;
6215 const char *screen=NULL;
6216 char buf[256];
6217 const char *clid = default_callerid;
6218 const char *clin = NULL;
6219 const char *fromdomain;
6221 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
6222 return;
6224 if (p->owner && p->owner->cid.cid_num)
6225 clid = p->owner->cid.cid_num;
6226 if (p->owner && p->owner->cid.cid_name)
6227 clin = p->owner->cid.cid_name;
6228 if (ast_strlen_zero(clin))
6229 clin = clid;
6231 switch (p->callingpres) {
6232 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
6233 privacy = "off";
6234 screen = "no";
6235 break;
6236 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
6237 privacy = "off";
6238 screen = "pass";
6239 break;
6240 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
6241 privacy = "off";
6242 screen = "fail";
6243 break;
6244 case AST_PRES_ALLOWED_NETWORK_NUMBER:
6245 privacy = "off";
6246 screen = "yes";
6247 break;
6248 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
6249 privacy = "full";
6250 screen = "no";
6251 break;
6252 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
6253 privacy = "full";
6254 screen = "pass";
6255 break;
6256 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
6257 privacy = "full";
6258 screen = "fail";
6259 break;
6260 case AST_PRES_PROHIB_NETWORK_NUMBER:
6261 privacy = "full";
6262 screen = "pass";
6263 break;
6264 case AST_PRES_NUMBER_NOT_AVAILABLE:
6265 send_pres_tags = FALSE;
6266 break;
6267 default:
6268 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
6269 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
6270 privacy = "full";
6271 else
6272 privacy = "off";
6273 screen = "no";
6274 break;
6277 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip));
6279 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
6280 if (send_pres_tags)
6281 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
6282 ast_string_field_set(p, rpid, buf);
6284 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
6285 S_OR(p->fromuser, clid),
6286 fromdomain, p->tag);
6289 /*! \brief Initiate new SIP request to peer/user */
6290 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
6292 char invite_buf[256] = "";
6293 char *invite = invite_buf;
6294 size_t invite_max = sizeof(invite_buf);
6295 char from[256];
6296 char to[256];
6297 char tmp[BUFSIZ/2];
6298 char tmp2[BUFSIZ/2];
6299 const char *l = NULL, *n = NULL;
6300 int x;
6301 char urioptions[256]="";
6303 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
6304 char onlydigits = TRUE;
6305 x=0;
6307 /* Test p->username against allowed characters in AST_DIGIT_ANY
6308 If it matches the allowed characters list, then sipuser = ";user=phone"
6309 If not, then sipuser = ""
6311 /* + is allowed in first position in a tel: uri */
6312 if (p->username && p->username[0] == '+')
6313 x=1;
6315 for (; x < strlen(p->username); x++) {
6316 if (!strchr(AST_DIGIT_ANYNUM, p->username[x])) {
6317 onlydigits = FALSE;
6318 break;
6322 /* If we have only digits, add ;user=phone to the uri */
6323 if (onlydigits)
6324 strcpy(urioptions, ";user=phone");
6328 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
6330 if (p->owner) {
6331 l = p->owner->cid.cid_num;
6332 n = p->owner->cid.cid_name;
6334 /* if we are not sending RPID and user wants his callerid restricted */
6335 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
6336 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
6337 l = CALLERID_UNKNOWN;
6338 n = l;
6340 if (ast_strlen_zero(l))
6341 l = default_callerid;
6342 if (ast_strlen_zero(n))
6343 n = l;
6344 /* Allow user to be overridden */
6345 if (!ast_strlen_zero(p->fromuser))
6346 l = p->fromuser;
6347 else /* Save for any further attempts */
6348 ast_string_field_set(p, fromuser, l);
6350 /* Allow user to be overridden */
6351 if (!ast_strlen_zero(p->fromname))
6352 n = p->fromname;
6353 else /* Save for any further attempts */
6354 ast_string_field_set(p, fromname, n);
6356 if (pedanticsipchecking) {
6357 ast_uri_encode(n, tmp, sizeof(tmp), 0);
6358 n = tmp;
6359 ast_uri_encode(l, tmp2, sizeof(tmp2), 0);
6360 l = tmp2;
6363 if ((ourport != 5060) && ast_strlen_zero(p->fromdomain)) /* Needs to be 5060 */
6364 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);
6365 else
6366 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)), p->tag);
6368 /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
6369 if (!ast_strlen_zero(p->fullcontact)) {
6370 /* If we have full contact, trust it */
6371 ast_build_string(&invite, &invite_max, "%s", p->fullcontact);
6372 } else {
6373 /* Otherwise, use the username while waiting for registration */
6374 ast_build_string(&invite, &invite_max, "sip:");
6375 if (!ast_strlen_zero(p->username)) {
6376 n = p->username;
6377 if (pedanticsipchecking) {
6378 ast_uri_encode(n, tmp, sizeof(tmp), 0);
6379 n = tmp;
6381 ast_build_string(&invite, &invite_max, "%s@", n);
6383 ast_build_string(&invite, &invite_max, "%s", p->tohost);
6384 if (ntohs(p->sa.sin_port) != 5060) /* Needs to be 5060 */
6385 ast_build_string(&invite, &invite_max, ":%d", ntohs(p->sa.sin_port));
6386 ast_build_string(&invite, &invite_max, "%s", urioptions);
6389 /* If custom URI options have been provided, append them */
6390 if (p->options && p->options->uri_options)
6391 ast_build_string(&invite, &invite_max, ";%s", p->options->uri_options);
6393 ast_string_field_set(p, uri, invite_buf);
6395 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
6396 /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
6397 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", p->uri, p->theirtag);
6398 } else if (p->options && p->options->vxml_url) {
6399 /* If there is a VXML URL append it to the SIP URL */
6400 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
6401 } else {
6402 snprintf(to, sizeof(to), "<%s>", p->uri);
6405 init_req(req, sipmethod, p->uri);
6406 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
6408 add_header(req, "Via", p->via);
6409 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
6410 * OTOH, then we won't have anything in p->route anyway */
6411 /* Build Remote Party-ID and From */
6412 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
6413 build_rpid(p);
6414 add_header(req, "From", p->rpid_from);
6415 } else {
6416 add_header(req, "From", from);
6418 add_header(req, "To", to);
6419 ast_string_field_set(p, exten, l);
6420 build_contact(p);
6421 add_header(req, "Contact", p->our_contact);
6422 add_header(req, "Call-ID", p->callid);
6423 add_header(req, "CSeq", tmp);
6424 add_header(req, "User-Agent", global_useragent);
6425 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
6426 if (!ast_strlen_zero(p->rpid))
6427 add_header(req, "Remote-Party-ID", p->rpid);
6430 /*! \brief Build REFER/INVITE/OPTIONS message and transmit it */
6431 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
6433 struct sip_request req;
6435 req.method = sipmethod;
6436 if (init) { /* Seems like init always is 2 */
6437 /* Bump branch even on initial requests */
6438 p->branch ^= ast_random();
6439 build_via(p);
6440 if (init > 1)
6441 initreqprep(&req, p, sipmethod);
6442 else
6443 reqprep(&req, p, sipmethod, 0, 1);
6444 } else
6445 reqprep(&req, p, sipmethod, 0, 1);
6447 if (p->options && p->options->auth)
6448 add_header(&req, p->options->authheader, p->options->auth);
6449 append_date(&req);
6450 if (sipmethod == SIP_REFER) { /* Call transfer */
6451 if (p->refer) {
6452 char buf[BUFSIZ];
6453 if (!ast_strlen_zero(p->refer->refer_to))
6454 add_header(&req, "Refer-To", p->refer->refer_to);
6455 if (!ast_strlen_zero(p->refer->referred_by)) {
6456 sprintf(buf, "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
6457 add_header(&req, "Referred-By", buf);
6461 /* This new INVITE is part of an attended transfer. Make sure that the
6462 other end knows and replace the current call with this new call */
6463 if (p->options && p->options->replaces && !ast_strlen_zero(p->options->replaces)) {
6464 add_header(&req, "Replaces", p->options->replaces);
6465 add_header(&req, "Require", "replaces");
6468 if (p->options && !ast_strlen_zero(p->options->distinctive_ring)) {
6469 add_header(&req, "Alert-Info", p->options->distinctive_ring);
6471 add_header(&req, "Allow", ALLOWED_METHODS);
6472 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6473 if (p->options && p->options->addsipheaders ) {
6474 struct ast_channel *ast;
6475 struct varshead *headp = NULL;
6476 const struct ast_var_t *current;
6478 ast = p->owner; /* The owner channel */
6479 if (ast) {
6480 char *headdup;
6481 headp = &ast->varshead;
6482 if (!headp)
6483 ast_log(LOG_WARNING,"No Headp for the channel...ooops!\n");
6484 else {
6485 AST_LIST_TRAVERSE(headp, current, entries) {
6486 /* SIPADDHEADER: Add SIP header to outgoing call */
6487 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
6488 char *content, *end;
6489 const char *header = ast_var_value(current);
6491 headdup = ast_strdupa(header);
6492 /* Strip of the starting " (if it's there) */
6493 if (*headdup == '"')
6494 headdup++;
6495 if ((content = strchr(headdup, ':'))) {
6496 *content++ = '\0';
6497 content = ast_skip_blanks(content); /* Skip white space */
6498 /* Strip the ending " (if it's there) */
6499 end = content + strlen(content) -1;
6500 if (*end == '"')
6501 *end = '\0';
6503 add_header(&req, headdup, content);
6504 if (sipdebug)
6505 ast_log(LOG_DEBUG, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
6512 if (sdp) {
6513 if (p->udptl && p->t38.state == T38_LOCAL_DIRECT) {
6514 ast_udptl_offered_from_local(p->udptl, 1);
6515 if (option_debug)
6516 ast_log(LOG_DEBUG, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
6517 add_t38_sdp(&req, p);
6518 } else if (p->rtp) {
6519 add_sdp(&req, p);
6521 } else {
6522 add_header_contentLength(&req, 0);
6525 if (!p->initreq.headers)
6526 initialize_initreq(p, &req);
6527 p->lastinvite = p->ocseq;
6528 return send_request(p, &req, init ? 2 : 1, p->ocseq);
6531 /*! \brief Used in the SUBSCRIBE notification subsystem */
6532 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
6534 char tmp[4000], from[256], to[256];
6535 char *t = tmp, *c, *mfrom, *mto;
6536 size_t maxbytes = sizeof(tmp);
6537 struct sip_request req;
6538 char hint[AST_MAX_EXTENSION];
6539 char *statestring = "terminated";
6540 const struct cfsubscription_types *subscriptiontype;
6541 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
6542 char *pidfstate = "--";
6543 char *pidfnote= "Ready";
6545 memset(from, 0, sizeof(from));
6546 memset(to, 0, sizeof(to));
6547 memset(tmp, 0, sizeof(tmp));
6549 switch (state) {
6550 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
6551 statestring = (global_notifyringing) ? "early" : "confirmed";
6552 local_state = NOTIFY_INUSE;
6553 pidfstate = "busy";
6554 pidfnote = "Ringing";
6555 break;
6556 case AST_EXTENSION_RINGING:
6557 statestring = "early";
6558 local_state = NOTIFY_INUSE;
6559 pidfstate = "busy";
6560 pidfnote = "Ringing";
6561 break;
6562 case AST_EXTENSION_INUSE:
6563 statestring = "confirmed";
6564 local_state = NOTIFY_INUSE;
6565 pidfstate = "busy";
6566 pidfnote = "On the phone";
6567 break;
6568 case AST_EXTENSION_BUSY:
6569 statestring = "confirmed";
6570 local_state = NOTIFY_CLOSED;
6571 pidfstate = "busy";
6572 pidfnote = "On the phone";
6573 break;
6574 case AST_EXTENSION_UNAVAILABLE:
6575 statestring = "confirmed";
6576 local_state = NOTIFY_CLOSED;
6577 pidfstate = "away";
6578 pidfnote = "Unavailable";
6579 break;
6580 case AST_EXTENSION_ONHOLD:
6581 break;
6582 case AST_EXTENSION_NOT_INUSE:
6583 default:
6584 /* Default setting */
6585 break;
6588 subscriptiontype = find_subscription_type(p->subscribed);
6590 /* Check which device/devices we are watching and if they are registered */
6591 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
6592 /* If they are not registered, we will override notification and show no availability */
6593 if (ast_device_state(hint) == AST_DEVICE_UNAVAILABLE) {
6594 local_state = NOTIFY_CLOSED;
6595 pidfstate = "away";
6596 pidfnote = "Not online";
6600 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
6601 c = get_in_brackets(from);
6602 if (strncmp(c, "sip:", 4)) {
6603 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
6604 return -1;
6606 mfrom = strsep(&c, ";"); /* trim ; and beyond */
6608 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
6609 c = get_in_brackets(to);
6610 if (strncmp(c, "sip:", 4)) {
6611 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
6612 return -1;
6614 mto = strsep(&c, ";"); /* trim ; and beyond */
6616 reqprep(&req, p, SIP_NOTIFY, 0, 1);
6619 add_header(&req, "Event", subscriptiontype->event);
6620 add_header(&req, "Content-Type", subscriptiontype->mediatype);
6621 switch(state) {
6622 case AST_EXTENSION_DEACTIVATED:
6623 if (p->subscribed == TIMEOUT)
6624 add_header(&req, "Subscription-State", "terminated;reason=timeout");
6625 else {
6626 add_header(&req, "Subscription-State", "terminated;reason=probation");
6627 add_header(&req, "Retry-After", "60");
6629 break;
6630 case AST_EXTENSION_REMOVED:
6631 add_header(&req, "Subscription-State", "terminated;reason=noresource");
6632 break;
6633 default:
6634 if (p->expiry)
6635 add_header(&req, "Subscription-State", "active");
6636 else /* Expired */
6637 add_header(&req, "Subscription-State", "terminated;reason=timeout");
6639 switch (p->subscribed) {
6640 case XPIDF_XML:
6641 case CPIM_PIDF_XML:
6642 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
6643 ast_build_string(&t, &maxbytes, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
6644 ast_build_string(&t, &maxbytes, "<presence>\n");
6645 ast_build_string(&t, &maxbytes, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
6646 ast_build_string(&t, &maxbytes, "<atom id=\"%s\">\n", p->exten);
6647 ast_build_string(&t, &maxbytes, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
6648 ast_build_string(&t, &maxbytes, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
6649 ast_build_string(&t, &maxbytes, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
6650 ast_build_string(&t, &maxbytes, "</address>\n</atom>\n</presence>\n");
6651 break;
6652 case PIDF_XML: /* Eyebeam supports this format */
6653 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
6654 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);
6655 ast_build_string(&t, &maxbytes, "<pp:person><status>\n");
6656 if (pidfstate[0] != '-')
6657 ast_build_string(&t, &maxbytes, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
6658 ast_build_string(&t, &maxbytes, "</status></pp:person>\n");
6659 ast_build_string(&t, &maxbytes, "<note>%s</note>\n", pidfnote); /* Note */
6660 ast_build_string(&t, &maxbytes, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
6661 ast_build_string(&t, &maxbytes, "<contact priority=\"1\">%s</contact>\n", mto);
6662 if (pidfstate[0] == 'b') /* Busy? Still open ... */
6663 ast_build_string(&t, &maxbytes, "<status><basic>open</basic></status>\n");
6664 else
6665 ast_build_string(&t, &maxbytes, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
6666 ast_build_string(&t, &maxbytes, "</tuple>\n</presence>\n");
6667 break;
6668 case DIALOG_INFO_XML: /* SNOM subscribes in this format */
6669 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
6670 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);
6671 if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
6672 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
6673 else
6674 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\">\n", p->exten);
6675 ast_build_string(&t, &maxbytes, "<state>%s</state>\n", statestring);
6676 ast_build_string(&t, &maxbytes, "</dialog>\n</dialog-info>\n");
6677 break;
6678 case NONE:
6679 default:
6680 break;
6683 if (t > tmp + sizeof(tmp))
6684 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
6686 add_header_contentLength(&req, strlen(tmp));
6687 add_line(&req, tmp);
6689 return send_request(p, &req, 1, p->ocseq);
6692 /*! \brief Notify user of messages waiting in voicemail
6693 \note - Notification only works for registered peers with mailbox= definitions
6694 in sip.conf
6695 - We use the SIP Event package message-summary
6696 MIME type defaults to "application/simple-message-summary";
6698 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
6700 struct sip_request req;
6701 char tmp[500];
6702 char *t = tmp;
6703 size_t maxbytes = sizeof(tmp);
6705 initreqprep(&req, p, SIP_NOTIFY);
6706 add_header(&req, "Event", "message-summary");
6707 add_header(&req, "Content-Type", default_notifymime);
6709 ast_build_string(&t, &maxbytes, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
6710 ast_build_string(&t, &maxbytes, "Message-Account: sip:%s@%s\r\n",
6711 S_OR(vmexten, default_vmexten), S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)));
6712 ast_build_string(&t, &maxbytes, "Voice-Message: %d/%d (0/0)\r\n", newmsgs, oldmsgs);
6713 if (p->subscribed) {
6714 if (p->expiry)
6715 add_header(&req, "Subscription-State", "active");
6716 else /* Expired */
6717 add_header(&req, "Subscription-State", "terminated;reason=timeout");
6720 if (t > tmp + sizeof(tmp))
6721 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
6723 add_header_contentLength(&req, strlen(tmp));
6724 add_line(&req, tmp);
6726 if (!p->initreq.headers)
6727 initialize_initreq(p, &req);
6728 return send_request(p, &req, 1, p->ocseq);
6731 /*! \brief Transmit SIP request */
6732 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req)
6734 if (!p->initreq.headers) /* Initialize first request before sending */
6735 initialize_initreq(p, req);
6736 return send_request(p, req, 0, p->ocseq);
6739 /*! \brief Notify a transferring party of the status of transfer */
6740 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
6742 struct sip_request req;
6743 char tmp[BUFSIZ/2];
6745 reqprep(&req, p, SIP_NOTIFY, 0, 1);
6746 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
6747 add_header(&req, "Event", tmp);
6748 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
6749 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
6750 add_header(&req, "Allow", ALLOWED_METHODS);
6751 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6753 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
6754 add_header_contentLength(&req, strlen(tmp));
6755 add_line(&req, tmp);
6757 if (!p->initreq.headers)
6758 initialize_initreq(p, &req);
6760 return send_request(p, &req, 1, p->ocseq);
6763 /*! \brief Convert registration state status to string */
6764 static char *regstate2str(enum sipregistrystate regstate)
6766 switch(regstate) {
6767 case REG_STATE_FAILED:
6768 return "Failed";
6769 case REG_STATE_UNREGISTERED:
6770 return "Unregistered";
6771 case REG_STATE_REGSENT:
6772 return "Request Sent";
6773 case REG_STATE_AUTHSENT:
6774 return "Auth. Sent";
6775 case REG_STATE_REGISTERED:
6776 return "Registered";
6777 case REG_STATE_REJECTED:
6778 return "Rejected";
6779 case REG_STATE_TIMEOUT:
6780 return "Timeout";
6781 case REG_STATE_NOAUTH:
6782 return "No Authentication";
6783 default:
6784 return "Unknown";
6788 /*! \brief Update registration with SIP Proxy */
6789 static int sip_reregister(void *data)
6791 /* if we are here, we know that we need to reregister. */
6792 struct sip_registry *r= ASTOBJ_REF((struct sip_registry *) data);
6794 /* if we couldn't get a reference to the registry object, punt */
6795 if (!r)
6796 return 0;
6798 if (r->call && recordhistory)
6799 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
6800 /* Since registry's are only added/removed by the the monitor thread, this
6801 may be overkill to reference/dereference at all here */
6802 if (sipdebug)
6803 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
6805 r->expire = -1;
6806 __sip_do_register(r);
6807 ASTOBJ_UNREF(r, sip_registry_destroy);
6808 return 0;
6811 /*! \brief Register with SIP proxy */
6812 static int __sip_do_register(struct sip_registry *r)
6814 int res;
6816 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
6817 return res;
6820 /*! \brief Registration timeout, register again */
6821 static int sip_reg_timeout(void *data)
6824 /* if we are here, our registration timed out, so we'll just do it over */
6825 struct sip_registry *r = ASTOBJ_REF((struct sip_registry *) data);
6826 struct sip_pvt *p;
6827 int res;
6829 /* if we couldn't get a reference to the registry object, punt */
6830 if (!r)
6831 return 0;
6833 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
6834 if (r->call) {
6835 /* Unlink us, destroy old call. Locking is not relevant here because all this happens
6836 in the single SIP manager thread. */
6837 p = r->call;
6838 if (p->registry)
6839 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
6840 r->call = NULL;
6841 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
6842 /* Pretend to ACK anything just in case */
6843 __sip_pretend_ack(p); /* XXX we need p locked, not sure we have */
6845 /* If we have a limit, stop registration and give up */
6846 if (global_regattempts_max && (r->regattempts > global_regattempts_max)) {
6847 /* Ok, enough is enough. Don't try any more */
6848 /* We could add an external notification here...
6849 steal it from app_voicemail :-) */
6850 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
6851 r->regstate = REG_STATE_FAILED;
6852 } else {
6853 r->regstate = REG_STATE_UNREGISTERED;
6854 r->timeout = -1;
6855 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
6857 manager_event(EVENT_FLAG_SYSTEM, "Registry", "Channel: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
6858 ASTOBJ_UNREF(r, sip_registry_destroy);
6859 return 0;
6862 /*! \brief Transmit register to SIP proxy or UA */
6863 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
6865 struct sip_request req;
6866 char from[256];
6867 char to[256];
6868 char tmp[80];
6869 char addr[80];
6870 struct sip_pvt *p;
6872 /* exit if we are already in process with this registrar ?*/
6873 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
6874 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
6875 return 0;
6878 if (r->call) { /* We have a registration */
6879 if (!auth) {
6880 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
6881 return 0;
6882 } else {
6883 p = r->call;
6884 make_our_tag(p->tag, sizeof(p->tag)); /* create a new local tag for every register attempt */
6885 ast_string_field_free(p, theirtag); /* forget their old tag, so we don't match tags when getting response */
6887 } else {
6888 /* Build callid for registration if we haven't registered before */
6889 if (!r->callid_valid) {
6890 build_callid_registry(r, __ourip, default_fromdomain);
6891 r->callid_valid = TRUE;
6893 /* Allocate SIP packet for registration */
6894 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER))) {
6895 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
6896 return 0;
6898 if (recordhistory)
6899 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
6900 /* Find address to hostname */
6901 if (create_addr(p, r->hostname)) {
6902 /* we have what we hope is a temporary network error,
6903 * probably DNS. We need to reschedule a registration try */
6904 sip_destroy(p);
6905 if (r->timeout > -1) {
6906 ast_sched_del(sched, r->timeout);
6907 r->timeout = ast_sched_add(sched, global_reg_timeout*1000, sip_reg_timeout, r);
6908 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
6909 } else {
6910 r->timeout = ast_sched_add(sched, global_reg_timeout*1000, sip_reg_timeout, r);
6911 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);
6913 r->regattempts++;
6914 return 0;
6916 /* Copy back Call-ID in case create_addr changed it */
6917 ast_string_field_set(r, callid, p->callid);
6918 if (r->portno)
6919 p->sa.sin_port = htons(r->portno);
6920 else /* Set registry port to the port set from the peer definition/srv or default */
6921 r->portno = ntohs(p->sa.sin_port);
6922 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
6923 r->call=p; /* Save pointer to SIP packet */
6924 p->registry = ASTOBJ_REF(r); /* Add pointer to registry in packet */
6925 if (!ast_strlen_zero(r->secret)) /* Secret (password) */
6926 ast_string_field_set(p, peersecret, r->secret);
6927 if (!ast_strlen_zero(r->md5secret))
6928 ast_string_field_set(p, peermd5secret, r->md5secret);
6929 /* User name in this realm
6930 - if authuser is set, use that, otherwise use username */
6931 if (!ast_strlen_zero(r->authuser)) {
6932 ast_string_field_set(p, peername, r->authuser);
6933 ast_string_field_set(p, authname, r->authuser);
6934 } else if (!ast_strlen_zero(r->username)) {
6935 ast_string_field_set(p, peername, r->username);
6936 ast_string_field_set(p, authname, r->username);
6937 ast_string_field_set(p, fromuser, r->username);
6939 if (!ast_strlen_zero(r->username))
6940 ast_string_field_set(p, username, r->username);
6941 /* Save extension in packet */
6942 ast_string_field_set(p, exten, r->contact);
6945 check which address we should use in our contact header
6946 based on whether the remote host is on the external or
6947 internal network so we can register through nat
6949 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
6950 p->ourip = bindaddr.sin_addr;
6951 build_contact(p);
6954 /* set up a timeout */
6955 if (auth == NULL) {
6956 if (r->timeout > -1) {
6957 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
6958 ast_sched_del(sched, r->timeout);
6960 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
6961 ast_log(LOG_DEBUG, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
6964 if (strchr(r->username, '@')) {
6965 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
6966 if (!ast_strlen_zero(p->theirtag))
6967 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
6968 else
6969 snprintf(to, sizeof(to), "<sip:%s>", r->username);
6970 } else {
6971 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
6972 if (!ast_strlen_zero(p->theirtag))
6973 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
6974 else
6975 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
6978 /* Fromdomain is what we are registering to, regardless of actual
6979 host name from SRV */
6980 snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain, r->hostname));
6981 ast_string_field_set(p, uri, addr);
6983 p->branch ^= ast_random();
6985 init_req(&req, sipmethod, addr);
6987 /* Add to CSEQ */
6988 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
6989 p->ocseq = r->ocseq;
6991 build_via(p);
6992 add_header(&req, "Via", p->via);
6993 add_header(&req, "From", from);
6994 add_header(&req, "To", to);
6995 add_header(&req, "Call-ID", p->callid);
6996 add_header(&req, "CSeq", tmp);
6997 add_header(&req, "User-Agent", global_useragent);
6998 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
7001 if (auth) /* Add auth header */
7002 add_header(&req, authheader, auth);
7003 else if (!ast_strlen_zero(r->nonce)) {
7004 char digest[1024];
7006 /* We have auth data to reuse, build a digest header! */
7007 if (sipdebug)
7008 ast_log(LOG_DEBUG, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
7009 ast_string_field_set(p, realm, r->realm);
7010 ast_string_field_set(p, nonce, r->nonce);
7011 ast_string_field_set(p, domain, r->domain);
7012 ast_string_field_set(p, opaque, r->opaque);
7013 ast_string_field_set(p, qop, r->qop);
7014 p->noncecount = r->noncecount++;
7016 memset(digest,0,sizeof(digest));
7017 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
7018 add_header(&req, "Authorization", digest);
7019 else
7020 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
7024 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
7025 add_header(&req, "Expires", tmp);
7026 add_header(&req, "Contact", p->our_contact);
7027 add_header(&req, "Event", "registration");
7028 add_header_contentLength(&req, 0);
7030 initialize_initreq(p, &req);
7031 if (sip_debug_test_pvt(p))
7032 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
7033 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
7034 r->regattempts++; /* Another attempt */
7035 if (option_debug > 3)
7036 ast_verbose("REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
7037 return send_request(p, &req, 2, p->ocseq);
7040 /*! \brief Transmit text with SIP MESSAGE method */
7041 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
7043 struct sip_request req;
7045 reqprep(&req, p, SIP_MESSAGE, 0, 1);
7046 add_text(&req, text);
7047 return send_request(p, &req, 1, p->ocseq);
7050 /*! \brief Allocate SIP refer structure */
7051 static int sip_refer_allocate(struct sip_pvt *p)
7053 p->refer = ast_calloc(1, sizeof(struct sip_refer));
7054 return p->refer ? 1 : 0;
7057 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
7058 \note this is currently broken as we have no way of telling the dialplan
7059 engine whether a transfer succeeds or fails.
7060 \todo Fix the transfer() dialplan function so that a transfer may fail
7062 static int transmit_refer(struct sip_pvt *p, const char *dest)
7064 struct sip_request req = {
7065 .headers = 0,
7067 char from[256];
7068 const char *of;
7069 char *c;
7070 char referto[256];
7071 char *ttag, *ftag;
7072 char *theirtag = ast_strdupa(p->theirtag);
7074 if (option_debug || sipdebug)
7075 ast_log(LOG_DEBUG, "SIP transfer of %s to %s\n", p->callid, dest);
7077 /* Are we transfering an inbound or outbound call ? */
7078 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
7079 of = get_header(&p->initreq, "To");
7080 ttag = theirtag;
7081 ftag = p->tag;
7082 } else {
7083 of = get_header(&p->initreq, "From");
7084 ftag = theirtag;
7085 ttag = p->tag;
7088 ast_copy_string(from, of, sizeof(from));
7089 of = get_in_brackets(from);
7090 ast_string_field_set(p, from, of);
7091 if (strncmp(of, "sip:", 4))
7092 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
7093 else
7094 of += 4;
7095 /* Get just the username part */
7096 if ((c = strchr(dest, '@')))
7097 c = NULL;
7098 else if ((c = strchr(of, '@')))
7099 *c++ = '\0';
7100 if (c)
7101 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
7102 else
7103 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
7105 /* save in case we get 407 challenge */
7106 sip_refer_allocate(p);
7107 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
7108 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
7109 p->refer->status = REFER_SENT; /* Set refer status */
7111 reqprep(&req, p, SIP_REFER, 0, 1);
7112 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
7114 add_header(&req, "Refer-To", referto);
7115 add_header(&req, "Allow", ALLOWED_METHODS);
7116 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7117 if (!ast_strlen_zero(p->our_contact))
7118 add_header(&req, "Referred-By", p->our_contact);
7120 return send_request(p, &req, 1, p->ocseq);
7121 /* We should propably wait for a NOTIFY here until we ack the transfer */
7122 /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
7124 /*! \todo In theory, we should hang around and wait for a reply, before
7125 returning to the dial plan here. Don't know really how that would
7126 affect the transfer() app or the pbx, but, well, to make this
7127 useful we should have a STATUS code on transfer().
7132 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
7133 static int transmit_info_with_digit(struct sip_pvt *p, const char digit)
7135 struct sip_request req;
7137 reqprep(&req, p, SIP_INFO, 0, 1);
7138 add_digit(&req, digit);
7139 return send_request(p, &req, 1, p->ocseq);
7142 /*! \brief Send SIP INFO with video update request */
7143 static int transmit_info_with_vidupdate(struct sip_pvt *p)
7145 struct sip_request req;
7147 reqprep(&req, p, SIP_INFO, 0, 1);
7148 add_vidupdate(&req);
7149 return send_request(p, &req, 1, p->ocseq);
7152 /*! \brief Transmit generic SIP request */
7153 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
7155 struct sip_request resp;
7157 reqprep(&resp, p, sipmethod, seqno, newbranch);
7158 add_header_contentLength(&resp, 0);
7159 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
7162 /*! \brief Transmit SIP request, auth added */
7163 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
7165 struct sip_request resp;
7167 reqprep(&resp, p, sipmethod, seqno, newbranch);
7168 if (!ast_strlen_zero(p->realm)) {
7169 char digest[1024];
7171 memset(digest, 0, sizeof(digest));
7172 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
7173 if (p->options && p->options->auth_type == PROXY_AUTH)
7174 add_header(&resp, "Proxy-Authorization", digest);
7175 else if (p->options && p->options->auth_type == WWW_AUTH)
7176 add_header(&resp, "Authorization", digest);
7177 else /* Default, to be backwards compatible (maybe being too careful, but leaving it for now) */
7178 add_header(&resp, "Proxy-Authorization", digest);
7179 } else
7180 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
7182 /* If we are hanging up and know a cause for that, send it in clear text to make
7183 debugging easier. */
7184 if (sipmethod == SIP_BYE && p->owner && p->owner->hangupcause) {
7185 char buf[10];
7187 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
7188 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
7189 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
7192 add_header_contentLength(&resp, 0);
7193 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
7196 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
7197 static void destroy_association(struct sip_peer *peer)
7199 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE)) {
7200 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
7201 ast_update_realtime("sippeers", "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "username", "", "regserver", "", NULL);
7202 else
7203 ast_db_del("SIP/Registry", peer->name);
7207 /*! \brief Expire registration of SIP peer */
7208 static int expire_register(void *data)
7210 struct sip_peer *peer = data;
7212 if (!peer) /* Hmmm. We have no peer. Weird. */
7213 return 0;
7215 memset(&peer->addr, 0, sizeof(peer->addr));
7217 destroy_association(peer); /* remove registration data from storage */
7219 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
7220 register_peer_exten(peer, FALSE); /* Remove regexten */
7221 peer->expire = -1;
7222 ast_device_state_changed("SIP/%s", peer->name);
7224 /* Do we need to release this peer from memory?
7225 Only for realtime peers and autocreated peers
7227 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT) ||
7228 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
7229 peer = ASTOBJ_CONTAINER_UNLINK(&peerl, peer); /* Remove from peer list */
7230 ASTOBJ_UNREF(peer, sip_destroy_peer); /* Remove from memory */
7233 return 0;
7236 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
7237 static int sip_poke_peer_s(void *data)
7239 struct sip_peer *peer = data;
7241 peer->pokeexpire = -1;
7242 sip_poke_peer(peer);
7243 return 0;
7246 /*! \brief Get registration details from Asterisk DB */
7247 static void reg_source_db(struct sip_peer *peer)
7249 char data[256];
7250 struct in_addr in;
7251 int expiry;
7252 int port;
7253 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
7255 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
7256 return;
7257 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
7258 return;
7260 scan = data;
7261 addr = strsep(&scan, ":");
7262 port_str = strsep(&scan, ":");
7263 expiry_str = strsep(&scan, ":");
7264 username = strsep(&scan, ":");
7265 contact = scan; /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
7267 if (!inet_aton(addr, &in))
7268 return;
7270 if (port_str)
7271 port = atoi(port_str);
7272 else
7273 return;
7275 if (expiry_str)
7276 expiry = atoi(expiry_str);
7277 else
7278 return;
7280 if (username)
7281 ast_copy_string(peer->username, username, sizeof(peer->username));
7282 if (contact)
7283 ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
7285 if (option_verbose > 2)
7286 ast_verbose(VERBOSE_PREFIX_3 "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
7287 peer->name, peer->username, ast_inet_ntoa(in), port, expiry);
7289 memset(&peer->addr, 0, sizeof(peer->addr));
7290 peer->addr.sin_family = AF_INET;
7291 peer->addr.sin_addr = in;
7292 peer->addr.sin_port = htons(port);
7293 if (sipsock < 0) {
7294 /* SIP isn't up yet, so schedule a poke only, pretty soon */
7295 if (peer->pokeexpire > -1)
7296 ast_sched_del(sched, peer->pokeexpire);
7297 peer->pokeexpire = ast_sched_add(sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer);
7298 } else
7299 sip_poke_peer(peer);
7300 if (peer->expire > -1)
7301 ast_sched_del(sched, peer->expire);
7302 peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, peer);
7303 register_peer_exten(peer, TRUE);
7306 /*! \brief Save contact header for 200 OK on INVITE */
7307 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
7309 char contact[250];
7310 char *c;
7312 /* Look for brackets */
7313 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
7314 c = get_in_brackets(contact);
7316 /* Save full contact to call pvt for later bye or re-invite */
7317 ast_string_field_set(pvt, fullcontact, c);
7319 /* Save URI for later ACKs, BYE or RE-invites */
7320 ast_string_field_set(pvt, okcontacturi, c);
7322 /* We should return false for URI:s we can't handle,
7323 like sips:, tel:, mailto:,ldap: etc */
7324 return TRUE;
7327 /*! \brief Change the other partys IP address based on given contact */
7328 static int set_address_from_contact(struct sip_pvt *pvt)
7330 struct hostent *hp;
7331 struct ast_hostent ahp;
7332 int port;
7333 char *c, *host, *pt;
7334 char *contact;
7337 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
7338 /* NAT: Don't trust the contact field. Just use what they came to us
7339 with. */
7340 pvt->sa = pvt->recv;
7341 return 0;
7345 /* Work on a copy */
7346 contact = ast_strdupa(pvt->fullcontact);
7348 /* XXX this code is repeated all over */
7349 /* Make sure it's a SIP URL */
7350 if (strncasecmp(contact, "sip:", 4)) {
7351 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
7352 } else
7353 contact += 4;
7355 /* Ditch arguments */
7356 /* XXX this code is replicated also shortly below */
7357 contact = strsep(&contact, ";"); /* trim ; and beyond */
7359 /* Grab host */
7360 host = strchr(contact, '@');
7361 if (!host) { /* No username part */
7362 host = contact;
7363 c = NULL;
7364 } else {
7365 *host++ = '\0';
7367 pt = strchr(host, ':');
7368 if (pt) {
7369 *pt++ = '\0';
7370 port = atoi(pt);
7371 } else
7372 port = DEFAULT_SIP_PORT;
7374 /* XXX This could block for a long time XXX */
7375 /* We should only do this if it's a name, not an IP */
7376 hp = ast_gethostbyname(host, &ahp);
7377 if (!hp) {
7378 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
7379 return -1;
7381 pvt->sa.sin_family = AF_INET;
7382 memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
7383 pvt->sa.sin_port = htons(port);
7385 return 0;
7389 /*! \brief Parse contact header and save registration (peer registration) */
7390 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
7392 char contact[BUFSIZ];
7393 char data[BUFSIZ];
7394 const char *expires = get_header(req, "Expires");
7395 int expiry = atoi(expires);
7396 char *curi, *n, *pt;
7397 int port;
7398 const char *useragent;
7399 struct hostent *hp;
7400 struct ast_hostent ahp;
7401 struct sockaddr_in oldsin;
7403 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
7405 if (ast_strlen_zero(expires)) { /* No expires header */
7406 expires = strcasestr(contact, ";expires=");
7407 if (expires) {
7408 /* XXX bug here, we overwrite the string */
7409 expires = strsep((char **) &expires, ";"); /* trim ; and beyond */
7410 if (sscanf(expires + 9, "%d", &expiry) != 1)
7411 expiry = default_expiry;
7412 } else {
7413 /* Nothing has been specified */
7414 expiry = default_expiry;
7418 /* Look for brackets */
7419 curi = contact;
7420 if (strchr(contact, '<') == NULL) /* No <, check for ; and strip it */
7421 strsep(&curi, ";"); /* This is Header options, not URI options */
7422 curi = get_in_brackets(contact);
7424 /* if they did not specify Contact: or Expires:, they are querying
7425 what we currently have stored as their contact address, so return
7428 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
7429 /* If we have an active registration, tell them when the registration is going to expire */
7430 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
7431 pvt->expiry = ast_sched_when(sched, peer->expire);
7432 return PARSE_REGISTER_QUERY;
7433 } else if (!strcasecmp(curi, "*") || !expiry) { /* Unregister this peer */
7434 /* This means remove all registrations and return OK */
7435 memset(&peer->addr, 0, sizeof(peer->addr));
7436 if (peer->expire > -1)
7437 ast_sched_del(sched, peer->expire);
7438 peer->expire = -1;
7440 destroy_association(peer);
7442 register_peer_exten(peer, 0); /* Add extension from regexten= setting in sip.conf */
7443 peer->fullcontact[0] = '\0';
7444 peer->useragent[0] = '\0';
7445 peer->sipoptions = 0;
7446 peer->lastms = 0;
7448 if (option_verbose > 2)
7449 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", peer->name);
7450 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
7451 return PARSE_REGISTER_UPDATE;
7454 /* Store whatever we got as a contact from the client */
7455 ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));
7457 /* For the 200 OK, we should use the received contact */
7458 ast_string_field_build(pvt, our_contact, "<%s>", curi);
7460 /* Make sure it's a SIP URL */
7461 if (strncasecmp(curi, "sip:", 4)) {
7462 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", curi);
7463 } else
7464 curi += 4;
7465 /* Ditch q */
7466 curi = strsep(&curi, ";");
7467 /* Grab host */
7468 n = strchr(curi, '@');
7469 if (!n) {
7470 n = curi;
7471 curi = NULL;
7472 } else
7473 *n++ = '\0';
7474 pt = strchr(n, ':');
7475 if (pt) {
7476 *pt++ = '\0';
7477 port = atoi(pt);
7478 } else
7479 port = DEFAULT_SIP_PORT;
7480 oldsin = peer->addr;
7481 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
7482 /* XXX This could block for a long time XXX */
7483 hp = ast_gethostbyname(n, &ahp);
7484 if (!hp) {
7485 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
7486 return PARSE_REGISTER_FAILED;
7488 peer->addr.sin_family = AF_INET;
7489 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
7490 peer->addr.sin_port = htons(port);
7491 } else {
7492 /* Don't trust the contact field. Just use what they came to us
7493 with */
7494 peer->addr = pvt->recv;
7497 /* Save SIP options profile */
7498 peer->sipoptions = pvt->sipoptions;
7500 if (curi) /* Overwrite the default username from config at registration */
7501 ast_copy_string(peer->username, curi, sizeof(peer->username));
7502 else
7503 peer->username[0] = '\0';
7505 if (peer->expire > -1)
7506 ast_sched_del(sched, peer->expire);
7507 if (expiry > max_expiry)
7508 expiry = max_expiry;
7509 if (expiry < min_expiry)
7510 expiry = min_expiry;
7511 peer->expire = ast_test_flag(&peer->flags[0], SIP_REALTIME) ? -1 :
7512 ast_sched_add(sched, (expiry + 10) * 1000, expire_register, peer);
7513 pvt->expiry = expiry;
7514 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);
7515 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
7516 ast_db_put("SIP/Registry", peer->name, data);
7517 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
7519 /* Is this a new IP address for us? */
7520 if (inaddrcmp(&peer->addr, &oldsin)) {
7521 sip_poke_peer(peer);
7522 if (option_verbose > 2)
7523 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);
7524 register_peer_exten(peer, 1);
7527 /* Save User agent */
7528 useragent = get_header(req, "User-Agent");
7529 if (useragent && strcasecmp(useragent, peer->useragent)) {
7530 ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
7531 if (option_verbose > 3)
7532 ast_verbose(VERBOSE_PREFIX_3 "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
7534 return PARSE_REGISTER_UPDATE;
7537 /*! \brief Remove route from route list */
7538 static void free_old_route(struct sip_route *route)
7540 struct sip_route *next;
7542 while (route) {
7543 next = route->next;
7544 free(route);
7545 route = next;
7549 /*! \brief List all routes - mostly for debugging */
7550 static void list_route(struct sip_route *route)
7552 if (!route)
7553 ast_verbose("list_route: no route\n");
7554 else {
7555 for (;route; route = route->next)
7556 ast_verbose("list_route: hop: <%s>\n", route->hop);
7560 /*! \brief Build route list from Record-Route header */
7561 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
7563 struct sip_route *thishop, *head, *tail;
7564 int start = 0;
7565 int len;
7566 const char *rr, *contact, *c;
7568 /* Once a persistant route is set, don't fool with it */
7569 if (p->route && p->route_persistant) {
7570 ast_log(LOG_DEBUG, "build_route: Retaining previous route: <%s>\n", p->route->hop);
7571 return;
7574 if (p->route) {
7575 free_old_route(p->route);
7576 p->route = NULL;
7579 p->route_persistant = backwards;
7581 /* Build a tailq, then assign it to p->route when done.
7582 * If backwards, we add entries from the head so they end up
7583 * in reverse order. However, we do need to maintain a correct
7584 * tail pointer because the contact is always at the end.
7586 head = NULL;
7587 tail = head;
7588 /* 1st we pass through all the hops in any Record-Route headers */
7589 for (;;) {
7590 /* Each Record-Route header */
7591 rr = __get_header(req, "Record-Route", &start);
7592 if (*rr == '\0')
7593 break;
7594 for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
7595 ++rr;
7596 len = strcspn(rr, ">") + 1;
7597 /* Make a struct route */
7598 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
7599 /* ast_calloc is not needed because all fields are initialized in this block */
7600 ast_copy_string(thishop->hop, rr, len);
7601 if (option_debug > 1)
7602 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
7603 /* Link in */
7604 if (backwards) {
7605 /* Link in at head so they end up in reverse order */
7606 thishop->next = head;
7607 head = thishop;
7608 /* If this was the first then it'll be the tail */
7609 if (!tail)
7610 tail = thishop;
7611 } else {
7612 thishop->next = NULL;
7613 /* Link in at the end */
7614 if (tail)
7615 tail->next = thishop;
7616 else
7617 head = thishop;
7618 tail = thishop;
7624 /* Only append the contact if we are dealing with a strict router */
7625 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop,";lr") == NULL) ) {
7626 /* 2nd append the Contact: if there is one */
7627 /* Can be multiple Contact headers, comma separated values - we just take the first */
7628 contact = get_header(req, "Contact");
7629 if (!ast_strlen_zero(contact)) {
7630 if (option_debug > 1)
7631 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
7632 /* Look for <: delimited address */
7633 c = strchr(contact, '<');
7634 if (c) {
7635 /* Take to > */
7636 ++c;
7637 len = strcspn(c, ">") + 1;
7638 } else {
7639 /* No <> - just take the lot */
7640 c = contact;
7641 len = strlen(contact) + 1;
7643 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
7644 /* ast_calloc is not needed because all fields are initialized in this block */
7645 ast_copy_string(thishop->hop, c, len);
7646 thishop->next = NULL;
7647 /* Goes at the end */
7648 if (tail)
7649 tail->next = thishop;
7650 else
7651 head = thishop;
7656 /* Store as new route */
7657 p->route = head;
7659 /* For debugging dump what we ended up with */
7660 if (sip_debug_test_pvt(p))
7661 list_route(p->route);
7665 /*! \brief Check user authorization from peer definition
7666 Some actions, like REGISTER and INVITEs from peers require
7667 authentication (if peer have secret set)
7668 \return 0 on success, non-zero on error
7670 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
7671 const char *secret, const char *md5secret, int sipmethod,
7672 char *uri, enum xmittype reliable, int ignore)
7674 const char *response = "407 Proxy Authentication Required";
7675 const char *reqheader = "Proxy-Authorization";
7676 const char *respheader = "Proxy-Authenticate";
7677 const char *authtoken;
7678 char a1_hash[256];
7679 char resp_hash[256]="";
7680 char tmp[BUFSIZ * 2]; /* Make a large enough buffer */
7681 char *c;
7682 int wrongnonce = FALSE;
7683 int good_response;
7684 const char *usednonce = p->randdata;
7686 /* table of recognised keywords, and their value in the digest */
7687 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
7688 struct x {
7689 const char *key;
7690 const char *s;
7691 } *i, keys[] = {
7692 [K_RESP] = { "response=", "" },
7693 [K_URI] = { "uri=", "" },
7694 [K_USER] = { "username=", "" },
7695 [K_NONCE] = { "nonce=", "" },
7696 [K_LAST] = { NULL, NULL}
7699 /* Always OK if no secret */
7700 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
7701 return AUTH_SUCCESSFUL;
7702 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
7703 /* On a REGISTER, we have to use 401 and its family of headers instead of 407 and its family
7704 of headers -- GO SIP! Whoo hoo! Two things that do the same thing but are used in
7705 different circumstances! What a surprise. */
7706 response = "401 Unauthorized";
7707 reqheader = "Authorization";
7708 respheader = "WWW-Authenticate";
7710 authtoken = get_header(req, reqheader);
7711 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
7712 /* This is a retransmitted invite/register/etc, don't reconstruct authentication
7713 information */
7714 if (!reliable) {
7715 /* Resend message if this was NOT a reliable delivery. Otherwise the
7716 retransmission should get it */
7717 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
7718 /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
7719 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
7721 return AUTH_CHALLENGE_SENT;
7722 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
7723 /* We have no auth, so issue challenge and request authentication */
7724 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
7725 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
7726 /* Schedule auto destroy in 32 seconds */
7727 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
7728 return AUTH_CHALLENGE_SENT;
7731 /* --- We have auth, so check it */
7733 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
7734 an example in the spec of just what it is you're doing a hash on. */
7737 /* Make a copy of the response and parse it */
7738 ast_copy_string(tmp, authtoken, sizeof(tmp));
7739 c = tmp;
7741 while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
7742 for (i = keys; i->key != NULL; i++) {
7743 const char *separator = ","; /* default */
7745 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
7746 continue;
7747 /* Found. Skip keyword, take text in quotes or up to the separator. */
7748 c += strlen(i->key);
7749 if (*c == '"') { /* in quotes. Skip first and look for last */
7750 c++;
7751 separator = "\"";
7753 i->s = c;
7754 strsep(&c, separator);
7755 break;
7757 if (i->key == NULL) /* not found, jump after space or comma */
7758 strsep(&c, " ,");
7761 /* Verify that digest username matches the username we auth as */
7762 if (strcmp(username, keys[K_USER].s)) {
7763 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
7764 username, keys[K_USER].s);
7765 /* Oops, we're trying something here */
7766 return AUTH_USERNAME_MISMATCH;
7769 /* Verify nonce from request matches our nonce. If not, send 401 with new nonce */
7770 if (strcasecmp(p->randdata, keys[K_NONCE].s)) { /* XXX it was 'n'casecmp ? */
7771 wrongnonce = TRUE;
7772 usednonce = keys[K_NONCE].s;
7775 if (!ast_strlen_zero(md5secret))
7776 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
7777 else {
7778 char a1[256];
7779 snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
7780 ast_md5_hash(a1_hash, a1);
7783 /* compute the expected response to compare with what we received */
7785 char a2[256];
7786 char a2_hash[256];
7787 char resp[256];
7789 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
7790 S_OR(keys[K_URI].s, uri));
7791 ast_md5_hash(a2_hash, a2);
7792 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
7793 ast_md5_hash(resp_hash, resp);
7796 good_response = keys[K_RESP].s &&
7797 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
7798 if (wrongnonce) {
7799 ast_string_field_build(p, randdata, "%08lx", ast_random());
7800 if (good_response) {
7801 if (sipdebug)
7802 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
7803 /* We got working auth token, based on stale nonce . */
7804 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 1);
7805 } else {
7806 /* Everything was wrong, so give the device one more try with a new challenge */
7807 if (sipdebug)
7808 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
7809 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
7812 /* Schedule auto destroy in 32 seconds */
7813 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
7814 return AUTH_CHALLENGE_SENT;
7816 if (good_response)
7817 return AUTH_SUCCESSFUL;
7819 /* Ok, we have a bad username/secret pair */
7820 /* Challenge again, and again, and again */
7821 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
7822 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
7824 return AUTH_CHALLENGE_SENT;
7827 /*! \brief Change onhold state of a peer using a pvt structure */
7828 static void sip_peer_hold(struct sip_pvt *p, int hold)
7830 struct sip_peer *peer = find_peer(p->peername, NULL, 1);
7832 if (!peer)
7833 return;
7835 /* If they put someone on hold, increment the value... otherwise decrement it */
7836 if (hold)
7837 peer->onHold++;
7838 else if (hold > 0)
7839 peer->onHold--;
7841 /* Request device state update */
7842 ast_device_state_changed("SIP/%s", peer->name);
7844 return;
7847 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
7848 \note If you add an "hint" priority to the extension in the dial plan,
7849 you will get notifications on device state changes */
7850 static int cb_extensionstate(char *context, char* exten, int state, void *data)
7852 struct sip_pvt *p = data;
7854 switch(state) {
7855 case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
7856 case AST_EXTENSION_REMOVED: /* Extension is gone */
7857 if (p->autokillid > -1)
7858 sip_cancel_destroy(p); /* Remove subscription expiry for renewals */
7859 sip_scheddestroy(p, SIP_TRANS_TIMEOUT); /* Delete subscription in 32 secs */
7860 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);
7861 p->stateid = -1;
7862 p->subscribed = NONE;
7863 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
7864 break;
7865 default: /* Tell user */
7866 p->laststate = state;
7867 break;
7869 transmit_state_notify(p, state, 1);
7871 if (option_debug > 1)
7872 ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %s for Notify User %s\n", exten, ast_extension_state2str(state), p->username);
7873 return 0;
7876 /*! \brief Send a fake 401 Unauthorized response when the administrator
7877 wants to hide the names of local users/peers from fishers
7879 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable)
7881 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
7882 transmit_response_with_auth(p, "401 Unauthorized", req, p->randdata, reliable, "WWW-Authenticate", 0);
7885 /*! \brief Verify registration of user
7886 - Registration is done in several steps, first a REGISTER without auth
7887 to get a challenge (nonce) then a second one with auth
7888 - Registration requests are only matched with peers that are marked as "dynamic"
7890 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
7891 struct sip_request *req, char *uri)
7893 enum check_auth_result res = AUTH_NOT_FOUND;
7894 struct sip_peer *peer;
7895 char tmp[256];
7896 char *name, *c;
7897 char *t;
7898 char *domain;
7900 /* Terminate URI */
7901 t = uri;
7902 while(*t && (*t > 32) && (*t != ';'))
7903 t++;
7904 *t = '\0';
7906 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
7907 if (pedanticsipchecking)
7908 ast_uri_decode(tmp);
7910 c = get_in_brackets(tmp);
7911 c = strsep(&c, ";"); /* Ditch ;user=phone */
7913 if (!strncmp(c, "sip:", 4)) {
7914 name = c + 4;
7915 } else {
7916 name = c;
7917 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
7920 /* Strip off the domain name */
7921 if ((c = strchr(name, '@'))) {
7922 *c++ = '\0';
7923 domain = c;
7924 if ((c = strchr(domain, ':'))) /* Remove :port */
7925 *c = '\0';
7926 if (!AST_LIST_EMPTY(&domain_list)) {
7927 if (!check_sip_domain(domain, NULL, 0)) {
7928 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
7929 return AUTH_UNKNOWN_DOMAIN;
7934 ast_string_field_set(p, exten, name);
7935 build_contact(p);
7936 peer = find_peer(name, NULL, 1);
7937 if (!(peer && ast_apply_ha(peer->ha, sin))) {
7938 if (peer)
7939 ASTOBJ_UNREF(peer, sip_destroy_peer);
7941 if (peer) {
7942 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
7943 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
7944 } else {
7945 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
7946 transmit_response(p, "100 Trying", req);
7947 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, ast_test_flag(req, SIP_PKT_IGNORE)))) {
7948 sip_cancel_destroy(p);
7950 /* We have a succesful registration attemp with proper authentication,
7951 now, update the peer */
7952 switch (parse_register_contact(p, peer, req)) {
7953 case PARSE_REGISTER_FAILED:
7954 ast_log(LOG_WARNING, "Failed to parse contact info\n");
7955 transmit_response_with_date(p, "400 Bad Request", req);
7956 peer->lastmsgssent = -1;
7957 res = 0;
7958 break;
7959 case PARSE_REGISTER_QUERY:
7960 transmit_response_with_date(p, "200 OK", req);
7961 peer->lastmsgssent = -1;
7962 res = 0;
7963 break;
7964 case PARSE_REGISTER_UPDATE:
7965 update_peer(peer, p->expiry);
7966 /* Say OK and ask subsystem to retransmit msg counter */
7967 transmit_response_with_date(p, "200 OK", req);
7968 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
7969 peer->lastmsgssent = -1;
7970 res = 0;
7971 break;
7976 if (!peer && autocreatepeer) {
7977 /* Create peer if we have autocreate mode enabled */
7978 peer = temp_peer(name);
7979 if (peer) {
7980 ASTOBJ_CONTAINER_LINK(&peerl, peer);
7981 sip_cancel_destroy(p);
7982 switch (parse_register_contact(p, peer, req)) {
7983 case PARSE_REGISTER_FAILED:
7984 ast_log(LOG_WARNING, "Failed to parse contact info\n");
7985 transmit_response_with_date(p, "400 Bad Request", req);
7986 peer->lastmsgssent = -1;
7987 res = 0;
7988 break;
7989 case PARSE_REGISTER_QUERY:
7990 transmit_response_with_date(p, "200 OK", req);
7991 peer->lastmsgssent = -1;
7992 res = 0;
7993 break;
7994 case PARSE_REGISTER_UPDATE:
7995 /* Say OK and ask subsystem to retransmit msg counter */
7996 transmit_response_with_date(p, "200 OK", req);
7997 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
7998 peer->lastmsgssent = -1;
7999 res = 0;
8000 break;
8004 if (!res) {
8005 ast_device_state_changed("SIP/%s", peer->name);
8007 if (res < 0) {
8008 switch (res) {
8009 case AUTH_SECRET_FAILED:
8010 /* Wrong password in authentication. Go away, don't try again until you fixed it */
8011 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
8012 break;
8013 case AUTH_USERNAME_MISMATCH:
8014 /* Username and digest username does not match.
8015 Asterisk uses the From: username for authentication. We need the
8016 users to use the same authentication user name until we support
8017 proper authentication by digest auth name */
8018 transmit_response(p, "403 Authentication user name does not match account name", &p->initreq);
8019 break;
8020 case AUTH_NOT_FOUND:
8021 if (global_alwaysauthreject) {
8022 transmit_fake_auth_response(p, &p->initreq, 1);
8023 } else {
8024 /* URI not found */
8025 transmit_response(p, "404 Not found", &p->initreq);
8027 break;
8028 default:
8029 break;
8031 if (option_debug > 1) {
8032 const char *reason = "";
8034 switch (res) {
8035 case AUTH_SECRET_FAILED:
8036 reason = "Bad password";
8037 break;
8038 case AUTH_USERNAME_MISMATCH:
8039 reason = "Bad digest user";
8040 break;
8041 case AUTH_NOT_FOUND:
8042 reason = "Peer not found";
8043 break;
8044 default:
8045 break;
8047 ast_log(LOG_DEBUG, "SIP REGISTER attempt failed for %s : %s\n",
8048 peer->name, reason);
8051 if (peer)
8052 ASTOBJ_UNREF(peer, sip_destroy_peer);
8054 return res;
8057 /*! \brief Get referring dnis */
8058 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
8060 char tmp[256], *c, *a;
8061 struct sip_request *req;
8063 req = oreq;
8064 if (!req)
8065 req = &p->initreq;
8066 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
8067 if (ast_strlen_zero(tmp))
8068 return 0;
8069 c = get_in_brackets(tmp);
8070 if (strncmp(c, "sip:", 4)) {
8071 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", c);
8072 return -1;
8074 c += 4;
8075 a = c;
8076 strsep(&a, "@;"); /* trim anything after @ or ; */
8077 if (sip_debug_test_pvt(p))
8078 ast_verbose("RDNIS is %s\n", c);
8079 ast_string_field_set(p, rdnis, c);
8081 return 0;
8084 /*! \brief Find out who the call is for
8085 We use the INVITE uri to find out
8087 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
8089 char tmp[256] = "", *uri, *a;
8090 char tmpf[256] = "", *from;
8091 struct sip_request *req;
8092 char *colon;
8094 req = oreq;
8095 if (!req)
8096 req = &p->initreq;
8098 /* Find the request URI */
8099 if (req->rlPart2)
8100 ast_copy_string(tmp, req->rlPart2, sizeof(tmp));
8102 if (pedanticsipchecking)
8103 ast_uri_decode(tmp);
8105 uri = get_in_brackets(tmp);
8107 if (strncmp(uri, "sip:", 4)) {
8108 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
8109 return -1;
8111 uri += 4;
8113 /* Now find the From: caller ID and name */
8114 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
8115 if (!ast_strlen_zero(tmpf)) {
8116 if (pedanticsipchecking)
8117 ast_uri_decode(tmpf);
8118 from = get_in_brackets(tmpf);
8119 } else {
8120 from = NULL;
8123 if (!ast_strlen_zero(from)) {
8124 if (strncmp(from, "sip:", 4)) {
8125 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
8126 return -1;
8128 from += 4;
8129 if ((a = strchr(from, '@')))
8130 *a++ = '\0';
8131 else
8132 a = from; /* just a domain */
8133 from = strsep(&from, ";"); /* Remove userinfo options */
8134 a = strsep(&a, ";"); /* Remove URI options */
8135 ast_string_field_set(p, fromdomain, a);
8138 /* Skip any options and find the domain */
8140 /* Get the target domain */
8141 if ((a = strchr(uri, '@'))) {
8142 *a++ = '\0';
8143 } else { /* No username part */
8144 a = uri;
8145 uri = "s"; /* Set extension to "s" */
8147 colon = strchr(a, ':'); /* Remove :port */
8148 if (colon)
8149 *colon = '\0';
8151 uri = strsep(&uri, ";"); /* Remove userinfo options */
8152 a = strsep(&a, ";"); /* Remove URI options */
8154 ast_string_field_set(p, domain, a);
8156 if (!AST_LIST_EMPTY(&domain_list)) {
8157 char domain_context[AST_MAX_EXTENSION];
8159 domain_context[0] = '\0';
8160 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
8161 if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
8162 ast_log(LOG_DEBUG, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
8163 return -2;
8166 /* If we have a context defined, overwrite the original context */
8167 if (!ast_strlen_zero(domain_context))
8168 ast_string_field_set(p, context, domain_context);
8171 if (sip_debug_test_pvt(p))
8172 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
8174 /* Check the dialplan for the username part of the request URI,
8175 the domain will be stored in the SIPDOMAIN variable
8176 Return 0 if we have a matching extension */
8177 if (ast_exists_extension(NULL, p->context, uri, 1, from) ||
8178 !strcmp(uri, ast_pickup_ext())) {
8179 if (!oreq)
8180 ast_string_field_set(p, exten, uri);
8181 return 0;
8184 /* Return 1 for pickup extension or overlap dialling support (if we support it) */
8185 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
8186 ast_canmatch_extension(NULL, p->context, uri, 1, from)) ||
8187 !strncmp(uri, ast_pickup_ext(), strlen(uri))) {
8188 return 1;
8191 return -1;
8194 /*! \brief Lock interface lock and find matching pvt lock
8195 - Their tag is fromtag, our tag is to-tag
8196 - This means that in some transactions, totag needs to be their tag :-)
8197 depending upon the direction
8199 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
8201 struct sip_pvt *sip_pvt_ptr;
8203 ast_mutex_lock(&iflock);
8205 if (option_debug > 3 && totag)
8206 ast_log(LOG_DEBUG, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
8208 /* Search interfaces and find the match */
8209 for (sip_pvt_ptr = iflist; sip_pvt_ptr; sip_pvt_ptr = sip_pvt_ptr->next) {
8210 if (!strcmp(sip_pvt_ptr->callid, callid)) {
8211 int match = 1;
8212 char *ourtag = sip_pvt_ptr->tag;
8214 /* Go ahead and lock it (and its owner) before returning */
8215 ast_mutex_lock(&sip_pvt_ptr->lock);
8217 /* Check if tags match. If not, this is not the call we want
8218 (With a forking SIP proxy, several call legs share the
8219 call id, but have different tags)
8221 if (pedanticsipchecking && (strcmp(fromtag, sip_pvt_ptr->theirtag) || strcmp(totag, ourtag)))
8222 match = 0;
8224 if (!match) {
8225 ast_mutex_unlock(&sip_pvt_ptr->lock);
8226 break;
8229 if (option_debug > 3 && totag)
8230 ast_log(LOG_DEBUG, "Matched %s call - their tag is %s Our tag is %s\n",
8231 ast_test_flag(&sip_pvt_ptr->flags[0], SIP_OUTGOING) ? "OUTGOING": "INCOMING",
8232 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
8234 /* deadlock avoidance... */
8235 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
8236 ast_mutex_unlock(&sip_pvt_ptr->lock);
8237 usleep(1);
8238 ast_mutex_lock(&sip_pvt_ptr->lock);
8240 break;
8243 ast_mutex_unlock(&iflock);
8244 if (option_debug > 3 && !sip_pvt_ptr)
8245 ast_log(LOG_DEBUG, "Found no match for callid %s to-tag %s from-tag %s\n", callid, totag, fromtag);
8246 return sip_pvt_ptr;
8249 /*! \brief Call transfer support (the REFER method)
8250 * Extracts Refer headers into pvt dialog structure */
8251 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
8254 const char *p_referred_by = NULL;
8255 char *h_refer_to = NULL;
8256 char *h_referred_by = NULL;
8257 char *refer_to;
8258 const char *p_refer_to;
8259 char *referred_by_uri = NULL;
8260 char *ptr;
8261 struct sip_request *req = NULL;
8262 const char *transfer_context = NULL;
8263 struct sip_refer *referdata;
8266 req = outgoing_req;
8267 referdata = transferer->refer;
8269 if (!req)
8270 req = &transferer->initreq;
8272 if (!(p_refer_to = get_header(req, "Refer-To"))) {
8273 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
8274 return -2; /* Syntax error */
8276 h_refer_to = ast_strdupa(p_refer_to);
8277 refer_to = get_in_brackets(h_refer_to);
8278 if (pedanticsipchecking)
8279 ast_uri_decode(refer_to);
8281 if (strncasecmp(refer_to, "sip:", 4)) {
8282 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
8283 return -3;
8285 refer_to += 4; /* Skip sip: */
8287 /* Get referred by header if it exists */
8288 if ((p_referred_by = get_header(req, "Referred-By"))) {
8289 char *lessthan;
8290 h_referred_by = ast_strdupa(p_referred_by);
8291 if (pedanticsipchecking)
8292 ast_uri_decode(h_referred_by);
8294 /* Store referrer's caller ID name */
8295 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
8296 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
8297 *(lessthan - 1) = '\0'; /* Space */
8300 referred_by_uri = get_in_brackets(h_referred_by);
8301 if(strncasecmp(referred_by_uri, "sip:", 4)) {
8302 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
8303 referred_by_uri = (char *) NULL;
8304 } else {
8305 referred_by_uri += 4; /* Skip sip: */
8309 /* Check for arguments in the refer_to header */
8310 if ((ptr = strchr(refer_to, '?'))) { /* Search for arguments */
8311 *ptr++ = '\0';
8312 if (!strncasecmp(ptr, "REPLACES=", 9)) {
8313 char *to = NULL, *from = NULL;
8315 /* This is an attended transfer */
8316 referdata->attendedtransfer = 1;
8317 strncpy(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
8318 ast_uri_decode(referdata->replaces_callid);
8319 if ((ptr = strchr(referdata->replaces_callid, ';'))) /* Find options */ {
8320 *ptr++ = '\0';
8323 if (ptr) {
8324 /* Find the different tags before we destroy the string */
8325 to = strcasestr(ptr, "to-tag=");
8326 from = strcasestr(ptr, "from-tag=");
8329 /* Grab the to header */
8330 if (to) {
8331 ptr = to + 7;
8332 if ((to = strchr(ptr, '&')))
8333 *to = '\0';
8334 if ((to = strchr(ptr, ';')))
8335 *to = '\0';
8336 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
8339 if (from) {
8340 ptr = from + 9;
8341 if ((to = strchr(ptr, '&')))
8342 *to = '\0';
8343 if ((to = strchr(ptr, ';')))
8344 *to = '\0';
8345 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
8348 if (option_debug > 1) {
8349 if (!pedanticsipchecking)
8350 ast_log(LOG_DEBUG,"Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
8351 else
8352 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>" );
8357 if ((ptr = strchr(refer_to, '@'))) { /* Separate domain */
8358 char *urioption;
8360 *ptr++ = '\0';
8361 if ((urioption = strchr(ptr, ';')))
8362 *urioption++ = '\0';
8363 /* Save the domain for the dial plan */
8364 strncpy(referdata->refer_to_domain, ptr, sizeof(referdata->refer_to_domain));
8365 if (urioption)
8366 strncpy(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
8369 if ((ptr = strchr(refer_to, ';'))) /* Remove options */
8370 *ptr = '\0';
8371 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
8373 if (referred_by_uri) {
8374 if ((ptr = strchr(referred_by_uri, ';'))) /* Remove options */
8375 *ptr = '\0';
8376 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
8377 } else {
8378 referdata->referred_by[0] = '\0';
8381 /* Determine transfer context */
8382 if (transferer->owner) /* Mimic behaviour in res_features.c */
8383 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
8385 /* By default, use the context in the channel sending the REFER */
8386 if (ast_strlen_zero(transfer_context)) {
8387 transfer_context = S_OR(transferer->owner->macrocontext,
8388 S_OR(transferer->context, default_context));
8391 strncpy(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
8393 /* Either an existing extension or the parking extension */
8394 if (ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
8395 if (sip_debug_test_pvt(transferer)) {
8396 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
8398 /* We are ready to transfer to the extension */
8399 return 0;
8401 if (sip_debug_test_pvt(transferer))
8402 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
8404 /* Failure, we can't find this extension */
8405 return -1;
8409 /*! \brief Call transfer support (old way, deprecated by the IETF)--*/
8410 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
8412 char tmp[256] = "", *c, *a;
8413 struct sip_request *req = oreq ? oreq : &p->initreq;
8414 struct sip_refer *referdata = p->refer;
8415 const char *transfer_context = NULL;
8417 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
8418 c = get_in_brackets(tmp);
8420 if (pedanticsipchecking)
8421 ast_uri_decode(c);
8423 if (strncmp(c, "sip:", 4)) {
8424 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
8425 return -1;
8427 c += 4;
8428 if ((a = strchr(c, '@'))) { /* Separate Domain */
8429 *a++ = '\0';
8430 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
8433 if ((a = strchr(c, ';'))) /* Remove arguments */
8434 *a = '\0';
8436 if (sip_debug_test_pvt(p))
8437 ast_verbose("Looking for %s in %s\n", c, p->context);
8439 if (p->owner) /* Mimic behaviour in res_features.c */
8440 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
8442 /* By default, use the context in the channel sending the REFER */
8443 if (ast_strlen_zero(transfer_context)) {
8444 transfer_context = S_OR(p->owner->macrocontext,
8445 S_OR(p->context, default_context));
8447 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
8448 /* This is a blind transfer */
8449 if (option_debug)
8450 ast_log(LOG_DEBUG,"SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
8451 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
8452 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
8453 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
8454 referdata->refer_call = NULL;
8455 /* Set new context */
8456 ast_string_field_set(p, context, transfer_context);
8457 return 0;
8458 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
8459 return 1;
8462 return -1;
8464 /*! \brief check Via: header for hostname, port and rport request/answer */
8465 static void check_via(struct sip_pvt *p, struct sip_request *req)
8467 char via[256];
8468 char *c, *pt;
8469 struct hostent *hp;
8470 struct ast_hostent ahp;
8472 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
8474 /* Check for rport */
8475 c = strstr(via, ";rport");
8476 if (c && (c[6] != '=')) /* rport query, not answer */
8477 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
8479 c = strchr(via, ';');
8480 if (c)
8481 *c = '\0';
8483 c = strchr(via, ' ');
8484 if (c) {
8485 *c = '\0';
8486 c = ast_skip_blanks(c+1);
8487 if (strcasecmp(via, "SIP/2.0/UDP")) {
8488 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
8489 return;
8491 pt = strchr(c, ':');
8492 if (pt)
8493 *pt++ = '\0'; /* remember port pointer */
8494 hp = ast_gethostbyname(c, &ahp);
8495 if (!hp) {
8496 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
8497 return;
8499 memset(&p->sa, 0, sizeof(p->sa));
8500 p->sa.sin_family = AF_INET;
8501 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
8502 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
8504 if (sip_debug_test_pvt(p)) {
8505 const struct sockaddr_in *dst = sip_real_dst(p);
8506 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
8511 /*! \brief Get caller id name from SIP headers */
8512 static char *get_calleridname(const char *input, char *output, size_t outputsize)
8514 const char *end = strchr(input,'<'); /* first_bracket */
8515 const char *tmp = strchr(input,'"'); /* first quote */
8516 int bytes = 0;
8517 int maxbytes = outputsize - 1;
8519 if (!end || end == input) /* we require a part in brackets */
8520 return NULL;
8522 /* move away from "<" */
8523 end--;
8525 /* we found "name" */
8526 if (tmp && tmp < end) {
8527 end = strchr(tmp+1, '"');
8528 if (!end)
8529 return NULL;
8530 bytes = (int) (end - tmp);
8531 /* protect the output buffer */
8532 if (bytes > maxbytes)
8533 bytes = maxbytes;
8534 ast_copy_string(output, tmp + 1, bytes);
8535 } else {
8536 /* we didn't find "name" */
8537 /* clear the empty characters in the begining*/
8538 input = ast_skip_blanks(input);
8539 /* clear the empty characters in the end */
8540 while(*end && *end < 33 && end > input)
8541 end--;
8542 if (end >= input) {
8543 bytes = (int) (end - input) + 2;
8544 /* protect the output buffer */
8545 if (bytes > maxbytes)
8546 bytes = maxbytes;
8547 ast_copy_string(output, input, bytes);
8548 } else
8549 return NULL;
8551 return output;
8554 /*! \brief Get caller id number from Remote-Party-ID header field
8555 * Returns true if number should be restricted (privacy setting found)
8556 * output is set to NULL if no number found
8558 static int get_rpid_num(const char *input, char *output, int maxlen)
8560 char *start;
8561 char *end;
8563 start = strchr(input,':');
8564 if (!start) {
8565 output[0] = '\0';
8566 return 0;
8568 start++;
8570 /* we found "number" */
8571 ast_copy_string(output,start,maxlen);
8572 output[maxlen-1] = '\0';
8574 end = strchr(output,'@');
8575 if (end)
8576 *end = '\0';
8577 else
8578 output[0] = '\0';
8579 if (strstr(input,"privacy=full") || strstr(input,"privacy=uri"))
8580 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
8582 return 0;
8586 /*! \brief Check if matching user or peer is defined
8587 Match user on From: user name and peer on IP/port
8588 This is used on first invite (not re-invites) and subscribe requests
8589 \return 0 on success, non-zero on failure
8591 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
8592 int sipmethod, char *uri, enum xmittype reliable,
8593 struct sockaddr_in *sin, struct sip_peer **authpeer)
8595 struct sip_user *user = NULL;
8596 struct sip_peer *peer;
8597 char from[256], *c;
8598 char *of;
8599 char rpid_num[50];
8600 const char *rpid;
8601 enum check_auth_result res = AUTH_SUCCESSFUL;
8602 char *t;
8603 char calleridname[50];
8604 int debug=sip_debug_test_addr(sin);
8605 struct ast_variable *tmpvar = NULL, *v = NULL;
8606 int usenatroute;
8607 char *uri2 = ast_strdupa(uri);
8609 /* Terminate URI */
8610 t = uri2;
8611 while (*t && *t > 32 && *t != ';')
8612 t++;
8613 *t = '\0';
8614 ast_copy_string(from, get_header(req, "From"), sizeof(from)); /* XXX bug in original code, overwrote string */
8615 if (pedanticsipchecking)
8616 ast_uri_decode(from);
8617 /* XXX here tries to map the username for invite things */
8618 memset(calleridname, 0, sizeof(calleridname));
8619 get_calleridname(from, calleridname, sizeof(calleridname));
8620 if (calleridname[0])
8621 ast_string_field_set(p, cid_name, calleridname);
8623 rpid = get_header(req, "Remote-Party-ID");
8624 memset(rpid_num, 0, sizeof(rpid_num));
8625 if (!ast_strlen_zero(rpid))
8626 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
8628 of = get_in_brackets(from);
8629 if (ast_strlen_zero(p->exten)) {
8630 t = uri2;
8631 if (!strncmp(t, "sip:", 4))
8632 t+= 4;
8633 ast_string_field_set(p, exten, t);
8634 t = strchr(p->exten, '@');
8635 if (t)
8636 *t = '\0';
8637 if (ast_strlen_zero(p->our_contact))
8638 build_contact(p);
8640 /* save the URI part of the From header */
8641 ast_string_field_set(p, from, of);
8642 if (strncmp(of, "sip:", 4)) {
8643 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
8644 } else
8645 of += 4;
8646 /* Get just the username part */
8647 if ((c = strchr(of, '@'))) {
8648 char *tmp;
8649 *c = '\0';
8650 if ((c = strchr(of, ':')))
8651 *c = '\0';
8652 tmp = ast_strdupa(of);
8653 if (ast_is_shrinkable_phonenumber(tmp))
8654 ast_shrink_phone_number(tmp);
8655 ast_string_field_set(p, cid_num, tmp);
8657 if (ast_strlen_zero(of))
8658 return AUTH_SUCCESSFUL;
8660 if (!authpeer) /* If we are looking for a peer, don't check the user objects (or realtime) */
8661 user = find_user(of, 1);
8663 /* Find user based on user name in the from header */
8664 if (user && ast_apply_ha(user->ha, sin)) {
8665 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
8666 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
8667 /* copy channel vars */
8668 for (v = user->chanvars ; v ; v = v->next) {
8669 if ((tmpvar = ast_variable_new(v->name, v->value))) {
8670 tmpvar->next = p->chanvars;
8671 p->chanvars = tmpvar;
8674 p->prefs = user->prefs;
8675 /* replace callerid if rpid found, and not restricted */
8676 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
8677 char *tmp;
8678 if (*calleridname)
8679 ast_string_field_set(p, cid_name, calleridname);
8680 tmp = ast_strdupa(rpid_num);
8681 if (ast_is_shrinkable_phonenumber(tmp))
8682 ast_shrink_phone_number(tmp);
8683 ast_string_field_set(p, cid_num, tmp);
8686 usenatroute = ast_test_flag(&p->flags[0], SIP_NAT_ROUTE);
8688 if (p->rtp) {
8689 if (option_debug)
8690 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", usenatroute ? "On" : "Off");
8691 ast_rtp_setnat(p->rtp, usenatroute);
8693 if (p->vrtp) {
8694 if (option_debug)
8695 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", usenatroute ? "On" : "Off");
8696 ast_rtp_setnat(p->vrtp, usenatroute);
8698 if (p->udptl) {
8699 if (option_debug)
8700 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", usenatroute ? "On" : "Off");
8701 ast_udptl_setnat(p->udptl, usenatroute);
8703 if (!(res = check_auth(p, req, user->name, user->secret, user->md5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
8704 sip_cancel_destroy(p);
8705 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
8706 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
8707 /* Copy SIP extensions profile from INVITE */
8708 if (p->sipoptions)
8709 user->sipoptions = p->sipoptions;
8711 /* If we have a call limit, set flag */
8712 if (user->call_limit)
8713 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
8714 if (!ast_strlen_zero(user->context))
8715 ast_string_field_set(p, context, user->context);
8716 if (!ast_strlen_zero(user->cid_num) && !ast_strlen_zero(p->cid_num)) {
8717 char *tmp = ast_strdupa(user->cid_num);
8718 if (ast_is_shrinkable_phonenumber(tmp))
8719 ast_shrink_phone_number(tmp);
8720 ast_string_field_set(p, cid_num, tmp);
8722 if (!ast_strlen_zero(user->cid_name) && !ast_strlen_zero(p->cid_num))
8723 ast_string_field_set(p, cid_name, user->cid_name);
8724 ast_string_field_set(p, username, user->name);
8725 ast_string_field_set(p, peername, user->name);
8726 ast_string_field_set(p, peersecret, user->secret);
8727 ast_string_field_set(p, peermd5secret, user->md5secret);
8728 ast_string_field_set(p, subscribecontext, user->subscribecontext);
8729 ast_string_field_set(p, accountcode, user->accountcode);
8730 ast_string_field_set(p, language, user->language);
8731 ast_string_field_set(p, mohsuggest, user->mohsuggest);
8732 ast_string_field_set(p, mohinterpret, user->mohinterpret);
8733 p->allowtransfer = user->allowtransfer;
8734 p->amaflags = user->amaflags;
8735 p->callgroup = user->callgroup;
8736 p->pickupgroup = user->pickupgroup;
8737 if (user->callingpres) /* User callingpres setting will override RPID header */
8738 p->callingpres = user->callingpres;
8740 /* Set default codec settings for this call */
8741 p->capability = user->capability; /* User codec choice */
8742 p->jointcapability = user->capability; /* Our codecs */
8743 if (p->peercapability) /* AND with peer's codecs */
8744 p->jointcapability &= p->peercapability;
8745 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
8746 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
8747 p->noncodeccapability |= AST_RTP_DTMF;
8748 else
8749 p->noncodeccapability &= ~AST_RTP_DTMF;
8750 if (p->t38.peercapability)
8751 p->t38.jointcapability &= p->t38.peercapability;
8752 p->maxcallbitrate = user->maxcallbitrate;
8753 /* If we do not support video, remove video from call structure */
8754 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && p->vrtp) {
8755 ast_rtp_destroy(p->vrtp);
8756 p->vrtp = NULL;
8759 if (user && debug)
8760 ast_verbose("Found user '%s'\n", user->name);
8761 } else {
8762 if (user) {
8763 if (!authpeer && debug)
8764 ast_verbose("Found user '%s', but fails host access\n", user->name);
8765 ASTOBJ_UNREF(user,sip_destroy_user);
8767 user = NULL;
8770 if (!user) {
8771 /* If we didn't find a user match, check for peers */
8772 if (sipmethod == SIP_SUBSCRIBE)
8773 /* For subscribes, match on peer name only */
8774 peer = find_peer(of, NULL, 1);
8775 else
8776 /* Look for peer based on the IP address we received data from */
8777 /* If peer is registered from this IP address or have this as a default
8778 IP address, this call is from the peer
8780 peer = find_peer(NULL, &p->recv, 1);
8782 if (peer) {
8783 if (debug)
8784 ast_verbose("Found peer '%s'\n", peer->name);
8786 /* Take the peer */
8787 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
8788 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
8790 /* Copy SIP extensions profile to peer */
8791 if (p->sipoptions)
8792 peer->sipoptions = p->sipoptions;
8794 /* replace callerid if rpid found, and not restricted */
8795 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
8796 char *tmp = ast_strdupa(rpid_num);
8797 if (*calleridname)
8798 ast_string_field_set(p, cid_name, calleridname);
8799 if (ast_is_shrinkable_phonenumber(tmp))
8800 ast_shrink_phone_number(tmp);
8801 ast_string_field_set(p, cid_num, tmp);
8803 usenatroute = ast_test_flag(&p->flags[0], SIP_NAT_ROUTE);
8804 if (p->rtp) {
8805 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", usenatroute ? "On" : "Off");
8806 ast_rtp_setnat(p->rtp, usenatroute);
8808 if (p->vrtp) {
8809 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", usenatroute ? "On" : "Off");
8810 ast_rtp_setnat(p->vrtp, usenatroute);
8812 if (p->udptl) {
8813 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", usenatroute ? "On" : "Off");
8814 ast_udptl_setnat(p->udptl, usenatroute);
8816 ast_string_field_set(p, peersecret, peer->secret);
8817 ast_string_field_set(p, peermd5secret, peer->md5secret);
8818 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
8819 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
8820 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
8821 if (peer->callingpres) /* Peer calling pres setting will override RPID */
8822 p->callingpres = peer->callingpres;
8823 if (peer->maxms && peer->lastms)
8824 p->timer_t1 = peer->lastms;
8825 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
8826 /* Pretend there is no required authentication */
8827 ast_string_field_free(p, peersecret);
8828 ast_string_field_free(p, peermd5secret);
8830 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
8831 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
8832 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
8833 /* If we have a call limit, set flag */
8834 if (peer->call_limit)
8835 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
8836 ast_string_field_set(p, peername, peer->name);
8837 ast_string_field_set(p, authname, peer->name);
8839 /* copy channel vars */
8840 for (v = peer->chanvars ; v ; v = v->next) {
8841 if ((tmpvar = ast_variable_new(v->name, v->value))) {
8842 tmpvar->next = p->chanvars;
8843 p->chanvars = tmpvar;
8846 if (authpeer) {
8847 (*authpeer) = ASTOBJ_REF(peer); /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
8850 if (!ast_strlen_zero(peer->username)) {
8851 ast_string_field_set(p, username, peer->username);
8852 /* Use the default username for authentication on outbound calls */
8853 /* XXX this takes the name from the caller... can we override ? */
8854 ast_string_field_set(p, authname, peer->username);
8856 if (!ast_strlen_zero(peer->cid_num) && !ast_strlen_zero(p->cid_num)) {
8857 char *tmp = ast_strdupa(peer->cid_num);
8858 if (ast_is_shrinkable_phonenumber(tmp))
8859 ast_shrink_phone_number(tmp);
8860 ast_string_field_set(p, cid_num, tmp);
8862 if (!ast_strlen_zero(peer->cid_name) && !ast_strlen_zero(p->cid_name))
8863 ast_string_field_set(p, cid_name, peer->cid_name);
8864 ast_string_field_set(p, fullcontact, peer->fullcontact);
8865 if (!ast_strlen_zero(peer->context))
8866 ast_string_field_set(p, context, peer->context);
8867 ast_string_field_set(p, peersecret, peer->secret);
8868 ast_string_field_set(p, peermd5secret, peer->md5secret);
8869 ast_string_field_set(p, language, peer->language);
8870 ast_string_field_set(p, accountcode, peer->accountcode);
8871 p->amaflags = peer->amaflags;
8872 p->callgroup = peer->callgroup;
8873 p->pickupgroup = peer->pickupgroup;
8874 p->capability = peer->capability;
8875 p->prefs = peer->prefs;
8876 p->jointcapability = peer->capability;
8877 if (p->peercapability)
8878 p->jointcapability &= p->peercapability;
8879 p->maxcallbitrate = peer->maxcallbitrate;
8880 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && p->vrtp) {
8881 ast_rtp_destroy(p->vrtp);
8882 p->vrtp = NULL;
8884 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
8885 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
8886 p->noncodeccapability |= AST_RTP_DTMF;
8887 else
8888 p->noncodeccapability &= ~AST_RTP_DTMF;
8889 if (p->t38.peercapability)
8890 p->t38.jointcapability &= p->t38.peercapability;
8892 ASTOBJ_UNREF(peer, sip_destroy_peer);
8893 } else {
8894 if (debug)
8895 ast_verbose("Found no matching peer or user for '%s:%d'\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
8897 /* do we allow guests? */
8898 if (!global_allowguest) {
8899 if (global_alwaysauthreject)
8900 res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
8901 else
8902 res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
8908 if (user)
8909 ASTOBJ_UNREF(user, sip_destroy_user);
8910 return res;
8913 /*! \brief Find user
8914 If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
8916 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
8918 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
8921 /*! \brief Get text out of a SIP MESSAGE packet */
8922 static int get_msg_text(char *buf, int len, struct sip_request *req)
8924 int x;
8925 int y;
8927 buf[0] = '\0';
8928 y = len - strlen(buf) - 5;
8929 if (y < 0)
8930 y = 0;
8931 for (x=0;x<req->lines;x++) {
8932 strncat(buf, req->line[x], y); /* safe */
8933 y -= strlen(req->line[x]) + 1;
8934 if (y < 0)
8935 y = 0;
8936 if (y != 0)
8937 strcat(buf, "\n"); /* safe */
8939 return 0;
8943 /*! \brief Receive SIP MESSAGE method messages
8944 \note We only handle messages within current calls currently
8945 Reference: RFC 3428 */
8946 static void receive_message(struct sip_pvt *p, struct sip_request *req)
8948 char buf[1024];
8949 struct ast_frame f;
8950 const char *content_type = get_header(req, "Content-Type");
8952 if (strcmp(content_type, "text/plain")) { /* No text/plain attachment */
8953 transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
8954 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
8955 return;
8958 if (get_msg_text(buf, sizeof(buf), req)) {
8959 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
8960 transmit_response(p, "202 Accepted", req);
8961 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
8962 return;
8965 if (p->owner) {
8966 if (sip_debug_test_pvt(p))
8967 ast_verbose("Message received: '%s'\n", buf);
8968 memset(&f, 0, sizeof(f));
8969 f.frametype = AST_FRAME_TEXT;
8970 f.subclass = 0;
8971 f.offset = 0;
8972 f.data = buf;
8973 f.datalen = strlen(buf);
8974 ast_queue_frame(p->owner, &f);
8975 transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
8976 } else { /* Message outside of a call, we do not support that */
8977 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);
8978 transmit_response(p, "405 Method Not Allowed", req); /* Good enough, or? */
8980 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
8981 return;
8984 /*! \brief CLI Command to show calls within limits set by call_limit */
8985 static int sip_show_inuse(int fd, int argc, char *argv[])
8987 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
8988 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
8989 char ilimits[40];
8990 char iused[40];
8991 int showall = FALSE;
8993 if (argc < 3)
8994 return RESULT_SHOWUSAGE;
8996 if (argc == 4 && !strcmp(argv[3],"all"))
8997 showall = TRUE;
8999 ast_cli(fd, FORMAT, "* User name", "In use", "Limit");
9000 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
9001 ASTOBJ_RDLOCK(iterator);
9002 if (iterator->call_limit)
9003 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
9004 else
9005 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
9006 snprintf(iused, sizeof(iused), "%d", iterator->inUse);
9007 if (showall || iterator->call_limit)
9008 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
9009 ASTOBJ_UNLOCK(iterator);
9010 } while (0) );
9012 ast_cli(fd, FORMAT, "* Peer name", "In use", "Limit");
9014 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
9015 ASTOBJ_RDLOCK(iterator);
9016 if (iterator->call_limit)
9017 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
9018 else
9019 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
9020 snprintf(iused, sizeof(iused), "%d/%d", iterator->inUse, iterator->inRinging);
9021 if (showall || iterator->call_limit)
9022 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
9023 ASTOBJ_UNLOCK(iterator);
9024 } while (0) );
9026 return RESULT_SUCCESS;
9027 #undef FORMAT
9028 #undef FORMAT2
9031 /*! \brief Convert transfer mode to text string */
9032 static char *transfermode2str(enum transfermodes mode)
9034 if (mode == TRANSFER_OPENFORALL)
9035 return "open";
9036 else if (mode == TRANSFER_CLOSED)
9037 return "closed";
9038 return "strict";
9041 /*! \brief Convert NAT setting to text string */
9042 static char *nat2str(int nat)
9044 switch(nat) {
9045 case SIP_NAT_NEVER:
9046 return "No";
9047 case SIP_NAT_ROUTE:
9048 return "Route";
9049 case SIP_NAT_ALWAYS:
9050 return "Always";
9051 case SIP_NAT_RFC3581:
9052 return "RFC3581";
9053 default:
9054 return "Unknown";
9058 /*! \brief Report Peer status in character string
9059 * \return 1 if peer is online, -1 if unmonitored */
9060 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
9062 int res = 0;
9063 if (peer->maxms) {
9064 if (peer->lastms < 0) {
9065 ast_copy_string(status, "UNREACHABLE", statuslen);
9066 } else if (peer->lastms > peer->maxms) {
9067 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
9068 res = 1;
9069 } else if (peer->lastms) {
9070 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
9071 res = 1;
9072 } else {
9073 ast_copy_string(status, "UNKNOWN", statuslen);
9075 } else {
9076 ast_copy_string(status, "Unmonitored", statuslen);
9077 /* Checking if port is 0 */
9078 res = -1;
9080 return res;
9083 /*! \brief CLI Command 'SIP Show Users' */
9084 static int sip_show_users(int fd, int argc, char *argv[])
9086 regex_t regexbuf;
9087 int havepattern = FALSE;
9089 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
9091 switch (argc) {
9092 case 5:
9093 if (!strcasecmp(argv[3], "like")) {
9094 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
9095 return RESULT_SHOWUSAGE;
9096 havepattern = TRUE;
9097 } else
9098 return RESULT_SHOWUSAGE;
9099 case 3:
9100 break;
9101 default:
9102 return RESULT_SHOWUSAGE;
9105 ast_cli(fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
9106 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
9107 ASTOBJ_RDLOCK(iterator);
9109 if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
9110 ASTOBJ_UNLOCK(iterator);
9111 continue;
9114 ast_cli(fd, FORMAT, iterator->name,
9115 iterator->secret,
9116 iterator->accountcode,
9117 iterator->context,
9118 iterator->ha ? "Yes" : "No",
9119 nat2str(ast_test_flag(&iterator->flags[0], SIP_NAT)));
9120 ASTOBJ_UNLOCK(iterator);
9121 } while (0)
9124 if (havepattern)
9125 regfree(&regexbuf);
9127 return RESULT_SUCCESS;
9128 #undef FORMAT
9131 static char mandescr_show_peers[] =
9132 "Description: Lists SIP peers in text format with details on current status.\n"
9133 "Variables: \n"
9134 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
9136 /*! \brief Show SIP peers in the manager API */
9137 /* Inspired from chan_iax2 */
9138 static int manager_sip_show_peers( struct mansession *s, struct message *m )
9140 char *id = astman_get_header(m,"ActionID");
9141 char *a[] = { "sip", "show", "peers" };
9142 char idtext[256] = "";
9143 int total = 0;
9145 if (!ast_strlen_zero(id))
9146 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
9148 astman_send_ack(s, m, "Peer status list will follow");
9149 /* List the peers in separate manager events */
9150 _sip_show_peers(-1, &total, s, m, 3, a);
9151 /* Send final confirmation */
9152 astman_append(s,
9153 "Event: PeerlistComplete\r\n"
9154 "ListItems: %d\r\n"
9155 "%s"
9156 "\r\n", total, idtext);
9157 return 0;
9160 /*! \brief CLI Show Peers command */
9161 static int sip_show_peers(int fd, int argc, char *argv[])
9163 return _sip_show_peers(fd, NULL, NULL, NULL, argc, argv);
9166 /*! \brief _sip_show_peers: Execute sip show peers command */
9167 static int _sip_show_peers(int fd, int *total, struct mansession *s, struct message *m, int argc, char *argv[])
9169 regex_t regexbuf;
9170 int havepattern = FALSE;
9172 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %-10s\n"
9173 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %-10s\n"
9175 char name[256];
9176 int total_peers = 0;
9177 int peers_online = 0;
9178 int peers_offline = 0;
9179 char *id;
9180 char idtext[256] = "";
9181 int realtimepeers;
9183 realtimepeers = ast_check_realtime("sippeers");
9185 if (s) { /* Manager - get ActionID */
9186 id = astman_get_header(m,"ActionID");
9187 if (!ast_strlen_zero(id))
9188 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
9191 switch (argc) {
9192 case 5:
9193 if (!strcasecmp(argv[3], "like")) {
9194 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
9195 return RESULT_SHOWUSAGE;
9196 havepattern = TRUE;
9197 } else
9198 return RESULT_SHOWUSAGE;
9199 case 3:
9200 break;
9201 default:
9202 return RESULT_SHOWUSAGE;
9205 if (!s) { /* Normal list */
9206 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
9209 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
9210 char status[20] = "";
9211 char srch[2000];
9212 char pstatus;
9214 ASTOBJ_RDLOCK(iterator);
9216 if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
9217 ASTOBJ_UNLOCK(iterator);
9218 continue;
9221 if (!ast_strlen_zero(iterator->username) && !s)
9222 snprintf(name, sizeof(name), "%s/%s", iterator->name, iterator->username);
9223 else
9224 ast_copy_string(name, iterator->name, sizeof(name));
9226 pstatus = peer_status(iterator, status, sizeof(status));
9227 if (pstatus)
9228 peers_online++;
9229 else {
9230 if (pstatus == 0)
9231 peers_offline++;
9232 else { /* Unmonitored */
9233 /* Checking if port is 0 */
9234 if ( ntohs(iterator->addr.sin_port) == 0 ) {
9235 peers_offline++;
9236 } else {
9237 peers_online++;
9242 snprintf(srch, sizeof(srch), FORMAT, name,
9243 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
9244 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ", /* Dynamic or not? */
9245 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
9246 iterator->ha ? " A " : " ", /* permit/deny */
9247 ntohs(iterator->addr.sin_port), status,
9248 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
9250 if (!s) {/* Normal CLI list */
9251 ast_cli(fd, FORMAT, name,
9252 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
9253 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ", /* Dynamic or not? */
9254 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
9255 iterator->ha ? " A " : " ", /* permit/deny */
9257 ntohs(iterator->addr.sin_port), status,
9258 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
9259 } else { /* Manager format */
9260 /* The names here need to be the same as other channels */
9261 astman_append(s,
9262 "Event: PeerEntry\r\n%s"
9263 "Channeltype: SIP\r\n"
9264 "ObjectName: %s\r\n"
9265 "ChanObjectType: peer\r\n" /* "peer" or "user" */
9266 "IPaddress: %s\r\n"
9267 "IPport: %d\r\n"
9268 "Dynamic: %s\r\n"
9269 "Natsupport: %s\r\n"
9270 "Video Support: %s\r\n"
9271 "ACL: %s\r\n"
9272 "Status: %s\r\n"
9273 "RealtimeDevice: %s\r\n\r\n",
9274 idtext,
9275 iterator->name,
9276 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "-none-",
9277 ntohs(iterator->addr.sin_port),
9278 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no", /* Dynamic or not? */
9279 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? "yes" : "no", /* NAT=yes? */
9280 ast_test_flag(&iterator->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no", /* VIDEOSUPPORT=yes? */
9281 iterator->ha ? "yes" : "no", /* permit/deny */
9282 status,
9283 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "yes":"no") : "no");
9286 ASTOBJ_UNLOCK(iterator);
9288 total_peers++;
9289 } while(0) );
9291 if (!s) {
9292 ast_cli(fd,"%d sip peers [%d online , %d offline]\n",total_peers,peers_online,peers_offline);
9295 if (havepattern)
9296 regfree(&regexbuf);
9298 if (total)
9299 *total = total_peers;
9302 return RESULT_SUCCESS;
9303 #undef FORMAT
9304 #undef FORMAT2
9307 /*! \brief List all allocated SIP Objects (realtime or static) */
9308 static int sip_show_objects(int fd, int argc, char *argv[])
9310 char tmp[256];
9311 if (argc != 3)
9312 return RESULT_SHOWUSAGE;
9313 ast_cli(fd, "-= User objects: %d static, %d realtime =-\n\n", suserobjs, ruserobjs);
9314 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &userl);
9315 ast_cli(fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
9316 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &peerl);
9317 ast_cli(fd, "-= Registry objects: %d =-\n\n", regobjs);
9318 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &regl);
9319 return RESULT_SUCCESS;
9321 /*! \brief Print call group and pickup group */
9322 static void print_group(int fd, unsigned int group, int crlf)
9324 char buf[256];
9325 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
9328 /*! \brief Convert DTMF mode to printable string */
9329 static const char *dtmfmode2str(int mode)
9331 switch (mode) {
9332 case SIP_DTMF_RFC2833:
9333 return "rfc2833";
9334 case SIP_DTMF_INFO:
9335 return "info";
9336 case SIP_DTMF_INBAND:
9337 return "inband";
9338 case SIP_DTMF_AUTO:
9339 return "auto";
9341 return "<error>";
9344 /*! \brief Convert Insecure setting to printable string */
9345 static const char *insecure2str(int port, int invite)
9347 if (port && invite)
9348 return "port,invite";
9349 else if (port)
9350 return "port";
9351 else if (invite)
9352 return "invite";
9353 else
9354 return "no";
9357 /*! \brief Destroy disused contexts between reloads
9358 Only used in reload_config so the code for regcontext doesn't get ugly
9360 static void cleanup_stale_contexts(char *new, char *old)
9362 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
9364 while ((oldcontext = strsep(&old, "&"))) {
9365 stalecontext = '\0';
9366 ast_copy_string(newlist, new, sizeof(newlist));
9367 stringp = newlist;
9368 while ((newcontext = strsep(&stringp, "&"))) {
9369 if (strcmp(newcontext, oldcontext) == 0) {
9370 /* This is not the context you're looking for */
9371 stalecontext = '\0';
9372 break;
9373 } else if (strcmp(newcontext, oldcontext)) {
9374 stalecontext = oldcontext;
9378 if (stalecontext)
9379 ast_context_destroy(ast_context_find(stalecontext), "SIP");
9383 /*! \brief Remove temporary realtime objects from memory (CLI) */
9384 static int sip_prune_realtime(int fd, int argc, char *argv[])
9386 struct sip_peer *peer;
9387 struct sip_user *user;
9388 int pruneuser = FALSE;
9389 int prunepeer = FALSE;
9390 int multi = FALSE;
9391 char *name = NULL;
9392 regex_t regexbuf;
9394 switch (argc) {
9395 case 4:
9396 if (!strcasecmp(argv[3], "user"))
9397 return RESULT_SHOWUSAGE;
9398 if (!strcasecmp(argv[3], "peer"))
9399 return RESULT_SHOWUSAGE;
9400 if (!strcasecmp(argv[3], "like"))
9401 return RESULT_SHOWUSAGE;
9402 if (!strcasecmp(argv[3], "all")) {
9403 multi = TRUE;
9404 pruneuser = prunepeer = TRUE;
9405 } else {
9406 pruneuser = prunepeer = TRUE;
9407 name = argv[3];
9409 break;
9410 case 5:
9411 if (!strcasecmp(argv[4], "like"))
9412 return RESULT_SHOWUSAGE;
9413 if (!strcasecmp(argv[3], "all"))
9414 return RESULT_SHOWUSAGE;
9415 if (!strcasecmp(argv[3], "like")) {
9416 multi = TRUE;
9417 name = argv[4];
9418 pruneuser = prunepeer = TRUE;
9419 } else if (!strcasecmp(argv[3], "user")) {
9420 pruneuser = TRUE;
9421 if (!strcasecmp(argv[4], "all"))
9422 multi = TRUE;
9423 else
9424 name = argv[4];
9425 } else if (!strcasecmp(argv[3], "peer")) {
9426 prunepeer = TRUE;
9427 if (!strcasecmp(argv[4], "all"))
9428 multi = TRUE;
9429 else
9430 name = argv[4];
9431 } else
9432 return RESULT_SHOWUSAGE;
9433 break;
9434 case 6:
9435 if (strcasecmp(argv[4], "like"))
9436 return RESULT_SHOWUSAGE;
9437 if (!strcasecmp(argv[3], "user")) {
9438 pruneuser = TRUE;
9439 name = argv[5];
9440 } else if (!strcasecmp(argv[3], "peer")) {
9441 prunepeer = TRUE;
9442 name = argv[5];
9443 } else
9444 return RESULT_SHOWUSAGE;
9445 break;
9446 default:
9447 return RESULT_SHOWUSAGE;
9450 if (multi && name) {
9451 if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
9452 return RESULT_SHOWUSAGE;
9455 if (multi) {
9456 if (prunepeer) {
9457 int pruned = 0;
9459 ASTOBJ_CONTAINER_WRLOCK(&peerl);
9460 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
9461 ASTOBJ_RDLOCK(iterator);
9462 if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
9463 ASTOBJ_UNLOCK(iterator);
9464 continue;
9466 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
9467 ASTOBJ_MARK(iterator);
9468 pruned++;
9470 ASTOBJ_UNLOCK(iterator);
9471 } while (0) );
9472 if (pruned) {
9473 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
9474 ast_cli(fd, "%d peers pruned.\n", pruned);
9475 } else
9476 ast_cli(fd, "No peers found to prune.\n");
9477 ASTOBJ_CONTAINER_UNLOCK(&peerl);
9479 if (pruneuser) {
9480 int pruned = 0;
9482 ASTOBJ_CONTAINER_WRLOCK(&userl);
9483 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
9484 ASTOBJ_RDLOCK(iterator);
9485 if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
9486 ASTOBJ_UNLOCK(iterator);
9487 continue;
9489 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
9490 ASTOBJ_MARK(iterator);
9491 pruned++;
9493 ASTOBJ_UNLOCK(iterator);
9494 } while (0) );
9495 if (pruned) {
9496 ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, sip_destroy_user);
9497 ast_cli(fd, "%d users pruned.\n", pruned);
9498 } else
9499 ast_cli(fd, "No users found to prune.\n");
9500 ASTOBJ_CONTAINER_UNLOCK(&userl);
9502 } else {
9503 if (prunepeer) {
9504 if ((peer = ASTOBJ_CONTAINER_FIND_UNLINK(&peerl, name))) {
9505 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
9506 ast_cli(fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
9507 ASTOBJ_CONTAINER_LINK(&peerl, peer);
9508 } else
9509 ast_cli(fd, "Peer '%s' pruned.\n", name);
9510 ASTOBJ_UNREF(peer, sip_destroy_peer);
9511 } else
9512 ast_cli(fd, "Peer '%s' not found.\n", name);
9514 if (pruneuser) {
9515 if ((user = ASTOBJ_CONTAINER_FIND_UNLINK(&userl, name))) {
9516 if (!ast_test_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
9517 ast_cli(fd, "User '%s' is not a Realtime user, cannot be pruned.\n", name);
9518 ASTOBJ_CONTAINER_LINK(&userl, user);
9519 } else
9520 ast_cli(fd, "User '%s' pruned.\n", name);
9521 ASTOBJ_UNREF(user, sip_destroy_user);
9522 } else
9523 ast_cli(fd, "User '%s' not found.\n", name);
9527 return RESULT_SUCCESS;
9530 /*! \brief Print codec list from preference to CLI/manager */
9531 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
9533 int x, codec;
9535 for(x = 0; x < 32 ; x++) {
9536 codec = ast_codec_pref_index(pref, x);
9537 if (!codec)
9538 break;
9539 ast_cli(fd, "%s", ast_getformatname(codec));
9540 if (x < 31 && ast_codec_pref_index(pref, x + 1))
9541 ast_cli(fd, ",");
9543 if (!x)
9544 ast_cli(fd, "none");
9547 /*! \brief Print domain mode to cli */
9548 static const char *domain_mode_to_text(const enum domain_mode mode)
9550 switch (mode) {
9551 case SIP_DOMAIN_AUTO:
9552 return "[Automatic]";
9553 case SIP_DOMAIN_CONFIG:
9554 return "[Configured]";
9557 return "";
9560 /*! \brief CLI command to list local domains */
9561 static int sip_show_domains(int fd, int argc, char *argv[])
9563 struct domain *d;
9564 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
9566 if (AST_LIST_EMPTY(&domain_list)) {
9567 ast_cli(fd, "SIP Domain support not enabled.\n\n");
9568 return RESULT_SUCCESS;
9569 } else {
9570 ast_cli(fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
9571 AST_LIST_LOCK(&domain_list);
9572 AST_LIST_TRAVERSE(&domain_list, d, list)
9573 ast_cli(fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
9574 domain_mode_to_text(d->mode));
9575 AST_LIST_UNLOCK(&domain_list);
9576 ast_cli(fd, "\n");
9577 return RESULT_SUCCESS;
9580 #undef FORMAT
9582 static char mandescr_show_peer[] =
9583 "Description: Show one SIP peer with details on current status.\n"
9584 "Variables: \n"
9585 " Peer: <name> The peer name you want to check.\n"
9586 " ActionID: <id> Optional action ID for this AMI transaction.\n";
9588 /*! \brief Show SIP peers in the manager API */
9589 static int manager_sip_show_peer( struct mansession *s, struct message *m)
9591 char *id = astman_get_header(m,"ActionID");
9592 char *a[4];
9593 char *peer;
9594 int ret;
9596 peer = astman_get_header(m,"Peer");
9597 if (ast_strlen_zero(peer)) {
9598 astman_send_error(s, m, "Peer: <name> missing.\n");
9599 return 0;
9601 a[0] = "sip";
9602 a[1] = "show";
9603 a[2] = "peer";
9604 a[3] = peer;
9606 if (!ast_strlen_zero(id))
9607 astman_append(s, "ActionID: %s\r\n",id);
9608 ret = _sip_show_peer(1, -1, s, m, 4, a );
9609 astman_append(s, "\r\n\r\n" );
9610 return ret;
9615 /*! \brief Show one peer in detail */
9616 static int sip_show_peer(int fd, int argc, char *argv[])
9618 return _sip_show_peer(0, fd, NULL, NULL, argc, argv);
9621 /*! \brief Show one peer in detail (main function) */
9622 static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[])
9624 char status[30] = "";
9625 char cbuf[256];
9626 struct sip_peer *peer;
9627 char codec_buf[512];
9628 struct ast_codec_pref *pref;
9629 struct ast_variable *v;
9630 struct sip_auth *auth;
9631 int x = 0, codec = 0, load_realtime;
9632 int realtimepeers;
9634 realtimepeers = ast_check_realtime("sippeers");
9636 if (argc < 4)
9637 return RESULT_SHOWUSAGE;
9639 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
9640 peer = find_peer(argv[3], NULL, load_realtime);
9641 if (s) { /* Manager */
9642 if (peer)
9643 astman_append(s, "Response: Success\r\n");
9644 else {
9645 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.\n", argv[3]);
9646 astman_send_error(s, m, cbuf);
9647 return 0;
9650 if (peer && type==0 ) { /* Normal listing */
9651 ast_cli(fd,"\n\n");
9652 ast_cli(fd, " * Name : %s\n", peer->name);
9653 if (realtimepeers) { /* Realtime is enabled */
9654 ast_cli(fd, " Realtime peer: %s\n", ast_test_flag(&peer->flags[0], SIP_REALTIME) ? "Yes, cached" : "No");
9656 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
9657 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
9658 for (auth = peer->auth; auth; auth = auth->next) {
9659 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
9660 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
9662 ast_cli(fd, " Context : %s\n", peer->context);
9663 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
9664 ast_cli(fd, " Language : %s\n", peer->language);
9665 if (!ast_strlen_zero(peer->accountcode))
9666 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
9667 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
9668 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
9669 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
9670 if (!ast_strlen_zero(peer->fromuser))
9671 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
9672 if (!ast_strlen_zero(peer->fromdomain))
9673 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
9674 ast_cli(fd, " Callgroup : ");
9675 print_group(fd, peer->callgroup, 0);
9676 ast_cli(fd, " Pickupgroup : ");
9677 print_group(fd, peer->pickupgroup, 0);
9678 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
9679 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
9680 ast_cli(fd, " LastMsgsSent : %d\n", peer->lastmsgssent);
9681 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
9682 ast_cli(fd, " Dynamic : %s\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Yes":"No"));
9683 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
9684 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
9685 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
9686 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)));
9687 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
9688 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
9689 ast_cli(fd, " T38 pt UDPTL : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL)?"Yes":"No");
9690 ast_cli(fd, " T38 pt RTP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_RTP)?"Yes":"No");
9691 ast_cli(fd, " T38 pt TCP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_TCP)?"Yes":"No");
9692 ast_cli(fd, " CanReinvite : %s\n", ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Yes":"No");
9693 ast_cli(fd, " PromiscRedir : %s\n", ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Yes":"No");
9694 ast_cli(fd, " User=Phone : %s\n", ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Yes":"No");
9695 ast_cli(fd, " Video Support: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Yes":"No");
9696 ast_cli(fd, " Trust RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_TRUSTRPID) ? "Yes" : "No");
9697 ast_cli(fd, " Send RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_SENDRPID) ? "Yes" : "No");
9698 ast_cli(fd, " Subscriptions: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
9699 ast_cli(fd, " Overlap dial : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
9701 /* - is enumerated */
9702 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
9703 ast_cli(fd, " LastMsg : %d\n", peer->lastmsg);
9704 ast_cli(fd, " ToHost : %s\n", peer->tohost);
9705 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));
9706 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
9707 if (!ast_strlen_zero(global_regcontext))
9708 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
9709 ast_cli(fd, " Def. Username: %s\n", peer->username);
9710 ast_cli(fd, " SIP Options : ");
9711 if (peer->sipoptions) {
9712 int lastoption = -1;
9713 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
9714 if (sip_options[x].id != lastoption) {
9715 if (peer->sipoptions & sip_options[x].id)
9716 ast_cli(fd, "%s ", sip_options[x].text);
9717 lastoption = x;
9720 } else
9721 ast_cli(fd, "(none)");
9723 ast_cli(fd, "\n");
9724 ast_cli(fd, " Codecs : ");
9725 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
9726 ast_cli(fd, "%s\n", codec_buf);
9727 ast_cli(fd, " Codec Order : (");
9728 print_codec_to_cli(fd, &peer->prefs);
9729 ast_cli(fd, ")\n");
9731 ast_cli(fd, " Status : ");
9732 peer_status(peer, status, sizeof(status));
9733 ast_cli(fd, "%s\n",status);
9734 ast_cli(fd, " Useragent : %s\n", peer->useragent);
9735 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
9736 if (peer->chanvars) {
9737 ast_cli(fd, " Variables :\n");
9738 for (v = peer->chanvars ; v ; v = v->next)
9739 ast_cli(fd, " %s = %s\n", v->name, v->value);
9741 ast_cli(fd,"\n");
9742 ASTOBJ_UNREF(peer,sip_destroy_peer);
9743 } else if (peer && type == 1) { /* manager listing */
9744 char buf[256];
9745 astman_append(s, "Channeltype: SIP\r\n");
9746 astman_append(s, "ObjectName: %s\r\n", peer->name);
9747 astman_append(s, "ChanObjectType: peer\r\n");
9748 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
9749 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
9750 astman_append(s, "Context: %s\r\n", peer->context);
9751 astman_append(s, "Language: %s\r\n", peer->language);
9752 if (!ast_strlen_zero(peer->accountcode))
9753 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
9754 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
9755 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
9756 if (!ast_strlen_zero(peer->fromuser))
9757 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
9758 if (!ast_strlen_zero(peer->fromdomain))
9759 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
9760 astman_append(s, "Callgroup: ");
9761 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->callgroup));
9762 astman_append(s, "Pickupgroup: ");
9763 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->pickupgroup));
9764 astman_append(s, "VoiceMailbox: %s\r\n", peer->mailbox);
9765 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
9766 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
9767 astman_append(s, "Call limit: %d\r\n", peer->call_limit);
9768 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
9769 astman_append(s, "Dynamic: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Y":"N"));
9770 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
9771 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched,peer->expire));
9772 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)));
9773 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
9774 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
9775 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
9776 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
9777 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
9778 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
9780 /* - is enumerated */
9781 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
9782 astman_append(s, "SIPLastMsg: %d\r\n", peer->lastmsg);
9783 astman_append(s, "ToHost: %s\r\n", peer->tohost);
9784 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));
9785 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));
9786 astman_append(s, "Default-Username: %s\r\n", peer->username);
9787 if (!ast_strlen_zero(global_regcontext))
9788 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
9789 astman_append(s, "Codecs: ");
9790 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
9791 astman_append(s, "%s\r\n", codec_buf);
9792 astman_append(s, "CodecOrder: ");
9793 pref = &peer->prefs;
9794 for(x = 0; x < 32 ; x++) {
9795 codec = ast_codec_pref_index(pref,x);
9796 if (!codec)
9797 break;
9798 astman_append(s, "%s", ast_getformatname(codec));
9799 if (x < 31 && ast_codec_pref_index(pref,x+1))
9800 astman_append(s, ",");
9803 astman_append(s, "\r\n");
9804 astman_append(s, "Status: ");
9805 peer_status(peer, status, sizeof(status));
9806 astman_append(s, "%s\r\n", status);
9807 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
9808 astman_append(s, "Reg-Contact : %s\r\n", peer->fullcontact);
9809 if (peer->chanvars) {
9810 for (v = peer->chanvars ; v ; v = v->next) {
9811 astman_append(s, "ChanVariable:\n");
9812 astman_append(s, " %s,%s\r\n", v->name, v->value);
9816 ASTOBJ_UNREF(peer,sip_destroy_peer);
9818 } else {
9819 ast_cli(fd,"Peer %s not found.\n", argv[3]);
9820 ast_cli(fd,"\n");
9823 return RESULT_SUCCESS;
9826 /*! \brief Show one user in detail */
9827 static int sip_show_user(int fd, int argc, char *argv[])
9829 char cbuf[256];
9830 struct sip_user *user;
9831 struct ast_variable *v;
9832 int load_realtime;
9834 if (argc < 4)
9835 return RESULT_SHOWUSAGE;
9837 /* Load from realtime storage? */
9838 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
9840 user = find_user(argv[3], load_realtime);
9841 if (user) {
9842 ast_cli(fd,"\n\n");
9843 ast_cli(fd, " * Name : %s\n", user->name);
9844 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
9845 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
9846 ast_cli(fd, " Context : %s\n", user->context);
9847 ast_cli(fd, " Language : %s\n", user->language);
9848 if (!ast_strlen_zero(user->accountcode))
9849 ast_cli(fd, " Accountcode : %s\n", user->accountcode);
9850 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
9851 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
9852 ast_cli(fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
9853 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
9854 ast_cli(fd, " Call limit : %d\n", user->call_limit);
9855 ast_cli(fd, " Callgroup : ");
9856 print_group(fd, user->callgroup, 0);
9857 ast_cli(fd, " Pickupgroup : ");
9858 print_group(fd, user->pickupgroup, 0);
9859 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
9860 ast_cli(fd, " ACL : %s\n", (user->ha?"Yes":"No"));
9861 ast_cli(fd, " Codec Order : (");
9862 print_codec_to_cli(fd, &user->prefs);
9863 ast_cli(fd, ")\n");
9865 if (user->chanvars) {
9866 ast_cli(fd, " Variables :\n");
9867 for (v = user->chanvars ; v ; v = v->next)
9868 ast_cli(fd, " %s = %s\n", v->name, v->value);
9870 ast_cli(fd,"\n");
9871 ASTOBJ_UNREF(user,sip_destroy_user);
9872 } else {
9873 ast_cli(fd,"User %s not found.\n", argv[3]);
9874 ast_cli(fd,"\n");
9877 return RESULT_SUCCESS;
9880 /*! \brief Show SIP Registry (registrations with other SIP proxies */
9881 static int sip_show_registry(int fd, int argc, char *argv[])
9883 #define FORMAT2 "%-30.30s %-12.12s %8.8s %-20.20s %-25.25s\n"
9884 #define FORMAT "%-30.30s %-12.12s %8d %-20.20s %-25.25s\n"
9885 char host[80];
9886 char tmpdat[256];
9887 struct tm tm;
9890 if (argc != 3)
9891 return RESULT_SHOWUSAGE;
9892 ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State", "Reg.Time");
9893 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
9894 ASTOBJ_RDLOCK(iterator);
9895 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : DEFAULT_SIP_PORT);
9896 if (iterator->regtime) {
9897 ast_localtime(&iterator->regtime, &tm, NULL);
9898 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
9899 } else {
9900 tmpdat[0] = 0;
9902 ast_cli(fd, FORMAT, host, iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
9903 ASTOBJ_UNLOCK(iterator);
9904 } while(0));
9905 return RESULT_SUCCESS;
9906 #undef FORMAT
9907 #undef FORMAT2
9910 /*! \brief List global settings for the SIP channel */
9911 static int sip_show_settings(int fd, int argc, char *argv[])
9913 int realtimepeers;
9914 int realtimeusers;
9916 realtimepeers = ast_check_realtime("sippeers");
9917 realtimeusers = ast_check_realtime("sipusers");
9919 if (argc != 3)
9920 return RESULT_SHOWUSAGE;
9921 ast_cli(fd, "\n\nGlobal Settings:\n");
9922 ast_cli(fd, "----------------\n");
9923 ast_cli(fd, " SIP Port: %d\n", ntohs(bindaddr.sin_port));
9924 ast_cli(fd, " Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
9925 ast_cli(fd, " Videosupport: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "Yes" : "No");
9926 ast_cli(fd, " AutoCreatePeer: %s\n", autocreatepeer ? "Yes" : "No");
9927 ast_cli(fd, " Allow unknown access: %s\n", global_allowguest ? "Yes" : "No");
9928 ast_cli(fd, " Allow subscriptions: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
9929 ast_cli(fd, " Allow overlap dialing: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
9930 ast_cli(fd, " Promsic. redir: %s\n", ast_test_flag(&global_flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
9931 ast_cli(fd, " SIP domain support: %s\n", AST_LIST_EMPTY(&domain_list) ? "No" : "Yes");
9932 ast_cli(fd, " Call to non-local dom.: %s\n", allow_external_domains ? "Yes" : "No");
9933 ast_cli(fd, " URI user is phone no: %s\n", ast_test_flag(&global_flags[0], SIP_USEREQPHONE) ? "Yes" : "No");
9934 ast_cli(fd, " Our auth realm %s\n", global_realm);
9935 ast_cli(fd, " Realm. auth: %s\n", authl ? "Yes": "No");
9936 ast_cli(fd, " Always auth rejects: %s\n", global_alwaysauthreject ? "Yes" : "No");
9937 ast_cli(fd, " User Agent: %s\n", global_useragent);
9938 ast_cli(fd, " MWI checking interval: %d secs\n", global_mwitime);
9939 ast_cli(fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
9940 ast_cli(fd, " Caller ID: %s\n", default_callerid);
9941 ast_cli(fd, " From: Domain: %s\n", default_fromdomain);
9942 ast_cli(fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
9943 ast_cli(fd, " Call Events: %s\n", global_callevents ? "On" : "Off");
9944 ast_cli(fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
9945 ast_cli(fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
9946 ast_cli(fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
9947 ast_cli(fd, " T38 fax pt UDPTL: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_UDPTL) ? "Yes" : "No");
9948 ast_cli(fd, " T38 fax pt RTP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_RTP) ? "Yes" : "No");
9949 ast_cli(fd, " T38 fax pt TCP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_TCP) ? "Yes" : "No");
9950 if (!realtimepeers && !realtimeusers)
9951 ast_cli(fd, " SIP realtime: Disabled\n" );
9952 else
9953 ast_cli(fd, " SIP realtime: Enabled\n" );
9955 ast_cli(fd, "\nGlobal Signalling Settings:\n");
9956 ast_cli(fd, "---------------------------\n");
9957 ast_cli(fd, " Codecs: ");
9958 print_codec_to_cli(fd, &default_prefs);
9959 ast_cli(fd, "\n");
9960 ast_cli(fd, " T1 minimum: %d\n", global_t1min);
9961 ast_cli(fd, " Relax DTMF: %s\n", global_relaxdtmf ? "Yes" : "No");
9962 ast_cli(fd, " Compact SIP headers: %s\n", compactheaders ? "Yes" : "No");
9963 ast_cli(fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
9964 ast_cli(fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
9965 ast_cli(fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
9966 ast_cli(fd, " DNS SRV lookup: %s\n", srvlookup ? "Yes" : "No");
9967 ast_cli(fd, " Pedantic SIP support: %s\n", pedanticsipchecking ? "Yes" : "No");
9968 ast_cli(fd, " Reg. min duration %d secs\n", min_expiry);
9969 ast_cli(fd, " Reg. max duration: %d secs\n", max_expiry);
9970 ast_cli(fd, " Reg. default duration: %d secs\n", default_expiry);
9971 ast_cli(fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
9972 ast_cli(fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
9973 ast_cli(fd, " Notify ringing state: %s\n", global_notifyringing ? "Yes" : "No");
9974 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(global_allowtransfer));
9975 ast_cli(fd, " Max Call Bitrate: %d kbps\r\n", default_maxcallbitrate);
9976 ast_cli(fd, "\nDefault Settings:\n");
9977 ast_cli(fd, "-----------------\n");
9978 ast_cli(fd, " Context: %s\n", default_context);
9979 ast_cli(fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
9980 ast_cli(fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
9981 ast_cli(fd, " Qualify: %d\n", default_qualify);
9982 ast_cli(fd, " Use ClientCode: %s\n", ast_test_flag(&global_flags[0], SIP_USECLIENTCODE) ? "Yes" : "No");
9983 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" );
9984 ast_cli(fd, " Language: %s\n", S_OR(default_language, "(Defaults to English)"));
9985 ast_cli(fd, " MOH Interpret: %s\n", default_mohinterpret);
9986 ast_cli(fd, " MOH Suggest: %s\n", default_mohsuggest);
9987 ast_cli(fd, " Voice Mail Extension: %s\n", default_vmexten);
9990 if (realtimepeers || realtimeusers) {
9991 ast_cli(fd, "\nRealtime SIP Settings:\n");
9992 ast_cli(fd, "----------------------\n");
9993 ast_cli(fd, " Realtime Peers: %s\n", realtimepeers ? "Yes" : "No");
9994 ast_cli(fd, " Realtime Users: %s\n", realtimeusers ? "Yes" : "No");
9995 ast_cli(fd, " Cache Friends: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? "Yes" : "No");
9996 ast_cli(fd, " Update: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) ? "Yes" : "No");
9997 ast_cli(fd, " Ignore Reg. Expire: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) ? "Yes" : "No");
9998 ast_cli(fd, " Save sys. name: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME) ? "Yes" : "No");
9999 ast_cli(fd, " Auto Clear: %d\n", global_rtautoclear);
10001 ast_cli(fd, "\n----\n");
10002 return RESULT_SUCCESS;
10005 /*! \brief Show subscription type in string format */
10006 static const char *subscription_type2str(enum subscriptiontype subtype)
10008 int i;
10010 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10011 if (subscription_types[i].type == subtype) {
10012 return subscription_types[i].text;
10015 return subscription_types[0].text;
10018 /*! \brief Find subscription type in array */
10019 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
10021 int i;
10023 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10024 if (subscription_types[i].type == subtype) {
10025 return &subscription_types[i];
10028 return &subscription_types[0];
10031 /*! \brief Show active SIP channels */
10032 static int sip_show_channels(int fd, int argc, char *argv[])
10034 return __sip_show_channels(fd, argc, argv, 0);
10037 /*! \brief Show active SIP subscriptions */
10038 static int sip_show_subscriptions(int fd, int argc, char *argv[])
10040 return __sip_show_channels(fd, argc, argv, 1);
10043 /*! \brief SIP show channels CLI (main function) */
10044 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions)
10046 #define FORMAT3 "%-15.15s %-10.10s %-11.11s %-15.15s %-13.13s %-15.15s %-10.10s\n"
10047 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-4.4s %-7.7s %-15.15s\n"
10048 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-4.4s %-3.3s %-3.3s %-15.15s %-10.10s\n"
10049 struct sip_pvt *cur;
10050 int numchans = 0;
10051 char *referstatus = NULL;
10053 if (argc != 3)
10054 return RESULT_SHOWUSAGE;
10055 ast_mutex_lock(&iflock);
10056 cur = iflist;
10057 if (!subscriptions)
10058 ast_cli(fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Seq (Tx/Rx)", "Format", "Hold", "Last Message");
10059 else
10060 ast_cli(fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox");
10061 for (; cur; cur = cur->next) {
10062 referstatus = "";
10063 if (cur->refer) { /* SIP transfer in progress */
10064 referstatus = referstatus2str(cur->refer->status);
10066 if (cur->subscribed == NONE && !subscriptions) {
10067 ast_cli(fd, FORMAT, ast_inet_ntoa(cur->sa.sin_addr),
10068 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10069 cur->callid,
10070 cur->ocseq, cur->icseq,
10071 ast_getformatname(cur->owner ? cur->owner->nativeformats : 0),
10072 ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD) ? "Yes" : "No",
10073 ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY) ? "(d)" : "",
10074 cur->lastmsg ,
10075 referstatus
10077 numchans++;
10079 if (cur->subscribed != NONE && subscriptions) {
10080 ast_cli(fd, FORMAT3, ast_inet_ntoa(cur->sa.sin_addr),
10081 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10082 cur->callid,
10083 /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
10084 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
10085 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
10086 subscription_type2str(cur->subscribed),
10087 cur->subscribed == MWI_NOTIFICATION ? (cur->relatedpeer ? cur->relatedpeer->mailbox : "<none>") : "<none>"
10089 numchans++;
10092 ast_mutex_unlock(&iflock);
10093 if (!subscriptions)
10094 ast_cli(fd, "%d active SIP channel%s\n", numchans, (numchans != 1) ? "s" : "");
10095 else
10096 ast_cli(fd, "%d active SIP subscription%s\n", numchans, (numchans != 1) ? "s" : "");
10097 return RESULT_SUCCESS;
10098 #undef FORMAT
10099 #undef FORMAT2
10100 #undef FORMAT3
10103 /*! \brief Support routine for 'sip show channel' CLI */
10104 static char *complete_sipch(const char *line, const char *word, int pos, int state)
10106 int which=0;
10107 struct sip_pvt *cur;
10108 char *c = NULL;
10109 int wordlen = strlen(word);
10111 ast_mutex_lock(&iflock);
10112 for (cur = iflist; cur; cur = cur->next) {
10113 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
10114 c = ast_strdup(cur->callid);
10115 break;
10118 ast_mutex_unlock(&iflock);
10119 return c;
10122 /*! \brief Do completion on peer name */
10123 static char *complete_sip_peer(const char *word, int state, int flags2)
10125 char *result = NULL;
10126 int wordlen = strlen(word);
10127 int which = 0;
10129 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !result, do {
10130 /* locking of the object is not required because only the name and flags are being compared */
10131 if (!strncasecmp(word, iterator->name, wordlen) &&
10132 (!flags2 || ast_test_flag(&iterator->flags[1], flags2)) &&
10133 ++which > state)
10134 result = ast_strdup(iterator->name);
10135 } while(0) );
10136 return result;
10139 /*! \brief Support routine for 'sip show peer' CLI */
10140 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
10142 if (pos == 3)
10143 return complete_sip_peer(word, state, 0);
10145 return NULL;
10148 /*! \brief Support routine for 'sip debug peer' CLI */
10149 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state)
10151 if (pos == 3)
10152 return complete_sip_peer(word, state, 0);
10154 return NULL;
10157 /*! \brief Do completion on user name */
10158 static char *complete_sip_user(const char *word, int state, int flags2)
10160 char *result = NULL;
10161 int wordlen = strlen(word);
10162 int which = 0;
10164 ASTOBJ_CONTAINER_TRAVERSE(&userl, !result, do {
10165 /* locking of the object is not required because only the name and flags are being compared */
10166 if (!strncasecmp(word, iterator->name, wordlen)) {
10167 if (flags2 && !ast_test_flag(&iterator->flags[1], flags2))
10168 continue;
10169 if (++which > state) {
10170 result = ast_strdup(iterator->name);
10173 } while(0) );
10174 return result;
10177 /*! \brief Support routine for 'sip show user' CLI */
10178 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
10180 if (pos == 3)
10181 return complete_sip_user(word, state, 0);
10183 return NULL;
10186 /*! \brief Support routine for 'sip notify' CLI */
10187 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
10189 char *c = NULL;
10191 if (pos == 2) {
10192 int which = 0;
10193 char *cat = NULL;
10194 int wordlen = strlen(word);
10196 /* do completion for notify type */
10198 if (!notify_types)
10199 return NULL;
10201 while ( (cat = ast_category_browse(notify_types, cat)) ) {
10202 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
10203 c = ast_strdup(cat);
10204 break;
10207 return c;
10210 if (pos > 2)
10211 return complete_sip_peer(word, state, 0);
10213 return NULL;
10216 /*! \brief Support routine for 'sip prune realtime peer' CLI */
10217 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state)
10219 if (pos == 4)
10220 return complete_sip_peer(word, state, SIP_PAGE2_RTCACHEFRIENDS);
10221 return NULL;
10224 /*! \brief Support routine for 'sip prune realtime user' CLI */
10225 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state)
10227 if (pos == 4)
10228 return complete_sip_user(word, state, SIP_PAGE2_RTCACHEFRIENDS);
10230 return NULL;
10233 /*! \brief Show details of one active dialog */
10234 static int sip_show_channel(int fd, int argc, char *argv[])
10236 struct sip_pvt *cur;
10237 size_t len;
10238 int found = 0;
10240 if (argc != 4)
10241 return RESULT_SHOWUSAGE;
10242 len = strlen(argv[3]);
10243 ast_mutex_lock(&iflock);
10244 for (cur = iflist; cur; cur = cur->next) {
10245 if (!strncasecmp(cur->callid, argv[3], len)) {
10246 char formatbuf[BUFSIZ/2];
10247 ast_cli(fd,"\n");
10248 if (cur->subscribed != NONE)
10249 ast_cli(fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
10250 else
10251 ast_cli(fd, " * SIP Call\n");
10252 ast_cli(fd, " Direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING)?"Outgoing":"Incoming");
10253 ast_cli(fd, " Call-ID: %s\n", cur->callid);
10254 ast_cli(fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
10255 ast_cli(fd, " Our Codec Capability: %d\n", cur->capability);
10256 ast_cli(fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
10257 ast_cli(fd, " Their Codec Capability: %d\n", cur->peercapability);
10258 ast_cli(fd, " Joint Codec Capability: %d\n", cur->jointcapability);
10259 ast_cli(fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
10260 ast_cli(fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
10261 ast_cli(fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
10262 ast_cli(fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
10263 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
10264 ast_cli(fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
10265 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)" );
10266 ast_cli(fd, " Our Tag: %s\n", cur->tag);
10267 ast_cli(fd, " Their Tag: %s\n", cur->theirtag);
10268 ast_cli(fd, " SIP User agent: %s\n", cur->useragent);
10269 if (!ast_strlen_zero(cur->username))
10270 ast_cli(fd, " Username: %s\n", cur->username);
10271 if (!ast_strlen_zero(cur->peername))
10272 ast_cli(fd, " Peername: %s\n", cur->peername);
10273 if (!ast_strlen_zero(cur->uri))
10274 ast_cli(fd, " Original uri: %s\n", cur->uri);
10275 if (!ast_strlen_zero(cur->cid_num))
10276 ast_cli(fd, " Caller-ID: %s\n", cur->cid_num);
10277 ast_cli(fd, " Need Destroy: %d\n", ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY));
10278 ast_cli(fd, " Last Message: %s\n", cur->lastmsg);
10279 ast_cli(fd, " Promiscuous Redir: %s\n", ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
10280 ast_cli(fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
10281 ast_cli(fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
10282 ast_cli(fd, " SIP Options: ");
10283 if (cur->sipoptions) {
10284 int x;
10285 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
10286 if (cur->sipoptions & sip_options[x].id)
10287 ast_cli(fd, "%s ", sip_options[x].text);
10289 } else
10290 ast_cli(fd, "(none)\n");
10291 ast_cli(fd, "\n\n");
10292 found++;
10295 ast_mutex_unlock(&iflock);
10296 if (!found)
10297 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
10298 return RESULT_SUCCESS;
10301 /*! \brief Show history details of one dialog */
10302 static int sip_show_history(int fd, int argc, char *argv[])
10304 struct sip_pvt *cur;
10305 size_t len;
10306 int found = 0;
10308 if (argc != 4)
10309 return RESULT_SHOWUSAGE;
10310 if (!recordhistory)
10311 ast_cli(fd, "\n***Note: History recording is currently DISABLED. Use 'sip history' to ENABLE.\n");
10312 len = strlen(argv[3]);
10313 ast_mutex_lock(&iflock);
10314 for (cur = iflist; cur; cur = cur->next) {
10315 if (!strncasecmp(cur->callid, argv[3], len)) {
10316 struct sip_history *hist;
10317 int x = 0;
10319 ast_cli(fd,"\n");
10320 if (cur->subscribed != NONE)
10321 ast_cli(fd, " * Subscription\n");
10322 else
10323 ast_cli(fd, " * SIP Call\n");
10324 if (cur->history)
10325 AST_LIST_TRAVERSE(cur->history, hist, list)
10326 ast_cli(fd, "%d. %s\n", ++x, hist->event);
10327 if (x == 0)
10328 ast_cli(fd, "Call '%s' has no history\n", cur->callid);
10329 found++;
10332 ast_mutex_unlock(&iflock);
10333 if (!found)
10334 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
10335 return RESULT_SUCCESS;
10338 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
10339 static void sip_dump_history(struct sip_pvt *dialog)
10341 int x = 0;
10342 struct sip_history *hist;
10344 if (!dialog)
10345 return;
10347 ast_log(LOG_DEBUG, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
10348 if (dialog->subscribed)
10349 ast_log(LOG_DEBUG, " * Subscription\n");
10350 else
10351 ast_log(LOG_DEBUG, " * SIP Call\n");
10352 if (dialog->history)
10353 AST_LIST_TRAVERSE(dialog->history, hist, list)
10354 ast_log(LOG_DEBUG, " %-3.3d. %s\n", ++x, hist->event);
10355 if (!x)
10356 ast_log(LOG_DEBUG, "Call '%s' has no history\n", dialog->callid);
10357 ast_log(LOG_DEBUG, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
10361 /*! \brief Receive SIP INFO Message
10362 \note Doesn't read the duration of the DTMF signal */
10363 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
10365 char buf[1024];
10366 unsigned int event;
10367 const char *c = get_header(req, "Content-Type");
10369 /* Need to check the media/type */
10370 if (!strcasecmp(c, "application/dtmf-relay") ||
10371 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
10373 /* Try getting the "signal=" part */
10374 if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
10375 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
10376 transmit_response(p, "200 OK", req); /* Should return error */
10377 return;
10378 } else {
10379 ast_copy_string(buf, c, sizeof(buf));
10382 if (!p->owner) { /* not a PBX call */
10383 transmit_response(p, "481 Call leg/transaction does not exist", req);
10384 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
10385 return;
10388 if (ast_strlen_zero(buf)) {
10389 transmit_response(p, "200 OK", req);
10390 return;
10393 if (buf[0] == '*')
10394 event = 10;
10395 else if (buf[0] == '#')
10396 event = 11;
10397 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
10398 event = 12 + buf[0] - 'A';
10399 else
10400 event = atoi(buf);
10401 if (event == 16) {
10402 /* send a FLASH event */
10403 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
10404 ast_queue_frame(p->owner, &f);
10405 if (sipdebug)
10406 ast_verbose("* DTMF-relay event received: FLASH\n");
10407 } else {
10408 /* send a DTMF event */
10409 struct ast_frame f = { AST_FRAME_DTMF, };
10410 if (event < 10) {
10411 f.subclass = '0' + event;
10412 } else if (event < 11) {
10413 f.subclass = '*';
10414 } else if (event < 12) {
10415 f.subclass = '#';
10416 } else if (event < 16) {
10417 f.subclass = 'A' + (event - 12);
10419 ast_queue_frame(p->owner, &f);
10420 if (sipdebug)
10421 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
10423 transmit_response(p, "200 OK", req);
10424 return;
10425 } else if (!strcasecmp(c, "application/media_control+xml")) {
10426 /* Eh, we'll just assume it's a fast picture update for now */
10427 if (p->owner)
10428 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
10429 transmit_response(p, "200 OK", req);
10430 return;
10431 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
10432 /* Client code (from SNOM phone) */
10433 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
10434 if (p->owner && p->owner->cdr)
10435 ast_cdr_setuserfield(p->owner, c);
10436 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
10437 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
10438 transmit_response(p, "200 OK", req);
10439 } else {
10440 transmit_response(p, "403 Unauthorized", req);
10442 return;
10444 /* Other type of INFO message, not really understood by Asterisk */
10445 /* if (get_msg_text(buf, sizeof(buf), req)) { */
10447 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
10448 transmit_response(p, "415 Unsupported media type", req);
10449 return;
10452 /*! \brief Enable SIP Debugging in CLI */
10453 static int sip_do_debug_ip(int fd, int argc, char *argv[])
10455 struct hostent *hp;
10456 struct ast_hostent ahp;
10457 int port = 0;
10458 char *p, *arg;
10460 if (argc != 4)
10461 return RESULT_SHOWUSAGE;
10462 p = arg = argv[3];
10463 strsep(&p, ":");
10464 if (p)
10465 port = atoi(p);
10466 hp = ast_gethostbyname(arg, &ahp);
10467 if (hp == NULL)
10468 return RESULT_SHOWUSAGE;
10470 debugaddr.sin_family = AF_INET;
10471 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
10472 debugaddr.sin_port = htons(port);
10473 if (port == 0)
10474 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
10475 else
10476 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
10478 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
10480 return RESULT_SUCCESS;
10483 /*! \brief sip_do_debug_peer: Turn on SIP debugging with peer mask */
10484 static int sip_do_debug_peer(int fd, int argc, char *argv[])
10486 struct sip_peer *peer;
10487 if (argc != 4)
10488 return RESULT_SHOWUSAGE;
10489 peer = find_peer(argv[3], NULL, 1);
10490 if (peer) {
10491 if (peer->addr.sin_addr.s_addr) {
10492 debugaddr.sin_family = AF_INET;
10493 debugaddr.sin_addr = peer->addr.sin_addr;
10494 debugaddr.sin_port = peer->addr.sin_port;
10495 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
10496 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
10497 } else
10498 ast_cli(fd, "Unable to get IP address of peer '%s'\n", argv[3]);
10499 ASTOBJ_UNREF(peer,sip_destroy_peer);
10500 } else
10501 ast_cli(fd, "No such peer '%s'\n", argv[3]);
10502 return RESULT_SUCCESS;
10505 /*! \brief Turn on SIP debugging (CLI command) */
10506 static int sip_do_debug(int fd, int argc, char *argv[])
10508 int oldsipdebug = sipdebug_console;
10509 if (argc != 2) {
10510 if (argc != 4)
10511 return RESULT_SHOWUSAGE;
10512 else if (strcmp(argv[2], "ip") == 0)
10513 return sip_do_debug_ip(fd, argc, argv);
10514 else if (strcmp(argv[2], "peer") == 0)
10515 return sip_do_debug_peer(fd, argc, argv);
10516 else
10517 return RESULT_SHOWUSAGE;
10519 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
10520 memset(&debugaddr, 0, sizeof(debugaddr));
10521 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
10522 return RESULT_SUCCESS;
10525 /*! \brief Cli command to send SIP notify to peer */
10526 static int sip_notify(int fd, int argc, char *argv[])
10528 struct ast_variable *varlist;
10529 int i;
10531 if (argc < 4)
10532 return RESULT_SHOWUSAGE;
10534 if (!notify_types) {
10535 ast_cli(fd, "No %s file found, or no types listed there\n", notify_config);
10536 return RESULT_FAILURE;
10539 varlist = ast_variable_browse(notify_types, argv[2]);
10541 if (!varlist) {
10542 ast_cli(fd, "Unable to find notify type '%s'\n", argv[2]);
10543 return RESULT_FAILURE;
10546 for (i = 3; i < argc; i++) {
10547 struct sip_pvt *p;
10548 struct sip_request req;
10549 struct ast_variable *var;
10551 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY))) {
10552 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
10553 return RESULT_FAILURE;
10556 if (create_addr(p, argv[i])) {
10557 /* Maybe they're not registered, etc. */
10558 sip_destroy(p);
10559 ast_cli(fd, "Could not create address for '%s'\n", argv[i]);
10560 continue;
10563 initreqprep(&req, p, SIP_NOTIFY);
10565 for (var = varlist; var; var = var->next)
10566 add_header(&req, var->name, var->value);
10568 /* Recalculate our side, and recalculate Call ID */
10569 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
10570 p->ourip = __ourip;
10571 build_via(p);
10572 build_callid_pvt(p);
10573 ast_cli(fd, "Sending NOTIFY of type '%s' to '%s'\n", argv[2], argv[i]);
10574 transmit_sip_request(p, &req);
10575 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
10578 return RESULT_SUCCESS;
10581 /*! \brief Disable SIP Debugging in CLI */
10582 static int sip_no_debug(int fd, int argc, char *argv[])
10584 if (argc != 3)
10585 return RESULT_SHOWUSAGE;
10586 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
10587 ast_cli(fd, "SIP Debugging Disabled\n");
10588 return RESULT_SUCCESS;
10591 /*! \brief Enable SIP History logging (CLI) */
10592 static int sip_do_history(int fd, int argc, char *argv[])
10594 if (argc != 2) {
10595 return RESULT_SHOWUSAGE;
10597 recordhistory = TRUE;
10598 ast_cli(fd, "SIP History Recording Enabled (use 'sip show history')\n");
10599 return RESULT_SUCCESS;
10602 /*! \brief Disable SIP History logging (CLI) */
10603 static int sip_no_history(int fd, int argc, char *argv[])
10605 if (argc != 3) {
10606 return RESULT_SHOWUSAGE;
10608 recordhistory = FALSE;
10609 ast_cli(fd, "SIP History Recording Disabled\n");
10610 return RESULT_SUCCESS;
10614 /*! \brief Authenticate for outbound registration */
10615 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader)
10617 char digest[1024];
10618 p->authtries++;
10619 memset(digest,0,sizeof(digest));
10620 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
10621 /* There's nothing to use for authentication */
10622 /* No digest challenge in request */
10623 if (sip_debug_test_pvt(p) && p->registry)
10624 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
10625 /* No old challenge */
10626 return -1;
10628 if (recordhistory)
10629 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
10630 if (sip_debug_test_pvt(p) && p->registry)
10631 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
10632 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
10635 /*! \brief Add authentication on outbound SIP packet */
10636 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init)
10638 char digest[1024];
10640 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
10641 return -2;
10643 p->authtries++;
10644 if (option_debug > 1)
10645 ast_log(LOG_DEBUG, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
10646 memset(digest, 0, sizeof(digest));
10647 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
10648 /* No way to authenticate */
10649 return -1;
10651 /* Now we have a reply digest */
10652 p->options->auth = digest;
10653 p->options->authheader = respheader;
10654 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
10657 /*! \brief reply to authentication for outbound registrations
10658 \return Returns -1 if we have no auth
10659 \note This is used for register= servers in sip.conf, SIP proxies we register
10660 with for receiving calls from. */
10661 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
10663 char tmp[512];
10664 char *c;
10665 char oldnonce[256];
10667 /* table of recognised keywords, and places where they should be copied */
10668 const struct x {
10669 const char *key;
10670 int field_index;
10671 } *i, keys[] = {
10672 { "realm=", ast_string_field_index(p, realm) },
10673 { "nonce=", ast_string_field_index(p, nonce) },
10674 { "opaque=", ast_string_field_index(p, opaque) },
10675 { "qop=", ast_string_field_index(p, qop) },
10676 { "domain=", ast_string_field_index(p, domain) },
10677 { NULL, 0 },
10680 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
10681 if (ast_strlen_zero(tmp))
10682 return -1;
10683 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
10684 ast_log(LOG_WARNING, "missing Digest.\n");
10685 return -1;
10687 c = tmp + strlen("Digest ");
10688 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
10689 while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
10690 for (i = keys; i->key != NULL; i++) {
10691 char *src, *separator;
10692 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
10693 continue;
10694 /* Found. Skip keyword, take text in quotes or up to the separator. */
10695 c += strlen(i->key);
10696 if (*c == '"') {
10697 src = ++c;
10698 separator = "\"";
10699 } else {
10700 src = c;
10701 separator = ",";
10703 strsep(&c, separator); /* clear separator and move ptr */
10704 ast_string_field_index_set(p, i->field_index, src);
10705 break;
10707 if (i->key == NULL) /* not found, try ',' */
10708 strsep(&c, ",");
10710 /* Reset nonce count */
10711 if (strcmp(p->nonce, oldnonce))
10712 p->noncecount = 0;
10714 /* Save auth data for following registrations */
10715 if (p->registry) {
10716 struct sip_registry *r = p->registry;
10718 if (strcmp(r->nonce, p->nonce)) {
10719 ast_string_field_set(r, realm, p->realm);
10720 ast_string_field_set(r, nonce, p->nonce);
10721 ast_string_field_set(r, domain, p->domain);
10722 ast_string_field_set(r, opaque, p->opaque);
10723 ast_string_field_set(r, qop, p->qop);
10724 r->noncecount = 0;
10727 return build_reply_digest(p, sipmethod, digest, digest_len);
10730 /*! \brief Build reply digest
10731 \return Returns -1 if we have no auth
10732 \note Build digest challenge for authentication of peers (for registration)
10733 and users (for calls). Also used for authentication of CANCEL and BYE
10735 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
10737 char a1[256];
10738 char a2[256];
10739 char a1_hash[256];
10740 char a2_hash[256];
10741 char resp[256];
10742 char resp_hash[256];
10743 char uri[256];
10744 char cnonce[80];
10745 const char *username;
10746 const char *secret;
10747 const char *md5secret;
10748 struct sip_auth *auth = NULL; /* Realm authentication */
10750 if (!ast_strlen_zero(p->domain))
10751 ast_copy_string(uri, p->domain, sizeof(uri));
10752 else if (!ast_strlen_zero(p->uri))
10753 ast_copy_string(uri, p->uri, sizeof(uri));
10754 else
10755 snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, ast_inet_ntoa(p->sa.sin_addr));
10757 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
10759 /* Check if we have separate auth credentials */
10760 if ((auth = find_realm_authentication(authl, p->realm))) {
10761 ast_log(LOG_WARNING, "use realm [%s] from peer [%s][%s]\n",
10762 auth->username, p->peername, p->username);
10763 username = auth->username;
10764 secret = auth->secret;
10765 md5secret = auth->md5secret;
10766 if (sipdebug)
10767 ast_log(LOG_DEBUG,"Using realm %s authentication for call %s\n", p->realm, p->callid);
10768 } else {
10769 /* No authentication, use peer or register= config */
10770 username = p->authname;
10771 secret = p->peersecret;
10772 md5secret = p->peermd5secret;
10774 if (ast_strlen_zero(username)) /* We have no authentication */
10775 return -1;
10777 /* Calculate SIP digest response */
10778 snprintf(a1,sizeof(a1),"%s:%s:%s", username, p->realm, secret);
10779 snprintf(a2,sizeof(a2),"%s:%s", sip_methods[method].text, uri);
10780 if (!ast_strlen_zero(md5secret))
10781 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
10782 else
10783 ast_md5_hash(a1_hash,a1);
10784 ast_md5_hash(a2_hash,a2);
10786 p->noncecount++;
10787 if (!ast_strlen_zero(p->qop))
10788 snprintf(resp,sizeof(resp),"%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
10789 else
10790 snprintf(resp,sizeof(resp),"%s:%s:%s", a1_hash, p->nonce, a2_hash);
10791 ast_md5_hash(resp_hash, resp);
10792 /* XXX We hard code our qop to "auth" for now. XXX */
10793 if (!ast_strlen_zero(p->qop))
10794 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);
10795 else
10796 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);
10798 return 0;
10801 static char show_domains_usage[] =
10802 "Usage: sip show domains\n"
10803 " Lists all configured SIP local domains.\n"
10804 " Asterisk only responds to SIP messages to local domains.\n";
10806 static char notify_usage[] =
10807 "Usage: sip notify <type> <peer> [<peer>...]\n"
10808 " Send a NOTIFY message to a SIP peer or peers\n"
10809 " Message types are defined in sip_notify.conf\n";
10811 static char show_users_usage[] =
10812 "Usage: sip show users [like <pattern>]\n"
10813 " Lists all known SIP users.\n"
10814 " Optional regular expression pattern is used to filter the user list.\n";
10816 static char show_user_usage[] =
10817 "Usage: sip show user <name> [load]\n"
10818 " Lists all details on one SIP user and the current status.\n"
10819 " Option \"load\" forces lookup of peer in realtime storage.\n";
10821 static char show_inuse_usage[] =
10822 "Usage: sip show inuse [all]\n"
10823 " List all SIP users and peers usage counters and limits.\n"
10824 " Add option \"all\" to show all devices, not only those with a limit.\n";
10826 static char show_channels_usage[] =
10827 "Usage: sip show channels\n"
10828 " Lists all currently active SIP channels.\n";
10830 static char show_channel_usage[] =
10831 "Usage: sip show channel <channel>\n"
10832 " Provides detailed status on a given SIP channel.\n";
10834 static char show_history_usage[] =
10835 "Usage: sip show history <channel>\n"
10836 " Provides detailed dialog history on a given SIP channel.\n";
10838 static char show_peers_usage[] =
10839 "Usage: sip show peers [like <pattern>]\n"
10840 " Lists all known SIP peers.\n"
10841 " Optional regular expression pattern is used to filter the peer list.\n";
10843 static char show_peer_usage[] =
10844 "Usage: sip show peer <name> [load]\n"
10845 " Lists all details on one SIP peer and the current status.\n"
10846 " Option \"load\" forces lookup of peer in realtime storage.\n";
10848 static char prune_realtime_usage[] =
10849 "Usage: sip prune realtime [peer|user] [<name>|all|like <pattern>]\n"
10850 " Prunes object(s) from the cache.\n"
10851 " Optional regular expression pattern is used to filter the objects.\n";
10853 static char show_reg_usage[] =
10854 "Usage: sip show registry\n"
10855 " Lists all registration requests and status.\n";
10857 static char debug_usage[] =
10858 "Usage: sip debug\n"
10859 " Enables dumping of SIP packets for debugging purposes\n\n"
10860 " sip debug ip <host[:PORT]>\n"
10861 " Enables dumping of SIP packets to and from host.\n\n"
10862 " sip debug peer <peername>\n"
10863 " Enables dumping of SIP packets to and from host.\n"
10864 " Require peer to be registered.\n";
10866 static char no_debug_usage[] =
10867 "Usage: sip no debug\n"
10868 " Disables dumping of SIP packets for debugging purposes\n";
10870 static char no_history_usage[] =
10871 "Usage: sip no history\n"
10872 " Disables recording of SIP dialog history for debugging purposes\n";
10874 static char history_usage[] =
10875 "Usage: sip history\n"
10876 " Enables recording of SIP dialog history for debugging purposes.\n"
10877 "Use 'sip show history' to view the history of a call number.\n";
10879 static char sip_reload_usage[] =
10880 "Usage: sip reload\n"
10881 " Reloads SIP configuration from sip.conf\n";
10883 static char show_subscriptions_usage[] =
10884 "Usage: sip show subscriptions\n"
10885 " Shows active SIP subscriptions for extension states\n";
10887 static char show_objects_usage[] =
10888 "Usage: sip show objects\n"
10889 " Shows status of known SIP objects\n";
10891 static char show_settings_usage[] =
10892 "Usage: sip show settings\n"
10893 " Provides detailed list of the configuration of the SIP channel.\n";
10897 /*! \brief Read SIP header (dialplan function) */
10898 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len)
10900 struct sip_pvt *p;
10901 const char *content = NULL;
10902 AST_DECLARE_APP_ARGS(args,
10903 AST_APP_ARG(header);
10904 AST_APP_ARG(number);
10906 int i, number, start = 0;
10908 if (ast_strlen_zero(data)) {
10909 ast_log(LOG_WARNING, "This function requires a header name.\n");
10910 return -1;
10913 ast_channel_lock(chan);
10914 if (chan->tech != &sip_tech) {
10915 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
10916 ast_channel_unlock(chan);
10917 return -1;
10920 AST_STANDARD_APP_ARGS(args, data);
10921 if (!args.number) {
10922 number = 1;
10923 } else {
10924 sscanf(args.number, "%d", &number);
10925 if (number < 1)
10926 number = 1;
10929 p = chan->tech_pvt;
10931 /* If there is no private structure, this channel is no longer alive */
10932 if (!p) {
10933 ast_channel_unlock(chan);
10934 return -1;
10937 for (i = 0; i < number; i++)
10938 content = __get_header(&p->initreq, args.header, &start);
10940 if (ast_strlen_zero(content)) {
10941 ast_channel_unlock(chan);
10942 return -1;
10945 ast_copy_string(buf, content, len);
10946 ast_channel_unlock(chan);
10948 return 0;
10951 static struct ast_custom_function sip_header_function = {
10952 .name = "SIP_HEADER",
10953 .synopsis = "Gets the specified SIP header",
10954 .syntax = "SIP_HEADER(<name>[,<number>])",
10955 .desc = "Since there are several headers (such as Via) which can occur multiple\n"
10956 "times, SIP_HEADER takes an optional second argument to specify which header with\n"
10957 "that name to retrieve. Headers start at offset 1.\n",
10958 .read = func_header_read,
10961 /*! \brief Dial plan function to check if domain is local */
10962 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
10964 if (ast_strlen_zero(data)) {
10965 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
10966 return -1;
10968 if (check_sip_domain(data, NULL, 0))
10969 ast_copy_string(buf, data, len);
10970 else
10971 buf[0] = '\0';
10972 return 0;
10975 static struct ast_custom_function checksipdomain_function = {
10976 .name = "CHECKSIPDOMAIN",
10977 .synopsis = "Checks if domain is a local domain",
10978 .syntax = "CHECKSIPDOMAIN(<domain|IP>)",
10979 .read = func_check_sipdomain,
10980 .desc = "This function checks if the domain in the argument is configured\n"
10981 "as a local SIP domain that this Asterisk server is configured to handle.\n"
10982 "Returns the domain name if it is locally handled, otherwise an empty string.\n"
10983 "Check the domain= configuration in sip.conf\n",
10986 /*! \brief ${SIPPEER()} Dialplan function - reads peer data */
10987 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
10989 struct sip_peer *peer;
10990 char *colname;
10992 if ((colname = strchr(data, ':'))) /*! \todo Will be deprecated after 1.4 */
10993 *colname++ = '\0';
10994 else if ((colname = strchr(data, '|')))
10995 *colname++ = '\0';
10996 else
10997 colname = "ip";
10999 if (!(peer = find_peer(data, NULL, 1)))
11000 return -1;
11002 if (!strcasecmp(colname, "ip")) {
11003 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
11004 } else if (!strcasecmp(colname, "status")) {
11005 peer_status(peer, buf, len);
11006 } else if (!strcasecmp(colname, "language")) {
11007 ast_copy_string(buf, peer->language, len);
11008 } else if (!strcasecmp(colname, "regexten")) {
11009 ast_copy_string(buf, peer->regexten, len);
11010 } else if (!strcasecmp(colname, "limit")) {
11011 snprintf(buf, len, "%d", peer->call_limit);
11012 } else if (!strcasecmp(colname, "curcalls")) {
11013 snprintf(buf, len, "%d", peer->inUse);
11014 } else if (!strcasecmp(colname, "accountcode")) {
11015 ast_copy_string(buf, peer->accountcode, len);
11016 } else if (!strcasecmp(colname, "useragent")) {
11017 ast_copy_string(buf, peer->useragent, len);
11018 } else if (!strcasecmp(colname, "mailbox")) {
11019 ast_copy_string(buf, peer->mailbox, len);
11020 } else if (!strcasecmp(colname, "context")) {
11021 ast_copy_string(buf, peer->context, len);
11022 } else if (!strcasecmp(colname, "expire")) {
11023 snprintf(buf, len, "%d", peer->expire);
11024 } else if (!strcasecmp(colname, "dynamic")) {
11025 ast_copy_string(buf, (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no"), len);
11026 } else if (!strcasecmp(colname, "callerid_name")) {
11027 ast_copy_string(buf, peer->cid_name, len);
11028 } else if (!strcasecmp(colname, "callerid_num")) {
11029 ast_copy_string(buf, peer->cid_num, len);
11030 } else if (!strcasecmp(colname, "codecs")) {
11031 ast_getformatname_multiple(buf, len -1, peer->capability);
11032 } else if (!strncasecmp(colname, "codec[", 6)) {
11033 char *codecnum;
11034 int index = 0, codec = 0;
11036 codecnum = colname + 6; /* move past the '[' */
11037 codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
11038 index = atoi(codecnum);
11039 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
11040 ast_copy_string(buf, ast_getformatname(codec), len);
11044 ASTOBJ_UNREF(peer, sip_destroy_peer);
11046 return 0;
11049 /*! \brief Structure to declare a dialplan function: SIPPEER */
11050 struct ast_custom_function sippeer_function = {
11051 .name = "SIPPEER",
11052 .synopsis = "Gets SIP peer information",
11053 .syntax = "SIPPEER(<peername>[|item])",
11054 .read = function_sippeer,
11055 .desc = "Valid items are:\n"
11056 "- ip (default) The IP address.\n"
11057 "- mailbox The configured mailbox.\n"
11058 "- context The configured context.\n"
11059 "- expire The epoch time of the next expire.\n"
11060 "- dynamic Is it dynamic? (yes/no).\n"
11061 "- callerid_name The configured Caller ID name.\n"
11062 "- callerid_num The configured Caller ID number.\n"
11063 "- codecs The configured codecs.\n"
11064 "- status Status (if qualify=yes).\n"
11065 "- regexten Registration extension\n"
11066 "- limit Call limit (call-limit)\n"
11067 "- curcalls Current amount of calls \n"
11068 " Only available if call-limit is set\n"
11069 "- language Default language for peer\n"
11070 "- accountcode Account code for this peer\n"
11071 "- useragent Current user agent id for peer\n"
11072 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
11073 "\n"
11076 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
11077 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11079 struct sip_pvt *p;
11081 *buf = 0;
11083 if (!data) {
11084 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
11085 return -1;
11088 ast_channel_lock(chan);
11089 if (chan->tech != &sip_tech) {
11090 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
11091 ast_channel_unlock(chan);
11092 return -1;
11095 p = chan->tech_pvt;
11097 /* If there is no private structure, this channel is no longer alive */
11098 if (!p) {
11099 ast_channel_unlock(chan);
11100 return -1;
11103 if (!strcasecmp(data, "peerip")) {
11104 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
11105 } else if (!strcasecmp(data, "recvip")) {
11106 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
11107 } else if (!strcasecmp(data, "from")) {
11108 ast_copy_string(buf, p->from, len);
11109 } else if (!strcasecmp(data, "uri")) {
11110 ast_copy_string(buf, p->uri, len);
11111 } else if (!strcasecmp(data, "useragent")) {
11112 ast_copy_string(buf, p->useragent, len);
11113 } else if (!strcasecmp(data, "peername")) {
11114 ast_copy_string(buf, p->peername, len);
11115 } else if (!strcasecmp(data, "t38passthrough")) {
11116 if (p->t38.state == T38_DISABLED)
11117 ast_copy_string(buf, "0", sizeof("0"));
11118 else /* T38 is offered or enabled in this call */
11119 ast_copy_string(buf, "1", sizeof("1"));
11120 } else {
11121 ast_channel_unlock(chan);
11122 return -1;
11124 ast_channel_unlock(chan);
11126 return 0;
11129 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
11130 static struct ast_custom_function sipchaninfo_function = {
11131 .name = "SIPCHANINFO",
11132 .synopsis = "Gets the specified SIP parameter from the current channel",
11133 .syntax = "SIPCHANINFO(item)",
11134 .read = function_sipchaninfo_read,
11135 .desc = "Valid items are:\n"
11136 "- peerip The IP address of the peer.\n"
11137 "- recvip The source IP address of the peer.\n"
11138 "- from The URI from the From: header.\n"
11139 "- uri The URI from the Contact: header.\n"
11140 "- useragent The useragent.\n"
11141 "- peername The name of the peer.\n"
11142 "- t38passthrough 1 if T38 is offered or enabled in this channel, otherwise 0\n"
11145 /*! \brief Parse 302 Moved temporalily response */
11146 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
11148 char tmp[256];
11149 char *s, *e;
11150 char *domain;
11152 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
11153 s = get_in_brackets(tmp);
11154 s = strsep(&s, ";"); /* strip ; and beyond */
11155 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
11156 if (!strncasecmp(s, "sip:", 4))
11157 s += 4;
11158 e = strchr(s, '/');
11159 if (e)
11160 *e = '\0';
11161 ast_log(LOG_DEBUG, "Found promiscuous redirection to 'SIP/%s'\n", s);
11162 if (p->owner)
11163 ast_string_field_build(p->owner, call_forward, "SIP/%s", s);
11164 } else {
11165 e = strchr(tmp, '@');
11166 if (e) {
11167 *e++ = '\0';
11168 domain = e;
11169 } else {
11170 /* No username part */
11171 domain = tmp;
11173 e = strchr(tmp, '/');
11174 if (e)
11175 *e = '\0';
11176 if (!strncasecmp(s, "sip:", 4))
11177 s += 4;
11178 if (option_debug > 1)
11179 ast_log(LOG_DEBUG, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
11180 if (p->owner) {
11181 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
11182 ast_string_field_set(p->owner, call_forward, s);
11187 /*! \brief Check pending actions on SIP call */
11188 static void check_pendings(struct sip_pvt *p)
11190 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
11191 /* if we can't BYE, then this is really a pending CANCEL */
11192 if (!ast_test_flag(&p->flags[0], SIP_CAN_BYE)) {
11193 transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, 1, 0);
11194 /* Actually don't destroy us yet, wait for the 487 on our original
11195 INVITE, but do set an autodestruct just in case we never get it. */
11196 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
11197 } else {
11198 transmit_request_with_auth(p, SIP_BYE, 0, 1, 1);
11199 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11200 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
11202 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
11203 if (option_debug)
11204 ast_log(LOG_DEBUG, "Sending pending reinvite on '%s'\n", p->callid);
11205 /* Didn't get to reinvite yet, so do it now */
11206 transmit_reinvite_with_sdp(p);
11207 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
11211 /*! \brief Handle SIP response to INVITE dialogue */
11212 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
11214 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
11215 int res = 0;
11216 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
11217 struct ast_channel *bridgepeer = NULL;
11219 if (option_debug > 3) {
11220 if (reinvite)
11221 ast_log(LOG_DEBUG, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
11222 else
11223 ast_log(LOG_DEBUG, "SIP response %d to standard invite\n", resp);
11226 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) { /* This call is already gone */
11227 ast_log(LOG_DEBUG, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
11228 return;
11231 /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
11232 if (p->initid > -1) {
11233 /* Don't auto congest anymore since we've gotten something useful back */
11234 ast_sched_del(sched, p->initid);
11235 p->initid = -1;
11238 /* RFC3261 says we must treat every 1xx response (but not 100)
11239 that we don't recognize as if it was 183.
11241 if ((resp > 100) &&
11242 (resp < 200) &&
11243 (resp != 180) &&
11244 (resp != 183))
11245 resp = 183;
11247 switch (resp) {
11248 case 100: /* Trying */
11249 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11250 sip_cancel_destroy(p);
11251 check_pendings(p);
11252 break;
11253 case 180: /* 180 Ringing */
11254 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11255 sip_cancel_destroy(p);
11256 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
11257 ast_queue_control(p->owner, AST_CONTROL_RINGING);
11258 if (p->owner->_state != AST_STATE_UP) {
11259 ast_setstate(p->owner, AST_STATE_RINGING);
11262 if (find_sdp(req)) {
11263 res = process_sdp(p, req);
11264 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
11265 /* Queue a progress frame only if we have SDP in 180 */
11266 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
11269 ast_set_flag(&p->flags[0], SIP_CAN_BYE);
11270 check_pendings(p);
11271 break;
11272 case 183: /* Session progress */
11273 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11274 sip_cancel_destroy(p);
11275 /* Ignore 183 Session progress without SDP */
11276 if (find_sdp(req)) {
11277 res = process_sdp(p, req);
11278 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
11279 /* Queue a progress frame */
11280 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
11283 ast_set_flag(&p->flags[0], SIP_CAN_BYE);
11284 check_pendings(p);
11285 break;
11286 case 200: /* 200 OK on invite - someone's answering our call */
11287 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11288 sip_cancel_destroy(p);
11289 p->authtries = 0;
11290 if (find_sdp(req)) {
11291 if ((res = process_sdp(p, req)) && !ast_test_flag(req, SIP_PKT_IGNORE))
11292 if (!reinvite)
11293 /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
11294 /* For re-invites, we try to recover */
11295 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
11298 /* Parse contact header for continued conversation */
11299 /* When we get 200 OK, we know which device (and IP) to contact for this call */
11300 /* This is important when we have a SIP proxy between us and the phone */
11301 if (outgoing) {
11302 update_call_counter(p, DEC_CALL_RINGING);
11303 parse_ok_contact(p, req);
11304 if(set_address_from_contact(p)) {
11305 /* Bad contact - we don't know how to reach this device */
11306 /* We need to ACK, but then send a bye */
11307 /* OEJ: Possible issue that may need a check:
11308 If we have a proxy route between us and the device,
11309 should we care about resolving the contact
11310 or should we just send it?
11312 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11313 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
11316 /* Save Record-Route for any later requests we make on this dialogue */
11317 build_route(p, req, 1);
11320 if (p->owner && (p->owner->_state == AST_STATE_UP) && (bridgepeer = ast_bridged_channel(p->owner))) { /* if this is a re-invite */
11321 struct sip_pvt *bridgepvt = NULL;
11323 if (!bridgepeer->tech) {
11324 ast_log(LOG_WARNING, "Ooooh.. no tech! That's REALLY bad\n");
11325 break;
11327 if (!strcasecmp(bridgepeer->tech->type,"SIP")) {
11328 bridgepvt = (struct sip_pvt*)(bridgepeer->tech_pvt);
11329 if (bridgepvt->udptl) {
11330 if (p->t38.state == T38_PEER_REINVITE) {
11331 sip_handle_t38_reinvite(bridgepeer, p, 0);
11332 } else if (p->t38.state == T38_DISABLED && bridgepeer && (bridgepvt->t38.state == T38_ENABLED)) {
11333 ast_log(LOG_WARNING, "RTP re-inivte after T38 session not handled yet !\n");
11334 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
11335 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11337 } else {
11338 ast_log(LOG_WARNING, "Strange... The other side of the bridge does not have a udptl struct\n");
11339 ast_mutex_lock(&bridgepvt->lock);
11340 bridgepvt->t38.state = T38_DISABLED;
11341 ast_mutex_unlock(&bridgepvt->lock);
11342 if (option_debug)
11343 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->tech->type);
11344 p->t38.state = T38_DISABLED;
11345 if (option_debug > 1)
11346 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11348 } else {
11349 /* Other side is not a SIP channel */
11350 ast_log(LOG_WARNING, "Strange... The other side of the bridge is not a SIP channel\n");
11351 p->t38.state = T38_DISABLED;
11352 if (option_debug > 1)
11353 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11356 if ((p->t38.state == T38_LOCAL_REINVITE) || (p->t38.state == T38_LOCAL_DIRECT)) {
11357 /* If there was T38 reinvite and we are supposed to answer with 200 OK than this should set us to T38 negotiated mode */
11358 p->t38.state = T38_ENABLED;
11359 if (option_debug)
11360 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11363 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
11364 if (!reinvite) {
11365 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
11366 } else { /* RE-invite */
11367 ast_queue_frame(p->owner, &ast_null_frame);
11369 } else {
11370 /* It's possible we're getting an 200 OK after we've tried to disconnect
11371 by sending CANCEL */
11372 /* First send ACK, then send bye */
11373 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11374 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
11376 /* If I understand this right, the branch is different for a non-200 ACK only */
11377 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
11378 ast_set_flag(&p->flags[0], SIP_CAN_BYE);
11379 check_pendings(p);
11380 break;
11381 case 407: /* Proxy authentication */
11382 case 401: /* Www auth */
11383 /* First we ACK */
11384 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11385 if (p->options)
11386 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
11388 /* Then we AUTH */
11389 ast_string_field_free(p, theirtag); /* forget their old tag, so we don't match tags when getting response */
11390 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
11391 char *authenticate = (resp == 401 ? "WWW-Authenticate" : "Proxy-Authenticate");
11392 char *authorization = (resp == 401 ? "Authorization" : "Proxy-Authorization");
11393 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, authenticate, authorization, SIP_INVITE, 1)) {
11394 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
11395 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11396 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
11397 if (p->owner)
11398 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11401 break;
11402 case 403: /* Forbidden */
11403 /* First we ACK */
11404 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11405 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
11406 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner)
11407 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11408 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11409 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
11410 break;
11411 case 404: /* Not found */
11412 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11413 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
11414 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11415 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
11416 break;
11417 case 481: /* Call leg does not exist */
11418 /* Could be REFER or INVITE */
11419 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
11420 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11421 break;
11422 case 491: /* Pending */
11423 /* we have to wait a while, then retransmit */
11424 /* Transmission is rescheduled, so everything should be taken care of.
11425 We should support the retry-after at some point */
11426 break;
11427 case 501: /* Not implemented */
11428 if (p->owner)
11429 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11430 break;
11434 /* \brief Handle SIP response in REFER transaction
11435 We've sent a REFER, now handle responses to it
11437 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
11439 char *auth = "Proxy-Authenticate";
11440 char *auth2 = "Proxy-Authorization";
11442 switch (resp) {
11443 case 202: /* Transfer accepted */
11444 /* We need to do something here */
11445 /* The transferee is now sending INVITE to target */
11446 p->refer->status = REFER_ACCEPTED;
11447 /* Now wait for next message */
11448 if (option_debug > 2)
11449 ast_log(LOG_DEBUG, "Got 202 accepted on transfer\n");
11450 /* We should hang along, waiting for NOTIFY's here */
11451 break;
11453 case 401: /* Not www-authorized on SIP method */
11454 case 407: /* Proxy auth */
11455 if (ast_strlen_zero(p->authname)) {
11456 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
11457 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
11458 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11460 if (resp == 401) {
11461 auth = "WWW-Authenticate";
11462 auth2 = "Authorization";
11464 if ((p->authtries > 1) || do_proxy_auth(p, req, auth, auth2, SIP_REFER, 0)) {
11465 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
11466 p->refer->status = REFER_NOAUTH;
11467 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11469 break;
11472 case 500: /* Server error */
11473 case 501: /* Method not implemented */
11474 /* Return to the current call onhold */
11475 /* Status flag needed to be reset */
11476 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
11477 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11478 p->refer->status = REFER_FAILED;
11479 break;
11480 case 603: /* Transfer declined */
11481 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
11482 p->refer->status = REFER_FAILED;
11483 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11484 break;
11488 /*! \brief Handle responses on REGISTER to services */
11489 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
11491 int expires, expires_ms;
11492 struct sip_registry *r;
11493 r=p->registry;
11495 switch (resp) {
11496 case 401: /* Unauthorized */
11497 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "WWW-Authenticate", "Authorization")) {
11498 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
11499 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11501 break;
11502 case 403: /* Forbidden */
11503 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
11504 if (global_regattempts_max)
11505 p->registry->regattempts = global_regattempts_max+1;
11506 ast_sched_del(sched, r->timeout);
11507 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11508 break;
11509 case 404: /* Not found */
11510 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username,p->registry->hostname);
11511 if (global_regattempts_max)
11512 p->registry->regattempts = global_regattempts_max+1;
11513 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11514 r->call = NULL;
11515 ast_sched_del(sched, r->timeout);
11516 break;
11517 case 407: /* Proxy auth */
11518 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization")) {
11519 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
11520 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11522 break;
11523 case 479: /* SER: Not able to process the URI - address is wrong in register*/
11524 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username,p->registry->hostname);
11525 if (global_regattempts_max)
11526 p->registry->regattempts = global_regattempts_max+1;
11527 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11528 r->call = NULL;
11529 ast_sched_del(sched, r->timeout);
11530 break;
11531 case 200: /* 200 OK */
11532 if (!r) {
11533 ast_log(LOG_WARNING, "Got 200 OK on REGISTER that isn't a register\n");
11534 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11535 return 0;
11538 r->regstate = REG_STATE_REGISTERED;
11539 r->regtime = time(NULL); /* Reset time of last succesful registration */
11540 manager_event(EVENT_FLAG_SYSTEM, "Registry", "Channel: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
11541 r->regattempts = 0;
11542 ast_log(LOG_DEBUG, "Registration successful\n");
11543 if (r->timeout > -1) {
11544 ast_log(LOG_DEBUG, "Cancelling timeout %d\n", r->timeout);
11545 ast_sched_del(sched, r->timeout);
11547 r->timeout=-1;
11548 r->call = NULL;
11549 p->registry = NULL;
11550 /* Let this one hang around until we have all the responses */
11551 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
11552 /* ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); */
11554 /* set us up for re-registering */
11555 /* figure out how long we got registered for */
11556 if (r->expire > -1)
11557 ast_sched_del(sched, r->expire);
11558 /* according to section 6.13 of RFC, contact headers override
11559 expires headers, so check those first */
11560 expires = 0;
11561 if (!ast_strlen_zero(get_header(req, "Contact"))) {
11562 const char *contact = NULL;
11563 const char *tmptmp = NULL;
11564 int start = 0;
11565 for(;;) {
11566 contact = __get_header(req, "Contact", &start);
11567 /* this loop ensures we get a contact header about our register request */
11568 if(!ast_strlen_zero(contact)) {
11569 if( (tmptmp=strstr(contact, p->our_contact))) {
11570 contact=tmptmp;
11571 break;
11573 } else
11574 break;
11576 tmptmp = strcasestr(contact, "expires=");
11577 if (tmptmp) {
11578 if (sscanf(tmptmp + 8, "%d;", &expires) != 1)
11579 expires = 0;
11583 if (!expires)
11584 expires=atoi(get_header(req, "expires"));
11585 if (!expires)
11586 expires=default_expiry;
11588 expires_ms = expires * 1000;
11589 if (expires <= EXPIRY_GUARD_LIMIT)
11590 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT),EXPIRY_GUARD_MIN);
11591 else
11592 expires_ms -= EXPIRY_GUARD_SECS * 1000;
11593 if (sipdebug)
11594 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
11596 r->refresh= (int) expires_ms / 1000;
11598 /* Schedule re-registration before we expire */
11599 r->expire=ast_sched_add(sched, expires_ms, sip_reregister, r);
11600 ASTOBJ_UNREF(r, sip_registry_destroy);
11602 return 1;
11605 /*! \brief Handle qualification responses (OPTIONS) */
11606 static int handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
11608 struct sip_peer *peer;
11609 int pingtime;
11610 struct timeval tv;
11612 if (resp != 100) {
11613 int statechanged = 0;
11614 int newstate = 0;
11615 peer = p->relatedpeer;
11616 gettimeofday(&tv, NULL);
11617 pingtime = ast_tvdiff_ms(tv, peer->ps);
11618 if (pingtime < 1)
11619 pingtime = 1;
11620 if ((peer->lastms < 0) || (peer->lastms > peer->maxms)) {
11621 if (pingtime <= peer->maxms) {
11622 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! (%dms / %dms)\n", peer->name, pingtime, peer->maxms);
11623 statechanged = 1;
11624 newstate = 1;
11626 } else if ((peer->lastms > 0) && (peer->lastms <= peer->maxms)) {
11627 if (pingtime > peer->maxms) {
11628 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED! (%dms / %dms)\n", peer->name, pingtime, peer->maxms);
11629 statechanged = 1;
11630 newstate = 2;
11633 if (!peer->lastms)
11634 statechanged = 1;
11635 peer->lastms = pingtime;
11636 peer->call = NULL;
11637 if (statechanged) {
11638 ast_device_state_changed("SIP/%s", peer->name);
11639 if (newstate == 2) {
11640 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Lagged\r\nTime: %d\r\n", peer->name, pingtime);
11641 } else {
11642 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Reachable\r\nTime: %d\r\n", peer->name, pingtime);
11646 if (peer->pokeexpire > -1)
11647 ast_sched_del(sched, peer->pokeexpire);
11648 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11650 /* Try again eventually */
11651 if ((peer->lastms < 0) || (peer->lastms > peer->maxms))
11652 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
11653 else
11654 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_OK, sip_poke_peer_s, peer);
11656 return 1;
11659 /*! \brief Handle SIP response in dialogue */
11660 /* XXX only called by handle_request */
11661 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
11663 struct ast_channel *owner;
11664 int sipmethod;
11665 int res = 1;
11666 const char *c = get_header(req, "Cseq");
11667 const char *msg = strchr(c, ' ');
11669 if (!msg)
11670 msg = "";
11671 else
11672 msg++;
11673 sipmethod = find_sip_method(msg);
11675 owner = p->owner;
11676 if (owner)
11677 owner->hangupcause = hangup_sip2cause(resp);
11679 /* Acknowledge whatever it is destined for */
11680 if ((resp >= 100) && (resp <= 199))
11681 __sip_semi_ack(p, seqno, 0, sipmethod);
11682 else
11683 __sip_ack(p, seqno, 0, sipmethod, resp == 491 ? TRUE : FALSE);
11685 /* Get their tag if we haven't already */
11686 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
11687 char tag[128];
11689 gettag(req, "To", tag, sizeof(tag));
11690 ast_string_field_set(p, theirtag, tag);
11692 if (p->relatedpeer && p->method == SIP_OPTIONS) {
11693 /* We don't really care what the response is, just that it replied back.
11694 Well, as long as it's not a 100 response... since we might
11695 need to hang around for something more "definitive" */
11697 res = handle_response_peerpoke(p, resp, req);
11698 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
11699 switch(resp) {
11700 case 100: /* 100 Trying */
11701 if (sipmethod == SIP_INVITE)
11702 handle_response_invite(p, resp, rest, req, seqno);
11703 break;
11704 case 183: /* 183 Session Progress */
11705 if (sipmethod == SIP_INVITE)
11706 handle_response_invite(p, resp, rest, req, seqno);
11707 break;
11708 case 180: /* 180 Ringing */
11709 if (sipmethod == SIP_INVITE)
11710 handle_response_invite(p, resp, rest, req, seqno);
11711 break;
11712 case 200: /* 200 OK */
11713 p->authtries = 0; /* Reset authentication counter */
11714 if (sipmethod == SIP_MESSAGE) {
11715 /* We successfully transmitted a message */
11716 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11717 } else if (sipmethod == SIP_INVITE) {
11718 handle_response_invite(p, resp, rest, req, seqno);
11719 } else if (sipmethod == SIP_NOTIFY) {
11720 /* They got the notify, this is the end */
11721 if (p->owner) {
11722 if (!p->refer) {
11723 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
11724 ast_queue_hangup(p->owner);
11725 } else if (option_debug > 3)
11726 ast_log(LOG_DEBUG, "Got OK on REFER Notify message\n");
11727 } else {
11728 if (p->subscribed == NONE)
11729 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11731 } else if (sipmethod == SIP_REGISTER)
11732 res = handle_response_register(p, resp, rest, req, ignore, seqno);
11733 else if (sipmethod == SIP_BYE) /* Ok, we're ready to go */
11734 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11735 break;
11736 case 202: /* Transfer accepted */
11737 if (sipmethod == SIP_REFER)
11738 handle_response_refer(p, resp, rest, req, seqno);
11739 break;
11740 case 401: /* Not www-authorized on SIP method */
11741 if (sipmethod == SIP_INVITE)
11742 handle_response_invite(p, resp, rest, req, seqno);
11743 else if (sipmethod == SIP_REFER)
11744 handle_response_refer(p, resp, rest, req, seqno);
11745 else if (p->registry && sipmethod == SIP_REGISTER)
11746 res = handle_response_register(p, resp, rest, req, ignore, seqno);
11747 else {
11748 ast_log(LOG_WARNING, "Got authentication request (401) on unknown %s to '%s'\n", sip_methods[sipmethod].text, get_header(req, "To"));
11749 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11751 break;
11752 case 403: /* Forbidden - we failed authentication */
11753 if (sipmethod == SIP_INVITE)
11754 handle_response_invite(p, resp, rest, req, seqno);
11755 else if (p->registry && sipmethod == SIP_REGISTER)
11756 res = handle_response_register(p, resp, rest, req, ignore, seqno);
11757 else {
11758 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
11759 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11761 break;
11762 case 404: /* Not found */
11763 if (p->registry && sipmethod == SIP_REGISTER)
11764 res = handle_response_register(p, resp, rest, req, ignore, seqno);
11765 else if (sipmethod == SIP_INVITE)
11766 handle_response_invite(p, resp, rest, req, seqno);
11767 else if (owner)
11768 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11769 break;
11770 case 407: /* Proxy auth required */
11771 if (sipmethod == SIP_INVITE)
11772 handle_response_invite(p, resp, rest, req, seqno);
11773 else if (sipmethod == SIP_REFER)
11774 handle_response_refer(p, resp, rest, req, seqno);
11775 else if (p->registry && sipmethod == SIP_REGISTER)
11776 res = handle_response_register(p, resp, rest, req, ignore, seqno);
11777 else if (sipmethod == SIP_BYE) {
11778 if (ast_strlen_zero(p->authname))
11779 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
11780 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
11781 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11782 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", sipmethod, 0)) {
11783 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
11784 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11786 } else /* We can't handle this, giving up in a bad way */
11787 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11789 break;
11790 case 481: /* Call leg does not exist */
11791 if (sipmethod == SIP_INVITE) {
11792 /* First we ACK */
11793 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11794 ast_log(LOG_WARNING, "INVITE with REPLACEs failed to '%s'\n", get_header(&p->initreq, "From"));
11795 if (owner)
11796 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11797 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
11798 } else if (sipmethod == SIP_REFER) {
11799 /* A transfer with Replaces did not work */
11800 /* OEJ: We should Set flag, cancel the REFER, go back
11801 to original call - but right now we can't */
11802 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
11803 if (owner)
11804 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11805 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11806 } else if (sipmethod == SIP_BYE) {
11807 /* The other side has no transaction to bye,
11808 just assume it's all right then */
11809 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
11810 } else if (sipmethod == SIP_CANCEL) {
11811 /* The other side has no transaction to cancel,
11812 just assume it's all right then */
11813 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
11814 } else {
11815 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
11816 /* Guessing that this is not an important request */
11818 break;
11819 case 491: /* Pending */
11820 if (sipmethod == SIP_INVITE)
11821 handle_response_invite(p, resp, rest, req, seqno);
11822 else {
11823 ast_log(LOG_DEBUG, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
11824 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11826 break;
11827 case 501: /* Not Implemented */
11828 if (sipmethod == SIP_INVITE)
11829 handle_response_invite(p, resp, rest, req, seqno);
11830 else if (sipmethod == SIP_REFER)
11831 handle_response_refer(p, resp, rest, req, seqno);
11832 else
11833 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
11834 break;
11835 case 603: /* Declined transfer */
11836 if (sipmethod == SIP_REFER) {
11837 handle_response_refer(p, resp, rest, req, seqno);
11838 break;
11840 /* Fallthrough */
11841 default:
11842 if ((resp >= 300) && (resp < 700)) {
11843 /* Fatal response */
11844 if ((option_verbose > 2) && (resp != 487))
11845 ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
11846 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
11847 if (p->rtp) {
11848 /* Immediately stop RTP */
11849 ast_rtp_stop(p->rtp);
11851 if (p->vrtp) {
11852 /* Immediately stop VRTP */
11853 ast_rtp_stop(p->vrtp);
11855 if (p->udptl) {
11856 /* Immediately stop UDPTL */
11857 ast_udptl_stop(p->udptl);
11859 /* XXX Locking issues?? XXX */
11860 switch(resp) {
11861 case 300: /* Multiple Choices */
11862 case 301: /* Moved permenantly */
11863 case 302: /* Moved temporarily */
11864 case 305: /* Use Proxy */
11865 parse_moved_contact(p, req);
11866 /* Fall through */
11867 case 486: /* Busy here */
11868 case 600: /* Busy everywhere */
11869 case 603: /* Decline */
11870 if (p->owner)
11871 ast_queue_control(p->owner, AST_CONTROL_BUSY);
11872 break;
11873 case 487: /* Response on INVITE that has been CANCELled */
11874 /* channel now destroyed - dec the inUse counter */
11875 if (owner)
11876 ast_queue_hangup(p->owner);
11877 update_call_counter(p, DEC_CALL_LIMIT);
11878 break;
11879 case 482: /*
11880 \note SIP is incapable of performing a hairpin call, which
11881 is yet another failure of not having a layer 2 (again, YAY
11882 IETF for thinking ahead). So we treat this as a call
11883 forward and hope we end up at the right place... */
11884 ast_log(LOG_DEBUG, "Hairpin detected, setting up call forward for what it's worth\n");
11885 if (p->owner)
11886 ast_string_field_build(p->owner, call_forward,
11887 "Local/%s@%s", p->username, p->context);
11888 /* Fall through */
11889 case 488: /* Not acceptable here - codec error */
11890 case 480: /* Temporarily Unavailable */
11891 case 404: /* Not Found */
11892 case 410: /* Gone */
11893 case 400: /* Bad Request */
11894 case 500: /* Server error */
11895 if (sipmethod == SIP_REFER) {
11896 handle_response_refer(p, resp, rest, req, seqno);
11897 break;
11899 /* Fall through */
11900 case 503: /* Service Unavailable */
11901 if (owner)
11902 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11903 break;
11904 default:
11905 /* Send hangup */
11906 if (owner)
11907 ast_queue_hangup(p->owner);
11908 break;
11910 /* ACK on invite */
11911 if (sipmethod == SIP_INVITE)
11912 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11913 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
11914 if (!p->owner)
11915 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11916 } else if ((resp >= 100) && (resp < 200)) {
11917 if (sipmethod == SIP_INVITE) {
11918 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11919 sip_cancel_destroy(p);
11920 if (find_sdp(req))
11921 process_sdp(p, req);
11922 if (p->owner) {
11923 /* Queue a progress frame */
11924 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
11927 } else
11928 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));
11930 } else {
11931 /* Responses to OUTGOING SIP requests on INCOMING calls
11932 get handled here. As well as out-of-call message responses */
11933 if (ast_test_flag(req, SIP_PKT_DEBUG))
11934 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
11936 if (sipmethod == SIP_INVITE && resp == 200) {
11937 /* Tags in early session is replaced by the tag in 200 OK, which is
11938 the final reply to our INVITE */
11939 char tag[128];
11941 gettag(req, "To", tag, sizeof(tag));
11942 ast_string_field_set(p, theirtag, tag);
11945 switch(resp) {
11946 case 200:
11947 if (sipmethod == SIP_INVITE) {
11948 handle_response_invite(p, resp, rest, req, seqno);
11949 } else if (sipmethod == SIP_CANCEL) {
11950 ast_log(LOG_DEBUG, "Got 200 OK on CANCEL\n");
11952 /* Wait for 487, then destroy */
11953 } else if (sipmethod == SIP_NOTIFY) {
11954 /* They got the notify, this is the end */
11955 if (p->owner) {
11956 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
11957 /* ast_queue_hangup(p->owner); Disabled */
11958 } else {
11959 if (!p->subscribed && !p->refer)
11960 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11962 } else if (sipmethod == SIP_BYE)
11963 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11964 else if (sipmethod == SIP_MESSAGE)
11965 /* We successfully transmitted a message */
11966 /* XXX Why destroy this pvt after message transfer? Bad */
11967 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11968 else if (sipmethod == SIP_BYE)
11969 /* Ok, we're ready to go */
11970 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11971 break;
11972 case 202: /* Transfer accepted */
11973 if (sipmethod == SIP_REFER)
11974 handle_response_refer(p, resp, rest, req, seqno);
11975 break;
11976 case 401: /* www-auth */
11977 case 407:
11978 if (sipmethod == SIP_REFER)
11979 handle_response_refer(p, resp, rest, req, seqno);
11980 else if (sipmethod == SIP_INVITE)
11981 handle_response_invite(p, resp, rest, req, seqno);
11982 else if (sipmethod == SIP_BYE) {
11983 char *auth, *auth2;
11985 auth = (resp == 407 ? "Proxy-Authenticate" : "WWW-Authenticate");
11986 auth2 = (resp == 407 ? "Proxy-Authorization" : "Authorization");
11987 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, auth, auth2, sipmethod, 0)) {
11988 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
11989 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11992 break;
11993 case 481: /* Call leg does not exist */
11994 if (sipmethod == SIP_INVITE) {
11995 /* Re-invite failed */
11996 handle_response_invite(p, resp, rest, req, seqno);
11997 } else if (sipmethod == SIP_BYE) {
11998 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11999 } else if (sipdebug) {
12000 ast_log (LOG_DEBUG, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
12002 break;
12003 case 501: /* Not Implemented */
12004 if (sipmethod == SIP_INVITE)
12005 handle_response_invite(p, resp, rest, req, seqno);
12006 else if (sipmethod == SIP_REFER)
12007 handle_response_refer(p, resp, rest, req, seqno);
12008 break;
12009 case 603: /* Declined transfer */
12010 if (sipmethod == SIP_REFER) {
12011 handle_response_refer(p, resp, rest, req, seqno);
12012 break;
12014 /* Fallthrough */
12015 default: /* Errors without handlers */
12016 if ((resp >= 100) && (resp < 200)) {
12017 if (sipmethod == SIP_INVITE) { /* re-invite */
12018 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12019 sip_cancel_destroy(p);
12022 if ((resp >= 300) && (resp < 700)) {
12023 if ((option_verbose > 2) && (resp != 487))
12024 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));
12025 switch(resp) {
12026 case 488: /* Not acceptable here - codec error */
12027 case 603: /* Decline */
12028 case 500: /* Server error */
12029 case 503: /* Service Unavailable */
12031 if (sipmethod == SIP_INVITE) { /* re-invite failed */
12032 sip_cancel_destroy(p);
12034 break;
12037 break;
12043 /*! \brief Park SIP call support function
12044 Starts in a new thread, then parks the call
12045 XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
12046 audio can't be heard before hangup
12048 static void *sip_park_thread(void *stuff)
12050 struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
12051 struct sip_dual *d;
12052 struct sip_request req;
12053 int ext;
12054 int res;
12056 d = stuff;
12057 transferee = d->chan1;
12058 transferer = d->chan2;
12059 copy_request(&req, &d->req);
12060 free(d);
12062 if (!transferee || !transferer) {
12063 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
12064 return NULL;
12066 if (option_debug > 3)
12067 ast_log(LOG_DEBUG, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
12069 ast_channel_lock(transferee);
12070 if (ast_do_masquerade(transferee)) {
12071 ast_log(LOG_WARNING, "Masquerade failed.\n");
12072 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
12073 ast_channel_unlock(transferee);
12074 return NULL;
12076 ast_channel_unlock(transferee);
12078 res = ast_park_call(transferee, transferer, 0, &ext);
12081 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
12082 if (!res) {
12083 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
12084 } else {
12085 /* Then tell the transferer what happened */
12086 sprintf(buf, "Call parked on extension '%d'", ext);
12087 transmit_message_with_text(transferer->tech_pvt, buf);
12089 #endif
12091 /* Any way back to the current call??? */
12092 /* Transmit response to the REFER request */
12093 transmit_response(transferer->tech_pvt, "202 Accepted", &req);
12094 if (!res) {
12095 /* Transfer succeeded */
12096 append_history(transferer->tech_pvt, "SIPpark","Parked call on %d", ext);
12097 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
12098 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
12099 ast_hangup(transferer); /* This will cause a BYE */
12100 if (option_debug)
12101 ast_log(LOG_DEBUG, "SIP Call parked on extension '%d'\n", ext);
12102 } else {
12103 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
12104 append_history(transferer->tech_pvt, "SIPpark","Parking failed\n");
12105 if (option_debug)
12106 ast_log(LOG_DEBUG, "SIP Call parked failed \n");
12107 /* Do not hangup call */
12109 return NULL;
12112 /*! \brief Park a call using the subsystem in res_features.c
12113 This is executed in a separate thread
12115 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
12117 struct sip_dual *d;
12118 struct ast_channel *transferee, *transferer;
12119 /* Chan2m: The transferer, chan1m: The transferee */
12120 pthread_t th;
12122 transferee = ast_channel_alloc(0);
12123 transferer = ast_channel_alloc(0);
12124 if ((!transferer) || (!transferee)) {
12125 if (transferee) {
12126 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
12127 ast_hangup(transferee);
12129 if (transferer) {
12130 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
12131 ast_hangup(transferer);
12133 return -1;
12135 ast_string_field_build(transferee, name, "Parking/%s", chan1->name);
12137 /* Make formats okay */
12138 transferee->readformat = chan1->readformat;
12139 transferee->writeformat = chan1->writeformat;
12141 /* Prepare for taking over the channel */
12142 ast_channel_masquerade(transferee, chan1);
12144 /* Setup the extensions and such */
12145 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
12146 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
12147 transferee->priority = chan1->priority;
12149 /* We make a clone of the peer channel too, so we can play
12150 back the announcement */
12151 ast_string_field_build(transferer, name, "SIPPeer/%s", chan2->name);
12153 /* Make formats okay */
12154 transferer->readformat = chan2->readformat;
12155 transferer->writeformat = chan2->writeformat;
12157 /* Prepare for taking over the channel */
12158 ast_channel_masquerade(transferer, chan2);
12160 /* Setup the extensions and such */
12161 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
12162 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
12163 transferer->priority = chan2->priority;
12165 ast_channel_lock(transferer);
12166 if (ast_do_masquerade(transferer)) {
12167 ast_log(LOG_WARNING, "Masquerade failed :(\n");
12168 ast_channel_unlock(transferer);
12169 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
12170 ast_hangup(transferer);
12171 return -1;
12173 ast_channel_unlock(transferer);
12174 if (!transferer || !transferee) {
12175 if (!transferer)
12176 ast_log(LOG_DEBUG, "No transferer channel, giving up parking\n");
12177 if (!transferee)
12178 ast_log(LOG_DEBUG, "No transferee channel, giving up parking\n");
12179 return -1;
12181 if ((d = ast_calloc(1, sizeof(*d)))) {
12182 /* Save original request for followup */
12183 copy_request(&d->req, req);
12184 d->chan1 = transferee; /* Transferee */
12185 d->chan2 = transferer; /* Transferer */
12186 d->seqno = seqno;
12187 if (ast_pthread_create(&th, NULL, sip_park_thread, d) < 0) {
12188 /* Could not start thread */
12189 free(d); /* We don't need it anymore. If thread is created, d will be free'd
12190 by sip_park_thread() */
12191 return 0;
12194 return -1;
12197 /*! \brief Turn off generator data
12198 XXX Does this function belong in the SIP channel?
12200 static void ast_quiet_chan(struct ast_channel *chan)
12202 if (chan && chan->_state == AST_STATE_UP) {
12203 if (chan->generatordata)
12204 ast_deactivate_generator(chan);
12208 /*! \brief Attempt transfer of SIP call
12209 This fix for attended transfers on a local PBX */
12210 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
12212 int res = 0;
12213 struct ast_channel *peera = NULL,
12214 *peerb = NULL,
12215 *peerc = NULL,
12216 *peerd = NULL;
12219 /* We will try to connect the transferee with the target and hangup
12220 all channels to the transferer */
12221 if (option_debug > 3) {
12222 ast_log(LOG_DEBUG, "Sip transfer:--------------------\n");
12223 if (transferer->chan1)
12224 ast_log(LOG_DEBUG, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
12225 else
12226 ast_log(LOG_DEBUG, "-- No transferer first channel - odd??? \n");
12227 if (target->chan1)
12228 ast_log(LOG_DEBUG, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
12229 else
12230 ast_log(LOG_DEBUG, "-- No target first channel ---\n");
12231 if (transferer->chan2)
12232 ast_log(LOG_DEBUG, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
12233 else
12234 ast_log(LOG_DEBUG, "-- No bridged call to transferee\n");
12235 if (target->chan2)
12236 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)");
12237 else
12238 ast_log(LOG_DEBUG, "-- No target second channel ---\n");
12239 ast_log(LOG_DEBUG, "-- END Sip transfer:--------------------\n");
12241 if (transferer->chan2) { /* We have a bridge on the transferer's channel */
12242 peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
12243 peerb = target->chan1; /* Transferer - PBX -> target channel - This will get lost in masq */
12244 peerc = transferer->chan2; /* Asterisk to Transferee */
12245 peerd = target->chan2; /* Asterisk to Target */
12246 if (option_debug > 2)
12247 ast_log(LOG_DEBUG, "SIP transfer: Four channels to handle\n");
12248 } else if (target->chan2) { /* Transferer has no bridge (IVR), but transferee */
12249 peera = target->chan1; /* Transferer to PBX -> target channel */
12250 peerb = transferer->chan1; /* Transferer to IVR*/
12251 peerc = target->chan2; /* Asterisk to Target */
12252 peerd = transferer->chan2; /* Nothing */
12253 if (option_debug > 2)
12254 ast_log(LOG_DEBUG, "SIP transfer: Three channels to handle\n");
12257 if (peera && peerb && peerc && (peerb != peerc)) {
12258 ast_quiet_chan(peera); /* Stop generators */
12259 ast_quiet_chan(peerb);
12260 ast_quiet_chan(peerc);
12261 if (peerd)
12262 ast_quiet_chan(peerd);
12264 /* Fix CDRs so they're attached to the remaining channel */
12265 if (peera->cdr && peerb->cdr)
12266 peerb->cdr = ast_cdr_append(peerb->cdr, peera->cdr);
12267 else if (peera->cdr)
12268 peerb->cdr = peera->cdr;
12269 peera->cdr = NULL;
12271 if (peerb->cdr && peerc->cdr)
12272 peerb->cdr = ast_cdr_append(peerb->cdr, peerc->cdr);
12273 else if (peerc->cdr)
12274 peerb->cdr = peerc->cdr;
12275 peerc->cdr = NULL;
12277 if (option_debug > 3)
12278 ast_log(LOG_DEBUG, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
12279 if (ast_channel_masquerade(peerb, peerc)) {
12280 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
12281 res = -1;
12282 } else
12283 ast_log(LOG_DEBUG, "SIP transfer: Succeeded to masquerade channels.\n");
12284 return res;
12285 } else {
12286 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
12287 if (transferer->chan1)
12288 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
12289 if (target->chan1)
12290 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
12291 return -1;
12293 return 0;
12296 /*! \brief Get tag from packet
12298 * \return Returns the pointer to the provided tag buffer,
12299 * or NULL if the tag was not found.
12301 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
12303 const char *thetag;
12305 if (!tagbuf)
12306 return NULL;
12307 tagbuf[0] = '\0'; /* reset the buffer */
12308 thetag = get_header(req, header);
12309 thetag = strcasestr(thetag, ";tag=");
12310 if (thetag) {
12311 thetag += 5;
12312 ast_copy_string(tagbuf, thetag, tagbufsize);
12313 return strsep(&tagbuf, ";");
12315 return NULL;
12318 /*! \brief Handle incoming notifications */
12319 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
12321 /* This is mostly a skeleton for future improvements */
12322 /* Mostly created to return proper answers on notifications on outbound REFER's */
12323 int res = 0;
12324 const char *event = get_header(req, "Event");
12325 char *eventid = NULL;
12326 char *sep;
12328 if( (sep = strchr(event, ';')) ) { /* XXX bug here - overwriting string ? */
12329 *sep++ = '\0';
12330 eventid = sep;
12333 if (option_debug > 1 && sipdebug)
12334 ast_log(LOG_DEBUG, "Got NOTIFY Event: %s\n", event);
12336 if (strcmp(event, "refer")) {
12337 /* We don't understand this event. */
12338 /* Here's room to implement incoming voicemail notifications :-) */
12339 transmit_response(p, "489 Bad event", req);
12340 if (!p->lastinvite)
12341 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12342 return -1;
12343 } else {
12344 /* Save nesting depth for now, since there might be other events we will
12345 support in the future */
12347 /* Handle REFER notifications */
12349 char buf[1024];
12350 char *cmd, *code;
12351 int respcode;
12352 int success = TRUE;
12354 /* EventID for each transfer... EventID is basically the REFER cseq
12356 We are getting notifications on a call that we transfered
12357 We should hangup when we are getting a 200 OK in a sipfrag
12358 Check if we have an owner of this event */
12360 /* Check the content type */
12361 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
12362 /* We need a sipfrag */
12363 transmit_response(p, "400 Bad request", req);
12364 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12365 return -1;
12368 /* Get the text of the attachment */
12369 if (get_msg_text(buf, sizeof(buf), req)) {
12370 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
12371 transmit_response(p, "400 Bad request", req);
12372 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12373 return -1;
12377 From the RFC...
12378 A minimal, but complete, implementation can respond with a single
12379 NOTIFY containing either the body:
12380 SIP/2.0 100 Trying
12382 if the subscription is pending, the body:
12383 SIP/2.0 200 OK
12384 if the reference was successful, the body:
12385 SIP/2.0 503 Service Unavailable
12386 if the reference failed, or the body:
12387 SIP/2.0 603 Declined
12389 if the REFER request was accepted before approval to follow the
12390 reference could be obtained and that approval was subsequently denied
12391 (see Section 2.4.7).
12393 If there are several REFERs in the same dialog, we need to
12394 match the ID of the event header...
12396 if (option_debug > 2)
12397 ast_log(LOG_DEBUG, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
12398 cmd = ast_skip_blanks(buf);
12399 code = cmd;
12400 /* We are at SIP/2.0 */
12401 while(*code && (*code > 32)) { /* Search white space */
12402 code++;
12404 *code++ = '\0';
12405 code = ast_skip_blanks(code);
12406 sep = code;
12407 sep++;
12408 while(*sep && (*sep > 32)) { /* Search white space */
12409 sep++;
12411 *sep++ = '\0'; /* Response string */
12412 respcode = atoi(code);
12413 switch (respcode) {
12414 case 100: /* Trying: */
12415 /* Don't do anything yet */
12416 break;
12417 case 183: /* Ringing: */
12418 /* Don't do anything yet */
12419 break;
12420 case 200: /* OK: The new call is up, hangup this call */
12421 /* Hangup the call that we are replacing */
12422 break;
12423 case 301: /* Moved permenantly */
12424 case 302: /* Moved temporarily */
12425 /* Do we get the header in the packet in this case? */
12426 success = FALSE;
12427 break;
12428 case 503: /* Service Unavailable: The new call failed */
12429 /* Cancel transfer, continue the call */
12430 success = FALSE;
12431 break;
12432 case 603: /* Declined: Not accepted */
12433 /* Cancel transfer, continue the current call */
12434 success = FALSE;
12435 break;
12437 if (!success) {
12438 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
12441 /* Confirm that we received this packet */
12442 transmit_response(p, "200 OK", req);
12443 return res;
12447 /*! \brief Handle incoming OPTIONS request */
12448 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
12450 int res;
12452 res = get_destination(p, req);
12453 build_contact(p);
12454 /* XXX Should we authenticate OPTIONS? XXX */
12455 if (ast_strlen_zero(p->context))
12456 ast_string_field_set(p, context, default_context);
12457 if (res < 0)
12458 transmit_response_with_allow(p, "404 Not Found", req, 0);
12459 else
12460 transmit_response_with_allow(p, "200 OK", req, 0);
12461 /* Destroy if this OPTIONS was the opening request, but not if
12462 it's in the middle of a normal call flow. */
12463 if (!p->lastinvite)
12464 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12466 return res;
12469 /*! \brief Handle the transfer part of INVITE with a replaces: header,
12470 meaning a target pickup or an attended transfer */
12471 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin)
12473 struct ast_frame *f;
12474 int earlyreplace = 0;
12475 int oneleggedreplace = 0; /* Call with no bridge, propably IVR or voice message */
12476 struct ast_channel *c = p->owner; /* Our incoming call */
12477 struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
12478 struct ast_channel *targetcall; /* The bridge to the take-over target */
12480 /* Check if we're in ring state */
12481 if (replacecall->_state == AST_STATE_RING)
12482 earlyreplace = 1;
12484 /* Check if we have a bridge */
12485 if (!(targetcall = ast_bridged_channel(replacecall))) {
12486 /* We have no bridge */
12487 if (!earlyreplace) {
12488 if (option_debug > 1)
12489 ast_log(LOG_DEBUG, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
12490 oneleggedreplace = 1;
12493 if (option_debug > 3 && targetcall && targetcall->_state == AST_STATE_RINGING)
12494 ast_log(LOG_DEBUG, "SIP transfer: Target channel is in ringing state\n");
12496 if (option_debug > 3) {
12497 if (targetcall)
12498 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);
12499 else
12500 ast_log(LOG_DEBUG, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
12503 if (ignore) {
12504 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
12505 /* We should answer something here. If we are here, the
12506 call we are replacing exists, so an accepted
12507 can't harm */
12508 transmit_response_with_sdp(p, "200 OK", req, 1);
12509 /* Do something more clever here */
12510 ast_channel_unlock(c);
12511 ast_mutex_unlock(&p->refer->refer_call->lock);
12512 return 1;
12514 if (!c) {
12515 /* What to do if no channel ??? */
12516 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
12517 transmit_response_with_sdp(p, "503 Service Unavailable", req, 1);
12518 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
12519 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12520 ast_mutex_unlock(&p->refer->refer_call->lock);
12521 return 1;
12523 append_history(p, "Xfer", "INVITE/Replace received");
12524 /* We have three channels to play with
12525 channel c: New incoming call
12526 targetcall: Call from PBX to target
12527 p->refer->refer_call: SIP pvt dialog from transferer to pbx.
12528 replacecall: The owner of the previous
12529 We need to masq C into refer_call to connect to
12530 targetcall;
12531 If we are talking to internal audio stream, target call is null.
12534 /* Fake call progress */
12535 transmit_response(p, "100 Trying", req);
12536 ast_setstate(c, AST_STATE_RING);
12538 /* Masquerade the new call into the referred call to connect to target call
12539 Targetcall is not touched by the masq */
12541 /* Answer the incoming call and set channel to UP state */
12542 transmit_response_with_sdp(p, "200 OK", req, 1);
12543 ast_setstate(c, AST_STATE_UP);
12545 /* Stop music on hold and other generators */
12546 ast_quiet_chan(replacecall);
12547 ast_quiet_chan(targetcall);
12548 if (option_debug > 3)
12549 ast_log(LOG_DEBUG, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
12550 /* Unlock clone, but not original (replacecall) */
12551 ast_channel_unlock(c);
12553 /* Unlock PVT */
12554 ast_mutex_unlock(&p->refer->refer_call->lock);
12556 /* Make sure that the masq does not free our PVT for the old call */
12557 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
12559 /* Prepare the masquerade - if this does not happen, we will be gone */
12560 if(ast_channel_masquerade(replacecall, c))
12561 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
12562 else if (option_debug > 3)
12563 ast_log(LOG_DEBUG, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
12565 /* The masquerade will happen as soon as someone reads a frame from the channel */
12567 /* C should now be in place of replacecall */
12568 /* ast_read needs to lock channel */
12569 ast_channel_unlock(c);
12571 if (earlyreplace || oneleggedreplace ) {
12572 /* Force the masq to happen */
12573 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
12574 ast_frfree(f);
12575 f = NULL;
12576 if (option_debug > 3)
12577 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from RING channel!\n");
12578 } else {
12579 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from RING channel \n");
12581 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
12582 ast_channel_unlock(replacecall);
12583 } else { /* Bridged call, UP channel */
12584 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
12585 /* Masq ok */
12586 ast_frfree(f);
12587 f = NULL;
12588 if (option_debug > 2)
12589 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from channel! Masq done.\n");
12590 } else {
12591 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from channel. Transfer failed\n");
12593 ast_channel_unlock(replacecall);
12595 ast_mutex_unlock(&p->refer->refer_call->lock);
12597 ast_setstate(c, AST_STATE_DOWN);
12598 if (option_debug > 3) {
12599 struct ast_channel *test;
12600 ast_log(LOG_DEBUG, "After transfer:----------------------------\n");
12601 ast_log(LOG_DEBUG, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
12602 if (replacecall)
12603 ast_log(LOG_DEBUG, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
12604 if (p->owner) {
12605 ast_log(LOG_DEBUG, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
12606 test = ast_bridged_channel(p->owner);
12607 if (test)
12608 ast_log(LOG_DEBUG, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
12609 else
12610 ast_log(LOG_DEBUG, " -- No call bridged to C->owner \n");
12611 } else
12612 ast_log(LOG_DEBUG, " -- No channel yet \n");
12613 ast_log(LOG_DEBUG, "End After transfer:----------------------------\n");
12616 ast_channel_unlock(p->owner); /* Unlock new owner */
12617 ast_mutex_unlock(&p->lock); /* Unlock SIP structure */
12619 /* The call should be down with no ast_channel, so hang it up */
12620 c->tech_pvt = NULL;
12621 ast_hangup(c);
12622 return 0;
12626 /*! \brief Handle incoming INVITE request
12627 \note If the INVITE has a Replaces header, it is part of an
12628 * attended transfer. If so, we do not go through the dial
12629 * plan but tries to find the active call and masquerade
12630 * into it
12632 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)
12634 int res = 1;
12635 int gotdest;
12636 const char *p_replaces;
12637 char *replace_id = NULL;
12638 const char *required;
12639 unsigned int required_profile = 0;
12640 struct ast_channel *c = NULL; /* New channel */
12642 /* Find out what they support */
12643 if (!p->sipoptions) {
12644 const char *supported = get_header(req, "Supported");
12645 if (supported)
12646 parse_sip_options(p, supported);
12649 /* Find out what they require */
12650 required = get_header(req, "Require");
12651 if (required && !ast_strlen_zero(required)) {
12652 required_profile = parse_sip_options(NULL, required);
12653 if (required_profile && required_profile != SIP_OPT_REPLACES) {
12654 /* At this point we only support REPLACES */
12655 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
12656 ast_log(LOG_WARNING,"Received SIP INVITE with unsupported required extension: %s\n", required);
12657 if (!p->lastinvite)
12658 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12659 return -1;
12663 /* Check if this is a loop */
12664 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->owner->_state != AST_STATE_UP)) {
12665 /* This is a call to ourself. Send ourselves an error code and stop
12666 processing immediately, as SIP really has no good mechanism for
12667 being able to call yourself */
12668 /* If pedantic is on, we need to check the tags. If they're different, this is
12669 in fact a forked call through a SIP proxy somewhere. */
12670 transmit_response(p, "482 Loop Detected", req);
12671 /* We do NOT destroy p here, so that our response will be accepted */
12672 return 0;
12675 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->pendinginvite) {
12676 /* We already have a pending invite. Sorry. You are on hold. */
12677 transmit_response(p, "491 Request Pending", req);
12678 if (option_debug)
12679 ast_log(LOG_DEBUG, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
12680 return 0;
12683 if ((p_replaces = get_header(req, "Replaces")) && !ast_strlen_zero(p_replaces)) {
12684 /* We have a replaces header */
12685 char *ptr;
12686 char *fromtag = NULL;
12687 char *totag = NULL;
12688 char *start, *to;
12689 int error = 0;
12691 if (p->owner) {
12692 if (option_debug > 2)
12693 ast_log(LOG_DEBUG, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
12694 transmit_response(p, "400 Bad request", req); /* The best way to not not accept the transfer */
12695 /* Do not destroy existing call */
12696 return -1;
12699 if (sipdebug && option_debug > 2)
12700 ast_log(LOG_DEBUG, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
12701 /* Create a buffer we can manipulate */
12702 replace_id = ast_strdupa(p_replaces);
12703 ast_uri_decode(replace_id);
12705 if (!p->refer && !sip_refer_allocate(p)) {
12706 transmit_response(p, "500 Server Internal Error", req);
12707 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
12708 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12709 return -1;
12712 /* Todo: (When we find phones that support this)
12713 if the replaces header contains ";early-only"
12714 we can only replace the call in early
12715 stage, not after it's up.
12717 If it's not in early mode, 486 Busy.
12720 /* Skip leading whitespace */
12721 replace_id = ast_skip_blanks(replace_id);
12723 start = replace_id;
12724 while ( (ptr = strsep(&start, ";")) ) {
12725 ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
12726 if ( (to = strcasestr(ptr, "to-tag=") ) )
12727 totag = to + 7; /* skip the keyword */
12728 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
12729 fromtag = to + 9; /* skip the keyword */
12730 fromtag = strsep(&fromtag, "&"); /* trim what ? */
12734 if (sipdebug && option_debug > 3)
12735 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>");
12738 /* Try to find call that we are replacing
12739 If we have a Replaces header, we need to cancel that call if we succeed with this call
12741 if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
12742 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
12743 transmit_response(p, "481 Call Leg Does Not Exist (Replaces)", req);
12744 error = 1;
12747 /* At this point, bot the pvt and the owner of the call to be replaced is locked */
12749 /* The matched call is the call from the transferer to Asterisk .
12750 We want to bridge the bridged part of the call to the
12751 incoming invite, thus taking over the refered call */
12753 if (p->refer->refer_call == p) {
12754 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
12755 p->refer->refer_call = NULL;
12756 transmit_response(p, "400 Bad request", req); /* The best way to not not accept the transfer */
12757 error = 1;
12760 if (!error && !p->refer->refer_call->owner) {
12761 /* Oops, someting wrong anyway, no owner, no call */
12762 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
12763 /* Check for better return code */
12764 transmit_response(p, "481 Call Leg Does Not Exist (Replace)", req);
12765 error = 1;
12768 if (!error && p->refer->refer_call->owner->_state != AST_STATE_RING && p->refer->refer_call->owner->_state != AST_STATE_UP ) {
12769 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
12770 transmit_response(p, "603 Declined (Replaces)", req);
12771 error = 1;
12774 if (error) { /* Give up this dialog */
12775 append_history(p, "Xfer", "INVITE/Replace Failed.");
12776 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12777 ast_mutex_unlock(&p->lock);
12778 if (p->refer->refer_call) {
12779 ast_mutex_unlock(&p->refer->refer_call->lock);
12780 ast_channel_unlock(p->refer->refer_call->owner);
12782 return -1;
12787 /* Check if this is an INVITE that sets up a new dialog or
12788 a re-invite in an existing dialog */
12790 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
12791 sip_cancel_destroy(p);
12792 /* This also counts as a pending invite */
12793 p->pendinginvite = seqno;
12794 check_via(p, req);
12796 if (!p->owner) { /* Not a re-invite */
12797 /* Use this as the basis */
12798 copy_request(&p->initreq, req);
12799 if (debug)
12800 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
12801 append_history(p, "Invite", "New call: %s", p->callid);
12802 parse_ok_contact(p, req);
12803 } else { /* Re-invite on existing call */
12804 /* Handle SDP here if we already have an owner */
12805 if (find_sdp(req)) {
12806 if (process_sdp(p, req)) {
12807 transmit_response(p, "488 Not acceptable here", req);
12808 if (!p->lastinvite)
12809 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12810 return -1;
12812 } else {
12813 p->jointcapability = p->capability;
12814 ast_log(LOG_DEBUG, "Hm.... No sdp for the moment\n");
12816 if (recordhistory) /* This is a response, note what it was for */
12817 append_history(p, "ReInv", "Re-invite received");
12819 } else if (debug)
12820 ast_verbose("Ignoring this INVITE request\n");
12823 if (!p->lastinvite && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner) {
12824 /* This is a new invite */
12825 /* Handle authentication if this is our first invite */
12826 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
12827 if (res == AUTH_CHALLENGE_SENT)
12828 return 0;
12829 if (res < 0) { /* Something failed in authentication */
12830 if (res == AUTH_FAKE_AUTH) {
12831 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
12832 transmit_fake_auth_response(p, req, 1);
12833 } else {
12834 ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
12835 transmit_response_reliable(p, "403 Forbidden", req);
12837 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12838 ast_string_field_free(p, theirtag);
12839 return 0;
12842 /* We have a succesful authentication, process the SDP portion if there is one */
12843 if (find_sdp(req)) {
12844 if (process_sdp(p, req)) {
12845 /* Unacceptable codecs */
12846 transmit_response_reliable(p, "488 Not acceptable here", req);
12847 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12848 if (option_debug)
12849 ast_log(LOG_DEBUG, "No compatible codecs for this SIP call.\n");
12850 return -1;
12852 } else { /* No SDP in invite, call control session */
12853 p->jointcapability = p->capability;
12854 if (option_debug > 1)
12855 ast_log(LOG_DEBUG, "No SDP in Invite, third party call control\n");
12858 /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
12859 /* This seems redundant ... see !p-owner above */
12860 if (p->owner)
12861 ast_queue_frame(p->owner, &ast_null_frame);
12864 /* Initialize the context if it hasn't been already */
12865 if (ast_strlen_zero(p->context))
12866 ast_string_field_set(p, context, default_context);
12869 /* Check number of concurrent calls -vs- incoming limit HERE */
12870 if (option_debug)
12871 ast_log(LOG_DEBUG, "Checking SIP call limits for device %s\n", p->username);
12872 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
12873 if (res < 0) {
12874 ast_log(LOG_NOTICE, "Failed to place call for user %s, too many calls\n", p->username);
12875 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
12876 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12878 return 0;
12880 gotdest = get_destination(p, NULL); /* Get destination right away */
12881 get_rdnis(p, NULL); /* Get redirect information */
12882 extract_uri(p, req); /* Get the Contact URI */
12883 build_contact(p); /* Build our contact header */
12884 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_INFO);
12885 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
12887 if (!replace_id && gotdest) { /* No matching extension found */
12888 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
12889 transmit_response_reliable(p, "484 Address Incomplete", req);
12890 update_call_counter(p, DEC_CALL_LIMIT);
12891 } else {
12892 transmit_response_reliable(p, "404 Not Found", req);
12893 update_call_counter(p, DEC_CALL_LIMIT);
12895 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12896 } else {
12897 /* If no extension was specified, use the s one */
12898 /* Basically for calling to IP/Host name only */
12899 if (ast_strlen_zero(p->exten))
12900 ast_string_field_set(p, exten, "s");
12901 /* Initialize our tag */
12903 make_our_tag(p->tag, sizeof(p->tag));
12905 /* First invitation - create the channel */
12906 c = sip_new(p, AST_STATE_DOWN, S_OR(p->username, NULL));
12907 *recount = 1;
12909 /* Save Record-Route for any later requests we make on this dialogue */
12910 build_route(p, req, 0);
12912 if (c) {
12913 /* Pre-lock the call */
12914 ast_channel_lock(c);
12917 } else {
12918 if (option_debug > 1 && sipdebug) {
12919 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12920 ast_log(LOG_DEBUG, "Got a SIP re-invite for call %s\n", p->callid);
12921 else
12922 ast_log(LOG_DEBUG, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
12924 c = p->owner;
12927 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
12928 p->lastinvite = seqno;
12930 if (replace_id) { /* Attended transfer or call pickup - we're the target */
12931 /* Go and take over the target call */
12932 if (sipdebug && option_debug > 3)
12933 ast_log(LOG_DEBUG, "Sending this call to the invite/replcaes handler %s\n", p->callid);
12934 return handle_invite_replaces(p, req, debug, ast_test_flag(req, SIP_PKT_IGNORE), seqno, sin);
12938 if (c) { /* We have a call -either a new call or an old one (RE-INVITE) */
12939 switch(c->_state) {
12940 case AST_STATE_DOWN:
12941 if (option_debug > 1)
12942 ast_log(LOG_DEBUG, "%s: New call is still down.... Trying... \n", c->name);
12943 transmit_response(p, "100 Trying", req);
12944 ast_setstate(c, AST_STATE_RING);
12945 if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
12946 enum ast_pbx_result res;
12948 res = ast_pbx_start(c);
12950 switch(res) {
12951 case AST_PBX_FAILED:
12952 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
12953 if (ast_test_flag(req, SIP_PKT_IGNORE))
12954 transmit_response(p, "503 Unavailable", req);
12955 else
12956 transmit_response_reliable(p, "503 Unavailable", req);
12957 break;
12958 case AST_PBX_CALL_LIMIT:
12959 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
12960 if (ast_test_flag(req, SIP_PKT_IGNORE))
12961 transmit_response(p, "480 Temporarily Unavailable", req);
12962 else
12963 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
12964 break;
12965 case AST_PBX_SUCCESS:
12966 /* nothing to do */
12967 break;
12970 if (res) {
12972 /* Unlock locks so ast_hangup can do its magic */
12973 ast_mutex_unlock(&c->lock);
12974 ast_mutex_unlock(&p->lock);
12975 ast_hangup(c);
12976 ast_mutex_lock(&p->lock);
12977 c = NULL;
12979 } else { /* Pickup call in call group */
12980 ast_channel_unlock(c);
12981 if (ast_pickup_call(c)) {
12982 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
12983 if (ast_test_flag(req, SIP_PKT_IGNORE))
12984 transmit_response(p, "503 Unavailable", req); /* OEJ - Right answer? */
12985 else
12986 transmit_response_reliable(p, "503 Unavailable", req);
12987 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
12988 /* Unlock locks so ast_hangup can do its magic */
12989 ast_mutex_unlock(&p->lock);
12990 c->hangupcause = AST_CAUSE_CALL_REJECTED;
12991 } else {
12992 ast_mutex_unlock(&p->lock);
12993 ast_setstate(c, AST_STATE_DOWN);
12994 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
12996 ast_hangup(c);
12997 ast_mutex_lock(&p->lock);
12998 c = NULL;
13000 break;
13001 case AST_STATE_RING:
13002 transmit_response(p, "100 Trying", req);
13003 break;
13004 case AST_STATE_RINGING:
13005 transmit_response(p, "180 Ringing", req);
13006 break;
13007 case AST_STATE_UP:
13008 if (option_debug > 1)
13009 ast_log(LOG_DEBUG, "%s: This call is UP.... \n", c->name);
13011 if (p->t38.state == T38_PEER_REINVITE) {
13012 struct ast_channel *bridgepeer = NULL;
13013 struct sip_pvt *bridgepvt = NULL;
13015 if ((bridgepeer = ast_bridged_channel(p->owner))) {
13016 /* 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*/
13017 /*! XXX: we should also check here does the other side supports t38 at all !!! XXX */
13018 if (!strcasecmp(bridgepeer->tech->type, "SIP")) { /* If we are bridged to SIP channel */
13019 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
13020 if (bridgepvt->t38.state == T38_DISABLED) {
13021 if (bridgepvt->udptl) { /* If everything is OK with other side's udptl struct */
13022 /* Send re-invite to the bridged channel */
13023 sip_handle_t38_reinvite(bridgepeer, p, 1);
13024 } else { /* Something is wrong with peers udptl struct */
13025 ast_log(LOG_WARNING, "Strange... The other side of the bridge don't have udptl struct\n");
13026 ast_mutex_lock(&bridgepvt->lock);
13027 bridgepvt->t38.state = T38_DISABLED;
13028 ast_mutex_unlock(&bridgepvt->lock);
13029 if (option_debug > 1)
13030 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->name);
13031 if (ast_test_flag(req, SIP_PKT_IGNORE))
13032 transmit_response(p, "488 Not acceptable here", req);
13033 else
13034 transmit_response_reliable(p, "488 Not acceptable here", req);
13035 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13038 } else {
13039 /* Other side is not a SIP channel */
13040 if (ast_test_flag(req, SIP_PKT_IGNORE))
13041 transmit_response(p, "488 Not acceptable here", req);
13042 else
13043 transmit_response_reliable(p, "488 Not acceptable here", req);
13044 p->t38.state = T38_DISABLED;
13045 if (option_debug > 1)
13046 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
13047 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13049 } else {
13050 /* we are not bridged in a call */
13051 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
13052 p->t38.state = T38_ENABLED;
13053 if (option_debug)
13054 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
13056 } else if (p->t38.state == T38_DISABLED) { /* Channel doesn't have T38 offered or enabled */
13057 int sendok = TRUE;
13059 /* If we are bridged to a channel that has T38 enabled than this is a case of RTP re-invite after T38 session */
13060 /* so handle it here (re-invite other party to RTP) */
13061 struct ast_channel *bridgepeer = NULL;
13062 struct sip_pvt *bridgepvt = NULL;
13063 if ((bridgepeer = ast_bridged_channel(p->owner))) {
13064 if (!strcasecmp(bridgepeer->tech->type, sip_tech.type)) {
13065 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
13066 /* Does the bridged peer have T38 ? */
13067 if (bridgepvt->t38.state == T38_ENABLED) {
13068 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
13069 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
13070 if (ast_test_flag(req, SIP_PKT_IGNORE))
13071 transmit_response(p, "488 Not Acceptable Here (unsupported)", req);
13072 else
13073 transmit_response_reliable(p, "488 Not Acceptable Here (unsupported)", req);
13074 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13075 sendok = FALSE;
13077 /* No bridged peer with T38 enabled*/
13080 if (sendok)
13081 transmit_response_with_sdp(p, "200 OK", req, XMIT_CRITICAL);
13084 break;
13085 default:
13086 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
13087 transmit_response(p, "100 Trying", req);
13088 break;
13090 } else {
13091 if (p && !ast_test_flag(&p->flags[0], SIP_NEEDDESTROY)) {
13092 const char *msg;
13094 if (!p->jointcapability)
13095 msg = "488 Not Acceptable Here (codec error)";
13096 else {
13097 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
13098 msg = "503 Unavailable";
13100 if (ast_test_flag(req, SIP_PKT_IGNORE))
13101 transmit_response(p, msg, req);
13102 else
13103 transmit_response_reliable(p, msg, req);
13104 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13107 return res;
13110 /*! \brief Find all call legs and bridge transferee with target
13111 * called from handle_request_refer */
13112 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
13114 struct sip_dual target; /* Chan 1: Call from tranferer to Asterisk */
13115 /* Chan 2: Call from Asterisk to target */
13116 int res = 0;
13117 struct sip_pvt *targetcall_pvt;
13118 int error = 0;
13120 /* Check if the call ID of the replaces header does exist locally */
13121 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
13122 transferer->refer->replaces_callid_fromtag))) {
13123 if (transferer->refer->localtransfer) {
13124 /* We did not find the refered call. Sorry, can't accept then */
13125 transmit_response(transferer, "202 Accepted", req);
13126 /* Let's fake a response from someone else in order
13127 to follow the standard */
13128 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
13129 append_history(transferer, "Xfer", "Refer failed");
13130 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
13131 transferer->refer->status = REFER_FAILED;
13132 return -1;
13134 /* Fall through for remote transfers that we did not find locally */
13135 if (option_debug > 2)
13136 ast_log(LOG_DEBUG, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
13137 return 0;
13140 /* Ok, we can accept this transfer */
13141 transmit_response(transferer, "202 Accepted", req);
13142 append_history(transferer, "Xfer", "Refer accepted");
13143 if (!targetcall_pvt->owner) { /* No active channel */
13144 if (option_debug > 3)
13145 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No owner of target call\n");
13146 error = 1;
13148 /* We have a channel, find the bridge */
13149 target.chan1 = targetcall_pvt->owner; /* Transferer to Asterisk */
13151 if (!error) {
13152 target.chan2 = ast_bridged_channel(targetcall_pvt->owner); /* Asterisk to target */
13154 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
13155 /* Wrong state of new channel */
13156 if (option_debug > 3) {
13157 if (target.chan2)
13158 ast_log(LOG_DEBUG, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
13159 else if (target.chan1->_state != AST_STATE_RING)
13160 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No target channel\n");
13161 else
13162 ast_log(LOG_DEBUG, "SIP attended transfer: Attempting transfer in ringing state\n");
13164 if (target.chan1->_state != AST_STATE_RING)
13165 error = 1;
13168 if (error) { /* Cancel transfer */
13169 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
13170 append_history(transferer, "Xfer", "Refer failed");
13171 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
13172 transferer->refer->status = REFER_FAILED;
13173 ast_mutex_unlock(&targetcall_pvt->lock);
13174 ast_channel_unlock(current->chan1);
13175 ast_channel_unlock(target.chan1);
13176 return -1;
13179 /* Transfer */
13180 if (option_debug > 3 && sipdebug) {
13181 if (current->chan2) /* We have two bridges */
13182 ast_log(LOG_DEBUG, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
13183 else /* One bridge, propably transfer of IVR/voicemail etc */
13184 ast_log(LOG_DEBUG, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
13187 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
13189 /* Perform the transfer */
13190 res = attempt_transfer(current, &target);
13191 ast_mutex_unlock(&targetcall_pvt->lock);
13192 if (res) {
13193 /* Failed transfer */
13194 /* Could find better message, but they will get the point */
13195 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy", TRUE);
13196 append_history(transferer, "Xfer", "Refer failed");
13197 if (targetcall_pvt->owner)
13198 ast_channel_unlock(targetcall_pvt->owner);
13199 /* Right now, we have to hangup, sorry. Bridge is destroyed */
13200 ast_hangup(transferer->owner);
13201 } else {
13202 /* Transfer succeeded! */
13204 /* Tell transferer that we're done. */
13205 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
13206 append_history(transferer, "Xfer", "Refer succeeded");
13207 transferer->refer->status = REFER_200OK;
13208 if (targetcall_pvt->owner) {
13209 ast_log(LOG_DEBUG, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
13210 ast_channel_unlock(targetcall_pvt->owner);
13213 return 1;
13217 /*! \brief Handle incoming REFER request */
13218 /*! \page SIP_REFER SIP transfer Support (REFER)
13220 REFER is used for call transfer in SIP. We get a REFER
13221 to place a new call with an INVITE somwhere and then
13222 keep the transferor up-to-date of the transfer. If the
13223 transfer fails, get back on line with the orginal call.
13225 - REFER can be sent outside or inside of a dialog.
13226 Asterisk only accepts REFER inside of a dialog.
13228 - If we get a replaces header, it is an attended transfer
13230 \par Blind transfers
13231 The transferor provides the transferee
13232 with the transfer targets contact. The signalling between
13233 transferer or transferee should not be cancelled, so the
13234 call is recoverable if the transfer target can not be reached
13235 by the transferee.
13237 In this case, Asterisk receives a TRANSFER from
13238 the transferor, thus is the transferee. We should
13239 try to set up a call to the contact provided
13240 and if that fails, re-connect the current session.
13241 If the new call is set up, we issue a hangup.
13242 In this scenario, we are following section 5.2
13243 in the SIP CC Transfer draft. (Transfer without
13244 a GRUU)
13246 \par Transfer with consultation hold
13247 In this case, the transferor
13248 talks to the transfer target before the transfer takes place.
13249 This is implemented with SIP hold and transfer.
13250 Note: The invite From: string could indicate a transfer.
13251 (Section 6. Transfer with consultation hold)
13252 The transferor places the transferee on hold, starts a call
13253 with the transfer target to alert them to the impending
13254 transfer, terminates the connection with the target, then
13255 proceeds with the transfer (as in Blind transfer above)
13257 \par Attended transfer
13258 The transferor places the transferee
13259 on hold, calls the transfer target to alert them,
13260 places the target on hold, then proceeds with the transfer
13261 using a Replaces header field in the Refer-to header. This
13262 will force the transfee to send an Invite to the target,
13263 with a replaces header that instructs the target to
13264 hangup the call between the transferor and the target.
13265 In this case, the Refer/to: uses the AOR address. (The same
13266 URI that the transferee used to establish the session with
13267 the transfer target (To: ). The Require: replaces header should
13268 be in the INVITE to avoid the wrong UA in a forked SIP proxy
13269 scenario to answer and have no call to replace with.
13271 The referred-by header is *NOT* required, but if we get it,
13272 can be copied into the INVITE to the transfer target to
13273 inform the target about the transferor
13275 "Any REFER request has to be appropriately authenticated.".
13277 We can't destroy dialogs, since we want the call to continue.
13280 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock)
13282 struct sip_dual current; /* Chan1: Call between asterisk and transferer */
13283 /* Chan2: Call between asterisk and transferee */
13285 int res = 0;
13287 if (ast_test_flag(req, SIP_PKT_DEBUG))
13288 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");
13290 if (!p->owner) {
13291 /* This is a REFER outside of an existing SIP dialog */
13292 /* We can't handle that, so decline it */
13293 if (option_debug > 2)
13294 ast_log(LOG_DEBUG, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
13295 transmit_response(p, "603 Declined (No dialog)", req);
13296 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
13297 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
13298 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
13299 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13301 return 0;
13305 /* Check if transfer is allowed from this device */
13306 if (p->allowtransfer == TRANSFER_CLOSED ) {
13307 /* Transfer not allowed, decline */
13308 transmit_response(p, "603 Declined (policy)", req);
13309 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
13310 /* Do not destroy SIP session */
13311 return 0;
13314 if(!ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
13315 /* Already have a pending REFER */
13316 transmit_response(p, "491 Request pending", req);
13317 append_history(p, "Xfer", "Refer failed. Request pending.");
13318 return 0;
13321 /* Allocate memory for call transfer data */
13322 if (!p->refer && !sip_refer_allocate(p)) {
13323 transmit_response(p, "500 Internal Server Error", req);
13324 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
13325 return -3;
13328 res = get_refer_info(p, req); /* Extract headers */
13330 p->refer->status = REFER_SENT;
13332 if (res != 0) {
13333 switch (res) {
13334 case -2: /* Syntax error */
13335 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
13336 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
13337 if (ast_test_flag(req, SIP_PKT_DEBUG))
13338 ast_log(LOG_DEBUG, "SIP transfer to black hole can't be handled (no refer-to: )\n");
13339 break;
13340 case -3:
13341 transmit_response(p, "603 Declined (Non sip: uri)", req);
13342 append_history(p, "Xfer", "Refer failed. Non SIP uri");
13343 if (ast_test_flag(req, SIP_PKT_DEBUG))
13344 ast_log(LOG_DEBUG, "SIP transfer to non-SIP uri denied\n");
13345 break;
13346 default:
13347 /* Refer-to extension not found, fake a failed transfer */
13348 transmit_response(p, "202 Accepted", req);
13349 append_history(p, "Xfer", "Refer failed. Bad extension.");
13350 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
13351 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
13352 if (ast_test_flag(req, SIP_PKT_DEBUG))
13353 ast_log(LOG_DEBUG, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
13354 break;
13356 return 0;
13358 if (ast_strlen_zero(p->context))
13359 ast_string_field_set(p, context, default_context);
13361 /* If we do not support SIP domains, all transfers are local */
13362 if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
13363 p->refer->localtransfer = 1;
13364 if (sipdebug && option_debug > 2)
13365 ast_log(LOG_DEBUG, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
13366 } else if (AST_LIST_EMPTY(&domain_list)) {
13367 /* This PBX don't bother with SIP domains, so all transfers are local */
13368 p->refer->localtransfer = 1;
13369 } else
13370 if (sipdebug && option_debug > 2)
13371 ast_log(LOG_DEBUG, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
13373 /* Is this a repeat of a current request? Ignore it */
13374 /* Don't know what else to do right now. */
13375 if (ignore)
13376 return res;
13378 /* If this is a blind transfer, we have the following
13379 channels to work with:
13380 - chan1, chan2: The current call between transferer and transferee (2 channels)
13381 - target_channel: A new call from the transferee to the target (1 channel)
13382 We need to stay tuned to what happens in order to be able
13383 to bring back the call to the transferer */
13385 /* If this is a attended transfer, we should have all call legs within reach:
13386 - chan1, chan2: The call between the transferer and transferee (2 channels)
13387 - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
13388 We want to bridge chan2 with targetcall_pvt!
13390 The replaces call id in the refer message points
13391 to the call leg between Asterisk and the transferer.
13392 So we need to connect the target and the transferee channel
13393 and hangup the two other channels silently
13395 If the target is non-local, the call ID could be on a remote
13396 machine and we need to send an INVITE with replaces to the
13397 target. We basically handle this as a blind transfer
13398 and let the sip_call function catch that we need replaces
13399 header in the INVITE.
13403 /* Get the transferer's channel */
13404 current.chan1 = p->owner;
13406 /* Find the other part of the bridge (2) - transferee */
13407 current.chan2 = ast_bridged_channel(current.chan1);
13409 if (sipdebug && option_debug > 2)
13410 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>");
13412 if (!current.chan2 && !p->refer->attendedtransfer) {
13413 /* No bridged channel, propably IVR or echo or similar... */
13414 /* Guess we should masquerade or something here */
13415 /* Until we figure it out, refuse transfer of such calls */
13416 if (sipdebug && option_debug > 2)
13417 ast_log(LOG_DEBUG,"Refused SIP transfer on non-bridged channel.\n");
13418 p->refer->status = REFER_FAILED;
13419 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
13420 transmit_response(p, "603 Declined", req);
13421 return -1;
13424 if (current.chan2) {
13425 if (sipdebug && option_debug > 3)
13426 ast_log(LOG_DEBUG, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
13428 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
13431 ast_set_flag(&p->flags[0], SIP_GOTREFER);
13433 /* Attended transfer: Find all call legs and bridge transferee with target*/
13434 if (p->refer->attendedtransfer) {
13435 if ((res = local_attended_transfer(p, &current, req, seqno)))
13436 return res; /* We're done with the transfer */
13437 /* Fall through for remote transfers that we did not find locally */
13438 if (sipdebug && option_debug > 3)
13439 ast_log(LOG_DEBUG, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
13440 /* Fallthrough if we can't find the call leg internally */
13444 /* Parking a call */
13445 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
13446 /* Must release c's lock now, because it will not longer be accessible after the transfer! */
13447 *nounlock = 1;
13448 ast_channel_unlock(current.chan1);
13449 copy_request(&current.req, req);
13450 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
13451 p->refer->status = REFER_200OK;
13452 append_history(p, "Xfer", "REFER to call parking.");
13453 if (sipdebug && option_debug > 3)
13454 ast_log(LOG_DEBUG, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
13455 sip_park(current.chan2, current.chan1, req, seqno);
13456 return res;
13459 /* Blind transfers and remote attended xfers */
13460 transmit_response(p, "202 Accepted", req);
13462 if (current.chan1 && current.chan2) {
13463 if (option_debug > 2)
13464 ast_log(LOG_DEBUG, "chan1->name: %s\n", current.chan1->name);
13465 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
13467 if (current.chan2) {
13468 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
13469 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
13470 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
13471 /* One for the new channel */
13472 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
13473 if (p->refer->referred_by)
13474 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
13475 if (p->refer->referred_by)
13476 /* Attended transfer to remote host, prepare headers for the INVITE */
13477 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
13479 /* Generate an URI-encoded string */
13480 if (p->refer->replaces_callid && !ast_strlen_zero(p->refer->replaces_callid)) {
13481 char tempheader[BUFSIZ];
13482 char tempheader2[BUFSIZ];
13483 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
13484 p->refer->replaces_callid_totag ? ";to-tag=" : "",
13485 p->refer->replaces_callid_totag,
13486 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
13487 p->refer->replaces_callid_fromtag);
13489 /* Convert it to URL encoding, also convert reserved strings */
13490 ast_uri_encode(tempheader, tempheader2, sizeof(tempheader2), 1);
13492 if (current.chan2)
13493 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader2);
13495 /* Must release lock now, because it will not longer
13496 be accessible after the transfer! */
13497 *nounlock = 1;
13498 ast_channel_unlock(current.chan1);
13499 ast_channel_unlock(current.chan2);
13501 /* Connect the call */
13503 /* FAKE ringing if not attended transfer */
13504 if (!p->refer->attendedtransfer)
13505 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
13507 /* For blind transfer, this will lead to a new call */
13508 /* For attended transfer to remote host, this will lead to
13509 a new SIP call with a replaces header, if the dial plan allows it
13511 if (!current.chan2) {
13512 /* We have no bridge, so we're talking with Asterisk somehow */
13513 /* We need to masquerade this call */
13514 /* What to do to fix this situation:
13515 * Set up the new call in a new channel
13516 * Let the new channel masq into this channel
13517 Please add that code here :-)
13519 transmit_response(p, "202 Accepted", req);
13520 p->refer->status = REFER_FAILED;
13521 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
13522 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
13523 append_history(p, "Xfer", "Refer failed (only bridged calls).");
13524 return -1;
13526 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
13528 /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
13529 servers - generate an INVITE with Replaces. Either way, let the dial plan decided */
13530 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
13532 if (!res) {
13533 /* Success - we have a new channel */
13534 if (option_debug > 2)
13535 ast_log(LOG_DEBUG, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
13536 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
13537 if (p->refer->localtransfer)
13538 p->refer->status = REFER_200OK;
13539 if (p->owner)
13540 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
13541 append_history(p, "Xfer", "Refer succeeded.");
13542 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
13543 /* Do not hangup call, the other side do that when we say 200 OK */
13544 /* We could possibly implement a timer here, auto congestion */
13545 res = 0;
13546 } else {
13547 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
13548 if (option_debug > 2)
13549 ast_log(LOG_DEBUG, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
13550 append_history(p, "Xfer", "Refer failed.");
13551 /* Failure of some kind */
13552 p->refer->status = REFER_FAILED;
13553 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
13554 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
13555 res = -1;
13557 return res;
13560 /*! \brief Handle incoming CANCEL request */
13561 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
13564 check_via(p, req);
13565 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
13567 if (p->owner && p->owner->_state == AST_STATE_UP) {
13568 /* This call is up, cancel is ignored, we need a bye */
13569 transmit_response(p, "200 OK", req);
13570 if (option_debug)
13571 ast_log(LOG_DEBUG, "Got CANCEL on an answered call. Ignoring... \n");
13572 return 0;
13574 if (p->rtp) {
13575 /* Immediately stop RTP */
13576 ast_rtp_stop(p->rtp);
13578 if (p->vrtp) {
13579 /* Immediately stop VRTP */
13580 ast_rtp_stop(p->vrtp);
13582 if (p->udptl) {
13583 /* Immediately stop UDPTL */
13584 ast_udptl_stop(p->udptl);
13586 if (p->owner)
13587 ast_queue_hangup(p->owner);
13588 else
13589 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13590 if (p->initreq.len > 0) {
13591 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
13592 transmit_response(p, "200 OK", req);
13593 return 1;
13594 } else {
13595 transmit_response(p, "481 Call Leg Does Not Exist", req);
13596 return 0;
13600 /*! \brief Handle incoming BYE request */
13601 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
13603 struct ast_channel *c=NULL;
13604 int res;
13605 struct ast_channel *bridged_to;
13606 char *audioqos = NULL, *videoqos = NULL;
13608 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_test_flag(req, SIP_PKT_IGNORE))
13609 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
13611 copy_request(&p->initreq, req);
13612 check_via(p, req);
13613 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
13615 if (p->rtp)
13616 audioqos = ast_rtp_get_quality(p->rtp);
13617 if (p->vrtp)
13618 videoqos = ast_rtp_get_quality(p->vrtp);
13620 /* Get RTCP quality before end of call */
13621 if (recordhistory) {
13622 if (p->rtp)
13623 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
13624 if (p->vrtp)
13625 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
13628 if (p->rtp) {
13629 if (p->owner)
13630 pbx_builtin_setvar_helper(p->owner, "RTPAUDIOQOS", audioqos);
13631 /* Immediately stop RTP */
13632 ast_rtp_stop(p->rtp);
13634 if (p->vrtp) {
13635 if (p->owner)
13636 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
13637 /* Immediately stop VRTP */
13638 ast_rtp_stop(p->vrtp);
13640 if (p->udptl) {
13641 /* Immediately stop UDPTL */
13642 ast_udptl_stop(p->udptl);
13644 if (!ast_strlen_zero(get_header(req, "Also"))) {
13645 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
13646 ast_inet_ntoa(p->recv.sin_addr));
13647 if (ast_strlen_zero(p->context))
13648 ast_string_field_set(p, context, default_context);
13649 res = get_also_info(p, req);
13650 if (!res) {
13651 c = p->owner;
13652 if (c) {
13653 bridged_to = ast_bridged_channel(c);
13654 if (bridged_to) {
13655 /* Don't actually hangup here... */
13656 ast_queue_control(c, AST_CONTROL_UNHOLD);
13657 ast_async_goto(bridged_to, p->context, p->refer->refer_to,1);
13658 } else
13659 ast_queue_hangup(p->owner);
13661 } else {
13662 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
13663 if (p->owner)
13664 ast_queue_hangup(p->owner);
13666 } else if (p->owner) {
13667 ast_queue_hangup(p->owner);
13668 if (option_debug > 2)
13669 ast_log(LOG_DEBUG, "Received bye, issuing owner hangup\n.");
13670 } else {
13671 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13672 if (option_debug > 2)
13673 ast_log(LOG_DEBUG, "Received bye, no owner, selfdestruct soon.\n.");
13675 transmit_response(p, "200 OK", req);
13677 return 1;
13680 /*! \brief Handle incoming MESSAGE request */
13681 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
13683 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
13684 if (ast_test_flag(req, SIP_PKT_DEBUG))
13685 ast_verbose("Receiving message!\n");
13686 receive_message(p, req);
13688 transmit_response(p, "202 Accepted", req);
13689 return 1;
13692 /*! \brief Handle incoming SUBSCRIBE request */
13693 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
13695 int gotdest;
13696 int res = 0;
13697 int firststate = AST_EXTENSION_REMOVED;
13698 struct sip_peer *authpeer = NULL;
13699 const char *event = get_header(req, "Event"); /* Get Event package name */
13700 const char *accept = get_header(req, "Accept");
13701 int resubscribe = (p->subscribed != NONE);
13703 if (p->initreq.headers) {
13704 /* We already have a dialog */
13705 if (p->initreq.method != SIP_SUBSCRIBE) {
13706 /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
13707 /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
13708 transmit_response(p, "403 Forbidden (within dialog)", req);
13709 /* Do not destroy session, since we will break the call if we do */
13710 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);
13711 return 0;
13712 } else if (ast_test_flag(req, SIP_PKT_DEBUG)) {
13713 if (resubscribe)
13714 ast_log(LOG_DEBUG, "Got a re-subscribe on existing subscription %s\n", p->callid);
13715 else
13716 ast_log(LOG_DEBUG, "Got a new subscription %s (possibly with auth)\n", p->callid);
13720 /* Check if we have a global disallow setting on subscriptions.
13721 if so, we don't have to check peer/user settings after auth, which saves a lot of processing
13723 if (!global_allowsubscribe) {
13724 transmit_response(p, "403 Forbidden (policy)", req);
13725 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13726 return 0;
13729 if (!ast_test_flag(req, SIP_PKT_IGNORE) && !p->initreq.headers) { /* Set up dialog, new subscription */
13730 /* Use this as the basis */
13731 if (ast_test_flag(req, SIP_PKT_DEBUG))
13732 ast_verbose("Creating new subscription\n");
13734 /* This call is no longer outgoing if it ever was */
13735 ast_clear_flag(&p->flags[0], SIP_OUTGOING);
13736 copy_request(&p->initreq, req);
13737 check_via(p, req);
13738 } else if (ast_test_flag(req, SIP_PKT_DEBUG) && ast_test_flag(req, SIP_PKT_IGNORE))
13739 ast_verbose("Ignoring this SUBSCRIBE request\n");
13741 /* Find parameters to Event: header value and remove them for now */
13742 event = strsep((char **)&event, ";"); /* XXX bug here, overwrite string */
13744 /* Handle authentication if this is our first subscribe */
13745 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
13746 /* if an authentication response was sent, we are done here */
13747 if (res == AUTH_CHALLENGE_SENT)
13748 return 0;
13749 if (res < 0) {
13750 if (res == AUTH_FAKE_AUTH) {
13751 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
13752 transmit_fake_auth_response(p, req, 1);
13753 } else {
13754 ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
13755 transmit_response_reliable(p, "403 Forbidden", req);
13757 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13758 return 0;
13761 /* Check if this user/peer is allowed to subscribe at all */
13762 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
13763 transmit_response(p, "403 Forbidden (policy)", req);
13764 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13765 return 0;
13768 /* Get destination right away */
13769 gotdest = get_destination(p, NULL);
13771 /* Initialize the context if it hasn't been already;
13772 note this is done _after_ handling any domain lookups,
13773 because the context specified there is for calls, not
13774 subscriptions
13776 if (!ast_strlen_zero(p->subscribecontext))
13777 ast_string_field_set(p, context, p->subscribecontext);
13778 else if (ast_strlen_zero(p->context))
13779 ast_string_field_set(p, context, default_context);
13781 build_contact(p);
13782 if (gotdest) {
13783 transmit_response(p, "404 Not Found", req);
13784 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13785 return 0;
13786 } else {
13787 /* XXX reduce nesting here */
13789 /* Initialize tag for new subscriptions */
13790 if (ast_strlen_zero(p->tag))
13791 make_our_tag(p->tag, sizeof(p->tag));
13793 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
13795 /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
13796 if (strstr(accept, "application/pidf+xml")) {
13797 p->subscribed = PIDF_XML; /* RFC 3863 format */
13798 } else if (strstr(accept, "application/dialog-info+xml")) {
13799 p->subscribed = DIALOG_INFO_XML;
13800 /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
13801 } else if (strstr(accept, "application/cpim-pidf+xml")) {
13802 p->subscribed = CPIM_PIDF_XML; /* RFC 3863 format */
13803 } else if (strstr(accept, "application/xpidf+xml")) {
13804 p->subscribed = XPIDF_XML; /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
13805 } else if (strstr(p->useragent, "Polycom")) {
13806 p->subscribed = XPIDF_XML; /* Polycoms subscribe for "event: dialog" but don't include an "accept:" header */
13807 } else {
13808 /* Can't find a format for events that we know about */
13809 transmit_response(p, "489 Bad Event", req);
13810 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13811 return 0;
13813 } else if (!strcmp(event, "message-summary")) {
13814 if (!ast_strlen_zero(accept) && strcmp(accept, "application/simple-message-summary")) {
13815 /* Format requested that we do not support */
13816 transmit_response(p, "406 Not Acceptable", req);
13817 if (option_debug > 1)
13818 ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", accept);
13819 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13820 return 0;
13822 /* Looks like they actually want a mailbox status
13823 This version of Asterisk supports mailbox subscriptions
13824 The subscribed URI needs to exist in the dial plan
13825 In most devices, this is configurable to the voicemailmain extension you use
13827 if (!authpeer || ast_strlen_zero(authpeer->mailbox)) {
13828 transmit_response(p, "404 Not found (no mailbox)", req);
13829 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13830 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
13831 return 0;
13834 p->subscribed = MWI_NOTIFICATION;
13835 if (authpeer->mwipvt && authpeer->mwipvt != p) /* Destroy old PVT if this is a new one */
13836 /* We only allow one subscription per peer */
13837 sip_destroy(authpeer->mwipvt);
13838 authpeer->mwipvt = p; /* Link from peer to pvt */
13839 p->relatedpeer = authpeer; /* Link from pvt to peer */
13840 } else { /* At this point, Asterisk does not understand the specified event */
13841 transmit_response(p, "489 Bad Event", req);
13842 if (option_debug > 1)
13843 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: %s\n", event);
13844 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13845 return 0;
13847 if (p->subscribed != MWI_NOTIFICATION && !resubscribe)
13848 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, p);
13851 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
13852 p->lastinvite = seqno;
13853 if (p && !ast_test_flag(&p->flags[0], SIP_NEEDDESTROY)) {
13854 p->expiry = atoi(get_header(req, "Expires"));
13856 /* check if the requested expiry-time is within the approved limits from sip.conf */
13857 if (p->expiry > max_expiry)
13858 p->expiry = max_expiry;
13859 if (p->expiry < min_expiry && p->expiry > 0)
13860 p->expiry = min_expiry;
13862 if (sipdebug || option_debug > 1) {
13863 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
13864 ast_log(LOG_DEBUG, "Adding subscription for mailbox notification - peer %s Mailbox %s\n", p->relatedpeer->name, p->relatedpeer->mailbox);
13865 else
13866 ast_log(LOG_DEBUG, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
13868 if (p->autokillid > -1)
13869 sip_cancel_destroy(p); /* Remove subscription expiry for renewals */
13870 if (p->expiry > 0)
13871 sip_scheddestroy(p, (p->expiry + 10) * 1000); /* Set timer for destruction of call at expiration */
13873 if (p->subscribed == MWI_NOTIFICATION) {
13874 transmit_response(p, "200 OK", req);
13875 if (p->relatedpeer) { /* Send first notification */
13876 ASTOBJ_WRLOCK(p->relatedpeer);
13877 sip_send_mwi_to_peer(p->relatedpeer);
13878 ASTOBJ_UNLOCK(p->relatedpeer);
13880 } else {
13881 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
13883 ast_log(LOG_ERROR, "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));
13884 transmit_response(p, "404 Not found", req);
13885 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13886 return 0;
13887 } else {
13888 /* XXX reduce nesting here */
13889 struct sip_pvt *p_old;
13891 transmit_response(p, "200 OK", req);
13892 transmit_state_notify(p, firststate, 1); /* Send first notification */
13893 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
13894 /* hide the 'complete' exten/context in the refer_to field for later display */
13895 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
13897 /* remove any old subscription from this peer for the same exten/context,
13898 as the peer has obviously forgotten about it and it's wasteful to wait
13899 for it to expire and send NOTIFY messages to the peer only to have them
13900 ignored (or generate errors)
13902 ast_mutex_lock(&iflock);
13903 for (p_old = iflist; p_old; p_old = p_old->next) {
13904 if (p_old == p)
13905 continue;
13906 if (p_old->initreq.method != SIP_SUBSCRIBE)
13907 continue;
13908 if (p_old->subscribed == NONE)
13909 continue;
13910 ast_mutex_lock(&p_old->lock);
13911 if (!strcmp(p_old->username, p->username)) {
13912 if (!strcmp(p_old->exten, p->exten) &&
13913 !strcmp(p_old->context, p->context)) {
13914 ast_set_flag(&p_old->flags[0], SIP_NEEDDESTROY);
13915 ast_mutex_unlock(&p_old->lock);
13916 break;
13919 ast_mutex_unlock(&p_old->lock);
13921 ast_mutex_unlock(&iflock);
13924 if (!p->expiry)
13925 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13927 if (authpeer)
13928 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
13929 return 1;
13932 /*! \brief Handle incoming REGISTER request */
13933 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
13935 enum check_auth_result res;
13937 /* Use this as the basis */
13938 if (ast_test_flag(req, SIP_PKT_DEBUG))
13939 ast_verbose("Using latest REGISTER request as basis request\n");
13940 copy_request(&p->initreq, req);
13941 check_via(p, req);
13942 if ((res = register_verify(p, sin, req, e)) < 0) {
13943 const char *reason = "";
13945 switch (res) {
13946 case AUTH_SECRET_FAILED:
13947 reason = "Wrong password";
13948 break;
13949 case AUTH_USERNAME_MISMATCH:
13950 reason = "Username/auth name mismatch";
13951 break;
13952 case AUTH_NOT_FOUND:
13953 reason = "No matching peer found";
13954 break;
13955 case AUTH_UNKNOWN_DOMAIN:
13956 reason = "Not a local domain";
13957 break;
13958 default:
13959 break;
13961 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
13962 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
13963 reason);
13965 if (res < 1) {
13966 /* Destroy the session, but keep us around for just a bit in case they don't
13967 get our 200 OK */
13968 sip_scheddestroy(p, 15000);
13970 append_history(p, "RegRequest", "%s : Account %s", res ? "Failed": "Succeeded", get_header(req, "To"));
13971 return res;
13974 /*! \brief Handle incoming SIP requests (methods)
13975 \note This is where all incoming requests go first */
13976 /* called with p and p->owner locked */
13977 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
13979 /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
13980 relatively static */
13981 struct sip_request resp;
13982 const char *cmd;
13983 const char *cseq;
13984 const char *useragent;
13985 int seqno;
13986 int len;
13987 int ignore = FALSE;
13988 int respid;
13989 int res = 0;
13990 int debug = sip_debug_test_pvt(p);
13991 char *e;
13992 int error = 0;
13994 /* Clear out potential response */
13995 memset(&resp, 0, sizeof(resp));
13997 /* Get Method and Cseq */
13998 cseq = get_header(req, "Cseq");
13999 cmd = req->header[0];
14001 /* Must have Cseq */
14002 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
14003 ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
14004 error = 1;
14006 if (!error && sscanf(cseq, "%d%n", &seqno, &len) != 1) {
14007 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
14008 error = 1;
14010 if (error) {
14011 if (!p->initreq.header) /* New call */
14012 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); /* Make sure we destroy this dialog */
14013 return -1;
14015 /* Get the command XXX */
14017 cmd = req->rlPart1;
14018 e = req->rlPart2;
14020 /* Save useragent of the client */
14021 useragent = get_header(req, "User-Agent");
14022 if (!ast_strlen_zero(useragent))
14023 ast_string_field_set(p, useragent, useragent);
14025 /* Find out SIP method for incoming request */
14026 if (req->method == SIP_RESPONSE) { /* Response to our request */
14027 /* Response to our request -- Do some sanity checks */
14028 if (!p->initreq.headers) {
14029 if (option_debug)
14030 ast_log(LOG_DEBUG, "That's odd... Got a response on a call we dont know about. Cseq %d Cmd %s\n", seqno, cmd);
14031 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14032 return 0;
14033 } else if (p->ocseq && (p->ocseq < seqno)) {
14034 if (option_debug)
14035 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
14036 return -1;
14037 } else if (p->ocseq && (p->ocseq != seqno)) {
14038 /* ignore means "don't do anything with it" but still have to
14039 respond appropriately */
14040 ignore = TRUE;
14041 ast_set_flag(req, SIP_PKT_IGNORE);
14042 ast_set_flag(req, SIP_PKT_IGNORE_RESP);
14043 append_history(p, "Ignore", "Ignoring this retransmit\n");
14046 e = ast_skip_blanks(e);
14047 if (sscanf(e, "%d %n", &respid, &len) != 1) {
14048 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
14049 } else {
14050 /* More SIP ridiculousness, we have to ignore bogus contacts in 100 etc responses */
14051 if ((respid == 200) || ((respid >= 300) && (respid <= 399)))
14052 extract_uri(p, req);
14053 handle_response(p, respid, e + len, req, ignore, seqno);
14055 return 0;
14058 /* New SIP request coming in
14059 (could be new request in existing SIP dialog as well...)
14062 p->method = req->method; /* Find out which SIP method they are using */
14063 if (option_debug > 3)
14064 ast_log(LOG_DEBUG, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
14066 if (p->icseq && (p->icseq > seqno)) {
14067 if (option_debug)
14068 ast_log(LOG_DEBUG, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
14069 if (req->method != SIP_ACK)
14070 transmit_response(p, "503 Server error", req); /* We must respond according to RFC 3261 sec 12.2 */
14071 return -1;
14072 } else if (p->icseq &&
14073 p->icseq == seqno &&
14074 req->method != SIP_ACK &&
14075 (p->method != SIP_CANCEL || ast_test_flag(&p->flags[0], SIP_ALREADYGONE))) {
14076 /* ignore means "don't do anything with it" but still have to
14077 respond appropriately. We do this if we receive a repeat of
14078 the last sequence number */
14079 ignore = 2;
14080 ast_set_flag(req, SIP_PKT_IGNORE);
14081 ast_set_flag(req, SIP_PKT_IGNORE_REQ);
14082 if (option_debug > 2)
14083 ast_log(LOG_DEBUG, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
14086 if (seqno >= p->icseq)
14087 /* Next should follow monotonically (but not necessarily
14088 incrementally -- thanks again to the genius authors of SIP --
14089 increasing */
14090 p->icseq = seqno;
14092 /* Find their tag if we haven't got it */
14093 if (ast_strlen_zero(p->theirtag)) {
14094 char tag[128];
14096 gettag(req, "From", tag, sizeof(tag));
14097 ast_string_field_set(p, theirtag, tag);
14099 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
14101 if (pedanticsipchecking) {
14102 /* If this is a request packet without a from tag, it's not
14103 correct according to RFC 3261 */
14104 /* Check if this a new request in a new dialog with a totag already attached to it,
14105 RFC 3261 - section 12.2 - and we don't want to mess with recovery */
14106 if (!p->initreq.headers && ast_test_flag(req, SIP_PKT_WITH_TOTAG)) {
14107 /* If this is a first request and it got a to-tag, it is not for us */
14108 if (!ast_test_flag(req, SIP_PKT_IGNORE) && req->method == SIP_INVITE) {
14109 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
14110 /* Will cease to exist after ACK */
14111 } else if (req->method != SIP_ACK) {
14112 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
14113 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14115 return res;
14119 /* Handle various incoming SIP methods in requests */
14120 switch (p->method) {
14121 case SIP_OPTIONS:
14122 res = handle_request_options(p, req);
14123 break;
14124 case SIP_INVITE:
14125 res = handle_request_invite(p, req, debug, seqno, sin, recount, e);
14126 break;
14127 case SIP_REFER:
14128 res = handle_request_refer(p, req, debug, ignore, seqno, nounlock);
14129 break;
14130 case SIP_CANCEL:
14131 res = handle_request_cancel(p, req);
14132 break;
14133 case SIP_BYE:
14134 res = handle_request_bye(p, req);
14135 break;
14136 case SIP_MESSAGE:
14137 res = handle_request_message(p, req);
14138 break;
14139 case SIP_SUBSCRIBE:
14140 res = handle_request_subscribe(p, req, sin, seqno, e);
14141 break;
14142 case SIP_REGISTER:
14143 res = handle_request_register(p, req, sin, e);
14144 break;
14145 case SIP_INFO:
14146 if (ast_test_flag(req, SIP_PKT_DEBUG))
14147 ast_verbose("Receiving INFO!\n");
14148 if (!ignore)
14149 handle_request_info(p, req);
14150 else /* if ignoring, transmit response */
14151 transmit_response(p, "200 OK", req);
14152 break;
14153 case SIP_NOTIFY:
14154 res = handle_request_notify(p, req, sin, seqno, e);
14155 break;
14156 case SIP_ACK:
14157 /* Make sure we don't ignore this */
14158 if (seqno == p->pendinginvite) {
14159 p->pendinginvite = 0;
14160 __sip_ack(p, seqno, FLAG_RESPONSE, 0, FALSE);
14161 if (find_sdp(req)) {
14162 if (process_sdp(p, req))
14163 return -1;
14165 check_pendings(p);
14167 if (!p->lastinvite && ast_strlen_zero(p->randdata))
14168 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14169 break;
14170 default:
14171 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
14172 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
14173 cmd, ast_inet_ntoa(p->sa.sin_addr));
14174 /* If this is some new method, and we don't have a call, destroy it now */
14175 if (!p->initreq.headers)
14176 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14177 break;
14179 return res;
14182 /*! \brief Read data from SIP socket
14183 \note sipsock_read locks the owner channel while we are processing the SIP message
14184 \return 1 on error, 0 on success
14185 \note Successful messages is connected to SIP call and forwarded to handle_request()
14187 static int sipsock_read(int *id, int fd, short events, void *ignore)
14189 struct sip_request req;
14190 struct sockaddr_in sin = { 0, };
14191 struct sip_pvt *p;
14192 int res;
14193 socklen_t len;
14194 int nounlock;
14195 int recount = 0;
14196 unsigned int lockretry = 100;
14198 len = sizeof(sin);
14199 memset(&req, 0, sizeof(req));
14200 res = recvfrom(sipsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
14201 if (res < 0) {
14202 #if !defined(__FreeBSD__)
14203 if (errno == EAGAIN)
14204 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
14205 else
14206 #endif
14207 if (errno != ECONNREFUSED)
14208 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
14209 return 1;
14211 if (option_debug && res == sizeof(req.data)) {
14212 ast_log(LOG_DEBUG, "Received packet exceeds buffer. Data is possibly lost\n");
14213 req.data[sizeof(req.data) - 1] = '\0';
14214 } else
14215 req.data[res] = '\0';
14216 req.len = res;
14217 if(sip_debug_test_addr(&sin)) /* Set the debug flag early on packet level */
14218 ast_set_flag(&req, SIP_PKT_DEBUG);
14219 if (pedanticsipchecking)
14220 req.len = lws2sws(req.data, req.len); /* Fix multiline headers */
14221 if (ast_test_flag(&req, SIP_PKT_DEBUG))
14222 ast_verbose("\n<-- SIP read from %s:%d: \n%s\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), req.data);
14224 parse_request(&req);
14225 req.method = find_sip_method(req.rlPart1);
14226 if (ast_test_flag(&req, SIP_PKT_DEBUG)) {
14227 ast_verbose("--- (%d headers %d lines)", req.headers, req.lines);
14228 if (req.headers + req.lines == 0)
14229 ast_verbose(" Nat keepalive ");
14230 ast_verbose("---\n");
14233 if (req.headers < 2) {
14234 /* Must have at least two headers */
14235 return 1;
14239 /* Process request, with netlock held */
14240 retrylock:
14241 ast_mutex_lock(&netlock);
14243 /* Find the active SIP dialog or create a new one */
14244 p = find_call(&req, &sin, req.method); /* returns p locked */
14245 if (p) {
14246 /* Go ahead and lock the owner if it has one -- we may need it */
14247 /* becaues this is deadlock-prone, we need to try and unlock if failed */
14248 if (p->owner && ast_channel_trylock(p->owner)) {
14249 if (option_debug)
14250 ast_log(LOG_DEBUG, "Failed to grab owner channel lock, trying again. (SIP call %s)\n", p->callid);
14251 ast_mutex_unlock(&p->lock);
14252 ast_mutex_unlock(&netlock);
14253 /* Sleep for a very short amount of time */
14254 usleep(1);
14255 if (--lockretry)
14256 goto retrylock;
14258 p->recv = sin;
14260 if (recordhistory) /* This is a request or response, note what it was for */
14261 append_history(p, "Rx", "%s / %s / %s", req.data, get_header(&req, "CSeq"), req.rlPart2);
14263 if (!lockretry) {
14264 ast_log(LOG_ERROR, "We could NOT get the channel lock for %s! \n", p->owner->name ? p->owner->name : "- no channel name ??? - ");
14265 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
14266 transmit_response(p, "503 Server error", &req); /* We must respond according to RFC 3261 sec 12.2 */
14267 /* XXX We could add retry-after to make sure they come back */
14268 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
14269 return 1;
14271 nounlock = 0;
14272 if (handle_request(p, &req, &sin, &recount, &nounlock) == -1) {
14273 /* Request failed */
14274 if (option_debug)
14275 ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
14278 if (p->owner && !nounlock)
14279 ast_channel_unlock(p->owner);
14280 ast_mutex_unlock(&p->lock);
14281 } else {
14282 if (option_debug)
14283 ast_log(LOG_DEBUG, "Invalid SIP message - rejected , bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
14285 ast_mutex_unlock(&netlock);
14286 if (recount)
14287 ast_update_use_count();
14289 return 1;
14292 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
14293 static int sip_send_mwi_to_peer(struct sip_peer *peer)
14295 /* Called with peerl lock, but releases it */
14296 struct sip_pvt *p;
14297 int newmsgs, oldmsgs;
14299 /* Check for messages */
14300 ast_app_inboxcount(peer->mailbox, &newmsgs, &oldmsgs);
14302 peer->lastmsgcheck = time(NULL);
14304 /* Return now if it's the same thing we told them last time */
14305 if (((newmsgs << 8) | (oldmsgs)) == peer->lastmsgssent) {
14306 return 0;
14310 peer->lastmsgssent = ((newmsgs << 8) | (oldmsgs));
14312 if (peer->mwipvt) {
14313 /* Base message on subscription */
14314 p = peer->mwipvt;
14315 } else {
14316 /* Build temporary dialog for this message */
14317 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY)))
14318 return -1;
14319 if (create_addr_from_peer(p, peer)) {
14320 /* Maybe they're not registered, etc. */
14321 sip_destroy(p);
14322 return 0;
14324 /* Recalculate our side, and recalculate Call ID */
14325 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
14326 p->ourip = __ourip;
14327 build_via(p);
14328 build_callid_pvt(p);
14329 /* Destroy this session after 32 secs */
14330 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
14332 /* Send MWI */
14333 ast_set_flag(&p->flags[0], SIP_OUTGOING);
14334 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
14335 return 0;
14338 /*! \brief Check whether peer needs a new MWI notification check */
14339 static int does_peer_need_mwi(struct sip_peer *peer)
14341 time_t t = time(NULL);
14343 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
14344 !peer->mwipvt) { /* We don't have a subscription */
14345 peer->lastmsgcheck = t; /* Reset timer */
14346 return FALSE;
14349 if (!ast_strlen_zero(peer->mailbox) && (t - peer->lastmsgcheck) > global_mwitime)
14350 return TRUE;
14352 return FALSE;
14356 /*! \brief The SIP monitoring thread
14357 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
14358 (and thus do not have a separate thread) indefinitely
14360 static void *do_monitor(void *data)
14362 int res;
14363 struct sip_pvt *sip;
14364 struct sip_peer *peer = NULL;
14365 time_t t;
14366 int fastrestart = FALSE;
14367 int lastpeernum = -1;
14368 int curpeernum;
14369 int reloading;
14371 /* Add an I/O event to our SIP UDP socket */
14372 if (sipsock > -1)
14373 ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
14375 /* From here on out, we die whenever asked */
14376 for(;;) {
14377 /* Check for a reload request */
14378 ast_mutex_lock(&sip_reload_lock);
14379 reloading = sip_reloading;
14380 sip_reloading = FALSE;
14381 ast_mutex_unlock(&sip_reload_lock);
14382 if (reloading) {
14383 if (option_verbose > 0)
14384 ast_verbose(VERBOSE_PREFIX_1 "Reloading SIP\n");
14385 sip_do_reload(sip_reloadreason);
14387 /* Check for interfaces needing to be killed */
14388 ast_mutex_lock(&iflock);
14389 restartsearch:
14390 t = time(NULL);
14391 /* don't scan the interface list if it hasn't been a reasonable period
14392 of time since the last time we did it (when MWI is being sent, we can
14393 get back to this point every millisecond or less)
14395 for (sip = iflist; !fastrestart && sip; sip = sip->next) {
14396 ast_mutex_lock(&sip->lock);
14397 /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
14398 if (sip->rtp && sip->owner &&
14399 (sip->owner->_state == AST_STATE_UP) &&
14400 !sip->redirip.sin_addr.s_addr) {
14401 if (sip->lastrtptx &&
14402 sip->rtpkeepalive &&
14403 (t > sip->lastrtptx + sip->rtpkeepalive)) {
14404 /* Need to send an empty RTP packet */
14405 sip->lastrtptx = time(NULL);
14406 ast_rtp_sendcng(sip->rtp, 0);
14408 if (sip->lastrtprx &&
14409 (sip->rtptimeout || sip->rtpholdtimeout) &&
14410 (t > sip->lastrtprx + sip->rtptimeout)) {
14411 /* Might be a timeout now -- see if we're on hold */
14412 struct sockaddr_in sin;
14413 ast_rtp_get_peer(sip->rtp, &sin);
14414 if (sin.sin_addr.s_addr ||
14415 (sip->rtpholdtimeout &&
14416 (t > sip->lastrtprx + sip->rtpholdtimeout))) {
14417 /* Needs a hangup */
14418 if (sip->rtptimeout) {
14419 while (sip->owner && ast_channel_trylock(sip->owner)) {
14420 ast_mutex_unlock(&sip->lock);
14421 usleep(1);
14422 ast_mutex_lock(&sip->lock);
14424 if (sip->owner) {
14425 if (!(ast_rtp_get_bridged(sip->rtp))) {
14426 ast_log(LOG_NOTICE,
14427 "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
14428 sip->owner->name,
14429 (long) (t - sip->lastrtprx));
14430 /* Issue a softhangup */
14431 ast_softhangup_nolock(sip->owner, AST_SOFTHANGUP_DEV);
14432 } else
14433 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));
14434 ast_channel_unlock(sip->owner);
14435 /* forget the timeouts for this call, since a hangup
14436 has already been requested and we don't want to
14437 repeatedly request hangups
14439 sip->rtptimeout = 0;
14440 sip->rtpholdtimeout = 0;
14446 /* If we have sessions that needs to be destroyed, do it now */
14447 if (ast_test_flag(&sip->flags[0], SIP_NEEDDESTROY) && !sip->packets &&
14448 !sip->owner) {
14449 ast_mutex_unlock(&sip->lock);
14450 __sip_destroy(sip, 1);
14451 goto restartsearch;
14453 ast_mutex_unlock(&sip->lock);
14455 ast_mutex_unlock(&iflock);
14457 pthread_testcancel();
14458 /* Wait for sched or io */
14459 res = ast_sched_wait(sched);
14460 if ((res < 0) || (res > 1000))
14461 res = 1000;
14462 /* If we might need to send more mailboxes, don't wait long at all.*/
14463 if (fastrestart)
14464 res = 1;
14465 res = ast_io_wait(io, res);
14466 if (option_debug && res > 20)
14467 ast_log(LOG_DEBUG, "chan_sip: ast_io_wait ran %d all at once\n", res);
14468 ast_mutex_lock(&monlock);
14469 if (res >= 0) {
14470 res = ast_sched_runq(sched);
14471 if (option_debug && res >= 20)
14472 ast_log(LOG_DEBUG, "chan_sip: ast_sched_runq ran %d all at once\n", res);
14475 /* Send MWI notifications to peers - static and cached realtime peers */
14476 t = time(NULL);
14477 fastrestart = FALSE;
14478 curpeernum = 0;
14479 peer = NULL;
14480 /* Find next peer that needs mwi */
14481 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !peer, do {
14482 if ((curpeernum > lastpeernum) && does_peer_need_mwi(iterator)) {
14483 fastrestart = TRUE;
14484 lastpeernum = curpeernum;
14485 peer = ASTOBJ_REF(iterator);
14487 curpeernum++;
14488 } while (0)
14490 /* Send MWI to the peer */
14491 if (peer) {
14492 ASTOBJ_WRLOCK(peer);
14493 sip_send_mwi_to_peer(peer);
14494 ASTOBJ_UNLOCK(peer);
14495 ASTOBJ_UNREF(peer,sip_destroy_peer);
14496 } else {
14497 /* Reset where we come from */
14498 lastpeernum = -1;
14500 ast_mutex_unlock(&monlock);
14502 /* Never reached */
14503 return NULL;
14507 /*! \brief Start the channel monitor thread */
14508 static int restart_monitor(void)
14510 /* If we're supposed to be stopped -- stay stopped */
14511 if (monitor_thread == AST_PTHREADT_STOP)
14512 return 0;
14513 ast_mutex_lock(&monlock);
14514 if (monitor_thread == pthread_self()) {
14515 ast_mutex_unlock(&monlock);
14516 ast_log(LOG_WARNING, "Cannot kill myself\n");
14517 return -1;
14519 if (monitor_thread != AST_PTHREADT_NULL) {
14520 /* Wake up the thread */
14521 pthread_kill(monitor_thread, SIGURG);
14522 } else {
14523 /* Start a new monitor */
14524 if (ast_pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
14525 ast_mutex_unlock(&monlock);
14526 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
14527 return -1;
14530 ast_mutex_unlock(&monlock);
14531 return 0;
14534 /*! \brief React to lack of answer to Qualify poke */
14535 static int sip_poke_noanswer(void *data)
14537 struct sip_peer *peer = data;
14539 peer->pokeexpire = -1;
14540 if (peer->lastms > -1) {
14541 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
14542 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
14544 if (peer->call)
14545 sip_destroy(peer->call);
14546 peer->call = NULL;
14547 peer->lastms = -1;
14548 ast_device_state_changed("SIP/%s", peer->name);
14549 /* Try again quickly */
14550 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
14551 return 0;
14554 /*! \brief Check availability of peer, also keep NAT open
14555 \note This is done with the interval in qualify= configuration option
14556 Default is 2 seconds */
14557 static int sip_poke_peer(struct sip_peer *peer)
14559 struct sip_pvt *p;
14561 if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
14562 /* IF we have no IP, or this isn't to be monitored, return
14563 imeediately after clearing things out */
14564 if (peer->pokeexpire > -1)
14565 ast_sched_del(sched, peer->pokeexpire);
14566 peer->lastms = 0;
14567 peer->pokeexpire = -1;
14568 peer->call = NULL;
14569 return 0;
14571 if (peer->call > 0) {
14572 if (sipdebug)
14573 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
14574 sip_destroy(peer->call);
14576 if (!(p = peer->call = sip_alloc(NULL, NULL, 0, SIP_OPTIONS)))
14577 return -1;
14579 p->sa = peer->addr;
14580 p->recv = peer->addr;
14581 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14582 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14584 /* Send OPTIONs to peer's fullcontact */
14585 if (!ast_strlen_zero(peer->fullcontact))
14586 ast_string_field_set(p, fullcontact, peer->fullcontact);
14588 if (!ast_strlen_zero(peer->tohost))
14589 ast_string_field_set(p, tohost, peer->tohost);
14590 else
14591 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
14593 /* Recalculate our side, and recalculate Call ID */
14594 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
14595 p->ourip = __ourip;
14596 build_via(p);
14597 build_callid_pvt(p);
14599 if (peer->pokeexpire > -1)
14600 ast_sched_del(sched, peer->pokeexpire);
14601 p->relatedpeer = peer;
14602 ast_set_flag(&p->flags[0], SIP_OUTGOING);
14603 #ifdef VOCAL_DATA_HACK
14604 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
14605 transmit_invite(p, SIP_INVITE, 0, 2);
14606 #else
14607 transmit_invite(p, SIP_OPTIONS, 0, 2);
14608 #endif
14609 gettimeofday(&peer->ps, NULL);
14610 peer->pokeexpire = ast_sched_add(sched, DEFAULT_MAXMS * 2, sip_poke_noanswer, peer);
14612 return 0;
14615 /*! \brief Part of PBX channel interface
14616 \note
14617 \par Return values:---
14619 If we have qualify on and the device is not reachable, regardless of registration
14620 state we return AST_DEVICE_UNAVAILABLE
14622 For peers with call limit:
14623 - not registered AST_DEVICE_UNAVAILABLE
14624 - registered, no call AST_DEVICE_NOT_INUSE
14625 - registered, active calls AST_DEVICE_INUSE
14626 - registered, call limit reached AST_DEVICE_BUSY
14627 For peers without call limit:
14628 - not registered AST_DEVICE_UNAVAILABLE
14629 - registered AST_DEVICE_NOT_INUSE
14630 - fixed IP (!dynamic) AST_DEVICE_NOT_INUSE
14632 If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
14633 out a state by walking the channel list.
14635 static int sip_devicestate(void *data)
14637 char *host;
14638 char *tmp;
14640 struct hostent *hp;
14641 struct ast_hostent ahp;
14642 struct sip_peer *p;
14644 int res = AST_DEVICE_INVALID;
14646 host = ast_strdupa(data);
14647 if ((tmp = strchr(host, '@')))
14648 host = tmp + 1;
14650 if (option_debug > 2)
14651 ast_log(LOG_DEBUG, "Checking device state for peer %s\n", host);
14653 if ((p = find_peer(host, NULL, 1))) {
14654 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
14655 /* we have an address for the peer */
14656 /* if qualify is turned on, check the status */
14657 if (p->maxms && (p->lastms > p->maxms)) {
14658 res = AST_DEVICE_UNAVAILABLE;
14659 } else {
14660 /* qualify is not on, or the peer is responding properly */
14661 /* check call limit */
14662 if (p->call_limit && (p->inUse == p->call_limit))
14663 res = AST_DEVICE_BUSY;
14664 else if (p->call_limit && p->inUse)
14665 res = AST_DEVICE_INUSE;
14666 else
14667 res = AST_DEVICE_NOT_INUSE;
14668 if (p->onHold)
14669 res = AST_DEVICE_ONHOLD;
14670 else if (p->inRinging) {
14671 if (p->inRinging == p->inUse)
14672 res = AST_DEVICE_RINGING;
14673 else
14674 res = AST_DEVICE_RINGINUSE;
14677 } else {
14678 /* there is no address, it's unavailable */
14679 res = AST_DEVICE_UNAVAILABLE;
14681 ASTOBJ_UNREF(p,sip_destroy_peer);
14682 } else {
14683 hp = ast_gethostbyname(host, &ahp);
14684 if (hp)
14685 res = AST_DEVICE_UNKNOWN;
14688 return res;
14691 /*! \brief PBX interface function -build SIP pvt structure */
14692 /* SIP calls initiated by the PBX arrive here */
14693 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
14695 int oldformat;
14696 struct sip_pvt *p;
14697 struct ast_channel *tmpc = NULL;
14698 char *ext, *host;
14699 char tmp[256];
14700 char *dest = data;
14702 oldformat = format;
14703 if (!(format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1))) {
14704 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));
14705 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL; /* Can't find codec to connect to host */
14706 return NULL;
14708 if (option_debug)
14709 ast_log(LOG_DEBUG, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
14711 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE))) {
14712 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", (char *)data);
14713 *cause = AST_CAUSE_SWITCH_CONGESTION;
14714 return NULL;
14717 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
14718 sip_destroy(p);
14719 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
14720 *cause = AST_CAUSE_SWITCH_CONGESTION;
14721 return NULL;
14724 ast_copy_string(tmp, dest, sizeof(tmp));
14725 host = strchr(tmp, '@');
14726 if (host) {
14727 *host++ = '\0';
14728 ext = tmp;
14729 } else {
14730 ext = strchr(tmp, '/');
14731 if (ext)
14732 *ext++ = '\0';
14733 host = tmp;
14736 if (create_addr(p, host)) {
14737 *cause = AST_CAUSE_UNREGISTERED;
14738 if (option_debug > 2)
14739 ast_log(LOG_DEBUG, "Cant create SIP call - target device not registred\n");
14740 sip_destroy(p);
14741 return NULL;
14743 if (ast_strlen_zero(p->peername) && ext)
14744 ast_string_field_set(p, peername, ext);
14745 /* Recalculate our side, and recalculate Call ID */
14746 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
14747 p->ourip = __ourip;
14748 build_via(p);
14749 build_callid_pvt(p);
14751 /* We have an extension to call, don't use the full contact here */
14752 /* This to enable dialing registered peers with extension dialling,
14753 like SIP/peername/extension
14754 SIP/peername will still use the full contact */
14755 if (ext) {
14756 ast_string_field_set(p, username, ext);
14757 ast_string_field_free(p, fullcontact);
14759 #if 0
14760 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
14761 #endif
14762 p->prefcodec = oldformat; /* Format for this call */
14763 ast_mutex_lock(&p->lock);
14764 tmpc = sip_new(p, AST_STATE_DOWN, host); /* Place the call */
14765 ast_mutex_unlock(&p->lock);
14766 if (!tmpc)
14767 sip_destroy(p);
14768 ast_update_use_count();
14769 restart_monitor();
14770 return tmpc;
14774 \brief Handle flag-type options common to configuration of devices - users and peers
14775 \param flags array of two struct ast_flags
14776 \param mask array of two struct ast_flags
14777 \param v linked list of config variables to process
14778 \returns non-zero if any config options were handled, zero otherwise
14780 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
14782 int res = 0;
14783 static int dep_insecure_very = 0;
14784 static int dep_insecure_yes = 0;
14786 if (!strcasecmp(v->name, "trustrpid")) {
14787 ast_set_flag(&mask[0], SIP_TRUSTRPID);
14788 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
14789 res = 1;
14790 } else if (!strcasecmp(v->name, "sendrpid")) {
14791 ast_set_flag(&mask[0], SIP_SENDRPID);
14792 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
14793 res = 1;
14794 } else if (!strcasecmp(v->name, "g726nonstandard")) {
14795 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
14796 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
14797 res = 1;
14798 } else if (!strcasecmp(v->name, "useclientcode")) {
14799 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
14800 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
14801 res = 1;
14802 } else if (!strcasecmp(v->name, "dtmfmode")) {
14803 ast_set_flag(&mask[0], SIP_DTMF);
14804 ast_clear_flag(&flags[0], SIP_DTMF);
14805 if (!strcasecmp(v->value, "inband"))
14806 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
14807 else if (!strcasecmp(v->value, "rfc2833"))
14808 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
14809 else if (!strcasecmp(v->value, "info"))
14810 ast_set_flag(&flags[0], SIP_DTMF_INFO);
14811 else if (!strcasecmp(v->value, "auto"))
14812 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
14813 else {
14814 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
14815 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
14817 } else if (!strcasecmp(v->name, "nat")) {
14818 ast_set_flag(&mask[0], SIP_NAT);
14819 ast_clear_flag(&flags[0], SIP_NAT);
14820 if (!strcasecmp(v->value, "never"))
14821 ast_set_flag(&flags[0], SIP_NAT_NEVER);
14822 else if (!strcasecmp(v->value, "route"))
14823 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
14824 else if (ast_true(v->value))
14825 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
14826 else
14827 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
14828 } else if (!strcasecmp(v->name, "canreinvite")) {
14829 ast_set_flag(&mask[0], SIP_REINVITE);
14830 ast_clear_flag(&flags[0], SIP_REINVITE);
14831 if (ast_true(v->value)) {
14832 ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
14833 } else if (!ast_false(v->value)) {
14834 char buf[64];
14835 char *word, *next = buf;
14837 ast_copy_string(buf, v->value, sizeof(buf));
14838 while ((word = strsep(&next, ","))) {
14839 if (!strcasecmp(word, "update")) {
14840 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
14841 } else if (!strcasecmp(word, "nonat")) {
14842 ast_set_flag(&flags[0], SIP_CAN_REINVITE);
14843 ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
14844 } else {
14845 ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
14849 } else if (!strcasecmp(v->name, "insecure")) {
14850 ast_set_flag(&mask[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
14851 ast_clear_flag(&flags[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
14852 if (!strcasecmp(v->value, "very")) {
14853 ast_set_flag(&flags[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
14854 if (!dep_insecure_very) {
14855 ast_log(LOG_WARNING, "insecure=very at line %d is deprecated; use insecure=port,invite instead\n", v->lineno);
14856 dep_insecure_very = 1;
14859 else if (ast_true(v->value)) {
14860 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
14861 if (!dep_insecure_yes) {
14862 ast_log(LOG_WARNING, "insecure=%s at line %d is deprecated; use insecure=port instead\n", v->value, v->lineno);
14863 dep_insecure_yes = 1;
14866 else if (!ast_false(v->value)) {
14867 char buf[64];
14868 char *word, *next;
14870 ast_copy_string(buf, v->value, sizeof(buf));
14871 next = buf;
14872 while ((word = strsep(&next, ","))) {
14873 if (!strcasecmp(word, "port"))
14874 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
14875 else if (!strcasecmp(word, "invite"))
14876 ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
14877 else
14878 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", v->value, v->lineno);
14881 } else if (!strcasecmp(v->name, "progressinband")) {
14882 ast_set_flag(&mask[0], SIP_PROG_INBAND);
14883 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
14884 if (ast_true(v->value))
14885 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
14886 else if (strcasecmp(v->value, "never"))
14887 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
14888 } else if (!strcasecmp(v->name, "allowguest")) {
14889 global_allowguest = ast_true(v->value) ? 1 : 0;
14890 } else if (!strcasecmp(v->name, "promiscredir")) {
14891 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
14892 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
14893 res = 1;
14894 } else if (!strcasecmp(v->name, "videosupport")) {
14895 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
14896 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
14897 } else if (!strcasecmp(v->name, "allowoverlap")) {
14898 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
14899 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
14900 } else if (!strcasecmp(v->name, "allowsubscribe")) {
14901 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
14902 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
14903 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
14904 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_UDPTL);
14905 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_UDPTL);
14906 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
14907 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_RTP);
14908 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_RTP);
14909 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
14910 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_TCP);
14911 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_TCP);
14912 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
14913 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
14914 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
14917 return res;
14920 /*! \brief Add SIP domain to list of domains we are responsible for */
14921 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
14923 struct domain *d;
14925 if (ast_strlen_zero(domain)) {
14926 ast_log(LOG_WARNING, "Zero length domain.\n");
14927 return 1;
14930 if (!(d = ast_calloc(1, sizeof(*d))))
14931 return 0;
14933 ast_copy_string(d->domain, domain, sizeof(d->domain));
14935 if (!ast_strlen_zero(context))
14936 ast_copy_string(d->context, context, sizeof(d->context));
14938 d->mode = mode;
14940 AST_LIST_LOCK(&domain_list);
14941 AST_LIST_INSERT_TAIL(&domain_list, d, list);
14942 AST_LIST_UNLOCK(&domain_list);
14944 if (sipdebug)
14945 ast_log(LOG_DEBUG, "Added local SIP domain '%s'\n", domain);
14947 return 1;
14950 /*! \brief check_sip_domain: Check if domain part of uri is local to our server */
14951 static int check_sip_domain(const char *domain, char *context, size_t len)
14953 struct domain *d;
14954 int result = 0;
14956 AST_LIST_LOCK(&domain_list);
14957 AST_LIST_TRAVERSE(&domain_list, d, list) {
14958 if (strcasecmp(d->domain, domain))
14959 continue;
14961 if (len && !ast_strlen_zero(d->context))
14962 ast_copy_string(context, d->context, len);
14964 result = 1;
14965 break;
14967 AST_LIST_UNLOCK(&domain_list);
14969 return result;
14972 /*! \brief Clear our domain list (at reload) */
14973 static void clear_sip_domains(void)
14975 struct domain *d;
14977 AST_LIST_LOCK(&domain_list);
14978 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
14979 free(d);
14980 AST_LIST_UNLOCK(&domain_list);
14984 /*! \brief Add realm authentication in list */
14985 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno)
14987 char authcopy[256];
14988 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
14989 char *stringp;
14990 struct sip_auth *a, *b, *auth;
14992 if (ast_strlen_zero(configuration))
14993 return authlist;
14995 ast_log(LOG_DEBUG, "Auth config :: %s\n", configuration);
14997 ast_copy_string(authcopy, configuration, sizeof(authcopy));
14998 stringp = authcopy;
15000 username = stringp;
15001 realm = strrchr(stringp, '@');
15002 if (realm)
15003 *realm++ = '\0';
15004 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
15005 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
15006 return authlist;
15008 stringp = username;
15009 username = strsep(&stringp, ":");
15010 if (username) {
15011 secret = strsep(&stringp, ":");
15012 if (!secret) {
15013 stringp = username;
15014 md5secret = strsep(&stringp,"#");
15017 if (!(auth = ast_calloc(1, sizeof(*auth))))
15018 return authlist;
15020 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
15021 ast_copy_string(auth->username, username, sizeof(auth->username));
15022 if (secret)
15023 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
15024 if (md5secret)
15025 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
15027 /* find the end of the list */
15028 for (b = NULL, a = authlist; a ; b = a, a = a->next)
15030 if (b)
15031 b->next = auth; /* Add structure add end of list */
15032 else
15033 authlist = auth;
15035 if (option_verbose > 2)
15036 ast_verbose("Added authentication for realm %s\n", realm);
15038 return authlist;
15042 /*! \brief Clear realm authentication list (at reload) */
15043 static int clear_realm_authentication(struct sip_auth *authlist)
15045 struct sip_auth *a = authlist;
15046 struct sip_auth *b;
15048 while (a) {
15049 b = a;
15050 a = a->next;
15051 free(b);
15054 return 1;
15057 /*! \brief Find authentication for a specific realm */
15058 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
15060 struct sip_auth *a;
15062 for (a = authlist; a; a = a->next) {
15063 if (!strcasecmp(a->realm, realm))
15064 break;
15067 return a;
15070 /*! \brief Initiate a SIP user structure from configuration (configuration or realtime) */
15071 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime)
15073 struct sip_user *user;
15074 int format;
15075 struct ast_ha *oldha = NULL;
15076 char *varname = NULL, *varval = NULL;
15077 struct ast_variable *tmpvar = NULL;
15078 struct ast_flags userflags[2] = {{(0)}};
15079 struct ast_flags mask[2] = {{(0)}};
15082 if (!(user = ast_calloc(1, sizeof(*user))))
15083 return NULL;
15085 suserobjs++;
15086 ASTOBJ_INIT(user);
15087 ast_copy_string(user->name, name, sizeof(user->name));
15088 oldha = user->ha;
15089 user->ha = NULL;
15090 ast_copy_flags(&user->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
15091 ast_copy_flags(&user->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15092 user->capability = global_capability;
15093 user->allowtransfer = global_allowtransfer;
15094 user->maxcallbitrate = default_maxcallbitrate;
15095 user->prefs = default_prefs;
15096 /* set default context */
15097 strcpy(user->context, default_context);
15098 strcpy(user->language, default_language);
15099 strcpy(user->mohinterpret, default_mohinterpret);
15100 strcpy(user->mohsuggest, default_mohsuggest);
15101 for (; v; v = v->next) {
15102 if (handle_common_options(&userflags[0], &mask[0], v))
15103 continue;
15105 if (!strcasecmp(v->name, "context")) {
15106 ast_copy_string(user->context, v->value, sizeof(user->context));
15107 } else if (!strcasecmp(v->name, "subscribecontext")) {
15108 ast_copy_string(user->subscribecontext, v->value, sizeof(user->subscribecontext));
15109 } else if (!strcasecmp(v->name, "setvar")) {
15110 varname = ast_strdupa(v->value);
15111 if ((varval = strchr(varname,'='))) {
15112 *varval++ = '\0';
15113 if ((tmpvar = ast_variable_new(varname, varval))) {
15114 tmpvar->next = user->chanvars;
15115 user->chanvars = tmpvar;
15118 } else if (!strcasecmp(v->name, "permit") ||
15119 !strcasecmp(v->name, "deny")) {
15120 user->ha = ast_append_ha(v->name, v->value, user->ha);
15121 } else if (!strcasecmp(v->name, "allowtransfer")) {
15122 user->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
15123 } else if (!strcasecmp(v->name, "secret")) {
15124 ast_copy_string(user->secret, v->value, sizeof(user->secret));
15125 } else if (!strcasecmp(v->name, "md5secret")) {
15126 ast_copy_string(user->md5secret, v->value, sizeof(user->md5secret));
15127 } else if (!strcasecmp(v->name, "callerid")) {
15128 ast_callerid_split(v->value, user->cid_name, sizeof(user->cid_name), user->cid_num, sizeof(user->cid_num));
15129 } else if (!strcasecmp(v->name, "callgroup")) {
15130 user->callgroup = ast_get_group(v->value);
15131 } else if (!strcasecmp(v->name, "pickupgroup")) {
15132 user->pickupgroup = ast_get_group(v->value);
15133 } else if (!strcasecmp(v->name, "language")) {
15134 ast_copy_string(user->language, v->value, sizeof(user->language));
15135 } else if (!strcasecmp(v->name, "mohinterpret")
15136 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
15137 ast_copy_string(user->mohinterpret, v->value, sizeof(user->mohinterpret));
15138 } else if (!strcasecmp(v->name, "mohsuggest")) {
15139 ast_copy_string(user->mohsuggest, v->value, sizeof(user->mohsuggest));
15140 } else if (!strcasecmp(v->name, "accountcode")) {
15141 ast_copy_string(user->accountcode, v->value, sizeof(user->accountcode));
15142 } else if (!strcasecmp(v->name, "call-limit")) {
15143 user->call_limit = atoi(v->value);
15144 if (user->call_limit < 0)
15145 user->call_limit = 0;
15146 } else if (!strcasecmp(v->name, "amaflags")) {
15147 format = ast_cdr_amaflags2int(v->value);
15148 if (format < 0) {
15149 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
15150 } else {
15151 user->amaflags = format;
15153 } else if (!strcasecmp(v->name, "allow")) {
15154 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
15155 } else if (!strcasecmp(v->name, "disallow")) {
15156 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 0);
15157 } else if (!strcasecmp(v->name, "callingpres")) {
15158 user->callingpres = ast_parse_caller_presentation(v->value);
15159 if (user->callingpres == -1)
15160 user->callingpres = atoi(v->value);
15161 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
15162 user->maxcallbitrate = atoi(v->value);
15163 if (user->maxcallbitrate < 0)
15164 user->maxcallbitrate = default_maxcallbitrate;
15165 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
15166 if (ast_true(v->value)) {
15167 ast_set_flag(&user->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
15168 } else
15169 ast_clear_flag(&user->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
15170 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
15171 if (ast_true(v->value)) {
15172 ast_set_flag(&user->flags[1], SIP_PAGE2_T38SUPPORT_RTP);
15173 } else
15174 ast_clear_flag(&user->flags[1], SIP_PAGE2_T38SUPPORT_RTP);
15175 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
15176 if (ast_true(v->value)) {
15177 ast_set_flag(&user->flags[1], SIP_PAGE2_T38SUPPORT_TCP);
15178 } else
15179 ast_clear_flag(&user->flags[1], SIP_PAGE2_T38SUPPORT_TCP);
15182 ast_copy_flags(&user->flags[0], &userflags[0], mask[0].flags);
15183 ast_copy_flags(&user->flags[1], &userflags[1], mask[1].flags);
15184 if (ast_test_flag(&user->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
15185 global_allowsubscribe = TRUE; /* No global ban any more */
15186 ast_free_ha(oldha);
15187 return user;
15190 /*! \brief Set peer defaults before configuring specific configurations */
15191 static void set_peer_defaults(struct sip_peer *peer)
15193 if (peer->expire == 0) {
15194 /* Don't reset expire or port time during reload
15195 if we have an active registration
15197 peer->expire = -1;
15198 peer->pokeexpire = -1;
15199 peer->addr.sin_port = htons(DEFAULT_SIP_PORT);
15201 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
15202 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15203 strcpy(peer->context, default_context);
15204 strcpy(peer->subscribecontext, default_subscribecontext);
15205 strcpy(peer->language, default_language);
15206 strcpy(peer->mohinterpret, default_mohinterpret);
15207 strcpy(peer->mohsuggest, default_mohsuggest);
15208 peer->addr.sin_family = AF_INET;
15209 peer->defaddr.sin_family = AF_INET;
15210 peer->capability = global_capability;
15211 peer->maxcallbitrate = default_maxcallbitrate;
15212 peer->rtptimeout = global_rtptimeout;
15213 peer->rtpholdtimeout = global_rtpholdtimeout;
15214 peer->rtpkeepalive = global_rtpkeepalive;
15215 peer->allowtransfer = global_allowtransfer;
15216 strcpy(peer->vmexten, default_vmexten);
15217 peer->secret[0] = '\0';
15218 peer->md5secret[0] = '\0';
15219 peer->cid_num[0] = '\0';
15220 peer->cid_name[0] = '\0';
15221 peer->fromdomain[0] = '\0';
15222 peer->fromuser[0] = '\0';
15223 peer->regexten[0] = '\0';
15224 peer->mailbox[0] = '\0';
15225 peer->callgroup = 0;
15226 peer->pickupgroup = 0;
15227 peer->maxms = default_qualify;
15228 peer->prefs = default_prefs;
15231 /*! \brief Create temporary peer (used in autocreatepeer mode) */
15232 static struct sip_peer *temp_peer(const char *name)
15234 struct sip_peer *peer;
15236 if (!(peer = ast_calloc(1, sizeof(*peer))))
15237 return NULL;
15239 apeerobjs++;
15240 ASTOBJ_INIT(peer);
15241 set_peer_defaults(peer);
15243 ast_copy_string(peer->name, name, sizeof(peer->name));
15245 ast_set_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT);
15246 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
15247 peer->prefs = default_prefs;
15248 reg_source_db(peer);
15250 return peer;
15253 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
15254 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime)
15256 struct sip_peer *peer = NULL;
15257 struct ast_ha *oldha = NULL;
15258 int obproxyfound=0;
15259 int found=0;
15260 int format=0; /* Ama flags */
15261 time_t regseconds = 0;
15262 char *varname = NULL, *varval = NULL;
15263 struct ast_variable *tmpvar = NULL;
15264 struct ast_flags peerflags[2] = {{(0)}};
15265 struct ast_flags mask[2] = {{(0)}};
15268 if (!realtime)
15269 /* Note we do NOT use find_peer here, to avoid realtime recursion */
15270 /* We also use a case-sensitive comparison (unlike find_peer) so
15271 that case changes made to the peer name will be properly handled
15272 during reload
15274 peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);
15276 if (peer) {
15277 /* Already in the list, remove it and it will be added back (or FREE'd) */
15278 found++;
15279 } else {
15280 if (!(peer = ast_calloc(1, sizeof(*peer))))
15281 return NULL;
15283 if (realtime)
15284 rpeerobjs++;
15285 else
15286 speerobjs++;
15287 ASTOBJ_INIT(peer);
15289 /* Note that our peer HAS had its reference count incrased */
15291 peer->lastmsgssent = -1;
15292 oldha = peer->ha;
15293 peer->ha = NULL;
15294 set_peer_defaults(peer); /* Set peer defaults */
15295 if (!found && name)
15296 ast_copy_string(peer->name, name, sizeof(peer->name));
15298 /* If we have channel variables, remove them (reload) */
15299 if (peer->chanvars) {
15300 ast_variables_destroy(peer->chanvars);
15301 peer->chanvars = NULL;
15302 /* XXX should unregister ? */
15304 for (; v; v = v->next) {
15305 if (handle_common_options(&peerflags[0], &mask[0], v))
15306 continue;
15307 if (realtime && !strcasecmp(v->name, "regseconds")) {
15308 ast_get_time_t(v->value, &regseconds, 0, NULL);
15309 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
15310 inet_aton(v->value, &(peer->addr.sin_addr));
15311 } else if (realtime && !strcasecmp(v->name, "name"))
15312 ast_copy_string(peer->name, v->value, sizeof(peer->name));
15313 else if (realtime && !strcasecmp(v->name, "fullcontact")) {
15314 ast_copy_string(peer->fullcontact, v->value, sizeof(peer->fullcontact));
15315 ast_set_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT);
15316 } else if (!strcasecmp(v->name, "secret"))
15317 ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
15318 else if (!strcasecmp(v->name, "md5secret"))
15319 ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
15320 else if (!strcasecmp(v->name, "auth"))
15321 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
15322 else if (!strcasecmp(v->name, "callerid")) {
15323 ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
15324 } else if (!strcasecmp(v->name, "context")) {
15325 ast_copy_string(peer->context, v->value, sizeof(peer->context));
15326 } else if (!strcasecmp(v->name, "subscribecontext")) {
15327 ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
15328 } else if (!strcasecmp(v->name, "fromdomain")) {
15329 ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
15330 } else if (!strcasecmp(v->name, "usereqphone")) {
15331 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
15332 } else if (!strcasecmp(v->name, "fromuser")) {
15333 ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
15334 } else if (!strcasecmp(v->name, "host") || !strcasecmp(v->name, "outboundproxy")) {
15335 if (!strcasecmp(v->value, "dynamic")) {
15336 if (!strcasecmp(v->name, "outboundproxy") || obproxyfound) {
15337 ast_log(LOG_WARNING, "You can't have a dynamic outbound proxy, you big silly head at line %d.\n", v->lineno);
15338 } else {
15339 /* They'll register with us */
15340 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
15341 if (!found) {
15342 /* Initialize stuff iff we're not found, otherwise
15343 we keep going with what we had */
15344 memset(&peer->addr.sin_addr, 0, 4);
15345 if (peer->addr.sin_port) {
15346 /* If we've already got a port, make it the default rather than absolute */
15347 peer->defaddr.sin_port = peer->addr.sin_port;
15348 peer->addr.sin_port = 0;
15352 } else {
15353 /* Non-dynamic. Make sure we become that way if we're not */
15354 if (peer->expire > -1)
15355 ast_sched_del(sched, peer->expire);
15356 peer->expire = -1;
15357 ast_clear_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
15358 if (!obproxyfound || !strcasecmp(v->name, "outboundproxy")) {
15359 if (ast_get_ip_or_srv(&peer->addr, v->value, srvlookup ? "_sip._udp" : NULL)) {
15360 ASTOBJ_UNREF(peer, sip_destroy_peer);
15361 return NULL;
15364 if (!strcasecmp(v->name, "outboundproxy"))
15365 obproxyfound=1;
15366 else {
15367 ast_copy_string(peer->tohost, v->value, sizeof(peer->tohost));
15368 if (!peer->addr.sin_port)
15369 peer->addr.sin_port = htons(DEFAULT_SIP_PORT);
15372 } else if (!strcasecmp(v->name, "defaultip")) {
15373 if (ast_get_ip(&peer->defaddr, v->value)) {
15374 ASTOBJ_UNREF(peer, sip_destroy_peer);
15375 return NULL;
15377 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
15378 peer->ha = ast_append_ha(v->name, v->value, peer->ha);
15379 } else if (!strcasecmp(v->name, "port")) {
15380 if (!realtime && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC))
15381 peer->defaddr.sin_port = htons(atoi(v->value));
15382 else
15383 peer->addr.sin_port = htons(atoi(v->value));
15384 } else if (!strcasecmp(v->name, "callingpres")) {
15385 peer->callingpres = ast_parse_caller_presentation(v->value);
15386 if (peer->callingpres == -1)
15387 peer->callingpres = atoi(v->value);
15388 } else if (!strcasecmp(v->name, "username")) {
15389 ast_copy_string(peer->username, v->value, sizeof(peer->username));
15390 } else if (!strcasecmp(v->name, "language")) {
15391 ast_copy_string(peer->language, v->value, sizeof(peer->language));
15392 } else if (!strcasecmp(v->name, "regexten")) {
15393 ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
15394 } else if (!strcasecmp(v->name, "call-limit") || !strcasecmp(v->name, "incominglimit")) {
15395 peer->call_limit = atoi(v->value);
15396 if (peer->call_limit < 0)
15397 peer->call_limit = 0;
15398 } else if (!strcasecmp(v->name, "amaflags")) {
15399 format = ast_cdr_amaflags2int(v->value);
15400 if (format < 0) {
15401 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
15402 } else {
15403 peer->amaflags = format;
15405 } else if (!strcasecmp(v->name, "accountcode")) {
15406 ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
15407 } else if (!strcasecmp(v->name, "mohinterpret")
15408 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
15409 ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
15410 } else if (!strcasecmp(v->name, "mohsuggest")) {
15411 ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
15412 } else if (!strcasecmp(v->name, "mailbox")) {
15413 ast_copy_string(peer->mailbox, v->value, sizeof(peer->mailbox));
15414 } else if (!strcasecmp(v->name, "subscribemwi")) {
15415 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
15416 } else if (!strcasecmp(v->name, "vmexten")) {
15417 ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
15418 } else if (!strcasecmp(v->name, "callgroup")) {
15419 peer->callgroup = ast_get_group(v->value);
15420 } else if (!strcasecmp(v->name, "allowtransfer")) {
15421 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
15422 } else if (!strcasecmp(v->name, "pickupgroup")) {
15423 peer->pickupgroup = ast_get_group(v->value);
15424 } else if (!strcasecmp(v->name, "allow")) {
15425 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
15426 } else if (!strcasecmp(v->name, "disallow")) {
15427 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
15428 } else if (!strcasecmp(v->name, "rtptimeout")) {
15429 if ((sscanf(v->value, "%d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
15430 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
15431 peer->rtptimeout = global_rtptimeout;
15433 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
15434 if ((sscanf(v->value, "%d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
15435 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
15436 peer->rtpholdtimeout = global_rtpholdtimeout;
15438 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
15439 if ((sscanf(v->value, "%d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
15440 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
15441 peer->rtpkeepalive = global_rtpkeepalive;
15443 } else if (!strcasecmp(v->name, "setvar")) {
15444 /* Set peer channel variable */
15445 varname = ast_strdupa(v->value);
15446 if ((varval = strchr(varname, '='))) {
15447 *varval++ = '\0';
15448 if ((tmpvar = ast_variable_new(varname, varval))) {
15449 tmpvar->next = peer->chanvars;
15450 peer->chanvars = tmpvar;
15453 } else if (!strcasecmp(v->name, "qualify")) {
15454 if (!strcasecmp(v->value, "no")) {
15455 peer->maxms = 0;
15456 } else if (!strcasecmp(v->value, "yes")) {
15457 peer->maxms = DEFAULT_MAXMS;
15458 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
15459 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);
15460 peer->maxms = 0;
15462 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
15463 peer->maxcallbitrate = atoi(v->value);
15464 if (peer->maxcallbitrate < 0)
15465 peer->maxcallbitrate = default_maxcallbitrate;
15466 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
15467 if (ast_true(v->value)) {
15468 ast_set_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
15469 } else
15470 ast_clear_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
15471 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
15472 if (ast_true(v->value)) {
15473 ast_set_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_RTP);
15474 } else
15475 ast_clear_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_RTP);
15476 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
15477 if (ast_true(v->value)) {
15478 ast_set_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_TCP);
15479 } else
15480 ast_clear_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_TCP);
15483 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && realtime) {
15484 time_t nowtime = time(NULL);
15486 if ((nowtime - regseconds) > 0) {
15487 destroy_association(peer);
15488 memset(&peer->addr, 0, sizeof(peer->addr));
15489 if (option_debug)
15490 ast_log(LOG_DEBUG, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
15493 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
15494 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
15495 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
15496 global_allowsubscribe = TRUE; /* No global ban any more */
15497 if (!found && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && !ast_test_flag(&peer->flags[0], SIP_REALTIME))
15498 reg_source_db(peer);
15499 ASTOBJ_UNMARK(peer);
15500 ast_free_ha(oldha);
15501 return peer;
15504 /*! \brief Re-read SIP.conf config file
15505 \note This function reloads all config data, except for
15506 active peers (with registrations). They will only
15507 change configuration data at restart, not at reload.
15508 SIP debug and recordhistory state will not change
15510 static int reload_config(enum channelreloadreason reason)
15512 struct ast_config *cfg;
15513 struct ast_variable *v;
15514 struct sip_peer *peer;
15515 struct sip_user *user;
15516 struct ast_hostent ahp;
15517 char *cat, *stringp, *context, *oldregcontext;
15518 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
15519 struct hostent *hp;
15520 int format;
15521 struct ast_flags dummy[2];
15522 int auto_sip_domains = FALSE;
15523 struct sockaddr_in old_bindaddr = bindaddr;
15524 int registry_count = 0, peer_count = 0, user_count = 0;
15525 unsigned int temp_tos = 0;
15526 struct ast_flags debugflag = {0};
15528 cfg = ast_config_load(config);
15530 /* We *must* have a config file otherwise stop immediately */
15531 if (!cfg) {
15532 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
15533 return -1;
15536 /* Initialize copy of current global_regcontext for later use in removing stale contexts */
15537 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
15538 oldregcontext = oldcontexts;
15540 /* Clear all flags before setting default values */
15541 /* Preserve debugging settings for console */
15542 ast_copy_flags(&debugflag, &global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
15543 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
15544 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
15545 ast_copy_flags(&global_flags[1], &debugflag, SIP_PAGE2_DEBUG_CONSOLE);
15547 /* Reset IP addresses */
15548 memset(&bindaddr, 0, sizeof(bindaddr));
15549 memset(&localaddr, 0, sizeof(localaddr));
15550 memset(&externip, 0, sizeof(externip));
15551 memset(&default_prefs, 0 , sizeof(default_prefs));
15552 outboundproxyip.sin_port = htons(DEFAULT_SIP_PORT);
15553 outboundproxyip.sin_family = AF_INET; /* Type of address: IPv4 */
15554 ourport = DEFAULT_SIP_PORT;
15555 srvlookup = DEFAULT_SRVLOOKUP;
15556 global_tos_sip = DEFAULT_TOS_SIP;
15557 global_tos_audio = DEFAULT_TOS_AUDIO;
15558 global_tos_video = DEFAULT_TOS_VIDEO;
15559 externhost[0] = '\0'; /* External host name (for behind NAT DynDNS support) */
15560 externexpire = 0; /* Expiration for DNS re-issuing */
15561 externrefresh = 10;
15562 memset(&outboundproxyip, 0, sizeof(outboundproxyip));
15564 /* Reset channel settings to default before re-configuring */
15565 allow_external_domains = DEFAULT_ALLOW_EXT_DOM; /* Allow external invites */
15566 global_regcontext[0] = '\0';
15567 expiry = DEFAULT_EXPIRY;
15568 global_notifyringing = DEFAULT_NOTIFYRINGING;
15569 global_alwaysauthreject = 0;
15570 global_allowsubscribe = FALSE;
15571 ast_copy_string(global_useragent, DEFAULT_USERAGENT, sizeof(global_useragent));
15572 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
15573 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME))
15574 ast_copy_string(global_realm, DEFAULT_REALM, sizeof(global_realm));
15575 else
15576 ast_copy_string(global_realm, ast_config_AST_SYSTEM_NAME, sizeof(global_realm));
15577 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
15578 compactheaders = DEFAULT_COMPACTHEADERS;
15579 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
15580 global_regattempts_max = 0;
15581 pedanticsipchecking = DEFAULT_PEDANTIC;
15582 global_mwitime = DEFAULT_MWITIME;
15583 autocreatepeer = DEFAULT_AUTOCREATEPEER;
15584 global_allowguest = DEFAULT_ALLOWGUEST;
15585 global_rtptimeout = 0;
15586 global_rtpholdtimeout = 0;
15587 global_rtpkeepalive = 0;
15588 global_allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
15589 global_rtautoclear = 120;
15590 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE); /* Default for peers, users: TRUE */
15591 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP); /* Default for peers, users: TRUE */
15592 ast_set_flag(&global_flags[1], SIP_PAGE2_RTUPDATE);
15594 /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for peers and users */
15595 ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
15596 default_subscribecontext[0] = '\0';
15597 default_language[0] = '\0';
15598 default_fromdomain[0] = '\0';
15599 default_qualify = DEFAULT_QUALIFY;
15600 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
15601 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
15602 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
15603 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
15604 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833); /*!< Default DTMF setting: RFC2833 */
15605 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581); /*!< NAT support if requested by device with rport */
15606 ast_set_flag(&global_flags[0], SIP_CAN_REINVITE); /*!< Allow re-invites */
15608 /* Debugging settings, always default to off */
15609 dumphistory = FALSE;
15610 recordhistory = FALSE;
15611 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
15613 /* Misc settings for the channel */
15614 global_relaxdtmf = FALSE;
15615 global_callevents = FALSE;
15616 global_t1min = DEFAULT_T1MIN;
15618 /* Copy the default jb config over global_jbconf */
15619 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
15621 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT);
15623 /* Read the [general] config section of sip.conf (or from realtime config) */
15624 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
15625 if (handle_common_options(&global_flags[0], &dummy[0], v))
15626 continue;
15627 /* handle jb conf */
15628 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
15629 continue;
15631 /* Create the interface list */
15632 if (!strcasecmp(v->name, "context")) {
15633 ast_copy_string(default_context, v->value, sizeof(default_context));
15634 } else if (!strcasecmp(v->name, "realm")) {
15635 ast_copy_string(global_realm, v->value, sizeof(global_realm));
15636 } else if (!strcasecmp(v->name, "useragent")) {
15637 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
15638 if (option_debug)
15639 ast_log(LOG_DEBUG, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
15640 } else if (!strcasecmp(v->name, "allowtransfer")) {
15641 global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
15642 } else if (!strcasecmp(v->name, "rtcachefriends")) {
15643 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
15644 } else if (!strcasecmp(v->name, "rtsavesysname")) {
15645 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTSAVE_SYSNAME);
15646 } else if (!strcasecmp(v->name, "rtupdate")) {
15647 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTUPDATE);
15648 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
15649 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_IGNOREREGEXPIRE);
15650 } else if (!strcasecmp(v->name, "t1min")) {
15651 global_t1min = atoi(v->value);
15652 } else if (!strcasecmp(v->name, "rtautoclear")) {
15653 int i = atoi(v->value);
15654 if (i > 0)
15655 global_rtautoclear = i;
15656 else
15657 i = 0;
15658 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
15659 } else if (!strcasecmp(v->name, "usereqphone")) {
15660 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
15661 } else if (!strcasecmp(v->name, "relaxdtmf")) {
15662 global_relaxdtmf = ast_true(v->value);
15663 } else if (!strcasecmp(v->name, "checkmwi")) {
15664 if ((sscanf(v->value, "%d", &global_mwitime) != 1) || (global_mwitime < 0)) {
15665 ast_log(LOG_WARNING, "'%s' is not a valid MWI time setting at line %d. Using default (10).\n", v->value, v->lineno);
15666 global_mwitime = DEFAULT_MWITIME;
15668 } else if (!strcasecmp(v->name, "vmexten")) {
15669 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
15670 } else if (!strcasecmp(v->name, "rtptimeout")) {
15671 if ((sscanf(v->value, "%d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
15672 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
15673 global_rtptimeout = 0;
15675 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
15676 if ((sscanf(v->value, "%d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
15677 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
15678 global_rtpholdtimeout = 0;
15680 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
15681 if ((sscanf(v->value, "%d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
15682 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
15683 global_rtpkeepalive = 0;
15685 } else if (!strcasecmp(v->name, "compactheaders")) {
15686 compactheaders = ast_true(v->value);
15687 } else if (!strcasecmp(v->name, "notifymimetype")) {
15688 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
15689 } else if (!strcasecmp(v->name, "notifyringing")) {
15690 global_notifyringing = ast_true(v->value);
15691 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
15692 global_alwaysauthreject = ast_true(v->value);
15693 } else if (!strcasecmp(v->name, "mohinterpret")
15694 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
15695 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
15696 } else if (!strcasecmp(v->name, "mohsuggest")) {
15697 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
15698 } else if (!strcasecmp(v->name, "language")) {
15699 ast_copy_string(default_language, v->value, sizeof(default_language));
15700 } else if (!strcasecmp(v->name, "regcontext")) {
15701 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
15702 stringp = newcontexts;
15703 /* Let's remove any contexts that are no longer defined in regcontext */
15704 cleanup_stale_contexts(stringp, oldregcontext);
15705 /* Create contexts if they don't exist already */
15706 while ((context = strsep(&stringp, "&"))) {
15707 if (!ast_context_find(context))
15708 ast_context_create(NULL, context,"SIP");
15710 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
15711 } else if (!strcasecmp(v->name, "callerid")) {
15712 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
15713 } else if (!strcasecmp(v->name, "fromdomain")) {
15714 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
15715 } else if (!strcasecmp(v->name, "outboundproxy")) {
15716 if (ast_get_ip_or_srv(&outboundproxyip, v->value, srvlookup ? "_sip._udp" : NULL) < 0)
15717 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", v->value);
15718 } else if (!strcasecmp(v->name, "outboundproxyport")) {
15719 /* Port needs to be after IP */
15720 sscanf(v->value, "%d", &format);
15721 outboundproxyip.sin_port = htons(format);
15722 } else if (!strcasecmp(v->name, "autocreatepeer")) {
15723 autocreatepeer = ast_true(v->value);
15724 } else if (!strcasecmp(v->name, "srvlookup")) {
15725 srvlookup = ast_true(v->value);
15726 } else if (!strcasecmp(v->name, "pedantic")) {
15727 pedanticsipchecking = ast_true(v->value);
15728 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
15729 max_expiry = atoi(v->value);
15730 if (max_expiry < 1)
15731 max_expiry = DEFAULT_MAX_EXPIRY;
15732 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
15733 min_expiry = atoi(v->value);
15734 if (min_expiry < 1)
15735 min_expiry = DEFAULT_MIN_EXPIRY;
15736 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
15737 default_expiry = atoi(v->value);
15738 if (default_expiry < 1)
15739 default_expiry = DEFAULT_DEFAULT_EXPIRY;
15740 } else if (!strcasecmp(v->name, "sipdebug")) {
15741 if (ast_true(v->value))
15742 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
15743 } else if (!strcasecmp(v->name, "dumphistory")) {
15744 dumphistory = ast_true(v->value);
15745 } else if (!strcasecmp(v->name, "recordhistory")) {
15746 recordhistory = ast_true(v->value);
15747 } else if (!strcasecmp(v->name, "registertimeout")) {
15748 global_reg_timeout = atoi(v->value);
15749 if (global_reg_timeout < 1)
15750 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
15751 } else if (!strcasecmp(v->name, "registerattempts")) {
15752 global_regattempts_max = atoi(v->value);
15753 } else if (!strcasecmp(v->name, "bindaddr")) {
15754 if (!(hp = ast_gethostbyname(v->value, &ahp))) {
15755 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
15756 } else {
15757 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
15759 } else if (!strcasecmp(v->name, "localnet")) {
15760 struct ast_ha *na;
15761 if (!(na = ast_append_ha("d", v->value, localaddr)))
15762 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
15763 else
15764 localaddr = na;
15765 } else if (!strcasecmp(v->name, "localmask")) {
15766 ast_log(LOG_WARNING, "Use of localmask is no long supported -- use localnet with mask syntax\n");
15767 } else if (!strcasecmp(v->name, "externip")) {
15768 if (!(hp = ast_gethostbyname(v->value, &ahp)))
15769 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
15770 else
15771 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
15772 externexpire = 0;
15773 } else if (!strcasecmp(v->name, "externhost")) {
15774 ast_copy_string(externhost, v->value, sizeof(externhost));
15775 if (!(hp = ast_gethostbyname(externhost, &ahp)))
15776 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
15777 else
15778 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
15779 externexpire = time(NULL);
15780 } else if (!strcasecmp(v->name, "externrefresh")) {
15781 if (sscanf(v->value, "%d", &externrefresh) != 1) {
15782 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
15783 externrefresh = 10;
15785 } else if (!strcasecmp(v->name, "allow")) {
15786 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 1);
15787 } else if (!strcasecmp(v->name, "disallow")) {
15788 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 0);
15789 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
15790 allow_external_domains = ast_true(v->value);
15791 } else if (!strcasecmp(v->name, "autodomain")) {
15792 auto_sip_domains = ast_true(v->value);
15793 } else if (!strcasecmp(v->name, "domain")) {
15794 char *domain = ast_strdupa(v->value);
15795 char *context = strchr(domain, ',');
15797 if (context)
15798 *context++ = '\0';
15800 if (option_debug && ast_strlen_zero(context))
15801 ast_log(LOG_DEBUG, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
15802 if (ast_strlen_zero(domain))
15803 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
15804 else
15805 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, context ? ast_strip(context) : "");
15806 } else if (!strcasecmp(v->name, "register")) {
15807 if (sip_register(v->value, v->lineno) == 0)
15808 registry_count++;
15809 } else if (!strcasecmp(v->name, "tos")) {
15810 if (!ast_str2tos(v->value, &temp_tos)) {
15811 global_tos_sip = temp_tos;
15812 global_tos_audio = temp_tos;
15813 global_tos_video = temp_tos;
15814 ast_log(LOG_WARNING, "tos value at line %d is deprecated. See doc/ip-tos.txt for more information.", v->lineno);
15815 } else
15816 ast_log(LOG_WARNING, "Invalid tos value at line %d, See doc/ip-tos.txt for more information.\n", v->lineno);
15817 } else if (!strcasecmp(v->name, "tos_sip")) {
15818 if (ast_str2tos(v->value, &global_tos_sip))
15819 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, recommended value is 'cs3'. See doc/ip-tos.txt.\n", v->lineno);
15820 } else if (!strcasecmp(v->name, "tos_audio")) {
15821 if (ast_str2tos(v->value, &global_tos_audio))
15822 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, recommended value is 'ef'. See doc/ip-tos.txt.\n", v->lineno);
15823 } else if (!strcasecmp(v->name, "tos_video")) {
15824 if (ast_str2tos(v->value, &global_tos_video))
15825 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, recommended value is 'af41'. See doc/ip-tos.txt.\n", v->lineno);
15826 } else if (!strcasecmp(v->name, "bindport")) {
15827 if (sscanf(v->value, "%d", &ourport) == 1) {
15828 bindaddr.sin_port = htons(ourport);
15829 } else {
15830 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
15832 } else if (!strcasecmp(v->name, "qualify")) {
15833 if (!strcasecmp(v->value, "no")) {
15834 default_qualify = 0;
15835 } else if (!strcasecmp(v->value, "yes")) {
15836 default_qualify = DEFAULT_MAXMS;
15837 } else if (sscanf(v->value, "%d", &default_qualify) != 1) {
15838 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
15839 default_qualify = 0;
15841 } else if (!strcasecmp(v->name, "callevents")) {
15842 global_callevents = ast_true(v->value);
15843 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
15844 default_maxcallbitrate = atoi(v->value);
15845 if (default_maxcallbitrate < 0)
15846 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
15847 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
15848 if (ast_true(v->value)) {
15849 ast_set_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
15851 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
15852 if (ast_true(v->value)) {
15853 ast_set_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_RTP);
15855 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
15856 if (ast_true(v->value)) {
15857 ast_set_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_TCP);
15862 if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
15863 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
15864 allow_external_domains = 1;
15867 /* Build list of authentication to various SIP realms, i.e. service providers */
15868 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
15869 /* Format for authentication is auth = username:password@realm */
15870 if (!strcasecmp(v->name, "auth"))
15871 authl = add_realm_authentication(authl, v->value, v->lineno);
15874 /* Load peers, users and friends */
15875 cat = NULL;
15876 while ( (cat = ast_category_browse(cfg, cat)) ) {
15877 const char *utype;
15878 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
15879 continue;
15880 utype = ast_variable_retrieve(cfg, cat, "type");
15881 if (!utype) {
15882 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
15883 continue;
15884 } else {
15885 int is_user = 0, is_peer = 0;
15886 if (!strcasecmp(utype, "user"))
15887 is_user = 1;
15888 else if (!strcasecmp(utype, "friend"))
15889 is_user = is_peer = 1;
15890 else if (!strcasecmp(utype, "peer"))
15891 is_peer = 1;
15892 else {
15893 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
15894 continue;
15896 if (is_user) {
15897 user = build_user(cat, ast_variable_browse(cfg, cat), 0);
15898 if (user) {
15899 ASTOBJ_CONTAINER_LINK(&userl,user);
15900 ASTOBJ_UNREF(user, sip_destroy_user);
15901 user_count++;
15904 if (is_peer) {
15905 peer = build_peer(cat, ast_variable_browse(cfg, cat), 0);
15906 if (peer) {
15907 ASTOBJ_CONTAINER_LINK(&peerl,peer);
15908 ASTOBJ_UNREF(peer, sip_destroy_peer);
15909 peer_count++;
15914 if (ast_find_ourip(&__ourip, bindaddr)) {
15915 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
15916 return 0;
15918 if (!ntohs(bindaddr.sin_port))
15919 bindaddr.sin_port = ntohs(DEFAULT_SIP_PORT);
15920 bindaddr.sin_family = AF_INET;
15921 ast_mutex_lock(&netlock);
15922 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
15923 close(sipsock);
15924 sipsock = -1;
15926 if (sipsock < 0) {
15927 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
15928 if (sipsock < 0) {
15929 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
15930 } else {
15931 /* Allow SIP clients on the same host to access us: */
15932 const int reuseFlag = 1;
15933 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
15934 (const char*)&reuseFlag,
15935 sizeof reuseFlag);
15937 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
15938 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
15939 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
15940 strerror(errno));
15941 close(sipsock);
15942 sipsock = -1;
15943 } else {
15944 if (option_verbose > 1) {
15945 ast_verbose(VERBOSE_PREFIX_2 "SIP Listening on %s:%d\n",
15946 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
15947 ast_verbose(VERBOSE_PREFIX_2 "Using SIP TOS: %s\n", ast_tos2str(global_tos_sip));
15949 if (setsockopt(sipsock, IPPROTO_IP, IP_TOS, &global_tos_sip, sizeof(global_tos_sip)))
15950 ast_log(LOG_WARNING, "Unable to set SIP TOS to %s\n", ast_tos2str(global_tos_sip));
15954 ast_mutex_unlock(&netlock);
15956 /* Add default domains - host name, IP address and IP:port */
15957 /* Only do this if user added any sip domain with "localdomains" */
15958 /* In order to *not* break backwards compatibility */
15959 /* Some phones address us at IP only, some with additional port number */
15960 if (auto_sip_domains) {
15961 char temp[MAXHOSTNAMELEN];
15963 /* First our default IP address */
15964 if (bindaddr.sin_addr.s_addr)
15965 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
15966 else
15967 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
15969 /* Our extern IP address, if configured */
15970 if (externip.sin_addr.s_addr)
15971 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
15973 /* Extern host name (NAT traversal support) */
15974 if (!ast_strlen_zero(externhost))
15975 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
15977 /* Our host name */
15978 if (!gethostname(temp, sizeof(temp)))
15979 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
15982 /* Release configuration from memory */
15983 ast_config_destroy(cfg);
15985 /* Load the list of manual NOTIFY types to support */
15986 if (notify_types)
15987 ast_config_destroy(notify_types);
15988 notify_types = ast_config_load(notify_config);
15990 /* Done, tell the manager */
15991 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);
15993 return 0;
15996 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
15998 struct sip_pvt *p;
15999 struct ast_udptl *udptl = NULL;
16001 p = chan->tech_pvt;
16002 if (!p)
16003 return NULL;
16005 ast_mutex_lock(&p->lock);
16006 if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
16007 udptl = p->udptl;
16008 ast_mutex_unlock(&p->lock);
16009 return udptl;
16012 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
16014 struct sip_pvt *p;
16016 p = chan->tech_pvt;
16017 if (!p)
16018 return -1;
16019 ast_mutex_lock(&p->lock);
16020 if (udptl)
16021 ast_udptl_get_peer(udptl, &p->udptlredirip);
16022 else
16023 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
16024 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
16025 if (!p->pendinginvite) {
16026 if (option_debug > 2) {
16027 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);
16029 transmit_reinvite_with_t38_sdp(p);
16030 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
16031 if (option_debug > 2) {
16032 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);
16034 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
16037 /* Reset lastrtprx timer */
16038 p->lastrtprx = p->lastrtptx = time(NULL);
16039 ast_mutex_unlock(&p->lock);
16040 return 0;
16043 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite)
16045 struct sip_pvt *p;
16046 int flag = 0;
16048 p = chan->tech_pvt;
16049 if (!p || !pvt->udptl)
16050 return -1;
16052 /* Setup everything on the other side like offered/responded from first side */
16053 ast_mutex_lock(&p->lock);
16054 p->t38.jointcapability = p->t38.peercapability = pvt->t38.jointcapability;
16055 ast_udptl_set_far_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
16056 ast_udptl_set_local_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
16057 ast_udptl_set_error_correction_scheme(p->udptl, ast_udptl_get_error_correction_scheme(pvt->udptl));
16059 if (reinvite) { /* If we are handling sending re-invite to the other side of the bridge */
16060 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
16061 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
16062 flag =1;
16063 } else {
16064 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
16066 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
16067 if (!p->pendinginvite) {
16068 if (option_debug > 2) {
16069 if (flag)
16070 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));
16071 else
16072 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));
16074 transmit_reinvite_with_t38_sdp(p);
16075 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
16076 if (option_debug > 2) {
16077 if (flag)
16078 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));
16079 else
16080 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));
16082 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
16085 /* Reset lastrtprx timer */
16086 p->lastrtprx = p->lastrtptx = time(NULL);
16087 ast_mutex_unlock(&p->lock);
16088 return 0;
16089 } else { /* If we are handling sending 200 OK to the other side of the bridge */
16090 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
16091 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
16092 flag = 1;
16093 } else {
16094 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
16096 if (option_debug > 2) {
16097 if (flag)
16098 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));
16099 else
16100 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));
16102 pvt->t38.state = T38_ENABLED;
16103 p->t38.state = T38_ENABLED;
16104 if (option_debug > 1) {
16105 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", pvt->t38.state, pvt->owner ? pvt->owner->name : "<none>");
16106 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
16108 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
16109 p->lastrtprx = p->lastrtptx = time(NULL);
16110 ast_mutex_unlock(&p->lock);
16111 return 0;
16116 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
16117 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
16119 struct sip_pvt *p = NULL;
16120 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
16122 if (!(p = chan->tech_pvt))
16123 return AST_RTP_GET_FAILED;
16125 ast_mutex_lock(&p->lock);
16126 if (!(p->rtp)) {
16127 ast_mutex_unlock(&p->lock);
16128 return AST_RTP_GET_FAILED;
16131 *rtp = p->rtp;
16133 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
16134 res = AST_RTP_TRY_NATIVE;
16136 ast_mutex_unlock(&p->lock);
16138 return res;
16141 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
16142 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
16144 struct sip_pvt *p = NULL;
16145 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
16147 if (!(p = chan->tech_pvt))
16148 return AST_RTP_GET_FAILED;
16150 ast_mutex_lock(&p->lock);
16151 if (!(p->vrtp)) {
16152 ast_mutex_unlock(&p->lock);
16153 return AST_RTP_GET_FAILED;
16156 *rtp = p->vrtp;
16158 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
16159 res = AST_RTP_TRY_NATIVE;
16161 ast_mutex_unlock(&p->lock);
16163 return res;
16166 /*! \brief Set the RTP peer for this call */
16167 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
16169 struct sip_pvt *p;
16170 int changed = 0;
16172 p = chan->tech_pvt;
16173 if (!p)
16174 return -1;
16175 ast_mutex_lock(&p->lock);
16176 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) {
16177 /* If we're destroyed, don't bother */
16178 ast_mutex_unlock(&p->lock);
16179 return 0;
16182 /* if this peer cannot handle reinvites of the media stream to devices
16183 that are known to be behind a NAT, then stop the process now
16185 if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
16186 ast_mutex_unlock(&p->lock);
16187 return 0;
16190 if (rtp) {
16191 changed |= ast_rtp_get_peer(rtp, &p->redirip);
16192 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
16193 memset(&p->redirip, 0, sizeof(p->redirip));
16194 changed = 1;
16196 if (vrtp) {
16197 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
16198 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
16199 memset(&p->vredirip, 0, sizeof(p->vredirip));
16200 changed = 1;
16202 if (codecs && (p->redircodecs != codecs)) {
16203 p->redircodecs = codecs;
16204 changed = 1;
16206 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
16207 if (chan->_state != AST_STATE_UP) { /* We are in early state */
16208 if (recordhistory)
16209 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
16210 if (option_debug)
16211 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));
16212 } else if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
16213 if (option_debug > 2) {
16214 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));
16216 transmit_reinvite_with_sdp(p);
16217 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
16218 if (option_debug > 2) {
16219 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));
16221 /* We have a pending Invite. Send re-invite when we're done with the invite */
16222 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
16225 /* Reset lastrtprx timer */
16226 p->lastrtprx = p->lastrtptx = time(NULL);
16227 ast_mutex_unlock(&p->lock);
16228 return 0;
16231 static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
16232 static char *descrip_dtmfmode = "SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
16233 static char *app_dtmfmode = "SIPDtmfMode";
16235 static char *app_sipaddheader = "SIPAddHeader";
16236 static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
16238 static char *descrip_sipaddheader = ""
16239 " SIPAddHeader(Header: Content)\n"
16240 "Adds a header to a SIP call placed with DIAL.\n"
16241 "Remember to user the X-header if you are adding non-standard SIP\n"
16242 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
16243 "Adding the wrong headers may jeopardize the SIP dialog.\n"
16244 "Always returns 0\n";
16247 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
16248 static int sip_dtmfmode(struct ast_channel *chan, void *data)
16250 struct sip_pvt *p;
16251 char *mode;
16252 if (data)
16253 mode = (char *)data;
16254 else {
16255 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
16256 return 0;
16258 ast_channel_lock(chan);
16259 if (chan->tech != &sip_tech) {
16260 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
16261 ast_channel_unlock(chan);
16262 return 0;
16264 p = chan->tech_pvt;
16265 if (!p) {
16266 ast_channel_unlock(chan);
16267 return 0;
16269 ast_mutex_lock(&p->lock);
16270 if (!strcasecmp(mode,"info")) {
16271 ast_clear_flag(&p->flags[0], SIP_DTMF);
16272 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
16273 } else if (!strcasecmp(mode,"rfc2833")) {
16274 ast_clear_flag(&p->flags[0], SIP_DTMF);
16275 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
16276 } else if (!strcasecmp(mode,"inband")) {
16277 ast_clear_flag(&p->flags[0], SIP_DTMF);
16278 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
16279 } else
16280 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n",mode);
16281 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
16282 if (!p->vad) {
16283 p->vad = ast_dsp_new();
16284 ast_dsp_set_features(p->vad, DSP_FEATURE_DTMF_DETECT);
16286 } else {
16287 if (p->vad) {
16288 ast_dsp_free(p->vad);
16289 p->vad = NULL;
16292 ast_mutex_unlock(&p->lock);
16293 ast_channel_unlock(chan);
16294 return 0;
16297 /*! \brief Add a SIP header to an outbound INVITE */
16298 static int sip_addheader(struct ast_channel *chan, void *data)
16300 int no = 0;
16301 int ok = FALSE;
16302 char varbuf[30];
16303 char *inbuf = (char *) data;
16305 if (ast_strlen_zero(inbuf)) {
16306 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
16307 return 0;
16309 ast_channel_lock(chan);
16311 /* Check for headers */
16312 while (!ok && no <= 50) {
16313 no++;
16314 snprintf(varbuf, sizeof(varbuf), "_SIPADDHEADER%.2d", no);
16316 if( (pbx_builtin_getvar_helper(chan, (const char *) varbuf) == (const char *) NULL) )
16317 ok = TRUE;
16319 if (ok) {
16320 pbx_builtin_setvar_helper (chan, varbuf, inbuf);
16321 if (sipdebug)
16322 ast_log(LOG_DEBUG,"SIP Header added \"%s\" as %s\n", inbuf, varbuf);
16323 } else {
16324 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
16326 ast_channel_unlock(chan);
16327 return 0;
16330 /*! \brief Transfer call before connect with a 302 redirect
16331 \note Called by the transfer() dialplan application through the sip_transfer()
16332 pbx interface function if the call is in ringing state
16333 \todo Fix this function so that we wait for reply to the REFER and
16334 react to errors, denials or other issues the other end might have.
16336 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
16338 char *cdest;
16339 char *extension, *host, *port;
16340 char tmp[80];
16342 cdest = ast_strdupa(dest);
16344 extension = strsep(&cdest, "@");
16345 host = strsep(&cdest, ":");
16346 port = strsep(&cdest, ":");
16347 if (!extension) {
16348 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
16349 return 0;
16352 /* we'll issue the redirect message here */
16353 if (!host) {
16354 char *localtmp;
16355 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
16356 if (ast_strlen_zero(tmp)) {
16357 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
16358 return 0;
16360 if ((localtmp = strstr(tmp, "sip:")) && (localtmp = strchr(localtmp, '@'))) {
16361 char lhost[80], lport[80];
16362 memset(lhost, 0, sizeof(lhost));
16363 memset(lport, 0, sizeof(lport));
16364 localtmp++;
16365 /* This is okey because lhost and lport are as big as tmp */
16366 sscanf(localtmp, "%[^<>:; ]:%[^<>:; ]", lhost, lport);
16367 if (ast_strlen_zero(lhost)) {
16368 ast_log(LOG_ERROR, "Can't find the host address\n");
16369 return 0;
16371 host = ast_strdupa(lhost);
16372 if (!ast_strlen_zero(lport)) {
16373 port = ast_strdupa(lport);
16378 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
16379 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
16381 /* this is all that we want to send to that SIP device */
16382 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
16384 /* hangup here */
16385 return -1;
16388 /*! \brief Return SIP UA's codec (part of the RTP interface) */
16389 static int sip_get_codec(struct ast_channel *chan)
16391 struct sip_pvt *p = chan->tech_pvt;
16392 return p->peercapability;
16395 /*! \brief Send a poke to all known peers
16396 Space them out 100 ms apart
16397 XXX We might have a cool algorithm for this or use random - any suggestions?
16399 static void sip_poke_all_peers(void)
16401 int ms = 0;
16403 if (!speerobjs) /* No peers, just give up */
16404 return;
16406 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
16407 ASTOBJ_WRLOCK(iterator);
16408 if (iterator->pokeexpire > -1)
16409 ast_sched_del(sched, iterator->pokeexpire);
16410 ms += 100;
16411 iterator->pokeexpire = ast_sched_add(sched, ms, sip_poke_peer_s, iterator);
16412 ASTOBJ_UNLOCK(iterator);
16413 } while (0)
16417 /*! \brief Send all known registrations */
16418 static void sip_send_all_registers(void)
16420 int ms;
16421 int regspacing;
16422 if (!regobjs)
16423 return;
16424 regspacing = default_expiry * 1000/regobjs;
16425 if (regspacing > 100)
16426 regspacing = 100;
16427 ms = regspacing;
16428 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
16429 ASTOBJ_WRLOCK(iterator);
16430 if (iterator->expire > -1)
16431 ast_sched_del(sched, iterator->expire);
16432 ms += regspacing;
16433 iterator->expire = ast_sched_add(sched, ms, sip_reregister, iterator);
16434 ASTOBJ_UNLOCK(iterator);
16435 } while (0)
16439 /*! \brief Reload module */
16440 static int sip_do_reload(enum channelreloadreason reason)
16442 if (option_debug > 3)
16443 ast_log(LOG_DEBUG, "--------------- SIP reload started\n");
16445 clear_realm_authentication(authl);
16446 clear_sip_domains();
16447 authl = NULL;
16449 /* First, destroy all outstanding registry calls */
16450 /* This is needed, since otherwise active registry entries will not be destroyed */
16451 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
16452 ASTOBJ_RDLOCK(iterator);
16453 if (iterator->call) {
16454 if (option_debug > 2)
16455 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
16456 /* This will also remove references to the registry */
16457 sip_destroy(iterator->call);
16459 ASTOBJ_UNLOCK(iterator);
16460 } while(0));
16462 /* Then, actually destroy users and registry */
16463 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
16464 if (option_debug > 3)
16465 ast_log(LOG_DEBUG, "--------------- Done destroying user list\n");
16466 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
16467 if (option_debug > 3)
16468 ast_log(LOG_DEBUG, "--------------- Done destroying registry list\n");
16469 ASTOBJ_CONTAINER_MARKALL(&peerl);
16470 reload_config(reason);
16472 /* Prune peers who still are supposed to be deleted */
16473 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
16474 if (option_debug > 3)
16475 ast_log(LOG_DEBUG, "--------------- Done destroying pruned peers\n");
16477 /* Send qualify (OPTIONS) to all peers */
16478 sip_poke_all_peers();
16480 /* Register with all services */
16481 sip_send_all_registers();
16483 if (option_debug > 3)
16484 ast_log(LOG_DEBUG, "--------------- SIP reload done\n");
16486 return 0;
16489 /*! \brief Force reload of module from cli */
16490 static int sip_reload(int fd, int argc, char *argv[])
16493 ast_mutex_lock(&sip_reload_lock);
16494 if (sip_reloading) {
16495 ast_verbose("Previous SIP reload not yet done\n");
16496 } else {
16497 sip_reloading = TRUE;
16498 if (fd)
16499 sip_reloadreason = CHANNEL_CLI_RELOAD;
16500 else
16501 sip_reloadreason = CHANNEL_MODULE_RELOAD;
16503 ast_mutex_unlock(&sip_reload_lock);
16504 restart_monitor();
16506 return 0;
16509 /*! \brief reload: Part of Asterisk module interface */
16510 static int reload(void)
16512 return sip_reload(0, 0, NULL);
16515 static struct ast_cli_entry my_clis[] = {
16516 { { "sip", "notify", NULL }, sip_notify, "Send a notify packet to a SIP peer", notify_usage, complete_sipnotify },
16517 { { "sip", "show", "objects", NULL }, sip_show_objects, "Show all SIP object allocations", show_objects_usage },
16518 { { "sip", "show", "users", NULL }, sip_show_users, "Show defined SIP users", show_users_usage },
16519 { { "sip", "show", "user", NULL }, sip_show_user, "Show details on specific SIP user", show_user_usage, complete_sip_show_user },
16520 { { "sip", "show", "subscriptions", NULL }, sip_show_subscriptions, "Show active SIP subscriptions", show_subscriptions_usage},
16521 { { "sip", "show", "channels", NULL }, sip_show_channels, "Show active SIP channels", show_channels_usage},
16522 { { "sip", "show", "channel", NULL }, sip_show_channel, "Show detailed SIP channel info", show_channel_usage, complete_sipch },
16523 { { "sip", "show", "history", NULL }, sip_show_history, "Show SIP dialog history", show_history_usage, complete_sipch },
16524 { { "sip", "show", "domains", NULL }, sip_show_domains, "List our local SIP domains.", show_domains_usage },
16525 { { "sip", "show", "settings", NULL }, sip_show_settings, "Show SIP global settings", show_settings_usage },
16526 { { "sip", "debug", NULL }, sip_do_debug, "Enable SIP debugging", debug_usage },
16527 { { "sip", "debug", "ip", NULL }, sip_do_debug, "Enable SIP debugging on IP", debug_usage },
16528 { { "sip", "debug", "peer", NULL }, sip_do_debug, "Enable SIP debugging on Peername", debug_usage, complete_sip_debug_peer },
16529 { { "sip", "show", "peer", NULL }, sip_show_peer, "Show details on specific SIP peer", show_peer_usage, complete_sip_show_peer },
16530 { { "sip", "show", "peers", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage },
16531 { { "sip", "prune", "realtime", NULL }, sip_prune_realtime,
16532 "Prune cached Realtime object(s)", prune_realtime_usage },
16533 { { "sip", "prune", "realtime", "peer", NULL }, sip_prune_realtime,
16534 "Prune cached Realtime peer(s)", prune_realtime_usage, complete_sip_prune_realtime_peer },
16535 { { "sip", "prune", "realtime", "user", NULL }, sip_prune_realtime,
16536 "Prune cached Realtime user(s)", prune_realtime_usage, complete_sip_prune_realtime_user },
16537 { { "sip", "show", "inuse", NULL }, sip_show_inuse, "List all inuse/limits", show_inuse_usage },
16538 { { "sip", "show", "registry", NULL }, sip_show_registry, "Show SIP registration status", show_reg_usage },
16539 { { "sip", "history", NULL }, sip_do_history, "Enable SIP history", history_usage },
16540 { { "sip", "no", "history", NULL }, sip_no_history, "Disable SIP history", no_history_usage },
16541 { { "sip", "no", "debug", NULL }, sip_no_debug, "Disable SIP debugging", no_debug_usage },
16542 { { "sip", "reload", NULL }, sip_reload, "Reload SIP configuration", sip_reload_usage },
16545 /*! \brief load_module: PBX load module - initialization */
16546 static int load_module(void)
16548 ASTOBJ_CONTAINER_INIT(&userl); /* User object list */
16549 ASTOBJ_CONTAINER_INIT(&peerl); /* Peer object list */
16550 ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list */
16552 sched = sched_context_create();
16553 if (!sched) {
16554 ast_log(LOG_WARNING, "Unable to create schedule context\n");
16557 io = io_context_create();
16558 if (!io) {
16559 ast_log(LOG_WARNING, "Unable to create I/O context\n");
16561 sip_reloadreason = CHANNEL_MODULE_LOAD;
16562 if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
16563 return AST_MODULE_LOAD_DECLINE;
16564 /* Make sure we can register our sip channel type */
16565 if (ast_channel_register(&sip_tech)) {
16566 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
16567 return -1;
16570 /* Register all CLI functions for SIP */
16571 ast_cli_register_multiple(my_clis, sizeof(my_clis)/ sizeof(my_clis[0]));
16573 /* Tell the RTP subdriver that we're here */
16574 ast_rtp_proto_register(&sip_rtp);
16576 /* Tell the UDPTL subdriver that we're here */
16577 ast_udptl_proto_register(&sip_udptl);
16579 /* Register dialplan applications */
16580 ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
16581 ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
16583 /* Register dialplan functions */
16584 ast_custom_function_register(&sip_header_function);
16585 ast_custom_function_register(&sippeer_function);
16586 ast_custom_function_register(&sipchaninfo_function);
16587 ast_custom_function_register(&checksipdomain_function);
16589 /* Register manager commands */
16590 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM, manager_sip_show_peers,
16591 "List SIP peers (text format)", mandescr_show_peers);
16592 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM, manager_sip_show_peer,
16593 "Show SIP peer (text format)", mandescr_show_peer);
16595 sip_poke_all_peers();
16596 sip_send_all_registers();
16598 /* And start the monitor for the first time */
16599 restart_monitor();
16601 return 0;
16604 static int unload_module(void)
16606 struct sip_pvt *p, *pl;
16608 /* First, take us out of the channel type list */
16609 ast_channel_unregister(&sip_tech);
16611 ast_custom_function_unregister(&sipchaninfo_function);
16612 ast_custom_function_unregister(&sippeer_function);
16613 ast_custom_function_unregister(&sip_header_function);
16614 ast_custom_function_unregister(&checksipdomain_function);
16616 ast_unregister_application(app_dtmfmode);
16617 ast_unregister_application(app_sipaddheader);
16619 ast_cli_unregister_multiple(my_clis, sizeof(my_clis) / sizeof(my_clis[0]));
16621 ast_rtp_proto_unregister(&sip_rtp);
16623 ast_udptl_proto_unregister(&sip_udptl);
16625 ast_manager_unregister("SIPpeers");
16626 ast_manager_unregister("SIPshowpeer");
16628 ast_mutex_lock(&iflock);
16629 /* Hangup all interfaces if they have an owner */
16630 for (p = iflist; p ; p = p->next) {
16631 if (p->owner)
16632 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
16634 ast_mutex_unlock(&iflock);
16636 ast_mutex_lock(&monlock);
16637 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
16638 pthread_cancel(monitor_thread);
16639 pthread_kill(monitor_thread, SIGURG);
16640 pthread_join(monitor_thread, NULL);
16642 monitor_thread = AST_PTHREADT_STOP;
16643 ast_mutex_unlock(&monlock);
16645 ast_mutex_lock(&iflock);
16646 /* Destroy all the interfaces and free their memory */
16647 p = iflist;
16648 while (p) {
16649 pl = p;
16650 p = p->next;
16651 /* Free associated memory */
16652 ast_mutex_destroy(&pl->lock);
16653 if (pl->chanvars) {
16654 ast_variables_destroy(pl->chanvars);
16655 pl->chanvars = NULL;
16657 free(pl);
16659 iflist = NULL;
16660 ast_mutex_unlock(&iflock);
16662 /* Free memory for local network address mask */
16663 ast_free_ha(localaddr);
16665 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
16666 ASTOBJ_CONTAINER_DESTROY(&userl);
16667 ASTOBJ_CONTAINER_DESTROYALL(&peerl, sip_destroy_peer);
16668 ASTOBJ_CONTAINER_DESTROY(&peerl);
16669 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
16670 ASTOBJ_CONTAINER_DESTROY(&regl);
16672 clear_realm_authentication(authl);
16673 clear_sip_domains();
16674 close(sipsock);
16675 sched_context_destroy(sched);
16677 return 0;
16680 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
16681 .load = load_module,
16682 .unload = unload_module,
16683 .reload = reload,