remove documentation of 'global' section in modules.conf, since it is no longer neede...
[asterisk-bristuff.git] / channels / chan_sip.c
blob7703530b88709ae4c42801ee3bc0a6f47da44226
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
87 #include "asterisk.h"
89 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
91 #include <stdio.h>
92 #include <ctype.h>
93 #include <string.h>
94 #include <unistd.h>
95 #include <sys/socket.h>
96 #include <sys/ioctl.h>
97 #include <net/if.h>
98 #include <errno.h>
99 #include <stdlib.h>
100 #include <fcntl.h>
101 #include <netdb.h>
102 #include <signal.h>
103 #include <sys/signal.h>
104 #include <netinet/in.h>
105 #include <netinet/in_systm.h>
106 #include <arpa/inet.h>
107 #include <netinet/ip.h>
108 #include <regex.h>
110 #include "asterisk/lock.h"
111 #include "asterisk/channel.h"
112 #include "asterisk/config.h"
113 #include "asterisk/logger.h"
114 #include "asterisk/module.h"
115 #include "asterisk/pbx.h"
116 #include "asterisk/options.h"
117 #include "asterisk/lock.h"
118 #include "asterisk/sched.h"
119 #include "asterisk/io.h"
120 #include "asterisk/rtp.h"
121 #include "asterisk/udptl.h"
122 #include "asterisk/acl.h"
123 #include "asterisk/manager.h"
124 #include "asterisk/callerid.h"
125 #include "asterisk/cli.h"
126 #include "asterisk/app.h"
127 #include "asterisk/musiconhold.h"
128 #include "asterisk/dsp.h"
129 #include "asterisk/features.h"
130 #include "asterisk/acl.h"
131 #include "asterisk/srv.h"
132 #include "asterisk/astdb.h"
133 #include "asterisk/causes.h"
134 #include "asterisk/utils.h"
135 #include "asterisk/file.h"
136 #include "asterisk/astobj.h"
137 #include "asterisk/dnsmgr.h"
138 #include "asterisk/devicestate.h"
139 #include "asterisk/linkedlists.h"
140 #include "asterisk/stringfields.h"
141 #include "asterisk/monitor.h"
142 #include "asterisk/localtime.h"
143 #include "asterisk/abstract_jb.h"
144 #include "asterisk/compiler.h"
146 #ifndef FALSE
147 #define FALSE 0
148 #endif
150 #ifndef TRUE
151 #define TRUE 1
152 #endif
154 #define VIDEO_CODEC_MASK 0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
155 #ifndef IPTOS_MINCOST
156 #define IPTOS_MINCOST 0x02
157 #endif
159 /* #define VOCAL_DATA_HACK */
161 #define DEFAULT_DEFAULT_EXPIRY 120
162 #define DEFAULT_MIN_EXPIRY 60
163 #define DEFAULT_MAX_EXPIRY 3600
164 #define DEFAULT_REGISTRATION_TIMEOUT 20
165 #define DEFAULT_MAX_FORWARDS "70"
167 /* guard limit must be larger than guard secs */
168 /* guard min must be < 1000, and should be >= 250 */
169 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
170 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
171 EXPIRY_GUARD_SECS */
172 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
173 GUARD_PCT turns out to be lower than this, it
174 will use this time instead.
175 This is in milliseconds. */
176 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
177 below EXPIRY_GUARD_LIMIT */
178 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
180 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
181 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
182 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
183 static int expiry = DEFAULT_EXPIRY;
185 #ifndef MAX
186 #define MAX(a,b) ((a) > (b) ? (a) : (b))
187 #endif
189 #define CALLERID_UNKNOWN "Unknown"
191 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
192 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
193 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
195 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
196 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
197 #define SIP_TRANS_TIMEOUT 32000 /*!< SIP request timeout (rfc 3261) 64*T1
198 \todo Use known T1 for timeout (peerpoke)
200 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
202 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
203 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
204 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
206 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
208 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
209 static struct ast_jb_conf default_jbconf =
211 .flags = 0,
212 .max_size = -1,
213 .resync_threshold = -1,
214 .impl = ""
216 static struct ast_jb_conf global_jbconf;
218 static const char config[] = "sip.conf";
219 static const char notify_config[] = "sip_notify.conf";
220 static int usecnt = 0;
223 #define RTP 1
224 #define NO_RTP 0
226 /*! \brief Authorization scheme for call transfers
227 \note Not a bitfield flag, since there are plans for other modes,
228 like "only allow transfers for authenticated devices" */
229 enum transfermodes {
230 TRANSFER_OPENFORALL, /*!< Allow all SIP transfers */
231 TRANSFER_CLOSED, /*!< Allow no SIP transfers */
235 enum sip_result {
236 AST_SUCCESS = 0,
237 AST_FAILURE = -1,
240 /* Do _NOT_ make any changes to this enum, or the array following it;
241 if you think you are doing the right thing, you are probably
242 not doing the right thing. If you think there are changes
243 needed, get someone else to review them first _before_
244 submitting a patch. If these two lists do not match properly
245 bad things will happen.
248 enum xmittype {
249 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
250 If it fails, it's critical and will cause a teardown of the session */
251 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
252 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
255 enum parse_register_result {
256 PARSE_REGISTER_FAILED,
257 PARSE_REGISTER_UPDATE,
258 PARSE_REGISTER_QUERY,
261 enum subscriptiontype {
262 NONE = 0,
263 TIMEOUT,
264 XPIDF_XML,
265 DIALOG_INFO_XML,
266 CPIM_PIDF_XML,
267 PIDF_XML,
268 MWI_NOTIFICATION
271 static const struct cfsubscription_types {
272 enum subscriptiontype type;
273 const char * const event;
274 const char * const mediatype;
275 const char * const text;
276 } subscription_types[] = {
277 { NONE, "-", "unknown", "unknown" },
278 /* RFC 4235: SIP Dialog event package */
279 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
280 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
281 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
282 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
283 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
286 /*! \brief SIP Request methods known by Asterisk */
287 enum sipmethod {
288 SIP_UNKNOWN, /* Unknown response */
289 SIP_RESPONSE, /* Not request, response to outbound request */
290 SIP_REGISTER,
291 SIP_OPTIONS,
292 SIP_NOTIFY,
293 SIP_INVITE,
294 SIP_ACK,
295 SIP_PRACK, /* Not supported at all */
296 SIP_BYE,
297 SIP_REFER,
298 SIP_SUBSCRIBE,
299 SIP_MESSAGE,
300 SIP_UPDATE, /* We can send UPDATE; but not accept it */
301 SIP_INFO,
302 SIP_CANCEL,
303 SIP_PUBLISH, /* Not supported at all */
306 /*! \brief Authentication types - proxy or www authentication
307 \note Endpoints, like Asterisk, should always use WWW authentication to
308 allow multiple authentications in the same call - to the proxy and
309 to the end point.
311 enum sip_auth_type {
312 PROXY_AUTH,
313 WWW_AUTH,
316 /*! \brief Authentication result from check_auth* functions */
317 enum check_auth_result {
318 AUTH_SUCCESSFUL = 0,
319 AUTH_CHALLENGE_SENT = 1,
320 AUTH_SECRET_FAILED = -1,
321 AUTH_USERNAME_MISMATCH = -2,
322 AUTH_NOT_FOUND = -3,
323 AUTH_FAKE_AUTH = -4,
324 AUTH_UNKNOWN_DOMAIN = -5,
327 /* States for outbound registrations (with register= lines in sip.conf */
328 enum sipregistrystate {
329 REG_STATE_UNREGISTERED = 0, /*!< We are not registred */
330 REG_STATE_REGSENT, /*!< Registration request sent */
331 REG_STATE_AUTHSENT, /*!< We have tried to authenticate */
332 REG_STATE_REGISTERED, /*!< Registred and done */
333 REG_STATE_REJECTED, /*!< Registration rejected */
334 REG_STATE_TIMEOUT, /*!< Registration timed out */
335 REG_STATE_NOAUTH, /*!< We have no accepted credentials */
336 REG_STATE_FAILED, /*!< Registration failed after several tries */
340 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
341 static const struct cfsip_methods {
342 enum sipmethod id;
343 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
344 char * const text;
345 } sip_methods[] = {
346 { SIP_UNKNOWN, RTP, "-UNKNOWN-" },
347 { SIP_RESPONSE, NO_RTP, "SIP/2.0" },
348 { SIP_REGISTER, NO_RTP, "REGISTER" },
349 { SIP_OPTIONS, NO_RTP, "OPTIONS" },
350 { SIP_NOTIFY, NO_RTP, "NOTIFY" },
351 { SIP_INVITE, RTP, "INVITE" },
352 { SIP_ACK, NO_RTP, "ACK" },
353 { SIP_PRACK, NO_RTP, "PRACK" },
354 { SIP_BYE, NO_RTP, "BYE" },
355 { SIP_REFER, NO_RTP, "REFER" },
356 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE" },
357 { SIP_MESSAGE, NO_RTP, "MESSAGE" },
358 { SIP_UPDATE, NO_RTP, "UPDATE" },
359 { SIP_INFO, NO_RTP, "INFO" },
360 { SIP_CANCEL, NO_RTP, "CANCEL" },
361 { SIP_PUBLISH, NO_RTP, "PUBLISH" }
364 /*! Define SIP option tags, used in Require: and Supported: headers
365 We need to be aware of these properties in the phones to use
366 the replace: header. We should not do that without knowing
367 that the other end supports it...
368 This is nothing we can configure, we learn by the dialog
369 Supported: header on the REGISTER (peer) or the INVITE
370 (other devices)
371 We are not using many of these today, but will in the future.
372 This is documented in RFC 3261
374 #define SUPPORTED 1
375 #define NOT_SUPPORTED 0
377 #define SIP_OPT_REPLACES (1 << 0)
378 #define SIP_OPT_100REL (1 << 1)
379 #define SIP_OPT_TIMER (1 << 2)
380 #define SIP_OPT_EARLY_SESSION (1 << 3)
381 #define SIP_OPT_JOIN (1 << 4)
382 #define SIP_OPT_PATH (1 << 5)
383 #define SIP_OPT_PREF (1 << 6)
384 #define SIP_OPT_PRECONDITION (1 << 7)
385 #define SIP_OPT_PRIVACY (1 << 8)
386 #define SIP_OPT_SDP_ANAT (1 << 9)
387 #define SIP_OPT_SEC_AGREE (1 << 10)
388 #define SIP_OPT_EVENTLIST (1 << 11)
389 #define SIP_OPT_GRUU (1 << 12)
390 #define SIP_OPT_TARGET_DIALOG (1 << 13)
391 #define SIP_OPT_NOREFERSUB (1 << 14)
392 #define SIP_OPT_HISTINFO (1 << 15)
393 #define SIP_OPT_RESPRIORITY (1 << 16)
395 /*! \brief List of well-known SIP options. If we get this in a require,
396 we should check the list and answer accordingly. */
397 static const struct cfsip_options {
398 int id; /*!< Bitmap ID */
399 int supported; /*!< Supported by Asterisk ? */
400 char * const text; /*!< Text id, as in standard */
401 } sip_options[] = { /* XXX used in 3 places */
402 /* RFC3891: Replaces: header for transfer */
403 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
404 /* One version of Polycom firmware has the wrong label */
405 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
406 /* RFC3262: PRACK 100% reliability */
407 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
408 /* RFC4028: SIP Session Timers */
409 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
410 /* RFC3959: SIP Early session support */
411 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
412 /* RFC3911: SIP Join header support */
413 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
414 /* RFC3327: Path support */
415 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
416 /* RFC3840: Callee preferences */
417 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
418 /* RFC3312: Precondition support */
419 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
420 /* RFC3323: Privacy with proxies*/
421 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
422 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
423 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
424 /* RFC3329: Security agreement mechanism */
425 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
426 /* SIMPLE events: draft-ietf-simple-event-list-07.txt */
427 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
428 /* GRUU: Globally Routable User Agent URI's */
429 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
430 /* Target-dialog: draft-ietf-sip-target-dialog-03.txt */
431 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
432 /* Disable the REFER subscription, RFC 4488 */
433 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
434 /* ietf-sip-history-info-06.txt */
435 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
436 /* ietf-sip-resource-priority-10.txt */
437 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
441 /*! \brief SIP Methods we support */
442 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
444 /*! \brief SIP Extensions we support */
445 #define SUPPORTED_EXTENSIONS "replaces"
448 /* Default values, set and reset in reload_config before reading configuration */
449 /* These are default values in the source. There are other recommended values in the
450 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
451 yet encouraging new behaviour on new installations
453 #define DEFAULT_SIP_PORT 5060 /*!< From RFC 3261 (former 2543) */
454 #define DEFAULT_CONTEXT "default"
455 #define DEFAULT_MOHINTERPRET "default"
456 #define DEFAULT_MOHSUGGEST ""
457 #define DEFAULT_VMEXTEN "asterisk"
458 #define DEFAULT_CALLERID "asterisk"
459 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
460 #define DEFAULT_MWITIME 10
461 #define DEFAULT_ALLOWGUEST TRUE
462 #define DEFAULT_SRVLOOKUP FALSE /*!< Recommended setting is ON */
463 #define DEFAULT_COMPACTHEADERS FALSE
464 #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. */
465 #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. */
466 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
467 #define DEFAULT_ALLOW_EXT_DOM TRUE
468 #define DEFAULT_REALM "asterisk"
469 #define DEFAULT_NOTIFYRINGING TRUE
470 #define DEFAULT_PEDANTIC FALSE
471 #define DEFAULT_AUTOCREATEPEER FALSE
472 #define DEFAULT_QUALIFY FALSE
473 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
474 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
475 #ifndef DEFAULT_USERAGENT
476 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
477 #endif
480 /* Default setttings are used as a channel setting and as a default when
481 configuring devices */
482 static char default_context[AST_MAX_CONTEXT];
483 static char default_subscribecontext[AST_MAX_CONTEXT];
484 static char default_language[MAX_LANGUAGE];
485 static char default_callerid[AST_MAX_EXTENSION];
486 static char default_fromdomain[AST_MAX_EXTENSION];
487 static char default_notifymime[AST_MAX_EXTENSION];
488 static int default_qualify; /*!< Default Qualify= setting */
489 static char default_vmexten[AST_MAX_EXTENSION];
490 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
491 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
492 * a bridged channel on hold */
493 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
494 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
496 /* Global settings only apply to the channel */
497 static int global_rtautoclear;
498 static int global_notifyringing; /*!< Send notifications on ringing */
499 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
500 static int srvlookup; /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
501 static int pedanticsipchecking; /*!< Extra checking ? Default off */
502 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
503 static int global_relaxdtmf; /*!< Relax DTMF */
504 static int global_rtptimeout; /*!< Time out call if no RTP */
505 static int global_rtpholdtimeout;
506 static int global_rtpkeepalive; /*!< Send RTP keepalives */
507 static int global_reg_timeout;
508 static int global_regattempts_max; /*!< Registration attempts before giving up */
509 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
510 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
511 the global setting is in globals_flags[1] */
512 static int global_mwitime; /*!< Time between MWI checks for peers */
513 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
514 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
515 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
516 static int compactheaders; /*!< send compact sip headers */
517 static int recordhistory; /*!< Record SIP history. Off by default */
518 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
519 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
520 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
521 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
522 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
523 static int global_callevents; /*!< Whether we send manager events or not */
524 static int global_t1min; /*!< T1 roundtrip time minimum */
525 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
527 /*! \brief Codecs that we support by default: */
528 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
529 static int noncodeccapability = AST_RTP_DTMF;
531 /* Object counters */
532 static int suserobjs = 0; /*!< Static users */
533 static int ruserobjs = 0; /*!< Realtime users */
534 static int speerobjs = 0; /*!< Statis peers */
535 static int rpeerobjs = 0; /*!< Realtime peers */
536 static int apeerobjs = 0; /*!< Autocreated peer objects */
537 static int regobjs = 0; /*!< Registry objects */
539 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
541 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
542 AST_MUTEX_DEFINE_STATIC(iflock);
544 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
545 when it's doing something critical. */
546 AST_MUTEX_DEFINE_STATIC(netlock);
548 AST_MUTEX_DEFINE_STATIC(monlock);
550 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
552 /*! \brief This is the thread for the monitor which checks for input on the channels
553 which are not currently in use. */
554 static pthread_t monitor_thread = AST_PTHREADT_NULL;
556 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
557 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
559 static struct sched_context *sched; /*!< The scheduling context */
560 static struct io_context *io; /*!< The IO context */
562 #define DEC_CALL_LIMIT 0
563 #define INC_CALL_LIMIT 1
564 #define DEC_CALL_RINGING 2
565 #define INC_CALL_RINGING 3
567 /*! \brief sip_request: The data grabbed from the UDP socket */
568 struct sip_request {
569 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
570 char *rlPart2; /*!< The Request URI or Response Status */
571 int len; /*!< Length */
572 int headers; /*!< # of SIP Headers */
573 int method; /*!< Method of this request */
574 int lines; /*!< Body Content */
575 unsigned int flags; /*!< SIP_PKT Flags for this packet */
576 char *header[SIP_MAX_HEADERS];
577 char *line[SIP_MAX_LINES];
578 char data[SIP_MAX_PACKET];
579 unsigned int sdp_start; /*!< the line number where the SDP begins */
580 unsigned int sdp_end; /*!< the line number where the SDP ends */
584 * A sip packet is stored into the data[] buffer, with the header followed
585 * by an empty line and the body of the message.
586 * On outgoing packets, data is accumulated in data[] with len reflecting
587 * the next available byte, headers and lines count the number of lines
588 * in both parts. There are no '\0' in data[0..len-1].
590 * On received packet, the input read from the socket is copied into data[],
591 * len is set and the string is NUL-terminated. Then a parser fills up
592 * the other fields -header[] and line[] to point to the lines of the
593 * message, rlPart1 and rlPart2 parse the first lnie as below:
595 * Requests have in the first line METHOD URI SIP/2.0
596 * rlPart1 = method; rlPart2 = uri;
597 * Responses have in the first line SIP/2.0 code description
598 * rlPart1 = SIP/2.0; rlPart2 = code + description;
602 /*! \brief structure used in transfers */
603 struct sip_dual {
604 struct ast_channel *chan1; /*!< First channel involved */
605 struct ast_channel *chan2; /*!< Second channel involved */
606 struct sip_request req; /*!< Request that caused the transfer (REFER) */
607 int seqno; /*!< Sequence number */
610 struct sip_pkt;
612 /*! \brief Parameters to the transmit_invite function */
613 struct sip_invite_param {
614 const char *distinctive_ring; /*!< Distinctive ring header */
615 int addsipheaders; /*!< Add extra SIP headers */
616 const char *uri_options; /*!< URI options to add to the URI */
617 const char *vxml_url; /*!< VXML url for Cisco phones */
618 char *auth; /*!< Authentication */
619 char *authheader; /*!< Auth header */
620 enum sip_auth_type auth_type; /*!< Authentication type */
621 const char *replaces; /*!< Replaces header for call transfers */
622 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
625 /*! \brief Structure to save routing information for a SIP session */
626 struct sip_route {
627 struct sip_route *next;
628 char hop[0];
631 /*! \brief Modes for SIP domain handling in the PBX */
632 enum domain_mode {
633 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
634 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
637 struct domain {
638 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
639 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
640 enum domain_mode mode; /*!< How did we find this domain? */
641 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
644 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
647 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
648 struct sip_history {
649 AST_LIST_ENTRY(sip_history) list;
650 char event[0]; /* actually more, depending on needs */
653 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
655 /*! \brief sip_auth: Creadentials for authentication to other SIP services */
656 struct sip_auth {
657 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
658 char username[256]; /*!< Username */
659 char secret[256]; /*!< Secret */
660 char md5secret[256]; /*!< MD5Secret */
661 struct sip_auth *next; /*!< Next auth structure in list */
664 /*--- Various flags for the flags field in the pvt structure */
665 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
666 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed by the monitor thread */
667 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
668 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
669 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
670 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
671 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
672 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
673 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
674 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
675 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
676 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
677 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
678 #define SIP_OUTGOING (1 << 13) /*!< Is this an outgoing call? */
679 #define SIP_CAN_BYE (1 << 14) /*!< Can we send BYE on this dialog? */
680 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 15) /*!< Do not hangup at first ast_hangup */
681 #define SIP_DTMF (3 << 16) /*!< DTMF Support: four settings, uses two bits */
682 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DTMF Support: RTP DTMF - "rfc2833" */
683 #define SIP_DTMF_INBAND (1 << 16) /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
684 #define SIP_DTMF_INFO (2 << 16) /*!< DTMF Support: SIP Info messages - "info" */
685 #define SIP_DTMF_AUTO (3 << 16) /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
686 /* NAT settings */
687 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
688 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
689 #define SIP_NAT_RFC3581 (1 << 18) /*!< NAT RFC3581 */
690 #define SIP_NAT_ROUTE (2 << 18) /*!< NAT Only ROUTE */
691 #define SIP_NAT_ALWAYS (3 << 18) /*!< NAT Both ROUTE and RFC3581 */
692 /* re-INVITE related settings */
693 #define SIP_REINVITE (7 << 20) /*!< three bits used */
694 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
695 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< allow media reinvite when new peer is behind NAT */
696 #define SIP_REINVITE_UPDATE (4 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
697 /* "insecure" settings */
698 #define SIP_INSECURE_PORT (1 << 23) /*!< don't require matching port for incoming requests */
699 #define SIP_INSECURE_INVITE (1 << 24) /*!< don't require authentication for incoming INVITEs */
700 /* Sending PROGRESS in-band settings */
701 #define SIP_PROG_INBAND (3 << 25) /*!< three settings, uses two bits */
702 #define SIP_PROG_INBAND_NEVER (0 << 25)
703 #define SIP_PROG_INBAND_NO (1 << 25)
704 #define SIP_PROG_INBAND_YES (2 << 25)
705 #define SIP_FREE_BIT (1 << 27) /*!< Undefined bit - not in use */
706 #define SIP_CALL_LIMIT (1 << 28) /*!< Call limit enforced for this call */
707 #define SIP_SENDRPID (1 << 29) /*!< Remote Party-ID Support */
708 #define SIP_INC_COUNT (1 << 30) /*!< Did this connection increment the counter of in-use calls? */
709 #define SIP_G726_NONSTANDARD (1 << 31) /*!< Use non-standard packing for G726-32 data */
711 #define SIP_FLAGS_TO_COPY \
712 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
713 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
714 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
716 /* a new page of flags */
717 /* realtime flags */
718 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
719 #define SIP_PAGE2_RTUPDATE (1 << 1)
720 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
721 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
722 #define SIP_PAGE2_RTSAVE_SYSNAME (1 << 5)
723 /* Space for addition of other realtime flags in the future */
724 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 10)
725 #define SIP_PAGE2_DEBUG (3 << 11)
726 #define SIP_PAGE2_DEBUG_CONFIG (1 << 11)
727 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 12)
728 #define SIP_PAGE2_DYNAMIC (1 << 13) /*!< Dynamic Peers register with Asterisk */
729 #define SIP_PAGE2_SELFDESTRUCT (1 << 14) /*!< Automatic peers need to destruct themselves */
730 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15)
731 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< Allow subscriptions from this peer? */
732 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< Allow overlap dialing ? */
733 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< Only issue MWI notification if subscribed to */
734 #define SIP_PAGE2_INC_RINGING (1 << 19) /*!< Did this connection increment the counter of in-use calls? */
735 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< T38 Fax Passthrough Support */
736 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< 20: T38 Fax Passthrough Support */
737 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< 21: T38 Fax Passthrough Support */
738 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< 22: T38 Fax Passthrough Support */
739 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< Call states */
740 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (1 << 23) /*!< 23: One directional hold */
741 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (2 << 24) /*!< 24: Inactive */
743 #define SIP_PAGE2_FLAGS_TO_COPY \
744 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT)
746 /* SIP packet flags */
747 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
748 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
749 #define SIP_PKT_IGNORE (1 << 2) /*!< This is a re-transmit, ignore it */
750 #define SIP_PKT_IGNORE_RESP (1 << 3) /*!< Resp ignore - ??? */
751 #define SIP_PKT_IGNORE_REQ (1 << 4) /*!< Req ignore - ??? */
753 /* T.38 set of flags */
754 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
755 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
756 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
757 /* Rate management */
758 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
759 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
760 /* UDP Error correction */
761 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
762 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
763 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
764 /* T38 Spec version */
765 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
766 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
767 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
768 /* Maximum Fax Rate */
769 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
770 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
771 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
772 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
773 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
774 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
776 /*!< This is default: NO MMR and JBIG trancoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
777 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
779 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
780 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
781 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
783 /*! \brief T38 States for a call */
784 enum t38state {
785 T38_DISABLED = 0, /*! Not enabled */
786 T38_LOCAL_DIRECT, /*! Offered from local */
787 T38_LOCAL_REINVITE, /*! Offered from local - REINVITE */
788 T38_PEER_DIRECT, /*! Offered from peer */
789 T38_PEER_REINVITE, /*! Offered from peer - REINVITE */
790 T38_ENABLED /*! Negotiated (enabled) */
793 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
794 struct t38properties {
795 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
796 int capability; /*!< Our T38 capability */
797 int peercapability; /*!< Peers T38 capability */
798 int jointcapability; /*!< Supported T38 capability at both ends */
799 enum t38state state; /*!< T.38 state */
802 /*! \brief Parameters to know status of transfer */
803 enum referstatus {
804 REFER_IDLE, /*!< No REFER is in progress */
805 REFER_SENT, /*!< Sent REFER to transferee */
806 REFER_RECEIVED, /*!< Received REFER from transferer */
807 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING */
808 REFER_ACCEPTED, /*!< Accepted by transferee */
809 REFER_RINGING, /*!< Target Ringing */
810 REFER_200OK, /*!< Answered by transfer target */
811 REFER_FAILED, /*!< REFER declined - go on */
812 REFER_NOAUTH /*!< We had no auth for REFER */
815 static const struct c_referstatusstring {
816 enum referstatus status;
817 char *text;
818 } referstatusstrings[] = {
819 { REFER_IDLE, "<none>" },
820 { REFER_SENT, "Request sent" },
821 { REFER_RECEIVED, "Request received" },
822 { REFER_ACCEPTED, "Accepted" },
823 { REFER_RINGING, "Target ringing" },
824 { REFER_200OK, "Done" },
825 { REFER_FAILED, "Failed" },
826 { REFER_NOAUTH, "Failed - auth failure" }
829 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed */
830 /* OEJ: Should be moved to string fields */
831 struct sip_refer {
832 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
833 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
834 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
835 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
836 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
837 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
838 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
839 char replaces_callid[BUFSIZ]; /*!< Replace info: callid */
840 char replaces_callid_totag[BUFSIZ/2]; /*!< Replace info: to-tag */
841 char replaces_callid_fromtag[BUFSIZ/2]; /*!< Replace info: from-tag */
842 struct sip_pvt *refer_call; /*!< Call we are referring */
843 int attendedtransfer; /*!< Attended or blind transfer? */
844 int localtransfer; /*!< Transfer to local domain? */
845 enum referstatus status; /*!< REFER status */
848 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
849 static struct sip_pvt {
850 ast_mutex_t lock; /*!< Dialog private lock */
851 int method; /*!< SIP method that opened this dialog */
852 AST_DECLARE_STRING_FIELDS(
853 AST_STRING_FIELD(callid); /*!< Global CallID */
854 AST_STRING_FIELD(randdata); /*!< Random data */
855 AST_STRING_FIELD(accountcode); /*!< Account code */
856 AST_STRING_FIELD(realm); /*!< Authorization realm */
857 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
858 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
859 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
860 AST_STRING_FIELD(domain); /*!< Authorization domain */
861 AST_STRING_FIELD(from); /*!< The From: header */
862 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
863 AST_STRING_FIELD(exten); /*!< Extension where to start */
864 AST_STRING_FIELD(context); /*!< Context for this call */
865 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
866 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
867 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
868 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
869 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
870 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
871 AST_STRING_FIELD(language); /*!< Default language for this call */
872 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
873 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
874 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
875 AST_STRING_FIELD(theirtag); /*!< Their tag */
876 AST_STRING_FIELD(username); /*!< [user] name */
877 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
878 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
879 AST_STRING_FIELD(uri); /*!< Original requested URI */
880 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
881 AST_STRING_FIELD(peersecret); /*!< Password */
882 AST_STRING_FIELD(peermd5secret);
883 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
884 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
885 AST_STRING_FIELD(via); /*!< Via: header */
886 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
887 AST_STRING_FIELD(our_contact); /*!< Our contact header */
888 AST_STRING_FIELD(rpid); /*!< Our RPID header */
889 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
891 unsigned int ocseq; /*!< Current outgoing seqno */
892 unsigned int icseq; /*!< Current incoming seqno */
893 ast_group_t callgroup; /*!< Call group */
894 ast_group_t pickupgroup; /*!< Pickup group */
895 int lastinvite; /*!< Last Cseq of invite */
896 struct ast_flags flags[2]; /*!< SIP_ flags */
897 int timer_t1; /*!< SIP timer T1, ms rtt */
898 unsigned int sipoptions; /*!< Supported SIP options on the other end */
899 struct ast_codec_pref prefs; /*!< codec prefs */
900 int capability; /*!< Special capability (codec) */
901 int jointcapability; /*!< Supported capability at both ends (codecs ) */
902 int peercapability; /*!< Supported peer capability */
903 int prefcodec; /*!< Preferred codec (outbound only) */
904 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
905 int redircodecs; /*!< Redirect codecs */
906 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
907 struct t38properties t38; /*!< T38 settings */
908 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
909 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
910 int callingpres; /*!< Calling presentation */
911 int authtries; /*!< Times we've tried to authenticate */
912 int expiry; /*!< How long we take to expire */
913 long branch; /*!< The branch identifier of this session */
914 char tag[11]; /*!< Our tag for this session */
915 int sessionid; /*!< SDP Session ID */
916 int sessionversion; /*!< SDP Session Version */
917 struct sockaddr_in sa; /*!< Our peer */
918 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
919 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
920 time_t lastrtprx; /*!< Last RTP received */
921 time_t lastrtptx; /*!< Last RTP sent */
922 int rtptimeout; /*!< RTP timeout time */
923 int rtpholdtimeout; /*!< RTP timeout when on hold */
924 int rtpkeepalive; /*!< Send RTP packets for keepalive */
925 struct sockaddr_in recv; /*!< Received as */
926 struct in_addr ourip; /*!< Our IP */
927 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
928 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
929 int route_persistant; /*!< Is this the "real" route? */
930 struct sip_auth *peerauth; /*!< Realm authentication */
931 int noncecount; /*!< Nonce-count */
932 char lastmsg[256]; /*!< Last Message sent/received */
933 int amaflags; /*!< AMA Flags */
934 int pendinginvite; /*!< Any pending invite ? (seqno of this) */
935 struct sip_request initreq; /*!< Initial request that opened the SIP dialog */
937 int maxtime; /*!< Max time for first response */
938 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
939 int autokillid; /*!< Auto-kill ID (scheduler) */
940 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
941 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
942 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
943 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
944 int laststate; /*!< SUBSCRIBE: Last known extension state */
945 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
947 struct ast_dsp *vad; /*!< Voice Activation Detection dsp */
949 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
950 Used in peerpoke, mwi subscriptions */
951 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
952 struct ast_rtp *rtp; /*!< RTP Session */
953 struct ast_rtp *vrtp; /*!< Video RTP session */
954 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
955 struct sip_history_head *history; /*!< History of this SIP dialog */
956 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
957 struct sip_pvt *next; /*!< Next dialog in chain */
958 struct sip_invite_param *options; /*!< Options for INVITE */
959 } *iflist = NULL;
961 #define FLAG_RESPONSE (1 << 0)
962 #define FLAG_FATAL (1 << 1)
964 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */
965 struct sip_pkt {
966 struct sip_pkt *next; /*!< Next packet in linked list */
967 int retrans; /*!< Retransmission number */
968 int method; /*!< SIP method for this packet */
969 int seqno; /*!< Sequence number */
970 unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */
971 struct sip_pvt *owner; /*!< Owner AST call */
972 int retransid; /*!< Retransmission ID */
973 int timer_a; /*!< SIP timer A, retransmission timer */
974 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
975 int packetlen; /*!< Length of packet */
976 char data[0];
979 /*! \brief Structure for SIP user data. User's place calls to us */
980 struct sip_user {
981 /* Users who can access various contexts */
982 ASTOBJ_COMPONENTS(struct sip_user);
983 char secret[80]; /*!< Password */
984 char md5secret[80]; /*!< Password in md5 */
985 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
986 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
987 char cid_num[80]; /*!< Caller ID num */
988 char cid_name[80]; /*!< Caller ID name */
989 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
990 char language[MAX_LANGUAGE]; /*!< Default language for this user */
991 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
992 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
993 char useragent[256]; /*!< User agent in SIP request */
994 struct ast_codec_pref prefs; /*!< codec prefs */
995 ast_group_t callgroup; /*!< Call group */
996 ast_group_t pickupgroup; /*!< Pickup Group */
997 unsigned int sipoptions; /*!< Supported SIP options */
998 struct ast_flags flags[2]; /*!< SIP_ flags */
999 int amaflags; /*!< AMA flags for billing */
1000 int callingpres; /*!< Calling id presentation */
1001 int capability; /*!< Codec capability */
1002 int inUse; /*!< Number of calls in use */
1003 int call_limit; /*!< Limit of concurrent calls */
1004 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1005 struct ast_ha *ha; /*!< ACL setting */
1006 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1007 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1010 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1011 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1012 struct sip_peer {
1013 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
1014 /*!< peer->name is the unique name of this object */
1015 char secret[80]; /*!< Password */
1016 char md5secret[80]; /*!< Password in MD5 */
1017 struct sip_auth *auth; /*!< Realm authentication list */
1018 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1019 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1020 char username[80]; /*!< Temporary username until registration */
1021 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1022 int amaflags; /*!< AMA Flags (for billing) */
1023 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1024 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1025 char fromuser[80]; /*!< From: user when calling this peer */
1026 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1027 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1028 char cid_num[80]; /*!< Caller ID num */
1029 char cid_name[80]; /*!< Caller ID name */
1030 int callingpres; /*!< Calling id presentation */
1031 int inUse; /*!< Number of calls in use */
1032 int inRinging; /*!< Number of calls ringing */
1033 int onHold; /*!< Peer has someone on hold */
1034 int call_limit; /*!< Limit of concurrent calls */
1035 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1036 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1037 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
1038 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1039 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1040 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1041 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1042 struct ast_codec_pref prefs; /*!< codec prefs */
1043 int lastmsgssent;
1044 time_t lastmsgcheck; /*!< Last time we checked for MWI */
1045 unsigned int sipoptions; /*!< Supported SIP options */
1046 struct ast_flags flags[2]; /*!< SIP_ flags */
1047 int expire; /*!< When to expire this peer registration */
1048 int capability; /*!< Codec capability */
1049 int rtptimeout; /*!< RTP timeout */
1050 int rtpholdtimeout; /*!< RTP Hold Timeout */
1051 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1052 ast_group_t callgroup; /*!< Call group */
1053 ast_group_t pickupgroup; /*!< Pickup group */
1054 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
1055 struct sockaddr_in addr; /*!< IP address of peer */
1056 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1058 /* Qualification */
1059 struct sip_pvt *call; /*!< Call pointer */
1060 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1061 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1062 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1063 struct timeval ps; /*!< Ping send time */
1065 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1066 struct ast_ha *ha; /*!< Access control list */
1067 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1068 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1069 int lastmsg;
1074 /*! \brief Registrations with other SIP proxies */
1075 struct sip_registry {
1076 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1077 AST_DECLARE_STRING_FIELDS(
1078 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1079 AST_STRING_FIELD(realm); /*!< Authorization realm */
1080 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1081 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1082 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1083 AST_STRING_FIELD(domain); /*!< Authorization domain */
1084 AST_STRING_FIELD(username); /*!< Who we are registering as */
1085 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1086 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1087 AST_STRING_FIELD(secret); /*!< Password in clear text */
1088 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1089 AST_STRING_FIELD(contact); /*!< Contact extension */
1090 AST_STRING_FIELD(random);
1092 int portno; /*!< Optional port override */
1093 int expire; /*!< Sched ID of expiration */
1094 int regattempts; /*!< Number of attempts (since the last success) */
1095 int timeout; /*!< sched id of sip_reg_timeout */
1096 int refresh; /*!< How often to refresh */
1097 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1098 enum sipregistrystate regstate; /*!< Registration state (see above) */
1099 time_t regtime; /*!< Last succesful registration time */
1100 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1101 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1102 struct sockaddr_in us; /*!< Who the server thinks we are */
1103 int noncecount; /*!< Nonce-count */
1104 char lastmsg[256]; /*!< Last Message sent/received */
1107 /* --- Linked lists of various objects --------*/
1109 /*! \brief The user list: Users and friends */
1110 static struct ast_user_list {
1111 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1112 } userl;
1114 /*! \brief The peer list: Peers and Friends */
1115 static struct ast_peer_list {
1116 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1117 } peerl;
1119 /*! \brief The register list: Other SIP proxys we register with and place calls to */
1120 static struct ast_register_list {
1121 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1122 int recheck;
1123 } regl;
1125 /*! \todo Move the sip_auth list to AST_LIST */
1126 static struct sip_auth *authl = NULL; /*!< Authentication list for realm authentication */
1129 /* --- Sockets and networking --------------*/
1130 static int sipsock = -1; /*!< Main socket for SIP network communication */
1131 static struct sockaddr_in bindaddr = { 0, }; /*!< The address we bind to */
1132 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1133 static char externhost[MAXHOSTNAMELEN]; /*!< External host name (possibly with dynamic DNS and DHCP */
1134 static time_t externexpire = 0; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1135 static int externrefresh = 10;
1136 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1137 static struct in_addr __ourip;
1138 static struct sockaddr_in outboundproxyip;
1139 static int ourport;
1140 static struct sockaddr_in debugaddr;
1142 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1144 /*---------------------------- Forward declarations of functions in chan_sip.c */
1145 /*! \note This is added to help splitting up chan_sip.c into several files
1146 in coming releases */
1148 /*--- PBX interface functions */
1149 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1150 static int sip_devicestate(void *data);
1151 static int sip_sendtext(struct ast_channel *ast, const char *text);
1152 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1153 static int sip_hangup(struct ast_channel *ast);
1154 static int sip_answer(struct ast_channel *ast);
1155 static struct ast_frame *sip_read(struct ast_channel *ast);
1156 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1157 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1158 static int sip_transfer(struct ast_channel *ast, const char *dest);
1159 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1160 static int sip_senddigit(struct ast_channel *ast, char digit);
1162 /*--- Transmitting responses and requests */
1163 static int sipsock_read(int *id, int fd, short events, void *ignore);
1164 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
1165 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
1166 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1167 static int retrans_pkt(void *data);
1168 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
1169 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1170 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1171 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1172 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1173 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1174 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);
1175 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1176 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1177 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1178 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1179 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1180 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
1181 static int transmit_info_with_digit(struct sip_pvt *p, const char digit);
1182 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1183 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1184 static int transmit_refer(struct sip_pvt *p, const char *dest);
1185 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1186 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1187 static int transmit_state_notify(struct sip_pvt *p, int state, int full);
1188 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1189 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1190 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1191 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1192 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1193 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1194 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1195 static int does_peer_need_mwi(struct sip_peer *peer);
1197 /*--- Dialog management */
1198 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1199 int useglobal_nat, const int intended_method);
1200 static int __sip_autodestruct(void *data);
1201 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1202 static void sip_cancel_destroy(struct sip_pvt *p);
1203 static void sip_destroy(struct sip_pvt *p);
1204 static void __sip_destroy(struct sip_pvt *p, int lockowner);
1205 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod, int reset);
1206 static void __sip_pretend_ack(struct sip_pvt *p);
1207 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1208 static int auto_congest(void *nothing);
1209 static int update_call_counter(struct sip_pvt *fup, int event);
1210 static int hangup_sip2cause(int cause);
1211 static const char *hangup_cause2sip(int cause);
1212 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1213 static void free_old_route(struct sip_route *route);
1214 static void list_route(struct sip_route *route);
1215 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1216 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1217 struct sip_request *req, char *uri);
1218 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1219 static void check_pendings(struct sip_pvt *p);
1220 static void *sip_park_thread(void *stuff);
1221 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1222 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1224 /*--- Codec handling / SDP */
1225 static void try_suggested_sip_codec(struct sip_pvt *p);
1226 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1227 static const char *get_sdp(struct sip_request *req, const char *name);
1228 static int find_sdp(struct sip_request *req);
1229 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
1230 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1231 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1232 int debug);
1233 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1234 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1235 int debug);
1236 static int add_sdp(struct sip_request *resp, struct sip_pvt *p);
1238 /*--- Authentication stuff */
1239 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
1240 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1241 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1242 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1243 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno); /* Add realm authentication in list */
1244 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm); /* Find authentication for a specific realm */
1245 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1246 const char *secret, const char *md5secret, int sipmethod,
1247 char *uri, enum xmittype reliable, int ignore);
1248 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1249 int sipmethod, char *uri, enum xmittype reliable,
1250 struct sockaddr_in *sin, struct sip_peer **authpeer);
1251 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1252 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
1253 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len);
1255 /*--- Domain handling */
1256 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1257 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1258 static void clear_sip_domains(void);
1260 /*--- SIP realm authentication */
1261 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
1262 static int clear_realm_authentication(struct sip_auth *authlist);
1263 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1265 /*--- Misc functions */
1266 static int sip_do_reload(enum channelreloadreason reason);
1267 static int reload_config(enum channelreloadreason reason);
1268 static int expire_register(void *data);
1269 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1270 static void *do_monitor(void *data);
1271 static int restart_monitor(void);
1272 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1273 static void sip_destroy(struct sip_pvt *p);
1274 static int sip_addrcmp(char *name, struct sockaddr_in *sin); /* Support for peer matching */
1275 static int sip_refer_allocate(struct sip_pvt *p);
1276 static void ast_quiet_chan(struct ast_channel *chan);
1277 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1279 /*--- Device monitoring and Device/extension state handling */
1280 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1281 static int sip_devicestate(void *data);
1282 static int sip_poke_noanswer(void *data);
1283 static int sip_poke_peer(struct sip_peer *peer);
1284 static void sip_poke_all_peers(void);
1285 static void sip_peer_hold(struct sip_pvt *p, int hold);
1287 /*--- Applications, functions, CLI and manager command helpers */
1288 static const char *sip_nat_mode(const struct sip_pvt *p);
1289 static int sip_show_inuse(int fd, int argc, char *argv[]);
1290 static char *transfermode2str(enum transfermodes mode) attribute_const;
1291 static char *nat2str(int nat) attribute_const;
1292 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1293 static int sip_show_users(int fd, int argc, char *argv[]);
1294 static int _sip_show_peers(int fd, int *total, struct mansession *s, struct message *m, int argc, char *argv[]);
1295 static int manager_sip_show_peers( struct mansession *s, struct message *m );
1296 static int sip_show_peers(int fd, int argc, char *argv[]);
1297 static int sip_show_objects(int fd, int argc, char *argv[]);
1298 static void print_group(int fd, unsigned int group, int crlf);
1299 static const char *dtmfmode2str(int mode) attribute_const;
1300 static const char *insecure2str(int port, int invite) attribute_const;
1301 static void cleanup_stale_contexts(char *new, char *old);
1302 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1303 static const char *domain_mode_to_text(const enum domain_mode mode);
1304 static int sip_show_domains(int fd, int argc, char *argv[]);
1305 static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[]);
1306 static int manager_sip_show_peer( struct mansession *s, struct message *m);
1307 static int sip_show_peer(int fd, int argc, char *argv[]);
1308 static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[]);
1309 static int sip_show_user(int fd, int argc, char *argv[]);
1310 static int sip_show_registry(int fd, int argc, char *argv[]);
1311 static int sip_show_settings(int fd, int argc, char *argv[]);
1312 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1313 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1314 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1315 static int sip_show_channels(int fd, int argc, char *argv[]);
1316 static int sip_show_subscriptions(int fd, int argc, char *argv[]);
1317 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1318 static char *complete_sipch(const char *line, const char *word, int pos, int state);
1319 static char *complete_sip_peer(const char *word, int state, int flags2);
1320 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1321 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state);
1322 static char *complete_sip_user(const char *word, int state, int flags2);
1323 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
1324 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1325 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state);
1326 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state);
1327 static int sip_show_channel(int fd, int argc, char *argv[]);
1328 static int sip_show_history(int fd, int argc, char *argv[]);
1329 static int sip_do_debug_ip(int fd, int argc, char *argv[]);
1330 static int sip_do_debug_peer(int fd, int argc, char *argv[]);
1331 static int sip_do_debug(int fd, int argc, char *argv[]);
1332 static int sip_no_debug(int fd, int argc, char *argv[]);
1333 static int sip_notify(int fd, int argc, char *argv[]);
1334 static int sip_do_history(int fd, int argc, char *argv[]);
1335 static int sip_no_history(int fd, int argc, char *argv[]);
1336 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
1337 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1338 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1339 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1340 static int sip_dtmfmode(struct ast_channel *chan, void *data);
1341 static int sip_addheader(struct ast_channel *chan, void *data);
1342 static int sip_do_reload(enum channelreloadreason reason);
1343 static int sip_reload(int fd, int argc, char *argv[]);
1345 /*--- Debugging
1346 Functions for enabling debug per IP or fully, or enabling history logging for
1347 a SIP dialog
1349 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1350 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1351 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1352 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1353 static void sip_dump_history(struct sip_pvt *dialog);
1355 /*--- Device object handling */
1356 static struct sip_peer *temp_peer(const char *name);
1357 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime);
1358 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
1359 static int update_call_counter(struct sip_pvt *fup, int event);
1360 static void sip_destroy_peer(struct sip_peer *peer);
1361 static void sip_destroy_user(struct sip_user *user);
1362 static int sip_poke_peer(struct sip_peer *peer);
1363 static void set_peer_defaults(struct sip_peer *peer);
1364 static struct sip_peer *temp_peer(const char *name);
1365 static void register_peer_exten(struct sip_peer *peer, int onoff);
1366 static void sip_destroy_peer(struct sip_peer *peer);
1367 static void sip_destroy_user(struct sip_user *user);
1368 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
1369 static struct sip_user *find_user(const char *name, int realtime);
1370 static int sip_poke_peer_s(void *data);
1371 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1372 static int expire_register(void *data);
1373 static void reg_source_db(struct sip_peer *peer);
1374 static void destroy_association(struct sip_peer *peer);
1375 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1377 /* Realtime device support */
1378 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
1379 static struct sip_user *realtime_user(const char *username);
1380 static void update_peer(struct sip_peer *p, int expiry);
1381 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
1382 static int sip_prune_realtime(int fd, int argc, char *argv[]);
1384 /*--- Internal UA client handling (outbound registrations) */
1385 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
1386 static void sip_registry_destroy(struct sip_registry *reg);
1387 static int sip_register(char *value, int lineno);
1388 static char *regstate2str(enum sipregistrystate regstate) attribute_const;
1389 static int sip_reregister(void *data);
1390 static int __sip_do_register(struct sip_registry *r);
1391 static int sip_reg_timeout(void *data);
1392 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader);
1393 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1394 static void sip_send_all_registers(void);
1396 /*--- Parsing SIP requests and responses */
1397 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1398 static int determine_firstline_parts(struct sip_request *req);
1399 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1400 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1401 static int find_sip_method(const char *msg);
1402 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1403 static void parse_request(struct sip_request *req);
1404 static const char *get_header(const struct sip_request *req, const char *name);
1405 static char *referstatus2str(enum referstatus rstatus) attribute_pure;
1406 static int method_match(enum sipmethod id, const char *name);
1407 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1408 static char *get_in_brackets(char *tmp);
1409 static const char *find_alias(const char *name, const char *_default);
1410 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1411 static const char *get_header(const struct sip_request *req, const char *name);
1412 static int lws2sws(char *msgbuf, int len);
1413 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1414 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1415 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1416 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1417 static int set_address_from_contact(struct sip_pvt *pvt);
1418 static void check_via(struct sip_pvt *p, struct sip_request *req);
1419 static char *get_calleridname(const char *input, char *output, size_t outputsize);
1420 static int get_rpid_num(const char *input, char *output, int maxlen);
1421 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
1422 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1423 static int get_msg_text(char *buf, int len, struct sip_request *req);
1424 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1425 static void free_old_route(struct sip_route *route);
1427 /*--- Constructing requests and responses */
1428 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1429 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1430 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1431 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1432 static int init_resp(struct sip_request *resp, const char *msg);
1433 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1434 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1435 static void build_via(struct sip_pvt *p);
1436 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1437 static int create_addr(struct sip_pvt *dialog, const char *opeer);
1438 static char *generate_random_string(char *buf, size_t size);
1439 static void build_callid_pvt(struct sip_pvt *pvt);
1440 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1441 static void make_our_tag(char *tagbuf, size_t len);
1442 static int add_header(struct sip_request *req, const char *var, const char *value);
1443 static int add_header_contentLength(struct sip_request *req, int len);
1444 static int add_line(struct sip_request *req, const char *line);
1445 static int add_text(struct sip_request *req, const char *text);
1446 static int add_digit(struct sip_request *req, char digit);
1447 static int add_vidupdate(struct sip_request *req);
1448 static void add_route(struct sip_request *req, struct sip_route *route);
1449 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1450 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1451 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1452 static void set_destination(struct sip_pvt *p, char *uri);
1453 static void append_date(struct sip_request *req);
1454 static void build_contact(struct sip_pvt *p);
1455 static void build_rpid(struct sip_pvt *p);
1457 /*------Request handling functions */
1458 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1459 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);
1460 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock);
1461 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1462 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1463 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1464 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1465 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1466 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1467 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1468 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1469 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1470 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1471 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
1473 /*------Response handling functions */
1474 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1475 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1476 static int handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req);
1477 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
1478 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
1480 /*----- RTP interface functions */
1481 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
1482 static struct ast_rtp *sip_get_rtp_peer(struct ast_channel *chan);
1483 static struct ast_rtp *sip_get_vrtp_peer(struct ast_channel *chan);
1484 static int sip_get_codec(struct ast_channel *chan);
1485 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
1487 /*------ T38 Support --------- */
1488 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite); /*!< T38 negotiation helper function */
1489 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1490 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p);
1491 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1492 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1494 /*! \brief Definition of this channel for PBX channel registration */
1495 static const struct ast_channel_tech sip_tech = {
1496 .type = "SIP",
1497 .description = "Session Initiation Protocol (SIP)",
1498 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1499 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1500 .requester = sip_request_call,
1501 .devicestate = sip_devicestate,
1502 .call = sip_call,
1503 .hangup = sip_hangup,
1504 .answer = sip_answer,
1505 .read = sip_read,
1506 .write = sip_write,
1507 .write_video = sip_write,
1508 .indicate = sip_indicate,
1509 .transfer = sip_transfer,
1510 .fixup = sip_fixup,
1511 .send_digit = sip_senddigit,
1512 .bridge = ast_rtp_bridge,
1513 .send_text = sip_sendtext,
1516 /**--- some list management macros. **/
1518 #define UNLINK(element, head, prev) do { \
1519 if (prev) \
1520 (prev)->next = (element)->next; \
1521 else \
1522 (head) = (element)->next; \
1523 } while (0)
1525 /*! \brief Interface structure with callbacks used to connect to RTP module */
1526 static struct ast_rtp_protocol sip_rtp = {
1527 type: "SIP",
1528 get_rtp_info: sip_get_rtp_peer,
1529 get_vrtp_info: sip_get_vrtp_peer,
1530 set_rtp_peer: sip_set_rtp_peer,
1531 get_codec: sip_get_codec,
1534 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1535 static struct ast_udptl_protocol sip_udptl = {
1536 type: "SIP",
1537 get_udptl_info: sip_get_udptl_peer,
1538 set_udptl_peer: sip_set_udptl_peer,
1541 /*! \brief Convert transfer status to string */
1542 static char *referstatus2str(enum referstatus rstatus)
1544 int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
1545 int x;
1547 for (x = 0; x < i; x++) {
1548 if (referstatusstrings[x].status == rstatus)
1549 return (char *) referstatusstrings[x].text;
1551 return "";
1554 /*! \brief Initialize the initital request packet in the pvt structure.
1555 This packet is used for creating replies and future requests in
1556 a dialog */
1557 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
1559 if (p->initreq.headers) {
1560 ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
1562 /* Use this as the basis */
1563 copy_request(&p->initreq, req);
1564 parse_request(&p->initreq);
1565 if (ast_test_flag(req, SIP_PKT_DEBUG))
1566 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
1570 /*! \brief returns true if 'name' (with optional trailing whitespace)
1571 * matches the sip method 'id'.
1572 * Strictly speaking, SIP methods are case SENSITIVE, but we do
1573 * a case-insensitive comparison to be more tolerant.
1574 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1576 static int method_match(enum sipmethod id, const char *name)
1578 int len = strlen(sip_methods[id].text);
1579 int l_name = name ? strlen(name) : 0;
1580 /* true if the string is long enough, and ends with whitespace, and matches */
1581 return (l_name >= len && name[len] < 33 &&
1582 !strncasecmp(sip_methods[id].text, name, len));
1585 /*! \brief find_sip_method: Find SIP method from header */
1586 static int find_sip_method(const char *msg)
1588 int i, res = 0;
1590 if (ast_strlen_zero(msg))
1591 return 0;
1592 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
1593 if (method_match(i, msg))
1594 res = sip_methods[i].id;
1596 return res;
1599 /*! \brief Parse supported header in incoming packet */
1600 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
1602 char *next, *sep;
1603 char *temp = ast_strdupa(supported);
1604 unsigned int profile = 0;
1605 int i, found;
1607 if (ast_strlen_zero(supported) )
1608 return 0;
1610 if (option_debug > 2 && sipdebug)
1611 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1613 for (next = temp; next; next = sep) {
1614 found = FALSE;
1615 if ( (sep = strchr(next, ',')) != NULL)
1616 *sep++ = '\0';
1617 next = ast_skip_blanks(next);
1618 if (option_debug > 2 && sipdebug)
1619 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1620 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
1621 if (!strcasecmp(next, sip_options[i].text)) {
1622 profile |= sip_options[i].id;
1623 found = TRUE;
1624 if (option_debug > 2 && sipdebug)
1625 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1626 break;
1629 if (!found && option_debug > 2 && sipdebug) {
1630 if (!strncasecmp(next, "x-", 2))
1631 ast_log(LOG_DEBUG, "Found private SIP option, not supported: %s\n", next);
1632 else
1633 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1637 if (pvt)
1638 pvt->sipoptions = profile;
1639 return profile;
1642 /*! \brief See if we pass debug IP filter */
1643 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
1645 if (!sipdebug)
1646 return 0;
1647 if (debugaddr.sin_addr.s_addr) {
1648 if (((ntohs(debugaddr.sin_port) != 0)
1649 && (debugaddr.sin_port != addr->sin_port))
1650 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1651 return 0;
1653 return 1;
1656 /*! \brief The real destination address for a write */
1657 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
1659 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
1662 /*! \brief Display SIP nat mode */
1663 static const char *sip_nat_mode(const struct sip_pvt *p)
1665 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
1668 /*! \brief Test PVT for debugging output */
1669 static inline int sip_debug_test_pvt(struct sip_pvt *p)
1671 if (!sipdebug)
1672 return 0;
1673 return sip_debug_test_addr(sip_real_dst(p));
1676 /*! \brief Transmit SIP message */
1677 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1679 int res;
1680 const struct sockaddr_in *dst = sip_real_dst(p);
1681 res=sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
1683 if (res != len)
1684 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));
1685 return res;
1689 /*! \brief Build a Via header for a request */
1690 static void build_via(struct sip_pvt *p)
1692 /* Work around buggy UNIDEN UIP200 firmware */
1693 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1695 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1696 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1697 ast_inet_ntoa(p->ourip), ourport, p->branch, rport);
1700 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1702 * Using the localaddr structure built up with localnet statements in sip.conf
1703 * apply it to their address to see if we need to substitute our
1704 * externip or can get away with our internal bindaddr
1706 static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1708 struct sockaddr_in theirs, ours;
1710 /* Get our local information */
1711 ast_ouraddrfor(them, us);
1712 theirs.sin_addr = *them;
1713 ours.sin_addr = *us;
1715 if (localaddr && externip.sin_addr.s_addr &&
1716 ast_apply_ha(localaddr, &theirs) &&
1717 !ast_apply_ha(localaddr, &ours)) {
1718 if (externexpire && time(NULL) >= externexpire) {
1719 struct ast_hostent ahp;
1720 struct hostent *hp;
1722 externexpire = time(NULL) + externrefresh;
1723 if ((hp = ast_gethostbyname(externhost, &ahp))) {
1724 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1725 } else
1726 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1728 *us = externip.sin_addr;
1729 if (option_debug) {
1730 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n",
1731 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
1733 } else if (bindaddr.sin_addr.s_addr)
1734 *us = bindaddr.sin_addr;
1735 return AST_SUCCESS;
1738 /*! \brief Append to SIP dialog history
1739 \return Always returns 0 */
1740 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1742 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1743 __attribute__ ((format (printf, 2, 3)));
1745 /*! \brief Append to SIP dialog history with arg list */
1746 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1748 char buf[80], *c = buf; /* max history length */
1749 struct sip_history *hist;
1750 int l;
1752 vsnprintf(buf, sizeof(buf), fmt, ap);
1753 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1754 l = strlen(buf) + 1;
1755 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1756 return;
1757 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1758 free(hist);
1759 return;
1761 memcpy(hist->event, buf, l);
1762 AST_LIST_INSERT_TAIL(p->history, hist, list);
1765 /*! \brief Append to SIP dialog history with arg list */
1766 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1768 va_list ap;
1770 if (!recordhistory || !p)
1771 return;
1772 va_start(ap, fmt);
1773 append_history_va(p, fmt, ap);
1774 va_end(ap);
1776 return;
1779 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
1780 static int retrans_pkt(void *data)
1782 struct sip_pkt *pkt = data, *prev, *cur = NULL;
1783 int reschedule = DEFAULT_RETRANS;
1785 /* Lock channel PVT */
1786 ast_mutex_lock(&pkt->owner->lock);
1788 if (pkt->retrans < MAX_RETRANS) {
1789 pkt->retrans++;
1790 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
1791 if (sipdebug && option_debug > 3)
1792 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);
1793 } else {
1794 int siptimer_a;
1796 if (sipdebug && option_debug > 3)
1797 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1798 if (!pkt->timer_a)
1799 pkt->timer_a = 2 ;
1800 else
1801 pkt->timer_a = 2 * pkt->timer_a;
1803 /* For non-invites, a maximum of 4 secs */
1804 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
1805 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1806 siptimer_a = 4000;
1808 /* Reschedule re-transmit */
1809 reschedule = siptimer_a;
1810 if (option_debug > 3)
1811 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);
1814 if (sip_debug_test_pvt(pkt->owner)) {
1815 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
1816 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
1817 pkt->retrans, sip_nat_mode(pkt->owner),
1818 ast_inet_ntoa(dst->sin_addr),
1819 ntohs(dst->sin_port), pkt->data);
1822 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1823 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1824 ast_mutex_unlock(&pkt->owner->lock);
1825 return reschedule;
1827 /* Too many retries */
1828 if (pkt->owner && pkt->method != SIP_OPTIONS) {
1829 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1830 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");
1831 } else {
1832 if ((pkt->method == SIP_OPTIONS) && sipdebug)
1833 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1835 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1837 pkt->retransid = -1;
1839 if (ast_test_flag(pkt, FLAG_FATAL)) {
1840 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
1841 ast_mutex_unlock(&pkt->owner->lock); /* SIP_PVT, not channel */
1842 usleep(1);
1843 ast_mutex_lock(&pkt->owner->lock);
1845 if (pkt->owner->owner) {
1846 ast_set_flag(&pkt->owner->flags[0], SIP_ALREADYGONE);
1847 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1848 ast_queue_hangup(pkt->owner->owner);
1849 ast_channel_unlock(pkt->owner->owner);
1850 } else {
1851 /* If no channel owner, destroy now */
1852 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
1855 /* In any case, go ahead and remove the packet */
1856 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
1857 if (cur == pkt)
1858 break;
1860 if (cur) {
1861 if (prev)
1862 prev->next = cur->next;
1863 else
1864 pkt->owner->packets = cur->next;
1865 ast_mutex_unlock(&pkt->owner->lock);
1866 free(cur);
1867 pkt = NULL;
1868 } else
1869 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
1870 if (pkt)
1871 ast_mutex_unlock(&pkt->owner->lock);
1872 return 0;
1875 /*! \brief Transmit packet with retransmits
1876 \return 0 on success, -1 on failure to allocate packet
1878 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
1880 struct sip_pkt *pkt;
1881 int siptimer_a = DEFAULT_RETRANS;
1883 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
1884 return AST_FAILURE;
1885 memcpy(pkt->data, data, len);
1886 pkt->method = sipmethod;
1887 pkt->packetlen = len;
1888 pkt->next = p->packets;
1889 pkt->owner = p;
1890 pkt->seqno = seqno;
1891 pkt->flags = resp;
1892 pkt->data[len] = '\0';
1893 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
1894 if (fatal)
1895 ast_set_flag(pkt, FLAG_FATAL);
1896 if (pkt->timer_t1)
1897 siptimer_a = pkt->timer_t1 * 2;
1899 /* Schedule retransmission */
1900 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
1901 if (option_debug > 3 && sipdebug)
1902 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt->retransid);
1903 pkt->next = p->packets;
1904 p->packets = pkt;
1906 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
1907 if (sipmethod == SIP_INVITE) {
1908 /* Note this is a pending invite */
1909 p->pendinginvite = seqno;
1911 return AST_SUCCESS;
1914 /*! \brief Kill a SIP dialog (called by scheduler) */
1915 static int __sip_autodestruct(void *data)
1917 struct sip_pvt *p = data;
1919 /* If this is a subscription, tell the phone that we got a timeout */
1920 if (p->subscribed) {
1921 p->subscribed = TIMEOUT;
1922 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1); /* Send last notification */
1923 p->subscribed = NONE;
1924 append_history(p, "Subscribestatus", "timeout");
1925 if (option_debug > 2)
1926 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
1927 return 10000; /* Reschedule this destruction so that we know that it's gone */
1930 /* Reset schedule ID */
1931 p->autokillid = -1;
1933 if (option_debug)
1934 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
1935 append_history(p, "AutoDestroy", "%s", p->callid);
1936 if (p->owner) {
1937 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
1938 ast_queue_hangup(p->owner);
1939 } else if (p->refer) {
1940 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
1941 } else {
1942 sip_destroy(p);
1944 return 0;
1947 /*! \brief Schedule destruction of SIP call */
1948 static void sip_scheddestroy(struct sip_pvt *p, int ms)
1950 if (sip_debug_test_pvt(p))
1951 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
1952 if (recordhistory)
1953 append_history(p, "SchedDestroy", "%d ms", ms);
1955 if (p->autokillid > -1)
1956 ast_sched_del(sched, p->autokillid);
1957 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
1960 /*! \brief Cancel destruction of SIP dialog */
1961 static void sip_cancel_destroy(struct sip_pvt *p)
1963 if (p->autokillid > -1) {
1964 ast_sched_del(sched, p->autokillid);
1965 append_history(p, "CancelDestroy", "");
1966 p->autokillid = -1;
1970 /*! \brief Acknowledges receipt of a packet and stops retransmission */
1971 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod, int reset)
1973 struct sip_pkt *cur, *prev = NULL;
1975 /* Just in case... */
1976 char *msg;
1977 int res = FALSE;
1979 msg = sip_methods[sipmethod].text;
1981 ast_mutex_lock(&p->lock);
1982 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
1983 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1984 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
1985 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1986 if (!resp && (seqno == p->pendinginvite)) {
1987 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
1988 p->pendinginvite = 0;
1990 /* this is our baby */
1991 res = TRUE;
1992 UNLINK(cur, p->packets, prev);
1993 if (cur->retransid > -1) {
1994 if (sipdebug && option_debug > 3)
1995 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
1996 ast_sched_del(sched, cur->retransid);
1998 if (!reset)
1999 free(cur);
2000 break;
2003 ast_mutex_unlock(&p->lock);
2004 if (option_debug)
2005 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
2008 /*! \brief Pretend to ack all packets
2009 * maybe the lock on p is not strictly necessary but there might be a race */
2010 static void __sip_pretend_ack(struct sip_pvt *p)
2012 struct sip_pkt *cur = NULL;
2014 while (p->packets) {
2015 int method;
2016 if (cur == p->packets) {
2017 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
2018 return;
2020 cur = p->packets;
2021 method = (cur->method) ? cur->method : find_sip_method(cur->data);
2022 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method, FALSE);
2026 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2027 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2029 struct sip_pkt *cur;
2030 int res = -1;
2032 for (cur = p->packets; cur; cur = cur->next) {
2033 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
2034 (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
2035 /* this is our baby */
2036 if (cur->retransid > -1) {
2037 if (option_debug > 3 && sipdebug)
2038 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
2039 ast_sched_del(sched, cur->retransid);
2041 cur->retransid = -1;
2042 res = 0;
2043 break;
2046 if (option_debug)
2047 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");
2048 return res;
2052 /*! \brief Copy SIP request, parse it */
2053 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2055 memset(dst, 0, sizeof(*dst));
2056 memcpy(dst->data, src->data, sizeof(dst->data));
2057 dst->len = src->len;
2058 parse_request(dst);
2061 /* add a blank line if no body */
2062 static void add_blank(struct sip_request *req)
2064 if (!req->lines) {
2065 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2066 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2067 req->len += strlen(req->data + req->len);
2071 /*! \brief Transmit response on SIP request*/
2072 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2074 int res;
2076 add_blank(req);
2077 if (sip_debug_test_pvt(p)) {
2078 const struct sockaddr_in *dst = sip_real_dst(p);
2080 ast_verbose("%sTransmitting (%s) to %s:%d:\n%s\n---\n",
2081 reliable ? "Reliably " : "", sip_nat_mode(p),
2082 ast_inet_ntoa(dst->sin_addr),
2083 ntohs(dst->sin_port), req->data);
2085 if (recordhistory) {
2086 struct sip_request tmp;
2087 parse_copy(&tmp, req);
2088 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
2089 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
2091 res = (reliable) ?
2092 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2093 __sip_xmit(p, req->data, req->len);
2094 if (res > 0)
2095 return 0;
2096 return res;
2099 /*! \brief Send SIP Request to the other part of the dialogue */
2100 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2102 int res;
2104 add_blank(req);
2105 if (sip_debug_test_pvt(p)) {
2106 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
2107 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);
2108 else
2109 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);
2111 if (recordhistory) {
2112 struct sip_request tmp;
2113 parse_copy(&tmp, req);
2114 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
2116 res = (reliable) ?
2117 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method) :
2118 __sip_xmit(p, req->data, req->len);
2119 return res;
2122 /*! \brief Pick out text in brackets from character string
2123 \return pointer to terminated stripped string
2124 \param tmp input string that will be modified */
2125 static char *get_in_brackets(char *tmp)
2127 char *parse;
2128 char *first_quote;
2129 char *first_bracket;
2130 char *second_bracket;
2131 char last_char;
2133 parse = tmp;
2134 for (;;) {
2135 first_quote = strchr(parse, '"');
2136 first_bracket = strchr(parse, '<');
2137 if (first_quote && first_bracket && (first_quote < first_bracket)) {
2138 last_char = '\0';
2139 for (parse = first_quote + 1; *parse; parse++) {
2140 if ((*parse == '"') && (last_char != '\\'))
2141 break;
2142 last_char = *parse;
2144 if (!*parse) {
2145 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
2146 return tmp;
2148 parse++;
2149 continue;
2151 if (first_bracket) {
2152 second_bracket = strchr(first_bracket + 1, '>');
2153 if (second_bracket) {
2154 *second_bracket = '\0';
2155 return first_bracket + 1;
2156 } else {
2157 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
2158 return tmp;
2161 return tmp;
2165 /*! \brief Send SIP MESSAGE text within a call
2166 Called from PBX core sendtext() application */
2167 static int sip_sendtext(struct ast_channel *ast, const char *text)
2169 struct sip_pvt *p = ast->tech_pvt;
2170 int debug = sip_debug_test_pvt(p);
2172 if (debug)
2173 ast_verbose("Sending text %s on %s\n", text, ast->name);
2174 if (!p)
2175 return -1;
2176 if (ast_strlen_zero(text))
2177 return 0;
2178 if (debug)
2179 ast_verbose("Really sending text %s on %s\n", text, ast->name);
2180 transmit_message_with_text(p, text);
2181 return 0;
2184 /*! \brief Update peer object in realtime storage
2185 If the Asterisk system name is set in asterisk.conf, we will use
2186 that name and store that in the "regserver" field in the sippeers
2187 table to facilitate multi-server setups.
2189 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
2191 char port[10];
2192 char ipaddr[INET_ADDRSTRLEN];
2193 char regseconds[20];
2195 char *sysname = ast_config_AST_SYSTEM_NAME;
2196 char *syslabel = NULL;
2198 time_t nowtime = time(NULL) + expirey;
2199 const char *fc = fullcontact ? "fullcontact" : NULL;
2201 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
2202 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2203 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2205 if (ast_strlen_zero(sysname)) /* No system name, disable this */
2206 sysname = NULL;
2207 else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME))
2208 syslabel = "regserver";
2210 if (fc)
2211 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2212 "port", port, "regseconds", regseconds,
2213 "username", username, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
2214 else
2215 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2216 "port", port, "regseconds", regseconds,
2217 "username", username, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
2220 /*! \brief Automatically add peer extension to dial plan */
2221 static void register_peer_exten(struct sip_peer *peer, int onoff)
2223 char multi[256];
2224 char *stringp, *ext, *context;
2226 /* XXX note that global_regcontext is both a global 'enable' flag and
2227 * the name of the global regexten context, if not specified
2228 * individually.
2230 if (ast_strlen_zero(global_regcontext))
2231 return;
2233 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
2234 stringp = multi;
2235 while ((ext = strsep(&stringp, "&"))) {
2236 if ((context = strchr(ext, '@'))) {
2237 *context++ = '\0'; /* split ext@context */
2238 if (!ast_context_find(context)) {
2239 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
2240 continue;
2242 } else {
2243 context = global_regcontext;
2245 if (onoff)
2246 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2247 ast_strdup(peer->name), ast_free, "SIP");
2248 else
2249 ast_context_remove_extension(context, ext, 1, NULL);
2253 /*! \brief Destroy peer object from memory */
2254 static void sip_destroy_peer(struct sip_peer *peer)
2256 if (option_debug > 2)
2257 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
2259 /* Delete it, it needs to disappear */
2260 if (peer->call)
2261 sip_destroy(peer->call);
2263 if (peer->mwipvt) /* We have an active subscription, delete it */
2264 sip_destroy(peer->mwipvt);
2266 if (peer->chanvars) {
2267 ast_variables_destroy(peer->chanvars);
2268 peer->chanvars = NULL;
2270 if (peer->expire > -1)
2271 ast_sched_del(sched, peer->expire);
2272 if (peer->pokeexpire > -1)
2273 ast_sched_del(sched, peer->pokeexpire);
2274 register_peer_exten(peer, FALSE);
2275 ast_free_ha(peer->ha);
2276 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
2277 apeerobjs--;
2278 else if (ast_test_flag(&peer->flags[0], SIP_REALTIME))
2279 rpeerobjs--;
2280 else
2281 speerobjs--;
2282 clear_realm_authentication(peer->auth);
2283 peer->auth = NULL;
2284 if (peer->dnsmgr)
2285 ast_dnsmgr_release(peer->dnsmgr);
2286 free(peer);
2289 /*! \brief Update peer data in database (if used) */
2290 static void update_peer(struct sip_peer *p, int expiry)
2292 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2293 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
2294 (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
2295 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
2300 /*! \brief realtime_peer: Get peer from realtime storage
2301 * Checks the "sippeers" realtime family from extconfig.conf
2302 * \todo Consider adding check of port address when matching here to follow the same
2303 * algorithm as for static peers. Will we break anything by adding that?
2305 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
2307 struct sip_peer *peer;
2308 struct ast_variable *var = NULL;
2309 struct ast_variable *tmp;
2310 char ipaddr[INET_ADDRSTRLEN];
2312 /* First check on peer name */
2313 if (newpeername)
2314 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
2315 else if (sin) { /* Then check on IP address for dynamic peers */
2316 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2317 var = ast_load_realtime("sippeers", "host", ipaddr, NULL); /* First check for fixed IP hosts */
2318 if (!var)
2319 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, NULL); /* Then check for registred hosts */
2322 if (!var)
2323 return NULL;
2325 for (tmp = var; tmp; tmp = tmp->next) {
2326 /* If this is type=user, then skip this object. */
2327 if (!strcasecmp(tmp->name, "type") &&
2328 !strcasecmp(tmp->value, "user")) {
2329 ast_variables_destroy(var);
2330 return NULL;
2331 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
2332 newpeername = tmp->value;
2336 if (!newpeername) { /* Did not find peer in realtime */
2337 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
2338 ast_variables_destroy(var);
2339 return NULL;
2342 /* Peer found in realtime, now build it in memory */
2343 peer = build_peer(newpeername, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2344 if (!peer) {
2345 ast_variables_destroy(var);
2346 return NULL;
2349 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2350 /* Cache peer */
2351 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
2352 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
2353 if (peer->expire > -1) {
2354 ast_sched_del(sched, peer->expire);
2356 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
2358 ASTOBJ_CONTAINER_LINK(&peerl,peer);
2359 } else {
2360 ast_set_flag(&peer->flags[0], SIP_REALTIME);
2362 ast_variables_destroy(var);
2364 return peer;
2367 /*! \brief Support routine for find_peer */
2368 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
2370 /* We know name is the first field, so we can cast */
2371 struct sip_peer *p = (struct sip_peer *) name;
2372 return !(!inaddrcmp(&p->addr, sin) ||
2373 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
2374 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
2377 /*! \brief Locate peer by name or ip address
2378 * This is used on incoming SIP message to find matching peer on ip
2379 or outgoing message to find matching peer on name */
2380 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
2382 struct sip_peer *p = NULL;
2384 if (peer)
2385 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
2386 else
2387 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
2389 if (!p && realtime) {
2390 p = realtime_peer(peer, sin);
2392 return p;
2395 /*! \brief Remove user object from in-memory storage */
2396 static void sip_destroy_user(struct sip_user *user)
2398 if (option_debug > 2)
2399 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
2400 ast_free_ha(user->ha);
2401 if (user->chanvars) {
2402 ast_variables_destroy(user->chanvars);
2403 user->chanvars = NULL;
2405 if (ast_test_flag(&user->flags[0], SIP_REALTIME))
2406 ruserobjs--;
2407 else
2408 suserobjs--;
2409 free(user);
2412 /*! \brief Load user from realtime storage
2413 * Loads user from "sipusers" category in realtime (extconfig.conf)
2414 * Users are matched on From: user name (the domain in skipped) */
2415 static struct sip_user *realtime_user(const char *username)
2417 struct ast_variable *var;
2418 struct ast_variable *tmp;
2419 struct sip_user *user = NULL;
2421 var = ast_load_realtime("sipusers", "name", username, NULL);
2423 if (!var)
2424 return NULL;
2426 for (tmp = var; tmp; tmp = tmp->next) {
2427 if (!strcasecmp(tmp->name, "type") &&
2428 !strcasecmp(tmp->value, "peer")) {
2429 ast_variables_destroy(var);
2430 return NULL;
2434 user = build_user(username, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2436 if (!user) { /* No user found */
2437 ast_variables_destroy(var);
2438 return NULL;
2441 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2442 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2443 suserobjs++;
2444 ASTOBJ_CONTAINER_LINK(&userl,user);
2445 } else {
2446 /* Move counter from s to r... */
2447 suserobjs--;
2448 ruserobjs++;
2449 ast_set_flag(&user->flags[0], SIP_REALTIME);
2451 ast_variables_destroy(var);
2452 return user;
2455 /*! \brief Locate user by name
2456 * Locates user by name (From: sip uri user name part) first
2457 * from in-memory list (static configuration) then from
2458 * realtime storage (defined in extconfig.conf) */
2459 static struct sip_user *find_user(const char *name, int realtime)
2461 struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
2462 if (!u && realtime)
2463 u = realtime_user(name);
2464 return u;
2467 /*! \brief Create address structure from peer reference.
2468 * return -1 on error, 0 on success.
2470 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer)
2472 int natflags;
2474 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
2475 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
2476 r->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
2477 r->recv = r->sa;
2478 } else {
2479 return -1;
2482 ast_copy_flags(&r->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
2483 ast_copy_flags(&r->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
2484 r->capability = peer->capability;
2485 if (!ast_test_flag(&r->flags[1], SIP_PAGE2_VIDEOSUPPORT) && r->vrtp) {
2486 ast_rtp_destroy(r->vrtp);
2487 r->vrtp = NULL;
2489 r->prefs = peer->prefs;
2490 if (ast_test_flag(&r->flags[1], SIP_PAGE2_T38SUPPORT)) {
2491 r->t38.capability = global_t38_capability;
2492 if (r->udptl) {
2493 if (ast_udptl_get_error_correction_scheme(r->udptl) == UDPTL_ERROR_CORRECTION_FEC )
2494 r->t38.capability |= T38FAX_UDP_EC_FEC;
2495 else if (ast_udptl_get_error_correction_scheme(r->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
2496 r->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
2497 else if (ast_udptl_get_error_correction_scheme(r->udptl) == UDPTL_ERROR_CORRECTION_NONE )
2498 r->t38.capability |= T38FAX_UDP_EC_NONE;
2499 r->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
2500 if (option_debug > 1)
2501 ast_log(LOG_DEBUG,"Our T38 capability (%d)\n", r->t38.capability);
2503 r->t38.jointcapability = r->t38.capability;
2504 } else if (r->udptl) {
2505 ast_udptl_destroy(r->udptl);
2506 r->udptl = NULL;
2508 natflags = ast_test_flag(&r->flags[0], SIP_NAT) & SIP_NAT_ROUTE;
2509 if (r->rtp) {
2510 if (option_debug)
2511 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", natflags ? "On" : "Off");
2512 ast_rtp_setnat(r->rtp, natflags);
2513 ast_rtp_setdtmf(r->rtp, ast_test_flag(&r->flags[0], SIP_DTMF) != SIP_DTMF_INFO);
2515 if (r->vrtp) {
2516 if (option_debug)
2517 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", natflags ? "On" : "Off");
2518 ast_rtp_setnat(r->vrtp, natflags);
2519 ast_rtp_setdtmf(r->vrtp, 0);
2521 if (r->udptl) {
2522 if (option_debug)
2523 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", natflags ? "On" : "Off");
2524 ast_udptl_setnat(r->udptl, natflags);
2526 ast_string_field_set(r, peername, peer->username);
2527 ast_string_field_set(r, authname, peer->username);
2528 ast_string_field_set(r, username, peer->username);
2529 ast_string_field_set(r, peersecret, peer->secret);
2530 ast_string_field_set(r, peermd5secret, peer->md5secret);
2531 ast_string_field_set(r, tohost, peer->tohost);
2532 ast_string_field_set(r, fullcontact, peer->fullcontact);
2533 if (!r->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
2534 char *tmpcall;
2535 char *c;
2536 tmpcall = ast_strdupa(r->callid);
2537 c = strchr(tmpcall, '@');
2538 if (c) {
2539 *c = '\0';
2540 ast_string_field_build(r, callid, "%s@%s", tmpcall, peer->fromdomain);
2543 if (ast_strlen_zero(r->tohost))
2544 ast_string_field_set(r, tohost, ast_inet_ntoa(r->sa.sin_addr));
2545 if (!ast_strlen_zero(peer->fromdomain))
2546 ast_string_field_set(r, fromdomain, peer->fromdomain);
2547 if (!ast_strlen_zero(peer->fromuser))
2548 ast_string_field_set(r, fromuser, peer->fromuser);
2549 r->maxtime = peer->maxms;
2550 r->callgroup = peer->callgroup;
2551 r->pickupgroup = peer->pickupgroup;
2552 r->allowtransfer = peer->allowtransfer;
2553 /* Set timer T1 to RTT for this peer (if known by qualify=) */
2554 /* Minimum is settable or default to 100 ms */
2555 if (peer->maxms && peer->lastms)
2556 r->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
2557 if ((ast_test_flag(&r->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
2558 (ast_test_flag(&r->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
2559 r->noncodeccapability |= AST_RTP_DTMF;
2560 else
2561 r->noncodeccapability &= ~AST_RTP_DTMF;
2562 ast_string_field_set(r, context, peer->context);
2563 r->rtptimeout = peer->rtptimeout;
2564 r->rtpholdtimeout = peer->rtpholdtimeout;
2565 r->rtpkeepalive = peer->rtpkeepalive;
2566 if (peer->call_limit)
2567 ast_set_flag(&r->flags[0], SIP_CALL_LIMIT);
2568 r->maxcallbitrate = peer->maxcallbitrate;
2570 return 0;
2573 /*! \brief create address structure from peer name
2574 * Or, if peer not found, find it in the global DNS
2575 * returns TRUE (-1) on failure, FALSE on success */
2576 static int create_addr(struct sip_pvt *dialog, const char *opeer)
2578 struct hostent *hp;
2579 struct ast_hostent ahp;
2580 struct sip_peer *p;
2581 char *port;
2582 int portno;
2583 char host[MAXHOSTNAMELEN], *hostn;
2584 char peer[256];
2586 ast_copy_string(peer, opeer, sizeof(peer));
2587 port = strchr(peer, ':');
2588 if (port)
2589 *port++ = '\0';
2590 dialog->sa.sin_family = AF_INET;
2591 dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
2592 p = find_peer(peer, NULL, 1);
2594 if (p) {
2595 int res = create_addr_from_peer(dialog, p);
2596 ASTOBJ_UNREF(p, sip_destroy_peer);
2597 return res;
2599 hostn = peer;
2600 portno = port ? atoi(port) : DEFAULT_SIP_PORT;
2601 if (srvlookup) {
2602 char service[MAXHOSTNAMELEN];
2603 int tportno;
2604 int ret;
2606 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
2607 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
2608 if (ret > 0) {
2609 hostn = host;
2610 portno = tportno;
2613 hp = ast_gethostbyname(hostn, &ahp);
2614 if (!hp) {
2615 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2616 return -1;
2618 ast_string_field_set(dialog, tohost, peer);
2619 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
2620 dialog->sa.sin_port = htons(portno);
2621 dialog->recv = dialog->sa;
2622 return 0;
2625 /*! \brief Scheduled congestion on a call */
2626 static int auto_congest(void *nothing)
2628 struct sip_pvt *p = nothing;
2630 ast_mutex_lock(&p->lock);
2631 p->initid = -1;
2632 if (p->owner) {
2633 /* XXX fails on possible deadlock */
2634 if (!ast_channel_trylock(p->owner)) {
2635 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
2636 append_history(p, "Cong", "Auto-congesting (timer)");
2637 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
2638 ast_channel_unlock(p->owner);
2641 ast_mutex_unlock(&p->lock);
2642 return 0;
2646 /*! \brief Initiate SIP call from PBX
2647 * used from the dial() application */
2648 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2650 int res;
2651 struct sip_pvt *p;
2652 struct varshead *headp;
2653 struct ast_var_t *current;
2654 const char *referer = NULL; /* SIP refererer */
2656 p = ast->tech_pvt;
2657 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2658 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2659 return -1;
2662 /* Check whether there is vxml_url, distinctive ring variables */
2663 headp=&ast->varshead;
2664 AST_LIST_TRAVERSE(headp,current,entries) {
2665 /* Check whether there is a VXML_URL variable */
2666 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2667 p->options->vxml_url = ast_var_value(current);
2668 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
2669 p->options->uri_options = ast_var_value(current);
2670 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
2671 /* Check whether there is a ALERT_INFO variable */
2672 p->options->distinctive_ring = ast_var_value(current);
2673 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2674 /* Check whether there is a variable with a name starting with SIPADDHEADER */
2675 p->options->addsipheaders = 1;
2676 } else if (!strcasecmp(ast_var_name(current),"SIPTRANSFER")) {
2677 /* This is a transfered call */
2678 p->options->transfer = 1;
2679 } else if (!strcasecmp(ast_var_name(current),"SIPTRANSFER_REFERER")) {
2680 /* This is the referer */
2681 referer = ast_var_value(current);
2682 } else if (!strcasecmp(ast_var_name(current),"SIPTRANSFER_REPLACES")) {
2683 /* We're replacing a call. */
2684 p->options->replaces = ast_var_value(current);
2685 } else if (!strcasecmp(ast_var_name(current),"T38CALL")) {
2686 p->t38.state = T38_LOCAL_DIRECT;
2687 if (option_debug)
2688 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
2693 res = 0;
2694 ast_set_flag(&p->flags[0], SIP_OUTGOING);
2696 if (p->options->transfer) {
2697 char buf[BUFSIZ/2];
2699 if (referer) {
2700 if (sipdebug && option_debug > 2)
2701 ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->username, referer);
2702 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
2703 } else {
2704 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
2706 ast_string_field_set(p, cid_name, buf);
2708 if (option_debug)
2709 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
2711 res = update_call_counter(p, INC_CALL_RINGING);
2712 if ( res != -1 ) {
2713 p->callingpres = ast->cid.cid_pres;
2714 p->jointcapability = p->capability;
2715 p->t38.jointcapability = p->t38.capability;
2716 if (option_debug)
2717 ast_log(LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
2718 transmit_invite(p, SIP_INVITE, 1, 2);
2719 if (p->maxtime) {
2720 /* Initialize auto-congest time */
2721 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
2722 } else {
2723 p->initid = ast_sched_add(sched, SIP_TRANS_TIMEOUT, auto_congest, p);
2726 return res;
2729 /*! \brief Destroy registry object
2730 Objects created with the register= statement in static configuration */
2731 static void sip_registry_destroy(struct sip_registry *reg)
2733 /* Really delete */
2734 if (option_debug > 2)
2735 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
2737 if (reg->call) {
2738 /* Clear registry before destroying to ensure
2739 we don't get reentered trying to grab the registry lock */
2740 reg->call->registry = NULL;
2741 if (option_debug > 2)
2742 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
2743 sip_destroy(reg->call);
2745 if (reg->expire > -1)
2746 ast_sched_del(sched, reg->expire);
2747 if (reg->timeout > -1)
2748 ast_sched_del(sched, reg->timeout);
2749 ast_string_field_free_all(reg);
2750 regobjs--;
2751 free(reg);
2755 /*! \brief Execute destruction of SIP dialog structure, release memory */
2756 static void __sip_destroy(struct sip_pvt *p, int lockowner)
2758 struct sip_pvt *cur, *prev = NULL;
2759 struct sip_pkt *cp;
2761 if (sip_debug_test_pvt(p) || option_debug > 2)
2762 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
2764 /* Remove link from peer to subscription of MWI */
2765 if (p->relatedpeer && p->relatedpeer->mwipvt)
2766 p->relatedpeer->mwipvt = NULL;
2768 if (dumphistory)
2769 sip_dump_history(p);
2771 if (p->options)
2772 free(p->options);
2774 if (p->stateid > -1)
2775 ast_extension_state_del(p->stateid, NULL);
2776 if (p->initid > -1)
2777 ast_sched_del(sched, p->initid);
2778 if (p->autokillid > -1)
2779 ast_sched_del(sched, p->autokillid);
2781 if (p->rtp)
2782 ast_rtp_destroy(p->rtp);
2783 if (p->vrtp)
2784 ast_rtp_destroy(p->vrtp);
2785 if (p->udptl)
2786 ast_udptl_destroy(p->udptl);
2787 if (p->refer)
2788 free(p->refer);
2789 if (p->route) {
2790 free_old_route(p->route);
2791 p->route = NULL;
2793 if (p->registry) {
2794 if (p->registry->call == p)
2795 p->registry->call = NULL;
2796 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
2799 /* Unlink us from the owner if we have one */
2800 if (p->owner) {
2801 if (lockowner)
2802 ast_channel_lock(p->owner);
2803 if (option_debug)
2804 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
2805 p->owner->tech_pvt = NULL;
2806 if (lockowner)
2807 ast_channel_unlock(p->owner);
2809 /* Clear history */
2810 if (p->history) {
2811 struct sip_history *hist;
2812 while( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) )
2813 free(hist);
2814 free(p->history);
2815 p->history = NULL;
2818 for (prev = NULL, cur = iflist; cur; prev = cur, cur = cur->next) {
2819 if (cur == p) {
2820 UNLINK(cur, iflist, prev);
2821 break;
2824 if (!cur) {
2825 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
2826 return;
2829 /* remove all current packets in this dialog */
2830 while((cp = p->packets)) {
2831 p->packets = p->packets->next;
2832 if (cp->retransid > -1)
2833 ast_sched_del(sched, cp->retransid);
2834 free(cp);
2836 if (p->chanvars) {
2837 ast_variables_destroy(p->chanvars);
2838 p->chanvars = NULL;
2840 ast_mutex_destroy(&p->lock);
2842 ast_string_field_free_all(p);
2844 free(p);
2847 /*! \brief update_call_counter: Handle call_limit for SIP users
2848 * Setting a call-limit will cause calls above the limit not to be accepted.
2850 * Remember that for a type=friend, there's one limit for the user and
2851 * another for the peer, not a combined call limit.
2852 * This will cause unexpected behaviour in subscriptions, since a "friend"
2853 * is *two* devices in Asterisk, not one.
2855 * Thought: For realtime, we should propably update storage with inuse counter...
2857 * \return 0 if call is ok (no call limit, below treshold)
2858 * -1 on rejection of call
2861 static int update_call_counter(struct sip_pvt *fup, int event)
2863 char name[256];
2864 int *inuse, *call_limit, *inringing = NULL;
2865 int outgoing = ast_test_flag(&fup->flags[0], SIP_OUTGOING);
2866 struct sip_user *u = NULL;
2867 struct sip_peer *p = NULL;
2869 if (option_debug > 2)
2870 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
2871 /* Test if we need to check call limits, in order to avoid
2872 realtime lookups if we do not need it */
2873 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT))
2874 return 0;
2876 ast_copy_string(name, fup->username, sizeof(name));
2878 /* Check the list of users */
2879 if (!outgoing) /* Only check users for incoming calls */
2880 u = find_user(name, 1);
2882 if (u) {
2883 inuse = &u->inUse;
2884 call_limit = &u->call_limit;
2885 p = NULL;
2886 } else {
2887 /* Try to find peer */
2888 if (!p)
2889 p = find_peer(fup->peername, NULL, 1);
2890 if (p) {
2891 inuse = &p->inUse;
2892 call_limit = &p->call_limit;
2893 inringing = &p->inRinging;
2894 ast_copy_string(name, fup->peername, sizeof(name));
2895 } else {
2896 if (option_debug > 1)
2897 ast_log(LOG_DEBUG, "%s is not a local device, no call limit\n", name);
2898 return 0;
2901 switch(event) {
2902 /* incoming and outgoing affects the inUse counter */
2903 case DEC_CALL_LIMIT:
2904 if ( *inuse > 0 ) {
2905 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT))
2906 (*inuse)--;
2907 } else {
2908 *inuse = 0;
2910 if (inringing) {
2911 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
2912 if (*inringing > 0)
2913 (*inringing)--;
2914 else
2915 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", fup->peername);
2916 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
2919 if (option_debug > 1 || sipdebug) {
2920 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
2922 break;
2923 case INC_CALL_RINGING:
2924 case INC_CALL_LIMIT:
2925 if (*call_limit > 0 ) {
2926 if (*inuse >= *call_limit) {
2927 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);
2928 if (u)
2929 ASTOBJ_UNREF(u, sip_destroy_user);
2930 else
2931 ASTOBJ_UNREF(p, sip_destroy_peer);
2932 return -1;
2935 if (inringing && (event == INC_CALL_RINGING)) {
2936 if (!ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
2937 (*inringing)++;
2938 ast_set_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
2941 /* Continue */
2942 (*inuse)++;
2943 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
2944 if (option_debug > 1 || sipdebug) {
2945 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
2947 break;
2948 case DEC_CALL_RINGING:
2949 if (inringing) {
2950 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
2951 if (*inringing > 0)
2952 (*inringing)--;
2953 else
2954 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", p->name);
2955 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
2958 break;
2959 default:
2960 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
2962 if (p)
2963 ast_device_state_changed("SIP/%s", p->name);
2964 if (u)
2965 ASTOBJ_UNREF(u, sip_destroy_user);
2966 else
2967 ASTOBJ_UNREF(p, sip_destroy_peer);
2968 return 0;
2971 /*! \brief Destroy SIP call structure */
2972 static void sip_destroy(struct sip_pvt *p)
2974 ast_mutex_lock(&iflock);
2975 if (option_debug > 2)
2976 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
2977 __sip_destroy(p, 1);
2978 ast_mutex_unlock(&iflock);
2981 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
2982 static int hangup_sip2cause(int cause)
2984 /* Possible values taken from causes.h */
2986 switch(cause) {
2987 case 401: /* Unauthorized */
2988 return AST_CAUSE_CALL_REJECTED;
2989 case 403: /* Not found */
2990 return AST_CAUSE_CALL_REJECTED;
2991 case 404: /* Not found */
2992 return AST_CAUSE_UNALLOCATED;
2993 case 405: /* Method not allowed */
2994 return AST_CAUSE_INTERWORKING;
2995 case 407: /* Proxy authentication required */
2996 return AST_CAUSE_CALL_REJECTED;
2997 case 408: /* No reaction */
2998 return AST_CAUSE_NO_USER_RESPONSE;
2999 case 409: /* Conflict */
3000 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
3001 case 410: /* Gone */
3002 return AST_CAUSE_UNALLOCATED;
3003 case 411: /* Length required */
3004 return AST_CAUSE_INTERWORKING;
3005 case 413: /* Request entity too large */
3006 return AST_CAUSE_INTERWORKING;
3007 case 414: /* Request URI too large */
3008 return AST_CAUSE_INTERWORKING;
3009 case 415: /* Unsupported media type */
3010 return AST_CAUSE_INTERWORKING;
3011 case 420: /* Bad extension */
3012 return AST_CAUSE_NO_ROUTE_DESTINATION;
3013 case 480: /* No answer */
3014 return AST_CAUSE_NO_ANSWER;
3015 case 481: /* No answer */
3016 return AST_CAUSE_INTERWORKING;
3017 case 482: /* Loop detected */
3018 return AST_CAUSE_INTERWORKING;
3019 case 483: /* Too many hops */
3020 return AST_CAUSE_NO_ANSWER;
3021 case 484: /* Address incomplete */
3022 return AST_CAUSE_INVALID_NUMBER_FORMAT;
3023 case 485: /* Ambigous */
3024 return AST_CAUSE_UNALLOCATED;
3025 case 486: /* Busy everywhere */
3026 return AST_CAUSE_BUSY;
3027 case 487: /* Request terminated */
3028 return AST_CAUSE_INTERWORKING;
3029 case 488: /* No codecs approved */
3030 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3031 case 491: /* Request pending */
3032 return AST_CAUSE_INTERWORKING;
3033 case 493: /* Undecipherable */
3034 return AST_CAUSE_INTERWORKING;
3035 case 500: /* Server internal failure */
3036 return AST_CAUSE_FAILURE;
3037 case 501: /* Call rejected */
3038 return AST_CAUSE_FACILITY_REJECTED;
3039 case 502:
3040 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
3041 case 503: /* Service unavailable */
3042 return AST_CAUSE_CONGESTION;
3043 case 504: /* Gateway timeout */
3044 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
3045 case 505: /* SIP version not supported */
3046 return AST_CAUSE_INTERWORKING;
3047 case 600: /* Busy everywhere */
3048 return AST_CAUSE_USER_BUSY;
3049 case 603: /* Decline */
3050 return AST_CAUSE_CALL_REJECTED;
3051 case 604: /* Does not exist anywhere */
3052 return AST_CAUSE_UNALLOCATED;
3053 case 606: /* Not acceptable */
3054 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3055 default:
3056 return AST_CAUSE_NORMAL;
3058 /* Never reached */
3059 return 0;
3062 /*! \brief Convert Asterisk hangup causes to SIP codes
3063 \verbatim
3064 Possible values from causes.h
3065 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
3066 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
3068 In addition to these, a lot of PRI codes is defined in causes.h
3069 ...should we take care of them too ?
3071 Quote RFC 3398
3073 ISUP Cause value SIP response
3074 ---------------- ------------
3075 1 unallocated number 404 Not Found
3076 2 no route to network 404 Not found
3077 3 no route to destination 404 Not found
3078 16 normal call clearing --- (*)
3079 17 user busy 486 Busy here
3080 18 no user responding 408 Request Timeout
3081 19 no answer from the user 480 Temporarily unavailable
3082 20 subscriber absent 480 Temporarily unavailable
3083 21 call rejected 403 Forbidden (+)
3084 22 number changed (w/o diagnostic) 410 Gone
3085 22 number changed (w/ diagnostic) 301 Moved Permanently
3086 23 redirection to new destination 410 Gone
3087 26 non-selected user clearing 404 Not Found (=)
3088 27 destination out of order 502 Bad Gateway
3089 28 address incomplete 484 Address incomplete
3090 29 facility rejected 501 Not implemented
3091 31 normal unspecified 480 Temporarily unavailable
3092 \endverbatim
3094 static const char *hangup_cause2sip(int cause)
3096 switch (cause) {
3097 case AST_CAUSE_UNALLOCATED: /* 1 */
3098 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
3099 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
3100 return "404 Not Found";
3101 case AST_CAUSE_CONGESTION: /* 34 */
3102 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
3103 return "503 Service Unavailable";
3104 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
3105 return "408 Request Timeout";
3106 case AST_CAUSE_NO_ANSWER: /* 19 */
3107 return "480 Temporarily unavailable";
3108 case AST_CAUSE_CALL_REJECTED: /* 21 */
3109 return "403 Forbidden";
3110 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
3111 return "410 Gone";
3112 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
3113 return "480 Temporarily unavailable";
3114 case AST_CAUSE_INVALID_NUMBER_FORMAT:
3115 return "484 Address incomplete";
3116 case AST_CAUSE_USER_BUSY:
3117 return "486 Busy here";
3118 case AST_CAUSE_FAILURE:
3119 return "500 Server internal failure";
3120 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
3121 return "501 Not Implemented";
3122 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
3123 return "503 Service Unavailable";
3124 /* Used in chan_iax2 */
3125 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
3126 return "502 Bad Gateway";
3127 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
3128 return "488 Not Acceptable Here";
3130 case AST_CAUSE_NOTDEFINED:
3131 default:
3132 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
3133 return NULL;
3136 /* Never reached */
3137 return 0;
3141 /*! \brief sip_hangup: Hangup SIP call
3142 * Part of PBX interface, called from ast_hangup */
3143 static int sip_hangup(struct ast_channel *ast)
3145 struct sip_pvt *p = ast->tech_pvt;
3146 int needcancel = FALSE;
3147 struct ast_flags locflags = {0};
3148 struct ast_channel *oldowner = ast;
3150 if (!p) {
3151 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
3152 return 0;
3155 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
3156 if (option_debug >3)
3157 ast_log(LOG_DEBUG, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
3158 if (p->autokillid > -1)
3159 sip_cancel_destroy(p);
3160 sip_scheddestroy(p, 32000);
3161 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
3162 ast_clear_flag(&p->flags[0], SIP_NEEDDESTROY);
3163 p->owner->tech_pvt = NULL;
3164 p->owner = NULL; /* Owner will be gone after we return, so take it away */
3165 return 0;
3167 if (option_debug) {
3168 if (ast_test_flag(ast, AST_FLAG_ZOMBIE) && p->refer && option_debug)
3169 ast_log(LOG_DEBUG, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
3170 else
3171 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
3173 if (option_debug && ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
3174 ast_log(LOG_DEBUG, "Hanging up zombie call. Be scared.\n");
3177 ast_mutex_lock(&p->lock);
3178 if (option_debug && sipdebug)
3179 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
3180 update_call_counter(p, DEC_CALL_LIMIT);
3182 /* Determine how to disconnect */
3183 if (p->owner != ast) {
3184 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
3185 ast_mutex_unlock(&p->lock);
3186 return 0;
3188 /* If the call is not UP, we need to send CANCEL instead of BYE */
3189 if (ast->_state != AST_STATE_UP) {
3190 needcancel = TRUE;
3191 if (option_debug > 3)
3192 ast_log(LOG_DEBUG, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
3195 /* Disconnect */
3196 p = ast->tech_pvt;
3197 if (p->vad)
3198 ast_dsp_free(p->vad);
3200 p->owner = NULL;
3201 ast->tech_pvt = NULL;
3203 ast_atomic_fetchadd_int(&usecnt, -1);
3204 ast_update_use_count();
3206 ast_set_flag(&locflags, SIP_NEEDDESTROY);
3208 /* Start the process if it's not already started */
3209 if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
3210 if (needcancel) { /* Outgoing call, not up */
3211 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3212 /* stop retransmitting an INVITE that has not received a response */
3213 __sip_pretend_ack(p);
3215 /* if we can't send right now, mark it pending */
3216 if (!ast_test_flag(&p->flags[0], SIP_CAN_BYE)) {
3217 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3218 } else {
3219 /* Send a new request: CANCEL */
3220 transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, FALSE);
3221 /* Actually don't destroy us yet, wait for the 487 on our original
3222 INVITE, but do set an autodestruct just in case we never get it. */
3223 ast_clear_flag(&locflags, SIP_NEEDDESTROY);
3225 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
3227 if ( p->initid != -1 ) {
3228 /* channel still up - reverse dec of inUse counter
3229 only if the channel is not auto-congested */
3230 update_call_counter(p, INC_CALL_LIMIT);
3232 } else { /* Incoming call, not up */
3233 const char *res;
3234 if (ast->hangupcause && (res = hangup_cause2sip(ast->hangupcause)))
3235 transmit_response_reliable(p, res, &p->initreq);
3236 else
3237 transmit_response_reliable(p, "603 Declined", &p->initreq);
3239 } else { /* Call is in UP state, send BYE */
3240 if (!p->pendinginvite) {
3241 char *audioqos = "";
3242 char *videoqos = "";
3243 if (p->rtp)
3244 audioqos = ast_rtp_get_quality(p->rtp);
3245 if (p->vrtp)
3246 videoqos = ast_rtp_get_quality(p->vrtp);
3247 /* Send a hangup */
3248 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3250 /* Get RTCP quality before end of call */
3251 if (recordhistory) {
3252 if (p->rtp)
3253 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
3254 if (p->vrtp)
3255 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
3257 if (p->rtp && oldowner)
3258 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
3259 if (p->vrtp && oldowner)
3260 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
3261 } else {
3262 /* Note we will need a BYE when this all settles out
3263 but we can't send one while we have "INVITE" outstanding. */
3264 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3265 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
3269 ast_copy_flags(&p->flags[0], &locflags, SIP_NEEDDESTROY);
3270 ast_mutex_unlock(&p->lock);
3271 return 0;
3274 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
3275 static void try_suggested_sip_codec(struct sip_pvt *p)
3277 int fmt;
3278 const char *codec;
3280 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
3281 if (!codec)
3282 return;
3284 fmt = ast_getformatbyname(codec);
3285 if (fmt) {
3286 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
3287 if (p->jointcapability & fmt) {
3288 p->jointcapability &= fmt;
3289 p->capability &= fmt;
3290 } else
3291 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
3292 } else
3293 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
3294 return;
3297 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
3298 * Part of PBX interface */
3299 static int sip_answer(struct ast_channel *ast)
3301 int res = 0;
3302 struct sip_pvt *p = ast->tech_pvt;
3304 ast_mutex_lock(&p->lock);
3305 if (ast->_state != AST_STATE_UP) {
3306 try_suggested_sip_codec(p);
3308 ast_setstate(ast, AST_STATE_UP);
3309 if (option_debug)
3310 ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name);
3311 if (p->t38.state == T38_PEER_DIRECT) {
3312 p->t38.state = T38_ENABLED;
3313 if (option_debug > 1)
3314 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
3315 res = transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
3316 } else {
3317 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
3320 ast_mutex_unlock(&p->lock);
3321 return res;
3324 /*! \brief Send frame to media channel (rtp) */
3325 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
3327 struct sip_pvt *p = ast->tech_pvt;
3328 int res = 0;
3330 switch (frame->frametype) {
3331 case AST_FRAME_VOICE:
3332 if (!(frame->subclass & ast->nativeformats)) {
3333 char s1[512], s2[512], s3[512];
3334 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
3335 frame->subclass,
3336 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
3337 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
3338 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
3339 ast->readformat,
3340 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
3341 ast->writeformat);
3342 return 0;
3344 if (p) {
3345 ast_mutex_lock(&p->lock);
3346 if (p->rtp) {
3347 /* If channel is not up, activate early media session */
3348 if ((ast->_state != AST_STATE_UP) &&
3349 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3350 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3351 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3352 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3354 p->lastrtptx = time(NULL);
3355 res = ast_rtp_write(p->rtp, frame);
3357 ast_mutex_unlock(&p->lock);
3359 break;
3360 case AST_FRAME_VIDEO:
3361 if (p) {
3362 ast_mutex_lock(&p->lock);
3363 if (p->vrtp) {
3364 /* Activate video early media */
3365 if ((ast->_state != AST_STATE_UP) &&
3366 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3367 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3368 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3369 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3371 p->lastrtptx = time(NULL);
3372 res = ast_rtp_write(p->vrtp, frame);
3374 ast_mutex_unlock(&p->lock);
3376 break;
3377 case AST_FRAME_IMAGE:
3378 return 0;
3379 break;
3380 case AST_FRAME_MODEM:
3381 if (p) {
3382 ast_mutex_lock(&p->lock);
3383 if (p->udptl) {
3384 if ((ast->_state != AST_STATE_UP) &&
3385 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3386 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3387 transmit_response_with_t38_sdp(p, "183 Session Progress", &p->initreq, XMIT_RELIABLE);
3388 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3390 res = ast_udptl_write(p->udptl, frame);
3392 ast_mutex_unlock(&p->lock);
3394 break;
3395 default:
3396 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
3397 return 0;
3400 return res;
3403 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
3404 Basically update any ->owner links */
3405 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
3407 int ret = -1;
3408 struct sip_pvt *p;
3410 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
3411 ast_log(LOG_DEBUG, "New channel is zombie\n");
3412 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
3413 ast_log(LOG_DEBUG, "Old channel is zombie\n");
3415 if (!newchan || !newchan->tech_pvt) {
3416 if (!newchan)
3417 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
3418 else
3419 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
3420 return -1;
3422 p = newchan->tech_pvt;
3424 ast_mutex_lock(&p->lock);
3425 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
3426 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
3427 if (p->owner != oldchan)
3428 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
3429 else {
3430 p->owner = newchan;
3431 ret = 0;
3433 if (option_debug > 2)
3434 ast_log(LOG_DEBUG, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
3436 ast_mutex_unlock(&p->lock);
3437 return ret;
3440 /*! \brief Send DTMF character on SIP channel
3441 within one call, we're able to transmit in many methods simultaneously */
3442 static int sip_senddigit(struct ast_channel *ast, char digit)
3444 struct sip_pvt *p = ast->tech_pvt;
3445 int res = 0;
3447 ast_mutex_lock(&p->lock);
3448 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
3449 case SIP_DTMF_INFO:
3450 transmit_info_with_digit(p, digit);
3451 break;
3452 case SIP_DTMF_RFC2833:
3453 if (p->rtp)
3454 ast_rtp_senddigit(p->rtp, digit);
3455 break;
3456 case SIP_DTMF_INBAND:
3457 res = -1;
3458 break;
3460 ast_mutex_unlock(&p->lock);
3461 return res;
3464 /*! \brief Transfer SIP call */
3465 static int sip_transfer(struct ast_channel *ast, const char *dest)
3467 struct sip_pvt *p = ast->tech_pvt;
3468 int res;
3470 ast_mutex_lock(&p->lock);
3471 if (ast->_state == AST_STATE_RING)
3472 res = sip_sipredirect(p, dest);
3473 else
3474 res = transmit_refer(p, dest);
3475 ast_mutex_unlock(&p->lock);
3476 return res;
3479 /*! \brief Play indication to user
3480 * With SIP a lot of indications is sent as messages, letting the device play
3481 the indication - busy signal, congestion etc
3482 \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
3484 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
3486 struct sip_pvt *p = ast->tech_pvt;
3487 int res = 0;
3489 ast_mutex_lock(&p->lock);
3490 switch(condition) {
3491 case AST_CONTROL_RINGING:
3492 if (ast->_state == AST_STATE_RING) {
3493 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
3494 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
3495 /* Send 180 ringing if out-of-band seems reasonable */
3496 transmit_response(p, "180 Ringing", &p->initreq);
3497 ast_set_flag(&p->flags[0], SIP_RINGING);
3498 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
3499 break;
3500 } else {
3501 /* Well, if it's not reasonable, just send in-band */
3504 res = -1;
3505 break;
3506 case AST_CONTROL_BUSY:
3507 if (ast->_state != AST_STATE_UP) {
3508 transmit_response(p, "486 Busy Here", &p->initreq);
3509 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
3510 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
3511 break;
3513 res = -1;
3514 break;
3515 case AST_CONTROL_CONGESTION:
3516 if (ast->_state != AST_STATE_UP) {
3517 transmit_response(p, "503 Service Unavailable", &p->initreq);
3518 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
3519 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
3520 break;
3522 res = -1;
3523 break;
3524 case AST_CONTROL_PROCEEDING:
3525 if ((ast->_state != AST_STATE_UP) &&
3526 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3527 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3528 transmit_response(p, "100 Trying", &p->initreq);
3529 break;
3531 res = -1;
3532 break;
3533 case AST_CONTROL_PROGRESS:
3534 if ((ast->_state != AST_STATE_UP) &&
3535 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3536 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3537 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3538 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3539 break;
3541 res = -1;
3542 break;
3543 case AST_CONTROL_HOLD:
3544 ast_moh_start(ast, data, p->mohinterpret);
3545 break;
3546 case AST_CONTROL_UNHOLD:
3547 ast_moh_stop(ast);
3548 break;
3549 case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
3550 if (p->vrtp && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
3551 transmit_info_with_vidupdate(p);
3552 /* ast_rtcp_send_h261fur(p->vrtp); */
3553 } else
3554 res = -1;
3555 break;
3556 case -1:
3557 res = -1;
3558 break;
3559 default:
3560 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
3561 res = -1;
3562 break;
3564 ast_mutex_unlock(&p->lock);
3565 return res;
3570 /*! \brief Initiate a call in the SIP channel
3571 called from sip_request_call (calls from the pbx ) for outbound channels
3572 and from handle_request_invite for inbound channels
3575 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
3577 struct ast_channel *tmp;
3578 struct ast_variable *v = NULL;
3579 int fmt;
3580 int what;
3581 int needvideo = 0;
3583 ast_mutex_unlock(&i->lock);
3584 /* Don't hold a sip pvt lock while we allocate a channel */
3585 tmp = ast_channel_alloc(1);
3586 ast_mutex_lock(&i->lock);
3587 if (!tmp) {
3588 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
3589 return NULL;
3591 tmp->tech = &sip_tech;
3593 /* Select our native format based on codec preference until we receive
3594 something from another device to the contrary. */
3595 if (i->jointcapability) /* The joint capabilities of us and peer */
3596 what = i->jointcapability;
3597 else if (i->capability) /* Our configured capability for this peer */
3598 what = i->capability;
3599 else
3600 what = global_capability; /* Global codec support */
3602 /* Set the native formats for audio and merge in video */
3603 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
3604 if (option_debug > 2) {
3605 char buf[BUFSIZ];
3606 ast_log(LOG_DEBUG, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, BUFSIZ, tmp->nativeformats));
3607 ast_log(LOG_DEBUG, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, BUFSIZ, i->jointcapability));
3608 ast_log(LOG_DEBUG, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, BUFSIZ, i->capability));
3609 ast_log(LOG_DEBUG, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, BUFSIZ, ast_codec_choose(&i->prefs, what, 1)));
3610 if (i->prefcodec)
3611 ast_log(LOG_DEBUG, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, BUFSIZ, i->prefcodec));
3614 /* XXX Why are we choosing a codec from the native formats?? */
3615 fmt = ast_best_codec(tmp->nativeformats);
3617 /* If we have a prefcodec setting, we have an inbound channel that set a
3618 preferred format for this call. Otherwise, we check the jointcapability
3619 We also check for vrtp. If it's not there, we are not allowed do any video anyway.
3621 if (i->vrtp) {
3622 if (i->prefcodec)
3623 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK; /* Outbound call */
3624 else
3625 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK; /* Inbound call */
3628 if (option_debug > 2) {
3629 if (needvideo)
3630 ast_log(LOG_DEBUG, "This channel can handle video! HOLLYWOOD next!\n");
3631 else
3632 ast_log(LOG_DEBUG, "This channel will not be able to handle video.\n");
3636 if (title)
3637 ast_string_field_build(tmp, name, "SIP/%s-%08x", title, (int)(long) i);
3638 else if (strchr(i->fromdomain,':'))
3639 ast_string_field_build(tmp, name, "SIP/%s-%08x", strchr(i->fromdomain,':') + 1, (int)(long) i);
3640 else
3641 ast_string_field_build(tmp, name, "SIP/%s-%08x", i->fromdomain, (int)(long) i);
3643 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
3644 i->vad = ast_dsp_new();
3645 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
3646 if (global_relaxdtmf)
3647 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
3649 if (i->rtp) {
3650 tmp->fds[0] = ast_rtp_fd(i->rtp);
3651 tmp->fds[1] = ast_rtcp_fd(i->rtp);
3653 if (needvideo && i->vrtp) {
3654 tmp->fds[2] = ast_rtp_fd(i->vrtp);
3655 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
3657 if (i->udptl) {
3658 tmp->fds[5] = ast_udptl_fd(i->udptl);
3660 if (state == AST_STATE_RING)
3661 tmp->rings = 1;
3662 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
3663 tmp->writeformat = fmt;
3664 tmp->rawwriteformat = fmt;
3665 tmp->readformat = fmt;
3666 tmp->rawreadformat = fmt;
3667 tmp->tech_pvt = i;
3669 tmp->callgroup = i->callgroup;
3670 tmp->pickupgroup = i->pickupgroup;
3671 tmp->cid.cid_pres = i->callingpres;
3672 if (!ast_strlen_zero(i->accountcode))
3673 ast_string_field_set(tmp, accountcode, i->accountcode);
3674 if (i->amaflags)
3675 tmp->amaflags = i->amaflags;
3676 if (!ast_strlen_zero(i->language))
3677 ast_string_field_set(tmp, language, i->language);
3678 i->owner = tmp;
3679 ast_atomic_fetchadd_int(&usecnt, 1);
3680 ast_update_use_count();
3681 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
3682 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
3684 /* Don't use ast_set_callerid() here because it will
3685 * generate a NewCallerID event before the NewChannel event */
3686 tmp->cid.cid_num = ast_strdup(i->cid_num);
3687 tmp->cid.cid_ani = ast_strdup(i->cid_num);
3688 tmp->cid.cid_name = ast_strdup(i->cid_name);
3689 if (!ast_strlen_zero(i->rdnis))
3690 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
3692 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
3693 tmp->cid.cid_dnid = ast_strdup(i->exten);
3695 tmp->priority = 1;
3696 if (!ast_strlen_zero(i->uri))
3697 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
3698 if (!ast_strlen_zero(i->domain))
3699 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
3700 if (!ast_strlen_zero(i->useragent))
3701 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
3702 if (!ast_strlen_zero(i->callid))
3703 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
3704 ast_setstate(tmp, state);
3705 if (i->rtp)
3706 ast_jb_configure(tmp, &global_jbconf);
3707 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
3708 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
3709 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
3710 ast_hangup(tmp);
3711 tmp = NULL;
3713 /* Set channel variables for this call from configuration */
3714 for (v = i->chanvars ; v ; v = v->next)
3715 pbx_builtin_setvar_helper(tmp,v->name,v->value);
3717 if (recordhistory)
3718 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
3720 return tmp;
3723 /*! \brief Reads one line of SIP message body */
3724 static char *get_body_by_line(const char *line, const char *name, int nameLen)
3726 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=')
3727 return ast_skip_blanks(line + nameLen + 1);
3729 return "";
3732 /*! \brief Lookup 'name' in the SDP starting
3733 * at the 'start' line. Returns the matching line, and 'start'
3734 * is updated with the next line number.
3736 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
3738 int len = strlen(name);
3740 while (*start < req->sdp_end) {
3741 const char *r = get_body_by_line(req->line[(*start)++], name, len);
3742 if (r[0] != '\0')
3743 return r;
3746 return "";
3749 /*! \brief Get a line from an SDP message body */
3750 static const char *get_sdp(struct sip_request *req, const char *name)
3752 int dummy = 0;
3754 return get_sdp_iterate(&dummy, req, name);
3757 /*! \brief Get a specific line from the message body */
3758 static char *get_body(struct sip_request *req, char *name)
3760 int x;
3761 int len = strlen(name);
3762 char *r;
3764 for (x = 0; x < req->lines; x++) {
3765 r = get_body_by_line(req->line[x], name, len);
3766 if (r[0] != '\0')
3767 return r;
3770 return "";
3773 /*! \brief Find compressed SIP alias */
3774 static const char *find_alias(const char *name, const char *_default)
3776 /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
3777 static const struct cfalias {
3778 char * const fullname;
3779 char * const shortname;
3780 } aliases[] = {
3781 { "Content-Type", "c" },
3782 { "Content-Encoding", "e" },
3783 { "From", "f" },
3784 { "Call-ID", "i" },
3785 { "Contact", "m" },
3786 { "Content-Length", "l" },
3787 { "Subject", "s" },
3788 { "To", "t" },
3789 { "Supported", "k" },
3790 { "Refer-To", "r" },
3791 { "Referred-By", "b" },
3792 { "Allow-Events", "u" },
3793 { "Event", "o" },
3794 { "Via", "v" },
3795 { "Accept-Contact", "a" },
3796 { "Reject-Contact", "j" },
3797 { "Request-Disposition", "d" },
3798 { "Session-Expires", "x" },
3800 int x;
3802 for (x=0; x<sizeof(aliases) / sizeof(aliases[0]); x++)
3803 if (!strcasecmp(aliases[x].fullname, name))
3804 return aliases[x].shortname;
3806 return _default;
3809 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
3811 int pass;
3814 * Technically you can place arbitrary whitespace both before and after the ':' in
3815 * a header, although RFC3261 clearly says you shouldn't before, and place just
3816 * one afterwards. If you shouldn't do it, what absolute idiot decided it was
3817 * a good idea to say you can do it, and if you can do it, why in the hell would.
3818 * you say you shouldn't.
3819 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
3820 * and we always allow spaces after that for compatibility.
3822 for (pass = 0; name && pass < 2;pass++) {
3823 int x, len = strlen(name);
3824 for (x=*start; x<req->headers; x++) {
3825 if (!strncasecmp(req->header[x], name, len)) {
3826 char *r = req->header[x] + len; /* skip name */
3827 if (pedanticsipchecking)
3828 r = ast_skip_blanks(r);
3830 if (*r == ':') {
3831 *start = x+1;
3832 return ast_skip_blanks(r+1);
3836 if (pass == 0) /* Try aliases */
3837 name = find_alias(name, NULL);
3840 /* Don't return NULL, so get_header is always a valid pointer */
3841 return "";
3844 /*! \brief Get header from SIP request */
3845 static const char *get_header(const struct sip_request *req, const char *name)
3847 int start = 0;
3848 return __get_header(req, name, &start);
3851 /*! \brief Read RTP from network */
3852 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
3854 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
3855 struct ast_frame *f;
3857 if (!p->rtp) {
3858 /* We have no RTP allocated for this channel */
3859 return &ast_null_frame;
3862 switch(ast->fdno) {
3863 case 0:
3864 f = ast_rtp_read(p->rtp); /* RTP Audio */
3865 break;
3866 case 1:
3867 f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
3868 break;
3869 case 2:
3870 f = ast_rtp_read(p->vrtp); /* RTP Video */
3871 break;
3872 case 3:
3873 f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
3874 break;
3875 case 5:
3876 f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
3877 break;
3878 default:
3879 f = &ast_null_frame;
3881 /* Don't forward RFC2833 if we're not supposed to */
3882 if (f && (f->frametype == AST_FRAME_DTMF) &&
3883 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833))
3884 return &ast_null_frame;
3886 if (p->owner) {
3887 /* We already hold the channel lock */
3888 if (f->frametype == AST_FRAME_VOICE) {
3889 if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
3890 if (option_debug)
3891 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
3892 p->owner->nativeformats = (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
3893 ast_set_read_format(p->owner, p->owner->readformat);
3894 ast_set_write_format(p->owner, p->owner->writeformat);
3896 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
3897 f = ast_dsp_process(p->owner, p->vad, f);
3898 if (f && f->frametype == AST_FRAME_DTMF) {
3899 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && f->subclass == 'f') {
3900 if (option_debug)
3901 ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
3902 *faxdetect = 1;
3903 } else if (option_debug) {
3904 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
3910 return f;
3913 /*! \brief Read SIP RTP from channel */
3914 static struct ast_frame *sip_read(struct ast_channel *ast)
3916 struct ast_frame *fr;
3917 struct sip_pvt *p = ast->tech_pvt;
3918 int faxdetected = FALSE;
3920 ast_mutex_lock(&p->lock);
3921 fr = sip_rtp_read(ast, p, &faxdetected);
3922 p->lastrtprx = time(NULL);
3924 /* If we are NOT bridged to another channel, and we have detected fax tone we issue T38 re-invite to a peer */
3925 /* 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 */
3926 if (faxdetected && ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && (p->t38.state == T38_DISABLED) && !(ast_bridged_channel(ast))) {
3927 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
3928 if (!p->pendinginvite) {
3929 if (option_debug > 2)
3930 ast_log(LOG_DEBUG, "Sending reinvite on SIP (%s) for T.38 negotiation.\n",ast->name);
3931 p->t38.state = T38_LOCAL_REINVITE;
3932 transmit_reinvite_with_t38_sdp(p);
3933 if (option_debug > 1)
3934 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s", p->t38.state, ast->name);
3936 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
3937 if (option_debug > 2)
3938 ast_log(LOG_DEBUG, "Deferring reinvite on SIP (%s) - it will be re-negotiated for T.38\n", ast->name);
3939 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
3943 ast_mutex_unlock(&p->lock);
3944 return fr;
3948 /*! \brief Generate 32 byte random string for callid's etc */
3949 static char *generate_random_string(char *buf, size_t size)
3951 long val[4];
3952 int x;
3954 for (x=0; x<4; x++)
3955 val[x] = ast_random();
3956 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
3958 return buf;
3961 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
3962 static void build_callid_pvt(struct sip_pvt *pvt)
3964 char buf[33];
3966 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip));
3968 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
3972 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
3973 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
3975 char buf[33];
3977 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
3979 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
3982 /*! \brief Make our SIP dialog tag */
3983 static void make_our_tag(char *tagbuf, size_t len)
3985 snprintf(tagbuf, len, "as%08lx", ast_random());
3988 /*! \brief Allocate SIP_PVT structure and set defaults */
3989 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
3990 int useglobal_nat, const int intended_method)
3992 struct sip_pvt *p;
3994 if (!(p = ast_calloc(1, sizeof(*p))))
3995 return NULL;
3997 if (ast_string_field_init(p, 512)) {
3998 free(p);
3999 return NULL;
4002 ast_mutex_init(&p->lock);
4004 p->method = intended_method;
4005 p->initid = -1;
4006 p->autokillid = -1;
4007 p->subscribed = NONE;
4008 p->stateid = -1;
4009 p->prefs = default_prefs; /* Set default codecs for this call */
4011 if (intended_method != SIP_OPTIONS) /* Peerpoke has it's own system */
4012 p->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
4014 if (sin) {
4015 p->sa = *sin;
4016 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
4017 p->ourip = __ourip;
4018 } else
4019 p->ourip = __ourip;
4021 /* Copy global flags to this PVT at setup. */
4022 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
4023 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
4025 p->branch = ast_random();
4026 make_our_tag(p->tag, sizeof(p->tag));
4027 p->ocseq = INITIAL_CSEQ;
4029 if (sip_methods[intended_method].need_rtp) {
4030 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
4031 /* If the global videosupport flag is on, we always create a RTP interface for video */
4032 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
4033 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
4034 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
4035 p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
4036 if (!p->rtp || (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)) {
4037 ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n",
4038 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video" : "", strerror(errno));
4039 ast_mutex_destroy(&p->lock);
4040 if (p->chanvars) {
4041 ast_variables_destroy(p->chanvars);
4042 p->chanvars = NULL;
4044 free(p);
4045 return NULL;
4047 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_INFO);
4048 ast_rtp_settos(p->rtp, global_tos_audio);
4049 if (p->vrtp) {
4050 ast_rtp_settos(p->vrtp, global_tos_video);
4051 ast_rtp_setdtmf(p->vrtp, 0);
4053 if (p->udptl)
4054 ast_udptl_settos(p->udptl, global_tos_audio);
4055 p->rtptimeout = global_rtptimeout;
4056 p->rtpholdtimeout = global_rtpholdtimeout;
4057 p->rtpkeepalive = global_rtpkeepalive;
4058 p->maxcallbitrate = default_maxcallbitrate;
4061 if (useglobal_nat && sin) {
4062 int natflags;
4063 /* Setup NAT structure according to global settings if we have an address */
4064 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
4065 p->recv = *sin;
4066 natflags = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE;
4067 if (p->rtp)
4068 ast_rtp_setnat(p->rtp, natflags);
4069 if (p->vrtp)
4070 ast_rtp_setnat(p->vrtp, natflags);
4071 if (p->udptl)
4072 ast_udptl_setnat(p->udptl, natflags);
4075 if (p->method != SIP_REGISTER)
4076 ast_string_field_set(p, fromdomain, default_fromdomain);
4077 build_via(p);
4078 if (!callid)
4079 build_callid_pvt(p);
4080 else
4081 ast_string_field_set(p, callid, callid);
4082 /* Assign default music on hold class */
4083 ast_string_field_set(p, mohinterpret, default_mohinterpret);
4084 ast_string_field_set(p, mohsuggest, default_mohsuggest);
4085 p->capability = global_capability;
4086 p->allowtransfer = global_allowtransfer;
4087 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
4088 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
4089 p->noncodeccapability |= AST_RTP_DTMF;
4090 if (p->udptl) {
4091 p->t38.capability = global_t38_capability;
4092 if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY)
4093 p->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
4094 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_FEC)
4095 p->t38.capability |= T38FAX_UDP_EC_FEC;
4096 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_NONE)
4097 p->t38.capability |= T38FAX_UDP_EC_NONE;
4098 p->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
4099 p->t38.jointcapability = p->t38.capability;
4101 ast_string_field_set(p, context, default_context);
4103 /* Add to active dialog list */
4104 ast_mutex_lock(&iflock);
4105 p->next = iflist;
4106 iflist = p;
4107 ast_mutex_unlock(&iflock);
4108 if (option_debug)
4109 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");
4110 return p;
4113 /*! \brief Connect incoming SIP message to current dialog or create new dialog structure
4114 Called by handle_request, sipsock_read */
4115 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
4117 struct sip_pvt *p;
4118 char *tag = ""; /* note, tag is never NULL */
4119 char totag[128];
4120 char fromtag[128];
4121 const char *callid = get_header(req, "Call-ID");
4122 const char *from = get_header(req, "From");
4123 const char *to = get_header(req, "To");
4124 const char *cseq = get_header(req, "Cseq");
4126 if (!callid || !to || !from || !cseq) /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
4127 return NULL; /* Invalid packet */
4129 if (pedanticsipchecking) {
4130 /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
4131 we need more to identify a branch - so we have to check branch, from
4132 and to tags to identify a call leg.
4133 For Asterisk to behave correctly, you need to turn on pedanticsipchecking
4134 in sip.conf
4136 if (gettag(req, "To", totag, sizeof(totag)))
4137 ast_set_flag(req, SIP_PKT_WITH_TOTAG); /* Used in handle_request/response */
4138 gettag(req, "From", fromtag, sizeof(fromtag));
4140 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
4142 if (option_debug > 4 )
4143 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);
4146 ast_mutex_lock(&iflock);
4147 for (p = iflist; p; p = p->next) {
4148 /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
4149 int found = FALSE;
4150 if (req->method == SIP_REGISTER)
4151 found = (!strcmp(p->callid, callid));
4152 else
4153 found = (!strcmp(p->callid, callid) &&
4154 (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ;
4156 if (option_debug > 4)
4157 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);
4159 /* If we get a new request within an existing to-tag - check the to tag as well */
4160 if (pedanticsipchecking && found && req->method != SIP_RESPONSE) { /* SIP Request */
4161 if (p->tag[0] == '\0' && totag[0]) {
4162 /* We have no to tag, but they have. Wrong dialog */
4163 found = FALSE;
4164 } else if (totag[0]) { /* Both have tags, compare them */
4165 if (strcmp(totag, p->tag)) {
4166 found = FALSE; /* This is not our packet */
4169 if (!found && option_debug > 4)
4170 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);
4174 if (found) {
4175 /* Found the call */
4176 ast_mutex_lock(&p->lock);
4177 ast_mutex_unlock(&iflock);
4178 return p;
4181 ast_mutex_unlock(&iflock);
4182 /* Allocate new call */
4183 if ((p = sip_alloc(callid, sin, 1, intended_method)))
4184 ast_mutex_lock(&p->lock);
4185 return p;
4188 /*! \brief Parse register=> line in sip.conf and add to registry */
4189 static int sip_register(char *value, int lineno)
4191 struct sip_registry *reg;
4192 char copy[256];
4193 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
4194 char *porta=NULL;
4195 char *contact=NULL;
4196 char *stringp=NULL;
4198 if (!value)
4199 return -1;
4200 ast_copy_string(copy, value, sizeof(copy));
4201 stringp=copy;
4202 username = stringp;
4203 hostname = strrchr(stringp, '@');
4204 if (hostname)
4205 *hostname++ = '\0';
4206 if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
4207 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
4208 return -1;
4210 stringp = username;
4211 username = strsep(&stringp, ":");
4212 if (username) {
4213 secret = strsep(&stringp, ":");
4214 if (secret)
4215 authuser = strsep(&stringp, ":");
4217 stringp = hostname;
4218 hostname = strsep(&stringp, "/");
4219 if (hostname)
4220 contact = strsep(&stringp, "/");
4221 if (ast_strlen_zero(contact))
4222 contact = "s";
4223 stringp=hostname;
4224 hostname = strsep(&stringp, ":");
4225 porta = strsep(&stringp, ":");
4227 if (porta && !atoi(porta)) {
4228 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
4229 return -1;
4231 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
4232 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
4233 return -1;
4236 if (ast_string_field_init(reg, 256)) {
4237 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
4238 free(reg);
4239 return -1;
4242 regobjs++;
4243 ASTOBJ_INIT(reg);
4244 ast_string_field_set(reg, contact, contact);
4245 if (username)
4246 ast_string_field_set(reg, username, username);
4247 if (hostname)
4248 ast_string_field_set(reg, hostname, hostname);
4249 if (authuser)
4250 ast_string_field_set(reg, authuser, authuser);
4251 if (secret)
4252 ast_string_field_set(reg, secret, secret);
4253 reg->expire = -1;
4254 reg->timeout = -1;
4255 reg->refresh = default_expiry;
4256 reg->portno = porta ? atoi(porta) : 0;
4257 reg->callid_valid = FALSE;
4258 reg->ocseq = INITIAL_CSEQ;
4259 ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
4260 ASTOBJ_UNREF(reg,sip_registry_destroy);
4261 return 0;
4264 /*! \brief Parse multiline SIP headers into one header
4265 This is enabled if pedanticsipchecking is enabled */
4266 static int lws2sws(char *msgbuf, int len)
4268 int h = 0, t = 0;
4269 int lws = 0;
4271 for (; h < len;) {
4272 /* Eliminate all CRs */
4273 if (msgbuf[h] == '\r') {
4274 h++;
4275 continue;
4277 /* Check for end-of-line */
4278 if (msgbuf[h] == '\n') {
4279 /* Check for end-of-message */
4280 if (h + 1 == len)
4281 break;
4282 /* Check for a continuation line */
4283 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
4284 /* Merge continuation line */
4285 h++;
4286 continue;
4288 /* Propagate LF and start new line */
4289 msgbuf[t++] = msgbuf[h++];
4290 lws = 0;
4291 continue;
4293 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
4294 if (lws) {
4295 h++;
4296 continue;
4298 msgbuf[t++] = msgbuf[h++];
4299 lws = 1;
4300 continue;
4302 msgbuf[t++] = msgbuf[h++];
4303 if (lws)
4304 lws = 0;
4306 msgbuf[t] = '\0';
4307 return t;
4310 /*! \brief Parse a SIP message
4311 \note this function is used both on incoming and outgoing packets
4313 static void parse_request(struct sip_request *req)
4315 /* Divide fields by NULL's */
4316 char *c;
4317 int f = 0;
4319 c = req->data;
4321 /* First header starts immediately */
4322 req->header[f] = c;
4323 while(*c) {
4324 if (*c == '\n') {
4325 /* We've got a new header */
4326 *c = 0;
4328 if (sipdebug && option_debug > 3)
4329 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
4330 if (ast_strlen_zero(req->header[f])) {
4331 /* Line by itself means we're now in content */
4332 c++;
4333 break;
4335 if (f >= SIP_MAX_HEADERS - 1) {
4336 ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n");
4337 } else
4338 f++;
4339 req->header[f] = c + 1;
4340 } else if (*c == '\r') {
4341 /* Ignore but eliminate \r's */
4342 *c = 0;
4344 c++;
4346 /* Check for last header */
4347 if (!ast_strlen_zero(req->header[f])) {
4348 if (sipdebug && option_debug > 3)
4349 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
4350 f++;
4352 req->headers = f;
4353 /* Now we process any mime content */
4354 f = 0;
4355 req->line[f] = c;
4356 while(*c) {
4357 if (*c == '\n') {
4358 /* We've got a new line */
4359 *c = 0;
4360 if (sipdebug && option_debug > 3)
4361 ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
4362 if (f >= SIP_MAX_LINES - 1) {
4363 ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n");
4364 } else
4365 f++;
4366 req->line[f] = c + 1;
4367 } else if (*c == '\r') {
4368 /* Ignore and eliminate \r's */
4369 *c = 0;
4371 c++;
4373 /* Check for last line */
4374 if (!ast_strlen_zero(req->line[f]))
4375 f++;
4376 req->lines = f;
4377 if (*c)
4378 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
4379 /* Split up the first line parts */
4380 determine_firstline_parts(req);
4384 \brief Determine whether a SIP message contains an SDP in its body
4385 \param req the SIP request to process
4386 \return 1 if SDP found, 0 if not found
4388 Also updates req->sdp_start and req->sdp_end to indicate where the SDP
4389 lives in the message body.
4391 static int find_sdp(struct sip_request *req)
4393 const char *content_type;
4394 const char *search;
4395 char *boundary;
4396 unsigned int x;
4398 content_type = get_header(req, "Content-Type");
4400 /* if the body contains only SDP, this is easy */
4401 if (!strcasecmp(content_type, "application/sdp")) {
4402 req->sdp_start = 0;
4403 req->sdp_end = req->lines;
4404 return 1;
4407 /* if it's not multipart/mixed, there cannot be an SDP */
4408 if (strncasecmp(content_type, "multipart/mixed", 15))
4409 return 0;
4411 /* if there is no boundary marker, it's invalid */
4412 if (!(search = strcasestr(content_type, ";boundary=")))
4413 return 0;
4415 search += 10;
4417 if (ast_strlen_zero(search))
4418 return 0;
4420 /* make a duplicate of the string, with two extra characters
4421 at the beginning */
4422 boundary = ast_strdupa(search - 2);
4423 boundary[0] = boundary[1] = '-';
4425 /* search for the boundary marker, but stop when there are not enough
4426 lines left for it, the Content-Type header and at least one line of
4427 body */
4428 for (x = 0; x < (req->lines - 2); x++) {
4429 if (!strncasecmp(req->line[x], boundary, strlen(boundary)) &&
4430 !strcasecmp(req->line[x + 1], "Content-Type: application/sdp")) {
4431 req->sdp_start = x + 2;
4432 /* search for the end of the body part */
4433 for ( ; x < req->lines; x++) {
4434 if (!strncasecmp(req->line[x], boundary, strlen(boundary)))
4435 break;
4437 req->sdp_end = x;
4438 return 1;
4442 return 0;
4445 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
4446 If offer is rejected, we will not change any properties of the call
4448 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
4450 const char *m; /* SDP media offer */
4451 const char *c;
4452 const char *a;
4453 char host[258];
4454 int len = -1;
4455 int portno = -1; /*!< RTP Audio port number */
4456 int vportno = -1; /*!< RTP Video port number */
4457 int udptlportno = -1;
4458 int peert38capability = 0;
4459 char s[256];
4460 int old = 0;
4462 /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
4463 int peercapability = 0, peernoncodeccapability = 0;
4464 int vpeercapability = 0, vpeernoncodeccapability = 0;
4465 struct sockaddr_in sin; /*!< media socket address */
4466 struct sockaddr_in vsin; /*!< Video socket address */
4468 const char *codecs;
4469 struct hostent *hp; /*!< RTP Audio host IP */
4470 struct hostent *vhp = NULL; /*!< RTP video host IP */
4471 struct ast_hostent audiohp;
4472 struct ast_hostent videohp;
4473 int codec;
4474 int destiterator = 0;
4475 int iterator;
4476 int sendonly = 0;
4477 int numberofports;
4478 struct ast_channel *bridgepeer = NULL;
4479 struct ast_rtp *newaudiortp, *newvideortp; /* Buffers for codec handling */
4480 int newjointcapability; /* Negotiated capability */
4481 int newpeercapability;
4482 int newnoncodeccapability;
4483 int numberofmediastreams = 0;
4484 int debug = sip_debug_test_pvt(p);
4486 if (!p->rtp) {
4487 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
4488 return -1;
4491 /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
4492 newaudiortp = alloca(ast_rtp_alloc_size());
4493 memset(newaudiortp, 0, ast_rtp_alloc_size());
4494 ast_rtp_pt_clear(newaudiortp);
4496 newvideortp = alloca(ast_rtp_alloc_size());
4497 memset(newvideortp, 0, ast_rtp_alloc_size());
4498 ast_rtp_pt_clear(newvideortp);
4500 /* Update our last rtprx when we receive an SDP, too */
4501 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
4504 /* Try to find first media stream */
4505 m = get_sdp(req, "m");
4506 destiterator = req->sdp_start;
4507 c = get_sdp_iterate(&destiterator, req, "c");
4508 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
4509 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
4510 return -1;
4513 /* Check for IPv4 address (not IPv6 yet) */
4514 if (sscanf(c, "IN IP4 %256s", host) != 1) {
4515 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
4516 return -1;
4519 /* XXX This could block for a long time, and block the main thread! XXX */
4520 hp = ast_gethostbyname(host, &audiohp);
4521 if (!hp) {
4522 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
4523 return -1;
4525 vhp = hp; /* Copy to video address as default too */
4527 iterator = req->sdp_start;
4528 ast_set_flag(&p->flags[0], SIP_NOVIDEO);
4531 /* Find media streams in this SDP offer */
4532 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
4533 int x;
4534 int audio = FALSE;
4536 numberofports = 1;
4537 if ((sscanf(m, "audio %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
4538 (sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
4539 audio = TRUE;
4540 numberofmediastreams++;
4541 /* Found audio stream in this media definition */
4542 portno = x;
4543 /* Scan through the RTP payload types specified in a "m=" line: */
4544 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
4545 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
4546 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
4547 return -1;
4549 if (debug)
4550 ast_verbose("Found RTP audio format %d\n", codec);
4551 ast_rtp_set_m_type(newaudiortp, codec);
4553 } else if ((sscanf(m, "video %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
4554 (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
4555 /* If it is not audio - is it video ? */
4556 ast_clear_flag(&p->flags[0], SIP_NOVIDEO);
4557 numberofmediastreams++;
4558 vportno = x;
4559 /* Scan through the RTP payload types specified in a "m=" line: */
4560 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
4561 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
4562 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
4563 return -1;
4565 if (debug)
4566 ast_verbose("Found RTP video format %d\n", codec);
4567 ast_rtp_set_m_type(newvideortp, codec);
4569 } else if (p->udptl && ((sscanf(m, "image %d udptl t38%n", &x, &len) == 1))) {
4570 if (debug)
4571 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
4572 udptlportno = x;
4573 numberofmediastreams++;
4575 if (p->owner && p->lastinvite) {
4576 p->t38.state = T38_PEER_REINVITE; /* T38 Offered in re-invite from remote party */
4577 if (option_debug > 1)
4578 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>" );
4579 } else {
4580 p->t38.state = T38_PEER_DIRECT; /* T38 Offered directly from peer in first invite */
4581 if (option_debug > 1)
4582 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
4584 } else
4585 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
4586 if (numberofports > 1)
4587 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
4590 /* Check for Media-description-level-address for audio */
4591 c = get_sdp_iterate(&destiterator, req, "c");
4592 if (!ast_strlen_zero(c)) {
4593 if (sscanf(c, "IN IP4 %256s", host) != 1) {
4594 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
4595 } else {
4596 /* XXX This could block for a long time, and block the main thread! XXX */
4597 if (audio) {
4598 if ( !(hp = ast_gethostbyname(host, &audiohp)))
4599 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in secondary c= line, '%s'\n", c);
4600 } else if (!(vhp = ast_gethostbyname(host, &videohp)))
4601 ast_log(LOG_WARNING, "Unable to lookup RTP video host in secondary c= line, '%s'\n", c);
4606 if (portno == -1 && vportno == -1 && udptlportno == -1)
4607 /* No acceptable offer found in SDP - we have no ports */
4608 /* Do not change RTP or VRTP if this is a re-invite */
4609 return -2;
4611 if (numberofmediastreams > 2)
4612 /* We have too many fax, audio and/or video media streams, fail this offer */
4613 return -3;
4615 /* RTP addresses and ports for audio and video */
4616 sin.sin_family = AF_INET;
4617 vsin.sin_family = AF_INET;
4618 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
4619 if (vhp)
4620 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
4622 if (p->rtp) {
4623 if (portno > 0) {
4624 sin.sin_port = htons(portno);
4625 ast_rtp_set_peer(p->rtp, &sin);
4626 if (debug)
4627 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
4628 } else {
4629 ast_rtp_stop(p->rtp);
4630 if (debug)
4631 ast_verbose("Peer doesn't provide audio\n");
4634 /* Setup video port number */
4635 if (vportno != -1)
4636 vsin.sin_port = htons(vportno);
4638 /* Setup UDPTL port number */
4639 if (p->udptl) {
4640 if (udptlportno > 0) {
4641 sin.sin_port = htons(udptlportno);
4642 ast_udptl_set_peer(p->udptl, &sin);
4643 if (debug)
4644 ast_log(LOG_DEBUG,"Peer T.38 UDPTL is at port %s:%d\n",ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
4645 } else {
4646 ast_udptl_stop(p->udptl);
4647 if (debug)
4648 ast_log(LOG_DEBUG, "Peer doesn't provide T.38 UDPTL\n");
4652 /* Next, scan through each "a=rtpmap:" line, noting each
4653 * specified RTP payload type (with corresponding MIME subtype):
4655 /* XXX This needs to be done per media stream, since it's media stream specific */
4656 iterator = req->sdp_start;
4657 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
4658 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
4659 if (option_debug > 1) {
4660 int breakout = FALSE;
4662 /* If we're debugging, check for unsupported sdp options */
4663 if (!strncasecmp(a, "rtcp:", (size_t) 5)) {
4664 if (debug)
4665 ast_verbose("Got unsupported a:rtcp in SDP offer \n");
4666 breakout = TRUE;
4667 } else if (!strncasecmp(a, "fmtp:", (size_t) 5)) {
4668 /* Format parameters: Not supported */
4669 /* Note: This is used for codec parameters, like bitrate for
4670 G722 and video formats for H263 and H264
4671 See RFC2327 for an example */
4672 if (debug)
4673 ast_verbose("Got unsupported a:fmtp in SDP offer \n");
4674 breakout = TRUE;
4675 } else if (!strncasecmp(a, "framerate:", (size_t) 10)) {
4676 /* Video stuff: Not supported */
4677 if (debug)
4678 ast_verbose("Got unsupported a:framerate in SDP offer \n");
4679 breakout = TRUE;
4680 } else if (!strncasecmp(a, "maxprate:", (size_t) 9)) {
4681 /* Video stuff: Not supported */
4682 if (debug)
4683 ast_verbose("Got unsupported a:maxprate in SDP offer \n");
4684 breakout = TRUE;
4685 } else if (!strncasecmp(a, "crypto:", (size_t) 7)) {
4686 /* SRTP stuff, not yet supported */
4687 if (debug)
4688 ast_verbose("Got unsupported a:crypto in SDP offer \n");
4689 breakout = TRUE;
4690 } else if (!strncasecmp(a, "ptime:", (size_t) 6)) {
4691 if (debug)
4692 ast_verbose("Got unsupported a:ptime in SDP offer \n");
4693 breakout = TRUE;
4695 if (breakout) /* We have a match, skip to next header */
4696 continue;
4698 if (!strcasecmp(a, "sendonly")) {
4699 sendonly = 1;
4700 continue;
4701 } else if (!strcasecmp(a, "inactive")) {
4702 sendonly = 2;
4703 continue;
4704 } else if (!strcasecmp(a, "sendrecv")) {
4705 sendonly = 0;
4706 continue;
4707 } else if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2)
4708 continue;
4709 /* We have a rtpmap to handle */
4710 if (debug)
4711 ast_verbose("Found description format %s for ID %d\n", mimeSubtype, codec);
4713 /* Note: should really look at the 'freq' and '#chans' params too */
4714 ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
4715 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0);
4716 if (p->vrtp)
4717 ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0);
4720 if (udptlportno != -1) {
4721 int found = 0, x;
4723 old = 0;
4725 /* Scan trough the a= lines for T38 attributes and set apropriate fileds */
4726 iterator = req->sdp_start;
4727 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
4728 if ((sscanf(a, "T38FaxMaxBuffer:%d", &x) == 1)) {
4729 found = 1;
4730 if (option_debug > 2)
4731 ast_log(LOG_DEBUG,"MaxBufferSize:%d\n",x);
4733 if ((sscanf(a, "T38MaxBitRate:%d", &x) == 1)) {
4734 found = 1;
4735 if (option_debug > 2)
4736 ast_log(LOG_DEBUG,"T38MaxBitRate: %d\n",x);
4737 switch (x) {
4738 case 14400:
4739 peert38capability |= T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
4740 break;
4741 case 12000:
4742 peert38capability |= T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
4743 break;
4744 case 9600:
4745 peert38capability |= T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
4746 break;
4747 case 7200:
4748 peert38capability |= T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
4749 break;
4750 case 4800:
4751 peert38capability |= T38FAX_RATE_4800 | T38FAX_RATE_2400;
4752 break;
4753 case 2400:
4754 peert38capability |= T38FAX_RATE_2400;
4755 break;
4758 if ((sscanf(a, "T38FaxVersion:%d", &x) == 1)) {
4759 found = 1;
4760 if (option_debug > 2)
4761 ast_log(LOG_DEBUG,"FaxVersion: %d\n",x);
4762 if (x == 0)
4763 peert38capability |= T38FAX_VERSION_0;
4764 else if (x == 1)
4765 peert38capability |= T38FAX_VERSION_1;
4767 if ((sscanf(a, "T38FaxMaxDatagram:%d", &x) == 1)) {
4768 found = 1;
4769 if (option_debug > 2)
4770 ast_log(LOG_DEBUG,"FaxMaxDatagram: %d\n",x);
4771 ast_udptl_set_far_max_datagram(p->udptl, x);
4772 ast_udptl_set_local_max_datagram(p->udptl, x);
4774 if ((sscanf(a, "T38FaxFillBitRemoval:%d", &x) == 1)) {
4775 found = 1;
4776 if (option_debug > 2)
4777 ast_log(LOG_DEBUG,"FillBitRemoval: %d\n",x);
4778 if (x == 1)
4779 peert38capability |= T38FAX_FILL_BIT_REMOVAL;
4781 if ((sscanf(a, "T38FaxTranscodingMMR:%d", &x) == 1)) {
4782 found = 1;
4783 if (option_debug > 2)
4784 ast_log(LOG_DEBUG,"Transcoding MMR: %d\n",x);
4785 if (x == 1)
4786 peert38capability |= T38FAX_TRANSCODING_MMR;
4788 if ((sscanf(a, "T38FaxTranscodingJBIG:%d", &x) == 1)) {
4789 found = 1;
4790 if (option_debug > 2)
4791 ast_log(LOG_DEBUG,"Transcoding JBIG: %d\n",x);
4792 if (x == 1)
4793 peert38capability |= T38FAX_TRANSCODING_JBIG;
4795 if ((sscanf(a, "T38FaxRateManagement:%s", s) == 1)) {
4796 found = 1;
4797 if (option_debug > 2)
4798 ast_log(LOG_DEBUG,"RateMangement: %s\n", s);
4799 if (!strcasecmp(s, "localTCF"))
4800 peert38capability |= T38FAX_RATE_MANAGEMENT_LOCAL_TCF;
4801 else if (!strcasecmp(s, "transferredTCF"))
4802 peert38capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
4804 if ((sscanf(a, "T38FaxUdpEC:%s", s) == 1)) {
4805 found = 1;
4806 if (option_debug > 2)
4807 ast_log(LOG_DEBUG,"UDP EC: %s\n", s);
4808 if (!strcasecmp(s, "t38UDPRedundancy")) {
4809 peert38capability |= T38FAX_UDP_EC_REDUNDANCY;
4810 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
4811 } else if (!strcasecmp(s, "t38UDPFEC")) {
4812 peert38capability |= T38FAX_UDP_EC_FEC;
4813 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
4814 } else {
4815 peert38capability |= T38FAX_UDP_EC_NONE;
4816 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
4820 if (found) { /* Some cisco equipment returns nothing beside c= and m= lines in 200 OK T38 SDP */
4821 p->t38.peercapability = peert38capability;
4822 p->t38.jointcapability = (peert38capability & 255); /* Put everything beside supported speeds settings */
4823 peert38capability &= (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400);
4824 p->t38.jointcapability |= (peert38capability & p->t38.capability); /* Put the lower of our's and peer's speed */
4826 if (debug)
4827 ast_log(LOG_DEBUG,"Our T38 capability = (%d), peer T38 capability (%d), joint T38 capability (%d)\n",
4828 p->t38.capability,
4829 p->t38.peercapability,
4830 p->t38.jointcapability);
4831 } else {
4832 p->t38.state = T38_DISABLED;
4833 if (option_debug > 2)
4834 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
4837 /* Now gather all of the codecs that we are asked for: */
4838 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
4839 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
4841 newjointcapability = p->capability & (peercapability | vpeercapability);
4842 newpeercapability = (peercapability | vpeercapability);
4843 newnoncodeccapability = noncodeccapability & peernoncodeccapability;
4846 if (debug) {
4847 /* shame on whoever coded this.... */
4848 char s1[BUFSIZ], s2[BUFSIZ], s3[BUFSIZ], s4[BUFSIZ];
4850 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
4851 ast_getformatname_multiple(s1, BUFSIZ, p->capability),
4852 ast_getformatname_multiple(s2, BUFSIZ, newpeercapability),
4853 ast_getformatname_multiple(s3, BUFSIZ, vpeercapability),
4854 ast_getformatname_multiple(s4, BUFSIZ, newjointcapability));
4856 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
4857 ast_rtp_lookup_mime_multiple(s1, BUFSIZ, noncodeccapability, 0, 0),
4858 ast_rtp_lookup_mime_multiple(s2, BUFSIZ, peernoncodeccapability, 0, 0),
4859 ast_rtp_lookup_mime_multiple(s3, BUFSIZ, newnoncodeccapability, 0, 0));
4861 if (!newjointcapability) {
4862 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
4863 /* Do NOT Change current setting */
4864 return -1;
4867 /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
4868 they are acceptable */
4869 p->jointcapability = newjointcapability; /* Our joint codec profile for this call */
4870 p->peercapability = newpeercapability; /* The other sides capability in latest offer */
4871 p->noncodeccapability = newnoncodeccapability; /* DTMF capabilities */
4873 ast_rtp_pt_copy(p->rtp, newaudiortp);
4874 if (p->vrtp)
4875 ast_rtp_pt_copy(p->vrtp, newvideortp);
4877 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
4878 ast_clear_flag(&p->flags[0], SIP_DTMF);
4879 if (newnoncodeccapability & AST_RTP_DTMF) {
4880 /* XXX Would it be reasonable to drop the DSP at this point? XXX */
4881 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
4882 } else {
4883 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
4887 /* Setup audio port number */
4888 if (p->rtp && sin.sin_port) {
4889 ast_rtp_set_peer(p->rtp, &sin);
4890 if (debug)
4891 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
4894 /* Setup video port number */
4895 if (p->vrtp && vsin.sin_port) {
4896 ast_rtp_set_peer(p->vrtp, &vsin);
4897 if (debug)
4898 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
4901 /* Ok, we're going with this offer */
4902 if (option_debug > 1) {
4903 char buf[BUFSIZ];
4904 ast_log(LOG_DEBUG, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, BUFSIZ, p->jointcapability));
4907 if (!p->owner) /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
4908 return 0;
4910 if (option_debug > 3)
4911 ast_log(LOG_DEBUG, "We have an owner, now see if we need to change this call\n");
4913 if (!(p->owner->nativeformats & p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
4914 if (debug) {
4915 char s1[BUFSIZ], s2[BUFSIZ];
4916 ast_log(LOG_DEBUG, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
4917 ast_getformatname_multiple(s1, BUFSIZ, p->jointcapability),
4918 ast_getformatname_multiple(s2, BUFSIZ, p->owner->nativeformats));
4920 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability);
4921 ast_set_read_format(p->owner, p->owner->readformat);
4922 ast_set_write_format(p->owner, p->owner->writeformat);
4925 bridgepeer = ast_bridged_channel(p->owner);
4927 /* Turn on/off music on hold if we are holding/unholding */
4928 if ((bridgepeer = ast_bridged_channel(p->owner))) {
4929 if (sin.sin_addr.s_addr && !sendonly) {
4930 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
4931 /* Activate a re-invite */
4932 ast_queue_frame(p->owner, &ast_null_frame);
4933 } else if (!sin.sin_addr.s_addr || sendonly) {
4934 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
4935 S_OR(p->mohsuggest, NULL),
4936 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
4937 if (sendonly)
4938 ast_rtp_stop(p->rtp);
4939 /* RTCP needs to go ahead, even if we're on hold!!! */
4940 /* Activate a re-invite */
4941 ast_queue_frame(p->owner, &ast_null_frame);
4945 /* Manager Hold and Unhold events must be generated, if necessary */
4946 if (sin.sin_addr.s_addr && !sendonly) {
4947 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
4948 append_history(p, "Unhold", "%s", req->data);
4949 if (global_callevents)
4950 manager_event(EVENT_FLAG_CALL, "Unhold",
4951 "Channel: %s\r\n"
4952 "Uniqueid: %s\r\n",
4953 p->owner->name,
4954 p->owner->uniqueid);
4955 sip_peer_hold(p, 0);
4957 ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
4958 } else if (!sin.sin_addr.s_addr || sendonly ) {
4959 /* No address for RTP, we're on hold */
4960 append_history(p, "Hold", "%s", req->data);
4962 if (global_callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
4963 manager_event(EVENT_FLAG_CALL, "Hold",
4964 "Channel: %s\r\n"
4965 "Uniqueid: %s\r\n",
4966 p->owner->name,
4967 p->owner->uniqueid);
4969 if (sendonly == 1) /* One directional hold (sendonly/recvonly) */
4970 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
4971 else if (sendonly == 2) /* Inactive stream */
4972 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
4973 sip_peer_hold(p, 1);
4976 return 0;
4980 /*! \brief Add header to SIP message */
4981 static int add_header(struct sip_request *req, const char *var, const char *value)
4983 int maxlen = sizeof(req->data) - 4 - req->len; /* 4 bytes are for two \r\n ? */
4985 if (req->headers == SIP_MAX_HEADERS) {
4986 ast_log(LOG_WARNING, "Out of SIP header space\n");
4987 return -1;
4990 if (req->lines) {
4991 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
4992 return -1;
4995 if (maxlen <= 0) {
4996 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
4997 return -1;
5000 req->header[req->headers] = req->data + req->len;
5002 if (compactheaders)
5003 var = find_alias(var, var);
5005 snprintf(req->header[req->headers], maxlen, "%s: %s\r\n", var, value);
5006 req->len += strlen(req->header[req->headers]);
5007 req->headers++;
5008 if (req->headers < SIP_MAX_HEADERS)
5009 req->headers++;
5010 else
5011 ast_log(LOG_WARNING, "Out of SIP header space... Will generate broken SIP message\n");
5013 return 0;
5016 /*! \brief Add 'Content-Length' header to SIP message */
5017 static int add_header_contentLength(struct sip_request *req, int len)
5019 char clen[10];
5021 snprintf(clen, sizeof(clen), "%d", len);
5022 return add_header(req, "Content-Length", clen);
5025 /*! \brief Add content (not header) to SIP message */
5026 static int add_line(struct sip_request *req, const char *line)
5028 if (req->lines == SIP_MAX_LINES) {
5029 ast_log(LOG_WARNING, "Out of SIP line space\n");
5030 return -1;
5032 if (!req->lines) {
5033 /* Add extra empty return */
5034 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
5035 req->len += strlen(req->data + req->len);
5037 if (req->len >= sizeof(req->data) - 4) {
5038 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
5039 return -1;
5041 req->line[req->lines] = req->data + req->len;
5042 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
5043 req->len += strlen(req->line[req->lines]);
5044 req->lines++;
5045 return 0;
5048 /*! \brief Copy one header field from one request to another */
5049 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
5051 const char *tmp = get_header(orig, field);
5053 if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
5054 return add_header(req, field, tmp);
5055 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
5056 return -1;
5059 /*! \brief Copy all headers from one request to another */
5060 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
5062 int start = 0;
5063 int copied = 0;
5064 for (;;) {
5065 const char *tmp = __get_header(orig, field, &start);
5067 if (ast_strlen_zero(tmp))
5068 break;
5069 /* Add what we're responding to */
5070 add_header(req, field, tmp);
5071 copied++;
5073 return copied ? 0 : -1;
5076 /*! \brief Copy SIP VIA Headers from the request to the response
5077 \note If the client indicates that it wishes to know the port we received from,
5078 it adds ;rport without an argument to the topmost via header. We need to
5079 add the port number (from our point of view) to that parameter.
5080 We always add ;received=<ip address> to the topmost via header.
5081 Received: RFC 3261, rport RFC 3581 */
5082 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
5084 int copied = 0;
5085 int start = 0;
5087 for (;;) {
5088 char new[256];
5089 const char *oh = __get_header(orig, field, &start);
5091 if (ast_strlen_zero(oh))
5092 break;
5094 if (!copied) { /* Only check for empty rport in topmost via header */
5095 char *rport;
5097 /* Find ;rport; (empty request) */
5098 rport = strstr(oh, ";rport");
5099 if (rport && *(rport+6) == '=')
5100 rport = NULL; /* We already have a parameter to rport */
5102 if (rport && ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) {
5103 /* We need to add received port - rport */
5104 char tmp[256], *end;
5106 ast_copy_string(tmp, oh, sizeof(tmp));
5108 rport = strstr(tmp, ";rport");
5110 if (rport) {
5111 end = strchr(rport + 1, ';');
5112 if (end)
5113 memmove(rport, end, strlen(end) + 1);
5114 else
5115 *rport = '\0';
5118 /* Add rport to first VIA header if requested */
5119 /* Whoo hoo! Now we can indicate port address translation too! Just
5120 another RFC (RFC3581). I'll leave the original comments in for
5121 posterity. */
5122 snprintf(new, sizeof(new), "%s;received=%s;rport=%d",
5123 tmp, ast_inet_ntoa(p->recv.sin_addr),
5124 ntohs(p->recv.sin_port));
5125 } else {
5126 /* We should *always* add a received to the topmost via */
5127 snprintf(new, sizeof(new), "%s;received=%s",
5128 oh, ast_inet_ntoa(p->recv.sin_addr));
5130 oh = new; /* the header to copy */
5131 } /* else add the following via headers untouched */
5132 add_header(req, field, oh);
5133 copied++;
5135 if (!copied) {
5136 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
5137 return -1;
5139 return 0;
5142 /*! \brief Add route header into request per learned route */
5143 static void add_route(struct sip_request *req, struct sip_route *route)
5145 char r[BUFSIZ*2], *p;
5146 int n, rem = sizeof(r);
5148 if (!route)
5149 return;
5151 p = r;
5152 for (;route ; route = route->next) {
5153 n = strlen(route->hop);
5154 if (rem < n+3) /* we need room for ",<route>" */
5155 break;
5156 if (p != r) { /* add a separator after fist route */
5157 *p++ = ',';
5158 --rem;
5160 *p++ = '<';
5161 ast_copy_string(p, route->hop, rem); /* cannot fail */
5162 p += n;
5163 *p++ = '>';
5164 rem -= (n+2);
5166 *p = '\0';
5167 add_header(req, "Route", r);
5170 /*! \brief Set destination from SIP URI */
5171 static void set_destination(struct sip_pvt *p, char *uri)
5173 char *h, *maddr, hostname[256];
5174 int port, hn;
5175 struct hostent *hp;
5176 struct ast_hostent ahp;
5177 int debug=sip_debug_test_pvt(p);
5179 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
5180 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
5182 if (debug)
5183 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
5185 /* Find and parse hostname */
5186 h = strchr(uri, '@');
5187 if (h)
5188 ++h;
5189 else {
5190 h = uri;
5191 if (strncmp(h, "sip:", 4) == 0)
5192 h += 4;
5193 else if (strncmp(h, "sips:", 5) == 0)
5194 h += 5;
5196 hn = strcspn(h, ":;>") + 1;
5197 if (hn > sizeof(hostname))
5198 hn = sizeof(hostname);
5199 ast_copy_string(hostname, h, hn);
5200 /* XXX bug here if string has been trimmed to sizeof(hostname) */
5201 h += hn - 1;
5203 /* Is "port" present? if not default to DEFAULT_SIP_PORT */
5204 if (*h == ':') {
5205 /* Parse port */
5206 ++h;
5207 port = strtol(h, &h, 10);
5209 else
5210 port = DEFAULT_SIP_PORT;
5212 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
5213 maddr = strstr(h, "maddr=");
5214 if (maddr) {
5215 maddr += 6;
5216 hn = strspn(maddr, "0123456789.") + 1;
5217 if (hn > sizeof(hostname))
5218 hn = sizeof(hostname);
5219 ast_copy_string(hostname, maddr, hn);
5222 hp = ast_gethostbyname(hostname, &ahp);
5223 if (hp == NULL) {
5224 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
5225 return;
5227 p->sa.sin_family = AF_INET;
5228 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
5229 p->sa.sin_port = htons(port);
5230 if (debug)
5231 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
5234 /*! \brief Initialize SIP response, based on SIP request */
5235 static int init_resp(struct sip_request *resp, const char *msg)
5237 /* Initialize a response */
5238 memset(resp, 0, sizeof(*resp));
5239 resp->method = SIP_RESPONSE;
5240 resp->header[0] = resp->data;
5241 snprintf(resp->header[0], sizeof(resp->data), "SIP/2.0 %s\r\n", msg);
5242 resp->len = strlen(resp->header[0]);
5243 resp->headers++;
5244 return 0;
5247 /*! \brief Initialize SIP request */
5248 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
5250 /* Initialize a request */
5251 memset(req, 0, sizeof(*req));
5252 req->method = sipmethod;
5253 req->header[0] = req->data;
5254 snprintf(req->header[0], sizeof(req->data), "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
5255 req->len = strlen(req->header[0]);
5256 req->headers++;
5257 return 0;
5261 /*! \brief Prepare SIP response packet */
5262 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
5264 char newto[256];
5265 const char *ot;
5267 init_resp(resp, msg);
5268 copy_via_headers(p, resp, req, "Via");
5269 if (msg[0] == '2')
5270 copy_all_header(resp, req, "Record-Route");
5271 copy_header(resp, req, "From");
5272 ot = get_header(req, "To");
5273 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
5274 /* Add the proper tag if we don't have it already. If they have specified
5275 their tag, use it. Otherwise, use our own tag */
5276 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
5277 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
5278 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
5279 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
5280 else
5281 ast_copy_string(newto, ot, sizeof(newto));
5282 ot = newto;
5284 add_header(resp, "To", ot);
5285 copy_header(resp, req, "Call-ID");
5286 copy_header(resp, req, "CSeq");
5287 add_header(resp, "User-Agent", global_useragent);
5288 add_header(resp, "Allow", ALLOWED_METHODS);
5289 add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
5290 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
5291 /* For registration responses, we also need expiry and
5292 contact info */
5293 char tmp[256];
5295 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
5296 add_header(resp, "Expires", tmp);
5297 if (p->expiry) { /* Only add contact if we have an expiry time */
5298 char contact[256];
5299 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
5300 add_header(resp, "Contact", contact); /* Not when we unregister */
5302 } else if (p->our_contact[0]) {
5303 add_header(resp, "Contact", p->our_contact);
5305 return 0;
5308 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
5309 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
5311 struct sip_request *orig = &p->initreq;
5312 char stripped[80];
5313 char tmp[80];
5314 char newto[256];
5315 const char *c;
5316 const char *ot, *of;
5317 int is_strict = FALSE; /*!< Strict routing flag */
5319 memset(req, 0, sizeof(struct sip_request));
5321 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
5323 if (!seqno) {
5324 p->ocseq++;
5325 seqno = p->ocseq;
5328 if (newbranch) {
5329 p->branch ^= ast_random();
5330 build_via(p);
5333 /* Check for strict or loose router */
5334 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop,";lr") == NULL) {
5335 is_strict = TRUE;
5336 if (sipdebug)
5337 ast_log(LOG_DEBUG, "Strict routing enforced for session %s\n", p->callid);
5340 if (sipmethod == SIP_CANCEL)
5341 c = p->initreq.rlPart2; /* Use original URI */
5342 else if (sipmethod == SIP_ACK) {
5343 /* Use URI from Contact: in 200 OK (if INVITE)
5344 (we only have the contacturi on INVITEs) */
5345 if (!ast_strlen_zero(p->okcontacturi))
5346 c = is_strict ? p->route->hop : p->okcontacturi;
5347 else
5348 c = p->initreq.rlPart2;
5349 } else if (!ast_strlen_zero(p->okcontacturi))
5350 c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
5351 else if (!ast_strlen_zero(p->uri))
5352 c = p->uri;
5353 else {
5354 char *n;
5355 /* We have no URI, use To: or From: header as URI (depending on direction) */
5356 ast_copy_string(stripped, get_header(orig, (ast_test_flag(&p->flags[0], SIP_OUTGOING)) ? "To" : "From"),
5357 sizeof(stripped));
5358 n = get_in_brackets(stripped);
5359 c = strsep(&n, ";"); /* trim ; and beyond */
5361 init_req(req, sipmethod, c);
5363 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
5365 add_header(req, "Via", p->via);
5366 if (p->route) {
5367 set_destination(p, p->route->hop);
5368 add_route(req, is_strict ? p->route->next : p->route);
5371 ot = get_header(orig, "To");
5372 of = get_header(orig, "From");
5374 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
5375 as our original request, including tag (or presumably lack thereof) */
5376 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
5377 /* Add the proper tag if we don't have it already. If they have specified
5378 their tag, use it. Otherwise, use our own tag */
5379 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_strlen_zero(p->theirtag))
5380 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
5381 else if (!ast_test_flag(&p->flags[0], SIP_OUTGOING))
5382 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
5383 else
5384 snprintf(newto, sizeof(newto), "%s", ot);
5385 ot = newto;
5388 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
5389 add_header(req, "From", of);
5390 add_header(req, "To", ot);
5391 } else {
5392 add_header(req, "From", ot);
5393 add_header(req, "To", of);
5395 add_header(req, "Contact", p->our_contact);
5396 copy_header(req, orig, "Call-ID");
5397 add_header(req, "CSeq", tmp);
5399 add_header(req, "User-Agent", global_useragent);
5400 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
5402 if (!ast_strlen_zero(p->rpid))
5403 add_header(req, "Remote-Party-ID", p->rpid);
5405 return 0;
5408 /*! \brief Base transmit response function */
5409 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
5411 struct sip_request resp;
5412 int seqno = 0;
5414 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
5415 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
5416 return -1;
5418 respprep(&resp, p, msg, req);
5419 add_header_contentLength(&resp, 0);
5420 /* If we are cancelling an incoming invite for some reason, add information
5421 about the reason why we are doing this in clear text */
5422 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
5423 char buf[10];
5425 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
5426 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
5427 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
5429 return send_response(p, &resp, reliable, seqno);
5432 /*! \brief Transmit response, no retransmits */
5433 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
5435 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
5438 /*! \brief Transmit response, no retransmits */
5439 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
5441 struct sip_request resp;
5442 respprep(&resp, p, msg, req);
5443 append_date(&resp);
5444 add_header(&resp, "Unsupported", unsupported);
5445 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
5448 /*! \brief Transmit response, Make sure you get an ACK
5449 This is only used for responses to INVITEs, where we need to make sure we get an ACK
5451 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
5453 return __transmit_response(p, msg, req, XMIT_CRITICAL);
5456 /*! \brief Append date to SIP message */
5457 static void append_date(struct sip_request *req)
5459 char tmpdat[256];
5460 struct tm tm;
5461 time_t t = time(NULL);
5463 gmtime_r(&t, &tm);
5464 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
5465 add_header(req, "Date", tmpdat);
5468 /*! \brief Append date and content length before transmitting response */
5469 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
5471 struct sip_request resp;
5472 respprep(&resp, p, msg, req);
5473 append_date(&resp);
5474 add_header_contentLength(&resp, 0);
5475 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
5478 /*! \brief Append Accept header, content length before transmitting response */
5479 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
5481 struct sip_request resp;
5482 respprep(&resp, p, msg, req);
5483 add_header(&resp, "Accept", "application/sdp");
5484 add_header_contentLength(&resp, 0);
5485 return send_response(p, &resp, reliable, 0);
5488 /*! \brief Respond with authorization request */
5489 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)
5491 struct sip_request resp;
5492 char tmp[512];
5493 int seqno = 0;
5495 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
5496 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
5497 return -1;
5499 /* Stale means that they sent us correct authentication, but
5500 based it on an old challenge (nonce) */
5501 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
5502 respprep(&resp, p, msg, req);
5503 add_header(&resp, header, tmp);
5504 add_header_contentLength(&resp, 0);
5505 return send_response(p, &resp, reliable, seqno);
5508 /*! \brief Add text body to SIP message */
5509 static int add_text(struct sip_request *req, const char *text)
5511 /* XXX Convert \n's to \r\n's XXX */
5512 add_header(req, "Content-Type", "text/plain");
5513 add_header_contentLength(req, strlen(text));
5514 add_line(req, text);
5515 return 0;
5518 /*! \brief Add DTMF INFO tone to sip message */
5519 /* Always adds default duration 250 ms, regardless of what came in over the line */
5520 static int add_digit(struct sip_request *req, char digit)
5522 char tmp[256];
5524 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
5525 add_header(req, "Content-Type", "application/dtmf-relay");
5526 add_header_contentLength(req, strlen(tmp));
5527 add_line(req, tmp);
5528 return 0;
5531 /*! \brief add XML encoded media control with update */
5532 /*! \note XML: The only way to turn 0 bits of information into a few hundred. */
5533 static int add_vidupdate(struct sip_request *req)
5535 const char *xml_is_a_huge_waste_of_space =
5536 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
5537 " <media_control>\r\n"
5538 " <vc_primitive>\r\n"
5539 " <to_encoder>\r\n"
5540 " <picture_fast_update>\r\n"
5541 " </picture_fast_update>\r\n"
5542 " </to_encoder>\r\n"
5543 " </vc_primitive>\r\n"
5544 " </media_control>\r\n";
5545 add_header(req, "Content-Type", "application/media_control+xml");
5546 add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
5547 add_line(req, xml_is_a_huge_waste_of_space);
5548 return 0;
5551 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
5552 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
5553 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
5554 int debug)
5556 int rtp_code;
5558 if (debug)
5559 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
5560 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
5561 return;
5563 ast_build_string(m_buf, m_size, " %d", rtp_code);
5564 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
5565 ast_rtp_lookup_mime_subtype(1, codec,
5566 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
5567 sample_rate);
5568 if (codec == AST_FORMAT_G729A) {
5569 /* Indicate that we don't support VAD (G.729 annex B) */
5570 ast_build_string(a_buf, a_size, "a=fmtp:%d annexb=no\r\n", rtp_code);
5571 } else if (codec == AST_FORMAT_ILBC) {
5572 /* Add information about us using only 20 ms packetization */
5573 ast_build_string(a_buf, a_size, "a=fmtp:%d mode=20\r\n", rtp_code);
5578 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
5579 static int t38_get_rate(int t38cap)
5581 int maxrate = (t38cap & (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400));
5583 if (maxrate & T38FAX_RATE_14400) {
5584 if (option_debug > 1)
5585 ast_log(LOG_DEBUG, "T38MaxFaxRate 14400 found\n");
5586 return 14400;
5587 } else if (maxrate & T38FAX_RATE_12000) {
5588 if (option_debug > 1)
5589 ast_log(LOG_DEBUG, "T38MaxFaxRate 12000 found\n");
5590 return 12000;
5591 } else if (maxrate & T38FAX_RATE_9600) {
5592 if (option_debug > 1)
5593 ast_log(LOG_DEBUG, "T38MaxFaxRate 9600 found\n");
5594 return 9600;
5595 } else if (maxrate & T38FAX_RATE_7200) {
5596 if (option_debug > 1)
5597 ast_log(LOG_DEBUG, "T38MaxFaxRate 7200 found\n");
5598 return 7200;
5599 } else if (maxrate & T38FAX_RATE_4800) {
5600 if (option_debug > 1)
5601 ast_log(LOG_DEBUG, "T38MaxFaxRate 4800 found\n");
5602 return 4800;
5603 } else if (maxrate & T38FAX_RATE_2400) {
5604 if (option_debug > 1)
5605 ast_log(LOG_DEBUG, "T38MaxFaxRate 2400 found\n");
5606 return 2400;
5607 } else {
5608 if (option_debug > 1)
5609 ast_log(LOG_DEBUG, "Strange, T38MaxFaxRate NOT found in peers T38 SDP.\n");
5610 return 0;
5614 /*! \brief Add T.38 Session Description Protocol message */
5615 static int add_t38_sdp(struct sip_request *resp, struct sip_pvt *p)
5617 int len = 0;
5618 int x = 0;
5619 struct sockaddr_in udptlsin;
5620 char v[256] = "";
5621 char s[256] = "";
5622 char o[256] = "";
5623 char c[256] = "";
5624 char t[256] = "";
5625 char m_modem[256];
5626 char a_modem[1024];
5627 char *m_modem_next = m_modem;
5628 size_t m_modem_left = sizeof(m_modem);
5629 char *a_modem_next = a_modem;
5630 size_t a_modem_left = sizeof(a_modem);
5631 struct sockaddr_in udptldest = { 0, };
5632 int debug;
5634 debug = sip_debug_test_pvt(p);
5635 len = 0;
5636 if (!p->udptl) {
5637 ast_log(LOG_WARNING, "No way to add SDP without an UDPTL structure\n");
5638 return -1;
5641 if (!p->sessionid) {
5642 p->sessionid = getpid();
5643 p->sessionversion = p->sessionid;
5644 } else
5645 p->sessionversion++;
5647 /* Our T.38 end is */
5648 ast_udptl_get_us(p->udptl, &udptlsin);
5650 /* Determine T.38 UDPTL destination */
5651 if (p->udptlredirip.sin_addr.s_addr) {
5652 udptldest.sin_port = p->udptlredirip.sin_port;
5653 udptldest.sin_addr = p->udptlredirip.sin_addr;
5654 } else {
5655 udptldest.sin_addr = p->ourip;
5656 udptldest.sin_port = udptlsin.sin_port;
5659 if (debug) {
5660 ast_log(LOG_DEBUG, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(udptlsin.sin_port));
5663 /* We break with the "recommendation" and send our IP, in order that our
5664 peer doesn't have to ast_gethostbyname() us */
5666 if (debug) {
5667 ast_log(LOG_DEBUG, "Our T38 capability (%d), peer T38 capability (%d), joint capability (%d)\n",
5668 p->t38.capability,
5669 p->t38.peercapability,
5670 p->t38.jointcapability);
5672 snprintf(v, sizeof(v), "v=0\r\n");
5673 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(udptldest.sin_addr));
5674 snprintf(s, sizeof(s), "s=session\r\n");
5675 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(udptldest.sin_addr));
5676 snprintf(t, sizeof(t), "t=0 0\r\n");
5677 ast_build_string(&m_modem_next, &m_modem_left, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
5679 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_0)
5680 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:0\r\n");
5681 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_1)
5682 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:1\r\n");
5683 if ((x = t38_get_rate(p->t38.jointcapability)))
5684 ast_build_string(&a_modem_next, &a_modem_left, "a=T38MaxBitRate:%d\r\n",x);
5685 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxFillBitRemoval:%d\r\n", (p->t38.jointcapability & T38FAX_FILL_BIT_REMOVAL) ? 1 : 0);
5686 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingMMR:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_MMR) ? 1 : 0);
5687 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingJBIG:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_JBIG) ? 1 : 0);
5688 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxRateManagement:%s\r\n", (p->t38.jointcapability & T38FAX_RATE_MANAGEMENT_LOCAL_TCF) ? "localTCF" : "transferredTCF");
5689 x = ast_udptl_get_local_max_datagram(p->udptl);
5690 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxBuffer:%d\r\n",x);
5691 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxDatagram:%d\r\n",x);
5692 if (p->t38.jointcapability != T38FAX_UDP_EC_NONE)
5693 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxUdpEC:%s\r\n", (p->t38.jointcapability & T38FAX_UDP_EC_REDUNDANCY) ? "t38UDPRedundancy" : "t38UDPFEC");
5694 if (p->udptl)
5695 len = strlen(m_modem) + strlen(a_modem);
5696 add_header(resp, "Content-Type", "application/sdp");
5697 add_header_contentLength(resp, len);
5698 add_line(resp, v);
5699 add_line(resp, o);
5700 add_line(resp, s);
5701 add_line(resp, c);
5702 add_line(resp, t);
5703 add_line(resp, m_modem);
5704 add_line(resp, a_modem);
5706 /* Update lastrtprx when we send our SDP */
5707 p->lastrtprx = p->lastrtptx = time(NULL);
5709 return 0;
5713 /*! \brief Add RFC 2833 DTMF offer to SDP */
5714 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
5715 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
5716 int debug)
5718 int rtp_code;
5720 if (debug)
5721 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
5722 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
5723 return;
5725 ast_build_string(m_buf, m_size, " %d", rtp_code);
5726 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
5727 ast_rtp_lookup_mime_subtype(0, format, 0),
5728 sample_rate);
5729 if (format == AST_RTP_DTMF)
5730 /* Indicate we support DTMF and FLASH... */
5731 ast_build_string(a_buf, a_size, "a=fmtp:%d 0-16\r\n", rtp_code);
5734 /*! \brief Add Session Description Protocol message */
5735 static int add_sdp(struct sip_request *resp, struct sip_pvt *p)
5737 int len = 0;
5738 int alreadysent = 0;
5740 struct sockaddr_in sin;
5741 struct sockaddr_in vsin;
5742 struct sockaddr_in dest;
5743 struct sockaddr_in vdest = { 0, };
5745 /* SDP fields */
5746 char *version = "v=0\r\n"; /* Protocol version */
5747 char *subject = "s=session\r\n"; /* Subject of the session */
5748 char owner[256]; /* Session owner/creator */
5749 char connection[256]; /* Connection data */
5750 char *stime = "t=0 0\r\n"; /* Time the session is active */
5751 char bandwidth[256] = ""; /* Max bitrate */
5752 char *hold;
5753 char m_audio[256]; /* Media declaration line for audio */
5754 char m_video[256]; /* Media declaration line for video */
5755 char a_audio[1024]; /* Attributes for audio */
5756 char a_video[1024]; /* Attributes for video */
5757 char *m_audio_next = m_audio;
5758 char *m_video_next = m_video;
5759 size_t m_audio_left = sizeof(m_audio);
5760 size_t m_video_left = sizeof(m_video);
5761 char *a_audio_next = a_audio;
5762 char *a_video_next = a_video;
5763 size_t a_audio_left = sizeof(a_audio);
5764 size_t a_video_left = sizeof(a_video);
5766 int x;
5767 int capability;
5768 int needvideo = FALSE;
5769 int debug = sip_debug_test_pvt(p);
5771 m_video[0] = '\0'; /* Reset the video media string if it's not needed */
5773 if (!p->rtp) {
5774 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
5775 return -1;
5778 /* Set RTP Session ID and version */
5779 if (!p->sessionid) {
5780 p->sessionid = getpid();
5781 p->sessionversion = p->sessionid;
5782 } else
5783 p->sessionversion++;
5785 /* Get our addresses */
5786 ast_rtp_get_us(p->rtp, &sin);
5787 if (p->vrtp)
5788 ast_rtp_get_us(p->vrtp, &vsin);
5790 /* Is this a re-invite to move the media out, then use the original offer from caller */
5791 if (p->redirip.sin_addr.s_addr) {
5792 dest.sin_port = p->redirip.sin_port;
5793 dest.sin_addr = p->redirip.sin_addr;
5794 if (p->redircodecs)
5795 capability = p->redircodecs;
5796 } else {
5797 dest.sin_addr = p->ourip;
5798 dest.sin_port = sin.sin_port;
5801 /* Ok, let's start working with codec selection here */
5802 capability = p->jointcapability;
5804 if (option_debug > 1) {
5805 char codecbuf[BUFSIZ];
5806 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");
5807 ast_log(LOG_DEBUG, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
5810 if ((ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_RTP))) {
5811 ast_build_string(&m_audio_next, &m_audio_left, " %d", 191);
5812 ast_build_string(&a_audio_next, &a_audio_left, "a=rtpmap:%d %s/%d\r\n", 191, "t38", 8000);
5815 /* Check if we need video in this call */
5816 if((capability & AST_FORMAT_VIDEO_MASK) && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
5817 if (p->vrtp) {
5818 needvideo = TRUE;
5819 if (option_debug > 1)
5820 ast_log(LOG_DEBUG, "This call needs video offers! \n");
5821 } else if (option_debug > 1)
5822 ast_log(LOG_DEBUG, "This call needs video offers, but there's no video support enabled ! \n");
5826 /* Ok, we need video. Let's add what we need for video and set codecs.
5827 Video is handled differently than audio since we can not transcode. */
5828 if (needvideo) {
5830 /* Determine video destination */
5831 if (p->vredirip.sin_addr.s_addr) {
5832 vdest.sin_addr = p->vredirip.sin_addr;
5833 vdest.sin_port = p->vredirip.sin_port;
5834 } else {
5835 vdest.sin_addr = p->ourip;
5836 vdest.sin_port = vsin.sin_port;
5838 ast_build_string(&m_video_next, &m_video_left, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
5840 /* Build max bitrate string */
5841 if (p->maxcallbitrate)
5842 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
5843 if (debug)
5844 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(vsin.sin_port));
5846 /* For video, we can't negotiate video offers. Let's compare the incoming call with what we got. */
5847 if (p->prefcodec) {
5848 int videocapability = (capability & p->prefcodec) & AST_FORMAT_VIDEO_MASK; /* Outbound call */
5850 /*! \todo XXX We need to select one codec, not many, since there's no transcoding */
5852 /* Now, merge this video capability into capability while removing unsupported codecs */
5853 if (!videocapability) {
5854 needvideo = FALSE;
5855 if (option_debug > 2)
5856 ast_log(LOG_DEBUG, "** No compatible video codecs... Disabling video.\n");
5859 /* Replace video capabilities with the new videocapability */
5860 capability = (capability & AST_FORMAT_AUDIO_MASK) | videocapability;
5862 if (option_debug > 4) {
5863 char codecbuf[BUFSIZ];
5864 if (videocapability)
5865 ast_log(LOG_DEBUG, "** Our video codec selection is: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), videocapability));
5866 ast_log(LOG_DEBUG, "** Capability now set to : %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability));
5870 if (debug)
5871 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(sin.sin_port));
5873 /* Start building generic SDP headers */
5875 /* We break with the "recommendation" and send our IP, in order that our
5876 peer doesn't have to ast_gethostbyname() us */
5878 snprintf(owner, sizeof(owner), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
5879 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
5880 ast_build_string(&m_audio_next, &m_audio_left, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
5882 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR))
5883 hold = "a=recvonly\r\n";
5884 else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE))
5885 hold = "a=inactive\r\n";
5886 else
5887 hold = "a=sendrecv\r\n";
5889 /* Now, start adding audio codecs. These are added in this order:
5890 - First what was requested by the calling channel
5891 - Then preferences in order from sip.conf device config for this peer/user
5892 - Then other codecs in capabilities, including video
5895 /* Prefer the audio codec we were requested to use, first, no matter what
5896 Note that p->prefcodec can include video codecs, so mask them out
5898 if (capability & p->prefcodec) {
5899 add_codec_to_sdp(p, p->prefcodec & AST_FORMAT_AUDIO_MASK, 8000,
5900 &m_audio_next, &m_audio_left,
5901 &a_audio_next, &a_audio_left,
5902 debug);
5903 alreadysent |= p->prefcodec & AST_FORMAT_AUDIO_MASK;
5907 /* Start by sending our preferred audio codecs */
5908 for (x = 0; x < 32; x++) {
5909 int pref_codec;
5911 if (!(pref_codec = ast_codec_pref_index(&p->prefs, x)))
5912 break;
5914 if (!(capability & pref_codec))
5915 continue;
5917 if (alreadysent & pref_codec)
5918 continue;
5920 add_codec_to_sdp(p, pref_codec, 8000,
5921 &m_audio_next, &m_audio_left,
5922 &a_audio_next, &a_audio_left,
5923 debug);
5924 alreadysent |= pref_codec;
5927 /* Now send any other common audio and video codecs, and non-codec formats: */
5928 for (x = 1; x <= (needvideo ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
5929 if (!(capability & x)) /* Codec not requested */
5930 continue;
5932 if (alreadysent & x) /* Already added to SDP */
5933 continue;
5935 if (x <= AST_FORMAT_MAX_AUDIO)
5936 add_codec_to_sdp(p, x, 8000,
5937 &m_audio_next, &m_audio_left,
5938 &a_audio_next, &a_audio_left,
5939 debug);
5940 else
5941 add_codec_to_sdp(p, x, 90000,
5942 &m_video_next, &m_video_left,
5943 &a_video_next, &a_video_left,
5944 debug);
5947 /* Now add DTMF RFC2833 telephony-event as a codec */
5948 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
5949 if (!(p->noncodeccapability & x))
5950 continue;
5952 add_noncodec_to_sdp(p, x, 8000,
5953 &m_audio_next, &m_audio_left,
5954 &a_audio_next, &a_audio_left,
5955 debug);
5958 if (option_debug > 2)
5959 ast_log(LOG_DEBUG, "-- Done with adding codecs to SDP\n");
5961 if(!ast_internal_timing_enabled(p->owner))
5962 ast_build_string(&a_audio_next, &a_audio_left, "a=silenceSupp:off - - - -\r\n");
5964 if ((m_audio_left < 2) || (m_video_left < 2) || (a_audio_left == 0) || (a_video_left == 0))
5965 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
5967 ast_build_string(&m_audio_next, &m_audio_left, "\r\n");
5968 if (needvideo)
5969 ast_build_string(&m_video_next, &m_video_left, "\r\n");
5971 len = strlen(version) + strlen(subject) + strlen(owner) + strlen(connection) + strlen(stime) + strlen(m_audio) + strlen(a_audio) + strlen(hold);
5972 if (needvideo) /* only if video response is appropriate */
5973 len += strlen(m_video) + strlen(a_video) + strlen(bandwidth) + strlen(hold);
5975 add_header(resp, "Content-Type", "application/sdp");
5976 add_header_contentLength(resp, len);
5977 add_line(resp, version);
5978 add_line(resp, owner);
5979 add_line(resp, subject);
5980 add_line(resp, connection);
5981 if (needvideo) /* only if video response is appropriate */
5982 add_line(resp, bandwidth);
5983 add_line(resp, stime);
5984 add_line(resp, m_audio);
5985 add_line(resp, a_audio);
5986 add_line(resp, hold);
5987 if (needvideo) { /* only if video response is appropriate */
5988 add_line(resp, m_video);
5989 add_line(resp, a_video);
5990 add_line(resp, hold); /* Repeat hold for the video stream */
5993 /* Update lastrtprx when we send our SDP */
5994 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
5996 if (option_debug > 2) {
5997 char buf[BUFSIZ];
5998 ast_log(LOG_DEBUG, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, BUFSIZ, capability));
6001 return 0;
6004 /*--- transmit_response_with_t38_sdp: Used for 200 OK and 183 early media ---*/
6005 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
6007 struct sip_request resp;
6008 int seqno;
6010 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
6011 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
6012 return -1;
6014 respprep(&resp, p, msg, req);
6015 if (p->udptl) {
6016 ast_udptl_offered_from_local(p->udptl, 0);
6017 add_t38_sdp(&resp, p);
6018 } else {
6019 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
6021 return send_response(p, &resp, retrans, seqno);
6024 /*! \brief copy SIP request (mostly used to save request for responses) */
6025 static void copy_request(struct sip_request *dst, const struct sip_request *src)
6027 long offset;
6028 int x;
6029 offset = ((void *)dst) - ((void *)src);
6030 /* First copy stuff */
6031 memcpy(dst, src, sizeof(*dst));
6032 /* Now fix pointer arithmetic */
6033 for (x=0; x < src->headers; x++)
6034 dst->header[x] += offset;
6035 for (x=0; x < src->lines; x++)
6036 dst->line[x] += offset;
6039 /*! \brief Used for 200 OK and 183 early media */
6040 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
6042 struct sip_request resp;
6043 int seqno;
6044 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
6045 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
6046 return -1;
6048 respprep(&resp, p, msg, req);
6049 if (p->rtp) {
6050 try_suggested_sip_codec(p);
6051 add_sdp(&resp, p);
6052 } else {
6053 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
6055 return send_response(p, &resp, reliable, seqno);
6058 /*! \brief Parse first line of incoming SIP request */
6059 static int determine_firstline_parts(struct sip_request *req)
6061 char *e = ast_skip_blanks(req->header[0]); /* there shouldn't be any */
6063 if (!*e)
6064 return -1;
6065 req->rlPart1 = e; /* method or protocol */
6066 e = ast_skip_nonblanks(e);
6067 if (*e)
6068 *e++ = '\0';
6069 /* Get URI or status code */
6070 e = ast_skip_blanks(e);
6071 if ( !*e )
6072 return -1;
6073 ast_trim_blanks(e);
6075 if (!strcasecmp(req->rlPart1, "SIP/2.0") ) { /* We have a response */
6076 if (strlen(e) < 3) /* status code is 3 digits */
6077 return -1;
6078 req->rlPart2 = e;
6079 } else { /* We have a request */
6080 if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
6081 ast_log(LOG_WARNING, "bogus uri in <> %s\n", e);
6082 e++;
6083 if (!*e)
6084 return -1;
6086 req->rlPart2 = e; /* URI */
6087 e = ast_skip_nonblanks(e);
6088 if (*e)
6089 *e++ = '\0';
6090 e = ast_skip_blanks(e);
6091 if (strcasecmp(e, "SIP/2.0") ) {
6092 ast_log(LOG_WARNING, "Bad request protocol %s\n", e);
6093 return -1;
6096 return 1;
6099 /*! \brief Transmit reinvite with SDP
6100 \note A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
6101 INVITE that opened the SIP dialogue
6102 We reinvite so that the audio stream (RTP) go directly between
6103 the SIP UAs. SIP Signalling stays with * in the path.
6105 static int transmit_reinvite_with_sdp(struct sip_pvt *p)
6107 struct sip_request req;
6109 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
6111 add_header(&req, "Allow", ALLOWED_METHODS);
6112 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6113 if (sipdebug)
6114 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
6115 if (recordhistory)
6116 append_history(p, "ReInv", "Re-invite sent");
6117 add_sdp(&req, p);
6118 /* Use this as the basis */
6119 initialize_initreq(p, &req);
6120 p->lastinvite = p->ocseq;
6121 return send_request(p, &req, 1, p->ocseq);
6124 /*! \brief Transmit reinvite with T38 SDP
6125 We reinvite so that the T38 processing can take place.
6126 SIP Signalling stays with * in the path.
6128 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p)
6130 struct sip_request req;
6132 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
6134 add_header(&req, "Allow", ALLOWED_METHODS);
6135 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6136 if (sipdebug)
6137 add_header(&req, "X-asterisk-info", "SIP re-invite (T38 switchover)");
6138 ast_udptl_offered_from_local(p->udptl, 1);
6139 add_t38_sdp(&req, p);
6140 /* Use this as the basis */
6141 initialize_initreq(p, &req);
6142 p->lastinvite = p->ocseq;
6143 return send_request(p, &req, 1, p->ocseq);
6146 /*! \brief Check Contact: URI of SIP message */
6147 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
6149 char stripped[256];
6150 char *c;
6152 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
6153 c = get_in_brackets(stripped);
6154 c = strsep(&c, ";"); /* trim ; and beyond */
6155 if (!ast_strlen_zero(c))
6156 ast_string_field_set(p, uri, c);
6159 /*! \brief Build contact header - the contact header we send out */
6160 static void build_contact(struct sip_pvt *p)
6162 /* Construct Contact: header */
6163 if (ourport != 5060) /* Needs to be 5060, according to the RFC */
6164 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);
6165 else
6166 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip));
6169 /*! \brief Build the Remote Party-ID & From using callingpres options */
6170 static void build_rpid(struct sip_pvt *p)
6172 int send_pres_tags = TRUE;
6173 const char *privacy=NULL;
6174 const char *screen=NULL;
6175 char buf[256];
6176 const char *clid = default_callerid;
6177 const char *clin = NULL;
6178 const char *fromdomain;
6180 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
6181 return;
6183 if (p->owner && p->owner->cid.cid_num)
6184 clid = p->owner->cid.cid_num;
6185 if (p->owner && p->owner->cid.cid_name)
6186 clin = p->owner->cid.cid_name;
6187 if (ast_strlen_zero(clin))
6188 clin = clid;
6190 switch (p->callingpres) {
6191 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
6192 privacy = "off";
6193 screen = "no";
6194 break;
6195 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
6196 privacy = "off";
6197 screen = "pass";
6198 break;
6199 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
6200 privacy = "off";
6201 screen = "fail";
6202 break;
6203 case AST_PRES_ALLOWED_NETWORK_NUMBER:
6204 privacy = "off";
6205 screen = "yes";
6206 break;
6207 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
6208 privacy = "full";
6209 screen = "no";
6210 break;
6211 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
6212 privacy = "full";
6213 screen = "pass";
6214 break;
6215 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
6216 privacy = "full";
6217 screen = "fail";
6218 break;
6219 case AST_PRES_PROHIB_NETWORK_NUMBER:
6220 privacy = "full";
6221 screen = "pass";
6222 break;
6223 case AST_PRES_NUMBER_NOT_AVAILABLE:
6224 send_pres_tags = FALSE;
6225 break;
6226 default:
6227 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
6228 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
6229 privacy = "full";
6230 else
6231 privacy = "off";
6232 screen = "no";
6233 break;
6236 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip));
6238 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
6239 if (send_pres_tags)
6240 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
6241 ast_string_field_set(p, rpid, buf);
6243 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
6244 S_OR(p->fromuser, clid),
6245 fromdomain, p->tag);
6248 /*! \brief Initiate new SIP request to peer/user */
6249 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
6251 char invite_buf[256] = "";
6252 char *invite = invite_buf;
6253 size_t invite_max = sizeof(invite_buf);
6254 char from[256];
6255 char to[256];
6256 char tmp[BUFSIZ/2];
6257 char tmp2[BUFSIZ/2];
6258 const char *l = NULL, *n = NULL;
6259 int x;
6260 char urioptions[256]="";
6262 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
6263 char onlydigits = TRUE;
6264 x=0;
6266 /* Test p->username against allowed characters in AST_DIGIT_ANY
6267 If it matches the allowed characters list, then sipuser = ";user=phone"
6268 If not, then sipuser = ""
6270 /* + is allowed in first position in a tel: uri */
6271 if (p->username && p->username[0] == '+')
6272 x=1;
6274 for (; x < strlen(p->username); x++) {
6275 if (!strchr(AST_DIGIT_ANYNUM, p->username[x])) {
6276 onlydigits = FALSE;
6277 break;
6281 /* If we have only digits, add ;user=phone to the uri */
6282 if (onlydigits)
6283 strcpy(urioptions, ";user=phone");
6287 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
6289 if (p->owner) {
6290 l = p->owner->cid.cid_num;
6291 n = p->owner->cid.cid_name;
6293 /* if we are not sending RPID and user wants his callerid restricted */
6294 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
6295 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
6296 l = CALLERID_UNKNOWN;
6297 n = l;
6299 if (ast_strlen_zero(l))
6300 l = default_callerid;
6301 if (ast_strlen_zero(n))
6302 n = l;
6303 /* Allow user to be overridden */
6304 if (!ast_strlen_zero(p->fromuser))
6305 l = p->fromuser;
6306 else /* Save for any further attempts */
6307 ast_string_field_set(p, fromuser, l);
6309 /* Allow user to be overridden */
6310 if (!ast_strlen_zero(p->fromname))
6311 n = p->fromname;
6312 else /* Save for any further attempts */
6313 ast_string_field_set(p, fromname, n);
6315 if (pedanticsipchecking) {
6316 ast_uri_encode(n, tmp, sizeof(tmp), 0);
6317 n = tmp;
6318 ast_uri_encode(l, tmp2, sizeof(tmp2), 0);
6319 l = tmp2;
6322 if ((ourport != 5060) && ast_strlen_zero(p->fromdomain)) /* Needs to be 5060 */
6323 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);
6324 else
6325 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)), p->tag);
6327 /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
6328 if (!ast_strlen_zero(p->fullcontact)) {
6329 /* If we have full contact, trust it */
6330 ast_build_string(&invite, &invite_max, "%s", p->fullcontact);
6331 } else {
6332 /* Otherwise, use the username while waiting for registration */
6333 ast_build_string(&invite, &invite_max, "sip:");
6334 if (!ast_strlen_zero(p->username)) {
6335 n = p->username;
6336 if (pedanticsipchecking) {
6337 ast_uri_encode(n, tmp, sizeof(tmp), 0);
6338 n = tmp;
6340 ast_build_string(&invite, &invite_max, "%s@", n);
6342 ast_build_string(&invite, &invite_max, "%s", p->tohost);
6343 if (ntohs(p->sa.sin_port) != 5060) /* Needs to be 5060 */
6344 ast_build_string(&invite, &invite_max, ":%d", ntohs(p->sa.sin_port));
6345 ast_build_string(&invite, &invite_max, "%s", urioptions);
6348 /* If custom URI options have been provided, append them */
6349 if (p->options && p->options->uri_options)
6350 ast_build_string(&invite, &invite_max, ";%s", p->options->uri_options);
6352 ast_string_field_set(p, uri, invite_buf);
6354 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
6355 /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
6356 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", p->uri, p->theirtag);
6357 } else if (p->options && p->options->vxml_url) {
6358 /* If there is a VXML URL append it to the SIP URL */
6359 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
6360 } else {
6361 snprintf(to, sizeof(to), "<%s>", p->uri);
6364 init_req(req, sipmethod, p->uri);
6365 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
6367 add_header(req, "Via", p->via);
6368 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
6369 * OTOH, then we won't have anything in p->route anyway */
6370 /* Build Remote Party-ID and From */
6371 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
6372 build_rpid(p);
6373 add_header(req, "From", p->rpid_from);
6374 } else {
6375 add_header(req, "From", from);
6377 add_header(req, "To", to);
6378 ast_string_field_set(p, exten, l);
6379 build_contact(p);
6380 add_header(req, "Contact", p->our_contact);
6381 add_header(req, "Call-ID", p->callid);
6382 add_header(req, "CSeq", tmp);
6383 add_header(req, "User-Agent", global_useragent);
6384 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
6385 if (!ast_strlen_zero(p->rpid))
6386 add_header(req, "Remote-Party-ID", p->rpid);
6389 /*! \brief Build REFER/INVITE/OPTIONS message and transmit it */
6390 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
6392 struct sip_request req;
6394 req.method = sipmethod;
6395 if (init) { /* Seems like init always is 2 */
6396 /* Bump branch even on initial requests */
6397 p->branch ^= ast_random();
6398 build_via(p);
6399 if (init > 1)
6400 initreqprep(&req, p, sipmethod);
6401 else
6402 reqprep(&req, p, sipmethod, 0, 1);
6403 } else
6404 reqprep(&req, p, sipmethod, 0, 1);
6406 if (p->options && p->options->auth)
6407 add_header(&req, p->options->authheader, p->options->auth);
6408 append_date(&req);
6409 if (sipmethod == SIP_REFER) { /* Call transfer */
6410 if (p->refer) {
6411 char buf[BUFSIZ];
6412 if (!ast_strlen_zero(p->refer->refer_to))
6413 add_header(&req, "Refer-To", p->refer->refer_to);
6414 if (!ast_strlen_zero(p->refer->referred_by)) {
6415 sprintf(buf, "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
6416 add_header(&req, "Referred-By", buf);
6420 /* This new INVITE is part of an attended transfer. Make sure that the
6421 other end knows and replace the current call with this new call */
6422 if (p->options && p->options->replaces && !ast_strlen_zero(p->options->replaces)) {
6423 add_header(&req, "Replaces", p->options->replaces);
6424 add_header(&req, "Require", "replaces");
6427 if (p->options && !ast_strlen_zero(p->options->distinctive_ring)) {
6428 add_header(&req, "Alert-Info", p->options->distinctive_ring);
6430 add_header(&req, "Allow", ALLOWED_METHODS);
6431 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6432 if (p->options && p->options->addsipheaders ) {
6433 struct ast_channel *ast;
6434 struct varshead *headp = NULL;
6435 const struct ast_var_t *current;
6437 ast = p->owner; /* The owner channel */
6438 if (ast) {
6439 char *headdup;
6440 headp = &ast->varshead;
6441 if (!headp)
6442 ast_log(LOG_WARNING,"No Headp for the channel...ooops!\n");
6443 else {
6444 AST_LIST_TRAVERSE(headp, current, entries) {
6445 /* SIPADDHEADER: Add SIP header to outgoing call */
6446 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
6447 char *content, *end;
6448 const char *header = ast_var_value(current);
6450 headdup = ast_strdupa(header);
6451 /* Strip of the starting " (if it's there) */
6452 if (*headdup == '"')
6453 headdup++;
6454 if ((content = strchr(headdup, ':'))) {
6455 *content++ = '\0';
6456 content = ast_skip_blanks(content); /* Skip white space */
6457 /* Strip the ending " (if it's there) */
6458 end = content + strlen(content) -1;
6459 if (*end == '"')
6460 *end = '\0';
6462 add_header(&req, headdup, content);
6463 if (sipdebug)
6464 ast_log(LOG_DEBUG, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
6471 if (sdp) {
6472 if (p->udptl && p->t38.state == T38_LOCAL_DIRECT) {
6473 ast_udptl_offered_from_local(p->udptl, 1);
6474 if (option_debug)
6475 ast_log(LOG_DEBUG, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
6476 add_t38_sdp(&req, p);
6477 } else if (p->rtp) {
6478 add_sdp(&req, p);
6480 } else {
6481 add_header_contentLength(&req, 0);
6484 if (!p->initreq.headers)
6485 initialize_initreq(p, &req);
6486 p->lastinvite = p->ocseq;
6487 return send_request(p, &req, init ? 2 : 1, p->ocseq);
6490 /*! \brief Used in the SUBSCRIBE notification subsystem */
6491 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
6493 char tmp[4000], from[256], to[256];
6494 char *t = tmp, *c, *mfrom, *mto;
6495 size_t maxbytes = sizeof(tmp);
6496 struct sip_request req;
6497 char hint[AST_MAX_EXTENSION];
6498 char *statestring = "terminated";
6499 const struct cfsubscription_types *subscriptiontype;
6500 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
6501 char *pidfstate = "--";
6502 char *pidfnote= "Ready";
6504 memset(from, 0, sizeof(from));
6505 memset(to, 0, sizeof(to));
6506 memset(tmp, 0, sizeof(tmp));
6508 switch (state) {
6509 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
6510 statestring = (global_notifyringing) ? "early" : "confirmed";
6511 local_state = NOTIFY_INUSE;
6512 pidfstate = "busy";
6513 pidfnote = "Ringing";
6514 break;
6515 case AST_EXTENSION_RINGING:
6516 statestring = "early";
6517 local_state = NOTIFY_INUSE;
6518 pidfstate = "busy";
6519 pidfnote = "Ringing";
6520 break;
6521 case AST_EXTENSION_INUSE:
6522 statestring = "confirmed";
6523 local_state = NOTIFY_INUSE;
6524 pidfstate = "busy";
6525 pidfnote = "On the phone";
6526 break;
6527 case AST_EXTENSION_BUSY:
6528 statestring = "confirmed";
6529 local_state = NOTIFY_CLOSED;
6530 pidfstate = "busy";
6531 pidfnote = "On the phone";
6532 break;
6533 case AST_EXTENSION_UNAVAILABLE:
6534 statestring = "confirmed";
6535 local_state = NOTIFY_CLOSED;
6536 pidfstate = "away";
6537 pidfnote = "Unavailable";
6538 break;
6539 case AST_EXTENSION_ONHOLD:
6540 break;
6541 case AST_EXTENSION_NOT_INUSE:
6542 default:
6543 /* Default setting */
6544 break;
6547 subscriptiontype = find_subscription_type(p->subscribed);
6549 /* Check which device/devices we are watching and if they are registered */
6550 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
6551 /* If they are not registered, we will override notification and show no availability */
6552 if (ast_device_state(hint) == AST_DEVICE_UNAVAILABLE) {
6553 local_state = NOTIFY_CLOSED;
6554 pidfstate = "away";
6555 pidfnote = "Not online";
6559 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
6560 c = get_in_brackets(from);
6561 if (strncmp(c, "sip:", 4)) {
6562 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
6563 return -1;
6565 mfrom = strsep(&c, ";"); /* trim ; and beyond */
6567 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
6568 c = get_in_brackets(to);
6569 if (strncmp(c, "sip:", 4)) {
6570 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
6571 return -1;
6573 mto = strsep(&c, ";"); /* trim ; and beyond */
6575 reqprep(&req, p, SIP_NOTIFY, 0, 1);
6578 add_header(&req, "Event", subscriptiontype->event);
6579 add_header(&req, "Content-Type", subscriptiontype->mediatype);
6580 switch(state) {
6581 case AST_EXTENSION_DEACTIVATED:
6582 if (p->subscribed == TIMEOUT)
6583 add_header(&req, "Subscription-State", "terminated;reason=timeout");
6584 else {
6585 add_header(&req, "Subscription-State", "terminated;reason=probation");
6586 add_header(&req, "Retry-After", "60");
6588 break;
6589 case AST_EXTENSION_REMOVED:
6590 add_header(&req, "Subscription-State", "terminated;reason=noresource");
6591 break;
6592 default:
6593 if (p->expiry)
6594 add_header(&req, "Subscription-State", "active");
6595 else /* Expired */
6596 add_header(&req, "Subscription-State", "terminated;reason=timeout");
6598 switch (p->subscribed) {
6599 case XPIDF_XML:
6600 case CPIM_PIDF_XML:
6601 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
6602 ast_build_string(&t, &maxbytes, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
6603 ast_build_string(&t, &maxbytes, "<presence>\n");
6604 ast_build_string(&t, &maxbytes, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
6605 ast_build_string(&t, &maxbytes, "<atom id=\"%s\">\n", p->exten);
6606 ast_build_string(&t, &maxbytes, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
6607 ast_build_string(&t, &maxbytes, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
6608 ast_build_string(&t, &maxbytes, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
6609 ast_build_string(&t, &maxbytes, "</address>\n</atom>\n</presence>\n");
6610 break;
6611 case PIDF_XML: /* Eyebeam supports this format */
6612 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
6613 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);
6614 ast_build_string(&t, &maxbytes, "<pp:person><status>\n");
6615 if (pidfstate[0] != '-')
6616 ast_build_string(&t, &maxbytes, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
6617 ast_build_string(&t, &maxbytes, "</status></pp:person>\n");
6618 ast_build_string(&t, &maxbytes, "<note>%s</note>\n", pidfnote); /* Note */
6619 ast_build_string(&t, &maxbytes, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
6620 ast_build_string(&t, &maxbytes, "<contact priority=\"1\">%s</contact>\n", mto);
6621 if (pidfstate[0] == 'b') /* Busy? Still open ... */
6622 ast_build_string(&t, &maxbytes, "<status><basic>open</basic></status>\n");
6623 else
6624 ast_build_string(&t, &maxbytes, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
6625 ast_build_string(&t, &maxbytes, "</tuple>\n</presence>\n");
6626 break;
6627 case DIALOG_INFO_XML: /* SNOM subscribes in this format */
6628 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
6629 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);
6630 if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
6631 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
6632 else
6633 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\">\n", p->exten);
6634 ast_build_string(&t, &maxbytes, "<state>%s</state>\n", statestring);
6635 ast_build_string(&t, &maxbytes, "</dialog>\n</dialog-info>\n");
6636 break;
6637 case NONE:
6638 default:
6639 break;
6642 if (t > tmp + sizeof(tmp))
6643 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
6645 add_header_contentLength(&req, strlen(tmp));
6646 add_line(&req, tmp);
6648 return send_request(p, &req, 1, p->ocseq);
6651 /*! \brief Notify user of messages waiting in voicemail
6652 \note - Notification only works for registered peers with mailbox= definitions
6653 in sip.conf
6654 - We use the SIP Event package message-summary
6655 MIME type defaults to "application/simple-message-summary";
6657 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
6659 struct sip_request req;
6660 char tmp[500];
6661 char *t = tmp;
6662 size_t maxbytes = sizeof(tmp);
6664 initreqprep(&req, p, SIP_NOTIFY);
6665 add_header(&req, "Event", "message-summary");
6666 add_header(&req, "Content-Type", default_notifymime);
6668 ast_build_string(&t, &maxbytes, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
6669 ast_build_string(&t, &maxbytes, "Message-Account: sip:%s@%s\r\n",
6670 S_OR(vmexten, default_vmexten), S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)));
6671 ast_build_string(&t, &maxbytes, "Voice-Message: %d/%d (0/0)\r\n", newmsgs, oldmsgs);
6672 if (p->subscribed) {
6673 if (p->expiry)
6674 add_header(&req, "Subscription-State", "active");
6675 else /* Expired */
6676 add_header(&req, "Subscription-State", "terminated;reason=timeout");
6679 if (t > tmp + sizeof(tmp))
6680 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
6682 add_header_contentLength(&req, strlen(tmp));
6683 add_line(&req, tmp);
6685 if (!p->initreq.headers)
6686 initialize_initreq(p, &req);
6687 return send_request(p, &req, 1, p->ocseq);
6690 /*! \brief Transmit SIP request */
6691 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req)
6693 if (!p->initreq.headers) /* Initialize first request before sending */
6694 initialize_initreq(p, req);
6695 return send_request(p, req, 0, p->ocseq);
6698 /*! \brief Notify a transferring party of the status of transfer */
6699 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
6701 struct sip_request req;
6702 char tmp[BUFSIZ/2];
6704 reqprep(&req, p, SIP_NOTIFY, 0, 1);
6705 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
6706 add_header(&req, "Event", tmp);
6707 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
6708 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
6709 add_header(&req, "Allow", ALLOWED_METHODS);
6710 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
6712 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
6713 add_header_contentLength(&req, strlen(tmp));
6714 add_line(&req, tmp);
6716 if (!p->initreq.headers)
6717 initialize_initreq(p, &req);
6719 return send_request(p, &req, 1, p->ocseq);
6722 /*! \brief Convert registration state status to string */
6723 static char *regstate2str(enum sipregistrystate regstate)
6725 switch(regstate) {
6726 case REG_STATE_FAILED:
6727 return "Failed";
6728 case REG_STATE_UNREGISTERED:
6729 return "Unregistered";
6730 case REG_STATE_REGSENT:
6731 return "Request Sent";
6732 case REG_STATE_AUTHSENT:
6733 return "Auth. Sent";
6734 case REG_STATE_REGISTERED:
6735 return "Registered";
6736 case REG_STATE_REJECTED:
6737 return "Rejected";
6738 case REG_STATE_TIMEOUT:
6739 return "Timeout";
6740 case REG_STATE_NOAUTH:
6741 return "No Authentication";
6742 default:
6743 return "Unknown";
6747 /*! \brief Update registration with SIP Proxy */
6748 static int sip_reregister(void *data)
6750 /* if we are here, we know that we need to reregister. */
6751 struct sip_registry *r= ASTOBJ_REF((struct sip_registry *) data);
6753 /* if we couldn't get a reference to the registry object, punt */
6754 if (!r)
6755 return 0;
6757 if (r->call && recordhistory)
6758 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
6759 /* Since registry's are only added/removed by the the monitor thread, this
6760 may be overkill to reference/dereference at all here */
6761 if (sipdebug)
6762 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
6764 r->expire = -1;
6765 __sip_do_register(r);
6766 ASTOBJ_UNREF(r, sip_registry_destroy);
6767 return 0;
6770 /*! \brief Register with SIP proxy */
6771 static int __sip_do_register(struct sip_registry *r)
6773 int res;
6775 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
6776 return res;
6779 /*! \brief Registration timeout, register again */
6780 static int sip_reg_timeout(void *data)
6783 /* if we are here, our registration timed out, so we'll just do it over */
6784 struct sip_registry *r = ASTOBJ_REF((struct sip_registry *) data);
6785 struct sip_pvt *p;
6786 int res;
6788 /* if we couldn't get a reference to the registry object, punt */
6789 if (!r)
6790 return 0;
6792 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
6793 if (r->call) {
6794 /* Unlink us, destroy old call. Locking is not relevant here because all this happens
6795 in the single SIP manager thread. */
6796 p = r->call;
6797 if (p->registry)
6798 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
6799 r->call = NULL;
6800 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
6801 /* Pretend to ACK anything just in case */
6802 __sip_pretend_ack(p); /* XXX we need p locked, not sure we have */
6804 /* If we have a limit, stop registration and give up */
6805 if (global_regattempts_max && (r->regattempts > global_regattempts_max)) {
6806 /* Ok, enough is enough. Don't try any more */
6807 /* We could add an external notification here...
6808 steal it from app_voicemail :-) */
6809 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
6810 r->regstate = REG_STATE_FAILED;
6811 } else {
6812 r->regstate = REG_STATE_UNREGISTERED;
6813 r->timeout = -1;
6814 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
6816 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));
6817 ASTOBJ_UNREF(r, sip_registry_destroy);
6818 return 0;
6821 /*! \brief Transmit register to SIP proxy or UA */
6822 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
6824 struct sip_request req;
6825 char from[256];
6826 char to[256];
6827 char tmp[80];
6828 char addr[80];
6829 struct sip_pvt *p;
6831 /* exit if we are already in process with this registrar ?*/
6832 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
6833 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
6834 return 0;
6837 if (r->call) { /* We have a registration */
6838 if (!auth) {
6839 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
6840 return 0;
6841 } else {
6842 p = r->call;
6843 make_our_tag(p->tag, sizeof(p->tag)); /* create a new local tag for every register attempt */
6844 ast_string_field_free(p, theirtag); /* forget their old tag, so we don't match tags when getting response */
6846 } else {
6847 /* Build callid for registration if we haven't registered before */
6848 if (!r->callid_valid) {
6849 build_callid_registry(r, __ourip, default_fromdomain);
6850 r->callid_valid = TRUE;
6852 /* Allocate SIP packet for registration */
6853 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER))) {
6854 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
6855 return 0;
6857 if (recordhistory)
6858 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
6859 /* Find address to hostname */
6860 if (create_addr(p, r->hostname)) {
6861 /* we have what we hope is a temporary network error,
6862 * probably DNS. We need to reschedule a registration try */
6863 sip_destroy(p);
6864 if (r->timeout > -1) {
6865 ast_sched_del(sched, r->timeout);
6866 r->timeout = ast_sched_add(sched, global_reg_timeout*1000, sip_reg_timeout, r);
6867 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
6868 } else {
6869 r->timeout = ast_sched_add(sched, global_reg_timeout*1000, sip_reg_timeout, r);
6870 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);
6872 r->regattempts++;
6873 return 0;
6875 /* Copy back Call-ID in case create_addr changed it */
6876 ast_string_field_set(r, callid, p->callid);
6877 if (r->portno)
6878 p->sa.sin_port = htons(r->portno);
6879 else /* Set registry port to the port set from the peer definition/srv or default */
6880 r->portno = ntohs(p->sa.sin_port);
6881 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
6882 r->call=p; /* Save pointer to SIP packet */
6883 p->registry = ASTOBJ_REF(r); /* Add pointer to registry in packet */
6884 if (!ast_strlen_zero(r->secret)) /* Secret (password) */
6885 ast_string_field_set(p, peersecret, r->secret);
6886 if (!ast_strlen_zero(r->md5secret))
6887 ast_string_field_set(p, peermd5secret, r->md5secret);
6888 /* User name in this realm
6889 - if authuser is set, use that, otherwise use username */
6890 if (!ast_strlen_zero(r->authuser)) {
6891 ast_string_field_set(p, peername, r->authuser);
6892 ast_string_field_set(p, authname, r->authuser);
6893 } else if (!ast_strlen_zero(r->username)) {
6894 ast_string_field_set(p, peername, r->username);
6895 ast_string_field_set(p, authname, r->username);
6896 ast_string_field_set(p, fromuser, r->username);
6898 if (!ast_strlen_zero(r->username))
6899 ast_string_field_set(p, username, r->username);
6900 /* Save extension in packet */
6901 ast_string_field_set(p, exten, r->contact);
6904 check which address we should use in our contact header
6905 based on whether the remote host is on the external or
6906 internal network so we can register through nat
6908 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
6909 p->ourip = bindaddr.sin_addr;
6910 build_contact(p);
6913 /* set up a timeout */
6914 if (auth == NULL) {
6915 if (r->timeout > -1) {
6916 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
6917 ast_sched_del(sched, r->timeout);
6919 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
6920 ast_log(LOG_DEBUG, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
6923 if (strchr(r->username, '@')) {
6924 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
6925 if (!ast_strlen_zero(p->theirtag))
6926 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
6927 else
6928 snprintf(to, sizeof(to), "<sip:%s>", r->username);
6929 } else {
6930 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
6931 if (!ast_strlen_zero(p->theirtag))
6932 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
6933 else
6934 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
6937 /* Fromdomain is what we are registering to, regardless of actual
6938 host name from SRV */
6939 snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain, r->hostname));
6940 ast_string_field_set(p, uri, addr);
6942 p->branch ^= ast_random();
6944 init_req(&req, sipmethod, addr);
6946 /* Add to CSEQ */
6947 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
6948 p->ocseq = r->ocseq;
6950 build_via(p);
6951 add_header(&req, "Via", p->via);
6952 add_header(&req, "From", from);
6953 add_header(&req, "To", to);
6954 add_header(&req, "Call-ID", p->callid);
6955 add_header(&req, "CSeq", tmp);
6956 add_header(&req, "User-Agent", global_useragent);
6957 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
6960 if (auth) /* Add auth header */
6961 add_header(&req, authheader, auth);
6962 else if (!ast_strlen_zero(r->nonce)) {
6963 char digest[1024];
6965 /* We have auth data to reuse, build a digest header! */
6966 if (sipdebug)
6967 ast_log(LOG_DEBUG, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
6968 ast_string_field_set(p, realm, r->realm);
6969 ast_string_field_set(p, nonce, r->nonce);
6970 ast_string_field_set(p, domain, r->domain);
6971 ast_string_field_set(p, opaque, r->opaque);
6972 ast_string_field_set(p, qop, r->qop);
6973 p->noncecount = r->noncecount++;
6975 memset(digest,0,sizeof(digest));
6976 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
6977 add_header(&req, "Authorization", digest);
6978 else
6979 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
6983 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
6984 add_header(&req, "Expires", tmp);
6985 add_header(&req, "Contact", p->our_contact);
6986 add_header(&req, "Event", "registration");
6987 add_header_contentLength(&req, 0);
6989 initialize_initreq(p, &req);
6990 if (sip_debug_test_pvt(p))
6991 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
6992 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
6993 r->regattempts++; /* Another attempt */
6994 if (option_debug > 3)
6995 ast_verbose("REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
6996 return send_request(p, &req, 2, p->ocseq);
6999 /*! \brief Transmit text with SIP MESSAGE method */
7000 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
7002 struct sip_request req;
7004 reqprep(&req, p, SIP_MESSAGE, 0, 1);
7005 add_text(&req, text);
7006 return send_request(p, &req, 1, p->ocseq);
7009 /*! \brief Allocate SIP refer structure */
7010 static int sip_refer_allocate(struct sip_pvt *p)
7012 p->refer = ast_calloc(1, sizeof(struct sip_refer));
7013 return p->refer ? 1 : 0;
7016 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
7017 \note this is currently broken as we have no way of telling the dialplan
7018 engine whether a transfer succeeds or fails.
7019 \todo Fix the transfer() dialplan function so that a transfer may fail
7021 static int transmit_refer(struct sip_pvt *p, const char *dest)
7023 struct sip_request req = {
7024 .headers = 0,
7026 char from[256];
7027 const char *of;
7028 char *c;
7029 char referto[256];
7030 char *ttag, *ftag;
7031 char *theirtag = ast_strdupa(p->theirtag);
7033 if (option_debug || sipdebug)
7034 ast_log(LOG_DEBUG, "SIP transfer of %s to %s\n", p->callid, dest);
7036 /* Are we transfering an inbound or outbound call ? */
7037 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
7038 of = get_header(&p->initreq, "To");
7039 ttag = theirtag;
7040 ftag = p->tag;
7041 } else {
7042 of = get_header(&p->initreq, "From");
7043 ftag = theirtag;
7044 ttag = p->tag;
7047 ast_copy_string(from, of, sizeof(from));
7048 of = get_in_brackets(from);
7049 ast_string_field_set(p, from, of);
7050 if (strncmp(of, "sip:", 4))
7051 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
7052 else
7053 of += 4;
7054 /* Get just the username part */
7055 if ((c = strchr(dest, '@')))
7056 c = NULL;
7057 else if ((c = strchr(of, '@')))
7058 *c++ = '\0';
7059 if (c)
7060 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
7061 else
7062 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
7064 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
7066 /* save in case we get 407 challenge */
7067 sip_refer_allocate(p);
7068 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
7069 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
7070 p->refer->status = REFER_SENT; /* Set refer status */
7072 reqprep(&req, p, SIP_REFER, 0, 1);
7073 add_header(&req, "Refer-To", referto);
7074 add_header(&req, "Allow", ALLOWED_METHODS);
7075 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
7076 if (!ast_strlen_zero(p->our_contact))
7077 add_header(&req, "Referred-By", p->our_contact);
7079 return send_request(p, &req, 1, p->ocseq);
7080 /* We should propably wait for a NOTIFY here until we ack the transfer */
7081 /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
7083 /*! \todo In theory, we should hang around and wait for a reply, before
7084 returning to the dial plan here. Don't know really how that would
7085 affect the transfer() app or the pbx, but, well, to make this
7086 useful we should have a STATUS code on transfer().
7091 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
7092 static int transmit_info_with_digit(struct sip_pvt *p, const char digit)
7094 struct sip_request req;
7096 reqprep(&req, p, SIP_INFO, 0, 1);
7097 add_digit(&req, digit);
7098 return send_request(p, &req, 1, p->ocseq);
7101 /*! \brief Send SIP INFO with video update request */
7102 static int transmit_info_with_vidupdate(struct sip_pvt *p)
7104 struct sip_request req;
7106 reqprep(&req, p, SIP_INFO, 0, 1);
7107 add_vidupdate(&req);
7108 return send_request(p, &req, 1, p->ocseq);
7111 /*! \brief Transmit generic SIP request */
7112 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
7114 struct sip_request resp;
7116 reqprep(&resp, p, sipmethod, seqno, newbranch);
7117 add_header_contentLength(&resp, 0);
7118 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
7121 /*! \brief Transmit SIP request, auth added */
7122 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
7124 struct sip_request resp;
7126 reqprep(&resp, p, sipmethod, seqno, newbranch);
7127 if (!ast_strlen_zero(p->realm)) {
7128 char digest[1024];
7130 memset(digest, 0, sizeof(digest));
7131 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
7132 if (p->options && p->options->auth_type == PROXY_AUTH)
7133 add_header(&resp, "Proxy-Authorization", digest);
7134 else if (p->options && p->options->auth_type == WWW_AUTH)
7135 add_header(&resp, "Authorization", digest);
7136 else /* Default, to be backwards compatible (maybe being too careful, but leaving it for now) */
7137 add_header(&resp, "Proxy-Authorization", digest);
7138 } else
7139 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
7141 /* If we are hanging up and know a cause for that, send it in clear text to make
7142 debugging easier. */
7143 if (sipmethod == SIP_BYE && p->owner && p->owner->hangupcause) {
7144 char buf[10];
7146 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
7147 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
7148 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
7151 add_header_contentLength(&resp, 0);
7152 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
7155 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
7156 static void destroy_association(struct sip_peer *peer)
7158 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE)) {
7159 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
7160 ast_update_realtime("sippeers", "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "username", "", "regserver", "", NULL);
7161 else
7162 ast_db_del("SIP/Registry", peer->name);
7166 /*! \brief Expire registration of SIP peer */
7167 static int expire_register(void *data)
7169 struct sip_peer *peer = data;
7171 if (!peer) /* Hmmm. We have no peer. Weird. */
7172 return 0;
7174 memset(&peer->addr, 0, sizeof(peer->addr));
7176 destroy_association(peer); /* remove registration data from storage */
7178 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
7179 register_peer_exten(peer, FALSE); /* Remove regexten */
7180 peer->expire = -1;
7181 ast_device_state_changed("SIP/%s", peer->name);
7183 /* Do we need to release this peer from memory?
7184 Only for realtime peers and autocreated peers
7186 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT) ||
7187 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
7188 peer = ASTOBJ_CONTAINER_UNLINK(&peerl, peer); /* Remove from peer list */
7189 ASTOBJ_UNREF(peer, sip_destroy_peer); /* Remove from memory */
7192 return 0;
7195 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
7196 static int sip_poke_peer_s(void *data)
7198 struct sip_peer *peer = data;
7200 peer->pokeexpire = -1;
7201 sip_poke_peer(peer);
7202 return 0;
7205 /*! \brief Get registration details from Asterisk DB */
7206 static void reg_source_db(struct sip_peer *peer)
7208 char data[256];
7209 struct in_addr in;
7210 int expiry;
7211 int port;
7212 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
7214 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
7215 return;
7216 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
7217 return;
7219 scan = data;
7220 addr = strsep(&scan, ":");
7221 port_str = strsep(&scan, ":");
7222 expiry_str = strsep(&scan, ":");
7223 username = strsep(&scan, ":");
7224 contact = scan; /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
7226 if (!inet_aton(addr, &in))
7227 return;
7229 if (port_str)
7230 port = atoi(port_str);
7231 else
7232 return;
7234 if (expiry_str)
7235 expiry = atoi(expiry_str);
7236 else
7237 return;
7239 if (username)
7240 ast_copy_string(peer->username, username, sizeof(peer->username));
7241 if (contact)
7242 ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
7244 if (option_verbose > 2)
7245 ast_verbose(VERBOSE_PREFIX_3 "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
7246 peer->name, peer->username, ast_inet_ntoa(in), port, expiry);
7248 memset(&peer->addr, 0, sizeof(peer->addr));
7249 peer->addr.sin_family = AF_INET;
7250 peer->addr.sin_addr = in;
7251 peer->addr.sin_port = htons(port);
7252 if (sipsock < 0) {
7253 /* SIP isn't up yet, so schedule a poke only, pretty soon */
7254 if (peer->pokeexpire > -1)
7255 ast_sched_del(sched, peer->pokeexpire);
7256 peer->pokeexpire = ast_sched_add(sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer);
7257 } else
7258 sip_poke_peer(peer);
7259 if (peer->expire > -1)
7260 ast_sched_del(sched, peer->expire);
7261 peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, peer);
7262 register_peer_exten(peer, TRUE);
7265 /*! \brief Save contact header for 200 OK on INVITE */
7266 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
7268 char contact[250];
7269 char *c;
7271 /* Look for brackets */
7272 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
7273 c = get_in_brackets(contact);
7275 /* Save full contact to call pvt for later bye or re-invite */
7276 ast_string_field_set(pvt, fullcontact, c);
7278 /* Save URI for later ACKs, BYE or RE-invites */
7279 ast_string_field_set(pvt, okcontacturi, c);
7281 /* We should return false for URI:s we can't handle,
7282 like sips:, tel:, mailto:,ldap: etc */
7283 return TRUE;
7286 /*! \brief Change the other partys IP address based on given contact */
7287 static int set_address_from_contact(struct sip_pvt *pvt)
7289 struct hostent *hp;
7290 struct ast_hostent ahp;
7291 int port;
7292 char *c, *host, *pt;
7293 char *contact;
7296 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
7297 /* NAT: Don't trust the contact field. Just use what they came to us
7298 with. */
7299 pvt->sa = pvt->recv;
7300 return 0;
7304 /* Work on a copy */
7305 contact = ast_strdupa(pvt->fullcontact);
7307 /* XXX this code is repeated all over */
7308 /* Make sure it's a SIP URL */
7309 if (strncasecmp(contact, "sip:", 4)) {
7310 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
7311 } else
7312 contact += 4;
7314 /* Ditch arguments */
7315 /* XXX this code is replicated also shortly below */
7316 contact = strsep(&contact, ";"); /* trim ; and beyond */
7318 /* Grab host */
7319 host = strchr(contact, '@');
7320 if (!host) { /* No username part */
7321 host = contact;
7322 c = NULL;
7323 } else {
7324 *host++ = '\0';
7326 pt = strchr(host, ':');
7327 if (pt) {
7328 *pt++ = '\0';
7329 port = atoi(pt);
7330 } else
7331 port = DEFAULT_SIP_PORT;
7333 /* XXX This could block for a long time XXX */
7334 /* We should only do this if it's a name, not an IP */
7335 hp = ast_gethostbyname(host, &ahp);
7336 if (!hp) {
7337 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
7338 return -1;
7340 pvt->sa.sin_family = AF_INET;
7341 memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
7342 pvt->sa.sin_port = htons(port);
7344 return 0;
7348 /*! \brief Parse contact header and save registration (peer registration) */
7349 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
7351 char contact[BUFSIZ];
7352 char data[BUFSIZ];
7353 const char *expires = get_header(req, "Expires");
7354 int expiry = atoi(expires);
7355 char *curi, *n, *pt;
7356 int port;
7357 const char *useragent;
7358 struct hostent *hp;
7359 struct ast_hostent ahp;
7360 struct sockaddr_in oldsin;
7362 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
7364 if (ast_strlen_zero(expires)) { /* No expires header */
7365 expires = strcasestr(contact, ";expires=");
7366 if (expires) {
7367 /* XXX bug here, we overwrite the string */
7368 expires = strsep((char **) &expires, ";"); /* trim ; and beyond */
7369 if (sscanf(expires + 9, "%d", &expiry) != 1)
7370 expiry = default_expiry;
7371 } else {
7372 /* Nothing has been specified */
7373 expiry = default_expiry;
7377 /* Look for brackets */
7378 curi = contact;
7379 if (strchr(contact, '<') == NULL) /* No <, check for ; and strip it */
7380 strsep(&curi, ";"); /* This is Header options, not URI options */
7381 curi = get_in_brackets(contact);
7383 /* if they did not specify Contact: or Expires:, they are querying
7384 what we currently have stored as their contact address, so return
7387 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
7388 /* If we have an active registration, tell them when the registration is going to expire */
7389 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
7390 pvt->expiry = ast_sched_when(sched, peer->expire);
7391 return PARSE_REGISTER_QUERY;
7392 } else if (!strcasecmp(curi, "*") || !expiry) { /* Unregister this peer */
7393 /* This means remove all registrations and return OK */
7394 memset(&peer->addr, 0, sizeof(peer->addr));
7395 if (peer->expire > -1)
7396 ast_sched_del(sched, peer->expire);
7397 peer->expire = -1;
7399 destroy_association(peer);
7401 register_peer_exten(peer, 0); /* Add extension from regexten= setting in sip.conf */
7402 peer->fullcontact[0] = '\0';
7403 peer->useragent[0] = '\0';
7404 peer->sipoptions = 0;
7405 peer->lastms = 0;
7407 if (option_verbose > 2)
7408 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", peer->name);
7409 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
7410 return PARSE_REGISTER_UPDATE;
7413 /* Store whatever we got as a contact from the client */
7414 ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));
7416 /* For the 200 OK, we should use the received contact */
7417 ast_string_field_build(pvt, our_contact, "<%s>", curi);
7419 /* Make sure it's a SIP URL */
7420 if (strncasecmp(curi, "sip:", 4)) {
7421 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", curi);
7422 } else
7423 curi += 4;
7424 /* Ditch q */
7425 curi = strsep(&curi, ";");
7426 /* Grab host */
7427 n = strchr(curi, '@');
7428 if (!n) {
7429 n = curi;
7430 curi = NULL;
7431 } else
7432 *n++ = '\0';
7433 pt = strchr(n, ':');
7434 if (pt) {
7435 *pt++ = '\0';
7436 port = atoi(pt);
7437 } else
7438 port = DEFAULT_SIP_PORT;
7439 oldsin = peer->addr;
7440 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
7441 /* XXX This could block for a long time XXX */
7442 hp = ast_gethostbyname(n, &ahp);
7443 if (!hp) {
7444 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
7445 return PARSE_REGISTER_FAILED;
7447 peer->addr.sin_family = AF_INET;
7448 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
7449 peer->addr.sin_port = htons(port);
7450 } else {
7451 /* Don't trust the contact field. Just use what they came to us
7452 with */
7453 peer->addr = pvt->recv;
7456 /* Save SIP options profile */
7457 peer->sipoptions = pvt->sipoptions;
7459 if (curi) /* Overwrite the default username from config at registration */
7460 ast_copy_string(peer->username, curi, sizeof(peer->username));
7461 else
7462 peer->username[0] = '\0';
7464 if (peer->expire > -1)
7465 ast_sched_del(sched, peer->expire);
7466 if (expiry > max_expiry)
7467 expiry = max_expiry;
7468 if (expiry < min_expiry)
7469 expiry = min_expiry;
7470 peer->expire = ast_test_flag(&peer->flags[0], SIP_REALTIME) ? -1 :
7471 ast_sched_add(sched, (expiry + 10) * 1000, expire_register, peer);
7472 pvt->expiry = expiry;
7473 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);
7474 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
7475 ast_db_put("SIP/Registry", peer->name, data);
7476 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
7478 /* Is this a new IP address for us? */
7479 if (inaddrcmp(&peer->addr, &oldsin)) {
7480 sip_poke_peer(peer);
7481 if (option_verbose > 2)
7482 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);
7483 register_peer_exten(peer, 1);
7486 /* Save User agent */
7487 useragent = get_header(req, "User-Agent");
7488 if (useragent && strcasecmp(useragent, peer->useragent)) {
7489 ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
7490 if (option_verbose > 3)
7491 ast_verbose(VERBOSE_PREFIX_3 "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
7493 return PARSE_REGISTER_UPDATE;
7496 /*! \brief Remove route from route list */
7497 static void free_old_route(struct sip_route *route)
7499 struct sip_route *next;
7501 while (route) {
7502 next = route->next;
7503 free(route);
7504 route = next;
7508 /*! \brief List all routes - mostly for debugging */
7509 static void list_route(struct sip_route *route)
7511 if (!route)
7512 ast_verbose("list_route: no route\n");
7513 else {
7514 for (;route; route = route->next)
7515 ast_verbose("list_route: hop: <%s>\n", route->hop);
7519 /*! \brief Build route list from Record-Route header */
7520 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
7522 struct sip_route *thishop, *head, *tail;
7523 int start = 0;
7524 int len;
7525 const char *rr, *contact, *c;
7527 /* Once a persistant route is set, don't fool with it */
7528 if (p->route && p->route_persistant) {
7529 ast_log(LOG_DEBUG, "build_route: Retaining previous route: <%s>\n", p->route->hop);
7530 return;
7533 if (p->route) {
7534 free_old_route(p->route);
7535 p->route = NULL;
7538 p->route_persistant = backwards;
7540 /* Build a tailq, then assign it to p->route when done.
7541 * If backwards, we add entries from the head so they end up
7542 * in reverse order. However, we do need to maintain a correct
7543 * tail pointer because the contact is always at the end.
7545 head = NULL;
7546 tail = head;
7547 /* 1st we pass through all the hops in any Record-Route headers */
7548 for (;;) {
7549 /* Each Record-Route header */
7550 rr = __get_header(req, "Record-Route", &start);
7551 if (*rr == '\0')
7552 break;
7553 for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
7554 ++rr;
7555 len = strcspn(rr, ">") + 1;
7556 /* Make a struct route */
7557 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
7558 /* ast_calloc is not needed because all fields are initialized in this block */
7559 ast_copy_string(thishop->hop, rr, len);
7560 if (option_debug > 1)
7561 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
7562 /* Link in */
7563 if (backwards) {
7564 /* Link in at head so they end up in reverse order */
7565 thishop->next = head;
7566 head = thishop;
7567 /* If this was the first then it'll be the tail */
7568 if (!tail)
7569 tail = thishop;
7570 } else {
7571 thishop->next = NULL;
7572 /* Link in at the end */
7573 if (tail)
7574 tail->next = thishop;
7575 else
7576 head = thishop;
7577 tail = thishop;
7583 /* Only append the contact if we are dealing with a strict router */
7584 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop,";lr") == NULL) ) {
7585 /* 2nd append the Contact: if there is one */
7586 /* Can be multiple Contact headers, comma separated values - we just take the first */
7587 contact = get_header(req, "Contact");
7588 if (!ast_strlen_zero(contact)) {
7589 if (option_debug > 1)
7590 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
7591 /* Look for <: delimited address */
7592 c = strchr(contact, '<');
7593 if (c) {
7594 /* Take to > */
7595 ++c;
7596 len = strcspn(c, ">") + 1;
7597 } else {
7598 /* No <> - just take the lot */
7599 c = contact;
7600 len = strlen(contact) + 1;
7602 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
7603 /* ast_calloc is not needed because all fields are initialized in this block */
7604 ast_copy_string(thishop->hop, c, len);
7605 thishop->next = NULL;
7606 /* Goes at the end */
7607 if (tail)
7608 tail->next = thishop;
7609 else
7610 head = thishop;
7615 /* Store as new route */
7616 p->route = head;
7618 /* For debugging dump what we ended up with */
7619 if (sip_debug_test_pvt(p))
7620 list_route(p->route);
7624 /*! \brief Check user authorization from peer definition
7625 Some actions, like REGISTER and INVITEs from peers require
7626 authentication (if peer have secret set)
7627 \return 0 on success, non-zero on error
7629 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
7630 const char *secret, const char *md5secret, int sipmethod,
7631 char *uri, enum xmittype reliable, int ignore)
7633 const char *response = "407 Proxy Authentication Required";
7634 const char *reqheader = "Proxy-Authorization";
7635 const char *respheader = "Proxy-Authenticate";
7636 const char *authtoken;
7637 char a1_hash[256];
7638 char resp_hash[256]="";
7639 char tmp[BUFSIZ * 2]; /* Make a large enough buffer */
7640 char *c;
7641 int wrongnonce = FALSE;
7642 int good_response;
7643 const char *usednonce = p->randdata;
7645 /* table of recognised keywords, and their value in the digest */
7646 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
7647 struct x {
7648 const char *key;
7649 const char *s;
7650 } *i, keys[] = {
7651 [K_RESP] = { "response=", "" },
7652 [K_URI] = { "uri=", "" },
7653 [K_USER] = { "username=", "" },
7654 [K_NONCE] = { "nonce=", "" },
7655 [K_LAST] = { NULL, NULL}
7658 /* Always OK if no secret */
7659 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
7660 return AUTH_SUCCESSFUL;
7661 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
7662 /* On a REGISTER, we have to use 401 and its family of headers instead of 407 and its family
7663 of headers -- GO SIP! Whoo hoo! Two things that do the same thing but are used in
7664 different circumstances! What a surprise. */
7665 response = "401 Unauthorized";
7666 reqheader = "Authorization";
7667 respheader = "WWW-Authenticate";
7669 authtoken = get_header(req, reqheader);
7670 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
7671 /* This is a retransmitted invite/register/etc, don't reconstruct authentication
7672 information */
7673 if (!reliable) {
7674 /* Resend message if this was NOT a reliable delivery. Otherwise the
7675 retransmission should get it */
7676 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
7677 /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
7678 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
7680 return AUTH_CHALLENGE_SENT;
7681 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
7682 /* We have no auth, so issue challenge and request authentication */
7683 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
7684 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
7685 /* Schedule auto destroy in 32 seconds */
7686 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
7687 return AUTH_CHALLENGE_SENT;
7690 /* --- We have auth, so check it */
7692 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
7693 an example in the spec of just what it is you're doing a hash on. */
7696 /* Make a copy of the response and parse it */
7697 ast_copy_string(tmp, authtoken, sizeof(tmp));
7698 c = tmp;
7700 while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
7701 for (i = keys; i->key != NULL; i++) {
7702 const char *separator = ","; /* default */
7704 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
7705 continue;
7706 /* Found. Skip keyword, take text in quotes or up to the separator. */
7707 c += strlen(i->key);
7708 if (*c == '"') { /* in quotes. Skip first and look for last */
7709 c++;
7710 separator = "\"";
7712 i->s = c;
7713 strsep(&c, separator);
7714 break;
7716 if (i->key == NULL) /* not found, jump after space or comma */
7717 strsep(&c, " ,");
7720 /* Verify that digest username matches the username we auth as */
7721 if (strcmp(username, keys[K_USER].s)) {
7722 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
7723 username, keys[K_USER].s);
7724 /* Oops, we're trying something here */
7725 return AUTH_USERNAME_MISMATCH;
7728 /* Verify nonce from request matches our nonce. If not, send 401 with new nonce */
7729 if (strcasecmp(p->randdata, keys[K_NONCE].s)) { /* XXX it was 'n'casecmp ? */
7730 wrongnonce = TRUE;
7731 usednonce = keys[K_NONCE].s;
7734 if (!ast_strlen_zero(md5secret))
7735 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
7736 else {
7737 char a1[256];
7738 snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
7739 ast_md5_hash(a1_hash, a1);
7742 /* compute the expected response to compare with what we received */
7744 char a2[256];
7745 char a2_hash[256];
7746 char resp[256];
7748 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
7749 S_OR(keys[K_URI].s, uri));
7750 ast_md5_hash(a2_hash, a2);
7751 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
7752 ast_md5_hash(resp_hash, resp);
7755 good_response = keys[K_RESP].s &&
7756 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
7757 if (wrongnonce) {
7758 ast_string_field_build(p, randdata, "%08lx", ast_random());
7759 if (good_response) {
7760 if (sipdebug)
7761 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
7762 /* We got working auth token, based on stale nonce . */
7763 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 1);
7764 } else {
7765 /* Everything was wrong, so give the device one more try with a new challenge */
7766 if (sipdebug)
7767 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
7768 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
7771 /* Schedule auto destroy in 32 seconds */
7772 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
7773 return AUTH_CHALLENGE_SENT;
7775 if (good_response)
7776 return AUTH_SUCCESSFUL;
7778 /* Ok, we have a bad username/secret pair */
7779 /* Challenge again, and again, and again */
7780 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
7781 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
7783 return AUTH_CHALLENGE_SENT;
7786 /*! \brief Change onhold state of a peer using a pvt structure */
7787 static void sip_peer_hold(struct sip_pvt *p, int hold)
7789 struct sip_peer *peer = find_peer(p->peername, NULL, 1);
7791 if (!peer)
7792 return;
7794 /* If they put someone on hold, increment the value... otherwise decrement it */
7795 if (hold)
7796 peer->onHold++;
7797 else if (hold > 0)
7798 peer->onHold--;
7800 /* Request device state update */
7801 ast_device_state_changed("SIP/%s", peer->name);
7803 return;
7806 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
7807 \note If you add an "hint" priority to the extension in the dial plan,
7808 you will get notifications on device state changes */
7809 static int cb_extensionstate(char *context, char* exten, int state, void *data)
7811 struct sip_pvt *p = data;
7813 switch(state) {
7814 case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
7815 case AST_EXTENSION_REMOVED: /* Extension is gone */
7816 if (p->autokillid > -1)
7817 sip_cancel_destroy(p); /* Remove subscription expiry for renewals */
7818 sip_scheddestroy(p, SIP_TRANS_TIMEOUT); /* Delete subscription in 32 secs */
7819 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);
7820 p->stateid = -1;
7821 p->subscribed = NONE;
7822 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
7823 break;
7824 default: /* Tell user */
7825 p->laststate = state;
7826 break;
7828 transmit_state_notify(p, state, 1);
7830 if (option_debug > 1)
7831 ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %s for Notify User %s\n", exten, ast_extension_state2str(state), p->username);
7832 return 0;
7835 /*! \brief Send a fake 401 Unauthorized response when the administrator
7836 wants to hide the names of local users/peers from fishers
7838 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable)
7840 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
7841 transmit_response_with_auth(p, "401 Unauthorized", req, p->randdata, reliable, "WWW-Authenticate", 0);
7844 /*! \brief Verify registration of user
7845 - Registration is done in several steps, first a REGISTER without auth
7846 to get a challenge (nonce) then a second one with auth
7847 - Registration requests are only matched with peers that are marked as "dynamic"
7849 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
7850 struct sip_request *req, char *uri)
7852 enum check_auth_result res = AUTH_NOT_FOUND;
7853 struct sip_peer *peer;
7854 char tmp[256];
7855 char *name, *c;
7856 char *t;
7857 char *domain;
7859 /* Terminate URI */
7860 t = uri;
7861 while(*t && (*t > 32) && (*t != ';'))
7862 t++;
7863 *t = '\0';
7865 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
7866 if (pedanticsipchecking)
7867 ast_uri_decode(tmp);
7869 c = get_in_brackets(tmp);
7870 c = strsep(&c, ";"); /* Ditch ;user=phone */
7872 if (!strncmp(c, "sip:", 4)) {
7873 name = c + 4;
7874 } else {
7875 name = c;
7876 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
7879 /* Strip off the domain name */
7880 if ((c = strchr(name, '@'))) {
7881 *c++ = '\0';
7882 domain = c;
7883 if ((c = strchr(domain, ':'))) /* Remove :port */
7884 *c = '\0';
7885 if (!AST_LIST_EMPTY(&domain_list)) {
7886 if (!check_sip_domain(domain, NULL, 0)) {
7887 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
7888 return AUTH_UNKNOWN_DOMAIN;
7893 ast_string_field_set(p, exten, name);
7894 build_contact(p);
7895 peer = find_peer(name, NULL, 1);
7896 if (!(peer && ast_apply_ha(peer->ha, sin))) {
7897 if (peer)
7898 ASTOBJ_UNREF(peer, sip_destroy_peer);
7900 if (peer) {
7901 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
7902 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
7903 } else {
7904 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
7905 transmit_response(p, "100 Trying", req);
7906 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, ast_test_flag(req, SIP_PKT_IGNORE)))) {
7907 sip_cancel_destroy(p);
7909 /* We have a succesful registration attemp with proper authentication,
7910 now, update the peer */
7911 switch (parse_register_contact(p, peer, req)) {
7912 case PARSE_REGISTER_FAILED:
7913 ast_log(LOG_WARNING, "Failed to parse contact info\n");
7914 transmit_response_with_date(p, "400 Bad Request", req);
7915 peer->lastmsgssent = -1;
7916 res = 0;
7917 break;
7918 case PARSE_REGISTER_QUERY:
7919 transmit_response_with_date(p, "200 OK", req);
7920 peer->lastmsgssent = -1;
7921 res = 0;
7922 break;
7923 case PARSE_REGISTER_UPDATE:
7924 update_peer(peer, p->expiry);
7925 /* Say OK and ask subsystem to retransmit msg counter */
7926 transmit_response_with_date(p, "200 OK", req);
7927 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
7928 peer->lastmsgssent = -1;
7929 res = 0;
7930 break;
7935 if (!peer && autocreatepeer) {
7936 /* Create peer if we have autocreate mode enabled */
7937 peer = temp_peer(name);
7938 if (peer) {
7939 ASTOBJ_CONTAINER_LINK(&peerl, peer);
7940 sip_cancel_destroy(p);
7941 switch (parse_register_contact(p, peer, req)) {
7942 case PARSE_REGISTER_FAILED:
7943 ast_log(LOG_WARNING, "Failed to parse contact info\n");
7944 transmit_response_with_date(p, "400 Bad Request", req);
7945 peer->lastmsgssent = -1;
7946 res = 0;
7947 break;
7948 case PARSE_REGISTER_QUERY:
7949 transmit_response_with_date(p, "200 OK", req);
7950 peer->lastmsgssent = -1;
7951 res = 0;
7952 break;
7953 case PARSE_REGISTER_UPDATE:
7954 /* Say OK and ask subsystem to retransmit msg counter */
7955 transmit_response_with_date(p, "200 OK", req);
7956 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
7957 peer->lastmsgssent = -1;
7958 res = 0;
7959 break;
7963 if (!res) {
7964 ast_device_state_changed("SIP/%s", peer->name);
7966 if (res < 0) {
7967 switch (res) {
7968 case AUTH_SECRET_FAILED:
7969 /* Wrong password in authentication. Go away, don't try again until you fixed it */
7970 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
7971 break;
7972 case AUTH_USERNAME_MISMATCH:
7973 /* Username and digest username does not match.
7974 Asterisk uses the From: username for authentication. We need the
7975 users to use the same authentication user name until we support
7976 proper authentication by digest auth name */
7977 transmit_response(p, "403 Authentication user name does not match account name", &p->initreq);
7978 break;
7979 case AUTH_NOT_FOUND:
7980 if (global_alwaysauthreject) {
7981 transmit_fake_auth_response(p, &p->initreq, 1);
7982 } else {
7983 /* URI not found */
7984 transmit_response(p, "404 Not found", &p->initreq);
7986 break;
7987 default:
7988 break;
7990 if (option_debug > 1) {
7991 const char *reason = "";
7993 switch (res) {
7994 case AUTH_SECRET_FAILED:
7995 reason = "Bad password";
7996 break;
7997 case AUTH_USERNAME_MISMATCH:
7998 reason = "Bad digest user";
7999 break;
8000 case AUTH_NOT_FOUND:
8001 reason = "Peer not found";
8002 break;
8003 default:
8004 break;
8006 ast_log(LOG_DEBUG, "SIP REGISTER attempt failed for %s : %s\n",
8007 peer->name, reason);
8010 if (peer)
8011 ASTOBJ_UNREF(peer, sip_destroy_peer);
8013 return res;
8016 /*! \brief Get referring dnis */
8017 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
8019 char tmp[256], *c, *a;
8020 struct sip_request *req;
8022 req = oreq;
8023 if (!req)
8024 req = &p->initreq;
8025 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
8026 if (ast_strlen_zero(tmp))
8027 return 0;
8028 c = get_in_brackets(tmp);
8029 if (strncmp(c, "sip:", 4)) {
8030 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", c);
8031 return -1;
8033 c += 4;
8034 a = c;
8035 strsep(&a, "@;"); /* trim anything after @ or ; */
8036 if (sip_debug_test_pvt(p))
8037 ast_verbose("RDNIS is %s\n", c);
8038 ast_string_field_set(p, rdnis, c);
8040 return 0;
8043 /*! \brief Find out who the call is for
8044 We use the INVITE uri to find out
8046 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
8048 char tmp[256] = "", *uri, *a;
8049 char tmpf[256] = "", *from;
8050 struct sip_request *req;
8051 char *colon;
8053 req = oreq;
8054 if (!req)
8055 req = &p->initreq;
8057 /* Find the request URI */
8058 if (req->rlPart2)
8059 ast_copy_string(tmp, req->rlPart2, sizeof(tmp));
8061 if (pedanticsipchecking)
8062 ast_uri_decode(tmp);
8064 uri = get_in_brackets(tmp);
8066 if (strncmp(uri, "sip:", 4)) {
8067 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
8068 return -1;
8070 uri += 4;
8072 /* Now find the From: caller ID and name */
8073 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
8074 if (!ast_strlen_zero(tmpf)) {
8075 if (pedanticsipchecking)
8076 ast_uri_decode(tmpf);
8077 from = get_in_brackets(tmpf);
8078 } else {
8079 from = NULL;
8082 if (!ast_strlen_zero(from)) {
8083 if (strncmp(from, "sip:", 4)) {
8084 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
8085 return -1;
8087 from += 4;
8088 if ((a = strchr(from, '@')))
8089 *a++ = '\0';
8090 else
8091 a = from; /* just a domain */
8092 from = strsep(&from, ";"); /* Remove userinfo options */
8093 a = strsep(&a, ";"); /* Remove URI options */
8094 ast_string_field_set(p, fromdomain, a);
8097 /* Skip any options and find the domain */
8099 /* Get the target domain */
8100 if ((a = strchr(uri, '@'))) {
8101 *a++ = '\0';
8102 } else { /* No username part */
8103 a = uri;
8104 uri = "s"; /* Set extension to "s" */
8106 colon = strchr(a, ':'); /* Remove :port */
8107 if (colon)
8108 *colon = '\0';
8110 uri = strsep(&uri, ";"); /* Remove userinfo options */
8111 a = strsep(&a, ";"); /* Remove URI options */
8113 ast_string_field_set(p, domain, a);
8115 if (!AST_LIST_EMPTY(&domain_list)) {
8116 char domain_context[AST_MAX_EXTENSION];
8118 domain_context[0] = '\0';
8119 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
8120 if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
8121 ast_log(LOG_DEBUG, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
8122 return -2;
8125 /* If we have a context defined, overwrite the original context */
8126 if (!ast_strlen_zero(domain_context))
8127 ast_string_field_set(p, context, domain_context);
8130 if (sip_debug_test_pvt(p))
8131 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
8133 /* Check the dialplan for the username part of the request URI,
8134 the domain will be stored in the SIPDOMAIN variable
8135 Return 0 if we have a matching extension */
8136 if (ast_exists_extension(NULL, p->context, uri, 1, from) ||
8137 !strcmp(uri, ast_pickup_ext())) {
8138 if (!oreq)
8139 ast_string_field_set(p, exten, uri);
8140 return 0;
8143 /* Return 1 for pickup extension or overlap dialling support (if we support it) */
8144 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
8145 ast_canmatch_extension(NULL, p->context, uri, 1, from)) ||
8146 !strncmp(uri, ast_pickup_ext(), strlen(uri))) {
8147 return 1;
8150 return -1;
8153 /*! \brief Lock interface lock and find matching pvt lock
8154 - Their tag is fromtag, our tag is to-tag
8155 - This means that in some transactions, totag needs to be their tag :-)
8156 depending upon the direction
8158 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
8160 struct sip_pvt *sip_pvt_ptr;
8162 ast_mutex_lock(&iflock);
8164 if (option_debug > 3 && totag)
8165 ast_log(LOG_DEBUG, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
8167 /* Search interfaces and find the match */
8168 for (sip_pvt_ptr = iflist; sip_pvt_ptr; sip_pvt_ptr = sip_pvt_ptr->next) {
8169 if (!strcmp(sip_pvt_ptr->callid, callid)) {
8170 int match = 1;
8171 char *ourtag = sip_pvt_ptr->tag;
8173 /* Go ahead and lock it (and its owner) before returning */
8174 ast_mutex_lock(&sip_pvt_ptr->lock);
8176 /* Check if tags match. If not, this is not the call we want
8177 (With a forking SIP proxy, several call legs share the
8178 call id, but have different tags)
8180 if (pedanticsipchecking && (strcmp(fromtag, sip_pvt_ptr->theirtag) || strcmp(totag, ourtag)))
8181 match = 0;
8183 if (!match) {
8184 ast_mutex_unlock(&sip_pvt_ptr->lock);
8185 break;
8188 if (option_debug > 3 && totag)
8189 ast_log(LOG_DEBUG, "Matched %s call - their tag is %s Our tag is %s\n",
8190 ast_test_flag(&sip_pvt_ptr->flags[0], SIP_OUTGOING) ? "OUTGOING": "INCOMING",
8191 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
8193 /* deadlock avoidance... */
8194 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
8195 ast_mutex_unlock(&sip_pvt_ptr->lock);
8196 usleep(1);
8197 ast_mutex_lock(&sip_pvt_ptr->lock);
8199 break;
8202 ast_mutex_unlock(&iflock);
8203 if (option_debug > 3 && !sip_pvt_ptr)
8204 ast_log(LOG_DEBUG, "Found no match for callid %s to-tag %s from-tag %s\n", callid, totag, fromtag);
8205 return sip_pvt_ptr;
8208 /*! \brief Call transfer support (the REFER method)
8209 * Extracts Refer headers into pvt dialog structure */
8210 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
8213 const char *p_referred_by = NULL;
8214 char *h_refer_to = NULL;
8215 char *h_referred_by = NULL;
8216 char *refer_to;
8217 const char *p_refer_to;
8218 char *referred_by_uri = NULL;
8219 char *ptr;
8220 struct sip_request *req = NULL;
8221 const char *transfer_context = NULL;
8222 struct sip_refer *referdata;
8225 req = outgoing_req;
8226 referdata = transferer->refer;
8228 if (!req)
8229 req = &transferer->initreq;
8231 if (!(p_refer_to = get_header(req, "Refer-To"))) {
8232 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
8233 return -2; /* Syntax error */
8235 h_refer_to = ast_strdupa(p_refer_to);
8236 refer_to = get_in_brackets(h_refer_to);
8237 if (pedanticsipchecking)
8238 ast_uri_decode(refer_to);
8240 if (strncasecmp(refer_to, "sip:", 4)) {
8241 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
8242 return -3;
8244 refer_to += 4; /* Skip sip: */
8246 /* Get referred by header if it exists */
8247 if ((p_referred_by = get_header(req, "Referred-By"))) {
8248 char *lessthan;
8249 h_referred_by = ast_strdupa(p_referred_by);
8250 if (pedanticsipchecking)
8251 ast_uri_decode(h_referred_by);
8253 /* Store referrer's caller ID name */
8254 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
8255 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
8256 *(lessthan - 1) = '\0'; /* Space */
8259 referred_by_uri = get_in_brackets(h_referred_by);
8260 if(strncasecmp(referred_by_uri, "sip:", 4)) {
8261 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
8262 referred_by_uri = (char *) NULL;
8263 } else {
8264 referred_by_uri += 4; /* Skip sip: */
8268 /* Check for arguments in the refer_to header */
8269 if ((ptr = strchr(refer_to, '?'))) { /* Search for arguments */
8270 *ptr++ = '\0';
8271 if (!strncasecmp(ptr, "REPLACES=", 9)) {
8272 char *to = NULL, *from = NULL;
8274 /* This is an attended transfer */
8275 referdata->attendedtransfer = 1;
8276 strncpy(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
8277 ast_uri_decode(referdata->replaces_callid);
8278 if ((ptr = strchr(referdata->replaces_callid, ';'))) /* Find options */ {
8279 *ptr++ = '\0';
8282 if (ptr) {
8283 /* Find the different tags before we destroy the string */
8284 to = strcasestr(ptr, "to-tag=");
8285 from = strcasestr(ptr, "from-tag=");
8288 /* Grab the to header */
8289 if (to) {
8290 ptr = to + 7;
8291 if ((to = strchr(ptr, '&')))
8292 *to = '\0';
8293 if ((to = strchr(ptr, ';')))
8294 *to = '\0';
8295 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
8298 if (from) {
8299 ptr = from + 9;
8300 if ((to = strchr(ptr, '&')))
8301 *to = '\0';
8302 if ((to = strchr(ptr, ';')))
8303 *to = '\0';
8304 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
8307 if (option_debug > 1) {
8308 if (!pedanticsipchecking)
8309 ast_log(LOG_DEBUG,"Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
8310 else
8311 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>" );
8316 if ((ptr = strchr(refer_to, '@'))) { /* Separate domain */
8317 char *urioption;
8319 *ptr++ = '\0';
8320 if ((urioption = strchr(ptr, ';')))
8321 *urioption++ = '\0';
8322 /* Save the domain for the dial plan */
8323 strncpy(referdata->refer_to_domain, ptr, sizeof(referdata->refer_to_domain));
8324 if (urioption)
8325 strncpy(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
8328 if ((ptr = strchr(refer_to, ';'))) /* Remove options */
8329 *ptr = '\0';
8330 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
8332 if (referred_by_uri) {
8333 if ((ptr = strchr(referred_by_uri, ';'))) /* Remove options */
8334 *ptr = '\0';
8335 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
8336 } else {
8337 referdata->referred_by[0] = '\0';
8340 /* Determine transfer context */
8341 if (transferer->owner) /* Mimic behaviour in res_features.c */
8342 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
8344 /* By default, use the context in the channel sending the REFER */
8345 if (ast_strlen_zero(transfer_context)) {
8346 transfer_context = S_OR(transferer->owner->macrocontext,
8347 S_OR(transferer->context, default_context));
8350 strncpy(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
8352 /* Either an existing extension or the parking extension */
8353 if (ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
8354 if (sip_debug_test_pvt(transferer)) {
8355 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
8357 /* We are ready to transfer to the extension */
8358 return 0;
8360 if (sip_debug_test_pvt(transferer))
8361 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
8363 /* Failure, we can't find this extension */
8364 return -1;
8368 /*! \brief Call transfer support (old way, deprecated by the IETF)--*/
8369 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
8371 char tmp[256] = "", *c, *a;
8372 struct sip_request *req = oreq ? oreq : &p->initreq;
8373 struct sip_refer *referdata = p->refer;
8374 const char *transfer_context = NULL;
8376 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
8377 c = get_in_brackets(tmp);
8379 if (pedanticsipchecking)
8380 ast_uri_decode(c);
8382 if (strncmp(c, "sip:", 4)) {
8383 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
8384 return -1;
8386 c += 4;
8387 if ((a = strchr(c, '@'))) { /* Separate Domain */
8388 *a++ = '\0';
8389 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
8392 if ((a = strchr(c, ';'))) /* Remove arguments */
8393 *a = '\0';
8395 if (sip_debug_test_pvt(p))
8396 ast_verbose("Looking for %s in %s\n", c, p->context);
8398 if (p->owner) /* Mimic behaviour in res_features.c */
8399 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
8401 /* By default, use the context in the channel sending the REFER */
8402 if (ast_strlen_zero(transfer_context)) {
8403 transfer_context = S_OR(p->owner->macrocontext,
8404 S_OR(p->context, default_context));
8406 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
8407 /* This is a blind transfer */
8408 if (option_debug)
8409 ast_log(LOG_DEBUG,"SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
8410 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
8411 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
8412 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
8413 referdata->refer_call = NULL;
8414 /* Set new context */
8415 ast_string_field_set(p, context, transfer_context);
8416 return 0;
8417 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
8418 return 1;
8421 return -1;
8423 /*! \brief check Via: header for hostname, port and rport request/answer */
8424 static void check_via(struct sip_pvt *p, struct sip_request *req)
8426 char via[256];
8427 char *c, *pt;
8428 struct hostent *hp;
8429 struct ast_hostent ahp;
8431 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
8433 /* Check for rport */
8434 c = strstr(via, ";rport");
8435 if (c && (c[6] != '=')) /* rport query, not answer */
8436 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
8438 c = strchr(via, ';');
8439 if (c)
8440 *c = '\0';
8442 c = strchr(via, ' ');
8443 if (c) {
8444 *c = '\0';
8445 c = ast_skip_blanks(c+1);
8446 if (strcasecmp(via, "SIP/2.0/UDP")) {
8447 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
8448 return;
8450 pt = strchr(c, ':');
8451 if (pt)
8452 *pt++ = '\0'; /* remember port pointer */
8453 hp = ast_gethostbyname(c, &ahp);
8454 if (!hp) {
8455 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
8456 return;
8458 memset(&p->sa, 0, sizeof(p->sa));
8459 p->sa.sin_family = AF_INET;
8460 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
8461 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
8463 if (sip_debug_test_pvt(p)) {
8464 const struct sockaddr_in *dst = sip_real_dst(p);
8465 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
8470 /*! \brief Get caller id name from SIP headers */
8471 static char *get_calleridname(const char *input, char *output, size_t outputsize)
8473 const char *end = strchr(input,'<'); /* first_bracket */
8474 const char *tmp = strchr(input,'"'); /* first quote */
8475 int bytes = 0;
8476 int maxbytes = outputsize - 1;
8478 if (!end || end == input) /* we require a part in brackets */
8479 return NULL;
8481 /* move away from "<" */
8482 end--;
8484 /* we found "name" */
8485 if (tmp && tmp < end) {
8486 end = strchr(tmp+1, '"');
8487 if (!end)
8488 return NULL;
8489 bytes = (int) (end - tmp);
8490 /* protect the output buffer */
8491 if (bytes > maxbytes)
8492 bytes = maxbytes;
8493 ast_copy_string(output, tmp + 1, bytes);
8494 } else {
8495 /* we didn't find "name" */
8496 /* clear the empty characters in the begining*/
8497 input = ast_skip_blanks(input);
8498 /* clear the empty characters in the end */
8499 while(*end && *end < 33 && end > input)
8500 end--;
8501 if (end >= input) {
8502 bytes = (int) (end - input) + 2;
8503 /* protect the output buffer */
8504 if (bytes > maxbytes)
8505 bytes = maxbytes;
8506 ast_copy_string(output, input, bytes);
8507 } else
8508 return NULL;
8510 return output;
8513 /*! \brief Get caller id number from Remote-Party-ID header field
8514 * Returns true if number should be restricted (privacy setting found)
8515 * output is set to NULL if no number found
8517 static int get_rpid_num(const char *input, char *output, int maxlen)
8519 char *start;
8520 char *end;
8522 start = strchr(input,':');
8523 if (!start) {
8524 output[0] = '\0';
8525 return 0;
8527 start++;
8529 /* we found "number" */
8530 ast_copy_string(output,start,maxlen);
8531 output[maxlen-1] = '\0';
8533 end = strchr(output,'@');
8534 if (end)
8535 *end = '\0';
8536 else
8537 output[0] = '\0';
8538 if (strstr(input,"privacy=full") || strstr(input,"privacy=uri"))
8539 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
8541 return 0;
8545 /*! \brief Check if matching user or peer is defined
8546 Match user on From: user name and peer on IP/port
8547 This is used on first invite (not re-invites) and subscribe requests
8548 \return 0 on success, non-zero on failure
8550 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
8551 int sipmethod, char *uri, enum xmittype reliable,
8552 struct sockaddr_in *sin, struct sip_peer **authpeer)
8554 struct sip_user *user = NULL;
8555 struct sip_peer *peer;
8556 char from[256], *c;
8557 char *of;
8558 char rpid_num[50];
8559 const char *rpid;
8560 enum check_auth_result res = AUTH_SUCCESSFUL;
8561 char *t;
8562 char calleridname[50];
8563 int debug=sip_debug_test_addr(sin);
8564 struct ast_variable *tmpvar = NULL, *v = NULL;
8565 int usenatroute;
8566 char *uri2 = ast_strdupa(uri);
8568 /* Terminate URI */
8569 t = uri2;
8570 while (*t && *t > 32 && *t != ';')
8571 t++;
8572 *t = '\0';
8573 ast_copy_string(from, get_header(req, "From"), sizeof(from)); /* XXX bug in original code, overwrote string */
8574 if (pedanticsipchecking)
8575 ast_uri_decode(from);
8576 /* XXX here tries to map the username for invite things */
8577 memset(calleridname, 0, sizeof(calleridname));
8578 get_calleridname(from, calleridname, sizeof(calleridname));
8579 if (calleridname[0])
8580 ast_string_field_set(p, cid_name, calleridname);
8582 rpid = get_header(req, "Remote-Party-ID");
8583 memset(rpid_num, 0, sizeof(rpid_num));
8584 if (!ast_strlen_zero(rpid))
8585 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
8587 of = get_in_brackets(from);
8588 if (ast_strlen_zero(p->exten)) {
8589 t = uri2;
8590 if (!strncmp(t, "sip:", 4))
8591 t+= 4;
8592 ast_string_field_set(p, exten, t);
8593 t = strchr(p->exten, '@');
8594 if (t)
8595 *t = '\0';
8596 if (ast_strlen_zero(p->our_contact))
8597 build_contact(p);
8599 /* save the URI part of the From header */
8600 ast_string_field_set(p, from, of);
8601 if (strncmp(of, "sip:", 4)) {
8602 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
8603 } else
8604 of += 4;
8605 /* Get just the username part */
8606 if ((c = strchr(of, '@'))) {
8607 char *tmp;
8608 *c = '\0';
8609 if ((c = strchr(of, ':')))
8610 *c = '\0';
8611 tmp = ast_strdupa(of);
8612 if (ast_is_shrinkable_phonenumber(tmp))
8613 ast_shrink_phone_number(tmp);
8614 ast_string_field_set(p, cid_num, tmp);
8616 if (ast_strlen_zero(of))
8617 return AUTH_SUCCESSFUL;
8619 if (!authpeer) /* If we are looking for a peer, don't check the user objects (or realtime) */
8620 user = find_user(of, 1);
8622 /* Find user based on user name in the from header */
8623 if (user && ast_apply_ha(user->ha, sin)) {
8624 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
8625 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
8626 /* copy channel vars */
8627 for (v = user->chanvars ; v ; v = v->next) {
8628 if ((tmpvar = ast_variable_new(v->name, v->value))) {
8629 tmpvar->next = p->chanvars;
8630 p->chanvars = tmpvar;
8633 p->prefs = user->prefs;
8634 /* replace callerid if rpid found, and not restricted */
8635 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
8636 char *tmp;
8637 if (*calleridname)
8638 ast_string_field_set(p, cid_name, calleridname);
8639 tmp = ast_strdupa(rpid_num);
8640 if (ast_is_shrinkable_phonenumber(tmp))
8641 ast_shrink_phone_number(tmp);
8642 ast_string_field_set(p, cid_num, tmp);
8645 usenatroute = ast_test_flag(&p->flags[0], SIP_NAT_ROUTE);
8647 if (p->rtp) {
8648 if (option_debug)
8649 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", usenatroute ? "On" : "Off");
8650 ast_rtp_setnat(p->rtp, usenatroute);
8652 if (p->vrtp) {
8653 if (option_debug)
8654 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", usenatroute ? "On" : "Off");
8655 ast_rtp_setnat(p->vrtp, usenatroute);
8657 if (p->udptl) {
8658 if (option_debug)
8659 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", usenatroute ? "On" : "Off");
8660 ast_udptl_setnat(p->udptl, usenatroute);
8662 if (!(res = check_auth(p, req, user->name, user->secret, user->md5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
8663 sip_cancel_destroy(p);
8664 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
8665 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
8666 /* Copy SIP extensions profile from INVITE */
8667 if (p->sipoptions)
8668 user->sipoptions = p->sipoptions;
8670 /* If we have a call limit, set flag */
8671 if (user->call_limit)
8672 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
8673 if (!ast_strlen_zero(user->context))
8674 ast_string_field_set(p, context, user->context);
8675 if (!ast_strlen_zero(user->cid_num) && !ast_strlen_zero(p->cid_num)) {
8676 char *tmp = ast_strdupa(user->cid_num);
8677 if (ast_is_shrinkable_phonenumber(tmp))
8678 ast_shrink_phone_number(tmp);
8679 ast_string_field_set(p, cid_num, tmp);
8681 if (!ast_strlen_zero(user->cid_name) && !ast_strlen_zero(p->cid_num))
8682 ast_string_field_set(p, cid_name, user->cid_name);
8683 ast_string_field_set(p, username, user->name);
8684 ast_string_field_set(p, peername, user->name);
8685 ast_string_field_set(p, peersecret, user->secret);
8686 ast_string_field_set(p, peermd5secret, user->md5secret);
8687 ast_string_field_set(p, subscribecontext, user->subscribecontext);
8688 ast_string_field_set(p, accountcode, user->accountcode);
8689 ast_string_field_set(p, language, user->language);
8690 ast_string_field_set(p, mohsuggest, user->mohsuggest);
8691 ast_string_field_set(p, mohinterpret, user->mohinterpret);
8692 p->allowtransfer = user->allowtransfer;
8693 p->amaflags = user->amaflags;
8694 p->callgroup = user->callgroup;
8695 p->pickupgroup = user->pickupgroup;
8696 if (user->callingpres) /* User callingpres setting will override RPID header */
8697 p->callingpres = user->callingpres;
8699 /* Set default codec settings for this call */
8700 p->capability = user->capability; /* User codec choice */
8701 p->jointcapability = user->capability; /* Our codecs */
8702 if (p->peercapability) /* AND with peer's codecs */
8703 p->jointcapability &= p->peercapability;
8704 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
8705 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
8706 p->noncodeccapability |= AST_RTP_DTMF;
8707 else
8708 p->noncodeccapability &= ~AST_RTP_DTMF;
8709 if (p->t38.peercapability)
8710 p->t38.jointcapability &= p->t38.peercapability;
8711 p->maxcallbitrate = user->maxcallbitrate;
8712 /* If we do not support video, remove video from call structure */
8713 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && p->vrtp) {
8714 ast_rtp_destroy(p->vrtp);
8715 p->vrtp = NULL;
8718 if (user && debug)
8719 ast_verbose("Found user '%s'\n", user->name);
8720 } else {
8721 if (user) {
8722 if (!authpeer && debug)
8723 ast_verbose("Found user '%s', but fails host access\n", user->name);
8724 ASTOBJ_UNREF(user,sip_destroy_user);
8726 user = NULL;
8729 if (!user) {
8730 /* If we didn't find a user match, check for peers */
8731 if (sipmethod == SIP_SUBSCRIBE)
8732 /* For subscribes, match on peer name only */
8733 peer = find_peer(of, NULL, 1);
8734 else
8735 /* Look for peer based on the IP address we received data from */
8736 /* If peer is registered from this IP address or have this as a default
8737 IP address, this call is from the peer
8739 peer = find_peer(NULL, &p->recv, 1);
8741 if (peer) {
8742 if (debug)
8743 ast_verbose("Found peer '%s'\n", peer->name);
8745 /* Take the peer */
8746 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
8747 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
8749 /* Copy SIP extensions profile to peer */
8750 if (p->sipoptions)
8751 peer->sipoptions = p->sipoptions;
8753 /* replace callerid if rpid found, and not restricted */
8754 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
8755 char *tmp = ast_strdupa(rpid_num);
8756 if (*calleridname)
8757 ast_string_field_set(p, cid_name, calleridname);
8758 if (ast_is_shrinkable_phonenumber(tmp))
8759 ast_shrink_phone_number(tmp);
8760 ast_string_field_set(p, cid_num, tmp);
8762 usenatroute = ast_test_flag(&p->flags[0], SIP_NAT_ROUTE);
8763 if (p->rtp) {
8764 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", usenatroute ? "On" : "Off");
8765 ast_rtp_setnat(p->rtp, usenatroute);
8767 if (p->vrtp) {
8768 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", usenatroute ? "On" : "Off");
8769 ast_rtp_setnat(p->vrtp, usenatroute);
8771 if (p->udptl) {
8772 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", usenatroute ? "On" : "Off");
8773 ast_udptl_setnat(p->udptl, usenatroute);
8775 ast_string_field_set(p, peersecret, peer->secret);
8776 ast_string_field_set(p, peermd5secret, peer->md5secret);
8777 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
8778 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
8779 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
8780 if (peer->callingpres) /* Peer calling pres setting will override RPID */
8781 p->callingpres = peer->callingpres;
8782 if (peer->maxms && peer->lastms)
8783 p->timer_t1 = peer->lastms;
8784 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
8785 /* Pretend there is no required authentication */
8786 ast_string_field_free(p, peersecret);
8787 ast_string_field_free(p, peermd5secret);
8789 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
8790 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
8791 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
8792 /* If we have a call limit, set flag */
8793 if (peer->call_limit)
8794 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
8795 ast_string_field_set(p, peername, peer->name);
8796 ast_string_field_set(p, authname, peer->name);
8798 /* copy channel vars */
8799 for (v = peer->chanvars ; v ; v = v->next) {
8800 if ((tmpvar = ast_variable_new(v->name, v->value))) {
8801 tmpvar->next = p->chanvars;
8802 p->chanvars = tmpvar;
8805 if (authpeer) {
8806 (*authpeer) = ASTOBJ_REF(peer); /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
8809 if (!ast_strlen_zero(peer->username)) {
8810 ast_string_field_set(p, username, peer->username);
8811 /* Use the default username for authentication on outbound calls */
8812 /* XXX this takes the name from the caller... can we override ? */
8813 ast_string_field_set(p, authname, peer->username);
8815 if (!ast_strlen_zero(peer->cid_num) && !ast_strlen_zero(p->cid_num)) {
8816 char *tmp = ast_strdupa(peer->cid_num);
8817 if (ast_is_shrinkable_phonenumber(tmp))
8818 ast_shrink_phone_number(tmp);
8819 ast_string_field_set(p, cid_num, tmp);
8821 if (!ast_strlen_zero(peer->cid_name) && !ast_strlen_zero(p->cid_name))
8822 ast_string_field_set(p, cid_name, peer->cid_name);
8823 ast_string_field_set(p, fullcontact, peer->fullcontact);
8824 if (!ast_strlen_zero(peer->context))
8825 ast_string_field_set(p, context, peer->context);
8826 ast_string_field_set(p, peersecret, peer->secret);
8827 ast_string_field_set(p, peermd5secret, peer->md5secret);
8828 ast_string_field_set(p, language, peer->language);
8829 ast_string_field_set(p, accountcode, peer->accountcode);
8830 p->amaflags = peer->amaflags;
8831 p->callgroup = peer->callgroup;
8832 p->pickupgroup = peer->pickupgroup;
8833 p->capability = peer->capability;
8834 p->prefs = peer->prefs;
8835 p->jointcapability = peer->capability;
8836 if (p->peercapability)
8837 p->jointcapability &= p->peercapability;
8838 p->maxcallbitrate = peer->maxcallbitrate;
8839 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && p->vrtp) {
8840 ast_rtp_destroy(p->vrtp);
8841 p->vrtp = NULL;
8843 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
8844 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
8845 p->noncodeccapability |= AST_RTP_DTMF;
8846 else
8847 p->noncodeccapability &= ~AST_RTP_DTMF;
8848 if (p->t38.peercapability)
8849 p->t38.jointcapability &= p->t38.peercapability;
8851 ASTOBJ_UNREF(peer, sip_destroy_peer);
8852 } else {
8853 if (debug)
8854 ast_verbose("Found no matching peer or user for '%s:%d'\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
8856 /* do we allow guests? */
8857 if (!global_allowguest) {
8858 if (global_alwaysauthreject)
8859 res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
8860 else
8861 res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
8867 if (user)
8868 ASTOBJ_UNREF(user, sip_destroy_user);
8869 return res;
8872 /*! \brief Find user
8873 If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
8875 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
8877 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
8880 /*! \brief Get text out of a SIP MESSAGE packet */
8881 static int get_msg_text(char *buf, int len, struct sip_request *req)
8883 int x;
8884 int y;
8886 buf[0] = '\0';
8887 y = len - strlen(buf) - 5;
8888 if (y < 0)
8889 y = 0;
8890 for (x=0;x<req->lines;x++) {
8891 strncat(buf, req->line[x], y); /* safe */
8892 y -= strlen(req->line[x]) + 1;
8893 if (y < 0)
8894 y = 0;
8895 if (y != 0)
8896 strcat(buf, "\n"); /* safe */
8898 return 0;
8902 /*! \brief Receive SIP MESSAGE method messages
8903 \note We only handle messages within current calls currently
8904 Reference: RFC 3428 */
8905 static void receive_message(struct sip_pvt *p, struct sip_request *req)
8907 char buf[1024];
8908 struct ast_frame f;
8909 const char *content_type = get_header(req, "Content-Type");
8911 if (strcmp(content_type, "text/plain")) { /* No text/plain attachment */
8912 transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
8913 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
8914 return;
8917 if (get_msg_text(buf, sizeof(buf), req)) {
8918 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
8919 transmit_response(p, "202 Accepted", req);
8920 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
8921 return;
8924 if (p->owner) {
8925 if (sip_debug_test_pvt(p))
8926 ast_verbose("Message received: '%s'\n", buf);
8927 memset(&f, 0, sizeof(f));
8928 f.frametype = AST_FRAME_TEXT;
8929 f.subclass = 0;
8930 f.offset = 0;
8931 f.data = buf;
8932 f.datalen = strlen(buf);
8933 ast_queue_frame(p->owner, &f);
8934 transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
8935 } else { /* Message outside of a call, we do not support that */
8936 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);
8937 transmit_response(p, "405 Method Not Allowed", req); /* Good enough, or? */
8939 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
8940 return;
8943 /*! \brief CLI Command to show calls within limits set by call_limit */
8944 static int sip_show_inuse(int fd, int argc, char *argv[])
8946 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
8947 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
8948 char ilimits[40];
8949 char iused[40];
8950 int showall = FALSE;
8952 if (argc < 3)
8953 return RESULT_SHOWUSAGE;
8955 if (argc == 4 && !strcmp(argv[3],"all"))
8956 showall = TRUE;
8958 ast_cli(fd, FORMAT, "* User name", "In use", "Limit");
8959 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
8960 ASTOBJ_RDLOCK(iterator);
8961 if (iterator->call_limit)
8962 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
8963 else
8964 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
8965 snprintf(iused, sizeof(iused), "%d", iterator->inUse);
8966 if (showall || iterator->call_limit)
8967 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
8968 ASTOBJ_UNLOCK(iterator);
8969 } while (0) );
8971 ast_cli(fd, FORMAT, "* Peer name", "In use", "Limit");
8973 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
8974 ASTOBJ_RDLOCK(iterator);
8975 if (iterator->call_limit)
8976 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
8977 else
8978 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
8979 snprintf(iused, sizeof(iused), "%d/%d", iterator->inUse, iterator->inRinging);
8980 if (showall || iterator->call_limit)
8981 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
8982 ASTOBJ_UNLOCK(iterator);
8983 } while (0) );
8985 return RESULT_SUCCESS;
8986 #undef FORMAT
8987 #undef FORMAT2
8990 /*! \brief Convert transfer mode to text string */
8991 static char *transfermode2str(enum transfermodes mode)
8993 if (mode == TRANSFER_OPENFORALL)
8994 return "open";
8995 else if (mode == TRANSFER_CLOSED)
8996 return "closed";
8997 return "strict";
9000 /*! \brief Convert NAT setting to text string */
9001 static char *nat2str(int nat)
9003 switch(nat) {
9004 case SIP_NAT_NEVER:
9005 return "No";
9006 case SIP_NAT_ROUTE:
9007 return "Route";
9008 case SIP_NAT_ALWAYS:
9009 return "Always";
9010 case SIP_NAT_RFC3581:
9011 return "RFC3581";
9012 default:
9013 return "Unknown";
9017 /*! \brief Report Peer status in character string
9018 * \return 1 if peer is online, -1 if unmonitored */
9019 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
9021 int res = 0;
9022 if (peer->maxms) {
9023 if (peer->lastms < 0) {
9024 ast_copy_string(status, "UNREACHABLE", statuslen);
9025 } else if (peer->lastms > peer->maxms) {
9026 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
9027 res = 1;
9028 } else if (peer->lastms) {
9029 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
9030 res = 1;
9031 } else {
9032 ast_copy_string(status, "UNKNOWN", statuslen);
9034 } else {
9035 ast_copy_string(status, "Unmonitored", statuslen);
9036 /* Checking if port is 0 */
9037 res = -1;
9039 return res;
9042 /*! \brief CLI Command 'SIP Show Users' */
9043 static int sip_show_users(int fd, int argc, char *argv[])
9045 regex_t regexbuf;
9046 int havepattern = FALSE;
9048 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
9050 switch (argc) {
9051 case 5:
9052 if (!strcasecmp(argv[3], "like")) {
9053 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
9054 return RESULT_SHOWUSAGE;
9055 havepattern = TRUE;
9056 } else
9057 return RESULT_SHOWUSAGE;
9058 case 3:
9059 break;
9060 default:
9061 return RESULT_SHOWUSAGE;
9064 ast_cli(fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
9065 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
9066 ASTOBJ_RDLOCK(iterator);
9068 if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
9069 ASTOBJ_UNLOCK(iterator);
9070 continue;
9073 ast_cli(fd, FORMAT, iterator->name,
9074 iterator->secret,
9075 iterator->accountcode,
9076 iterator->context,
9077 iterator->ha ? "Yes" : "No",
9078 nat2str(ast_test_flag(&iterator->flags[0], SIP_NAT)));
9079 ASTOBJ_UNLOCK(iterator);
9080 } while (0)
9083 if (havepattern)
9084 regfree(&regexbuf);
9086 return RESULT_SUCCESS;
9087 #undef FORMAT
9090 static char mandescr_show_peers[] =
9091 "Description: Lists SIP peers in text format with details on current status.\n"
9092 "Variables: \n"
9093 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
9095 /*! \brief Show SIP peers in the manager API */
9096 /* Inspired from chan_iax2 */
9097 static int manager_sip_show_peers( struct mansession *s, struct message *m )
9099 char *id = astman_get_header(m,"ActionID");
9100 char *a[] = { "sip", "show", "peers" };
9101 char idtext[256] = "";
9102 int total = 0;
9104 if (!ast_strlen_zero(id))
9105 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
9107 astman_send_ack(s, m, "Peer status list will follow");
9108 /* List the peers in separate manager events */
9109 _sip_show_peers(-1, &total, s, m, 3, a);
9110 /* Send final confirmation */
9111 astman_append(s,
9112 "Event: PeerlistComplete\r\n"
9113 "ListItems: %d\r\n"
9114 "%s"
9115 "\r\n", total, idtext);
9116 return 0;
9119 /*! \brief CLI Show Peers command */
9120 static int sip_show_peers(int fd, int argc, char *argv[])
9122 return _sip_show_peers(fd, NULL, NULL, NULL, argc, argv);
9125 /*! \brief _sip_show_peers: Execute sip show peers command */
9126 static int _sip_show_peers(int fd, int *total, struct mansession *s, struct message *m, int argc, char *argv[])
9128 regex_t regexbuf;
9129 int havepattern = FALSE;
9131 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %-10s\n"
9132 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %-10s\n"
9134 char name[256];
9135 int total_peers = 0;
9136 int peers_online = 0;
9137 int peers_offline = 0;
9138 char *id;
9139 char idtext[256] = "";
9140 int realtimepeers;
9142 realtimepeers = ast_check_realtime("sippeers");
9144 if (s) { /* Manager - get ActionID */
9145 id = astman_get_header(m,"ActionID");
9146 if (!ast_strlen_zero(id))
9147 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
9150 switch (argc) {
9151 case 5:
9152 if (!strcasecmp(argv[3], "like")) {
9153 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
9154 return RESULT_SHOWUSAGE;
9155 havepattern = TRUE;
9156 } else
9157 return RESULT_SHOWUSAGE;
9158 case 3:
9159 break;
9160 default:
9161 return RESULT_SHOWUSAGE;
9164 if (!s) { /* Normal list */
9165 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
9168 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
9169 char status[20] = "";
9170 char srch[2000];
9171 char pstatus;
9173 ASTOBJ_RDLOCK(iterator);
9175 if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
9176 ASTOBJ_UNLOCK(iterator);
9177 continue;
9180 if (!ast_strlen_zero(iterator->username) && !s)
9181 snprintf(name, sizeof(name), "%s/%s", iterator->name, iterator->username);
9182 else
9183 ast_copy_string(name, iterator->name, sizeof(name));
9185 pstatus = peer_status(iterator, status, sizeof(status));
9186 if (pstatus)
9187 peers_online++;
9188 else {
9189 if (pstatus == 0)
9190 peers_offline++;
9191 else { /* Unmonitored */
9192 /* Checking if port is 0 */
9193 if ( ntohs(iterator->addr.sin_port) == 0 ) {
9194 peers_offline++;
9195 } else {
9196 peers_online++;
9201 snprintf(srch, sizeof(srch), FORMAT, name,
9202 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
9203 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ", /* Dynamic or not? */
9204 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
9205 iterator->ha ? " A " : " ", /* permit/deny */
9206 ntohs(iterator->addr.sin_port), status,
9207 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
9209 if (!s) {/* Normal CLI list */
9210 ast_cli(fd, FORMAT, name,
9211 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
9212 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ", /* Dynamic or not? */
9213 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
9214 iterator->ha ? " A " : " ", /* permit/deny */
9216 ntohs(iterator->addr.sin_port), status,
9217 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
9218 } else { /* Manager format */
9219 /* The names here need to be the same as other channels */
9220 astman_append(s,
9221 "Event: PeerEntry\r\n%s"
9222 "Channeltype: SIP\r\n"
9223 "ObjectName: %s\r\n"
9224 "ChanObjectType: peer\r\n" /* "peer" or "user" */
9225 "IPaddress: %s\r\n"
9226 "IPport: %d\r\n"
9227 "Dynamic: %s\r\n"
9228 "Natsupport: %s\r\n"
9229 "Video Support: %s\r\n"
9230 "ACL: %s\r\n"
9231 "Status: %s\r\n"
9232 "RealtimeDevice: %s\r\n\r\n",
9233 idtext,
9234 iterator->name,
9235 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "-none-",
9236 ntohs(iterator->addr.sin_port),
9237 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no", /* Dynamic or not? */
9238 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? "yes" : "no", /* NAT=yes? */
9239 ast_test_flag(&iterator->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no", /* VIDEOSUPPORT=yes? */
9240 iterator->ha ? "yes" : "no", /* permit/deny */
9241 status,
9242 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "yes":"no") : "no");
9245 ASTOBJ_UNLOCK(iterator);
9247 total_peers++;
9248 } while(0) );
9250 if (!s) {
9251 ast_cli(fd,"%d sip peers [%d online , %d offline]\n",total_peers,peers_online,peers_offline);
9254 if (havepattern)
9255 regfree(&regexbuf);
9257 if (total)
9258 *total = total_peers;
9261 return RESULT_SUCCESS;
9262 #undef FORMAT
9263 #undef FORMAT2
9266 /*! \brief List all allocated SIP Objects (realtime or static) */
9267 static int sip_show_objects(int fd, int argc, char *argv[])
9269 char tmp[256];
9270 if (argc != 3)
9271 return RESULT_SHOWUSAGE;
9272 ast_cli(fd, "-= User objects: %d static, %d realtime =-\n\n", suserobjs, ruserobjs);
9273 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &userl);
9274 ast_cli(fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
9275 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &peerl);
9276 ast_cli(fd, "-= Registry objects: %d =-\n\n", regobjs);
9277 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &regl);
9278 return RESULT_SUCCESS;
9280 /*! \brief Print call group and pickup group */
9281 static void print_group(int fd, unsigned int group, int crlf)
9283 char buf[256];
9284 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
9287 /*! \brief Convert DTMF mode to printable string */
9288 static const char *dtmfmode2str(int mode)
9290 switch (mode) {
9291 case SIP_DTMF_RFC2833:
9292 return "rfc2833";
9293 case SIP_DTMF_INFO:
9294 return "info";
9295 case SIP_DTMF_INBAND:
9296 return "inband";
9297 case SIP_DTMF_AUTO:
9298 return "auto";
9300 return "<error>";
9303 /*! \brief Convert Insecure setting to printable string */
9304 static const char *insecure2str(int port, int invite)
9306 if (port && invite)
9307 return "port,invite";
9308 else if (port)
9309 return "port";
9310 else if (invite)
9311 return "invite";
9312 else
9313 return "no";
9316 /*! \brief Destroy disused contexts between reloads
9317 Only used in reload_config so the code for regcontext doesn't get ugly
9319 static void cleanup_stale_contexts(char *new, char *old)
9321 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
9323 while ((oldcontext = strsep(&old, "&"))) {
9324 stalecontext = '\0';
9325 ast_copy_string(newlist, new, sizeof(newlist));
9326 stringp = newlist;
9327 while ((newcontext = strsep(&stringp, "&"))) {
9328 if (strcmp(newcontext, oldcontext) == 0) {
9329 /* This is not the context you're looking for */
9330 stalecontext = '\0';
9331 break;
9332 } else if (strcmp(newcontext, oldcontext)) {
9333 stalecontext = oldcontext;
9337 if (stalecontext)
9338 ast_context_destroy(ast_context_find(stalecontext), "SIP");
9342 /*! \brief Remove temporary realtime objects from memory (CLI) */
9343 static int sip_prune_realtime(int fd, int argc, char *argv[])
9345 struct sip_peer *peer;
9346 struct sip_user *user;
9347 int pruneuser = FALSE;
9348 int prunepeer = FALSE;
9349 int multi = FALSE;
9350 char *name = NULL;
9351 regex_t regexbuf;
9353 switch (argc) {
9354 case 4:
9355 if (!strcasecmp(argv[3], "user"))
9356 return RESULT_SHOWUSAGE;
9357 if (!strcasecmp(argv[3], "peer"))
9358 return RESULT_SHOWUSAGE;
9359 if (!strcasecmp(argv[3], "like"))
9360 return RESULT_SHOWUSAGE;
9361 if (!strcasecmp(argv[3], "all")) {
9362 multi = TRUE;
9363 pruneuser = prunepeer = TRUE;
9364 } else {
9365 pruneuser = prunepeer = TRUE;
9366 name = argv[3];
9368 break;
9369 case 5:
9370 if (!strcasecmp(argv[4], "like"))
9371 return RESULT_SHOWUSAGE;
9372 if (!strcasecmp(argv[3], "all"))
9373 return RESULT_SHOWUSAGE;
9374 if (!strcasecmp(argv[3], "like")) {
9375 multi = TRUE;
9376 name = argv[4];
9377 pruneuser = prunepeer = TRUE;
9378 } else if (!strcasecmp(argv[3], "user")) {
9379 pruneuser = TRUE;
9380 if (!strcasecmp(argv[4], "all"))
9381 multi = TRUE;
9382 else
9383 name = argv[4];
9384 } else if (!strcasecmp(argv[3], "peer")) {
9385 prunepeer = TRUE;
9386 if (!strcasecmp(argv[4], "all"))
9387 multi = TRUE;
9388 else
9389 name = argv[4];
9390 } else
9391 return RESULT_SHOWUSAGE;
9392 break;
9393 case 6:
9394 if (strcasecmp(argv[4], "like"))
9395 return RESULT_SHOWUSAGE;
9396 if (!strcasecmp(argv[3], "user")) {
9397 pruneuser = TRUE;
9398 name = argv[5];
9399 } else if (!strcasecmp(argv[3], "peer")) {
9400 prunepeer = TRUE;
9401 name = argv[5];
9402 } else
9403 return RESULT_SHOWUSAGE;
9404 break;
9405 default:
9406 return RESULT_SHOWUSAGE;
9409 if (multi && name) {
9410 if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
9411 return RESULT_SHOWUSAGE;
9414 if (multi) {
9415 if (prunepeer) {
9416 int pruned = 0;
9418 ASTOBJ_CONTAINER_WRLOCK(&peerl);
9419 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
9420 ASTOBJ_RDLOCK(iterator);
9421 if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
9422 ASTOBJ_UNLOCK(iterator);
9423 continue;
9425 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
9426 ASTOBJ_MARK(iterator);
9427 pruned++;
9429 ASTOBJ_UNLOCK(iterator);
9430 } while (0) );
9431 if (pruned) {
9432 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
9433 ast_cli(fd, "%d peers pruned.\n", pruned);
9434 } else
9435 ast_cli(fd, "No peers found to prune.\n");
9436 ASTOBJ_CONTAINER_UNLOCK(&peerl);
9438 if (pruneuser) {
9439 int pruned = 0;
9441 ASTOBJ_CONTAINER_WRLOCK(&userl);
9442 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
9443 ASTOBJ_RDLOCK(iterator);
9444 if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
9445 ASTOBJ_UNLOCK(iterator);
9446 continue;
9448 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
9449 ASTOBJ_MARK(iterator);
9450 pruned++;
9452 ASTOBJ_UNLOCK(iterator);
9453 } while (0) );
9454 if (pruned) {
9455 ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, sip_destroy_user);
9456 ast_cli(fd, "%d users pruned.\n", pruned);
9457 } else
9458 ast_cli(fd, "No users found to prune.\n");
9459 ASTOBJ_CONTAINER_UNLOCK(&userl);
9461 } else {
9462 if (prunepeer) {
9463 if ((peer = ASTOBJ_CONTAINER_FIND_UNLINK(&peerl, name))) {
9464 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
9465 ast_cli(fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
9466 ASTOBJ_CONTAINER_LINK(&peerl, peer);
9467 } else
9468 ast_cli(fd, "Peer '%s' pruned.\n", name);
9469 ASTOBJ_UNREF(peer, sip_destroy_peer);
9470 } else
9471 ast_cli(fd, "Peer '%s' not found.\n", name);
9473 if (pruneuser) {
9474 if ((user = ASTOBJ_CONTAINER_FIND_UNLINK(&userl, name))) {
9475 if (!ast_test_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
9476 ast_cli(fd, "User '%s' is not a Realtime user, cannot be pruned.\n", name);
9477 ASTOBJ_CONTAINER_LINK(&userl, user);
9478 } else
9479 ast_cli(fd, "User '%s' pruned.\n", name);
9480 ASTOBJ_UNREF(user, sip_destroy_user);
9481 } else
9482 ast_cli(fd, "User '%s' not found.\n", name);
9486 return RESULT_SUCCESS;
9489 /*! \brief Print codec list from preference to CLI/manager */
9490 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
9492 int x, codec;
9494 for(x = 0; x < 32 ; x++) {
9495 codec = ast_codec_pref_index(pref, x);
9496 if (!codec)
9497 break;
9498 ast_cli(fd, "%s", ast_getformatname(codec));
9499 if (x < 31 && ast_codec_pref_index(pref, x + 1))
9500 ast_cli(fd, ",");
9502 if (!x)
9503 ast_cli(fd, "none");
9506 /*! \brief Print domain mode to cli */
9507 static const char *domain_mode_to_text(const enum domain_mode mode)
9509 switch (mode) {
9510 case SIP_DOMAIN_AUTO:
9511 return "[Automatic]";
9512 case SIP_DOMAIN_CONFIG:
9513 return "[Configured]";
9516 return "";
9519 /*! \brief CLI command to list local domains */
9520 static int sip_show_domains(int fd, int argc, char *argv[])
9522 struct domain *d;
9523 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
9525 if (AST_LIST_EMPTY(&domain_list)) {
9526 ast_cli(fd, "SIP Domain support not enabled.\n\n");
9527 return RESULT_SUCCESS;
9528 } else {
9529 ast_cli(fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
9530 AST_LIST_LOCK(&domain_list);
9531 AST_LIST_TRAVERSE(&domain_list, d, list)
9532 ast_cli(fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
9533 domain_mode_to_text(d->mode));
9534 AST_LIST_UNLOCK(&domain_list);
9535 ast_cli(fd, "\n");
9536 return RESULT_SUCCESS;
9539 #undef FORMAT
9541 static char mandescr_show_peer[] =
9542 "Description: Show one SIP peer with details on current status.\n"
9543 "Variables: \n"
9544 " Peer: <name> The peer name you want to check.\n"
9545 " ActionID: <id> Optional action ID for this AMI transaction.\n";
9547 /*! \brief Show SIP peers in the manager API */
9548 static int manager_sip_show_peer( struct mansession *s, struct message *m)
9550 char *id = astman_get_header(m,"ActionID");
9551 char *a[4];
9552 char *peer;
9553 int ret;
9555 peer = astman_get_header(m,"Peer");
9556 if (ast_strlen_zero(peer)) {
9557 astman_send_error(s, m, "Peer: <name> missing.\n");
9558 return 0;
9560 a[0] = "sip";
9561 a[1] = "show";
9562 a[2] = "peer";
9563 a[3] = peer;
9565 if (!ast_strlen_zero(id))
9566 astman_append(s, "ActionID: %s\r\n",id);
9567 ret = _sip_show_peer(1, -1, s, m, 4, a );
9568 astman_append(s, "\r\n\r\n" );
9569 return ret;
9574 /*! \brief Show one peer in detail */
9575 static int sip_show_peer(int fd, int argc, char *argv[])
9577 return _sip_show_peer(0, fd, NULL, NULL, argc, argv);
9580 /*! \brief Show one peer in detail (main function) */
9581 static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[])
9583 char status[30] = "";
9584 char cbuf[256];
9585 struct sip_peer *peer;
9586 char codec_buf[512];
9587 struct ast_codec_pref *pref;
9588 struct ast_variable *v;
9589 struct sip_auth *auth;
9590 int x = 0, codec = 0, load_realtime;
9591 int realtimepeers;
9593 realtimepeers = ast_check_realtime("sippeers");
9595 if (argc < 4)
9596 return RESULT_SHOWUSAGE;
9598 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
9599 peer = find_peer(argv[3], NULL, load_realtime);
9600 if (s) { /* Manager */
9601 if (peer)
9602 astman_append(s, "Response: Success\r\n");
9603 else {
9604 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.\n", argv[3]);
9605 astman_send_error(s, m, cbuf);
9606 return 0;
9609 if (peer && type==0 ) { /* Normal listing */
9610 ast_cli(fd,"\n\n");
9611 ast_cli(fd, " * Name : %s\n", peer->name);
9612 if (realtimepeers) { /* Realtime is enabled */
9613 ast_cli(fd, " Realtime peer: %s\n", ast_test_flag(&peer->flags[0], SIP_REALTIME) ? "Yes, cached" : "No");
9615 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
9616 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
9617 for (auth = peer->auth; auth; auth = auth->next) {
9618 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
9619 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
9621 ast_cli(fd, " Context : %s\n", peer->context);
9622 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
9623 ast_cli(fd, " Language : %s\n", peer->language);
9624 if (!ast_strlen_zero(peer->accountcode))
9625 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
9626 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
9627 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
9628 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
9629 if (!ast_strlen_zero(peer->fromuser))
9630 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
9631 if (!ast_strlen_zero(peer->fromdomain))
9632 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
9633 ast_cli(fd, " Callgroup : ");
9634 print_group(fd, peer->callgroup, 0);
9635 ast_cli(fd, " Pickupgroup : ");
9636 print_group(fd, peer->pickupgroup, 0);
9637 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
9638 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
9639 ast_cli(fd, " LastMsgsSent : %d\n", peer->lastmsgssent);
9640 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
9641 ast_cli(fd, " Dynamic : %s\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Yes":"No"));
9642 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
9643 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
9644 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
9645 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)));
9646 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
9647 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
9648 ast_cli(fd, " T38 pt UDPTL : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL)?"Yes":"No");
9649 ast_cli(fd, " T38 pt RTP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_RTP)?"Yes":"No");
9650 ast_cli(fd, " T38 pt TCP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_TCP)?"Yes":"No");
9651 ast_cli(fd, " CanReinvite : %s\n", ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Yes":"No");
9652 ast_cli(fd, " PromiscRedir : %s\n", ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Yes":"No");
9653 ast_cli(fd, " User=Phone : %s\n", ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Yes":"No");
9654 ast_cli(fd, " Video Support: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Yes":"No");
9655 ast_cli(fd, " Trust RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_TRUSTRPID) ? "Yes" : "No");
9656 ast_cli(fd, " Send RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_SENDRPID) ? "Yes" : "No");
9657 ast_cli(fd, " Subscriptions: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
9658 ast_cli(fd, " Overlap dial : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
9660 /* - is enumerated */
9661 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
9662 ast_cli(fd, " LastMsg : %d\n", peer->lastmsg);
9663 ast_cli(fd, " ToHost : %s\n", peer->tohost);
9664 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));
9665 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
9666 if (!ast_strlen_zero(global_regcontext))
9667 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
9668 ast_cli(fd, " Def. Username: %s\n", peer->username);
9669 ast_cli(fd, " SIP Options : ");
9670 if (peer->sipoptions) {
9671 int lastoption = -1;
9672 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
9673 if (sip_options[x].id != lastoption) {
9674 if (peer->sipoptions & sip_options[x].id)
9675 ast_cli(fd, "%s ", sip_options[x].text);
9676 lastoption = x;
9679 } else
9680 ast_cli(fd, "(none)");
9682 ast_cli(fd, "\n");
9683 ast_cli(fd, " Codecs : ");
9684 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
9685 ast_cli(fd, "%s\n", codec_buf);
9686 ast_cli(fd, " Codec Order : (");
9687 print_codec_to_cli(fd, &peer->prefs);
9688 ast_cli(fd, ")\n");
9690 ast_cli(fd, " Status : ");
9691 peer_status(peer, status, sizeof(status));
9692 ast_cli(fd, "%s\n",status);
9693 ast_cli(fd, " Useragent : %s\n", peer->useragent);
9694 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
9695 if (peer->chanvars) {
9696 ast_cli(fd, " Variables :\n");
9697 for (v = peer->chanvars ; v ; v = v->next)
9698 ast_cli(fd, " %s = %s\n", v->name, v->value);
9700 ast_cli(fd,"\n");
9701 ASTOBJ_UNREF(peer,sip_destroy_peer);
9702 } else if (peer && type == 1) { /* manager listing */
9703 char buf[256];
9704 astman_append(s, "Channeltype: SIP\r\n");
9705 astman_append(s, "ObjectName: %s\r\n", peer->name);
9706 astman_append(s, "ChanObjectType: peer\r\n");
9707 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
9708 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
9709 astman_append(s, "Context: %s\r\n", peer->context);
9710 astman_append(s, "Language: %s\r\n", peer->language);
9711 if (!ast_strlen_zero(peer->accountcode))
9712 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
9713 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
9714 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
9715 if (!ast_strlen_zero(peer->fromuser))
9716 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
9717 if (!ast_strlen_zero(peer->fromdomain))
9718 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
9719 astman_append(s, "Callgroup: ");
9720 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->callgroup));
9721 astman_append(s, "Pickupgroup: ");
9722 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->pickupgroup));
9723 astman_append(s, "VoiceMailbox: %s\r\n", peer->mailbox);
9724 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
9725 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
9726 astman_append(s, "Call limit: %d\r\n", peer->call_limit);
9727 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
9728 astman_append(s, "Dynamic: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Y":"N"));
9729 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
9730 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched,peer->expire));
9731 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)));
9732 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
9733 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
9734 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
9735 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
9736 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
9737 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
9739 /* - is enumerated */
9740 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
9741 astman_append(s, "SIPLastMsg: %d\r\n", peer->lastmsg);
9742 astman_append(s, "ToHost: %s\r\n", peer->tohost);
9743 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));
9744 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));
9745 astman_append(s, "Default-Username: %s\r\n", peer->username);
9746 if (!ast_strlen_zero(global_regcontext))
9747 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
9748 astman_append(s, "Codecs: ");
9749 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
9750 astman_append(s, "%s\r\n", codec_buf);
9751 astman_append(s, "CodecOrder: ");
9752 pref = &peer->prefs;
9753 for(x = 0; x < 32 ; x++) {
9754 codec = ast_codec_pref_index(pref,x);
9755 if (!codec)
9756 break;
9757 astman_append(s, "%s", ast_getformatname(codec));
9758 if (x < 31 && ast_codec_pref_index(pref,x+1))
9759 astman_append(s, ",");
9762 astman_append(s, "\r\n");
9763 astman_append(s, "Status: ");
9764 peer_status(peer, status, sizeof(status));
9765 astman_append(s, "%s\r\n", status);
9766 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
9767 astman_append(s, "Reg-Contact : %s\r\n", peer->fullcontact);
9768 if (peer->chanvars) {
9769 for (v = peer->chanvars ; v ; v = v->next) {
9770 astman_append(s, "ChanVariable:\n");
9771 astman_append(s, " %s,%s\r\n", v->name, v->value);
9775 ASTOBJ_UNREF(peer,sip_destroy_peer);
9777 } else {
9778 ast_cli(fd,"Peer %s not found.\n", argv[3]);
9779 ast_cli(fd,"\n");
9782 return RESULT_SUCCESS;
9785 /*! \brief Show one user in detail */
9786 static int sip_show_user(int fd, int argc, char *argv[])
9788 char cbuf[256];
9789 struct sip_user *user;
9790 struct ast_variable *v;
9791 int load_realtime;
9793 if (argc < 4)
9794 return RESULT_SHOWUSAGE;
9796 /* Load from realtime storage? */
9797 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
9799 user = find_user(argv[3], load_realtime);
9800 if (user) {
9801 ast_cli(fd,"\n\n");
9802 ast_cli(fd, " * Name : %s\n", user->name);
9803 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
9804 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
9805 ast_cli(fd, " Context : %s\n", user->context);
9806 ast_cli(fd, " Language : %s\n", user->language);
9807 if (!ast_strlen_zero(user->accountcode))
9808 ast_cli(fd, " Accountcode : %s\n", user->accountcode);
9809 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
9810 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
9811 ast_cli(fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
9812 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
9813 ast_cli(fd, " Call limit : %d\n", user->call_limit);
9814 ast_cli(fd, " Callgroup : ");
9815 print_group(fd, user->callgroup, 0);
9816 ast_cli(fd, " Pickupgroup : ");
9817 print_group(fd, user->pickupgroup, 0);
9818 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
9819 ast_cli(fd, " ACL : %s\n", (user->ha?"Yes":"No"));
9820 ast_cli(fd, " Codec Order : (");
9821 print_codec_to_cli(fd, &user->prefs);
9822 ast_cli(fd, ")\n");
9824 if (user->chanvars) {
9825 ast_cli(fd, " Variables :\n");
9826 for (v = user->chanvars ; v ; v = v->next)
9827 ast_cli(fd, " %s = %s\n", v->name, v->value);
9829 ast_cli(fd,"\n");
9830 ASTOBJ_UNREF(user,sip_destroy_user);
9831 } else {
9832 ast_cli(fd,"User %s not found.\n", argv[3]);
9833 ast_cli(fd,"\n");
9836 return RESULT_SUCCESS;
9839 /*! \brief Show SIP Registry (registrations with other SIP proxies */
9840 static int sip_show_registry(int fd, int argc, char *argv[])
9842 #define FORMAT2 "%-30.30s %-12.12s %8.8s %-20.20s %-25.25s\n"
9843 #define FORMAT "%-30.30s %-12.12s %8d %-20.20s %-25.25s\n"
9844 char host[80];
9845 char tmpdat[256];
9846 struct tm tm;
9849 if (argc != 3)
9850 return RESULT_SHOWUSAGE;
9851 ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State", "Reg.Time");
9852 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
9853 ASTOBJ_RDLOCK(iterator);
9854 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : DEFAULT_SIP_PORT);
9855 if (iterator->regtime) {
9856 ast_localtime(&iterator->regtime, &tm, NULL);
9857 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
9858 } else {
9859 tmpdat[0] = 0;
9861 ast_cli(fd, FORMAT, host, iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
9862 ASTOBJ_UNLOCK(iterator);
9863 } while(0));
9864 return RESULT_SUCCESS;
9865 #undef FORMAT
9866 #undef FORMAT2
9869 /*! \brief List global settings for the SIP channel */
9870 static int sip_show_settings(int fd, int argc, char *argv[])
9872 int realtimepeers;
9873 int realtimeusers;
9875 realtimepeers = ast_check_realtime("sippeers");
9876 realtimeusers = ast_check_realtime("sipusers");
9878 if (argc != 3)
9879 return RESULT_SHOWUSAGE;
9880 ast_cli(fd, "\n\nGlobal Settings:\n");
9881 ast_cli(fd, "----------------\n");
9882 ast_cli(fd, " SIP Port: %d\n", ntohs(bindaddr.sin_port));
9883 ast_cli(fd, " Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
9884 ast_cli(fd, " Videosupport: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "Yes" : "No");
9885 ast_cli(fd, " AutoCreatePeer: %s\n", autocreatepeer ? "Yes" : "No");
9886 ast_cli(fd, " Allow unknown access: %s\n", global_allowguest ? "Yes" : "No");
9887 ast_cli(fd, " Allow subscriptions: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
9888 ast_cli(fd, " Allow overlap dialing: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
9889 ast_cli(fd, " Promsic. redir: %s\n", ast_test_flag(&global_flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
9890 ast_cli(fd, " SIP domain support: %s\n", AST_LIST_EMPTY(&domain_list) ? "No" : "Yes");
9891 ast_cli(fd, " Call to non-local dom.: %s\n", allow_external_domains ? "Yes" : "No");
9892 ast_cli(fd, " URI user is phone no: %s\n", ast_test_flag(&global_flags[0], SIP_USEREQPHONE) ? "Yes" : "No");
9893 ast_cli(fd, " Our auth realm %s\n", global_realm);
9894 ast_cli(fd, " Realm. auth: %s\n", authl ? "Yes": "No");
9895 ast_cli(fd, " Always auth rejects: %s\n", global_alwaysauthreject ? "Yes" : "No");
9896 ast_cli(fd, " User Agent: %s\n", global_useragent);
9897 ast_cli(fd, " MWI checking interval: %d secs\n", global_mwitime);
9898 ast_cli(fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
9899 ast_cli(fd, " Caller ID: %s\n", default_callerid);
9900 ast_cli(fd, " From: Domain: %s\n", default_fromdomain);
9901 ast_cli(fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
9902 ast_cli(fd, " Call Events: %s\n", global_callevents ? "On" : "Off");
9903 ast_cli(fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
9904 ast_cli(fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
9905 ast_cli(fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
9906 ast_cli(fd, " T38 fax pt UDPTL: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_UDPTL) ? "Yes" : "No");
9907 ast_cli(fd, " T38 fax pt RTP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_RTP) ? "Yes" : "No");
9908 ast_cli(fd, " T38 fax pt TCP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_TCP) ? "Yes" : "No");
9909 if (!realtimepeers && !realtimeusers)
9910 ast_cli(fd, " SIP realtime: Disabled\n" );
9911 else
9912 ast_cli(fd, " SIP realtime: Enabled\n" );
9914 ast_cli(fd, "\nGlobal Signalling Settings:\n");
9915 ast_cli(fd, "---------------------------\n");
9916 ast_cli(fd, " Codecs: ");
9917 print_codec_to_cli(fd, &default_prefs);
9918 ast_cli(fd, "\n");
9919 ast_cli(fd, " T1 minimum: %d\n", global_t1min);
9920 ast_cli(fd, " Relax DTMF: %s\n", global_relaxdtmf ? "Yes" : "No");
9921 ast_cli(fd, " Compact SIP headers: %s\n", compactheaders ? "Yes" : "No");
9922 ast_cli(fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
9923 ast_cli(fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
9924 ast_cli(fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
9925 ast_cli(fd, " DNS SRV lookup: %s\n", srvlookup ? "Yes" : "No");
9926 ast_cli(fd, " Pedantic SIP support: %s\n", pedanticsipchecking ? "Yes" : "No");
9927 ast_cli(fd, " Reg. min duration %d secs\n", min_expiry);
9928 ast_cli(fd, " Reg. max duration: %d secs\n", max_expiry);
9929 ast_cli(fd, " Reg. default duration: %d secs\n", default_expiry);
9930 ast_cli(fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
9931 ast_cli(fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
9932 ast_cli(fd, " Notify ringing state: %s\n", global_notifyringing ? "Yes" : "No");
9933 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(global_allowtransfer));
9934 ast_cli(fd, " Max Call Bitrate: %d kbps\r\n", default_maxcallbitrate);
9935 ast_cli(fd, "\nDefault Settings:\n");
9936 ast_cli(fd, "-----------------\n");
9937 ast_cli(fd, " Context: %s\n", default_context);
9938 ast_cli(fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
9939 ast_cli(fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
9940 ast_cli(fd, " Qualify: %d\n", default_qualify);
9941 ast_cli(fd, " Use ClientCode: %s\n", ast_test_flag(&global_flags[0], SIP_USECLIENTCODE) ? "Yes" : "No");
9942 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" );
9943 ast_cli(fd, " Language: %s\n", S_OR(default_language, "(Defaults to English)"));
9944 ast_cli(fd, " MOH Interpret: %s\n", default_mohinterpret);
9945 ast_cli(fd, " MOH Suggest: %s\n", default_mohsuggest);
9946 ast_cli(fd, " Voice Mail Extension: %s\n", default_vmexten);
9949 if (realtimepeers || realtimeusers) {
9950 ast_cli(fd, "\nRealtime SIP Settings:\n");
9951 ast_cli(fd, "----------------------\n");
9952 ast_cli(fd, " Realtime Peers: %s\n", realtimepeers ? "Yes" : "No");
9953 ast_cli(fd, " Realtime Users: %s\n", realtimeusers ? "Yes" : "No");
9954 ast_cli(fd, " Cache Friends: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? "Yes" : "No");
9955 ast_cli(fd, " Update: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) ? "Yes" : "No");
9956 ast_cli(fd, " Ignore Reg. Expire: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) ? "Yes" : "No");
9957 ast_cli(fd, " Save sys. name: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME) ? "Yes" : "No");
9958 ast_cli(fd, " Auto Clear: %d\n", global_rtautoclear);
9960 ast_cli(fd, "\n----\n");
9961 return RESULT_SUCCESS;
9964 /*! \brief Show subscription type in string format */
9965 static const char *subscription_type2str(enum subscriptiontype subtype)
9967 int i;
9969 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
9970 if (subscription_types[i].type == subtype) {
9971 return subscription_types[i].text;
9974 return subscription_types[0].text;
9977 /*! \brief Find subscription type in array */
9978 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
9980 int i;
9982 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
9983 if (subscription_types[i].type == subtype) {
9984 return &subscription_types[i];
9987 return &subscription_types[0];
9990 /*! \brief Show active SIP channels */
9991 static int sip_show_channels(int fd, int argc, char *argv[])
9993 return __sip_show_channels(fd, argc, argv, 0);
9996 /*! \brief Show active SIP subscriptions */
9997 static int sip_show_subscriptions(int fd, int argc, char *argv[])
9999 return __sip_show_channels(fd, argc, argv, 1);
10002 /*! \brief SIP show channels CLI (main function) */
10003 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions)
10005 #define FORMAT3 "%-15.15s %-10.10s %-11.11s %-15.15s %-13.13s %-15.15s %-10.10s\n"
10006 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-4.4s %-7.7s %-15.15s\n"
10007 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-4.4s %-3.3s %-3.3s %-15.15s %-10.10s\n"
10008 struct sip_pvt *cur;
10009 int numchans = 0;
10010 char *referstatus = NULL;
10012 if (argc != 3)
10013 return RESULT_SHOWUSAGE;
10014 ast_mutex_lock(&iflock);
10015 cur = iflist;
10016 if (!subscriptions)
10017 ast_cli(fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Seq (Tx/Rx)", "Format", "Hold", "Last Message");
10018 else
10019 ast_cli(fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox");
10020 for (; cur; cur = cur->next) {
10021 referstatus = "";
10022 if (cur->refer) { /* SIP transfer in progress */
10023 referstatus = referstatus2str(cur->refer->status);
10025 if (cur->subscribed == NONE && !subscriptions) {
10026 ast_cli(fd, FORMAT, ast_inet_ntoa(cur->sa.sin_addr),
10027 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10028 cur->callid,
10029 cur->ocseq, cur->icseq,
10030 ast_getformatname(cur->owner ? cur->owner->nativeformats : 0),
10031 ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD) ? "Yes" : "No",
10032 ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY) ? "(d)" : "",
10033 cur->lastmsg ,
10034 referstatus
10036 numchans++;
10038 if (cur->subscribed != NONE && subscriptions) {
10039 ast_cli(fd, FORMAT3, ast_inet_ntoa(cur->sa.sin_addr),
10040 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10041 cur->callid,
10042 /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
10043 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
10044 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
10045 subscription_type2str(cur->subscribed),
10046 cur->subscribed == MWI_NOTIFICATION ? (cur->relatedpeer ? cur->relatedpeer->mailbox : "<none>") : "<none>"
10048 numchans++;
10051 ast_mutex_unlock(&iflock);
10052 if (!subscriptions)
10053 ast_cli(fd, "%d active SIP channel%s\n", numchans, (numchans != 1) ? "s" : "");
10054 else
10055 ast_cli(fd, "%d active SIP subscription%s\n", numchans, (numchans != 1) ? "s" : "");
10056 return RESULT_SUCCESS;
10057 #undef FORMAT
10058 #undef FORMAT2
10059 #undef FORMAT3
10062 /*! \brief Support routine for 'sip show channel' CLI */
10063 static char *complete_sipch(const char *line, const char *word, int pos, int state)
10065 int which=0;
10066 struct sip_pvt *cur;
10067 char *c = NULL;
10068 int wordlen = strlen(word);
10070 ast_mutex_lock(&iflock);
10071 for (cur = iflist; cur; cur = cur->next) {
10072 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
10073 c = ast_strdup(cur->callid);
10074 break;
10077 ast_mutex_unlock(&iflock);
10078 return c;
10081 /*! \brief Do completion on peer name */
10082 static char *complete_sip_peer(const char *word, int state, int flags2)
10084 char *result = NULL;
10085 int wordlen = strlen(word);
10086 int which = 0;
10088 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !result, do {
10089 /* locking of the object is not required because only the name and flags are being compared */
10090 if (!strncasecmp(word, iterator->name, wordlen) &&
10091 (!flags2 || ast_test_flag(&iterator->flags[1], flags2)) &&
10092 ++which > state)
10093 result = ast_strdup(iterator->name);
10094 } while(0) );
10095 return result;
10098 /*! \brief Support routine for 'sip show peer' CLI */
10099 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
10101 if (pos == 3)
10102 return complete_sip_peer(word, state, 0);
10104 return NULL;
10107 /*! \brief Support routine for 'sip debug peer' CLI */
10108 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state)
10110 if (pos == 3)
10111 return complete_sip_peer(word, state, 0);
10113 return NULL;
10116 /*! \brief Do completion on user name */
10117 static char *complete_sip_user(const char *word, int state, int flags2)
10119 char *result = NULL;
10120 int wordlen = strlen(word);
10121 int which = 0;
10123 ASTOBJ_CONTAINER_TRAVERSE(&userl, !result, do {
10124 /* locking of the object is not required because only the name and flags are being compared */
10125 if (!strncasecmp(word, iterator->name, wordlen)) {
10126 if (flags2 && !ast_test_flag(&iterator->flags[1], flags2))
10127 continue;
10128 if (++which > state) {
10129 result = ast_strdup(iterator->name);
10132 } while(0) );
10133 return result;
10136 /*! \brief Support routine for 'sip show user' CLI */
10137 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
10139 if (pos == 3)
10140 return complete_sip_user(word, state, 0);
10142 return NULL;
10145 /*! \brief Support routine for 'sip notify' CLI */
10146 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
10148 char *c = NULL;
10150 if (pos == 2) {
10151 int which = 0;
10152 char *cat = NULL;
10153 int wordlen = strlen(word);
10155 /* do completion for notify type */
10157 if (!notify_types)
10158 return NULL;
10160 while ( (cat = ast_category_browse(notify_types, cat)) ) {
10161 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
10162 c = ast_strdup(cat);
10163 break;
10166 return c;
10169 if (pos > 2)
10170 return complete_sip_peer(word, state, 0);
10172 return NULL;
10175 /*! \brief Support routine for 'sip prune realtime peer' CLI */
10176 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state)
10178 if (pos == 4)
10179 return complete_sip_peer(word, state, SIP_PAGE2_RTCACHEFRIENDS);
10180 return NULL;
10183 /*! \brief Support routine for 'sip prune realtime user' CLI */
10184 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state)
10186 if (pos == 4)
10187 return complete_sip_user(word, state, SIP_PAGE2_RTCACHEFRIENDS);
10189 return NULL;
10192 /*! \brief Show details of one active dialog */
10193 static int sip_show_channel(int fd, int argc, char *argv[])
10195 struct sip_pvt *cur;
10196 size_t len;
10197 int found = 0;
10199 if (argc != 4)
10200 return RESULT_SHOWUSAGE;
10201 len = strlen(argv[3]);
10202 ast_mutex_lock(&iflock);
10203 for (cur = iflist; cur; cur = cur->next) {
10204 if (!strncasecmp(cur->callid, argv[3], len)) {
10205 char formatbuf[BUFSIZ/2];
10206 ast_cli(fd,"\n");
10207 if (cur->subscribed != NONE)
10208 ast_cli(fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
10209 else
10210 ast_cli(fd, " * SIP Call\n");
10211 ast_cli(fd, " Direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING)?"Outgoing":"Incoming");
10212 ast_cli(fd, " Call-ID: %s\n", cur->callid);
10213 ast_cli(fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
10214 ast_cli(fd, " Our Codec Capability: %d\n", cur->capability);
10215 ast_cli(fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
10216 ast_cli(fd, " Their Codec Capability: %d\n", cur->peercapability);
10217 ast_cli(fd, " Joint Codec Capability: %d\n", cur->jointcapability);
10218 ast_cli(fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
10219 ast_cli(fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
10220 ast_cli(fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
10221 ast_cli(fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
10222 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
10223 ast_cli(fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
10224 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)" );
10225 ast_cli(fd, " Our Tag: %s\n", cur->tag);
10226 ast_cli(fd, " Their Tag: %s\n", cur->theirtag);
10227 ast_cli(fd, " SIP User agent: %s\n", cur->useragent);
10228 if (!ast_strlen_zero(cur->username))
10229 ast_cli(fd, " Username: %s\n", cur->username);
10230 if (!ast_strlen_zero(cur->peername))
10231 ast_cli(fd, " Peername: %s\n", cur->peername);
10232 if (!ast_strlen_zero(cur->uri))
10233 ast_cli(fd, " Original uri: %s\n", cur->uri);
10234 if (!ast_strlen_zero(cur->cid_num))
10235 ast_cli(fd, " Caller-ID: %s\n", cur->cid_num);
10236 ast_cli(fd, " Need Destroy: %d\n", ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY));
10237 ast_cli(fd, " Last Message: %s\n", cur->lastmsg);
10238 ast_cli(fd, " Promiscuous Redir: %s\n", ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
10239 ast_cli(fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
10240 ast_cli(fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
10241 ast_cli(fd, " SIP Options: ");
10242 if (cur->sipoptions) {
10243 int x;
10244 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
10245 if (cur->sipoptions & sip_options[x].id)
10246 ast_cli(fd, "%s ", sip_options[x].text);
10248 } else
10249 ast_cli(fd, "(none)\n");
10250 ast_cli(fd, "\n\n");
10251 found++;
10254 ast_mutex_unlock(&iflock);
10255 if (!found)
10256 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
10257 return RESULT_SUCCESS;
10260 /*! \brief Show history details of one dialog */
10261 static int sip_show_history(int fd, int argc, char *argv[])
10263 struct sip_pvt *cur;
10264 size_t len;
10265 int found = 0;
10267 if (argc != 4)
10268 return RESULT_SHOWUSAGE;
10269 if (!recordhistory)
10270 ast_cli(fd, "\n***Note: History recording is currently DISABLED. Use 'sip history' to ENABLE.\n");
10271 len = strlen(argv[3]);
10272 ast_mutex_lock(&iflock);
10273 for (cur = iflist; cur; cur = cur->next) {
10274 if (!strncasecmp(cur->callid, argv[3], len)) {
10275 struct sip_history *hist;
10276 int x = 0;
10278 ast_cli(fd,"\n");
10279 if (cur->subscribed != NONE)
10280 ast_cli(fd, " * Subscription\n");
10281 else
10282 ast_cli(fd, " * SIP Call\n");
10283 if (cur->history)
10284 AST_LIST_TRAVERSE(cur->history, hist, list)
10285 ast_cli(fd, "%d. %s\n", ++x, hist->event);
10286 if (x == 0)
10287 ast_cli(fd, "Call '%s' has no history\n", cur->callid);
10288 found++;
10291 ast_mutex_unlock(&iflock);
10292 if (!found)
10293 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
10294 return RESULT_SUCCESS;
10297 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
10298 static void sip_dump_history(struct sip_pvt *dialog)
10300 int x = 0;
10301 struct sip_history *hist;
10303 if (!dialog)
10304 return;
10306 ast_log(LOG_DEBUG, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
10307 if (dialog->subscribed)
10308 ast_log(LOG_DEBUG, " * Subscription\n");
10309 else
10310 ast_log(LOG_DEBUG, " * SIP Call\n");
10311 if (dialog->history)
10312 AST_LIST_TRAVERSE(dialog->history, hist, list)
10313 ast_log(LOG_DEBUG, " %-3.3d. %s\n", ++x, hist->event);
10314 if (!x)
10315 ast_log(LOG_DEBUG, "Call '%s' has no history\n", dialog->callid);
10316 ast_log(LOG_DEBUG, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
10320 /*! \brief Receive SIP INFO Message
10321 \note Doesn't read the duration of the DTMF signal */
10322 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
10324 char buf[1024];
10325 unsigned int event;
10326 const char *c = get_header(req, "Content-Type");
10328 /* Need to check the media/type */
10329 if (!strcasecmp(c, "application/dtmf-relay") ||
10330 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
10332 /* Try getting the "signal=" part */
10333 if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
10334 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
10335 transmit_response(p, "200 OK", req); /* Should return error */
10336 return;
10337 } else {
10338 ast_copy_string(buf, c, sizeof(buf));
10341 if (!p->owner) { /* not a PBX call */
10342 transmit_response(p, "481 Call leg/transaction does not exist", req);
10343 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
10344 return;
10347 if (ast_strlen_zero(buf)) {
10348 transmit_response(p, "200 OK", req);
10349 return;
10352 if (buf[0] == '*')
10353 event = 10;
10354 else if (buf[0] == '#')
10355 event = 11;
10356 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
10357 event = 12 + buf[0] - 'A';
10358 else
10359 event = atoi(buf);
10360 if (event == 16) {
10361 /* send a FLASH event */
10362 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
10363 ast_queue_frame(p->owner, &f);
10364 if (sipdebug)
10365 ast_verbose("* DTMF-relay event received: FLASH\n");
10366 } else {
10367 /* send a DTMF event */
10368 struct ast_frame f = { AST_FRAME_DTMF, };
10369 if (event < 10) {
10370 f.subclass = '0' + event;
10371 } else if (event < 11) {
10372 f.subclass = '*';
10373 } else if (event < 12) {
10374 f.subclass = '#';
10375 } else if (event < 16) {
10376 f.subclass = 'A' + (event - 12);
10378 ast_queue_frame(p->owner, &f);
10379 if (sipdebug)
10380 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
10382 transmit_response(p, "200 OK", req);
10383 return;
10384 } else if (!strcasecmp(c, "application/media_control+xml")) {
10385 /* Eh, we'll just assume it's a fast picture update for now */
10386 if (p->owner)
10387 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
10388 transmit_response(p, "200 OK", req);
10389 return;
10390 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
10391 /* Client code (from SNOM phone) */
10392 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
10393 if (p->owner && p->owner->cdr)
10394 ast_cdr_setuserfield(p->owner, c);
10395 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
10396 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
10397 transmit_response(p, "200 OK", req);
10398 } else {
10399 transmit_response(p, "403 Unauthorized", req);
10401 return;
10403 /* Other type of INFO message, not really understood by Asterisk */
10404 /* if (get_msg_text(buf, sizeof(buf), req)) { */
10406 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
10407 transmit_response(p, "415 Unsupported media type", req);
10408 return;
10411 /*! \brief Enable SIP Debugging in CLI */
10412 static int sip_do_debug_ip(int fd, int argc, char *argv[])
10414 struct hostent *hp;
10415 struct ast_hostent ahp;
10416 int port = 0;
10417 char *p, *arg;
10419 if (argc != 4)
10420 return RESULT_SHOWUSAGE;
10421 p = arg = argv[3];
10422 strsep(&p, ":");
10423 if (p)
10424 port = atoi(p);
10425 hp = ast_gethostbyname(arg, &ahp);
10426 if (hp == NULL)
10427 return RESULT_SHOWUSAGE;
10429 debugaddr.sin_family = AF_INET;
10430 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
10431 debugaddr.sin_port = htons(port);
10432 if (port == 0)
10433 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
10434 else
10435 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
10437 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
10439 return RESULT_SUCCESS;
10442 /*! \brief sip_do_debug_peer: Turn on SIP debugging with peer mask */
10443 static int sip_do_debug_peer(int fd, int argc, char *argv[])
10445 struct sip_peer *peer;
10446 if (argc != 4)
10447 return RESULT_SHOWUSAGE;
10448 peer = find_peer(argv[3], NULL, 1);
10449 if (peer) {
10450 if (peer->addr.sin_addr.s_addr) {
10451 debugaddr.sin_family = AF_INET;
10452 debugaddr.sin_addr = peer->addr.sin_addr;
10453 debugaddr.sin_port = peer->addr.sin_port;
10454 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
10455 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
10456 } else
10457 ast_cli(fd, "Unable to get IP address of peer '%s'\n", argv[3]);
10458 ASTOBJ_UNREF(peer,sip_destroy_peer);
10459 } else
10460 ast_cli(fd, "No such peer '%s'\n", argv[3]);
10461 return RESULT_SUCCESS;
10464 /*! \brief Turn on SIP debugging (CLI command) */
10465 static int sip_do_debug(int fd, int argc, char *argv[])
10467 int oldsipdebug = sipdebug_console;
10468 if (argc != 2) {
10469 if (argc != 4)
10470 return RESULT_SHOWUSAGE;
10471 else if (strcmp(argv[2], "ip") == 0)
10472 return sip_do_debug_ip(fd, argc, argv);
10473 else if (strcmp(argv[2], "peer") == 0)
10474 return sip_do_debug_peer(fd, argc, argv);
10475 else
10476 return RESULT_SHOWUSAGE;
10478 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
10479 memset(&debugaddr, 0, sizeof(debugaddr));
10480 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
10481 return RESULT_SUCCESS;
10484 /*! \brief Cli command to send SIP notify to peer */
10485 static int sip_notify(int fd, int argc, char *argv[])
10487 struct ast_variable *varlist;
10488 int i;
10490 if (argc < 4)
10491 return RESULT_SHOWUSAGE;
10493 if (!notify_types) {
10494 ast_cli(fd, "No %s file found, or no types listed there\n", notify_config);
10495 return RESULT_FAILURE;
10498 varlist = ast_variable_browse(notify_types, argv[2]);
10500 if (!varlist) {
10501 ast_cli(fd, "Unable to find notify type '%s'\n", argv[2]);
10502 return RESULT_FAILURE;
10505 for (i = 3; i < argc; i++) {
10506 struct sip_pvt *p;
10507 struct sip_request req;
10508 struct ast_variable *var;
10510 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY))) {
10511 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
10512 return RESULT_FAILURE;
10515 if (create_addr(p, argv[i])) {
10516 /* Maybe they're not registered, etc. */
10517 sip_destroy(p);
10518 ast_cli(fd, "Could not create address for '%s'\n", argv[i]);
10519 continue;
10522 initreqprep(&req, p, SIP_NOTIFY);
10524 for (var = varlist; var; var = var->next)
10525 add_header(&req, var->name, var->value);
10527 /* Recalculate our side, and recalculate Call ID */
10528 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
10529 p->ourip = __ourip;
10530 build_via(p);
10531 build_callid_pvt(p);
10532 ast_cli(fd, "Sending NOTIFY of type '%s' to '%s'\n", argv[2], argv[i]);
10533 transmit_sip_request(p, &req);
10534 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
10537 return RESULT_SUCCESS;
10540 /*! \brief Disable SIP Debugging in CLI */
10541 static int sip_no_debug(int fd, int argc, char *argv[])
10543 if (argc != 3)
10544 return RESULT_SHOWUSAGE;
10545 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
10546 ast_cli(fd, "SIP Debugging Disabled\n");
10547 return RESULT_SUCCESS;
10550 /*! \brief Enable SIP History logging (CLI) */
10551 static int sip_do_history(int fd, int argc, char *argv[])
10553 if (argc != 2) {
10554 return RESULT_SHOWUSAGE;
10556 recordhistory = TRUE;
10557 ast_cli(fd, "SIP History Recording Enabled (use 'sip show history')\n");
10558 return RESULT_SUCCESS;
10561 /*! \brief Disable SIP History logging (CLI) */
10562 static int sip_no_history(int fd, int argc, char *argv[])
10564 if (argc != 3) {
10565 return RESULT_SHOWUSAGE;
10567 recordhistory = FALSE;
10568 ast_cli(fd, "SIP History Recording Disabled\n");
10569 return RESULT_SUCCESS;
10573 /*! \brief Authenticate for outbound registration */
10574 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader)
10576 char digest[1024];
10577 p->authtries++;
10578 memset(digest,0,sizeof(digest));
10579 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
10580 /* There's nothing to use for authentication */
10581 /* No digest challenge in request */
10582 if (sip_debug_test_pvt(p) && p->registry)
10583 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
10584 /* No old challenge */
10585 return -1;
10587 if (recordhistory)
10588 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
10589 if (sip_debug_test_pvt(p) && p->registry)
10590 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
10591 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
10594 /*! \brief Add authentication on outbound SIP packet */
10595 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init)
10597 char digest[1024];
10599 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
10600 return -2;
10602 p->authtries++;
10603 if (option_debug > 1)
10604 ast_log(LOG_DEBUG, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
10605 memset(digest, 0, sizeof(digest));
10606 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
10607 /* No way to authenticate */
10608 return -1;
10610 /* Now we have a reply digest */
10611 p->options->auth = digest;
10612 p->options->authheader = respheader;
10613 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
10616 /*! \brief reply to authentication for outbound registrations
10617 \return Returns -1 if we have no auth
10618 \note This is used for register= servers in sip.conf, SIP proxies we register
10619 with for receiving calls from. */
10620 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
10622 char tmp[512];
10623 char *c;
10624 char oldnonce[256];
10626 /* table of recognised keywords, and places where they should be copied */
10627 const struct x {
10628 const char *key;
10629 int field_index;
10630 } *i, keys[] = {
10631 { "realm=", ast_string_field_index(p, realm) },
10632 { "nonce=", ast_string_field_index(p, nonce) },
10633 { "opaque=", ast_string_field_index(p, opaque) },
10634 { "qop=", ast_string_field_index(p, qop) },
10635 { "domain=", ast_string_field_index(p, domain) },
10636 { NULL, 0 },
10639 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
10640 if (ast_strlen_zero(tmp))
10641 return -1;
10642 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
10643 ast_log(LOG_WARNING, "missing Digest.\n");
10644 return -1;
10646 c = tmp + strlen("Digest ");
10647 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
10648 while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
10649 for (i = keys; i->key != NULL; i++) {
10650 char *src, *separator;
10651 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
10652 continue;
10653 /* Found. Skip keyword, take text in quotes or up to the separator. */
10654 c += strlen(i->key);
10655 if (*c == '"') {
10656 src = ++c;
10657 separator = "\"";
10658 } else {
10659 src = c;
10660 separator = ",";
10662 strsep(&c, separator); /* clear separator and move ptr */
10663 ast_string_field_index_set(p, i->field_index, src);
10664 break;
10666 if (i->key == NULL) /* not found, try ',' */
10667 strsep(&c, ",");
10669 /* Reset nonce count */
10670 if (strcmp(p->nonce, oldnonce))
10671 p->noncecount = 0;
10673 /* Save auth data for following registrations */
10674 if (p->registry) {
10675 struct sip_registry *r = p->registry;
10677 if (strcmp(r->nonce, p->nonce)) {
10678 ast_string_field_set(r, realm, p->realm);
10679 ast_string_field_set(r, nonce, p->nonce);
10680 ast_string_field_set(r, domain, p->domain);
10681 ast_string_field_set(r, opaque, p->opaque);
10682 ast_string_field_set(r, qop, p->qop);
10683 r->noncecount = 0;
10686 return build_reply_digest(p, sipmethod, digest, digest_len);
10689 /*! \brief Build reply digest
10690 \return Returns -1 if we have no auth
10691 \note Build digest challenge for authentication of peers (for registration)
10692 and users (for calls). Also used for authentication of CANCEL and BYE
10694 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
10696 char a1[256];
10697 char a2[256];
10698 char a1_hash[256];
10699 char a2_hash[256];
10700 char resp[256];
10701 char resp_hash[256];
10702 char uri[256];
10703 char cnonce[80];
10704 const char *username;
10705 const char *secret;
10706 const char *md5secret;
10707 struct sip_auth *auth = NULL; /* Realm authentication */
10709 if (!ast_strlen_zero(p->domain))
10710 ast_copy_string(uri, p->domain, sizeof(uri));
10711 else if (!ast_strlen_zero(p->uri))
10712 ast_copy_string(uri, p->uri, sizeof(uri));
10713 else
10714 snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, ast_inet_ntoa(p->sa.sin_addr));
10716 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
10718 /* Check if we have separate auth credentials */
10719 if ((auth = find_realm_authentication(authl, p->realm))) {
10720 ast_log(LOG_WARNING, "use realm [%s] from peer [%s][%s]\n",
10721 auth->username, p->peername, p->username);
10722 username = auth->username;
10723 secret = auth->secret;
10724 md5secret = auth->md5secret;
10725 if (sipdebug)
10726 ast_log(LOG_DEBUG,"Using realm %s authentication for call %s\n", p->realm, p->callid);
10727 } else {
10728 /* No authentication, use peer or register= config */
10729 username = p->authname;
10730 secret = p->peersecret;
10731 md5secret = p->peermd5secret;
10733 if (ast_strlen_zero(username)) /* We have no authentication */
10734 return -1;
10736 /* Calculate SIP digest response */
10737 snprintf(a1,sizeof(a1),"%s:%s:%s", username, p->realm, secret);
10738 snprintf(a2,sizeof(a2),"%s:%s", sip_methods[method].text, uri);
10739 if (!ast_strlen_zero(md5secret))
10740 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
10741 else
10742 ast_md5_hash(a1_hash,a1);
10743 ast_md5_hash(a2_hash,a2);
10745 p->noncecount++;
10746 if (!ast_strlen_zero(p->qop))
10747 snprintf(resp,sizeof(resp),"%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
10748 else
10749 snprintf(resp,sizeof(resp),"%s:%s:%s", a1_hash, p->nonce, a2_hash);
10750 ast_md5_hash(resp_hash, resp);
10751 /* XXX We hard code our qop to "auth" for now. XXX */
10752 if (!ast_strlen_zero(p->qop))
10753 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);
10754 else
10755 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);
10757 return 0;
10760 static char show_domains_usage[] =
10761 "Usage: sip show domains\n"
10762 " Lists all configured SIP local domains.\n"
10763 " Asterisk only responds to SIP messages to local domains.\n";
10765 static char notify_usage[] =
10766 "Usage: sip notify <type> <peer> [<peer>...]\n"
10767 " Send a NOTIFY message to a SIP peer or peers\n"
10768 " Message types are defined in sip_notify.conf\n";
10770 static char show_users_usage[] =
10771 "Usage: sip show users [like <pattern>]\n"
10772 " Lists all known SIP users.\n"
10773 " Optional regular expression pattern is used to filter the user list.\n";
10775 static char show_user_usage[] =
10776 "Usage: sip show user <name> [load]\n"
10777 " Lists all details on one SIP user and the current status.\n"
10778 " Option \"load\" forces lookup of peer in realtime storage.\n";
10780 static char show_inuse_usage[] =
10781 "Usage: sip show inuse [all]\n"
10782 " List all SIP users and peers usage counters and limits.\n"
10783 " Add option \"all\" to show all devices, not only those with a limit.\n";
10785 static char show_channels_usage[] =
10786 "Usage: sip show channels\n"
10787 " Lists all currently active SIP channels.\n";
10789 static char show_channel_usage[] =
10790 "Usage: sip show channel <channel>\n"
10791 " Provides detailed status on a given SIP channel.\n";
10793 static char show_history_usage[] =
10794 "Usage: sip show history <channel>\n"
10795 " Provides detailed dialog history on a given SIP channel.\n";
10797 static char show_peers_usage[] =
10798 "Usage: sip show peers [like <pattern>]\n"
10799 " Lists all known SIP peers.\n"
10800 " Optional regular expression pattern is used to filter the peer list.\n";
10802 static char show_peer_usage[] =
10803 "Usage: sip show peer <name> [load]\n"
10804 " Lists all details on one SIP peer and the current status.\n"
10805 " Option \"load\" forces lookup of peer in realtime storage.\n";
10807 static char prune_realtime_usage[] =
10808 "Usage: sip prune realtime [peer|user] [<name>|all|like <pattern>]\n"
10809 " Prunes object(s) from the cache.\n"
10810 " Optional regular expression pattern is used to filter the objects.\n";
10812 static char show_reg_usage[] =
10813 "Usage: sip show registry\n"
10814 " Lists all registration requests and status.\n";
10816 static char debug_usage[] =
10817 "Usage: sip debug\n"
10818 " Enables dumping of SIP packets for debugging purposes\n\n"
10819 " sip debug ip <host[:PORT]>\n"
10820 " Enables dumping of SIP packets to and from host.\n\n"
10821 " sip debug peer <peername>\n"
10822 " Enables dumping of SIP packets to and from host.\n"
10823 " Require peer to be registered.\n";
10825 static char no_debug_usage[] =
10826 "Usage: sip no debug\n"
10827 " Disables dumping of SIP packets for debugging purposes\n";
10829 static char no_history_usage[] =
10830 "Usage: sip no history\n"
10831 " Disables recording of SIP dialog history for debugging purposes\n";
10833 static char history_usage[] =
10834 "Usage: sip history\n"
10835 " Enables recording of SIP dialog history for debugging purposes.\n"
10836 "Use 'sip show history' to view the history of a call number.\n";
10838 static char sip_reload_usage[] =
10839 "Usage: sip reload\n"
10840 " Reloads SIP configuration from sip.conf\n";
10842 static char show_subscriptions_usage[] =
10843 "Usage: sip show subscriptions\n"
10844 " Shows active SIP subscriptions for extension states\n";
10846 static char show_objects_usage[] =
10847 "Usage: sip show objects\n"
10848 " Shows status of known SIP objects\n";
10850 static char show_settings_usage[] =
10851 "Usage: sip show settings\n"
10852 " Provides detailed list of the configuration of the SIP channel.\n";
10856 /*! \brief Read SIP header (dialplan function) */
10857 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len)
10859 struct sip_pvt *p;
10860 const char *content = NULL;
10861 AST_DECLARE_APP_ARGS(args,
10862 AST_APP_ARG(header);
10863 AST_APP_ARG(number);
10865 int i, number, start = 0;
10867 if (ast_strlen_zero(data)) {
10868 ast_log(LOG_WARNING, "This function requires a header name.\n");
10869 return -1;
10872 ast_channel_lock(chan);
10873 if (chan->tech != &sip_tech) {
10874 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
10875 ast_channel_unlock(chan);
10876 return -1;
10879 AST_STANDARD_APP_ARGS(args, data);
10880 sscanf(args.number, "%d", &number);
10881 if (number < 1)
10882 number = 1;
10884 p = chan->tech_pvt;
10886 /* If there is no private structure, this channel is no longer alive */
10887 if (!p) {
10888 ast_channel_unlock(chan);
10889 return -1;
10892 for (i = 0; i < number; i++)
10893 content = __get_header(&p->initreq, args.header, &start);
10895 if (ast_strlen_zero(content)) {
10896 ast_channel_unlock(chan);
10897 return -1;
10900 ast_copy_string(buf, content, len);
10901 ast_channel_unlock(chan);
10903 return 0;
10906 static struct ast_custom_function sip_header_function = {
10907 .name = "SIP_HEADER",
10908 .synopsis = "Gets the specified SIP header",
10909 .syntax = "SIP_HEADER(<name>[,<number>])",
10910 .desc = "Since there are several headers (such as Via) which can occur multiple\n"
10911 "times, SIP_HEADER takes an optional second argument to specify which header with\n"
10912 "that name to retrieve. Headers start at offset 1.\n",
10913 .read = func_header_read,
10916 /*! \brief Dial plan function to check if domain is local */
10917 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
10919 if (ast_strlen_zero(data)) {
10920 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
10921 return -1;
10923 if (check_sip_domain(data, NULL, 0))
10924 ast_copy_string(buf, data, len);
10925 else
10926 buf[0] = '\0';
10927 return 0;
10930 static struct ast_custom_function checksipdomain_function = {
10931 .name = "CHECKSIPDOMAIN",
10932 .synopsis = "Checks if domain is a local domain",
10933 .syntax = "CHECKSIPDOMAIN(<domain|IP>)",
10934 .read = func_check_sipdomain,
10935 .desc = "This function checks if the domain in the argument is configured\n"
10936 "as a local SIP domain that this Asterisk server is configured to handle.\n"
10937 "Returns the domain name if it is locally handled, otherwise an empty string.\n"
10938 "Check the domain= configuration in sip.conf\n",
10941 /*! \brief ${SIPPEER()} Dialplan function - reads peer data */
10942 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
10944 struct sip_peer *peer;
10945 char *colname;
10947 if ((colname = strchr(data, ':'))) /*! \todo Will be deprecated after 1.4 */
10948 *colname++ = '\0';
10949 else if ((colname = strchr(data, '|')))
10950 *colname++ = '\0';
10951 else
10952 colname = "ip";
10954 if (!(peer = find_peer(data, NULL, 1)))
10955 return -1;
10957 if (!strcasecmp(colname, "ip")) {
10958 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
10959 } else if (!strcasecmp(colname, "status")) {
10960 peer_status(peer, buf, len);
10961 } else if (!strcasecmp(colname, "language")) {
10962 ast_copy_string(buf, peer->language, len);
10963 } else if (!strcasecmp(colname, "regexten")) {
10964 ast_copy_string(buf, peer->regexten, len);
10965 } else if (!strcasecmp(colname, "limit")) {
10966 snprintf(buf, len, "%d", peer->call_limit);
10967 } else if (!strcasecmp(colname, "curcalls")) {
10968 snprintf(buf, len, "%d", peer->inUse);
10969 } else if (!strcasecmp(colname, "accountcode")) {
10970 ast_copy_string(buf, peer->accountcode, len);
10971 } else if (!strcasecmp(colname, "useragent")) {
10972 ast_copy_string(buf, peer->useragent, len);
10973 } else if (!strcasecmp(colname, "mailbox")) {
10974 ast_copy_string(buf, peer->mailbox, len);
10975 } else if (!strcasecmp(colname, "context")) {
10976 ast_copy_string(buf, peer->context, len);
10977 } else if (!strcasecmp(colname, "expire")) {
10978 snprintf(buf, len, "%d", peer->expire);
10979 } else if (!strcasecmp(colname, "dynamic")) {
10980 ast_copy_string(buf, (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no"), len);
10981 } else if (!strcasecmp(colname, "callerid_name")) {
10982 ast_copy_string(buf, peer->cid_name, len);
10983 } else if (!strcasecmp(colname, "callerid_num")) {
10984 ast_copy_string(buf, peer->cid_num, len);
10985 } else if (!strcasecmp(colname, "codecs")) {
10986 ast_getformatname_multiple(buf, len -1, peer->capability);
10987 } else if (!strncasecmp(colname, "codec[", 6)) {
10988 char *codecnum;
10989 int index = 0, codec = 0;
10991 codecnum = colname + 6; /* move past the '[' */
10992 codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
10993 index = atoi(codecnum);
10994 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
10995 ast_copy_string(buf, ast_getformatname(codec), len);
10999 ASTOBJ_UNREF(peer, sip_destroy_peer);
11001 return 0;
11004 /*! \brief Structure to declare a dialplan function: SIPPEER */
11005 struct ast_custom_function sippeer_function = {
11006 .name = "SIPPEER",
11007 .synopsis = "Gets SIP peer information",
11008 .syntax = "SIPPEER(<peername>[|item])",
11009 .read = function_sippeer,
11010 .desc = "Valid items are:\n"
11011 "- ip (default) The IP address.\n"
11012 "- mailbox The configured mailbox.\n"
11013 "- context The configured context.\n"
11014 "- expire The epoch time of the next expire.\n"
11015 "- dynamic Is it dynamic? (yes/no).\n"
11016 "- callerid_name The configured Caller ID name.\n"
11017 "- callerid_num The configured Caller ID number.\n"
11018 "- codecs The configured codecs.\n"
11019 "- status Status (if qualify=yes).\n"
11020 "- regexten Registration extension\n"
11021 "- limit Call limit (call-limit)\n"
11022 "- curcalls Current amount of calls \n"
11023 " Only available if call-limit is set\n"
11024 "- language Default language for peer\n"
11025 "- accountcode Account code for this peer\n"
11026 "- useragent Current user agent id for peer\n"
11027 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
11028 "\n"
11031 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
11032 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11034 struct sip_pvt *p;
11036 *buf = 0;
11038 if (!data) {
11039 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
11040 return -1;
11043 ast_channel_lock(chan);
11044 if (chan->tech != &sip_tech) {
11045 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
11046 ast_channel_unlock(chan);
11047 return -1;
11050 p = chan->tech_pvt;
11052 /* If there is no private structure, this channel is no longer alive */
11053 if (!p) {
11054 ast_channel_unlock(chan);
11055 return -1;
11058 if (!strcasecmp(data, "peerip")) {
11059 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
11060 } else if (!strcasecmp(data, "recvip")) {
11061 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
11062 } else if (!strcasecmp(data, "from")) {
11063 ast_copy_string(buf, p->from, len);
11064 } else if (!strcasecmp(data, "uri")) {
11065 ast_copy_string(buf, p->uri, len);
11066 } else if (!strcasecmp(data, "useragent")) {
11067 ast_copy_string(buf, p->useragent, len);
11068 } else if (!strcasecmp(data, "peername")) {
11069 ast_copy_string(buf, p->peername, len);
11070 } else if (!strcasecmp(data, "t38passthrough")) {
11071 if (p->t38.state == T38_DISABLED)
11072 ast_copy_string(buf, "0", sizeof("0"));
11073 else /* T38 is offered or enabled in this call */
11074 ast_copy_string(buf, "1", sizeof("1"));
11075 } else {
11076 ast_channel_unlock(chan);
11077 return -1;
11079 ast_channel_unlock(chan);
11081 return 0;
11084 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
11085 static struct ast_custom_function sipchaninfo_function = {
11086 .name = "SIPCHANINFO",
11087 .synopsis = "Gets the specified SIP parameter from the current channel",
11088 .syntax = "SIPCHANINFO(item)",
11089 .read = function_sipchaninfo_read,
11090 .desc = "Valid items are:\n"
11091 "- peerip The IP address of the peer.\n"
11092 "- recvip The source IP address of the peer.\n"
11093 "- from The URI from the From: header.\n"
11094 "- uri The URI from the Contact: header.\n"
11095 "- useragent The useragent.\n"
11096 "- peername The name of the peer.\n"
11097 "- t38passthrough 1 if T38 is offered or enabled in this channel, otherwise 0\n"
11100 /*! \brief Parse 302 Moved temporalily response */
11101 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
11103 char tmp[256];
11104 char *s, *e;
11105 char *domain;
11107 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
11108 s = get_in_brackets(tmp);
11109 s = strsep(&s, ";"); /* strip ; and beyond */
11110 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
11111 if (!strncasecmp(s, "sip:", 4))
11112 s += 4;
11113 e = strchr(s, '/');
11114 if (e)
11115 *e = '\0';
11116 ast_log(LOG_DEBUG, "Found promiscuous redirection to 'SIP/%s'\n", s);
11117 if (p->owner)
11118 ast_string_field_build(p->owner, call_forward, "SIP/%s", s);
11119 } else {
11120 e = strchr(tmp, '@');
11121 if (e) {
11122 *e++ = '\0';
11123 domain = e;
11124 } else {
11125 /* No username part */
11126 domain = tmp;
11128 e = strchr(tmp, '/');
11129 if (e)
11130 *e = '\0';
11131 if (!strncasecmp(s, "sip:", 4))
11132 s += 4;
11133 if (option_debug > 1)
11134 ast_log(LOG_DEBUG, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
11135 if (p->owner) {
11136 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
11137 ast_string_field_set(p->owner, call_forward, s);
11142 /*! \brief Check pending actions on SIP call */
11143 static void check_pendings(struct sip_pvt *p)
11145 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
11146 /* if we can't BYE, then this is really a pending CANCEL */
11147 if (!ast_test_flag(&p->flags[0], SIP_CAN_BYE)) {
11148 transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, 1, 0);
11149 /* Actually don't destroy us yet, wait for the 487 on our original
11150 INVITE, but do set an autodestruct just in case we never get it. */
11151 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
11152 } else {
11153 transmit_request_with_auth(p, SIP_BYE, 0, 1, 1);
11154 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11155 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
11157 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
11158 if (option_debug)
11159 ast_log(LOG_DEBUG, "Sending pending reinvite on '%s'\n", p->callid);
11160 /* Didn't get to reinvite yet, so do it now */
11161 transmit_reinvite_with_sdp(p);
11162 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
11166 /*! \brief Handle SIP response to INVITE dialogue */
11167 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
11169 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
11170 int res = 0;
11171 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
11172 struct ast_channel *bridgepeer = NULL;
11174 if (option_debug > 3) {
11175 if (reinvite)
11176 ast_log(LOG_DEBUG, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
11177 else
11178 ast_log(LOG_DEBUG, "SIP response %d to standard invite\n", resp);
11181 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) { /* This call is already gone */
11182 ast_log(LOG_DEBUG, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
11183 return;
11186 /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
11187 if (p->initid > -1) {
11188 /* Don't auto congest anymore since we've gotten something useful back */
11189 ast_sched_del(sched, p->initid);
11190 p->initid = -1;
11193 /* RFC3261 says we must treat every 1xx response (but not 100)
11194 that we don't recognize as if it was 183.
11196 if ((resp > 100) &&
11197 (resp < 200) &&
11198 (resp != 180) &&
11199 (resp != 183))
11200 resp = 183;
11202 switch (resp) {
11203 case 100: /* Trying */
11204 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11205 sip_cancel_destroy(p);
11206 check_pendings(p);
11207 break;
11208 case 180: /* 180 Ringing */
11209 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11210 sip_cancel_destroy(p);
11211 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
11212 ast_queue_control(p->owner, AST_CONTROL_RINGING);
11213 if (p->owner->_state != AST_STATE_UP) {
11214 ast_setstate(p->owner, AST_STATE_RINGING);
11217 if (find_sdp(req)) {
11218 res = process_sdp(p, req);
11219 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
11220 /* Queue a progress frame only if we have SDP in 180 */
11221 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
11224 ast_set_flag(&p->flags[0], SIP_CAN_BYE);
11225 check_pendings(p);
11226 break;
11227 case 183: /* Session progress */
11228 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11229 sip_cancel_destroy(p);
11230 /* Ignore 183 Session progress without SDP */
11231 if (find_sdp(req)) {
11232 res = process_sdp(p, req);
11233 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
11234 /* Queue a progress frame */
11235 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
11238 ast_set_flag(&p->flags[0], SIP_CAN_BYE);
11239 check_pendings(p);
11240 break;
11241 case 200: /* 200 OK on invite - someone's answering our call */
11242 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11243 sip_cancel_destroy(p);
11244 p->authtries = 0;
11245 if (find_sdp(req)) {
11246 if ((res = process_sdp(p, req)) && !ast_test_flag(req, SIP_PKT_IGNORE))
11247 if (!reinvite)
11248 /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
11249 /* For re-invites, we try to recover */
11250 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
11253 /* Parse contact header for continued conversation */
11254 /* When we get 200 OK, we know which device (and IP) to contact for this call */
11255 /* This is important when we have a SIP proxy between us and the phone */
11256 if (outgoing) {
11257 update_call_counter(p, DEC_CALL_RINGING);
11258 parse_ok_contact(p, req);
11259 if(set_address_from_contact(p)) {
11260 /* Bad contact - we don't know how to reach this device */
11261 /* We need to ACK, but then send a bye */
11262 /* OEJ: Possible issue that may need a check:
11263 If we have a proxy route between us and the device,
11264 should we care about resolving the contact
11265 or should we just send it?
11267 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11268 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
11271 /* Save Record-Route for any later requests we make on this dialogue */
11272 build_route(p, req, 1);
11275 if (p->owner && (p->owner->_state == AST_STATE_UP) && (bridgepeer = ast_bridged_channel(p->owner))) { /* if this is a re-invite */
11276 struct sip_pvt *bridgepvt = NULL;
11278 if (!bridgepeer->tech) {
11279 ast_log(LOG_WARNING, "Ooooh.. no tech! That's REALLY bad\n");
11280 break;
11282 if (!strcasecmp(bridgepeer->tech->type,"SIP")) {
11283 bridgepvt = (struct sip_pvt*)(bridgepeer->tech_pvt);
11284 if (bridgepvt->udptl) {
11285 if (p->t38.state == T38_PEER_REINVITE) {
11286 sip_handle_t38_reinvite(bridgepeer, p, 0);
11287 } else if (p->t38.state == T38_DISABLED && bridgepeer && (bridgepvt->t38.state == T38_ENABLED)) {
11288 ast_log(LOG_WARNING, "RTP re-inivte after T38 session not handled yet !\n");
11289 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
11290 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11292 } else {
11293 ast_log(LOG_WARNING, "Strange... The other side of the bridge does not have a udptl struct\n");
11294 ast_mutex_lock(&bridgepvt->lock);
11295 bridgepvt->t38.state = T38_DISABLED;
11296 ast_mutex_unlock(&bridgepvt->lock);
11297 if (option_debug)
11298 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->tech->type);
11299 p->t38.state = T38_DISABLED;
11300 if (option_debug > 1)
11301 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11303 } else {
11304 /* Other side is not a SIP channel */
11305 ast_log(LOG_WARNING, "Strange... The other side of the bridge is not a SIP channel\n");
11306 p->t38.state = T38_DISABLED;
11307 if (option_debug > 1)
11308 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11311 if ((p->t38.state == T38_LOCAL_REINVITE) || (p->t38.state == T38_LOCAL_DIRECT)) {
11312 /* If there was T38 reinvite and we are supposed to answer with 200 OK than this should set us to T38 negotiated mode */
11313 p->t38.state = T38_ENABLED;
11314 if (option_debug)
11315 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11318 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
11319 if (!reinvite) {
11320 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
11321 } else { /* RE-invite */
11322 ast_queue_frame(p->owner, &ast_null_frame);
11324 } else {
11325 /* It's possible we're getting an 200 OK after we've tried to disconnect
11326 by sending CANCEL */
11327 /* First send ACK, then send bye */
11328 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11329 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
11331 /* If I understand this right, the branch is different for a non-200 ACK only */
11332 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
11333 ast_set_flag(&p->flags[0], SIP_CAN_BYE);
11334 check_pendings(p);
11335 break;
11336 case 407: /* Proxy authentication */
11337 case 401: /* Www auth */
11338 /* First we ACK */
11339 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11340 if (p->options)
11341 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
11343 /* Then we AUTH */
11344 ast_string_field_free(p, theirtag); /* forget their old tag, so we don't match tags when getting response */
11345 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
11346 char *authenticate = (resp == 401 ? "WWW-Authenticate" : "Proxy-Authenticate");
11347 char *authorization = (resp == 401 ? "Authorization" : "Proxy-Authorization");
11348 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, authenticate, authorization, SIP_INVITE, 1)) {
11349 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
11350 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11351 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
11352 if (p->owner)
11353 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11356 break;
11357 case 403: /* Forbidden */
11358 /* First we ACK */
11359 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11360 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
11361 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner)
11362 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11363 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11364 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
11365 break;
11366 case 404: /* Not found */
11367 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11368 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
11369 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11370 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
11371 break;
11372 case 481: /* Call leg does not exist */
11373 /* Could be REFER or INVITE */
11374 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
11375 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11376 break;
11377 case 491: /* Pending */
11378 /* we have to wait a while, then retransmit */
11379 /* Transmission is rescheduled, so everything should be taken care of.
11380 We should support the retry-after at some point */
11381 break;
11382 case 501: /* Not implemented */
11383 if (p->owner)
11384 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11385 break;
11389 /* \brief Handle SIP response in REFER transaction
11390 We've sent a REFER, now handle responses to it
11392 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
11394 char *auth = "Proxy-Authenticate";
11395 char *auth2 = "Proxy-Authorization";
11397 switch (resp) {
11398 case 202: /* Transfer accepted */
11399 /* We need to do something here */
11400 /* The transferee is now sending INVITE to target */
11401 p->refer->status = REFER_ACCEPTED;
11402 /* Now wait for next message */
11403 if (option_debug > 2)
11404 ast_log(LOG_DEBUG, "Got 202 accepted on transfer\n");
11405 /* We should hang along, waiting for NOTIFY's here */
11406 break;
11408 case 401: /* Not www-authorized on SIP method */
11409 case 407: /* Proxy auth */
11410 if (ast_strlen_zero(p->authname)) {
11411 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
11412 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
11413 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11415 if (resp == 401) {
11416 auth = "WWW-Authenticate";
11417 auth2 = "Authorization";
11419 if ((p->authtries > 1) || do_proxy_auth(p, req, auth, auth2, SIP_REFER, 0)) {
11420 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
11421 p->refer->status = REFER_NOAUTH;
11422 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11424 break;
11427 case 500: /* Server error */
11428 case 501: /* Method not implemented */
11429 /* Return to the current call onhold */
11430 /* Status flag needed to be reset */
11431 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
11432 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11433 p->refer->status = REFER_FAILED;
11434 break;
11435 case 603: /* Transfer declined */
11436 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
11437 p->refer->status = REFER_FAILED;
11438 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11439 break;
11443 /*! \brief Handle responses on REGISTER to services */
11444 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
11446 int expires, expires_ms;
11447 struct sip_registry *r;
11448 r=p->registry;
11450 switch (resp) {
11451 case 401: /* Unauthorized */
11452 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "WWW-Authenticate", "Authorization")) {
11453 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
11454 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11456 break;
11457 case 403: /* Forbidden */
11458 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
11459 if (global_regattempts_max)
11460 p->registry->regattempts = global_regattempts_max+1;
11461 ast_sched_del(sched, r->timeout);
11462 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11463 break;
11464 case 404: /* Not found */
11465 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username,p->registry->hostname);
11466 if (global_regattempts_max)
11467 p->registry->regattempts = global_regattempts_max+1;
11468 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11469 r->call = NULL;
11470 ast_sched_del(sched, r->timeout);
11471 break;
11472 case 407: /* Proxy auth */
11473 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization")) {
11474 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
11475 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11477 break;
11478 case 479: /* SER: Not able to process the URI - address is wrong in register*/
11479 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username,p->registry->hostname);
11480 if (global_regattempts_max)
11481 p->registry->regattempts = global_regattempts_max+1;
11482 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11483 r->call = NULL;
11484 ast_sched_del(sched, r->timeout);
11485 break;
11486 case 200: /* 200 OK */
11487 if (!r) {
11488 ast_log(LOG_WARNING, "Got 200 OK on REGISTER that isn't a register\n");
11489 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11490 return 0;
11493 r->regstate = REG_STATE_REGISTERED;
11494 r->regtime = time(NULL); /* Reset time of last succesful registration */
11495 manager_event(EVENT_FLAG_SYSTEM, "Registry", "Channel: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
11496 r->regattempts = 0;
11497 ast_log(LOG_DEBUG, "Registration successful\n");
11498 if (r->timeout > -1) {
11499 ast_log(LOG_DEBUG, "Cancelling timeout %d\n", r->timeout);
11500 ast_sched_del(sched, r->timeout);
11502 r->timeout=-1;
11503 r->call = NULL;
11504 p->registry = NULL;
11505 /* Let this one hang around until we have all the responses */
11506 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
11507 /* ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); */
11509 /* set us up for re-registering */
11510 /* figure out how long we got registered for */
11511 if (r->expire > -1)
11512 ast_sched_del(sched, r->expire);
11513 /* according to section 6.13 of RFC, contact headers override
11514 expires headers, so check those first */
11515 expires = 0;
11516 if (!ast_strlen_zero(get_header(req, "Contact"))) {
11517 const char *contact = NULL;
11518 const char *tmptmp = NULL;
11519 int start = 0;
11520 for(;;) {
11521 contact = __get_header(req, "Contact", &start);
11522 /* this loop ensures we get a contact header about our register request */
11523 if(!ast_strlen_zero(contact)) {
11524 if( (tmptmp=strstr(contact, p->our_contact))) {
11525 contact=tmptmp;
11526 break;
11528 } else
11529 break;
11531 tmptmp = strcasestr(contact, "expires=");
11532 if (tmptmp) {
11533 if (sscanf(tmptmp + 8, "%d;", &expires) != 1)
11534 expires = 0;
11538 if (!expires)
11539 expires=atoi(get_header(req, "expires"));
11540 if (!expires)
11541 expires=default_expiry;
11543 expires_ms = expires * 1000;
11544 if (expires <= EXPIRY_GUARD_LIMIT)
11545 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT),EXPIRY_GUARD_MIN);
11546 else
11547 expires_ms -= EXPIRY_GUARD_SECS * 1000;
11548 if (sipdebug)
11549 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
11551 r->refresh= (int) expires_ms / 1000;
11553 /* Schedule re-registration before we expire */
11554 r->expire=ast_sched_add(sched, expires_ms, sip_reregister, r);
11555 ASTOBJ_UNREF(r, sip_registry_destroy);
11557 return 1;
11560 /*! \brief Handle qualification responses (OPTIONS) */
11561 static int handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
11563 struct sip_peer *peer;
11564 int pingtime;
11565 struct timeval tv;
11567 if (resp != 100) {
11568 int statechanged = 0;
11569 int newstate = 0;
11570 peer = p->relatedpeer;
11571 gettimeofday(&tv, NULL);
11572 pingtime = ast_tvdiff_ms(tv, peer->ps);
11573 if (pingtime < 1)
11574 pingtime = 1;
11575 if ((peer->lastms < 0) || (peer->lastms > peer->maxms)) {
11576 if (pingtime <= peer->maxms) {
11577 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! (%dms / %dms)\n", peer->name, pingtime, peer->maxms);
11578 statechanged = 1;
11579 newstate = 1;
11581 } else if ((peer->lastms > 0) && (peer->lastms <= peer->maxms)) {
11582 if (pingtime > peer->maxms) {
11583 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED! (%dms / %dms)\n", peer->name, pingtime, peer->maxms);
11584 statechanged = 1;
11585 newstate = 2;
11588 if (!peer->lastms)
11589 statechanged = 1;
11590 peer->lastms = pingtime;
11591 peer->call = NULL;
11592 if (statechanged) {
11593 ast_device_state_changed("SIP/%s", peer->name);
11594 if (newstate == 2) {
11595 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Lagged\r\nTime: %d\r\n", peer->name, pingtime);
11596 } else {
11597 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Reachable\r\nTime: %d\r\n", peer->name, pingtime);
11601 if (peer->pokeexpire > -1)
11602 ast_sched_del(sched, peer->pokeexpire);
11603 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11605 /* Try again eventually */
11606 if ((peer->lastms < 0) || (peer->lastms > peer->maxms))
11607 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
11608 else
11609 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_OK, sip_poke_peer_s, peer);
11611 return 1;
11614 /*! \brief Handle SIP response in dialogue */
11615 /* XXX only called by handle_request */
11616 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
11618 struct ast_channel *owner;
11619 int sipmethod;
11620 int res = 1;
11621 const char *c = get_header(req, "Cseq");
11622 const char *msg = strchr(c, ' ');
11624 if (!msg)
11625 msg = "";
11626 else
11627 msg++;
11628 sipmethod = find_sip_method(msg);
11630 owner = p->owner;
11631 if (owner)
11632 owner->hangupcause = hangup_sip2cause(resp);
11634 /* Acknowledge whatever it is destined for */
11635 if ((resp >= 100) && (resp <= 199))
11636 __sip_semi_ack(p, seqno, 0, sipmethod);
11637 else
11638 __sip_ack(p, seqno, 0, sipmethod, resp == 491 ? TRUE : FALSE);
11640 /* Get their tag if we haven't already */
11641 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
11642 char tag[128];
11644 gettag(req, "To", tag, sizeof(tag));
11645 ast_string_field_set(p, theirtag, tag);
11647 if (p->relatedpeer && p->method == SIP_OPTIONS) {
11648 /* We don't really care what the response is, just that it replied back.
11649 Well, as long as it's not a 100 response... since we might
11650 need to hang around for something more "definitive" */
11652 res = handle_response_peerpoke(p, resp, req);
11653 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
11654 switch(resp) {
11655 case 100: /* 100 Trying */
11656 if (sipmethod == SIP_INVITE)
11657 handle_response_invite(p, resp, rest, req, seqno);
11658 break;
11659 case 183: /* 183 Session Progress */
11660 if (sipmethod == SIP_INVITE)
11661 handle_response_invite(p, resp, rest, req, seqno);
11662 break;
11663 case 180: /* 180 Ringing */
11664 if (sipmethod == SIP_INVITE)
11665 handle_response_invite(p, resp, rest, req, seqno);
11666 break;
11667 case 200: /* 200 OK */
11668 p->authtries = 0; /* Reset authentication counter */
11669 if (sipmethod == SIP_MESSAGE) {
11670 /* We successfully transmitted a message */
11671 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11672 } else if (sipmethod == SIP_INVITE) {
11673 handle_response_invite(p, resp, rest, req, seqno);
11674 } else if (sipmethod == SIP_NOTIFY) {
11675 /* They got the notify, this is the end */
11676 if (p->owner) {
11677 if (!p->refer) {
11678 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
11679 ast_queue_hangup(p->owner);
11680 } else if (option_debug > 3)
11681 ast_log(LOG_DEBUG, "Got OK on REFER Notify message\n");
11682 } else {
11683 if (p->subscribed == NONE)
11684 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11686 } else if (sipmethod == SIP_REGISTER)
11687 res = handle_response_register(p, resp, rest, req, ignore, seqno);
11688 else if (sipmethod == SIP_BYE)
11689 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11690 break;
11691 case 202: /* Transfer accepted */
11692 if (sipmethod == SIP_REFER)
11693 handle_response_refer(p, resp, rest, req, seqno);
11694 break;
11695 case 401: /* Not www-authorized on SIP method */
11696 if (sipmethod == SIP_INVITE)
11697 handle_response_invite(p, resp, rest, req, seqno);
11698 else if (sipmethod == SIP_REFER)
11699 handle_response_refer(p, resp, rest, req, seqno);
11700 else if (p->registry && sipmethod == SIP_REGISTER)
11701 res = handle_response_register(p, resp, rest, req, ignore, seqno);
11702 else {
11703 ast_log(LOG_WARNING, "Got authentication request (401) on unknown %s to '%s'\n", sip_methods[sipmethod].text, get_header(req, "To"));
11704 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11706 break;
11707 case 403: /* Forbidden - we failed authentication */
11708 if (sipmethod == SIP_INVITE)
11709 handle_response_invite(p, resp, rest, req, seqno);
11710 else if (p->registry && sipmethod == SIP_REGISTER)
11711 res = handle_response_register(p, resp, rest, req, ignore, seqno);
11712 else {
11713 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
11714 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11716 break;
11717 case 404: /* Not found */
11718 if (p->registry && sipmethod == SIP_REGISTER)
11719 res = handle_response_register(p, resp, rest, req, ignore, seqno);
11720 else if (sipmethod == SIP_INVITE)
11721 handle_response_invite(p, resp, rest, req, seqno);
11722 else if (owner)
11723 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11724 break;
11725 case 407: /* Proxy auth required */
11726 if (sipmethod == SIP_INVITE)
11727 handle_response_invite(p, resp, rest, req, seqno);
11728 else if (sipmethod == SIP_REFER)
11729 handle_response_refer(p, resp, rest, req, seqno);
11730 else if (p->registry && sipmethod == SIP_REGISTER)
11731 res = handle_response_register(p, resp, rest, req, ignore, seqno);
11732 else if (sipmethod == SIP_BYE) {
11733 if (ast_strlen_zero(p->authname))
11734 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
11735 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
11736 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11737 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", sipmethod, 0)) {
11738 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
11739 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11741 } else /* We can't handle this, giving up in a bad way */
11742 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11744 break;
11745 case 481: /* Call leg does not exist */
11746 if (sipmethod == SIP_INVITE) {
11747 /* First we ACK */
11748 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11749 ast_log(LOG_WARNING, "INVITE with REPLACEs failed to '%s'\n", get_header(&p->initreq, "From"));
11750 if (owner)
11751 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11752 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
11753 } else if (sipmethod == SIP_REFER) {
11754 /* A transfer with Replaces did not work */
11755 /* OEJ: We should Set flag, cancel the REFER, go back
11756 to original call - but right now we can't */
11757 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
11758 if (owner)
11759 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11760 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11761 } else if (sipmethod == SIP_BYE) {
11762 /* The other side has no transaction to bye,
11763 just assume it's all right then */
11764 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
11765 } else if (sipmethod == SIP_CANCEL) {
11766 /* The other side has no transaction to cancel,
11767 just assume it's all right then */
11768 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
11769 } else {
11770 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
11771 /* Guessing that this is not an important request */
11773 break;
11774 case 491: /* Pending */
11775 if (sipmethod == SIP_INVITE)
11776 handle_response_invite(p, resp, rest, req, seqno);
11777 else {
11778 ast_log(LOG_DEBUG, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
11779 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11781 break;
11782 case 501: /* Not Implemented */
11783 if (sipmethod == SIP_INVITE)
11784 handle_response_invite(p, resp, rest, req, seqno);
11785 else if (sipmethod == SIP_REFER)
11786 handle_response_refer(p, resp, rest, req, seqno);
11787 else
11788 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
11789 break;
11790 case 603: /* Declined transfer */
11791 if (sipmethod == SIP_REFER) {
11792 handle_response_refer(p, resp, rest, req, seqno);
11793 break;
11795 /* Fallthrough */
11796 default:
11797 if ((resp >= 300) && (resp < 700)) {
11798 /* Fatal response */
11799 if ((option_verbose > 2) && (resp != 487))
11800 ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
11801 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
11802 if (p->rtp) {
11803 /* Immediately stop RTP */
11804 ast_rtp_stop(p->rtp);
11806 if (p->vrtp) {
11807 /* Immediately stop VRTP */
11808 ast_rtp_stop(p->vrtp);
11810 if (p->udptl) {
11811 /* Immediately stop UDPTL */
11812 ast_udptl_stop(p->udptl);
11814 /* XXX Locking issues?? XXX */
11815 switch(resp) {
11816 case 300: /* Multiple Choices */
11817 case 301: /* Moved permenantly */
11818 case 302: /* Moved temporarily */
11819 case 305: /* Use Proxy */
11820 parse_moved_contact(p, req);
11821 /* Fall through */
11822 case 486: /* Busy here */
11823 case 600: /* Busy everywhere */
11824 case 603: /* Decline */
11825 if (p->owner)
11826 ast_queue_control(p->owner, AST_CONTROL_BUSY);
11827 break;
11828 case 487: /* Response on INVITE that has been CANCELled */
11829 /* channel now destroyed - dec the inUse counter */
11830 update_call_counter(p, DEC_CALL_LIMIT);
11831 break;
11832 case 482: /*
11833 \note SIP is incapable of performing a hairpin call, which
11834 is yet another failure of not having a layer 2 (again, YAY
11835 IETF for thinking ahead). So we treat this as a call
11836 forward and hope we end up at the right place... */
11837 ast_log(LOG_DEBUG, "Hairpin detected, setting up call forward for what it's worth\n");
11838 if (p->owner)
11839 ast_string_field_build(p->owner, call_forward,
11840 "Local/%s@%s", p->username, p->context);
11841 /* Fall through */
11842 case 488: /* Not acceptable here - codec error */
11843 case 480: /* Temporarily Unavailable */
11844 case 404: /* Not Found */
11845 case 410: /* Gone */
11846 case 400: /* Bad Request */
11847 case 500: /* Server error */
11848 if (sipmethod == SIP_REFER) {
11849 handle_response_refer(p, resp, rest, req, seqno);
11850 break;
11852 /* Fall through */
11853 case 503: /* Service Unavailable */
11854 if (owner)
11855 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11856 break;
11857 default:
11858 /* Send hangup */
11859 if (owner)
11860 ast_queue_hangup(p->owner);
11861 break;
11863 /* ACK on invite */
11864 if (sipmethod == SIP_INVITE)
11865 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11866 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
11867 if (!p->owner)
11868 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11869 } else if ((resp >= 100) && (resp < 200)) {
11870 if (sipmethod == SIP_INVITE) {
11871 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11872 sip_cancel_destroy(p);
11873 if (find_sdp(req))
11874 process_sdp(p, req);
11875 if (p->owner) {
11876 /* Queue a progress frame */
11877 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
11880 } else
11881 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));
11883 } else {
11884 /* Responses to OUTGOING SIP requests on INCOMING calls
11885 get handled here. As well as out-of-call message responses */
11886 if (ast_test_flag(req, SIP_PKT_DEBUG))
11887 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
11889 if (sipmethod == SIP_INVITE && resp == 200) {
11890 /* Tags in early session is replaced by the tag in 200 OK, which is
11891 the final reply to our INVITE */
11892 char tag[128];
11894 gettag(req, "To", tag, sizeof(tag));
11895 ast_string_field_set(p, theirtag, tag);
11898 switch(resp) {
11899 case 200:
11900 if (sipmethod == SIP_INVITE) {
11901 handle_response_invite(p, resp, rest, req, seqno);
11902 } else if (sipmethod == SIP_CANCEL) {
11903 ast_log(LOG_DEBUG, "Got 200 OK on CANCEL\n");
11904 /* Wait for 487, then destroy */
11905 } else if (sipmethod == SIP_NOTIFY) {
11906 /* They got the notify, this is the end */
11907 if (p->owner) {
11908 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
11909 /* ast_queue_hangup(p->owner); Disabled */
11910 } else {
11911 if (!p->subscribed && !p->refer)
11912 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11914 } else if (sipmethod == SIP_BYE)
11915 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11916 else if (sipmethod == SIP_MESSAGE)
11917 /* We successfully transmitted a message */
11918 /* XXX Why destroy this pvt after message transfer? Bad */
11919 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11920 break;
11921 case 202: /* Transfer accepted */
11922 if (sipmethod == SIP_REFER)
11923 handle_response_refer(p, resp, rest, req, seqno);
11924 break;
11925 case 401: /* www-auth */
11926 case 407:
11927 if (sipmethod == SIP_REFER)
11928 handle_response_refer(p, resp, rest, req, seqno);
11929 else if (sipmethod == SIP_INVITE)
11930 handle_response_invite(p, resp, rest, req, seqno);
11931 else if (sipmethod == SIP_BYE) {
11932 char *auth, *auth2;
11934 auth = (resp == 407 ? "Proxy-Authenticate" : "WWW-Authenticate");
11935 auth2 = (resp == 407 ? "Proxy-Authorization" : "Authorization");
11936 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, auth, auth2, sipmethod, 0)) {
11937 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
11938 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11941 break;
11942 case 481: /* Call leg does not exist */
11943 if (sipmethod == SIP_INVITE) {
11944 /* Re-invite failed */
11945 handle_response_invite(p, resp, rest, req, seqno);
11946 } else if (sipmethod == SIP_BYE) {
11947 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11948 } else if (sipdebug) {
11949 ast_log (LOG_DEBUG, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
11951 break;
11952 case 501: /* Not Implemented */
11953 if (sipmethod == SIP_INVITE)
11954 handle_response_invite(p, resp, rest, req, seqno);
11955 else if (sipmethod == SIP_REFER)
11956 handle_response_refer(p, resp, rest, req, seqno);
11957 break;
11958 case 603: /* Declined transfer */
11959 if (sipmethod == SIP_REFER) {
11960 handle_response_refer(p, resp, rest, req, seqno);
11961 break;
11963 /* Fallthrough */
11964 default: /* Errors without handlers */
11965 if ((resp >= 100) && (resp < 200)) {
11966 if (sipmethod == SIP_INVITE) { /* re-invite */
11967 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11968 sip_cancel_destroy(p);
11971 if ((resp >= 300) && (resp < 700)) {
11972 if ((option_verbose > 2) && (resp != 487))
11973 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));
11974 switch(resp) {
11975 case 488: /* Not acceptable here - codec error */
11976 case 603: /* Decline */
11977 case 500: /* Server error */
11978 case 503: /* Service Unavailable */
11980 if (sipmethod == SIP_INVITE) { /* re-invite failed */
11981 sip_cancel_destroy(p);
11983 break;
11986 break;
11992 /*! \brief Park SIP call support function
11993 Starts in a new thread, then parks the call
11994 XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
11995 audio can't be heard before hangup
11997 static void *sip_park_thread(void *stuff)
11999 struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
12000 struct sip_dual *d;
12001 struct sip_request req;
12002 int ext;
12003 int res;
12005 d = stuff;
12006 transferee = d->chan1;
12007 transferer = d->chan2;
12008 copy_request(&req, &d->req);
12009 free(d);
12011 if (!transferee || !transferer) {
12012 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
12013 return NULL;
12015 if (option_debug > 3)
12016 ast_log(LOG_DEBUG, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
12018 ast_channel_lock(transferee);
12019 if (ast_do_masquerade(transferee)) {
12020 ast_log(LOG_WARNING, "Masquerade failed.\n");
12021 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
12022 ast_channel_unlock(transferee);
12023 return NULL;
12025 ast_channel_unlock(transferee);
12027 res = ast_park_call(transferee, transferer, 0, &ext);
12030 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
12031 if (!res) {
12032 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
12033 } else {
12034 /* Then tell the transferer what happened */
12035 sprintf(buf, "Call parked on extension '%d'", ext);
12036 transmit_message_with_text(transferer->tech_pvt, buf);
12038 #endif
12040 /* Any way back to the current call??? */
12041 /* Transmit response to the REFER request */
12042 transmit_response(transferer->tech_pvt, "202 Accepted", &req);
12043 if (!res) {
12044 /* Transfer succeeded */
12045 append_history(transferer->tech_pvt, "SIPpark","Parked call on %d", ext);
12046 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
12047 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
12048 ast_hangup(transferer); /* This will cause a BYE */
12049 if (option_debug)
12050 ast_log(LOG_DEBUG, "SIP Call parked on extension '%d'\n", ext);
12051 } else {
12052 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
12053 append_history(transferer->tech_pvt, "SIPpark","Parking failed\n");
12054 if (option_debug)
12055 ast_log(LOG_DEBUG, "SIP Call parked failed \n");
12056 /* Do not hangup call */
12058 return NULL;
12061 /*! \brief Park a call using the subsystem in res_features.c
12062 This is executed in a separate thread
12064 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
12066 struct sip_dual *d;
12067 struct ast_channel *transferee, *transferer;
12068 /* Chan2m: The transferer, chan1m: The transferee */
12069 pthread_t th;
12071 transferee = ast_channel_alloc(0);
12072 transferer = ast_channel_alloc(0);
12073 if ((!transferer) || (!transferee)) {
12074 if (transferee) {
12075 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
12076 ast_hangup(transferee);
12078 if (transferer) {
12079 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
12080 ast_hangup(transferer);
12082 return -1;
12084 ast_string_field_build(transferee, name, "Parking/%s", chan1->name);
12086 /* Make formats okay */
12087 transferee->readformat = chan1->readformat;
12088 transferee->writeformat = chan1->writeformat;
12090 /* Prepare for taking over the channel */
12091 ast_channel_masquerade(transferee, chan1);
12093 /* Setup the extensions and such */
12094 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
12095 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
12096 transferee->priority = chan1->priority;
12098 /* We make a clone of the peer channel too, so we can play
12099 back the announcement */
12100 ast_string_field_build(transferer, name, "SIPPeer/%s", chan2->name);
12102 /* Make formats okay */
12103 transferer->readformat = chan2->readformat;
12104 transferer->writeformat = chan2->writeformat;
12106 /* Prepare for taking over the channel */
12107 ast_channel_masquerade(transferer, chan2);
12109 /* Setup the extensions and such */
12110 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
12111 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
12112 transferer->priority = chan2->priority;
12114 ast_channel_lock(transferer);
12115 if (ast_do_masquerade(transferer)) {
12116 ast_log(LOG_WARNING, "Masquerade failed :(\n");
12117 ast_channel_unlock(transferer);
12118 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
12119 ast_hangup(transferer);
12120 return -1;
12122 ast_channel_unlock(transferer);
12123 if (!transferer || !transferee) {
12124 if (!transferer)
12125 ast_log(LOG_DEBUG, "No transferer channel, giving up parking\n");
12126 if (!transferee)
12127 ast_log(LOG_DEBUG, "No transferee channel, giving up parking\n");
12128 return -1;
12130 if ((d = ast_calloc(1, sizeof(*d)))) {
12131 /* Save original request for followup */
12132 copy_request(&d->req, req);
12133 d->chan1 = transferee; /* Transferee */
12134 d->chan2 = transferer; /* Transferer */
12135 d->seqno = seqno;
12136 if (ast_pthread_create(&th, NULL, sip_park_thread, d) < 0) {
12137 /* Could not start thread */
12138 free(d); /* We don't need it anymore. If thread is created, d will be free'd
12139 by sip_park_thread() */
12140 return 0;
12143 return -1;
12146 /*! \brief Turn off generator data
12147 XXX Does this function belong in the SIP channel?
12149 static void ast_quiet_chan(struct ast_channel *chan)
12151 if (chan && chan->_state == AST_STATE_UP) {
12152 if (chan->generatordata)
12153 ast_deactivate_generator(chan);
12157 /*! \brief Attempt transfer of SIP call
12158 This fix for attended transfers on a local PBX */
12159 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
12161 int res = 0;
12162 struct ast_channel *peera = NULL,
12163 *peerb = NULL,
12164 *peerc = NULL,
12165 *peerd = NULL;
12168 /* We will try to connect the transferee with the target and hangup
12169 all channels to the transferer */
12170 if (option_debug > 3) {
12171 ast_log(LOG_DEBUG, "Sip transfer:--------------------\n");
12172 if (transferer->chan1)
12173 ast_log(LOG_DEBUG, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
12174 else
12175 ast_log(LOG_DEBUG, "-- No transferer first channel - odd??? \n");
12176 if (target->chan1)
12177 ast_log(LOG_DEBUG, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
12178 else
12179 ast_log(LOG_DEBUG, "-- No target first channel ---\n");
12180 if (transferer->chan2)
12181 ast_log(LOG_DEBUG, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
12182 else
12183 ast_log(LOG_DEBUG, "-- No bridged call to transferee\n");
12184 if (target->chan2)
12185 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)");
12186 else
12187 ast_log(LOG_DEBUG, "-- No target second channel ---\n");
12188 ast_log(LOG_DEBUG, "-- END Sip transfer:--------------------\n");
12190 if (transferer->chan2) { /* We have a bridge on the transferer's channel */
12191 peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
12192 peerb = target->chan1; /* Transferer - PBX -> target channel - This will get lost in masq */
12193 peerc = transferer->chan2; /* Asterisk to Transferee */
12194 peerd = target->chan2; /* Asterisk to Target */
12195 if (option_debug > 2)
12196 ast_log(LOG_DEBUG, "SIP transfer: Four channels to handle\n");
12197 } else if (target->chan2) { /* Transferer has no bridge (IVR), but transferee */
12198 peera = target->chan1; /* Transferer to PBX -> target channel */
12199 peerb = transferer->chan1; /* Transferer to IVR*/
12200 peerc = target->chan2; /* Asterisk to Target */
12201 peerd = transferer->chan2; /* Nothing */
12202 if (option_debug > 2)
12203 ast_log(LOG_DEBUG, "SIP transfer: Three channels to handle\n");
12206 if (peera && peerb && peerc && (peerb != peerc)) {
12207 ast_quiet_chan(peera); /* Stop generators */
12208 ast_quiet_chan(peerb);
12209 ast_quiet_chan(peerc);
12210 if (peerd)
12211 ast_quiet_chan(peerd);
12213 /* Fix CDRs so they're attached to the remaining channel */
12214 if (peera->cdr && peerb->cdr)
12215 peerb->cdr = ast_cdr_append(peerb->cdr, peera->cdr);
12216 else if (peera->cdr)
12217 peerb->cdr = peera->cdr;
12218 peera->cdr = NULL;
12220 if (peerb->cdr && peerc->cdr)
12221 peerb->cdr = ast_cdr_append(peerb->cdr, peerc->cdr);
12222 else if (peerc->cdr)
12223 peerb->cdr = peerc->cdr;
12224 peerc->cdr = NULL;
12226 if (option_debug > 3)
12227 ast_log(LOG_DEBUG, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
12228 if (ast_channel_masquerade(peerb, peerc)) {
12229 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
12230 res = -1;
12231 } else
12232 ast_log(LOG_DEBUG, "SIP transfer: Succeeded to masquerade channels.\n");
12233 return res;
12234 } else {
12235 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
12236 if (transferer->chan1)
12237 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
12238 if (target->chan1)
12239 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
12240 return -1;
12242 return 0;
12245 /*! \brief Get tag from packet
12247 * \return Returns the pointer to the provided tag buffer,
12248 * or NULL if the tag was not found.
12250 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
12252 const char *thetag;
12254 if (!tagbuf)
12255 return NULL;
12256 tagbuf[0] = '\0'; /* reset the buffer */
12257 thetag = get_header(req, header);
12258 thetag = strcasestr(thetag, ";tag=");
12259 if (thetag) {
12260 thetag += 5;
12261 ast_copy_string(tagbuf, thetag, tagbufsize);
12262 return strsep(&tagbuf, ";");
12264 return NULL;
12267 /*! \brief Handle incoming notifications */
12268 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
12270 /* This is mostly a skeleton for future improvements */
12271 /* Mostly created to return proper answers on notifications on outbound REFER's */
12272 int res = 0;
12273 const char *event = get_header(req, "Event");
12274 char *eventid = NULL;
12275 char *sep;
12277 if( (sep = strchr(event, ';')) ) { /* XXX bug here - overwriting string ? */
12278 *sep++ = '\0';
12279 eventid = sep;
12282 if (option_debug > 1 && sipdebug)
12283 ast_log(LOG_DEBUG, "Got NOTIFY Event: %s\n", event);
12285 if (strcmp(event, "refer")) {
12286 /* We don't understand this event. */
12287 /* Here's room to implement incoming voicemail notifications :-) */
12288 transmit_response(p, "489 Bad event", req);
12289 if (!p->lastinvite)
12290 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12291 return -1;
12292 } else {
12293 /* Save nesting depth for now, since there might be other events we will
12294 support in the future */
12296 /* Handle REFER notifications */
12298 char buf[1024];
12299 char *cmd, *code;
12300 int respcode;
12301 int success = TRUE;
12303 /* EventID for each transfer... EventID is basically the REFER cseq
12305 We are getting notifications on a call that we transfered
12306 We should hangup when we are getting a 200 OK in a sipfrag
12307 Check if we have an owner of this event */
12309 /* Check the content type */
12310 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
12311 /* We need a sipfrag */
12312 transmit_response(p, "400 Bad request", req);
12313 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12314 return -1;
12317 /* Get the text of the attachment */
12318 if (get_msg_text(buf, sizeof(buf), req)) {
12319 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
12320 transmit_response(p, "400 Bad request", req);
12321 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12322 return -1;
12326 From the RFC...
12327 A minimal, but complete, implementation can respond with a single
12328 NOTIFY containing either the body:
12329 SIP/2.0 100 Trying
12331 if the subscription is pending, the body:
12332 SIP/2.0 200 OK
12333 if the reference was successful, the body:
12334 SIP/2.0 503 Service Unavailable
12335 if the reference failed, or the body:
12336 SIP/2.0 603 Declined
12338 if the REFER request was accepted before approval to follow the
12339 reference could be obtained and that approval was subsequently denied
12340 (see Section 2.4.7).
12342 If there are several REFERs in the same dialog, we need to
12343 match the ID of the event header...
12345 if (option_debug > 2)
12346 ast_log(LOG_DEBUG, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
12347 cmd = ast_skip_blanks(buf);
12348 code = cmd;
12349 /* We are at SIP/2.0 */
12350 while(*code && (*code > 32)) { /* Search white space */
12351 code++;
12353 *code++ = '\0';
12354 code = ast_skip_blanks(code);
12355 sep = code;
12356 sep++;
12357 while(*sep && (*sep > 32)) { /* Search white space */
12358 sep++;
12360 *sep++ = '\0'; /* Response string */
12361 respcode = atoi(code);
12362 switch (respcode) {
12363 case 100: /* Trying: */
12364 /* Don't do anything yet */
12365 break;
12366 case 183: /* Ringing: */
12367 /* Don't do anything yet */
12368 break;
12369 case 200: /* OK: The new call is up, hangup this call */
12370 /* Hangup the call that we are replacing */
12371 break;
12372 case 301: /* Moved permenantly */
12373 case 302: /* Moved temporarily */
12374 /* Do we get the header in the packet in this case? */
12375 success = FALSE;
12376 break;
12377 case 503: /* Service Unavailable: The new call failed */
12378 /* Cancel transfer, continue the call */
12379 success = FALSE;
12380 break;
12381 case 603: /* Declined: Not accepted */
12382 /* Cancel transfer, continue the current call */
12383 success = FALSE;
12384 break;
12386 if (!success) {
12387 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
12390 /* Confirm that we received this packet */
12391 transmit_response(p, "200 OK", req);
12392 return res;
12396 /*! \brief Handle incoming OPTIONS request */
12397 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
12399 int res;
12401 res = get_destination(p, req);
12402 build_contact(p);
12403 /* XXX Should we authenticate OPTIONS? XXX */
12404 if (ast_strlen_zero(p->context))
12405 ast_string_field_set(p, context, default_context);
12406 if (res < 0)
12407 transmit_response_with_allow(p, "404 Not Found", req, 0);
12408 else
12409 transmit_response_with_allow(p, "200 OK", req, 0);
12410 /* Destroy if this OPTIONS was the opening request, but not if
12411 it's in the middle of a normal call flow. */
12412 if (!p->lastinvite)
12413 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12415 return res;
12418 /*! \brief Handle the transfer part of INVITE with a replaces: header,
12419 meaning a target pickup or an attended transfer */
12420 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin)
12422 struct ast_frame *f;
12423 int earlyreplace = 0;
12424 int oneleggedreplace = 0; /* Call with no bridge, propably IVR or voice message */
12425 struct ast_channel *c = p->owner; /* Our incoming call */
12426 struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
12427 struct ast_channel *targetcall; /* The bridge to the take-over target */
12429 /* Check if we're in ring state */
12430 if (replacecall->_state == AST_STATE_RING)
12431 earlyreplace = 1;
12433 /* Check if we have a bridge */
12434 if (!(targetcall = ast_bridged_channel(replacecall))) {
12435 /* We have no bridge */
12436 if (!earlyreplace) {
12437 if (option_debug > 1)
12438 ast_log(LOG_DEBUG, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
12439 oneleggedreplace = 1;
12442 if (option_debug > 3 && targetcall && targetcall->_state == AST_STATE_RINGING)
12443 ast_log(LOG_DEBUG, "SIP transfer: Target channel is in ringing state\n");
12445 if (option_debug > 3) {
12446 if (targetcall)
12447 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);
12448 else
12449 ast_log(LOG_DEBUG, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
12452 if (ignore) {
12453 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
12454 /* We should answer something here. If we are here, the
12455 call we are replacing exists, so an accepted
12456 can't harm */
12457 transmit_response_with_sdp(p, "200 OK", req, 1);
12458 /* Do something more clever here */
12459 ast_channel_unlock(c);
12460 ast_mutex_unlock(&p->refer->refer_call->lock);
12461 return 1;
12463 if (!c) {
12464 /* What to do if no channel ??? */
12465 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
12466 transmit_response_with_sdp(p, "503 Service Unavailable", req, 1);
12467 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
12468 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12469 ast_mutex_unlock(&p->refer->refer_call->lock);
12470 return 1;
12472 append_history(p, "Xfer", "INVITE/Replace received");
12473 /* We have three channels to play with
12474 channel c: New incoming call
12475 targetcall: Call from PBX to target
12476 p->refer->refer_call: SIP pvt dialog from transferer to pbx.
12477 replacecall: The owner of the previous
12478 We need to masq C into refer_call to connect to
12479 targetcall;
12480 If we are talking to internal audio stream, target call is null.
12483 /* Fake call progress */
12484 transmit_response(p, "100 Trying", req);
12485 ast_setstate(c, AST_STATE_RING);
12487 /* Masquerade the new call into the referred call to connect to target call
12488 Targetcall is not touched by the masq */
12490 /* Answer the incoming call and set channel to UP state */
12491 transmit_response_with_sdp(p, "200 OK", req, 1);
12492 ast_setstate(c, AST_STATE_UP);
12494 /* Stop music on hold and other generators */
12495 ast_quiet_chan(replacecall);
12496 ast_quiet_chan(targetcall);
12497 if (option_debug > 3)
12498 ast_log(LOG_DEBUG, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
12499 /* Unlock clone, but not original (replacecall) */
12500 ast_channel_unlock(c);
12502 /* Unlock PVT */
12503 ast_mutex_unlock(&p->refer->refer_call->lock);
12505 /* Make sure that the masq does not free our PVT for the old call */
12506 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
12508 /* Prepare the masquerade - if this does not happen, we will be gone */
12509 if(ast_channel_masquerade(replacecall, c))
12510 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
12511 else if (option_debug > 3)
12512 ast_log(LOG_DEBUG, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
12514 /* The masquerade will happen as soon as someone reads a frame from the channel */
12516 /* C should now be in place of replacecall */
12517 /* ast_read needs to lock channel */
12518 ast_channel_unlock(c);
12520 if (earlyreplace || oneleggedreplace ) {
12521 /* Force the masq to happen */
12522 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
12523 ast_frfree(f);
12524 f = NULL;
12525 if (option_debug > 3)
12526 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from RING channel!\n");
12527 } else {
12528 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from RING channel \n");
12530 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
12531 ast_channel_unlock(replacecall);
12532 } else { /* Bridged call, UP channel */
12533 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
12534 /* Masq ok */
12535 ast_frfree(f);
12536 f = NULL;
12537 if (option_debug > 2)
12538 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from channel! Masq done.\n");
12539 } else {
12540 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from channel. Transfer failed\n");
12542 ast_channel_unlock(replacecall);
12544 ast_mutex_unlock(&p->refer->refer_call->lock);
12546 ast_setstate(c, AST_STATE_DOWN);
12547 if (option_debug > 3) {
12548 struct ast_channel *test;
12549 ast_log(LOG_DEBUG, "After transfer:----------------------------\n");
12550 ast_log(LOG_DEBUG, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
12551 if (replacecall)
12552 ast_log(LOG_DEBUG, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
12553 if (p->owner) {
12554 ast_log(LOG_DEBUG, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
12555 test = ast_bridged_channel(p->owner);
12556 if (test)
12557 ast_log(LOG_DEBUG, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
12558 else
12559 ast_log(LOG_DEBUG, " -- No call bridged to C->owner \n");
12560 } else
12561 ast_log(LOG_DEBUG, " -- No channel yet \n");
12562 ast_log(LOG_DEBUG, "End After transfer:----------------------------\n");
12565 ast_channel_unlock(p->owner); /* Unlock new owner */
12566 ast_mutex_unlock(&p->lock); /* Unlock SIP structure */
12568 /* The call should be down with no ast_channel, so hang it up */
12569 c->tech_pvt = NULL;
12570 ast_hangup(c);
12571 return 0;
12575 /*! \brief Handle incoming INVITE request
12576 \note If the INVITE has a Replaces header, it is part of an
12577 * attended transfer. If so, we do not go through the dial
12578 * plan but tries to find the active call and masquerade
12579 * into it
12581 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)
12583 int res = 1;
12584 int gotdest;
12585 const char *p_replaces;
12586 char *replace_id = NULL;
12587 const char *required;
12588 unsigned int required_profile = 0;
12589 struct ast_channel *c = NULL; /* New channel */
12591 /* Find out what they support */
12592 if (!p->sipoptions) {
12593 const char *supported = get_header(req, "Supported");
12594 if (supported)
12595 parse_sip_options(p, supported);
12598 /* Find out what they require */
12599 required = get_header(req, "Require");
12600 if (required && !ast_strlen_zero(required)) {
12601 required_profile = parse_sip_options(NULL, required);
12602 if (required_profile && required_profile != SIP_OPT_REPLACES) {
12603 /* At this point we only support REPLACES */
12604 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
12605 ast_log(LOG_WARNING,"Received SIP INVITE with unsupported required extension: %s\n", required);
12606 if (!p->lastinvite)
12607 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12608 return -1;
12612 /* Check if this is a loop */
12613 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->owner->_state != AST_STATE_UP)) {
12614 /* This is a call to ourself. Send ourselves an error code and stop
12615 processing immediately, as SIP really has no good mechanism for
12616 being able to call yourself */
12617 /* If pedantic is on, we need to check the tags. If they're different, this is
12618 in fact a forked call through a SIP proxy somewhere. */
12619 transmit_response(p, "482 Loop Detected", req);
12620 /* We do NOT destroy p here, so that our response will be accepted */
12621 return 0;
12624 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->pendinginvite) {
12625 /* We already have a pending invite. Sorry. You are on hold. */
12626 transmit_response(p, "491 Request Pending", req);
12627 if (option_debug)
12628 ast_log(LOG_DEBUG, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
12629 return 0;
12632 if ((p_replaces = get_header(req, "Replaces")) && !ast_strlen_zero(p_replaces)) {
12633 /* We have a replaces header */
12634 char *ptr;
12635 char *fromtag = NULL;
12636 char *totag = NULL;
12637 char *start, *to;
12638 int error = 0;
12640 if (p->owner) {
12641 if (option_debug > 2)
12642 ast_log(LOG_DEBUG, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
12643 transmit_response(p, "400 Bad request", req); /* The best way to not not accept the transfer */
12644 /* Do not destroy existing call */
12645 return -1;
12648 if (sipdebug && option_debug > 2)
12649 ast_log(LOG_DEBUG, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
12650 /* Create a buffer we can manipulate */
12651 replace_id = ast_strdupa(p_replaces);
12652 ast_uri_decode(replace_id);
12654 if (!p->refer && !sip_refer_allocate(p)) {
12655 transmit_response(p, "500 Server Internal Error", req);
12656 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
12657 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12658 return -1;
12661 /* Todo: (When we find phones that support this)
12662 if the replaces header contains ";early-only"
12663 we can only replace the call in early
12664 stage, not after it's up.
12666 If it's not in early mode, 486 Busy.
12669 /* Skip leading whitespace */
12670 replace_id = ast_skip_blanks(replace_id);
12672 start = replace_id;
12673 while ( (ptr = strsep(&start, ";")) ) {
12674 ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
12675 if ( (to = strcasestr(ptr, "to-tag=") ) )
12676 totag = to + 7; /* skip the keyword */
12677 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
12678 fromtag = to + 9; /* skip the keyword */
12679 fromtag = strsep(&fromtag, "&"); /* trim what ? */
12683 if (sipdebug && option_debug > 3)
12684 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>");
12687 /* Try to find call that we are replacing
12688 If we have a Replaces header, we need to cancel that call if we succeed with this call
12690 if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
12691 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
12692 transmit_response(p, "481 Call Leg Does Not Exist (Replaces)", req);
12693 error = 1;
12696 /* At this point, bot the pvt and the owner of the call to be replaced is locked */
12698 /* The matched call is the call from the transferer to Asterisk .
12699 We want to bridge the bridged part of the call to the
12700 incoming invite, thus taking over the refered call */
12702 if (p->refer->refer_call == p) {
12703 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
12704 p->refer->refer_call = NULL;
12705 transmit_response(p, "400 Bad request", req); /* The best way to not not accept the transfer */
12706 error = 1;
12709 if (!error && !p->refer->refer_call->owner) {
12710 /* Oops, someting wrong anyway, no owner, no call */
12711 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
12712 /* Check for better return code */
12713 transmit_response(p, "481 Call Leg Does Not Exist (Replace)", req);
12714 error = 1;
12717 if (!error && p->refer->refer_call->owner->_state != AST_STATE_RING && p->refer->refer_call->owner->_state != AST_STATE_UP ) {
12718 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
12719 transmit_response(p, "603 Declined (Replaces)", req);
12720 error = 1;
12723 if (error) { /* Give up this dialog */
12724 append_history(p, "Xfer", "INVITE/Replace Failed.");
12725 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12726 ast_mutex_unlock(&p->lock);
12727 if (p->refer->refer_call) {
12728 ast_mutex_unlock(&p->refer->refer_call->lock);
12729 ast_channel_unlock(p->refer->refer_call->owner);
12731 return -1;
12736 /* Check if this is an INVITE that sets up a new dialog or
12737 a re-invite in an existing dialog */
12739 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
12740 sip_cancel_destroy(p);
12741 /* This also counts as a pending invite */
12742 p->pendinginvite = seqno;
12743 check_via(p, req);
12745 if (!p->owner) { /* Not a re-invite */
12746 /* Use this as the basis */
12747 copy_request(&p->initreq, req);
12748 if (debug)
12749 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
12750 append_history(p, "Invite", "New call: %s", p->callid);
12751 parse_ok_contact(p, req);
12752 } else { /* Re-invite on existing call */
12753 /* Handle SDP here if we already have an owner */
12754 if (find_sdp(req)) {
12755 if (process_sdp(p, req)) {
12756 transmit_response(p, "488 Not acceptable here", req);
12757 if (!p->lastinvite)
12758 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12759 return -1;
12761 } else {
12762 p->jointcapability = p->capability;
12763 ast_log(LOG_DEBUG, "Hm.... No sdp for the moment\n");
12765 if (recordhistory) /* This is a response, note what it was for */
12766 append_history(p, "ReInv", "Re-invite received");
12768 } else if (debug)
12769 ast_verbose("Ignoring this INVITE request\n");
12772 if (!p->lastinvite && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner) {
12773 /* This is a new invite */
12774 /* Handle authentication if this is our first invite */
12775 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
12776 if (res == AUTH_CHALLENGE_SENT)
12777 return 0;
12778 if (res < 0) { /* Something failed in authentication */
12779 if (res == AUTH_FAKE_AUTH) {
12780 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
12781 transmit_fake_auth_response(p, req, 1);
12782 } else {
12783 ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
12784 transmit_response_reliable(p, "403 Forbidden", req);
12786 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12787 ast_string_field_free(p, theirtag);
12788 return 0;
12791 /* We have a succesful authentication, process the SDP portion if there is one */
12792 if (find_sdp(req)) {
12793 if (process_sdp(p, req)) {
12794 /* Unacceptable codecs */
12795 transmit_response_reliable(p, "488 Not acceptable here", req);
12796 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12797 if (option_debug)
12798 ast_log(LOG_DEBUG, "No compatible codecs for this SIP call.\n");
12799 return -1;
12801 } else { /* No SDP in invite, call control session */
12802 p->jointcapability = p->capability;
12803 if (option_debug > 1)
12804 ast_log(LOG_DEBUG, "No SDP in Invite, third party call control\n");
12807 /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
12808 /* This seems redundant ... see !p-owner above */
12809 if (p->owner)
12810 ast_queue_frame(p->owner, &ast_null_frame);
12813 /* Initialize the context if it hasn't been already */
12814 if (ast_strlen_zero(p->context))
12815 ast_string_field_set(p, context, default_context);
12818 /* Check number of concurrent calls -vs- incoming limit HERE */
12819 if (option_debug)
12820 ast_log(LOG_DEBUG, "Checking SIP call limits for device %s\n", p->username);
12821 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
12822 if (res < 0) {
12823 ast_log(LOG_NOTICE, "Failed to place call for user %s, too many calls\n", p->username);
12824 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
12825 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12827 return 0;
12829 gotdest = get_destination(p, NULL); /* Get destination right away */
12830 get_rdnis(p, NULL); /* Get redirect information */
12831 extract_uri(p, req); /* Get the Contact URI */
12832 build_contact(p); /* Build our contact header */
12833 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_INFO);
12835 if (!replace_id && gotdest) { /* No matching extension found */
12836 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
12837 transmit_response_reliable(p, "484 Address Incomplete", req);
12838 update_call_counter(p, DEC_CALL_LIMIT);
12839 } else {
12840 transmit_response_reliable(p, "404 Not Found", req);
12841 update_call_counter(p, DEC_CALL_LIMIT);
12843 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12844 } else {
12845 /* If no extension was specified, use the s one */
12846 /* Basically for calling to IP/Host name only */
12847 if (ast_strlen_zero(p->exten))
12848 ast_string_field_set(p, exten, "s");
12849 /* Initialize our tag */
12851 make_our_tag(p->tag, sizeof(p->tag));
12853 /* First invitation - create the channel */
12854 c = sip_new(p, AST_STATE_DOWN, S_OR(p->username, NULL));
12855 *recount = 1;
12857 /* Save Record-Route for any later requests we make on this dialogue */
12858 build_route(p, req, 0);
12860 if (c) {
12861 /* Pre-lock the call */
12862 ast_channel_lock(c);
12865 } else {
12866 if (option_debug > 1 && sipdebug) {
12867 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12868 ast_log(LOG_DEBUG, "Got a SIP re-invite for call %s\n", p->callid);
12869 else
12870 ast_log(LOG_DEBUG, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
12872 c = p->owner;
12875 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
12876 p->lastinvite = seqno;
12878 if (replace_id) { /* Attended transfer or call pickup - we're the target */
12879 /* Go and take over the target call */
12880 if (sipdebug && option_debug > 3)
12881 ast_log(LOG_DEBUG, "Sending this call to the invite/replcaes handler %s\n", p->callid);
12882 return handle_invite_replaces(p, req, debug, ast_test_flag(req, SIP_PKT_IGNORE), seqno, sin);
12886 if (c) { /* We have a call -either a new call or an old one (RE-INVITE) */
12887 switch(c->_state) {
12888 case AST_STATE_DOWN:
12889 if (option_debug > 1)
12890 ast_log(LOG_DEBUG, "%s: New call is still down.... Trying... \n", c->name);
12891 transmit_response(p, "100 Trying", req);
12892 ast_setstate(c, AST_STATE_RING);
12893 if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
12894 enum ast_pbx_result res;
12896 res = ast_pbx_start(c);
12898 switch(res) {
12899 case AST_PBX_FAILED:
12900 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
12901 if (ast_test_flag(req, SIP_PKT_IGNORE))
12902 transmit_response(p, "503 Unavailable", req);
12903 else
12904 transmit_response_reliable(p, "503 Unavailable", req);
12905 break;
12906 case AST_PBX_CALL_LIMIT:
12907 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
12908 if (ast_test_flag(req, SIP_PKT_IGNORE))
12909 transmit_response(p, "480 Temporarily Unavailable", req);
12910 else
12911 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
12912 break;
12913 case AST_PBX_SUCCESS:
12914 /* nothing to do */
12915 break;
12918 if (res) {
12920 /* Unlock locks so ast_hangup can do its magic */
12921 ast_mutex_unlock(&c->lock);
12922 ast_mutex_unlock(&p->lock);
12923 ast_hangup(c);
12924 ast_mutex_lock(&p->lock);
12925 c = NULL;
12927 } else { /* Pickup call in call group */
12928 ast_channel_unlock(c);
12929 if (ast_pickup_call(c)) {
12930 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
12931 if (ast_test_flag(req, SIP_PKT_IGNORE))
12932 transmit_response(p, "503 Unavailable", req); /* OEJ - Right answer? */
12933 else
12934 transmit_response_reliable(p, "503 Unavailable", req);
12935 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
12936 /* Unlock locks so ast_hangup can do its magic */
12937 ast_mutex_unlock(&p->lock);
12938 c->hangupcause = AST_CAUSE_CALL_REJECTED;
12939 } else {
12940 ast_mutex_unlock(&p->lock);
12941 ast_setstate(c, AST_STATE_DOWN);
12942 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
12944 ast_hangup(c);
12945 ast_mutex_lock(&p->lock);
12946 c = NULL;
12948 break;
12949 case AST_STATE_RING:
12950 transmit_response(p, "100 Trying", req);
12951 break;
12952 case AST_STATE_RINGING:
12953 transmit_response(p, "180 Ringing", req);
12954 break;
12955 case AST_STATE_UP:
12956 if (option_debug > 1)
12957 ast_log(LOG_DEBUG, "%s: This call is UP.... \n", c->name);
12959 if (p->t38.state == T38_PEER_REINVITE) {
12960 struct ast_channel *bridgepeer = NULL;
12961 struct sip_pvt *bridgepvt = NULL;
12963 if ((bridgepeer = ast_bridged_channel(p->owner))) {
12964 /* 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*/
12965 /*! XXX: we should also check here does the other side supports t38 at all !!! XXX */
12966 if (!strcasecmp(bridgepeer->tech->type, "SIP")) { /* If we are bridged to SIP channel */
12967 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
12968 if (bridgepvt->t38.state == T38_DISABLED) {
12969 if (bridgepvt->udptl) { /* If everything is OK with other side's udptl struct */
12970 /* Send re-invite to the bridged channel */
12971 sip_handle_t38_reinvite(bridgepeer, p, 1);
12972 } else { /* Something is wrong with peers udptl struct */
12973 ast_log(LOG_WARNING, "Strange... The other side of the bridge don't have udptl struct\n");
12974 ast_mutex_lock(&bridgepvt->lock);
12975 bridgepvt->t38.state = T38_DISABLED;
12976 ast_mutex_unlock(&bridgepvt->lock);
12977 if (option_debug > 1)
12978 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->name);
12979 if (ast_test_flag(req, SIP_PKT_IGNORE))
12980 transmit_response(p, "488 Not acceptable here", req);
12981 else
12982 transmit_response_reliable(p, "488 Not acceptable here", req);
12983 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12986 } else {
12987 /* Other side is not a SIP channel */
12988 if (ast_test_flag(req, SIP_PKT_IGNORE))
12989 transmit_response(p, "488 Not acceptable here", req);
12990 else
12991 transmit_response_reliable(p, "488 Not acceptable here", req);
12992 p->t38.state = T38_DISABLED;
12993 if (option_debug > 1)
12994 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12995 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12997 } else {
12998 /* we are not bridged in a call */
12999 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
13000 p->t38.state = T38_ENABLED;
13001 if (option_debug)
13002 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
13004 } else if (p->t38.state == T38_DISABLED) { /* Channel doesn't have T38 offered or enabled */
13005 int sendok = TRUE;
13007 /* If we are bridged to a channel that has T38 enabled than this is a case of RTP re-invite after T38 session */
13008 /* so handle it here (re-invite other party to RTP) */
13009 struct ast_channel *bridgepeer = NULL;
13010 struct sip_pvt *bridgepvt = NULL;
13011 if ((bridgepeer = ast_bridged_channel(p->owner))) {
13012 if (!strcasecmp(bridgepeer->tech->type, sip_tech.type)) {
13013 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
13014 /* Does the bridged peer have T38 ? */
13015 if (bridgepvt->t38.state == T38_ENABLED) {
13016 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
13017 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
13018 if (ast_test_flag(req, SIP_PKT_IGNORE))
13019 transmit_response(p, "488 Not Acceptable Here (unsupported)", req);
13020 else
13021 transmit_response_reliable(p, "488 Not Acceptable Here (unsupported)", req);
13022 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13023 sendok = FALSE;
13025 /* No bridged peer with T38 enabled*/
13028 if (sendok)
13029 transmit_response_with_sdp(p, "200 OK", req, XMIT_CRITICAL);
13032 break;
13033 default:
13034 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
13035 transmit_response(p, "100 Trying", req);
13036 break;
13038 } else {
13039 if (p && !ast_test_flag(&p->flags[0], SIP_NEEDDESTROY)) {
13040 const char *msg;
13042 if (!p->jointcapability)
13043 msg = "488 Not Acceptable Here (codec error)";
13044 else {
13045 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
13046 msg = "503 Unavailable";
13048 if (ast_test_flag(req, SIP_PKT_IGNORE))
13049 transmit_response(p, msg, req);
13050 else
13051 transmit_response_reliable(p, msg, req);
13052 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13055 return res;
13058 /*! \brief Find all call legs and bridge transferee with target
13059 * called from handle_request_refer */
13060 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
13062 struct sip_dual target; /* Chan 1: Call from tranferer to Asterisk */
13063 /* Chan 2: Call from Asterisk to target */
13064 int res = 0;
13065 struct sip_pvt *targetcall_pvt;
13066 int error = 0;
13068 /* Check if the call ID of the replaces header does exist locally */
13069 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
13070 transferer->refer->replaces_callid_fromtag))) {
13071 if (transferer->refer->localtransfer) {
13072 /* We did not find the refered call. Sorry, can't accept then */
13073 transmit_response(transferer, "202 Accepted", req);
13074 /* Let's fake a response from someone else in order
13075 to follow the standard */
13076 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
13077 append_history(transferer, "Xfer", "Refer failed");
13078 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
13079 transferer->refer->status = REFER_FAILED;
13080 return -1;
13082 /* Fall through for remote transfers that we did not find locally */
13083 if (option_debug > 2)
13084 ast_log(LOG_DEBUG, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
13085 return 0;
13088 /* Ok, we can accept this transfer */
13089 transmit_response(transferer, "202 Accepted", req);
13090 append_history(transferer, "Xfer", "Refer accepted");
13091 if (!targetcall_pvt->owner) { /* No active channel */
13092 if (option_debug > 3)
13093 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No owner of target call\n");
13094 error = 1;
13096 /* We have a channel, find the bridge */
13097 target.chan1 = targetcall_pvt->owner; /* Transferer to Asterisk */
13099 if (!error) {
13100 target.chan2 = ast_bridged_channel(targetcall_pvt->owner); /* Asterisk to target */
13102 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
13103 /* Wrong state of new channel */
13104 if (option_debug > 3) {
13105 if (target.chan2)
13106 ast_log(LOG_DEBUG, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
13107 else if (target.chan1->_state != AST_STATE_RING)
13108 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No target channel\n");
13109 else
13110 ast_log(LOG_DEBUG, "SIP attended transfer: Attempting transfer in ringing state\n");
13112 if (target.chan1->_state != AST_STATE_RING)
13113 error = 1;
13116 if (error) { /* Cancel transfer */
13117 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
13118 append_history(transferer, "Xfer", "Refer failed");
13119 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
13120 transferer->refer->status = REFER_FAILED;
13121 ast_mutex_unlock(&targetcall_pvt->lock);
13122 ast_channel_unlock(current->chan1);
13123 ast_channel_unlock(target.chan1);
13124 return -1;
13127 /* Transfer */
13128 if (option_debug > 3 && sipdebug) {
13129 if (current->chan2) /* We have two bridges */
13130 ast_log(LOG_DEBUG, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
13131 else /* One bridge, propably transfer of IVR/voicemail etc */
13132 ast_log(LOG_DEBUG, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
13135 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
13137 /* Perform the transfer */
13138 res = attempt_transfer(current, &target);
13139 ast_mutex_unlock(&targetcall_pvt->lock);
13140 if (res) {
13141 /* Failed transfer */
13142 /* Could find better message, but they will get the point */
13143 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy", TRUE);
13144 append_history(transferer, "Xfer", "Refer failed");
13145 if (targetcall_pvt->owner)
13146 ast_channel_unlock(targetcall_pvt->owner);
13147 /* Right now, we have to hangup, sorry. Bridge is destroyed */
13148 ast_hangup(transferer->owner);
13149 } else {
13150 /* Transfer succeeded! */
13152 /* Tell transferer that we're done. */
13153 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
13154 append_history(transferer, "Xfer", "Refer succeeded");
13155 transferer->refer->status = REFER_200OK;
13156 if (targetcall_pvt->owner) {
13157 ast_log(LOG_DEBUG, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
13158 ast_channel_unlock(targetcall_pvt->owner);
13161 return 1;
13165 /*! \brief Handle incoming REFER request */
13166 /*! \page SIP_REFER SIP transfer Support (REFER)
13168 REFER is used for call transfer in SIP. We get a REFER
13169 to place a new call with an INVITE somwhere and then
13170 keep the transferor up-to-date of the transfer. If the
13171 transfer fails, get back on line with the orginal call.
13173 - REFER can be sent outside or inside of a dialog.
13174 Asterisk only accepts REFER inside of a dialog.
13176 - If we get a replaces header, it is an attended transfer
13178 \par Blind transfers
13179 The transferor provides the transferee
13180 with the transfer targets contact. The signalling between
13181 transferer or transferee should not be cancelled, so the
13182 call is recoverable if the transfer target can not be reached
13183 by the transferee.
13185 In this case, Asterisk receives a TRANSFER from
13186 the transferor, thus is the transferee. We should
13187 try to set up a call to the contact provided
13188 and if that fails, re-connect the current session.
13189 If the new call is set up, we issue a hangup.
13190 In this scenario, we are following section 5.2
13191 in the SIP CC Transfer draft. (Transfer without
13192 a GRUU)
13194 \par Transfer with consultation hold
13195 In this case, the transferor
13196 talks to the transfer target before the transfer takes place.
13197 This is implemented with SIP hold and transfer.
13198 Note: The invite From: string could indicate a transfer.
13199 (Section 6. Transfer with consultation hold)
13200 The transferor places the transferee on hold, starts a call
13201 with the transfer target to alert them to the impending
13202 transfer, terminates the connection with the target, then
13203 proceeds with the transfer (as in Blind transfer above)
13205 \par Attended transfer
13206 The transferor places the transferee
13207 on hold, calls the transfer target to alert them,
13208 places the target on hold, then proceeds with the transfer
13209 using a Replaces header field in the Refer-to header. This
13210 will force the transfee to send an Invite to the target,
13211 with a replaces header that instructs the target to
13212 hangup the call between the transferor and the target.
13213 In this case, the Refer/to: uses the AOR address. (The same
13214 URI that the transferee used to establish the session with
13215 the transfer target (To: ). The Require: replaces header should
13216 be in the INVITE to avoid the wrong UA in a forked SIP proxy
13217 scenario to answer and have no call to replace with.
13219 The referred-by header is *NOT* required, but if we get it,
13220 can be copied into the INVITE to the transfer target to
13221 inform the target about the transferor
13223 "Any REFER request has to be appropriately authenticated.".
13225 We can't destroy dialogs, since we want the call to continue.
13228 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock)
13230 struct sip_dual current; /* Chan1: Call between asterisk and transferer */
13231 /* Chan2: Call between asterisk and transferee */
13233 int res = 0;
13235 if (ast_test_flag(req, SIP_PKT_DEBUG))
13236 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");
13238 if (!p->owner) {
13239 /* This is a REFER outside of an existing SIP dialog */
13240 /* We can't handle that, so decline it */
13241 if (option_debug > 2)
13242 ast_log(LOG_DEBUG, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
13243 transmit_response(p, "603 Declined (No dialog)", req);
13244 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
13245 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
13246 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
13247 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13249 return 0;
13253 /* Check if transfer is allowed from this device */
13254 if (p->allowtransfer == TRANSFER_CLOSED ) {
13255 /* Transfer not allowed, decline */
13256 transmit_response(p, "603 Declined (policy)", req);
13257 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
13258 /* Do not destroy SIP session */
13259 return 0;
13262 if(!ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
13263 /* Already have a pending REFER */
13264 transmit_response(p, "491 Request pending", req);
13265 append_history(p, "Xfer", "Refer failed. Request pending.");
13266 return 0;
13269 /* Allocate memory for call transfer data */
13270 if (!p->refer && !sip_refer_allocate(p)) {
13271 transmit_response(p, "500 Internal Server Error", req);
13272 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
13273 return -3;
13276 res = get_refer_info(p, req); /* Extract headers */
13278 p->refer->status = REFER_SENT;
13280 if (res != 0) {
13281 switch (res) {
13282 case -2: /* Syntax error */
13283 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
13284 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
13285 if (ast_test_flag(req, SIP_PKT_DEBUG))
13286 ast_log(LOG_DEBUG, "SIP transfer to black hole can't be handled (no refer-to: )\n");
13287 break;
13288 case -3:
13289 transmit_response(p, "603 Declined (Non sip: uri)", req);
13290 append_history(p, "Xfer", "Refer failed. Non SIP uri");
13291 if (ast_test_flag(req, SIP_PKT_DEBUG))
13292 ast_log(LOG_DEBUG, "SIP transfer to non-SIP uri denied\n");
13293 break;
13294 default:
13295 /* Refer-to extension not found, fake a failed transfer */
13296 transmit_response(p, "202 Accepted", req);
13297 append_history(p, "Xfer", "Refer failed. Bad extension.");
13298 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
13299 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
13300 if (ast_test_flag(req, SIP_PKT_DEBUG))
13301 ast_log(LOG_DEBUG, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
13302 break;
13304 return 0;
13306 if (ast_strlen_zero(p->context))
13307 ast_string_field_set(p, context, default_context);
13309 /* If we do not support SIP domains, all transfers are local */
13310 if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
13311 p->refer->localtransfer = 1;
13312 if (sipdebug && option_debug > 2)
13313 ast_log(LOG_DEBUG, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
13314 } else if (AST_LIST_EMPTY(&domain_list)) {
13315 /* This PBX don't bother with SIP domains, so all transfers are local */
13316 p->refer->localtransfer = 1;
13317 } else
13318 if (sipdebug && option_debug > 2)
13319 ast_log(LOG_DEBUG, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
13321 /* Is this a repeat of a current request? Ignore it */
13322 /* Don't know what else to do right now. */
13323 if (ignore)
13324 return res;
13326 /* If this is a blind transfer, we have the following
13327 channels to work with:
13328 - chan1, chan2: The current call between transferer and transferee (2 channels)
13329 - target_channel: A new call from the transferee to the target (1 channel)
13330 We need to stay tuned to what happens in order to be able
13331 to bring back the call to the transferer */
13333 /* If this is a attended transfer, we should have all call legs within reach:
13334 - chan1, chan2: The call between the transferer and transferee (2 channels)
13335 - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
13336 We want to bridge chan2 with targetcall_pvt!
13338 The replaces call id in the refer message points
13339 to the call leg between Asterisk and the transferer.
13340 So we need to connect the target and the transferee channel
13341 and hangup the two other channels silently
13343 If the target is non-local, the call ID could be on a remote
13344 machine and we need to send an INVITE with replaces to the
13345 target. We basically handle this as a blind transfer
13346 and let the sip_call function catch that we need replaces
13347 header in the INVITE.
13351 /* Get the transferer's channel */
13352 current.chan1 = p->owner;
13354 /* Find the other part of the bridge (2) - transferee */
13355 current.chan2 = ast_bridged_channel(current.chan1);
13357 if (sipdebug && option_debug > 2)
13358 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>");
13360 if (!current.chan2 && !p->refer->attendedtransfer) {
13361 /* No bridged channel, propably IVR or echo or similar... */
13362 /* Guess we should masquerade or something here */
13363 /* Until we figure it out, refuse transfer of such calls */
13364 if (sipdebug && option_debug > 2)
13365 ast_log(LOG_DEBUG,"Refused SIP transfer on non-bridged channel.\n");
13366 p->refer->status = REFER_FAILED;
13367 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
13368 transmit_response(p, "603 Declined", req);
13369 return -1;
13372 if (current.chan2) {
13373 if (sipdebug && option_debug > 3)
13374 ast_log(LOG_DEBUG, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
13376 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
13379 ast_set_flag(&p->flags[0], SIP_GOTREFER);
13381 /* Attended transfer: Find all call legs and bridge transferee with target*/
13382 if (p->refer->attendedtransfer) {
13383 if ((res = local_attended_transfer(p, &current, req, seqno)))
13384 return res; /* We're done with the transfer */
13385 /* Fall through for remote transfers that we did not find locally */
13386 if (sipdebug && option_debug > 3)
13387 ast_log(LOG_DEBUG, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
13388 /* Fallthrough if we can't find the call leg internally */
13392 /* Parking a call */
13393 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
13394 /* Must release c's lock now, because it will not longer be accessible after the transfer! */
13395 *nounlock = 1;
13396 ast_channel_unlock(current.chan1);
13397 copy_request(&current.req, req);
13398 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
13399 p->refer->status = REFER_200OK;
13400 append_history(p, "Xfer", "REFER to call parking.");
13401 if (sipdebug && option_debug > 3)
13402 ast_log(LOG_DEBUG, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
13403 sip_park(current.chan2, current.chan1, req, seqno);
13404 return res;
13407 /* Blind transfers and remote attended xfers */
13408 transmit_response(p, "202 Accepted", req);
13410 if (current.chan1 && current.chan2) {
13411 if (option_debug > 2)
13412 ast_log(LOG_DEBUG, "chan1->name: %s\n", current.chan1->name);
13413 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
13415 if (current.chan2) {
13416 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
13417 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
13418 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
13419 /* One for the new channel */
13420 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
13421 if (p->refer->referred_by)
13422 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
13423 if (p->refer->referred_by)
13424 /* Attended transfer to remote host, prepare headers for the INVITE */
13425 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
13427 /* Generate an URI-encoded string */
13428 if (p->refer->replaces_callid && !ast_strlen_zero(p->refer->replaces_callid)) {
13429 char tempheader[BUFSIZ];
13430 char tempheader2[BUFSIZ];
13431 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
13432 p->refer->replaces_callid_totag ? ";to-tag=" : "",
13433 p->refer->replaces_callid_totag,
13434 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
13435 p->refer->replaces_callid_fromtag);
13437 /* Convert it to URL encoding, also convert reserved strings */
13438 ast_uri_encode(tempheader, tempheader2, sizeof(tempheader2), 1);
13440 if (current.chan2)
13441 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader2);
13443 /* Must release lock now, because it will not longer
13444 be accessible after the transfer! */
13445 *nounlock = 1;
13446 ast_channel_unlock(current.chan1);
13447 ast_channel_unlock(current.chan2);
13449 /* Connect the call */
13451 /* FAKE ringing if not attended transfer */
13452 if (!p->refer->attendedtransfer)
13453 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
13455 /* For blind transfer, this will lead to a new call */
13456 /* For attended transfer to remote host, this will lead to
13457 a new SIP call with a replaces header, if the dial plan allows it
13459 if (!current.chan2) {
13460 /* We have no bridge, so we're talking with Asterisk somehow */
13461 /* We need to masquerade this call */
13462 /* What to do to fix this situation:
13463 * Set up the new call in a new channel
13464 * Let the new channel masq into this channel
13465 Please add that code here :-)
13467 transmit_response(p, "202 Accepted", req);
13468 p->refer->status = REFER_FAILED;
13469 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
13470 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
13471 append_history(p, "Xfer", "Refer failed (only bridged calls).");
13472 return -1;
13474 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
13476 /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
13477 servers - generate an INVITE with Replaces. Either way, let the dial plan decided */
13478 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
13480 if (!res) {
13481 /* Success - we have a new channel */
13482 if (option_debug > 2)
13483 ast_log(LOG_DEBUG, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
13484 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
13485 if (p->refer->localtransfer)
13486 p->refer->status = REFER_200OK;
13487 if (p->owner)
13488 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
13489 append_history(p, "Xfer", "Refer succeeded.");
13490 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
13491 /* Do not hangup call, the other side do that when we say 200 OK */
13492 /* We could possibly implement a timer here, auto congestion */
13493 res = 0;
13494 } else {
13495 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
13496 if (option_debug > 2)
13497 ast_log(LOG_DEBUG, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
13498 append_history(p, "Xfer", "Refer failed.");
13499 /* Failure of some kind */
13500 p->refer->status = REFER_FAILED;
13501 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
13502 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
13503 res = -1;
13505 return res;
13508 /*! \brief Handle incoming CANCEL request */
13509 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
13512 check_via(p, req);
13513 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
13515 if (p->owner && p->owner->_state == AST_STATE_UP) {
13516 /* This call is up, cancel is ignored, we need a bye */
13517 transmit_response(p, "200 OK", req);
13518 if (option_debug)
13519 ast_log(LOG_DEBUG, "Got CANCEL on an answered call. Ignoring... \n");
13520 return 0;
13522 if (p->rtp) {
13523 /* Immediately stop RTP */
13524 ast_rtp_stop(p->rtp);
13526 if (p->vrtp) {
13527 /* Immediately stop VRTP */
13528 ast_rtp_stop(p->vrtp);
13530 if (p->udptl) {
13531 /* Immediately stop UDPTL */
13532 ast_udptl_stop(p->udptl);
13534 if (p->owner)
13535 ast_queue_hangup(p->owner);
13536 else
13537 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13538 if (p->initreq.len > 0) {
13539 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
13540 transmit_response(p, "200 OK", req);
13541 return 1;
13542 } else {
13543 transmit_response(p, "481 Call Leg Does Not Exist", req);
13544 return 0;
13548 /*! \brief Handle incoming BYE request */
13549 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
13551 struct ast_channel *c=NULL;
13552 int res;
13553 struct ast_channel *bridged_to;
13554 char *audioqos = NULL, *videoqos = NULL;
13556 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_test_flag(req, SIP_PKT_IGNORE))
13557 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
13559 copy_request(&p->initreq, req);
13560 check_via(p, req);
13561 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
13563 if (p->rtp)
13564 audioqos = ast_rtp_get_quality(p->rtp);
13565 if (p->vrtp)
13566 videoqos = ast_rtp_get_quality(p->vrtp);
13568 /* Get RTCP quality before end of call */
13569 if (recordhistory) {
13570 if (p->rtp)
13571 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
13572 if (p->vrtp)
13573 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
13576 if (p->rtp) {
13577 if (p->owner)
13578 pbx_builtin_setvar_helper(p->owner, "RTPAUDIOQOS", audioqos);
13579 /* Immediately stop RTP */
13580 ast_rtp_stop(p->rtp);
13582 if (p->vrtp) {
13583 if (p->owner)
13584 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
13585 /* Immediately stop VRTP */
13586 ast_rtp_stop(p->vrtp);
13588 if (p->udptl) {
13589 /* Immediately stop UDPTL */
13590 ast_udptl_stop(p->udptl);
13592 if (!ast_strlen_zero(get_header(req, "Also"))) {
13593 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
13594 ast_inet_ntoa(p->recv.sin_addr));
13595 if (ast_strlen_zero(p->context))
13596 ast_string_field_set(p, context, default_context);
13597 res = get_also_info(p, req);
13598 if (!res) {
13599 c = p->owner;
13600 if (c) {
13601 bridged_to = ast_bridged_channel(c);
13602 if (bridged_to) {
13603 /* Don't actually hangup here... */
13604 ast_queue_control(c, AST_CONTROL_UNHOLD);
13605 ast_async_goto(bridged_to, p->context, p->refer->refer_to,1);
13606 } else
13607 ast_queue_hangup(p->owner);
13609 } else {
13610 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
13611 if (p->owner)
13612 ast_queue_hangup(p->owner);
13614 } else if (p->owner)
13615 ast_queue_hangup(p->owner);
13616 else
13617 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13618 transmit_response(p, "200 OK", req);
13620 return 1;
13623 /*! \brief Handle incoming MESSAGE request */
13624 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
13626 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
13627 if (ast_test_flag(req, SIP_PKT_DEBUG))
13628 ast_verbose("Receiving message!\n");
13629 receive_message(p, req);
13631 transmit_response(p, "202 Accepted", req);
13632 return 1;
13635 /*! \brief Handle incoming SUBSCRIBE request */
13636 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
13638 int gotdest;
13639 int res = 0;
13640 int firststate = AST_EXTENSION_REMOVED;
13641 struct sip_peer *authpeer = NULL;
13642 const char *event = get_header(req, "Event"); /* Get Event package name */
13643 const char *accept = get_header(req, "Accept");
13644 int resubscribe = (p->subscribed != NONE);
13646 if (p->initreq.headers) {
13647 /* We already have a dialog */
13648 if (p->initreq.method != SIP_SUBSCRIBE) {
13649 /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
13650 /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
13651 transmit_response(p, "403 Forbidden (within dialog)", req);
13652 /* Do not destroy session, since we will break the call if we do */
13653 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);
13654 return 0;
13655 } else if (ast_test_flag(req, SIP_PKT_DEBUG)) {
13656 if (resubscribe)
13657 ast_log(LOG_DEBUG, "Got a re-subscribe on existing subscription %s\n", p->callid);
13658 else
13659 ast_log(LOG_DEBUG, "Got a new subscription %s (possibly with auth)\n", p->callid);
13663 /* Check if we have a global disallow setting on subscriptions.
13664 if so, we don't have to check peer/user settings after auth, which saves a lot of processing
13666 if (!global_allowsubscribe) {
13667 transmit_response(p, "403 Forbidden (policy)", req);
13668 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13669 return 0;
13672 if (!ast_test_flag(req, SIP_PKT_IGNORE) && !p->initreq.headers) { /* Set up dialog, new subscription */
13673 /* Use this as the basis */
13674 if (ast_test_flag(req, SIP_PKT_DEBUG))
13675 ast_verbose("Creating new subscription\n");
13677 /* This call is no longer outgoing if it ever was */
13678 ast_clear_flag(&p->flags[0], SIP_OUTGOING);
13679 copy_request(&p->initreq, req);
13680 check_via(p, req);
13681 } else if (ast_test_flag(req, SIP_PKT_DEBUG) && ast_test_flag(req, SIP_PKT_IGNORE))
13682 ast_verbose("Ignoring this SUBSCRIBE request\n");
13684 /* Find parameters to Event: header value and remove them for now */
13685 event = strsep((char **)&event, ";"); /* XXX bug here, overwrite string */
13687 /* Handle authentication if this is our first subscribe */
13688 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
13689 /* if an authentication response was sent, we are done here */
13690 if (res == AUTH_CHALLENGE_SENT)
13691 return 0;
13692 if (res < 0) {
13693 if (res == AUTH_FAKE_AUTH) {
13694 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
13695 transmit_fake_auth_response(p, req, 1);
13696 } else {
13697 ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
13698 transmit_response_reliable(p, "403 Forbidden", req);
13700 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13701 return 0;
13704 /* Check if this user/peer is allowed to subscribe at all */
13705 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
13706 transmit_response(p, "403 Forbidden (policy)", req);
13707 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13708 return 0;
13711 /* Get destination right away */
13712 gotdest = get_destination(p, NULL);
13714 /* Initialize the context if it hasn't been already;
13715 note this is done _after_ handling any domain lookups,
13716 because the context specified there is for calls, not
13717 subscriptions
13719 if (!ast_strlen_zero(p->subscribecontext))
13720 ast_string_field_set(p, context, p->subscribecontext);
13721 else if (ast_strlen_zero(p->context))
13722 ast_string_field_set(p, context, default_context);
13724 build_contact(p);
13725 if (gotdest) {
13726 transmit_response(p, "404 Not Found", req);
13727 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13728 return 0;
13729 } else {
13730 /* XXX reduce nesting here */
13732 /* Initialize tag for new subscriptions */
13733 if (ast_strlen_zero(p->tag))
13734 make_our_tag(p->tag, sizeof(p->tag));
13736 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
13738 /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
13739 if (strstr(accept, "application/pidf+xml")) {
13740 p->subscribed = PIDF_XML; /* RFC 3863 format */
13741 } else if (strstr(accept, "application/dialog-info+xml")) {
13742 p->subscribed = DIALOG_INFO_XML;
13743 /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
13744 } else if (strstr(accept, "application/cpim-pidf+xml")) {
13745 p->subscribed = CPIM_PIDF_XML; /* RFC 3863 format */
13746 } else if (strstr(accept, "application/xpidf+xml")) {
13747 p->subscribed = XPIDF_XML; /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
13748 } else if (strstr(p->useragent, "Polycom")) {
13749 p->subscribed = XPIDF_XML; /* Polycoms subscribe for "event: dialog" but don't include an "accept:" header */
13750 } else {
13751 /* Can't find a format for events that we know about */
13752 transmit_response(p, "489 Bad Event", req);
13753 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13754 return 0;
13756 } else if (!strcmp(event, "message-summary")) {
13757 if (!ast_strlen_zero(accept) && strcmp(accept, "application/simple-message-summary")) {
13758 /* Format requested that we do not support */
13759 transmit_response(p, "406 Not Acceptable", req);
13760 if (option_debug > 1)
13761 ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", accept);
13762 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13763 return 0;
13765 /* Looks like they actually want a mailbox status
13766 This version of Asterisk supports mailbox subscriptions
13767 The subscribed URI needs to exist in the dial plan
13768 In most devices, this is configurable to the voicemailmain extension you use
13770 if (!authpeer || ast_strlen_zero(authpeer->mailbox)) {
13771 transmit_response(p, "404 Not found (no mailbox)", req);
13772 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13773 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
13774 return 0;
13777 p->subscribed = MWI_NOTIFICATION;
13778 if (authpeer->mwipvt && authpeer->mwipvt != p) /* Destroy old PVT if this is a new one */
13779 /* We only allow one subscription per peer */
13780 sip_destroy(authpeer->mwipvt);
13781 authpeer->mwipvt = p; /* Link from peer to pvt */
13782 p->relatedpeer = authpeer; /* Link from pvt to peer */
13783 } else { /* At this point, Asterisk does not understand the specified event */
13784 transmit_response(p, "489 Bad Event", req);
13785 if (option_debug > 1)
13786 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: %s\n", event);
13787 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13788 return 0;
13790 if (p->subscribed != MWI_NOTIFICATION && !resubscribe)
13791 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, p);
13794 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
13795 p->lastinvite = seqno;
13796 if (p && !ast_test_flag(&p->flags[0], SIP_NEEDDESTROY)) {
13797 p->expiry = atoi(get_header(req, "Expires"));
13799 /* check if the requested expiry-time is within the approved limits from sip.conf */
13800 if (p->expiry > max_expiry)
13801 p->expiry = max_expiry;
13802 if (p->expiry < min_expiry && p->expiry > 0)
13803 p->expiry = min_expiry;
13805 if (sipdebug || option_debug > 1) {
13806 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
13807 ast_log(LOG_DEBUG, "Adding subscription for mailbox notification - peer %s Mailbox %s\n", p->relatedpeer->name, p->relatedpeer->mailbox);
13808 else
13809 ast_log(LOG_DEBUG, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
13811 if (p->autokillid > -1)
13812 sip_cancel_destroy(p); /* Remove subscription expiry for renewals */
13813 if (p->expiry > 0)
13814 sip_scheddestroy(p, (p->expiry + 10) * 1000); /* Set timer for destruction of call at expiration */
13816 if (p->subscribed == MWI_NOTIFICATION) {
13817 transmit_response(p, "200 OK", req);
13818 if (p->relatedpeer) { /* Send first notification */
13819 ASTOBJ_WRLOCK(p->relatedpeer);
13820 sip_send_mwi_to_peer(p->relatedpeer);
13821 ASTOBJ_UNLOCK(p->relatedpeer);
13823 } else {
13824 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
13826 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));
13827 transmit_response(p, "404 Not found", req);
13828 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13829 return 0;
13830 } else {
13831 /* XXX reduce nesting here */
13832 struct sip_pvt *p_old;
13834 transmit_response(p, "200 OK", req);
13835 transmit_state_notify(p, firststate, 1); /* Send first notification */
13836 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
13837 /* hide the 'complete' exten/context in the refer_to field for later display */
13838 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
13840 /* remove any old subscription from this peer for the same exten/context,
13841 as the peer has obviously forgotten about it and it's wasteful to wait
13842 for it to expire and send NOTIFY messages to the peer only to have them
13843 ignored (or generate errors)
13845 ast_mutex_lock(&iflock);
13846 for (p_old = iflist; p_old; p_old = p_old->next) {
13847 if (p_old == p)
13848 continue;
13849 if (p_old->initreq.method != SIP_SUBSCRIBE)
13850 continue;
13851 if (p_old->subscribed == NONE)
13852 continue;
13853 ast_mutex_lock(&p_old->lock);
13854 if (!strcmp(p_old->username, p->username)) {
13855 if (!strcmp(p_old->exten, p->exten) &&
13856 !strcmp(p_old->context, p->context)) {
13857 ast_set_flag(&p_old->flags[0], SIP_NEEDDESTROY);
13858 ast_mutex_unlock(&p_old->lock);
13859 break;
13862 ast_mutex_unlock(&p_old->lock);
13864 ast_mutex_unlock(&iflock);
13867 if (!p->expiry)
13868 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13870 if (authpeer)
13871 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
13872 return 1;
13875 /*! \brief Handle incoming REGISTER request */
13876 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
13878 enum check_auth_result res;
13880 /* Use this as the basis */
13881 if (ast_test_flag(req, SIP_PKT_DEBUG))
13882 ast_verbose("Using latest REGISTER request as basis request\n");
13883 copy_request(&p->initreq, req);
13884 check_via(p, req);
13885 if ((res = register_verify(p, sin, req, e)) < 0) {
13886 const char *reason = "";
13888 switch (res) {
13889 case AUTH_SECRET_FAILED:
13890 reason = "Wrong password";
13891 break;
13892 case AUTH_USERNAME_MISMATCH:
13893 reason = "Username/auth name mismatch";
13894 break;
13895 case AUTH_NOT_FOUND:
13896 reason = "No matching peer found";
13897 break;
13898 case AUTH_UNKNOWN_DOMAIN:
13899 reason = "Not a local domain";
13900 break;
13901 default:
13902 break;
13904 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
13905 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
13906 reason);
13908 if (res < 1) {
13909 /* Destroy the session, but keep us around for just a bit in case they don't
13910 get our 200 OK */
13911 sip_scheddestroy(p, 15000);
13913 append_history(p, "RegRequest", "%s : Account %s", res ? "Failed": "Succeeded", get_header(req, "To"));
13914 return res;
13917 /*! \brief Handle incoming SIP requests (methods)
13918 \note This is where all incoming requests go first */
13919 /* called with p and p->owner locked */
13920 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
13922 /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
13923 relatively static */
13924 struct sip_request resp;
13925 const char *cmd;
13926 const char *cseq;
13927 const char *useragent;
13928 int seqno;
13929 int len;
13930 int ignore = FALSE;
13931 int respid;
13932 int res = 0;
13933 int debug = sip_debug_test_pvt(p);
13934 char *e;
13935 int error = 0;
13937 /* Clear out potential response */
13938 memset(&resp, 0, sizeof(resp));
13940 /* Get Method and Cseq */
13941 cseq = get_header(req, "Cseq");
13942 cmd = req->header[0];
13944 /* Must have Cseq */
13945 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
13946 ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
13947 error = 1;
13949 if (!error && sscanf(cseq, "%d%n", &seqno, &len) != 1) {
13950 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
13951 error = 1;
13953 if (error) {
13954 if (!p->initreq.header) /* New call */
13955 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); /* Make sure we destroy this dialog */
13956 return -1;
13958 /* Get the command XXX */
13960 cmd = req->rlPart1;
13961 e = req->rlPart2;
13963 /* Save useragent of the client */
13964 useragent = get_header(req, "User-Agent");
13965 if (!ast_strlen_zero(useragent))
13966 ast_string_field_set(p, useragent, useragent);
13968 /* Find out SIP method for incoming request */
13969 if (req->method == SIP_RESPONSE) { /* Response to our request */
13970 /* Response to our request -- Do some sanity checks */
13971 if (!p->initreq.headers) {
13972 if (option_debug)
13973 ast_log(LOG_DEBUG, "That's odd... Got a response on a call we dont know about. Cseq %d Cmd %s\n", seqno, cmd);
13974 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13975 return 0;
13976 } else if (p->ocseq && (p->ocseq < seqno)) {
13977 if (option_debug)
13978 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
13979 return -1;
13980 } else if (p->ocseq && (p->ocseq != seqno)) {
13981 /* ignore means "don't do anything with it" but still have to
13982 respond appropriately */
13983 ignore = TRUE;
13984 ast_set_flag(req, SIP_PKT_IGNORE);
13985 ast_set_flag(req, SIP_PKT_IGNORE_RESP);
13986 append_history(p, "Ignore", "Ignoring this retransmit\n");
13989 e = ast_skip_blanks(e);
13990 if (sscanf(e, "%d %n", &respid, &len) != 1) {
13991 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
13992 } else {
13993 /* More SIP ridiculousness, we have to ignore bogus contacts in 100 etc responses */
13994 if ((respid == 200) || ((respid >= 300) && (respid <= 399)))
13995 extract_uri(p, req);
13996 handle_response(p, respid, e + len, req, ignore, seqno);
13998 return 0;
14001 /* New SIP request coming in
14002 (could be new request in existing SIP dialog as well...)
14005 p->method = req->method; /* Find out which SIP method they are using */
14006 if (option_debug > 3)
14007 ast_log(LOG_DEBUG, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
14009 if (p->icseq && (p->icseq > seqno)) {
14010 if (option_debug)
14011 ast_log(LOG_DEBUG, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
14012 if (req->method != SIP_ACK)
14013 transmit_response(p, "503 Server error", req); /* We must respond according to RFC 3261 sec 12.2 */
14014 return -1;
14015 } else if (p->icseq &&
14016 p->icseq == seqno &&
14017 req->method != SIP_ACK &&
14018 (p->method != SIP_CANCEL || ast_test_flag(&p->flags[0], SIP_ALREADYGONE))) {
14019 /* ignore means "don't do anything with it" but still have to
14020 respond appropriately. We do this if we receive a repeat of
14021 the last sequence number */
14022 ignore = 2;
14023 ast_set_flag(req, SIP_PKT_IGNORE);
14024 ast_set_flag(req, SIP_PKT_IGNORE_REQ);
14025 if (option_debug > 2)
14026 ast_log(LOG_DEBUG, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
14029 if (seqno >= p->icseq)
14030 /* Next should follow monotonically (but not necessarily
14031 incrementally -- thanks again to the genius authors of SIP --
14032 increasing */
14033 p->icseq = seqno;
14035 /* Find their tag if we haven't got it */
14036 if (ast_strlen_zero(p->theirtag)) {
14037 char tag[128];
14039 gettag(req, "From", tag, sizeof(tag));
14040 ast_string_field_set(p, theirtag, tag);
14042 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
14044 if (pedanticsipchecking) {
14045 /* If this is a request packet without a from tag, it's not
14046 correct according to RFC 3261 */
14047 /* Check if this a new request in a new dialog with a totag already attached to it,
14048 RFC 3261 - section 12.2 - and we don't want to mess with recovery */
14049 if (!p->initreq.headers && ast_test_flag(req, SIP_PKT_WITH_TOTAG)) {
14050 /* If this is a first request and it got a to-tag, it is not for us */
14051 if (!ast_test_flag(req, SIP_PKT_IGNORE) && req->method == SIP_INVITE) {
14052 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
14053 /* Will cease to exist after ACK */
14054 } else if (req->method != SIP_ACK) {
14055 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
14056 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14058 return res;
14062 /* Handle various incoming SIP methods in requests */
14063 switch (p->method) {
14064 case SIP_OPTIONS:
14065 res = handle_request_options(p, req);
14066 break;
14067 case SIP_INVITE:
14068 res = handle_request_invite(p, req, debug, seqno, sin, recount, e);
14069 break;
14070 case SIP_REFER:
14071 res = handle_request_refer(p, req, debug, ignore, seqno, nounlock);
14072 break;
14073 case SIP_CANCEL:
14074 res = handle_request_cancel(p, req);
14075 break;
14076 case SIP_BYE:
14077 res = handle_request_bye(p, req);
14078 break;
14079 case SIP_MESSAGE:
14080 res = handle_request_message(p, req);
14081 break;
14082 case SIP_SUBSCRIBE:
14083 res = handle_request_subscribe(p, req, sin, seqno, e);
14084 break;
14085 case SIP_REGISTER:
14086 res = handle_request_register(p, req, sin, e);
14087 break;
14088 case SIP_INFO:
14089 if (ast_test_flag(req, SIP_PKT_DEBUG))
14090 ast_verbose("Receiving INFO!\n");
14091 if (!ignore)
14092 handle_request_info(p, req);
14093 else /* if ignoring, transmit response */
14094 transmit_response(p, "200 OK", req);
14095 break;
14096 case SIP_NOTIFY:
14097 res = handle_request_notify(p, req, sin, seqno, e);
14098 break;
14099 case SIP_ACK:
14100 /* Make sure we don't ignore this */
14101 if (seqno == p->pendinginvite) {
14102 p->pendinginvite = 0;
14103 __sip_ack(p, seqno, FLAG_RESPONSE, 0, FALSE);
14104 if (find_sdp(req)) {
14105 if (process_sdp(p, req))
14106 return -1;
14108 check_pendings(p);
14110 if (!p->lastinvite && ast_strlen_zero(p->randdata))
14111 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14112 break;
14113 default:
14114 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
14115 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
14116 cmd, ast_inet_ntoa(p->sa.sin_addr));
14117 /* If this is some new method, and we don't have a call, destroy it now */
14118 if (!p->initreq.headers)
14119 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14120 break;
14122 return res;
14125 /*! \brief Read data from SIP socket
14126 \note sipsock_read locks the owner channel while we are processing the SIP message
14127 \return 1 on error, 0 on success
14128 \note Successful messages is connected to SIP call and forwarded to handle_request()
14130 static int sipsock_read(int *id, int fd, short events, void *ignore)
14132 struct sip_request req;
14133 struct sockaddr_in sin = { 0, };
14134 struct sip_pvt *p;
14135 int res;
14136 socklen_t len;
14137 int nounlock;
14138 int recount = 0;
14139 unsigned int lockretry = 100;
14141 len = sizeof(sin);
14142 memset(&req, 0, sizeof(req));
14143 res = recvfrom(sipsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
14144 if (res < 0) {
14145 #if !defined(__FreeBSD__)
14146 if (errno == EAGAIN)
14147 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
14148 else
14149 #endif
14150 if (errno != ECONNREFUSED)
14151 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
14152 return 1;
14154 if (option_debug && res == sizeof(req.data)) {
14155 ast_log(LOG_DEBUG, "Received packet exceeds buffer. Data is possibly lost\n");
14156 req.data[sizeof(req.data) - 1] = '\0';
14157 } else
14158 req.data[res] = '\0';
14159 req.len = res;
14160 if(sip_debug_test_addr(&sin)) /* Set the debug flag early on packet level */
14161 ast_set_flag(&req, SIP_PKT_DEBUG);
14162 if (pedanticsipchecking)
14163 req.len = lws2sws(req.data, req.len); /* Fix multiline headers */
14164 if (ast_test_flag(&req, SIP_PKT_DEBUG))
14165 ast_verbose("\n<-- SIP read from %s:%d: \n%s\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), req.data);
14167 parse_request(&req);
14168 req.method = find_sip_method(req.rlPart1);
14169 if (ast_test_flag(&req, SIP_PKT_DEBUG)) {
14170 ast_verbose("--- (%d headers %d lines)", req.headers, req.lines);
14171 if (req.headers + req.lines == 0)
14172 ast_verbose(" Nat keepalive ");
14173 ast_verbose("---\n");
14176 if (req.headers < 2) {
14177 /* Must have at least two headers */
14178 return 1;
14182 /* Process request, with netlock held */
14183 retrylock:
14184 ast_mutex_lock(&netlock);
14186 /* Find the active SIP dialog or create a new one */
14187 p = find_call(&req, &sin, req.method); /* returns p locked */
14188 if (p) {
14189 /* Go ahead and lock the owner if it has one -- we may need it */
14190 /* becaues this is deadlock-prone, we need to try and unlock if failed */
14191 if (p->owner && ast_channel_trylock(p->owner)) {
14192 if (option_debug)
14193 ast_log(LOG_DEBUG, "Failed to grab owner channel lock, trying again. (SIP call %s)\n", p->callid);
14194 ast_mutex_unlock(&p->lock);
14195 ast_mutex_unlock(&netlock);
14196 /* Sleep for a very short amount of time */
14197 usleep(1);
14198 if (--lockretry)
14199 goto retrylock;
14201 p->recv = sin;
14203 if (recordhistory) /* This is a request or response, note what it was for */
14204 append_history(p, "Rx", "%s / %s / %s", req.data, get_header(&req, "CSeq"), req.rlPart2);
14206 if (!lockretry) {
14207 ast_log(LOG_ERROR, "We could NOT get the channel lock for %s! \n", p->owner->name ? p->owner->name : "- no channel name ??? - ");
14208 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
14209 transmit_response(p, "503 Server error", &req); /* We must respond according to RFC 3261 sec 12.2 */
14210 /* XXX We could add retry-after to make sure they come back */
14211 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
14212 return 1;
14214 nounlock = 0;
14215 if (handle_request(p, &req, &sin, &recount, &nounlock) == -1) {
14216 /* Request failed */
14217 if (option_debug)
14218 ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
14221 if (p->owner && !nounlock)
14222 ast_channel_unlock(p->owner);
14223 ast_mutex_unlock(&p->lock);
14224 } else {
14225 if (option_debug)
14226 ast_log(LOG_DEBUG, "Invalid SIP message - rejected , bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
14228 ast_mutex_unlock(&netlock);
14229 if (recount)
14230 ast_update_use_count();
14232 return 1;
14235 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
14236 static int sip_send_mwi_to_peer(struct sip_peer *peer)
14238 /* Called with peerl lock, but releases it */
14239 struct sip_pvt *p;
14240 int newmsgs, oldmsgs;
14242 /* Check for messages */
14243 ast_app_inboxcount(peer->mailbox, &newmsgs, &oldmsgs);
14245 peer->lastmsgcheck = time(NULL);
14247 /* Return now if it's the same thing we told them last time */
14248 if (((newmsgs << 8) | (oldmsgs)) == peer->lastmsgssent) {
14249 return 0;
14253 peer->lastmsgssent = ((newmsgs << 8) | (oldmsgs));
14255 if (peer->mwipvt) {
14256 /* Base message on subscription */
14257 p = peer->mwipvt;
14258 } else {
14259 /* Build temporary dialog for this message */
14260 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY)))
14261 return -1;
14262 if (create_addr_from_peer(p, peer)) {
14263 /* Maybe they're not registered, etc. */
14264 sip_destroy(p);
14265 return 0;
14267 /* Recalculate our side, and recalculate Call ID */
14268 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
14269 p->ourip = __ourip;
14270 build_via(p);
14271 build_callid_pvt(p);
14272 /* Destroy this session after 32 secs */
14273 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
14275 /* Send MWI */
14276 ast_set_flag(&p->flags[0], SIP_OUTGOING);
14277 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
14278 return 0;
14281 /*! \brief Check whether peer needs a new MWI notification check */
14282 static int does_peer_need_mwi(struct sip_peer *peer)
14284 time_t t = time(NULL);
14286 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
14287 !peer->mwipvt) { /* We don't have a subscription */
14288 peer->lastmsgcheck = t; /* Reset timer */
14289 return FALSE;
14292 if (!ast_strlen_zero(peer->mailbox) && (t - peer->lastmsgcheck) > global_mwitime)
14293 return TRUE;
14295 return FALSE;
14299 /*! \brief The SIP monitoring thread
14300 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
14301 (and thus do not have a separate thread) indefinitely
14303 static void *do_monitor(void *data)
14305 int res;
14306 struct sip_pvt *sip;
14307 struct sip_peer *peer = NULL;
14308 time_t t;
14309 int fastrestart = FALSE;
14310 int lastpeernum = -1;
14311 int curpeernum;
14312 int reloading;
14314 /* Add an I/O event to our SIP UDP socket */
14315 if (sipsock > -1)
14316 ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
14318 /* From here on out, we die whenever asked */
14319 for(;;) {
14320 /* Check for a reload request */
14321 ast_mutex_lock(&sip_reload_lock);
14322 reloading = sip_reloading;
14323 sip_reloading = FALSE;
14324 ast_mutex_unlock(&sip_reload_lock);
14325 if (reloading) {
14326 if (option_verbose > 0)
14327 ast_verbose(VERBOSE_PREFIX_1 "Reloading SIP\n");
14328 sip_do_reload(sip_reloadreason);
14330 /* Check for interfaces needing to be killed */
14331 ast_mutex_lock(&iflock);
14332 restartsearch:
14333 t = time(NULL);
14334 /* don't scan the interface list if it hasn't been a reasonable period
14335 of time since the last time we did it (when MWI is being sent, we can
14336 get back to this point every millisecond or less)
14338 for (sip = iflist; !fastrestart && sip; sip = sip->next) {
14339 ast_mutex_lock(&sip->lock);
14340 /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
14341 if (sip->rtp && sip->owner &&
14342 (sip->owner->_state == AST_STATE_UP) &&
14343 !sip->redirip.sin_addr.s_addr) {
14344 if (sip->lastrtptx &&
14345 sip->rtpkeepalive &&
14346 (t > sip->lastrtptx + sip->rtpkeepalive)) {
14347 /* Need to send an empty RTP packet */
14348 sip->lastrtptx = time(NULL);
14349 ast_rtp_sendcng(sip->rtp, 0);
14351 if (sip->lastrtprx &&
14352 (sip->rtptimeout || sip->rtpholdtimeout) &&
14353 (t > sip->lastrtprx + sip->rtptimeout)) {
14354 /* Might be a timeout now -- see if we're on hold */
14355 struct sockaddr_in sin;
14356 ast_rtp_get_peer(sip->rtp, &sin);
14357 if (sin.sin_addr.s_addr ||
14358 (sip->rtpholdtimeout &&
14359 (t > sip->lastrtprx + sip->rtpholdtimeout))) {
14360 /* Needs a hangup */
14361 if (sip->rtptimeout) {
14362 while (sip->owner && ast_channel_trylock(sip->owner)) {
14363 ast_mutex_unlock(&sip->lock);
14364 usleep(1);
14365 ast_mutex_lock(&sip->lock);
14367 if (sip->owner) {
14368 ast_log(LOG_NOTICE,
14369 "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
14370 sip->owner->name,
14371 (long) (t - sip->lastrtprx));
14372 /* Issue a softhangup */
14373 ast_softhangup_nolock(sip->owner, AST_SOFTHANGUP_DEV);
14374 ast_channel_unlock(sip->owner);
14375 /* forget the timeouts for this call, since a hangup
14376 has already been requested and we don't want to
14377 repeatedly request hangups
14379 sip->rtptimeout = 0;
14380 sip->rtpholdtimeout = 0;
14386 /* If we have sessions that needs to be destroyed, do it now */
14387 if (ast_test_flag(&sip->flags[0], SIP_NEEDDESTROY) && !sip->packets &&
14388 !sip->owner) {
14389 ast_mutex_unlock(&sip->lock);
14390 __sip_destroy(sip, 1);
14391 goto restartsearch;
14393 ast_mutex_unlock(&sip->lock);
14395 ast_mutex_unlock(&iflock);
14397 pthread_testcancel();
14398 /* Wait for sched or io */
14399 res = ast_sched_wait(sched);
14400 if ((res < 0) || (res > 1000))
14401 res = 1000;
14402 /* If we might need to send more mailboxes, don't wait long at all.*/
14403 if (fastrestart)
14404 res = 1;
14405 res = ast_io_wait(io, res);
14406 if (option_debug && res > 20)
14407 ast_log(LOG_DEBUG, "chan_sip: ast_io_wait ran %d all at once\n", res);
14408 ast_mutex_lock(&monlock);
14409 if (res >= 0) {
14410 res = ast_sched_runq(sched);
14411 if (option_debug && res >= 20)
14412 ast_log(LOG_DEBUG, "chan_sip: ast_sched_runq ran %d all at once\n", res);
14415 /* Send MWI notifications to peers - static and cached realtime peers */
14416 t = time(NULL);
14417 fastrestart = FALSE;
14418 curpeernum = 0;
14419 peer = NULL;
14420 /* Find next peer that needs mwi */
14421 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !peer, do {
14422 if ((curpeernum > lastpeernum) && does_peer_need_mwi(iterator)) {
14423 fastrestart = TRUE;
14424 lastpeernum = curpeernum;
14425 peer = ASTOBJ_REF(iterator);
14427 curpeernum++;
14428 } while (0)
14430 /* Send MWI to the peer */
14431 if (peer) {
14432 ASTOBJ_WRLOCK(peer);
14433 sip_send_mwi_to_peer(peer);
14434 ASTOBJ_UNLOCK(peer);
14435 ASTOBJ_UNREF(peer,sip_destroy_peer);
14436 } else {
14437 /* Reset where we come from */
14438 lastpeernum = -1;
14440 ast_mutex_unlock(&monlock);
14442 /* Never reached */
14443 return NULL;
14447 /*! \brief Start the channel monitor thread */
14448 static int restart_monitor(void)
14450 /* If we're supposed to be stopped -- stay stopped */
14451 if (monitor_thread == AST_PTHREADT_STOP)
14452 return 0;
14453 ast_mutex_lock(&monlock);
14454 if (monitor_thread == pthread_self()) {
14455 ast_mutex_unlock(&monlock);
14456 ast_log(LOG_WARNING, "Cannot kill myself\n");
14457 return -1;
14459 if (monitor_thread != AST_PTHREADT_NULL) {
14460 /* Wake up the thread */
14461 pthread_kill(monitor_thread, SIGURG);
14462 } else {
14463 /* Start a new monitor */
14464 if (ast_pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
14465 ast_mutex_unlock(&monlock);
14466 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
14467 return -1;
14470 ast_mutex_unlock(&monlock);
14471 return 0;
14474 /*! \brief React to lack of answer to Qualify poke */
14475 static int sip_poke_noanswer(void *data)
14477 struct sip_peer *peer = data;
14479 peer->pokeexpire = -1;
14480 if (peer->lastms > -1) {
14481 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
14482 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
14484 if (peer->call)
14485 sip_destroy(peer->call);
14486 peer->call = NULL;
14487 peer->lastms = -1;
14488 ast_device_state_changed("SIP/%s", peer->name);
14489 /* Try again quickly */
14490 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
14491 return 0;
14494 /*! \brief Check availability of peer, also keep NAT open
14495 \note This is done with the interval in qualify= configuration option
14496 Default is 2 seconds */
14497 static int sip_poke_peer(struct sip_peer *peer)
14499 struct sip_pvt *p;
14501 if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
14502 /* IF we have no IP, or this isn't to be monitored, return
14503 imeediately after clearing things out */
14504 if (peer->pokeexpire > -1)
14505 ast_sched_del(sched, peer->pokeexpire);
14506 peer->lastms = 0;
14507 peer->pokeexpire = -1;
14508 peer->call = NULL;
14509 return 0;
14511 if (peer->call > 0) {
14512 if (sipdebug)
14513 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
14514 sip_destroy(peer->call);
14516 if (!(p = peer->call = sip_alloc(NULL, NULL, 0, SIP_OPTIONS)))
14517 return -1;
14519 p->sa = peer->addr;
14520 p->recv = peer->addr;
14521 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14522 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14524 /* Send OPTIONs to peer's fullcontact */
14525 if (!ast_strlen_zero(peer->fullcontact))
14526 ast_string_field_set(p, fullcontact, peer->fullcontact);
14528 if (!ast_strlen_zero(peer->tohost))
14529 ast_string_field_set(p, tohost, peer->tohost);
14530 else
14531 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
14533 /* Recalculate our side, and recalculate Call ID */
14534 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
14535 p->ourip = __ourip;
14536 build_via(p);
14537 build_callid_pvt(p);
14539 if (peer->pokeexpire > -1)
14540 ast_sched_del(sched, peer->pokeexpire);
14541 p->relatedpeer = peer;
14542 ast_set_flag(&p->flags[0], SIP_OUTGOING);
14543 #ifdef VOCAL_DATA_HACK
14544 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
14545 transmit_invite(p, SIP_INVITE, 0, 2);
14546 #else
14547 transmit_invite(p, SIP_OPTIONS, 0, 2);
14548 #endif
14549 gettimeofday(&peer->ps, NULL);
14550 peer->pokeexpire = ast_sched_add(sched, DEFAULT_MAXMS * 2, sip_poke_noanswer, peer);
14552 return 0;
14555 /*! \brief Part of PBX channel interface
14556 \note
14557 \par Return values:---
14559 If we have qualify on and the device is not reachable, regardless of registration
14560 state we return AST_DEVICE_UNAVAILABLE
14562 For peers with call limit:
14563 - not registered AST_DEVICE_UNAVAILABLE
14564 - registered, no call AST_DEVICE_NOT_INUSE
14565 - registered, active calls AST_DEVICE_INUSE
14566 - registered, call limit reached AST_DEVICE_BUSY
14567 For peers without call limit:
14568 - not registered AST_DEVICE_UNAVAILABLE
14569 - registered AST_DEVICE_NOT_INUSE
14570 - fixed IP (!dynamic) AST_DEVICE_NOT_INUSE
14572 If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
14573 out a state by walking the channel list.
14575 static int sip_devicestate(void *data)
14577 char *host;
14578 char *tmp;
14580 struct hostent *hp;
14581 struct ast_hostent ahp;
14582 struct sip_peer *p;
14584 int res = AST_DEVICE_INVALID;
14586 host = ast_strdupa(data);
14587 if ((tmp = strchr(host, '@')))
14588 host = tmp + 1;
14590 if (option_debug > 2)
14591 ast_log(LOG_DEBUG, "Checking device state for peer %s\n", host);
14593 if ((p = find_peer(host, NULL, 1))) {
14594 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
14595 /* we have an address for the peer */
14596 /* if qualify is turned on, check the status */
14597 if (p->maxms && (p->lastms > p->maxms)) {
14598 res = AST_DEVICE_UNAVAILABLE;
14599 } else {
14600 /* qualify is not on, or the peer is responding properly */
14601 /* check call limit */
14602 if (p->call_limit && (p->inUse == p->call_limit))
14603 res = AST_DEVICE_BUSY;
14604 else if (p->call_limit && p->inUse)
14605 res = AST_DEVICE_INUSE;
14606 else
14607 res = AST_DEVICE_NOT_INUSE;
14608 if (p->onHold)
14609 res = AST_DEVICE_ONHOLD;
14610 else if (p->inRinging) {
14611 if (p->inRinging == p->inUse)
14612 res = AST_DEVICE_RINGING;
14613 else
14614 res = AST_DEVICE_RINGINUSE;
14617 } else {
14618 /* there is no address, it's unavailable */
14619 res = AST_DEVICE_UNAVAILABLE;
14621 ASTOBJ_UNREF(p,sip_destroy_peer);
14622 } else {
14623 hp = ast_gethostbyname(host, &ahp);
14624 if (hp)
14625 res = AST_DEVICE_UNKNOWN;
14628 return res;
14631 /*! \brief PBX interface function -build SIP pvt structure */
14632 /* SIP calls initiated by the PBX arrive here */
14633 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
14635 int oldformat;
14636 struct sip_pvt *p;
14637 struct ast_channel *tmpc = NULL;
14638 char *ext, *host;
14639 char tmp[256];
14640 char *dest = data;
14642 oldformat = format;
14643 if (!(format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1))) {
14644 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));
14645 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL; /* Can't find codec to connect to host */
14646 return NULL;
14648 if (option_debug)
14649 ast_log(LOG_DEBUG, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
14651 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE))) {
14652 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", (char *)data);
14653 *cause = AST_CAUSE_SWITCH_CONGESTION;
14654 return NULL;
14657 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
14658 sip_destroy(p);
14659 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
14660 *cause = AST_CAUSE_SWITCH_CONGESTION;
14661 return NULL;
14664 ast_copy_string(tmp, dest, sizeof(tmp));
14665 host = strchr(tmp, '@');
14666 if (host) {
14667 *host++ = '\0';
14668 ext = tmp;
14669 } else {
14670 ext = strchr(tmp, '/');
14671 if (ext)
14672 *ext++ = '\0';
14673 host = tmp;
14676 if (create_addr(p, host)) {
14677 *cause = AST_CAUSE_UNREGISTERED;
14678 if (option_debug > 2)
14679 ast_log(LOG_DEBUG, "Cant create SIP call - target device not registred\n");
14680 sip_destroy(p);
14681 return NULL;
14683 if (ast_strlen_zero(p->peername) && ext)
14684 ast_string_field_set(p, peername, ext);
14685 /* Recalculate our side, and recalculate Call ID */
14686 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
14687 p->ourip = __ourip;
14688 build_via(p);
14689 build_callid_pvt(p);
14691 /* We have an extension to call, don't use the full contact here */
14692 /* This to enable dialing registered peers with extension dialling,
14693 like SIP/peername/extension
14694 SIP/peername will still use the full contact */
14695 if (ext) {
14696 ast_string_field_set(p, username, ext);
14697 ast_string_field_free(p, fullcontact);
14699 #if 0
14700 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
14701 #endif
14702 p->prefcodec = oldformat; /* Format for this call */
14703 ast_mutex_lock(&p->lock);
14704 tmpc = sip_new(p, AST_STATE_DOWN, host); /* Place the call */
14705 ast_mutex_unlock(&p->lock);
14706 if (!tmpc)
14707 sip_destroy(p);
14708 ast_update_use_count();
14709 restart_monitor();
14710 return tmpc;
14714 \brief Handle flag-type options common to configuration of devices - users and peers
14715 \param flags array of two struct ast_flags
14716 \param mask array of two struct ast_flags
14717 \param v linked list of config variables to process
14718 \returns non-zero if any config options were handled, zero otherwise
14720 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
14722 int res = 0;
14723 static int dep_insecure_very = 0;
14724 static int dep_insecure_yes = 0;
14726 if (!strcasecmp(v->name, "trustrpid")) {
14727 ast_set_flag(&mask[0], SIP_TRUSTRPID);
14728 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
14729 res = 1;
14730 } else if (!strcasecmp(v->name, "sendrpid")) {
14731 ast_set_flag(&mask[0], SIP_SENDRPID);
14732 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
14733 res = 1;
14734 } else if (!strcasecmp(v->name, "g726nonstandard")) {
14735 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
14736 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
14737 res = 1;
14738 } else if (!strcasecmp(v->name, "useclientcode")) {
14739 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
14740 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
14741 res = 1;
14742 } else if (!strcasecmp(v->name, "dtmfmode")) {
14743 ast_set_flag(&mask[0], SIP_DTMF);
14744 ast_clear_flag(&flags[0], SIP_DTMF);
14745 if (!strcasecmp(v->value, "inband"))
14746 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
14747 else if (!strcasecmp(v->value, "rfc2833"))
14748 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
14749 else if (!strcasecmp(v->value, "info"))
14750 ast_set_flag(&flags[0], SIP_DTMF_INFO);
14751 else if (!strcasecmp(v->value, "auto"))
14752 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
14753 else {
14754 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
14755 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
14757 } else if (!strcasecmp(v->name, "nat")) {
14758 ast_set_flag(&mask[0], SIP_NAT);
14759 ast_clear_flag(&flags[0], SIP_NAT);
14760 if (!strcasecmp(v->value, "never"))
14761 ast_set_flag(&flags[0], SIP_NAT_NEVER);
14762 else if (!strcasecmp(v->value, "route"))
14763 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
14764 else if (ast_true(v->value))
14765 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
14766 else
14767 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
14768 } else if (!strcasecmp(v->name, "canreinvite")) {
14769 ast_set_flag(&mask[0], SIP_REINVITE);
14770 ast_clear_flag(&flags[0], SIP_REINVITE);
14771 if (ast_true(v->value)) {
14772 ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
14773 } else if (!ast_false(v->value)) {
14774 char buf[64];
14775 char *word, *next = buf;
14777 ast_copy_string(buf, v->value, sizeof(buf));
14778 while ((word = strsep(&next, ","))) {
14779 if (!strcasecmp(word, "update")) {
14780 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
14781 } else if (!strcasecmp(word, "nonat")) {
14782 ast_set_flag(&flags[0], SIP_CAN_REINVITE);
14783 ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
14784 } else {
14785 ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
14789 } else if (!strcasecmp(v->name, "insecure")) {
14790 ast_set_flag(&mask[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
14791 ast_clear_flag(&flags[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
14792 if (!strcasecmp(v->value, "very")) {
14793 ast_set_flag(&flags[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
14794 if (!dep_insecure_very) {
14795 ast_log(LOG_WARNING, "insecure=very at line %d is deprecated; use insecure=port,invite instead\n", v->lineno);
14796 dep_insecure_very = 1;
14799 else if (ast_true(v->value)) {
14800 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
14801 if (!dep_insecure_yes) {
14802 ast_log(LOG_WARNING, "insecure=%s at line %d is deprecated; use insecure=port instead\n", v->value, v->lineno);
14803 dep_insecure_yes = 1;
14806 else if (!ast_false(v->value)) {
14807 char buf[64];
14808 char *word, *next;
14810 ast_copy_string(buf, v->value, sizeof(buf));
14811 next = buf;
14812 while ((word = strsep(&next, ","))) {
14813 if (!strcasecmp(word, "port"))
14814 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
14815 else if (!strcasecmp(word, "invite"))
14816 ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
14817 else
14818 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", v->value, v->lineno);
14821 } else if (!strcasecmp(v->name, "progressinband")) {
14822 ast_set_flag(&mask[0], SIP_PROG_INBAND);
14823 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
14824 if (ast_true(v->value))
14825 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
14826 else if (strcasecmp(v->value, "never"))
14827 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
14828 } else if (!strcasecmp(v->name, "allowguest")) {
14829 global_allowguest = ast_true(v->value) ? 1 : 0;
14830 } else if (!strcasecmp(v->name, "promiscredir")) {
14831 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
14832 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
14833 res = 1;
14834 } else if (!strcasecmp(v->name, "videosupport")) {
14835 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
14836 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
14837 } else if (!strcasecmp(v->name, "allowoverlap")) {
14838 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
14839 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
14840 } else if (!strcasecmp(v->name, "allowsubscribe")) {
14841 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
14842 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
14843 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
14844 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_UDPTL);
14845 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_UDPTL);
14846 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
14847 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_RTP);
14848 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_RTP);
14849 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
14850 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_TCP);
14851 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_TCP);
14854 return res;
14857 /*! \brief Add SIP domain to list of domains we are responsible for */
14858 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
14860 struct domain *d;
14862 if (ast_strlen_zero(domain)) {
14863 ast_log(LOG_WARNING, "Zero length domain.\n");
14864 return 1;
14867 if (!(d = ast_calloc(1, sizeof(*d))))
14868 return 0;
14870 ast_copy_string(d->domain, domain, sizeof(d->domain));
14872 if (!ast_strlen_zero(context))
14873 ast_copy_string(d->context, context, sizeof(d->context));
14875 d->mode = mode;
14877 AST_LIST_LOCK(&domain_list);
14878 AST_LIST_INSERT_TAIL(&domain_list, d, list);
14879 AST_LIST_UNLOCK(&domain_list);
14881 if (sipdebug)
14882 ast_log(LOG_DEBUG, "Added local SIP domain '%s'\n", domain);
14884 return 1;
14887 /*! \brief check_sip_domain: Check if domain part of uri is local to our server */
14888 static int check_sip_domain(const char *domain, char *context, size_t len)
14890 struct domain *d;
14891 int result = 0;
14893 AST_LIST_LOCK(&domain_list);
14894 AST_LIST_TRAVERSE(&domain_list, d, list) {
14895 if (strcasecmp(d->domain, domain))
14896 continue;
14898 if (len && !ast_strlen_zero(d->context))
14899 ast_copy_string(context, d->context, len);
14901 result = 1;
14902 break;
14904 AST_LIST_UNLOCK(&domain_list);
14906 return result;
14909 /*! \brief Clear our domain list (at reload) */
14910 static void clear_sip_domains(void)
14912 struct domain *d;
14914 AST_LIST_LOCK(&domain_list);
14915 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
14916 free(d);
14917 AST_LIST_UNLOCK(&domain_list);
14921 /*! \brief Add realm authentication in list */
14922 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno)
14924 char authcopy[256];
14925 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
14926 char *stringp;
14927 struct sip_auth *a, *b, *auth;
14929 if (ast_strlen_zero(configuration))
14930 return authlist;
14932 ast_log(LOG_DEBUG, "Auth config :: %s\n", configuration);
14934 ast_copy_string(authcopy, configuration, sizeof(authcopy));
14935 stringp = authcopy;
14937 username = stringp;
14938 realm = strrchr(stringp, '@');
14939 if (realm)
14940 *realm++ = '\0';
14941 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
14942 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
14943 return authlist;
14945 stringp = username;
14946 username = strsep(&stringp, ":");
14947 if (username) {
14948 secret = strsep(&stringp, ":");
14949 if (!secret) {
14950 stringp = username;
14951 md5secret = strsep(&stringp,"#");
14954 if (!(auth = ast_calloc(1, sizeof(*auth))))
14955 return authlist;
14957 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
14958 ast_copy_string(auth->username, username, sizeof(auth->username));
14959 if (secret)
14960 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
14961 if (md5secret)
14962 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
14964 /* find the end of the list */
14965 for (b = NULL, a = authlist; a ; b = a, a = a->next)
14967 if (b)
14968 b->next = auth; /* Add structure add end of list */
14969 else
14970 authlist = auth;
14972 if (option_verbose > 2)
14973 ast_verbose("Added authentication for realm %s\n", realm);
14975 return authlist;
14979 /*! \brief Clear realm authentication list (at reload) */
14980 static int clear_realm_authentication(struct sip_auth *authlist)
14982 struct sip_auth *a = authlist;
14983 struct sip_auth *b;
14985 while (a) {
14986 b = a;
14987 a = a->next;
14988 free(b);
14991 return 1;
14994 /*! \brief Find authentication for a specific realm */
14995 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
14997 struct sip_auth *a;
14999 for (a = authlist; a; a = a->next) {
15000 if (!strcasecmp(a->realm, realm))
15001 break;
15004 return a;
15007 /*! \brief Initiate a SIP user structure from configuration (configuration or realtime) */
15008 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime)
15010 struct sip_user *user;
15011 int format;
15012 struct ast_ha *oldha = NULL;
15013 char *varname = NULL, *varval = NULL;
15014 struct ast_variable *tmpvar = NULL;
15015 struct ast_flags userflags[2] = {{(0)}};
15016 struct ast_flags mask[2] = {{(0)}};
15019 if (!(user = ast_calloc(1, sizeof(*user))))
15020 return NULL;
15022 suserobjs++;
15023 ASTOBJ_INIT(user);
15024 ast_copy_string(user->name, name, sizeof(user->name));
15025 oldha = user->ha;
15026 user->ha = NULL;
15027 ast_copy_flags(&user->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
15028 ast_copy_flags(&user->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15029 user->capability = global_capability;
15030 user->allowtransfer = global_allowtransfer;
15031 user->maxcallbitrate = default_maxcallbitrate;
15032 user->prefs = default_prefs;
15033 /* set default context */
15034 strcpy(user->context, default_context);
15035 strcpy(user->language, default_language);
15036 strcpy(user->mohinterpret, default_mohinterpret);
15037 strcpy(user->mohsuggest, default_mohsuggest);
15038 for (; v; v = v->next) {
15039 if (handle_common_options(&userflags[0], &mask[0], v))
15040 continue;
15042 if (!strcasecmp(v->name, "context")) {
15043 ast_copy_string(user->context, v->value, sizeof(user->context));
15044 } else if (!strcasecmp(v->name, "subscribecontext")) {
15045 ast_copy_string(user->subscribecontext, v->value, sizeof(user->subscribecontext));
15046 } else if (!strcasecmp(v->name, "setvar")) {
15047 varname = ast_strdupa(v->value);
15048 if ((varval = strchr(varname,'='))) {
15049 *varval++ = '\0';
15050 if ((tmpvar = ast_variable_new(varname, varval))) {
15051 tmpvar->next = user->chanvars;
15052 user->chanvars = tmpvar;
15055 } else if (!strcasecmp(v->name, "permit") ||
15056 !strcasecmp(v->name, "deny")) {
15057 user->ha = ast_append_ha(v->name, v->value, user->ha);
15058 } else if (!strcasecmp(v->name, "allowtransfer")) {
15059 user->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
15060 } else if (!strcasecmp(v->name, "secret")) {
15061 ast_copy_string(user->secret, v->value, sizeof(user->secret));
15062 } else if (!strcasecmp(v->name, "md5secret")) {
15063 ast_copy_string(user->md5secret, v->value, sizeof(user->md5secret));
15064 } else if (!strcasecmp(v->name, "callerid")) {
15065 ast_callerid_split(v->value, user->cid_name, sizeof(user->cid_name), user->cid_num, sizeof(user->cid_num));
15066 } else if (!strcasecmp(v->name, "callgroup")) {
15067 user->callgroup = ast_get_group(v->value);
15068 } else if (!strcasecmp(v->name, "pickupgroup")) {
15069 user->pickupgroup = ast_get_group(v->value);
15070 } else if (!strcasecmp(v->name, "language")) {
15071 ast_copy_string(user->language, v->value, sizeof(user->language));
15072 } else if (!strcasecmp(v->name, "mohinterpret")
15073 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
15074 ast_copy_string(user->mohinterpret, v->value, sizeof(user->mohinterpret));
15075 } else if (!strcasecmp(v->name, "mohsuggest")) {
15076 ast_copy_string(user->mohsuggest, v->value, sizeof(user->mohsuggest));
15077 } else if (!strcasecmp(v->name, "accountcode")) {
15078 ast_copy_string(user->accountcode, v->value, sizeof(user->accountcode));
15079 } else if (!strcasecmp(v->name, "call-limit")) {
15080 user->call_limit = atoi(v->value);
15081 if (user->call_limit < 0)
15082 user->call_limit = 0;
15083 } else if (!strcasecmp(v->name, "amaflags")) {
15084 format = ast_cdr_amaflags2int(v->value);
15085 if (format < 0) {
15086 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
15087 } else {
15088 user->amaflags = format;
15090 } else if (!strcasecmp(v->name, "allow")) {
15091 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
15092 } else if (!strcasecmp(v->name, "disallow")) {
15093 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 0);
15094 } else if (!strcasecmp(v->name, "callingpres")) {
15095 user->callingpres = ast_parse_caller_presentation(v->value);
15096 if (user->callingpres == -1)
15097 user->callingpres = atoi(v->value);
15098 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
15099 user->maxcallbitrate = atoi(v->value);
15100 if (user->maxcallbitrate < 0)
15101 user->maxcallbitrate = default_maxcallbitrate;
15102 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
15103 if (ast_true(v->value)) {
15104 ast_set_flag(&user->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
15105 } else
15106 ast_clear_flag(&user->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
15107 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
15108 if (ast_true(v->value)) {
15109 ast_set_flag(&user->flags[1], SIP_PAGE2_T38SUPPORT_RTP);
15110 } else
15111 ast_clear_flag(&user->flags[1], SIP_PAGE2_T38SUPPORT_RTP);
15112 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
15113 if (ast_true(v->value)) {
15114 ast_set_flag(&user->flags[1], SIP_PAGE2_T38SUPPORT_TCP);
15115 } else
15116 ast_clear_flag(&user->flags[1], SIP_PAGE2_T38SUPPORT_TCP);
15119 ast_copy_flags(&user->flags[0], &userflags[0], mask[0].flags);
15120 ast_copy_flags(&user->flags[1], &userflags[1], mask[1].flags);
15121 if (ast_test_flag(&user->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
15122 global_allowsubscribe = TRUE; /* No global ban any more */
15123 ast_free_ha(oldha);
15124 return user;
15127 /*! \brief Set peer defaults before configuring specific configurations */
15128 static void set_peer_defaults(struct sip_peer *peer)
15130 if (peer->expire == 0) {
15131 /* Don't reset expire or port time during reload
15132 if we have an active registration
15134 peer->expire = -1;
15135 peer->pokeexpire = -1;
15136 peer->addr.sin_port = htons(DEFAULT_SIP_PORT);
15138 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
15139 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15140 strcpy(peer->context, default_context);
15141 strcpy(peer->subscribecontext, default_subscribecontext);
15142 strcpy(peer->language, default_language);
15143 strcpy(peer->mohinterpret, default_mohinterpret);
15144 strcpy(peer->mohsuggest, default_mohsuggest);
15145 peer->addr.sin_family = AF_INET;
15146 peer->defaddr.sin_family = AF_INET;
15147 peer->capability = global_capability;
15148 peer->maxcallbitrate = default_maxcallbitrate;
15149 peer->rtptimeout = global_rtptimeout;
15150 peer->rtpholdtimeout = global_rtpholdtimeout;
15151 peer->rtpkeepalive = global_rtpkeepalive;
15152 peer->allowtransfer = global_allowtransfer;
15153 strcpy(peer->vmexten, default_vmexten);
15154 peer->secret[0] = '\0';
15155 peer->md5secret[0] = '\0';
15156 peer->cid_num[0] = '\0';
15157 peer->cid_name[0] = '\0';
15158 peer->fromdomain[0] = '\0';
15159 peer->fromuser[0] = '\0';
15160 peer->regexten[0] = '\0';
15161 peer->mailbox[0] = '\0';
15162 peer->callgroup = 0;
15163 peer->pickupgroup = 0;
15164 peer->maxms = default_qualify;
15165 peer->prefs = default_prefs;
15168 /*! \brief Create temporary peer (used in autocreatepeer mode) */
15169 static struct sip_peer *temp_peer(const char *name)
15171 struct sip_peer *peer;
15173 if (!(peer = ast_calloc(1, sizeof(*peer))))
15174 return NULL;
15176 apeerobjs++;
15177 ASTOBJ_INIT(peer);
15178 set_peer_defaults(peer);
15180 ast_copy_string(peer->name, name, sizeof(peer->name));
15182 ast_set_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT);
15183 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
15184 peer->prefs = default_prefs;
15185 reg_source_db(peer);
15187 return peer;
15190 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
15191 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime)
15193 struct sip_peer *peer = NULL;
15194 struct ast_ha *oldha = NULL;
15195 int obproxyfound=0;
15196 int found=0;
15197 int format=0; /* Ama flags */
15198 time_t regseconds = 0;
15199 char *varname = NULL, *varval = NULL;
15200 struct ast_variable *tmpvar = NULL;
15201 struct ast_flags peerflags[2] = {{(0)}};
15202 struct ast_flags mask[2] = {{(0)}};
15205 if (!realtime)
15206 /* Note we do NOT use find_peer here, to avoid realtime recursion */
15207 /* We also use a case-sensitive comparison (unlike find_peer) so
15208 that case changes made to the peer name will be properly handled
15209 during reload
15211 peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);
15213 if (peer) {
15214 /* Already in the list, remove it and it will be added back (or FREE'd) */
15215 found++;
15216 } else {
15217 if (!(peer = ast_calloc(1, sizeof(*peer))))
15218 return NULL;
15220 if (realtime)
15221 rpeerobjs++;
15222 else
15223 speerobjs++;
15224 ASTOBJ_INIT(peer);
15226 /* Note that our peer HAS had its reference count incrased */
15228 peer->lastmsgssent = -1;
15229 oldha = peer->ha;
15230 peer->ha = NULL;
15231 set_peer_defaults(peer); /* Set peer defaults */
15232 if (!found && name)
15233 ast_copy_string(peer->name, name, sizeof(peer->name));
15235 /* If we have channel variables, remove them (reload) */
15236 if (peer->chanvars) {
15237 ast_variables_destroy(peer->chanvars);
15238 peer->chanvars = NULL;
15239 /* XXX should unregister ? */
15241 for (; v; v = v->next) {
15242 if (handle_common_options(&peerflags[0], &mask[0], v))
15243 continue;
15244 if (realtime && !strcasecmp(v->name, "regseconds")) {
15245 ast_get_time_t(v->value, &regseconds, 0, NULL);
15246 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
15247 inet_aton(v->value, &(peer->addr.sin_addr));
15248 } else if (realtime && !strcasecmp(v->name, "name"))
15249 ast_copy_string(peer->name, v->value, sizeof(peer->name));
15250 else if (realtime && !strcasecmp(v->name, "fullcontact")) {
15251 ast_copy_string(peer->fullcontact, v->value, sizeof(peer->fullcontact));
15252 ast_set_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT);
15253 } else if (!strcasecmp(v->name, "secret"))
15254 ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
15255 else if (!strcasecmp(v->name, "md5secret"))
15256 ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
15257 else if (!strcasecmp(v->name, "auth"))
15258 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
15259 else if (!strcasecmp(v->name, "callerid")) {
15260 ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
15261 } else if (!strcasecmp(v->name, "context")) {
15262 ast_copy_string(peer->context, v->value, sizeof(peer->context));
15263 } else if (!strcasecmp(v->name, "subscribecontext")) {
15264 ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
15265 } else if (!strcasecmp(v->name, "fromdomain")) {
15266 ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
15267 } else if (!strcasecmp(v->name, "usereqphone")) {
15268 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
15269 } else if (!strcasecmp(v->name, "fromuser")) {
15270 ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
15271 } else if (!strcasecmp(v->name, "host") || !strcasecmp(v->name, "outboundproxy")) {
15272 if (!strcasecmp(v->value, "dynamic")) {
15273 if (!strcasecmp(v->name, "outboundproxy") || obproxyfound) {
15274 ast_log(LOG_WARNING, "You can't have a dynamic outbound proxy, you big silly head at line %d.\n", v->lineno);
15275 } else {
15276 /* They'll register with us */
15277 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
15278 if (!found) {
15279 /* Initialize stuff iff we're not found, otherwise
15280 we keep going with what we had */
15281 memset(&peer->addr.sin_addr, 0, 4);
15282 if (peer->addr.sin_port) {
15283 /* If we've already got a port, make it the default rather than absolute */
15284 peer->defaddr.sin_port = peer->addr.sin_port;
15285 peer->addr.sin_port = 0;
15289 } else {
15290 /* Non-dynamic. Make sure we become that way if we're not */
15291 if (peer->expire > -1)
15292 ast_sched_del(sched, peer->expire);
15293 peer->expire = -1;
15294 ast_clear_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
15295 if (!obproxyfound || !strcasecmp(v->name, "outboundproxy")) {
15296 if (ast_get_ip_or_srv(&peer->addr, v->value, "_sip._udp")) {
15297 ASTOBJ_UNREF(peer, sip_destroy_peer);
15298 return NULL;
15301 if (!strcasecmp(v->name, "outboundproxy"))
15302 obproxyfound=1;
15303 else {
15304 ast_copy_string(peer->tohost, v->value, sizeof(peer->tohost));
15305 if (!peer->addr.sin_port)
15306 peer->addr.sin_port = htons(DEFAULT_SIP_PORT);
15309 } else if (!strcasecmp(v->name, "defaultip")) {
15310 if (ast_get_ip(&peer->defaddr, v->value)) {
15311 ASTOBJ_UNREF(peer, sip_destroy_peer);
15312 return NULL;
15314 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
15315 peer->ha = ast_append_ha(v->name, v->value, peer->ha);
15316 } else if (!strcasecmp(v->name, "port")) {
15317 if (!realtime && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC))
15318 peer->defaddr.sin_port = htons(atoi(v->value));
15319 else
15320 peer->addr.sin_port = htons(atoi(v->value));
15321 } else if (!strcasecmp(v->name, "callingpres")) {
15322 peer->callingpres = ast_parse_caller_presentation(v->value);
15323 if (peer->callingpres == -1)
15324 peer->callingpres = atoi(v->value);
15325 } else if (!strcasecmp(v->name, "username")) {
15326 ast_copy_string(peer->username, v->value, sizeof(peer->username));
15327 } else if (!strcasecmp(v->name, "language")) {
15328 ast_copy_string(peer->language, v->value, sizeof(peer->language));
15329 } else if (!strcasecmp(v->name, "regexten")) {
15330 ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
15331 } else if (!strcasecmp(v->name, "call-limit") || !strcasecmp(v->name, "incominglimit")) {
15332 peer->call_limit = atoi(v->value);
15333 if (peer->call_limit < 0)
15334 peer->call_limit = 0;
15335 } else if (!strcasecmp(v->name, "amaflags")) {
15336 format = ast_cdr_amaflags2int(v->value);
15337 if (format < 0) {
15338 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
15339 } else {
15340 peer->amaflags = format;
15342 } else if (!strcasecmp(v->name, "accountcode")) {
15343 ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
15344 } else if (!strcasecmp(v->name, "mohinterpret")
15345 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
15346 ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
15347 } else if (!strcasecmp(v->name, "mohsuggest")) {
15348 ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
15349 } else if (!strcasecmp(v->name, "mailbox")) {
15350 ast_copy_string(peer->mailbox, v->value, sizeof(peer->mailbox));
15351 } else if (!strcasecmp(v->name, "subscribemwi")) {
15352 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
15353 } else if (!strcasecmp(v->name, "vmexten")) {
15354 ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
15355 } else if (!strcasecmp(v->name, "callgroup")) {
15356 peer->callgroup = ast_get_group(v->value);
15357 } else if (!strcasecmp(v->name, "allowtransfer")) {
15358 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
15359 } else if (!strcasecmp(v->name, "pickupgroup")) {
15360 peer->pickupgroup = ast_get_group(v->value);
15361 } else if (!strcasecmp(v->name, "allow")) {
15362 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
15363 } else if (!strcasecmp(v->name, "disallow")) {
15364 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
15365 } else if (!strcasecmp(v->name, "rtptimeout")) {
15366 if ((sscanf(v->value, "%d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
15367 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
15368 peer->rtptimeout = global_rtptimeout;
15370 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
15371 if ((sscanf(v->value, "%d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
15372 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
15373 peer->rtpholdtimeout = global_rtpholdtimeout;
15375 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
15376 if ((sscanf(v->value, "%d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
15377 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
15378 peer->rtpkeepalive = global_rtpkeepalive;
15380 } else if (!strcasecmp(v->name, "setvar")) {
15381 /* Set peer channel variable */
15382 varname = ast_strdupa(v->value);
15383 if ((varval = strchr(varname, '='))) {
15384 *varval++ = '\0';
15385 if ((tmpvar = ast_variable_new(varname, varval))) {
15386 tmpvar->next = peer->chanvars;
15387 peer->chanvars = tmpvar;
15390 } else if (!strcasecmp(v->name, "qualify")) {
15391 if (!strcasecmp(v->value, "no")) {
15392 peer->maxms = 0;
15393 } else if (!strcasecmp(v->value, "yes")) {
15394 peer->maxms = DEFAULT_MAXMS;
15395 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
15396 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);
15397 peer->maxms = 0;
15399 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
15400 peer->maxcallbitrate = atoi(v->value);
15401 if (peer->maxcallbitrate < 0)
15402 peer->maxcallbitrate = default_maxcallbitrate;
15403 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
15404 if (ast_true(v->value)) {
15405 ast_set_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
15406 } else
15407 ast_clear_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
15408 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
15409 if (ast_true(v->value)) {
15410 ast_set_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_RTP);
15411 } else
15412 ast_clear_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_RTP);
15413 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
15414 if (ast_true(v->value)) {
15415 ast_set_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_TCP);
15416 } else
15417 ast_clear_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_TCP);
15420 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && realtime) {
15421 time_t nowtime = time(NULL);
15423 if ((nowtime - regseconds) > 0) {
15424 destroy_association(peer);
15425 memset(&peer->addr, 0, sizeof(peer->addr));
15426 if (option_debug)
15427 ast_log(LOG_DEBUG, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
15430 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
15431 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
15432 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
15433 global_allowsubscribe = TRUE; /* No global ban any more */
15434 if (!found && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && !ast_test_flag(&peer->flags[0], SIP_REALTIME))
15435 reg_source_db(peer);
15436 ASTOBJ_UNMARK(peer);
15437 ast_free_ha(oldha);
15438 return peer;
15441 /*! \brief Re-read SIP.conf config file
15442 \note This function reloads all config data, except for
15443 active peers (with registrations). They will only
15444 change configuration data at restart, not at reload.
15445 SIP debug and recordhistory state will not change
15447 static int reload_config(enum channelreloadreason reason)
15449 struct ast_config *cfg;
15450 struct ast_variable *v;
15451 struct sip_peer *peer;
15452 struct sip_user *user;
15453 struct ast_hostent ahp;
15454 char *cat, *stringp, *context, *oldregcontext;
15455 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
15456 struct hostent *hp;
15457 int format;
15458 struct ast_flags dummy[2];
15459 int auto_sip_domains = FALSE;
15460 struct sockaddr_in old_bindaddr = bindaddr;
15461 int registry_count = 0, peer_count = 0, user_count = 0;
15462 unsigned int temp_tos = 0;
15463 struct ast_flags debugflag = {0};
15465 cfg = ast_config_load(config);
15467 /* We *must* have a config file otherwise stop immediately */
15468 if (!cfg) {
15469 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
15470 return -1;
15473 /* Initialize copy of current global_regcontext for later use in removing stale contexts */
15474 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
15475 oldregcontext = oldcontexts;
15477 /* Clear all flags before setting default values */
15478 /* Preserve debugging settings for console */
15479 ast_copy_flags(&debugflag, &global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
15480 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
15481 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
15482 ast_copy_flags(&global_flags[1], &debugflag, SIP_PAGE2_DEBUG_CONSOLE);
15484 /* Reset IP addresses */
15485 memset(&bindaddr, 0, sizeof(bindaddr));
15486 memset(&localaddr, 0, sizeof(localaddr));
15487 memset(&externip, 0, sizeof(externip));
15488 memset(&default_prefs, 0 , sizeof(default_prefs));
15489 outboundproxyip.sin_port = htons(DEFAULT_SIP_PORT);
15490 outboundproxyip.sin_family = AF_INET; /* Type of address: IPv4 */
15491 ourport = DEFAULT_SIP_PORT;
15492 srvlookup = DEFAULT_SRVLOOKUP;
15493 global_tos_sip = DEFAULT_TOS_SIP;
15494 global_tos_audio = DEFAULT_TOS_AUDIO;
15495 global_tos_video = DEFAULT_TOS_VIDEO;
15496 externhost[0] = '\0'; /* External host name (for behind NAT DynDNS support) */
15497 externexpire = 0; /* Expiration for DNS re-issuing */
15498 externrefresh = 10;
15499 memset(&outboundproxyip, 0, sizeof(outboundproxyip));
15501 /* Reset channel settings to default before re-configuring */
15502 allow_external_domains = DEFAULT_ALLOW_EXT_DOM; /* Allow external invites */
15503 global_regcontext[0] = '\0';
15504 expiry = DEFAULT_EXPIRY;
15505 global_notifyringing = DEFAULT_NOTIFYRINGING;
15506 global_alwaysauthreject = 0;
15507 global_allowsubscribe = FALSE;
15508 ast_copy_string(global_useragent, DEFAULT_USERAGENT, sizeof(global_useragent));
15509 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
15510 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME))
15511 ast_copy_string(global_realm, DEFAULT_REALM, sizeof(global_realm));
15512 else
15513 ast_copy_string(global_realm, ast_config_AST_SYSTEM_NAME, sizeof(global_realm));
15514 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
15515 compactheaders = DEFAULT_COMPACTHEADERS;
15516 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
15517 global_regattempts_max = 0;
15518 pedanticsipchecking = DEFAULT_PEDANTIC;
15519 global_mwitime = DEFAULT_MWITIME;
15520 autocreatepeer = DEFAULT_AUTOCREATEPEER;
15521 global_allowguest = DEFAULT_ALLOWGUEST;
15522 global_rtptimeout = 0;
15523 global_rtpholdtimeout = 0;
15524 global_rtpkeepalive = 0;
15525 global_allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
15526 global_rtautoclear = 120;
15527 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE); /* Default for peers, users: TRUE */
15528 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP); /* Default for peers, users: TRUE */
15529 ast_set_flag(&global_flags[1], SIP_PAGE2_RTUPDATE);
15531 /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for peers and users */
15532 ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
15533 default_subscribecontext[0] = '\0';
15534 default_language[0] = '\0';
15535 default_fromdomain[0] = '\0';
15536 default_qualify = DEFAULT_QUALIFY;
15537 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
15538 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
15539 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
15540 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
15541 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833); /*!< Default DTMF setting: RFC2833 */
15542 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581); /*!< NAT support if requested by device with rport */
15543 ast_set_flag(&global_flags[0], SIP_CAN_REINVITE); /*!< Allow re-invites */
15545 /* Debugging settings, always default to off */
15546 dumphistory = FALSE;
15547 recordhistory = FALSE;
15548 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
15550 /* Misc settings for the channel */
15551 global_relaxdtmf = FALSE;
15552 global_callevents = FALSE;
15553 global_t1min = DEFAULT_T1MIN;
15555 /* Copy the default jb config over global_jbconf */
15556 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
15558 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT);
15560 /* Read the [general] config section of sip.conf (or from realtime config) */
15561 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
15562 if (handle_common_options(&global_flags[0], &dummy[0], v))
15563 continue;
15564 /* handle jb conf */
15565 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
15566 continue;
15568 /* Create the interface list */
15569 if (!strcasecmp(v->name, "context")) {
15570 ast_copy_string(default_context, v->value, sizeof(default_context));
15571 } else if (!strcasecmp(v->name, "realm")) {
15572 ast_copy_string(global_realm, v->value, sizeof(global_realm));
15573 } else if (!strcasecmp(v->name, "useragent")) {
15574 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
15575 if (option_debug)
15576 ast_log(LOG_DEBUG, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
15577 } else if (!strcasecmp(v->name, "allowtransfer")) {
15578 global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
15579 } else if (!strcasecmp(v->name, "rtcachefriends")) {
15580 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
15581 } else if (!strcasecmp(v->name, "rtsavesysname")) {
15582 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTSAVE_SYSNAME);
15583 } else if (!strcasecmp(v->name, "rtupdate")) {
15584 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTUPDATE);
15585 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
15586 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_IGNOREREGEXPIRE);
15587 } else if (!strcasecmp(v->name, "t1min")) {
15588 global_t1min = atoi(v->value);
15589 } else if (!strcasecmp(v->name, "rtautoclear")) {
15590 int i = atoi(v->value);
15591 if (i > 0)
15592 global_rtautoclear = i;
15593 else
15594 i = 0;
15595 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
15596 } else if (!strcasecmp(v->name, "usereqphone")) {
15597 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
15598 } else if (!strcasecmp(v->name, "relaxdtmf")) {
15599 global_relaxdtmf = ast_true(v->value);
15600 } else if (!strcasecmp(v->name, "checkmwi")) {
15601 if ((sscanf(v->value, "%d", &global_mwitime) != 1) || (global_mwitime < 0)) {
15602 ast_log(LOG_WARNING, "'%s' is not a valid MWI time setting at line %d. Using default (10).\n", v->value, v->lineno);
15603 global_mwitime = DEFAULT_MWITIME;
15605 } else if (!strcasecmp(v->name, "vmexten")) {
15606 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
15607 } else if (!strcasecmp(v->name, "rtptimeout")) {
15608 if ((sscanf(v->value, "%d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
15609 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
15610 global_rtptimeout = 0;
15612 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
15613 if ((sscanf(v->value, "%d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
15614 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
15615 global_rtpholdtimeout = 0;
15617 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
15618 if ((sscanf(v->value, "%d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
15619 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
15620 global_rtpkeepalive = 0;
15622 } else if (!strcasecmp(v->name, "compactheaders")) {
15623 compactheaders = ast_true(v->value);
15624 } else if (!strcasecmp(v->name, "notifymimetype")) {
15625 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
15626 } else if (!strcasecmp(v->name, "notifyringing")) {
15627 global_notifyringing = ast_true(v->value);
15628 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
15629 global_alwaysauthreject = ast_true(v->value);
15630 } else if (!strcasecmp(v->name, "mohinterpret")
15631 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
15632 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
15633 } else if (!strcasecmp(v->name, "mohsuggest")) {
15634 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
15635 } else if (!strcasecmp(v->name, "language")) {
15636 ast_copy_string(default_language, v->value, sizeof(default_language));
15637 } else if (!strcasecmp(v->name, "regcontext")) {
15638 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
15639 stringp = newcontexts;
15640 /* Let's remove any contexts that are no longer defined in regcontext */
15641 cleanup_stale_contexts(stringp, oldregcontext);
15642 /* Create contexts if they don't exist already */
15643 while ((context = strsep(&stringp, "&"))) {
15644 if (!ast_context_find(context))
15645 ast_context_create(NULL, context,"SIP");
15647 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
15648 } else if (!strcasecmp(v->name, "callerid")) {
15649 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
15650 } else if (!strcasecmp(v->name, "fromdomain")) {
15651 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
15652 } else if (!strcasecmp(v->name, "outboundproxy")) {
15653 if (ast_get_ip_or_srv(&outboundproxyip, v->value, "_sip._udp") < 0)
15654 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", v->value);
15655 } else if (!strcasecmp(v->name, "outboundproxyport")) {
15656 /* Port needs to be after IP */
15657 sscanf(v->value, "%d", &format);
15658 outboundproxyip.sin_port = htons(format);
15659 } else if (!strcasecmp(v->name, "autocreatepeer")) {
15660 autocreatepeer = ast_true(v->value);
15661 } else if (!strcasecmp(v->name, "srvlookup")) {
15662 srvlookup = ast_true(v->value);
15663 } else if (!strcasecmp(v->name, "pedantic")) {
15664 pedanticsipchecking = ast_true(v->value);
15665 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
15666 max_expiry = atoi(v->value);
15667 if (max_expiry < 1)
15668 max_expiry = DEFAULT_MAX_EXPIRY;
15669 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
15670 min_expiry = atoi(v->value);
15671 if (min_expiry < 1)
15672 min_expiry = DEFAULT_MIN_EXPIRY;
15673 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
15674 default_expiry = atoi(v->value);
15675 if (default_expiry < 1)
15676 default_expiry = DEFAULT_DEFAULT_EXPIRY;
15677 } else if (!strcasecmp(v->name, "sipdebug")) {
15678 if (ast_true(v->value))
15679 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
15680 } else if (!strcasecmp(v->name, "dumphistory")) {
15681 dumphistory = ast_true(v->value);
15682 } else if (!strcasecmp(v->name, "recordhistory")) {
15683 recordhistory = ast_true(v->value);
15684 } else if (!strcasecmp(v->name, "registertimeout")) {
15685 global_reg_timeout = atoi(v->value);
15686 if (global_reg_timeout < 1)
15687 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
15688 } else if (!strcasecmp(v->name, "registerattempts")) {
15689 global_regattempts_max = atoi(v->value);
15690 } else if (!strcasecmp(v->name, "bindaddr")) {
15691 if (!(hp = ast_gethostbyname(v->value, &ahp))) {
15692 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
15693 } else {
15694 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
15696 } else if (!strcasecmp(v->name, "localnet")) {
15697 struct ast_ha *na;
15698 if (!(na = ast_append_ha("d", v->value, localaddr)))
15699 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
15700 else
15701 localaddr = na;
15702 } else if (!strcasecmp(v->name, "localmask")) {
15703 ast_log(LOG_WARNING, "Use of localmask is no long supported -- use localnet with mask syntax\n");
15704 } else if (!strcasecmp(v->name, "externip")) {
15705 if (!(hp = ast_gethostbyname(v->value, &ahp)))
15706 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
15707 else
15708 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
15709 externexpire = 0;
15710 } else if (!strcasecmp(v->name, "externhost")) {
15711 ast_copy_string(externhost, v->value, sizeof(externhost));
15712 if (!(hp = ast_gethostbyname(externhost, &ahp)))
15713 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
15714 else
15715 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
15716 externexpire = time(NULL);
15717 } else if (!strcasecmp(v->name, "externrefresh")) {
15718 if (sscanf(v->value, "%d", &externrefresh) != 1) {
15719 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
15720 externrefresh = 10;
15722 } else if (!strcasecmp(v->name, "allow")) {
15723 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 1);
15724 } else if (!strcasecmp(v->name, "disallow")) {
15725 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 0);
15726 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
15727 allow_external_domains = ast_true(v->value);
15728 } else if (!strcasecmp(v->name, "autodomain")) {
15729 auto_sip_domains = ast_true(v->value);
15730 } else if (!strcasecmp(v->name, "domain")) {
15731 char *domain = ast_strdupa(v->value);
15732 char *context = strchr(domain, ',');
15734 if (context)
15735 *context++ = '\0';
15737 if (option_debug && ast_strlen_zero(context))
15738 ast_log(LOG_DEBUG, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
15739 if (ast_strlen_zero(domain))
15740 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
15741 else
15742 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, context ? ast_strip(context) : "");
15743 } else if (!strcasecmp(v->name, "register")) {
15744 if (sip_register(v->value, v->lineno) == 0)
15745 registry_count++;
15746 } else if (!strcasecmp(v->name, "tos")) {
15747 if (!ast_str2tos(v->value, &temp_tos)) {
15748 global_tos_sip = temp_tos;
15749 global_tos_audio = temp_tos;
15750 global_tos_video = temp_tos;
15751 ast_log(LOG_WARNING, "tos value at line %d is deprecated. See doc/ip-tos.txt for more information.", v->lineno);
15752 } else
15753 ast_log(LOG_WARNING, "Invalid tos value at line %d, See doc/ip-tos.txt for more information.\n", v->lineno);
15754 } else if (!strcasecmp(v->name, "tos_sip")) {
15755 if (ast_str2tos(v->value, &global_tos_sip))
15756 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, recommended value is 'cs3'. See doc/ip-tos.txt.\n", v->lineno);
15757 } else if (!strcasecmp(v->name, "tos_audio")) {
15758 if (ast_str2tos(v->value, &global_tos_audio))
15759 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, recommended value is 'ef'. See doc/ip-tos.txt.\n", v->lineno);
15760 } else if (!strcasecmp(v->name, "tos_video")) {
15761 if (ast_str2tos(v->value, &global_tos_video))
15762 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, recommended value is 'af41'. See doc/ip-tos.txt.\n", v->lineno);
15763 } else if (!strcasecmp(v->name, "bindport")) {
15764 if (sscanf(v->value, "%d", &ourport) == 1) {
15765 bindaddr.sin_port = htons(ourport);
15766 } else {
15767 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
15769 } else if (!strcasecmp(v->name, "qualify")) {
15770 if (!strcasecmp(v->value, "no")) {
15771 default_qualify = 0;
15772 } else if (!strcasecmp(v->value, "yes")) {
15773 default_qualify = DEFAULT_MAXMS;
15774 } else if (sscanf(v->value, "%d", &default_qualify) != 1) {
15775 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
15776 default_qualify = 0;
15778 } else if (!strcasecmp(v->name, "callevents")) {
15779 global_callevents = ast_true(v->value);
15780 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
15781 default_maxcallbitrate = atoi(v->value);
15782 if (default_maxcallbitrate < 0)
15783 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
15784 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
15785 if (ast_true(v->value)) {
15786 ast_set_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
15788 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
15789 if (ast_true(v->value)) {
15790 ast_set_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_RTP);
15792 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
15793 if (ast_true(v->value)) {
15794 ast_set_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_TCP);
15799 if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
15800 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
15801 allow_external_domains = 1;
15804 /* Build list of authentication to various SIP realms, i.e. service providers */
15805 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
15806 /* Format for authentication is auth = username:password@realm */
15807 if (!strcasecmp(v->name, "auth"))
15808 authl = add_realm_authentication(authl, v->value, v->lineno);
15811 /* Load peers, users and friends */
15812 cat = NULL;
15813 while ( (cat = ast_category_browse(cfg, cat)) ) {
15814 const char *utype;
15815 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
15816 continue;
15817 utype = ast_variable_retrieve(cfg, cat, "type");
15818 if (!utype) {
15819 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
15820 continue;
15821 } else {
15822 int is_user = 0, is_peer = 0;
15823 if (!strcasecmp(utype, "user"))
15824 is_user = 1;
15825 else if (!strcasecmp(utype, "friend"))
15826 is_user = is_peer = 1;
15827 else if (!strcasecmp(utype, "peer"))
15828 is_peer = 1;
15829 else {
15830 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
15831 continue;
15833 if (is_user) {
15834 user = build_user(cat, ast_variable_browse(cfg, cat), 0);
15835 if (user) {
15836 ASTOBJ_CONTAINER_LINK(&userl,user);
15837 ASTOBJ_UNREF(user, sip_destroy_user);
15838 user_count++;
15841 if (is_peer) {
15842 peer = build_peer(cat, ast_variable_browse(cfg, cat), 0);
15843 if (peer) {
15844 ASTOBJ_CONTAINER_LINK(&peerl,peer);
15845 ASTOBJ_UNREF(peer, sip_destroy_peer);
15846 peer_count++;
15851 if (ast_find_ourip(&__ourip, bindaddr)) {
15852 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
15853 return 0;
15855 if (!ntohs(bindaddr.sin_port))
15856 bindaddr.sin_port = ntohs(DEFAULT_SIP_PORT);
15857 bindaddr.sin_family = AF_INET;
15858 ast_mutex_lock(&netlock);
15859 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
15860 close(sipsock);
15861 sipsock = -1;
15863 if (sipsock < 0) {
15864 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
15865 if (sipsock < 0) {
15866 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
15867 } else {
15868 /* Allow SIP clients on the same host to access us: */
15869 const int reuseFlag = 1;
15870 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
15871 (const char*)&reuseFlag,
15872 sizeof reuseFlag);
15874 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
15875 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
15876 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
15877 strerror(errno));
15878 close(sipsock);
15879 sipsock = -1;
15880 } else {
15881 if (option_verbose > 1) {
15882 ast_verbose(VERBOSE_PREFIX_2 "SIP Listening on %s:%d\n",
15883 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
15884 ast_verbose(VERBOSE_PREFIX_2 "Using SIP TOS: %s\n", ast_tos2str(global_tos_sip));
15886 if (setsockopt(sipsock, IPPROTO_IP, IP_TOS, &global_tos_sip, sizeof(global_tos_sip)))
15887 ast_log(LOG_WARNING, "Unable to set SIP TOS to %s\n", ast_tos2str(global_tos_sip));
15891 ast_mutex_unlock(&netlock);
15893 /* Add default domains - host name, IP address and IP:port */
15894 /* Only do this if user added any sip domain with "localdomains" */
15895 /* In order to *not* break backwards compatibility */
15896 /* Some phones address us at IP only, some with additional port number */
15897 if (auto_sip_domains) {
15898 char temp[MAXHOSTNAMELEN];
15900 /* First our default IP address */
15901 if (bindaddr.sin_addr.s_addr)
15902 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
15903 else
15904 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
15906 /* Our extern IP address, if configured */
15907 if (externip.sin_addr.s_addr)
15908 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
15910 /* Extern host name (NAT traversal support) */
15911 if (!ast_strlen_zero(externhost))
15912 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
15914 /* Our host name */
15915 if (!gethostname(temp, sizeof(temp)))
15916 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
15919 /* Release configuration from memory */
15920 ast_config_destroy(cfg);
15922 /* Load the list of manual NOTIFY types to support */
15923 if (notify_types)
15924 ast_config_destroy(notify_types);
15925 notify_types = ast_config_load(notify_config);
15927 /* Done, tell the manager */
15928 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);
15930 return 0;
15933 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
15935 struct sip_pvt *p;
15936 struct ast_udptl *udptl = NULL;
15938 p = chan->tech_pvt;
15939 if (!p)
15940 return NULL;
15942 ast_mutex_lock(&p->lock);
15943 if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
15944 udptl = p->udptl;
15945 ast_mutex_unlock(&p->lock);
15946 return udptl;
15949 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
15951 struct sip_pvt *p;
15953 p = chan->tech_pvt;
15954 if (!p)
15955 return -1;
15956 ast_mutex_lock(&p->lock);
15957 if (udptl)
15958 ast_udptl_get_peer(udptl, &p->udptlredirip);
15959 else
15960 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
15961 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
15962 if (!p->pendinginvite) {
15963 if (option_debug > 2) {
15964 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);
15966 transmit_reinvite_with_t38_sdp(p);
15967 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
15968 if (option_debug > 2) {
15969 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);
15971 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
15974 /* Reset lastrtprx timer */
15975 p->lastrtprx = p->lastrtptx = time(NULL);
15976 ast_mutex_unlock(&p->lock);
15977 return 0;
15980 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite)
15982 struct sip_pvt *p;
15983 int flag = 0;
15985 p = chan->tech_pvt;
15986 if (!p || !pvt->udptl)
15987 return -1;
15989 /* Setup everything on the other side like offered/responded from first side */
15990 ast_mutex_lock(&p->lock);
15991 p->t38.jointcapability = p->t38.peercapability = pvt->t38.jointcapability;
15992 ast_udptl_set_far_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
15993 ast_udptl_set_local_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
15994 ast_udptl_set_error_correction_scheme(p->udptl, ast_udptl_get_error_correction_scheme(pvt->udptl));
15996 if (reinvite) { /* If we are handling sending re-invite to the other side of the bridge */
15997 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
15998 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
15999 flag =1;
16000 } else {
16001 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
16003 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
16004 if (!p->pendinginvite) {
16005 if (option_debug > 2) {
16006 if (flag)
16007 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));
16008 else
16009 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));
16011 transmit_reinvite_with_t38_sdp(p);
16012 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
16013 if (option_debug > 2) {
16014 if (flag)
16015 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));
16016 else
16017 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));
16019 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
16022 /* Reset lastrtprx timer */
16023 p->lastrtprx = p->lastrtptx = time(NULL);
16024 ast_mutex_unlock(&p->lock);
16025 return 0;
16026 } else { /* If we are handling sending 200 OK to the other side of the bridge */
16027 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
16028 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
16029 flag = 1;
16030 } else {
16031 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
16033 if (option_debug > 2) {
16034 if (flag)
16035 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));
16036 else
16037 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));
16039 pvt->t38.state = T38_ENABLED;
16040 p->t38.state = T38_ENABLED;
16041 if (option_debug > 1) {
16042 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", pvt->t38.state, pvt->owner ? pvt->owner->name : "<none>");
16043 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
16045 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
16046 p->lastrtprx = p->lastrtptx = time(NULL);
16047 ast_mutex_unlock(&p->lock);
16048 return 0;
16053 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
16054 static struct ast_rtp *sip_get_rtp_peer(struct ast_channel *chan)
16056 struct sip_pvt *p;
16057 struct ast_rtp *rtp = NULL;
16058 p = chan->tech_pvt;
16059 if (!p)
16060 return NULL;
16061 ast_mutex_lock(&p->lock);
16062 if (p->rtp && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
16063 rtp = p->rtp;
16064 ast_mutex_unlock(&p->lock);
16065 return rtp;
16068 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
16069 static struct ast_rtp *sip_get_vrtp_peer(struct ast_channel *chan)
16071 struct sip_pvt *p;
16072 struct ast_rtp *rtp = NULL;
16073 p = chan->tech_pvt;
16074 if (!p)
16075 return NULL;
16077 ast_mutex_lock(&p->lock);
16078 if (p->vrtp && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
16079 rtp = p->vrtp;
16080 ast_mutex_unlock(&p->lock);
16081 return rtp;
16084 /*! \brief Set the RTP peer for this call */
16085 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
16087 struct sip_pvt *p;
16088 int changed = 0;
16090 p = chan->tech_pvt;
16091 if (!p)
16092 return -1;
16093 ast_mutex_lock(&p->lock);
16094 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) {
16095 /* If we're destroyed, don't bother */
16096 ast_mutex_unlock(&p->lock);
16097 return 0;
16100 /* if this peer cannot handle reinvites of the media stream to devices
16101 that are known to be behind a NAT, then stop the process now
16103 if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
16104 ast_mutex_unlock(&p->lock);
16105 return 0;
16108 if (rtp)
16109 changed |= ast_rtp_get_peer(rtp, &p->redirip);
16110 else
16111 memset(&p->redirip, 0, sizeof(p->redirip));
16112 if (vrtp)
16113 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
16114 else
16115 memset(&p->vredirip, 0, sizeof(p->vredirip));
16116 if (codecs && (p->redircodecs != codecs)) {
16117 p->redircodecs = codecs;
16118 changed = 1;
16120 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
16121 if (chan->_state != AST_STATE_UP) { /* We are in early state */
16122 if (recordhistory)
16123 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
16124 if (option_debug)
16125 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));
16126 } else if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
16127 if (option_debug > 2) {
16128 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));
16130 transmit_reinvite_with_sdp(p);
16131 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
16132 if (option_debug > 2) {
16133 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));
16135 /* We have a pending Invite. Send re-invite when we're done with the invite */
16136 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
16139 /* Reset lastrtprx timer */
16140 p->lastrtprx = p->lastrtptx = time(NULL);
16141 ast_mutex_unlock(&p->lock);
16142 return 0;
16145 static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
16146 static char *descrip_dtmfmode = "SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
16147 static char *app_dtmfmode = "SIPDtmfMode";
16149 static char *app_sipaddheader = "SIPAddHeader";
16150 static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
16152 static char *descrip_sipaddheader = ""
16153 " SIPAddHeader(Header: Content)\n"
16154 "Adds a header to a SIP call placed with DIAL.\n"
16155 "Remember to user the X-header if you are adding non-standard SIP\n"
16156 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
16157 "Adding the wrong headers may jeopardize the SIP dialog.\n"
16158 "Always returns 0\n";
16161 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
16162 static int sip_dtmfmode(struct ast_channel *chan, void *data)
16164 struct sip_pvt *p;
16165 char *mode;
16166 if (data)
16167 mode = (char *)data;
16168 else {
16169 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
16170 return 0;
16172 ast_channel_lock(chan);
16173 if (chan->tech != &sip_tech) {
16174 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
16175 ast_channel_unlock(chan);
16176 return 0;
16178 p = chan->tech_pvt;
16179 if (!p) {
16180 ast_channel_unlock(chan);
16181 return 0;
16183 ast_mutex_lock(&p->lock);
16184 if (!strcasecmp(mode,"info")) {
16185 ast_clear_flag(&p->flags[0], SIP_DTMF);
16186 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
16187 } else if (!strcasecmp(mode,"rfc2833")) {
16188 ast_clear_flag(&p->flags[0], SIP_DTMF);
16189 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
16190 } else if (!strcasecmp(mode,"inband")) {
16191 ast_clear_flag(&p->flags[0], SIP_DTMF);
16192 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
16193 } else
16194 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n",mode);
16195 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
16196 if (!p->vad) {
16197 p->vad = ast_dsp_new();
16198 ast_dsp_set_features(p->vad, DSP_FEATURE_DTMF_DETECT);
16200 } else {
16201 if (p->vad) {
16202 ast_dsp_free(p->vad);
16203 p->vad = NULL;
16206 ast_mutex_unlock(&p->lock);
16207 ast_channel_unlock(chan);
16208 return 0;
16211 /*! \brief Add a SIP header to an outbound INVITE */
16212 static int sip_addheader(struct ast_channel *chan, void *data)
16214 int no = 0;
16215 int ok = FALSE;
16216 char varbuf[30];
16217 char *inbuf = (char *) data;
16219 if (ast_strlen_zero(inbuf)) {
16220 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
16221 return 0;
16223 ast_channel_lock(chan);
16225 /* Check for headers */
16226 while (!ok && no <= 50) {
16227 no++;
16228 snprintf(varbuf, sizeof(varbuf), "_SIPADDHEADER%.2d", no);
16230 if( (pbx_builtin_getvar_helper(chan, (const char *) varbuf) == (const char *) NULL) )
16231 ok = TRUE;
16233 if (ok) {
16234 pbx_builtin_setvar_helper (chan, varbuf, inbuf);
16235 if (sipdebug)
16236 ast_log(LOG_DEBUG,"SIP Header added \"%s\" as %s\n", inbuf, varbuf);
16237 } else {
16238 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
16240 ast_channel_unlock(chan);
16241 return 0;
16244 /*! \brief Transfer call before connect with a 302 redirect
16245 \note Called by the transfer() dialplan application through the sip_transfer()
16246 pbx interface function if the call is in ringing state
16247 \todo Fix this function so that we wait for reply to the REFER and
16248 react to errors, denials or other issues the other end might have.
16250 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
16252 char *cdest;
16253 char *extension, *host, *port;
16254 char tmp[80];
16256 cdest = ast_strdupa(dest);
16258 extension = strsep(&cdest, "@");
16259 host = strsep(&cdest, ":");
16260 port = strsep(&cdest, ":");
16261 if (!extension) {
16262 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
16263 return 0;
16266 /* we'll issue the redirect message here */
16267 if (!host) {
16268 char *localtmp;
16269 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
16270 if (ast_strlen_zero(tmp)) {
16271 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
16272 return 0;
16274 if ((localtmp = strstr(tmp, "sip:")) && (localtmp = strchr(localtmp, '@'))) {
16275 char lhost[80], lport[80];
16276 memset(lhost, 0, sizeof(lhost));
16277 memset(lport, 0, sizeof(lport));
16278 localtmp++;
16279 /* This is okey because lhost and lport are as big as tmp */
16280 sscanf(localtmp, "%[^<>:; ]:%[^<>:; ]", lhost, lport);
16281 if (ast_strlen_zero(lhost)) {
16282 ast_log(LOG_ERROR, "Can't find the host address\n");
16283 return 0;
16285 host = ast_strdupa(lhost);
16286 if (!ast_strlen_zero(lport)) {
16287 port = ast_strdupa(lport);
16292 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
16293 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
16295 /* this is all that we want to send to that SIP device */
16296 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
16298 /* hangup here */
16299 return -1;
16302 /*! \brief Return SIP UA's codec (part of the RTP interface) */
16303 static int sip_get_codec(struct ast_channel *chan)
16305 struct sip_pvt *p = chan->tech_pvt;
16306 return p->peercapability;
16309 /*! \brief Send a poke to all known peers
16310 Space them out 100 ms apart
16311 XXX We might have a cool algorithm for this or use random - any suggestions?
16313 static void sip_poke_all_peers(void)
16315 int ms = 0;
16317 if (!speerobjs) /* No peers, just give up */
16318 return;
16320 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
16321 ASTOBJ_WRLOCK(iterator);
16322 if (iterator->pokeexpire > -1)
16323 ast_sched_del(sched, iterator->pokeexpire);
16324 ms += 100;
16325 iterator->pokeexpire = ast_sched_add(sched, ms, sip_poke_peer_s, iterator);
16326 ASTOBJ_UNLOCK(iterator);
16327 } while (0)
16331 /*! \brief Send all known registrations */
16332 static void sip_send_all_registers(void)
16334 int ms;
16335 int regspacing;
16336 if (!regobjs)
16337 return;
16338 regspacing = default_expiry * 1000/regobjs;
16339 if (regspacing > 100)
16340 regspacing = 100;
16341 ms = regspacing;
16342 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
16343 ASTOBJ_WRLOCK(iterator);
16344 if (iterator->expire > -1)
16345 ast_sched_del(sched, iterator->expire);
16346 ms += regspacing;
16347 iterator->expire = ast_sched_add(sched, ms, sip_reregister, iterator);
16348 ASTOBJ_UNLOCK(iterator);
16349 } while (0)
16353 /*! \brief Reload module */
16354 static int sip_do_reload(enum channelreloadreason reason)
16356 if (option_debug > 3)
16357 ast_log(LOG_DEBUG, "--------------- SIP reload started\n");
16359 clear_realm_authentication(authl);
16360 clear_sip_domains();
16361 authl = NULL;
16363 /* First, destroy all outstanding registry calls */
16364 /* This is needed, since otherwise active registry entries will not be destroyed */
16365 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
16366 ASTOBJ_RDLOCK(iterator);
16367 if (iterator->call) {
16368 if (option_debug > 2)
16369 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
16370 /* This will also remove references to the registry */
16371 sip_destroy(iterator->call);
16373 ASTOBJ_UNLOCK(iterator);
16374 } while(0));
16376 /* Then, actually destroy users and registry */
16377 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
16378 if (option_debug > 3)
16379 ast_log(LOG_DEBUG, "--------------- Done destroying user list\n");
16380 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
16381 if (option_debug > 3)
16382 ast_log(LOG_DEBUG, "--------------- Done destroying registry list\n");
16383 ASTOBJ_CONTAINER_MARKALL(&peerl);
16384 reload_config(reason);
16386 /* Prune peers who still are supposed to be deleted */
16387 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
16388 if (option_debug > 3)
16389 ast_log(LOG_DEBUG, "--------------- Done destroying pruned peers\n");
16391 /* Send qualify (OPTIONS) to all peers */
16392 sip_poke_all_peers();
16394 /* Register with all services */
16395 sip_send_all_registers();
16397 if (option_debug > 3)
16398 ast_log(LOG_DEBUG, "--------------- SIP reload done\n");
16400 return 0;
16403 /*! \brief Force reload of module from cli */
16404 static int sip_reload(int fd, int argc, char *argv[])
16407 ast_mutex_lock(&sip_reload_lock);
16408 if (sip_reloading) {
16409 ast_verbose("Previous SIP reload not yet done\n");
16410 } else {
16411 sip_reloading = TRUE;
16412 if (fd)
16413 sip_reloadreason = CHANNEL_CLI_RELOAD;
16414 else
16415 sip_reloadreason = CHANNEL_MODULE_RELOAD;
16417 ast_mutex_unlock(&sip_reload_lock);
16418 restart_monitor();
16420 return 0;
16423 /*! \brief reload: Part of Asterisk module interface */
16424 static int reload(void)
16426 return sip_reload(0, 0, NULL);
16429 static struct ast_cli_entry my_clis[] = {
16430 { { "sip", "notify", NULL }, sip_notify, "Send a notify packet to a SIP peer", notify_usage, complete_sipnotify },
16431 { { "sip", "show", "objects", NULL }, sip_show_objects, "Show all SIP object allocations", show_objects_usage },
16432 { { "sip", "show", "users", NULL }, sip_show_users, "Show defined SIP users", show_users_usage },
16433 { { "sip", "show", "user", NULL }, sip_show_user, "Show details on specific SIP user", show_user_usage, complete_sip_show_user },
16434 { { "sip", "show", "subscriptions", NULL }, sip_show_subscriptions, "Show active SIP subscriptions", show_subscriptions_usage},
16435 { { "sip", "show", "channels", NULL }, sip_show_channels, "Show active SIP channels", show_channels_usage},
16436 { { "sip", "show", "channel", NULL }, sip_show_channel, "Show detailed SIP channel info", show_channel_usage, complete_sipch },
16437 { { "sip", "show", "history", NULL }, sip_show_history, "Show SIP dialog history", show_history_usage, complete_sipch },
16438 { { "sip", "show", "domains", NULL }, sip_show_domains, "List our local SIP domains.", show_domains_usage },
16439 { { "sip", "show", "settings", NULL }, sip_show_settings, "Show SIP global settings", show_settings_usage },
16440 { { "sip", "debug", NULL }, sip_do_debug, "Enable SIP debugging", debug_usage },
16441 { { "sip", "debug", "ip", NULL }, sip_do_debug, "Enable SIP debugging on IP", debug_usage },
16442 { { "sip", "debug", "peer", NULL }, sip_do_debug, "Enable SIP debugging on Peername", debug_usage, complete_sip_debug_peer },
16443 { { "sip", "show", "peer", NULL }, sip_show_peer, "Show details on specific SIP peer", show_peer_usage, complete_sip_show_peer },
16444 { { "sip", "show", "peers", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage },
16445 { { "sip", "prune", "realtime", NULL }, sip_prune_realtime,
16446 "Prune cached Realtime object(s)", prune_realtime_usage },
16447 { { "sip", "prune", "realtime", "peer", NULL }, sip_prune_realtime,
16448 "Prune cached Realtime peer(s)", prune_realtime_usage, complete_sip_prune_realtime_peer },
16449 { { "sip", "prune", "realtime", "user", NULL }, sip_prune_realtime,
16450 "Prune cached Realtime user(s)", prune_realtime_usage, complete_sip_prune_realtime_user },
16451 { { "sip", "show", "inuse", NULL }, sip_show_inuse, "List all inuse/limits", show_inuse_usage },
16452 { { "sip", "show", "registry", NULL }, sip_show_registry, "Show SIP registration status", show_reg_usage },
16453 { { "sip", "history", NULL }, sip_do_history, "Enable SIP history", history_usage },
16454 { { "sip", "no", "history", NULL }, sip_no_history, "Disable SIP history", no_history_usage },
16455 { { "sip", "no", "debug", NULL }, sip_no_debug, "Disable SIP debugging", no_debug_usage },
16456 { { "sip", "reload", NULL }, sip_reload, "Reload SIP configuration", sip_reload_usage },
16459 /*! \brief load_module: PBX load module - initialization */
16460 static int load_module(void)
16462 ASTOBJ_CONTAINER_INIT(&userl); /* User object list */
16463 ASTOBJ_CONTAINER_INIT(&peerl); /* Peer object list */
16464 ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list */
16466 sched = sched_context_create();
16467 if (!sched) {
16468 ast_log(LOG_WARNING, "Unable to create schedule context\n");
16471 io = io_context_create();
16472 if (!io) {
16473 ast_log(LOG_WARNING, "Unable to create I/O context\n");
16475 sip_reloadreason = CHANNEL_MODULE_LOAD;
16476 reload_config(sip_reloadreason); /* Load the configuration from sip.conf */
16478 /* Make sure we can register our sip channel type */
16479 if (ast_channel_register(&sip_tech)) {
16480 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
16481 return -1;
16484 /* Register all CLI functions for SIP */
16485 ast_cli_register_multiple(my_clis, sizeof(my_clis)/ sizeof(my_clis[0]));
16487 /* Tell the RTP subdriver that we're here */
16488 ast_rtp_proto_register(&sip_rtp);
16490 /* Tell the UDPTL subdriver that we're here */
16491 ast_udptl_proto_register(&sip_udptl);
16493 /* Register dialplan applications */
16494 ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
16495 ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
16497 /* Register dialplan functions */
16498 ast_custom_function_register(&sip_header_function);
16499 ast_custom_function_register(&sippeer_function);
16500 ast_custom_function_register(&sipchaninfo_function);
16501 ast_custom_function_register(&checksipdomain_function);
16503 /* Register manager commands */
16504 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM, manager_sip_show_peers,
16505 "List SIP peers (text format)", mandescr_show_peers);
16506 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM, manager_sip_show_peer,
16507 "Show SIP peer (text format)", mandescr_show_peer);
16509 sip_poke_all_peers();
16510 sip_send_all_registers();
16512 /* And start the monitor for the first time */
16513 restart_monitor();
16515 return 0;
16518 static int unload_module(void)
16520 struct sip_pvt *p, *pl;
16522 /* First, take us out of the channel type list */
16523 ast_channel_unregister(&sip_tech);
16525 ast_custom_function_unregister(&sipchaninfo_function);
16526 ast_custom_function_unregister(&sippeer_function);
16527 ast_custom_function_unregister(&sip_header_function);
16528 ast_custom_function_unregister(&checksipdomain_function);
16530 ast_unregister_application(app_dtmfmode);
16531 ast_unregister_application(app_sipaddheader);
16533 ast_cli_unregister_multiple(my_clis, sizeof(my_clis) / sizeof(my_clis[0]));
16535 ast_rtp_proto_unregister(&sip_rtp);
16537 ast_udptl_proto_unregister(&sip_udptl);
16539 ast_manager_unregister("SIPpeers");
16540 ast_manager_unregister("SIPshowpeer");
16542 ast_mutex_lock(&iflock);
16543 /* Hangup all interfaces if they have an owner */
16544 for (p = iflist; p ; p = p->next) {
16545 if (p->owner)
16546 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
16548 ast_mutex_unlock(&iflock);
16550 ast_mutex_lock(&monlock);
16551 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
16552 pthread_cancel(monitor_thread);
16553 pthread_kill(monitor_thread, SIGURG);
16554 pthread_join(monitor_thread, NULL);
16556 monitor_thread = AST_PTHREADT_STOP;
16557 ast_mutex_unlock(&monlock);
16559 ast_mutex_lock(&iflock);
16560 /* Destroy all the interfaces and free their memory */
16561 p = iflist;
16562 while (p) {
16563 pl = p;
16564 p = p->next;
16565 /* Free associated memory */
16566 ast_mutex_destroy(&pl->lock);
16567 if (pl->chanvars) {
16568 ast_variables_destroy(pl->chanvars);
16569 pl->chanvars = NULL;
16571 free(pl);
16573 iflist = NULL;
16574 ast_mutex_unlock(&iflock);
16576 /* Free memory for local network address mask */
16577 ast_free_ha(localaddr);
16579 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
16580 ASTOBJ_CONTAINER_DESTROY(&userl);
16581 ASTOBJ_CONTAINER_DESTROYALL(&peerl, sip_destroy_peer);
16582 ASTOBJ_CONTAINER_DESTROY(&peerl);
16583 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
16584 ASTOBJ_CONTAINER_DESTROY(&regl);
16586 clear_realm_authentication(authl);
16587 clear_sip_domains();
16588 close(sipsock);
16589 sched_context_destroy(sched);
16591 return 0;
16594 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
16595 .load = load_module,
16596 .unload = unload_module,
16597 .reload = reload,