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.
21 * \brief Implementation of Session Initiation Protocol
23 * \author Mark Spencer <markster@digium.com>
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
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)
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
77 * Outbound calls are set up by the PBX through the sip_request_call()
78 * function. After that, they are activated by sip_call().
81 * The PBX issues a hangup on both incoming and outgoing calls through
82 * the sip_hangup() function
84 * \par Deprecated stuff
85 * This is deprecated and will be removed after the 1.4 release
86 * - the SIPUSERAGENT dialplan variable
87 * - the ALERT_INFO dialplan variable
93 ASTERISK_FILE_VERSION(__FILE__
, "$Revision$")
99 #include <sys/socket.h>
100 #include <sys/ioctl.h>
107 #include <sys/signal.h>
108 #include <netinet/in.h>
109 #include <netinet/in_systm.h>
110 #include <arpa/inet.h>
111 #include <netinet/ip.h>
114 #include "asterisk/lock.h"
115 #include "asterisk/channel.h"
116 #include "asterisk/config.h"
117 #include "asterisk/logger.h"
118 #include "asterisk/module.h"
119 #include "asterisk/pbx.h"
120 #include "asterisk/options.h"
121 #include "asterisk/sched.h"
122 #include "asterisk/io.h"
123 #include "asterisk/rtp.h"
124 #include "asterisk/udptl.h"
125 #include "asterisk/acl.h"
126 #include "asterisk/manager.h"
127 #include "asterisk/callerid.h"
128 #include "asterisk/cli.h"
129 #include "asterisk/app.h"
130 #include "asterisk/musiconhold.h"
131 #include "asterisk/dsp.h"
132 #include "asterisk/features.h"
133 #include "asterisk/srv.h"
134 #include "asterisk/astdb.h"
135 #include "asterisk/causes.h"
136 #include "asterisk/utils.h"
137 #include "asterisk/file.h"
138 #include "asterisk/astobj.h"
139 #include "asterisk/devicestate.h"
140 #include "asterisk/linkedlists.h"
141 #include "asterisk/stringfields.h"
142 #include "asterisk/monitor.h"
143 #include "asterisk/localtime.h"
144 #include "asterisk/abstract_jb.h"
145 #include "asterisk/compiler.h"
146 #include "asterisk/threadstorage.h"
147 #include "asterisk/translate.h"
157 #define VIDEO_CODEC_MASK 0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
158 #ifndef IPTOS_MINCOST
159 #define IPTOS_MINCOST 0x02
162 /* #define VOCAL_DATA_HACK */
164 #define DEFAULT_DEFAULT_EXPIRY 120
165 #define DEFAULT_MIN_EXPIRY 60
166 #define DEFAULT_MAX_EXPIRY 3600
167 #define DEFAULT_REGISTRATION_TIMEOUT 20
168 #define DEFAULT_MAX_FORWARDS "70"
170 /* guard limit must be larger than guard secs */
171 /* guard min must be < 1000, and should be >= 250 */
172 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
173 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
175 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
176 GUARD_PCT turns out to be lower than this, it
177 will use this time instead.
178 This is in milliseconds. */
179 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
180 below EXPIRY_GUARD_LIMIT */
181 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
183 static int min_expiry
= DEFAULT_MIN_EXPIRY
; /*!< Minimum accepted registration time */
184 static int max_expiry
= DEFAULT_MAX_EXPIRY
; /*!< Maximum accepted registration time */
185 static int default_expiry
= DEFAULT_DEFAULT_EXPIRY
;
186 static int expiry
= DEFAULT_EXPIRY
;
189 #define MAX(a,b) ((a) > (b) ? (a) : (b))
192 #define CALLERID_UNKNOWN "Unknown"
194 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
195 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
196 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
198 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
199 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
200 #define SIP_TRANS_TIMEOUT 32000 /*!< SIP request timeout (rfc 3261) 64*T1
201 \todo Use known T1 for timeout (peerpoke)
203 #define DEFAULT_TRANS_TIMEOUT -1 /* Use default SIP transaction timeout */
204 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
206 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
207 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
208 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
210 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
212 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
213 static struct ast_jb_conf default_jbconf
=
217 .resync_threshold
= -1,
220 static struct ast_jb_conf global_jbconf
;
222 static const char config
[] = "sip.conf";
223 static const char notify_config
[] = "sip_notify.conf";
228 /*! \brief Authorization scheme for call transfers
229 \note Not a bitfield flag, since there are plans for other modes,
230 like "only allow transfers for authenticated devices" */
232 TRANSFER_OPENFORALL
, /*!< Allow all SIP transfers */
233 TRANSFER_CLOSED
, /*!< Allow no SIP transfers */
242 /*! \brief States for the INVITE transaction, not the dialog
243 \note this is for the INVITE that sets up the dialog
246 INV_NONE
= 0, /*!< No state at all, maybe not an INVITE dialog */
247 INV_CALLING
= 1, /*!< Invite sent, no answer */
248 INV_PROCEEDING
= 2, /*!< We got/sent 1xx message */
249 INV_EARLY_MEDIA
= 3, /*!< We got 18x message with to-tag back */
250 INV_COMPLETED
= 4, /*!< Got final response with error. Wait for ACK, then CONFIRMED */
251 INV_CONFIRMED
= 5, /*!< Confirmed response - we've got an ack (Incoming calls only) */
252 INV_TERMINATED
= 6, /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done
253 The only way out of this is a BYE from one side */
254 INV_CANCELLED
= 7, /*!< Transaction cancelled by client or server in non-terminated state */
257 /* Do _NOT_ make any changes to this enum, or the array following it;
258 if you think you are doing the right thing, you are probably
259 not doing the right thing. If you think there are changes
260 needed, get someone else to review them first _before_
261 submitting a patch. If these two lists do not match properly
262 bad things will happen.
266 XMIT_CRITICAL
= 2, /*!< Transmit critical SIP message reliably, with re-transmits.
267 If it fails, it's critical and will cause a teardown of the session */
268 XMIT_RELIABLE
= 1, /*!< Transmit SIP message reliably, with re-transmits */
269 XMIT_UNRELIABLE
= 0, /*!< Transmit SIP message without bothering with re-transmits */
272 enum parse_register_result
{
273 PARSE_REGISTER_FAILED
,
274 PARSE_REGISTER_UPDATE
,
275 PARSE_REGISTER_QUERY
,
278 enum subscriptiontype
{
287 static const struct cfsubscription_types
{
288 enum subscriptiontype type
;
289 const char * const event
;
290 const char * const mediatype
;
291 const char * const text
;
292 } subscription_types
[] = {
293 { NONE
, "-", "unknown", "unknown" },
294 /* RFC 4235: SIP Dialog event package */
295 { DIALOG_INFO_XML
, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
296 { CPIM_PIDF_XML
, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
297 { PIDF_XML
, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
298 { XPIDF_XML
, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
299 { MWI_NOTIFICATION
, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
302 /*! \brief SIP Request methods known by Asterisk */
304 SIP_UNKNOWN
, /* Unknown response */
305 SIP_RESPONSE
, /* Not request, response to outbound request */
311 SIP_PRACK
, /* Not supported at all */
316 SIP_UPDATE
, /* We can send UPDATE; but not accept it */
319 SIP_PUBLISH
, /* Not supported at all */
320 SIP_PING
, /* Not supported at all, no standard but still implemented out there */
323 /*! \brief Authentication types - proxy or www authentication
324 \note Endpoints, like Asterisk, should always use WWW authentication to
325 allow multiple authentications in the same call - to the proxy and
333 /*! \brief Authentication result from check_auth* functions */
334 enum check_auth_result
{
336 AUTH_CHALLENGE_SENT
= 1,
337 AUTH_SECRET_FAILED
= -1,
338 AUTH_USERNAME_MISMATCH
= -2,
341 AUTH_UNKNOWN_DOMAIN
= -5,
344 /*! \brief States for outbound registrations (with register= lines in sip.conf */
345 enum sipregistrystate
{
346 REG_STATE_UNREGISTERED
= 0, /*!< We are not registred */
347 REG_STATE_REGSENT
, /*!< Registration request sent */
348 REG_STATE_AUTHSENT
, /*!< We have tried to authenticate */
349 REG_STATE_REGISTERED
, /*!< Registred and done */
350 REG_STATE_REJECTED
, /*!< Registration rejected */
351 REG_STATE_TIMEOUT
, /*!< Registration timed out */
352 REG_STATE_NOAUTH
, /*!< We have no accepted credentials */
353 REG_STATE_FAILED
, /*!< Registration failed after several tries */
356 #define CAN_NOT_CREATE_DIALOG 0
357 #define CAN_CREATE_DIALOG 1
358 #define CAN_CREATE_DIALOG_UNSUPPORTED_METHOD 2
360 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
361 static const struct cfsip_methods
{
363 int need_rtp
; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
367 { SIP_UNKNOWN
, RTP
, "-UNKNOWN-", CAN_CREATE_DIALOG
},
368 { SIP_RESPONSE
, NO_RTP
, "SIP/2.0", CAN_NOT_CREATE_DIALOG
},
369 { SIP_REGISTER
, NO_RTP
, "REGISTER", CAN_CREATE_DIALOG
},
370 { SIP_OPTIONS
, NO_RTP
, "OPTIONS", CAN_CREATE_DIALOG
},
371 { SIP_NOTIFY
, NO_RTP
, "NOTIFY", CAN_CREATE_DIALOG
},
372 { SIP_INVITE
, RTP
, "INVITE", CAN_CREATE_DIALOG
},
373 { SIP_ACK
, NO_RTP
, "ACK", CAN_NOT_CREATE_DIALOG
},
374 { SIP_PRACK
, NO_RTP
, "PRACK", CAN_NOT_CREATE_DIALOG
},
375 { SIP_BYE
, NO_RTP
, "BYE", CAN_NOT_CREATE_DIALOG
},
376 { SIP_REFER
, NO_RTP
, "REFER", CAN_CREATE_DIALOG
},
377 { SIP_SUBSCRIBE
, NO_RTP
, "SUBSCRIBE", CAN_CREATE_DIALOG
},
378 { SIP_MESSAGE
, NO_RTP
, "MESSAGE", CAN_CREATE_DIALOG
},
379 { SIP_UPDATE
, NO_RTP
, "UPDATE", CAN_NOT_CREATE_DIALOG
},
380 { SIP_INFO
, NO_RTP
, "INFO", CAN_NOT_CREATE_DIALOG
},
381 { SIP_CANCEL
, NO_RTP
, "CANCEL", CAN_NOT_CREATE_DIALOG
},
382 { SIP_PUBLISH
, NO_RTP
, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD
},
383 { SIP_PING
, NO_RTP
, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD
}
386 /*! Define SIP option tags, used in Require: and Supported: headers
387 We need to be aware of these properties in the phones to use
388 the replace: header. We should not do that without knowing
389 that the other end supports it...
390 This is nothing we can configure, we learn by the dialog
391 Supported: header on the REGISTER (peer) or the INVITE
393 We are not using many of these today, but will in the future.
394 This is documented in RFC 3261
397 #define NOT_SUPPORTED 0
399 #define SIP_OPT_REPLACES (1 << 0)
400 #define SIP_OPT_100REL (1 << 1)
401 #define SIP_OPT_TIMER (1 << 2)
402 #define SIP_OPT_EARLY_SESSION (1 << 3)
403 #define SIP_OPT_JOIN (1 << 4)
404 #define SIP_OPT_PATH (1 << 5)
405 #define SIP_OPT_PREF (1 << 6)
406 #define SIP_OPT_PRECONDITION (1 << 7)
407 #define SIP_OPT_PRIVACY (1 << 8)
408 #define SIP_OPT_SDP_ANAT (1 << 9)
409 #define SIP_OPT_SEC_AGREE (1 << 10)
410 #define SIP_OPT_EVENTLIST (1 << 11)
411 #define SIP_OPT_GRUU (1 << 12)
412 #define SIP_OPT_TARGET_DIALOG (1 << 13)
413 #define SIP_OPT_NOREFERSUB (1 << 14)
414 #define SIP_OPT_HISTINFO (1 << 15)
415 #define SIP_OPT_RESPRIORITY (1 << 16)
417 /*! \brief List of well-known SIP options. If we get this in a require,
418 we should check the list and answer accordingly. */
419 static const struct cfsip_options
{
420 int id
; /*!< Bitmap ID */
421 int supported
; /*!< Supported by Asterisk ? */
422 char * const text
; /*!< Text id, as in standard */
423 } sip_options
[] = { /* XXX used in 3 places */
424 /* RFC3891: Replaces: header for transfer */
425 { SIP_OPT_REPLACES
, SUPPORTED
, "replaces" },
426 /* One version of Polycom firmware has the wrong label */
427 { SIP_OPT_REPLACES
, SUPPORTED
, "replace" },
428 /* RFC3262: PRACK 100% reliability */
429 { SIP_OPT_100REL
, NOT_SUPPORTED
, "100rel" },
430 /* RFC4028: SIP Session Timers */
431 { SIP_OPT_TIMER
, NOT_SUPPORTED
, "timer" },
432 /* RFC3959: SIP Early session support */
433 { SIP_OPT_EARLY_SESSION
, NOT_SUPPORTED
, "early-session" },
434 /* RFC3911: SIP Join header support */
435 { SIP_OPT_JOIN
, NOT_SUPPORTED
, "join" },
436 /* RFC3327: Path support */
437 { SIP_OPT_PATH
, NOT_SUPPORTED
, "path" },
438 /* RFC3840: Callee preferences */
439 { SIP_OPT_PREF
, NOT_SUPPORTED
, "pref" },
440 /* RFC3312: Precondition support */
441 { SIP_OPT_PRECONDITION
, NOT_SUPPORTED
, "precondition" },
442 /* RFC3323: Privacy with proxies*/
443 { SIP_OPT_PRIVACY
, NOT_SUPPORTED
, "privacy" },
444 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
445 { SIP_OPT_SDP_ANAT
, NOT_SUPPORTED
, "sdp-anat" },
446 /* RFC3329: Security agreement mechanism */
447 { SIP_OPT_SEC_AGREE
, NOT_SUPPORTED
, "sec_agree" },
448 /* SIMPLE events: RFC4662 */
449 { SIP_OPT_EVENTLIST
, NOT_SUPPORTED
, "eventlist" },
450 /* GRUU: Globally Routable User Agent URI's */
451 { SIP_OPT_GRUU
, NOT_SUPPORTED
, "gruu" },
452 /* RFC4538: Target-dialog */
453 { SIP_OPT_TARGET_DIALOG
,NOT_SUPPORTED
, "tdialog" },
454 /* Disable the REFER subscription, RFC 4488 */
455 { SIP_OPT_NOREFERSUB
, NOT_SUPPORTED
, "norefersub" },
456 /* ietf-sip-history-info-06.txt */
457 { SIP_OPT_HISTINFO
, NOT_SUPPORTED
, "histinfo" },
458 /* ietf-sip-resource-priority-10.txt */
459 { SIP_OPT_RESPRIORITY
, NOT_SUPPORTED
, "resource-priority" },
463 /*! \brief SIP Methods we support */
464 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
466 /*! \brief SIP Extensions we support */
467 #define SUPPORTED_EXTENSIONS "replaces"
469 /*! \brief Standard SIP port from RFC 3261. DO NOT CHANGE THIS */
470 #define STANDARD_SIP_PORT 5060
471 /* Note: in many SIP headers, absence of a port number implies port 5060,
472 * and this is why we cannot change the above constant.
473 * There is a limited number of places in asterisk where we could,
474 * in principle, use a different "default" port number, but
475 * we do not support this feature at the moment.
478 /* Default values, set and reset in reload_config before reading configuration */
479 /* These are default values in the source. There are other recommended values in the
480 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
481 yet encouraging new behaviour on new installations
483 #define DEFAULT_CONTEXT "default"
484 #define DEFAULT_MOHINTERPRET "default"
485 #define DEFAULT_MOHSUGGEST ""
486 #define DEFAULT_VMEXTEN "asterisk"
487 #define DEFAULT_CALLERID "asterisk"
488 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
489 #define DEFAULT_MWITIME 10
490 #define DEFAULT_ALLOWGUEST TRUE
491 #define DEFAULT_SRVLOOKUP FALSE /*!< Recommended setting is ON */
492 #define DEFAULT_COMPACTHEADERS FALSE
493 #define DEFAULT_TOS_SIP 0 /*!< Call signalling packets should be marked as DSCP CS3, but the default is 0 to be compatible with previous versions. */
494 #define DEFAULT_TOS_AUDIO 0 /*!< Audio packets should be marked as DSCP EF (Expedited Forwarding), but the default is 0 to be compatible with previous versions. */
495 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
496 #define DEFAULT_ALLOW_EXT_DOM TRUE
497 #define DEFAULT_REALM "asterisk"
498 #define DEFAULT_NOTIFYRINGING TRUE
499 #define DEFAULT_PEDANTIC FALSE
500 #define DEFAULT_AUTOCREATEPEER FALSE
501 #define DEFAULT_QUALIFY FALSE
502 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
503 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
504 #ifndef DEFAULT_USERAGENT
505 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
509 /* Default setttings are used as a channel setting and as a default when
510 configuring devices */
511 static char default_context
[AST_MAX_CONTEXT
];
512 static char default_subscribecontext
[AST_MAX_CONTEXT
];
513 static char default_language
[MAX_LANGUAGE
];
514 static char default_callerid
[AST_MAX_EXTENSION
];
515 static char default_fromdomain
[AST_MAX_EXTENSION
];
516 static char default_notifymime
[AST_MAX_EXTENSION
];
517 static int default_qualify
; /*!< Default Qualify= setting */
518 static char default_vmexten
[AST_MAX_EXTENSION
];
519 static char default_mohinterpret
[MAX_MUSICCLASS
]; /*!< Global setting for moh class to use when put on hold */
520 static char default_mohsuggest
[MAX_MUSICCLASS
]; /*!< Global setting for moh class to suggest when putting
521 * a bridged channel on hold */
522 static int default_maxcallbitrate
; /*!< Maximum bitrate for call */
523 static struct ast_codec_pref default_prefs
; /*!< Default codec prefs */
525 /* Global settings only apply to the channel */
526 static int global_directrtpsetup
; /*!< Enable support for Direct RTP setup (no re-invites) */
527 static int global_limitonpeers
; /*!< Match call limit on peers only */
528 static int global_rtautoclear
;
529 static int global_notifyringing
; /*!< Send notifications on ringing */
530 static int global_notifyhold
; /*!< Send notifications on hold */
531 static int global_alwaysauthreject
; /*!< Send 401 Unauthorized for all failing requests */
532 static int srvlookup
; /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
533 static int pedanticsipchecking
; /*!< Extra checking ? Default off */
534 static int autocreatepeer
; /*!< Auto creation of peers at registration? Default off. */
535 static int global_relaxdtmf
; /*!< Relax DTMF */
536 static int global_rtptimeout
; /*!< Time out call if no RTP */
537 static int global_rtpholdtimeout
;
538 static int global_rtpkeepalive
; /*!< Send RTP keepalives */
539 static int global_reg_timeout
;
540 static int global_regattempts_max
; /*!< Registration attempts before giving up */
541 static int global_allowguest
; /*!< allow unauthenticated users/peers to connect? */
542 static int global_allowsubscribe
; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
543 the global setting is in globals_flags[1] */
544 static int global_mwitime
; /*!< Time between MWI checks for peers */
545 static unsigned int global_tos_sip
; /*!< IP type of service for SIP packets */
546 static unsigned int global_tos_audio
; /*!< IP type of service for audio RTP packets */
547 static unsigned int global_tos_video
; /*!< IP type of service for video RTP packets */
548 static int compactheaders
; /*!< send compact sip headers */
549 static int recordhistory
; /*!< Record SIP history. Off by default */
550 static int dumphistory
; /*!< Dump history to verbose before destroying SIP dialog */
551 static char global_realm
[MAXHOSTNAMELEN
]; /*!< Default realm */
552 static char global_regcontext
[AST_MAX_CONTEXT
]; /*!< Context for auto-extensions */
553 static char global_useragent
[AST_MAX_EXTENSION
]; /*!< Useragent for the SIP channel */
554 static int allow_external_domains
; /*!< Accept calls to external SIP domains? */
555 static int global_callevents
; /*!< Whether we send manager events or not */
556 static int global_t1min
; /*!< T1 roundtrip time minimum */
557 static int global_autoframing
; /*!< Turn autoframing on or off. */
558 static enum transfermodes global_allowtransfer
; /*!< SIP Refer restriction scheme */
560 /*! \brief Codecs that we support by default: */
561 static int global_capability
= AST_FORMAT_ULAW
| AST_FORMAT_ALAW
| AST_FORMAT_GSM
| AST_FORMAT_H263
;
563 /* Object counters */
564 static int suserobjs
= 0; /*!< Static users */
565 static int ruserobjs
= 0; /*!< Realtime users */
566 static int speerobjs
= 0; /*!< Statis peers */
567 static int rpeerobjs
= 0; /*!< Realtime peers */
568 static int apeerobjs
= 0; /*!< Autocreated peer objects */
569 static int regobjs
= 0; /*!< Registry objects */
571 static struct ast_flags global_flags
[2] = {{0}}; /*!< global SIP_ flags */
573 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
574 AST_MUTEX_DEFINE_STATIC(iflock
);
576 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
577 when it's doing something critical. */
578 AST_MUTEX_DEFINE_STATIC(netlock
);
580 AST_MUTEX_DEFINE_STATIC(monlock
);
582 AST_MUTEX_DEFINE_STATIC(sip_reload_lock
);
584 /*! \brief This is the thread for the monitor which checks for input on the channels
585 which are not currently in use. */
586 static pthread_t monitor_thread
= AST_PTHREADT_NULL
;
588 static int sip_reloading
= FALSE
; /*!< Flag for avoiding multiple reloads at the same time */
589 static enum channelreloadreason sip_reloadreason
; /*!< Reason for last reload/load of configuration */
591 static struct sched_context
*sched
; /*!< The scheduling context */
592 static struct io_context
*io
; /*!< The IO context */
593 static int *sipsock_read_id
; /*!< ID of IO entry for sipsock FD */
595 #define DEC_CALL_LIMIT 0
596 #define INC_CALL_LIMIT 1
597 #define DEC_CALL_RINGING 2
598 #define INC_CALL_RINGING 3
600 /*! \brief sip_request: The data grabbed from the UDP socket */
602 char *rlPart1
; /*!< SIP Method Name or "SIP/2.0" protocol version */
603 char *rlPart2
; /*!< The Request URI or Response Status */
604 int len
; /*!< Length */
605 int headers
; /*!< # of SIP Headers */
606 int method
; /*!< Method of this request */
607 int lines
; /*!< Body Content */
608 unsigned int flags
; /*!< SIP_PKT Flags for this packet */
609 char *header
[SIP_MAX_HEADERS
];
610 char *line
[SIP_MAX_LINES
];
611 char data
[SIP_MAX_PACKET
];
612 unsigned int sdp_start
; /*!< the line number where the SDP begins */
613 unsigned int sdp_end
; /*!< the line number where the SDP ends */
617 * A sip packet is stored into the data[] buffer, with the header followed
618 * by an empty line and the body of the message.
619 * On outgoing packets, data is accumulated in data[] with len reflecting
620 * the next available byte, headers and lines count the number of lines
621 * in both parts. There are no '\0' in data[0..len-1].
623 * On received packet, the input read from the socket is copied into data[],
624 * len is set and the string is NUL-terminated. Then a parser fills up
625 * the other fields -header[] and line[] to point to the lines of the
626 * message, rlPart1 and rlPart2 parse the first lnie as below:
628 * Requests have in the first line METHOD URI SIP/2.0
629 * rlPart1 = method; rlPart2 = uri;
630 * Responses have in the first line SIP/2.0 code description
631 * rlPart1 = SIP/2.0; rlPart2 = code + description;
635 /*! \brief structure used in transfers */
637 struct ast_channel
*chan1
; /*!< First channel involved */
638 struct ast_channel
*chan2
; /*!< Second channel involved */
639 struct sip_request req
; /*!< Request that caused the transfer (REFER) */
640 int seqno
; /*!< Sequence number */
645 /*! \brief Parameters to the transmit_invite function */
646 struct sip_invite_param
{
647 const char *distinctive_ring
; /*!< Distinctive ring header */
648 int addsipheaders
; /*!< Add extra SIP headers */
649 const char *uri_options
; /*!< URI options to add to the URI */
650 const char *vxml_url
; /*!< VXML url for Cisco phones */
651 char *auth
; /*!< Authentication */
652 char *authheader
; /*!< Auth header */
653 enum sip_auth_type auth_type
; /*!< Authentication type */
654 const char *replaces
; /*!< Replaces header for call transfers */
655 int transfer
; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
658 /*! \brief Structure to save routing information for a SIP session */
660 struct sip_route
*next
;
664 /*! \brief Modes for SIP domain handling in the PBX */
666 SIP_DOMAIN_AUTO
, /*!< This domain is auto-configured */
667 SIP_DOMAIN_CONFIG
, /*!< This domain is from configuration */
670 /*! \brief Domain data structure.
671 \note In the future, we will connect this to a configuration tree specific
675 char domain
[MAXHOSTNAMELEN
]; /*!< SIP domain we are responsible for */
676 char context
[AST_MAX_EXTENSION
]; /*!< Incoming context for this domain */
677 enum domain_mode mode
; /*!< How did we find this domain? */
678 AST_LIST_ENTRY(domain
) list
; /*!< List mechanics */
681 static AST_LIST_HEAD_STATIC(domain_list
, domain
); /*!< The SIP domain list */
684 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
686 AST_LIST_ENTRY(sip_history
) list
;
687 char event
[0]; /* actually more, depending on needs */
690 AST_LIST_HEAD_NOLOCK(sip_history_head
, sip_history
); /*!< history list, entry in sip_pvt */
692 /*! \brief sip_auth: Credentials for authentication to other SIP services */
694 char realm
[AST_MAX_EXTENSION
]; /*!< Realm in which these credentials are valid */
695 char username
[256]; /*!< Username */
696 char secret
[256]; /*!< Secret */
697 char md5secret
[256]; /*!< MD5Secret */
698 struct sip_auth
*next
; /*!< Next auth structure in list */
701 /*--- Various flags for the flags field in the pvt structure */
702 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
703 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed by the monitor thread */
704 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
705 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
706 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
707 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
708 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
709 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
710 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
711 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
712 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
713 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
714 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
715 #define SIP_OUTGOING (1 << 13) /*!< Direction of the last transaction in this dialog */
716 #define SIP_FREE_BIT (1 << 14) /*!< ---- */
717 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 15) /*!< Do not hangup at first ast_hangup */
718 #define SIP_DTMF (3 << 16) /*!< DTMF Support: four settings, uses two bits */
719 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DTMF Support: RTP DTMF - "rfc2833" */
720 #define SIP_DTMF_INBAND (1 << 16) /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
721 #define SIP_DTMF_INFO (2 << 16) /*!< DTMF Support: SIP Info messages - "info" */
722 #define SIP_DTMF_AUTO (3 << 16) /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
724 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
725 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
726 #define SIP_NAT_RFC3581 (1 << 18) /*!< NAT RFC3581 */
727 #define SIP_NAT_ROUTE (2 << 18) /*!< NAT Only ROUTE */
728 #define SIP_NAT_ALWAYS (3 << 18) /*!< NAT Both ROUTE and RFC3581 */
729 /* re-INVITE related settings */
730 #define SIP_REINVITE (7 << 20) /*!< three bits used */
731 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
732 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< allow media reinvite when new peer is behind NAT */
733 #define SIP_REINVITE_UPDATE (4 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
734 /* "insecure" settings */
735 #define SIP_INSECURE_PORT (1 << 23) /*!< don't require matching port for incoming requests */
736 #define SIP_INSECURE_INVITE (1 << 24) /*!< don't require authentication for incoming INVITEs */
737 /* Sending PROGRESS in-band settings */
738 #define SIP_PROG_INBAND (3 << 25) /*!< three settings, uses two bits */
739 #define SIP_PROG_INBAND_NEVER (0 << 25)
740 #define SIP_PROG_INBAND_NO (1 << 25)
741 #define SIP_PROG_INBAND_YES (2 << 25)
742 #define SIP_NO_HISTORY (1 << 27) /*!< Suppress recording request/response history */
743 #define SIP_CALL_LIMIT (1 << 28) /*!< Call limit enforced for this call */
744 #define SIP_SENDRPID (1 << 29) /*!< Remote Party-ID Support */
745 #define SIP_INC_COUNT (1 << 30) /*!< Did this connection increment the counter of in-use calls? */
746 #define SIP_G726_NONSTANDARD (1 << 31) /*!< Use non-standard packing for G726-32 data */
748 #define SIP_FLAGS_TO_COPY \
749 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
750 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
751 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
753 /*--- a new page of flags (for flags[1] */
755 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
756 #define SIP_PAGE2_RTUPDATE (1 << 1)
757 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
758 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
759 #define SIP_PAGE2_RTSAVE_SYSNAME (1 << 5)
760 /* Space for addition of other realtime flags in the future */
761 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 10)
762 #define SIP_PAGE2_DEBUG (3 << 11)
763 #define SIP_PAGE2_DEBUG_CONFIG (1 << 11)
764 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 12)
765 #define SIP_PAGE2_DYNAMIC (1 << 13) /*!< Dynamic Peers register with Asterisk */
766 #define SIP_PAGE2_SELFDESTRUCT (1 << 14) /*!< Automatic peers need to destruct themselves */
767 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15)
768 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< Allow subscriptions from this peer? */
769 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< Allow overlap dialing ? */
770 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< Only issue MWI notification if subscribed to */
771 #define SIP_PAGE2_INC_RINGING (1 << 19) /*!< Did this connection increment the counter of in-use calls? */
772 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< T38 Fax Passthrough Support */
773 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< 20: T38 Fax Passthrough Support */
774 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< 21: T38 Fax Passthrough Support (not implemented) */
775 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< 22: T38 Fax Passthrough Support (not implemented) */
776 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< Call states */
777 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (1 << 23) /*!< 23: One directional hold */
778 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (1 << 24) /*!< 24: Inactive */
779 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25) /*!< 25: ???? */
780 #define SIP_PAGE2_BUGGY_MWI (1 << 26) /*!< 26: Buggy CISCO MWI fix */
781 #define SIP_PAGE2_OUTGOING_CALL (1 << 27) /*!< 27: Is this an outgoing call? */
783 #define SIP_PAGE2_FLAGS_TO_COPY \
784 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
785 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI)
787 /* SIP packet flags */
788 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
789 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
790 #define SIP_PKT_IGNORE (1 << 2) /*!< This is a re-transmit, ignore it */
791 #define SIP_PKT_IGNORE_RESP (1 << 3) /*!< Resp ignore - ??? */
792 #define SIP_PKT_IGNORE_REQ (1 << 4) /*!< Req ignore - ??? */
794 /* T.38 set of flags */
795 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
796 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
797 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
798 /* Rate management */
799 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
800 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
801 /* UDP Error correction */
802 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
803 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
804 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
805 /* T38 Spec version */
806 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
807 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
808 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
809 /* Maximum Fax Rate */
810 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
811 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
812 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
813 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
814 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
815 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
817 /*!< This is default: NO MMR and JBIG trancoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
818 static int global_t38_capability
= T38FAX_VERSION_0
| T38FAX_RATE_2400
| T38FAX_RATE_4800
| T38FAX_RATE_7200
| T38FAX_RATE_9600
;
820 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
821 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
822 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
824 /*! \brief T38 States for a call */
826 T38_DISABLED
= 0, /*!< Not enabled */
827 T38_LOCAL_DIRECT
, /*!< Offered from local */
828 T38_LOCAL_REINVITE
, /*!< Offered from local - REINVITE */
829 T38_PEER_DIRECT
, /*!< Offered from peer */
830 T38_PEER_REINVITE
, /*!< Offered from peer - REINVITE */
831 T38_ENABLED
/*!< Negotiated (enabled) */
834 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
835 struct t38properties
{
836 struct ast_flags t38support
; /*!< Flag for udptl, rtp or tcp support for this session */
837 int capability
; /*!< Our T38 capability */
838 int peercapability
; /*!< Peers T38 capability */
839 int jointcapability
; /*!< Supported T38 capability at both ends */
840 enum t38state state
; /*!< T.38 state */
843 /*! \brief Parameters to know status of transfer */
845 REFER_IDLE
, /*!< No REFER is in progress */
846 REFER_SENT
, /*!< Sent REFER to transferee */
847 REFER_RECEIVED
, /*!< Received REFER from transferer */
848 REFER_CONFIRMED
, /*!< Refer confirmed with a 100 TRYING */
849 REFER_ACCEPTED
, /*!< Accepted by transferee */
850 REFER_RINGING
, /*!< Target Ringing */
851 REFER_200OK
, /*!< Answered by transfer target */
852 REFER_FAILED
, /*!< REFER declined - go on */
853 REFER_NOAUTH
/*!< We had no auth for REFER */
856 static const struct c_referstatusstring
{
857 enum referstatus status
;
859 } referstatusstrings
[] = {
860 { REFER_IDLE
, "<none>" },
861 { REFER_SENT
, "Request sent" },
862 { REFER_RECEIVED
, "Request received" },
863 { REFER_ACCEPTED
, "Accepted" },
864 { REFER_RINGING
, "Target ringing" },
865 { REFER_200OK
, "Done" },
866 { REFER_FAILED
, "Failed" },
867 { REFER_NOAUTH
, "Failed - auth failure" }
870 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed */
871 /* OEJ: Should be moved to string fields */
873 char refer_to
[AST_MAX_EXTENSION
]; /*!< Place to store REFER-TO extension */
874 char refer_to_domain
[AST_MAX_EXTENSION
]; /*!< Place to store REFER-TO domain */
875 char refer_to_urioption
[AST_MAX_EXTENSION
]; /*!< Place to store REFER-TO uri options */
876 char refer_to_context
[AST_MAX_EXTENSION
]; /*!< Place to store REFER-TO context */
877 char referred_by
[AST_MAX_EXTENSION
]; /*!< Place to store REFERRED-BY extension */
878 char referred_by_name
[AST_MAX_EXTENSION
]; /*!< Place to store REFERRED-BY extension */
879 char refer_contact
[AST_MAX_EXTENSION
]; /*!< Place to store Contact info from a REFER extension */
880 char replaces_callid
[BUFSIZ
]; /*!< Replace info: callid */
881 char replaces_callid_totag
[BUFSIZ
/2]; /*!< Replace info: to-tag */
882 char replaces_callid_fromtag
[BUFSIZ
/2]; /*!< Replace info: from-tag */
883 struct sip_pvt
*refer_call
; /*!< Call we are referring */
884 int attendedtransfer
; /*!< Attended or blind transfer? */
885 int localtransfer
; /*!< Transfer to local domain? */
886 enum referstatus status
; /*!< REFER status */
889 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
890 static struct sip_pvt
{
891 ast_mutex_t lock
; /*!< Dialog private lock */
892 int method
; /*!< SIP method that opened this dialog */
893 enum invitestates invitestate
; /*!< The state of the INVITE transaction only */
894 AST_DECLARE_STRING_FIELDS(
895 AST_STRING_FIELD(callid
); /*!< Global CallID */
896 AST_STRING_FIELD(randdata
); /*!< Random data */
897 AST_STRING_FIELD(accountcode
); /*!< Account code */
898 AST_STRING_FIELD(realm
); /*!< Authorization realm */
899 AST_STRING_FIELD(nonce
); /*!< Authorization nonce */
900 AST_STRING_FIELD(opaque
); /*!< Opaque nonsense */
901 AST_STRING_FIELD(qop
); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
902 AST_STRING_FIELD(domain
); /*!< Authorization domain */
903 AST_STRING_FIELD(from
); /*!< The From: header */
904 AST_STRING_FIELD(useragent
); /*!< User agent in SIP request */
905 AST_STRING_FIELD(exten
); /*!< Extension where to start */
906 AST_STRING_FIELD(context
); /*!< Context for this call */
907 AST_STRING_FIELD(subscribecontext
); /*!< Subscribecontext */
908 AST_STRING_FIELD(subscribeuri
); /*!< Subscribecontext */
909 AST_STRING_FIELD(fromdomain
); /*!< Domain to show in the from field */
910 AST_STRING_FIELD(fromuser
); /*!< User to show in the user field */
911 AST_STRING_FIELD(fromname
); /*!< Name to show in the user field */
912 AST_STRING_FIELD(tohost
); /*!< Host we should put in the "to" field */
913 AST_STRING_FIELD(language
); /*!< Default language for this call */
914 AST_STRING_FIELD(mohinterpret
); /*!< MOH class to use when put on hold */
915 AST_STRING_FIELD(mohsuggest
); /*!< MOH class to suggest when putting a peer on hold */
916 AST_STRING_FIELD(rdnis
); /*!< Referring DNIS */
917 AST_STRING_FIELD(theirtag
); /*!< Their tag */
918 AST_STRING_FIELD(username
); /*!< [user] name */
919 AST_STRING_FIELD(peername
); /*!< [peer] name, not set if [user] */
920 AST_STRING_FIELD(authname
); /*!< Who we use for authentication */
921 AST_STRING_FIELD(uri
); /*!< Original requested URI */
922 AST_STRING_FIELD(okcontacturi
); /*!< URI from the 200 OK on INVITE */
923 AST_STRING_FIELD(peersecret
); /*!< Password */
924 AST_STRING_FIELD(peermd5secret
);
925 AST_STRING_FIELD(cid_num
); /*!< Caller*ID number */
926 AST_STRING_FIELD(cid_name
); /*!< Caller*ID name */
927 AST_STRING_FIELD(via
); /*!< Via: header */
928 AST_STRING_FIELD(fullcontact
); /*!< The Contact: that the UA registers with us */
929 AST_STRING_FIELD(our_contact
); /*!< Our contact header */
930 AST_STRING_FIELD(rpid
); /*!< Our RPID header */
931 AST_STRING_FIELD(rpid_from
); /*!< Our RPID From header */
933 unsigned int ocseq
; /*!< Current outgoing seqno */
934 unsigned int icseq
; /*!< Current incoming seqno */
935 ast_group_t callgroup
; /*!< Call group */
936 ast_group_t pickupgroup
; /*!< Pickup group */
937 int lastinvite
; /*!< Last Cseq of invite */
938 struct ast_flags flags
[2]; /*!< SIP_ flags */
939 int timer_t1
; /*!< SIP timer T1, ms rtt */
940 unsigned int sipoptions
; /*!< Supported SIP options on the other end */
941 struct ast_codec_pref prefs
; /*!< codec prefs */
942 int capability
; /*!< Special capability (codec) */
943 int jointcapability
; /*!< Supported capability at both ends (codecs) */
944 int peercapability
; /*!< Supported peer capability */
945 int prefcodec
; /*!< Preferred codec (outbound only) */
946 int noncodeccapability
; /*!< DTMF RFC2833 telephony-event */
947 int jointnoncodeccapability
; /*!< Joint Non codec capability */
948 int redircodecs
; /*!< Redirect codecs */
949 int maxcallbitrate
; /*!< Maximum Call Bitrate for Video Calls */
950 struct t38properties t38
; /*!< T38 settings */
951 struct sockaddr_in udptlredirip
; /*!< Where our T.38 UDPTL should be going if not to us */
952 struct ast_udptl
*udptl
; /*!< T.38 UDPTL session */
953 int callingpres
; /*!< Calling presentation */
954 int authtries
; /*!< Times we've tried to authenticate */
955 int expiry
; /*!< How long we take to expire */
956 long branch
; /*!< The branch identifier of this session */
957 char tag
[11]; /*!< Our tag for this session */
958 int sessionid
; /*!< SDP Session ID */
959 int sessionversion
; /*!< SDP Session Version */
960 struct sockaddr_in sa
; /*!< Our peer */
961 struct sockaddr_in redirip
; /*!< Where our RTP should be going if not to us */
962 struct sockaddr_in vredirip
; /*!< Where our Video RTP should be going if not to us */
963 time_t lastrtprx
; /*!< Last RTP received */
964 time_t lastrtptx
; /*!< Last RTP sent */
965 int rtptimeout
; /*!< RTP timeout time */
966 struct sockaddr_in recv
; /*!< Received as */
967 struct in_addr ourip
; /*!< Our IP */
968 struct ast_channel
*owner
; /*!< Who owns us (if we have an owner) */
969 struct sip_route
*route
; /*!< Head of linked list of routing steps (fm Record-Route) */
970 int route_persistant
; /*!< Is this the "real" route? */
971 struct sip_auth
*peerauth
; /*!< Realm authentication */
972 int noncecount
; /*!< Nonce-count */
973 char lastmsg
[256]; /*!< Last Message sent/received */
974 int amaflags
; /*!< AMA Flags */
975 int pendinginvite
; /*!< Any pending invite ? (seqno of this) */
976 struct sip_request initreq
; /*!< Request that opened the latest transaction
977 within this SIP dialog */
979 int maxtime
; /*!< Max time for first response */
980 int initid
; /*!< Auto-congest ID if appropriate (scheduler) */
981 int autokillid
; /*!< Auto-kill ID (scheduler) */
982 enum transfermodes allowtransfer
; /*!< REFER: restriction scheme */
983 struct sip_refer
*refer
; /*!< REFER: SIP transfer data structure */
984 enum subscriptiontype subscribed
; /*!< SUBSCRIBE: Is this dialog a subscription? */
985 int stateid
; /*!< SUBSCRIBE: ID for devicestate subscriptions */
986 int laststate
; /*!< SUBSCRIBE: Last known extension state */
987 int dialogver
; /*!< SUBSCRIBE: Version for subscription dialog-info */
989 struct ast_dsp
*vad
; /*!< Voice Activation Detection dsp */
991 struct sip_peer
*relatedpeer
; /*!< If this dialog is related to a peer, which one
992 Used in peerpoke, mwi subscriptions */
993 struct sip_registry
*registry
; /*!< If this is a REGISTER dialog, to which registry */
994 struct ast_rtp
*rtp
; /*!< RTP Session */
995 struct ast_rtp
*vrtp
; /*!< Video RTP session */
996 struct sip_pkt
*packets
; /*!< Packets scheduled for re-transmission */
997 struct sip_history_head
*history
; /*!< History of this SIP dialog */
998 struct ast_variable
*chanvars
; /*!< Channel variables to set for inbound call */
999 struct sip_pvt
*next
; /*!< Next dialog in chain */
1000 struct sip_invite_param
*options
; /*!< Options for INVITE */
1004 #define FLAG_RESPONSE (1 << 0)
1005 #define FLAG_FATAL (1 << 1)
1007 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */
1009 struct sip_pkt
*next
; /*!< Next packet in linked list */
1010 int retrans
; /*!< Retransmission number */
1011 int method
; /*!< SIP method for this packet */
1012 int seqno
; /*!< Sequence number */
1013 unsigned int flags
; /*!< non-zero if this is a response packet (e.g. 200 OK) */
1014 struct sip_pvt
*owner
; /*!< Owner AST call */
1015 int retransid
; /*!< Retransmission ID */
1016 int timer_a
; /*!< SIP timer A, retransmission timer */
1017 int timer_t1
; /*!< SIP Timer T1, estimated RTT or 500 ms */
1018 int packetlen
; /*!< Length of packet */
1022 /*! \brief Structure for SIP user data. User's place calls to us */
1024 /* Users who can access various contexts */
1025 ASTOBJ_COMPONENTS(struct sip_user
);
1026 char secret
[80]; /*!< Password */
1027 char md5secret
[80]; /*!< Password in md5 */
1028 char context
[AST_MAX_CONTEXT
]; /*!< Default context for incoming calls */
1029 char subscribecontext
[AST_MAX_CONTEXT
]; /* Default context for subscriptions */
1030 char cid_num
[80]; /*!< Caller ID num */
1031 char cid_name
[80]; /*!< Caller ID name */
1032 char accountcode
[AST_MAX_ACCOUNT_CODE
]; /* Account code */
1033 char language
[MAX_LANGUAGE
]; /*!< Default language for this user */
1034 char mohinterpret
[MAX_MUSICCLASS
];/*!< Music on Hold class */
1035 char mohsuggest
[MAX_MUSICCLASS
];/*!< Music on Hold class */
1036 char useragent
[256]; /*!< User agent in SIP request */
1037 struct ast_codec_pref prefs
; /*!< codec prefs */
1038 ast_group_t callgroup
; /*!< Call group */
1039 ast_group_t pickupgroup
; /*!< Pickup Group */
1040 unsigned int sipoptions
; /*!< Supported SIP options */
1041 struct ast_flags flags
[2]; /*!< SIP_ flags */
1042 int amaflags
; /*!< AMA flags for billing */
1043 int callingpres
; /*!< Calling id presentation */
1044 int capability
; /*!< Codec capability */
1045 int inUse
; /*!< Number of calls in use */
1046 int call_limit
; /*!< Limit of concurrent calls */
1047 enum transfermodes allowtransfer
; /*! SIP Refer restriction scheme */
1048 struct ast_ha
*ha
; /*!< ACL setting */
1049 struct ast_variable
*chanvars
; /*!< Variables to set for channel created by user */
1050 int maxcallbitrate
; /*!< Maximum Bitrate for a video call */
1054 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1055 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1057 ASTOBJ_COMPONENTS(struct sip_peer
); /*!< name, refcount, objflags, object pointers */
1058 /*!< peer->name is the unique name of this object */
1059 char secret
[80]; /*!< Password */
1060 char md5secret
[80]; /*!< Password in MD5 */
1061 struct sip_auth
*auth
; /*!< Realm authentication list */
1062 char context
[AST_MAX_CONTEXT
]; /*!< Default context for incoming calls */
1063 char subscribecontext
[AST_MAX_CONTEXT
]; /*!< Default context for subscriptions */
1064 char username
[80]; /*!< Temporary username until registration */
1065 char accountcode
[AST_MAX_ACCOUNT_CODE
]; /*!< Account code */
1066 int amaflags
; /*!< AMA Flags (for billing) */
1067 char tohost
[MAXHOSTNAMELEN
]; /*!< If not dynamic, IP address */
1068 char regexten
[AST_MAX_EXTENSION
]; /*!< Extension to register (if regcontext is used) */
1069 char fromuser
[80]; /*!< From: user when calling this peer */
1070 char fromdomain
[MAXHOSTNAMELEN
]; /*!< From: domain when calling this peer */
1071 char fullcontact
[256]; /*!< Contact registered with us (not in sip.conf) */
1072 char cid_num
[80]; /*!< Caller ID num */
1073 char cid_name
[80]; /*!< Caller ID name */
1074 int callingpres
; /*!< Calling id presentation */
1075 int inUse
; /*!< Number of calls in use */
1076 int inRinging
; /*!< Number of calls ringing */
1077 int onHold
; /*!< Peer has someone on hold */
1078 int call_limit
; /*!< Limit of concurrent calls */
1079 enum transfermodes allowtransfer
; /*! SIP Refer restriction scheme */
1080 char vmexten
[AST_MAX_EXTENSION
]; /*!< Dialplan extension for MWI notify message*/
1081 char mailbox
[AST_MAX_EXTENSION
]; /*!< Mailbox setting for MWI checks */
1082 char language
[MAX_LANGUAGE
]; /*!< Default language for prompts */
1083 char mohinterpret
[MAX_MUSICCLASS
];/*!< Music on Hold class */
1084 char mohsuggest
[MAX_MUSICCLASS
];/*!< Music on Hold class */
1085 char useragent
[256]; /*!< User agent in SIP request (saved from registration) */
1086 struct ast_codec_pref prefs
; /*!< codec prefs */
1088 time_t lastmsgcheck
; /*!< Last time we checked for MWI */
1089 unsigned int sipoptions
; /*!< Supported SIP options */
1090 struct ast_flags flags
[2]; /*!< SIP_ flags */
1091 int expire
; /*!< When to expire this peer registration */
1092 int capability
; /*!< Codec capability */
1093 int rtptimeout
; /*!< RTP timeout */
1094 int rtpholdtimeout
; /*!< RTP Hold Timeout */
1095 int rtpkeepalive
; /*!< Send RTP packets for keepalive */
1096 ast_group_t callgroup
; /*!< Call group */
1097 ast_group_t pickupgroup
; /*!< Pickup group */
1098 struct sockaddr_in addr
; /*!< IP address of peer */
1099 int maxcallbitrate
; /*!< Maximum Bitrate for a video call */
1102 struct sip_pvt
*call
; /*!< Call pointer */
1103 int pokeexpire
; /*!< When to expire poke (qualify= checking) */
1104 int lastms
; /*!< How long last response took (in ms), or -1 for no response */
1105 int maxms
; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1106 struct timeval ps
; /*!< Ping send time */
1108 struct sockaddr_in defaddr
; /*!< Default IP address, used until registration */
1109 struct ast_ha
*ha
; /*!< Access control list */
1110 struct ast_variable
*chanvars
; /*!< Variables to set for channel created by user */
1111 struct sip_pvt
*mwipvt
; /*!< Subscription for MWI */
1118 /*! \brief Registrations with other SIP proxies */
1119 struct sip_registry
{
1120 ASTOBJ_COMPONENTS_FULL(struct sip_registry
,1,1);
1121 AST_DECLARE_STRING_FIELDS(
1122 AST_STRING_FIELD(callid
); /*!< Global Call-ID */
1123 AST_STRING_FIELD(realm
); /*!< Authorization realm */
1124 AST_STRING_FIELD(nonce
); /*!< Authorization nonce */
1125 AST_STRING_FIELD(opaque
); /*!< Opaque nonsense */
1126 AST_STRING_FIELD(qop
); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1127 AST_STRING_FIELD(domain
); /*!< Authorization domain */
1128 AST_STRING_FIELD(username
); /*!< Who we are registering as */
1129 AST_STRING_FIELD(authuser
); /*!< Who we *authenticate* as */
1130 AST_STRING_FIELD(hostname
); /*!< Domain or host we register to */
1131 AST_STRING_FIELD(secret
); /*!< Password in clear text */
1132 AST_STRING_FIELD(md5secret
); /*!< Password in md5 */
1133 AST_STRING_FIELD(contact
); /*!< Contact extension */
1134 AST_STRING_FIELD(random
);
1136 int portno
; /*!< Optional port override */
1137 int expire
; /*!< Sched ID of expiration */
1138 int regattempts
; /*!< Number of attempts (since the last success) */
1139 int timeout
; /*!< sched id of sip_reg_timeout */
1140 int refresh
; /*!< How often to refresh */
1141 struct sip_pvt
*call
; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1142 enum sipregistrystate regstate
; /*!< Registration state (see above) */
1143 time_t regtime
; /*!< Last succesful registration time */
1144 int callid_valid
; /*!< 0 means we haven't chosen callid for this registry yet. */
1145 unsigned int ocseq
; /*!< Sequence number we got to for REGISTERs for this registry */
1146 struct sockaddr_in us
; /*!< Who the server thinks we are */
1147 int noncecount
; /*!< Nonce-count */
1148 char lastmsg
[256]; /*!< Last Message sent/received */
1151 /* --- Linked lists of various objects --------*/
1153 /*! \brief The user list: Users and friends */
1154 static struct ast_user_list
{
1155 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user
);
1158 /*! \brief The peer list: Peers and Friends */
1159 static struct ast_peer_list
{
1160 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer
);
1163 /*! \brief The register list: Other SIP proxys we register with and place calls to */
1164 static struct ast_register_list
{
1165 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry
);
1169 static void temp_pvt_cleanup(void *);
1171 /*! \brief A per-thread temporary pvt structure */
1172 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt
, temp_pvt_init
, temp_pvt_cleanup
);
1174 /*! \todo Move the sip_auth list to AST_LIST */
1175 static struct sip_auth
*authl
= NULL
; /*!< Authentication list for realm authentication */
1178 /* --- Sockets and networking --------------*/
1179 static int sipsock
= -1; /*!< Main socket for SIP network communication */
1180 static struct sockaddr_in bindaddr
= { 0, }; /*!< The address we bind to */
1181 static struct sockaddr_in externip
; /*!< External IP address if we are behind NAT */
1182 static char externhost
[MAXHOSTNAMELEN
]; /*!< External host name (possibly with dynamic DNS and DHCP */
1183 static time_t externexpire
= 0; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1184 static int externrefresh
= 10;
1185 static struct ast_ha
*localaddr
; /*!< List of local networks, on the same side of NAT as this Asterisk */
1186 static struct in_addr __ourip
;
1187 static struct sockaddr_in outboundproxyip
;
1189 static struct sockaddr_in debugaddr
;
1191 static struct ast_config
*notify_types
; /*!< The list of manual NOTIFY types we know how to send */
1193 /*---------------------------- Forward declarations of functions in chan_sip.c */
1194 /*! \note This is added to help splitting up chan_sip.c into several files
1195 in coming releases */
1197 /*--- PBX interface functions */
1198 static struct ast_channel
*sip_request_call(const char *type
, int format
, void *data
, int *cause
);
1199 static int sip_devicestate(void *data
);
1200 static int sip_sendtext(struct ast_channel
*ast
, const char *text
);
1201 static int sip_call(struct ast_channel
*ast
, char *dest
, int timeout
);
1202 static int sip_hangup(struct ast_channel
*ast
);
1203 static int sip_answer(struct ast_channel
*ast
);
1204 static struct ast_frame
*sip_read(struct ast_channel
*ast
);
1205 static int sip_write(struct ast_channel
*ast
, struct ast_frame
*frame
);
1206 static int sip_indicate(struct ast_channel
*ast
, int condition
, const void *data
, size_t datalen
);
1207 static int sip_transfer(struct ast_channel
*ast
, const char *dest
);
1208 static int sip_fixup(struct ast_channel
*oldchan
, struct ast_channel
*newchan
);
1209 static int sip_senddigit_begin(struct ast_channel
*ast
, char digit
);
1210 static int sip_senddigit_end(struct ast_channel
*ast
, char digit
, unsigned int duration
);
1212 /*--- Transmitting responses and requests */
1213 static int sipsock_read(int *id
, int fd
, short events
, void *ignore
);
1214 static int __sip_xmit(struct sip_pvt
*p
, char *data
, int len
);
1215 static int __sip_reliable_xmit(struct sip_pvt
*p
, int seqno
, int resp
, char *data
, int len
, int fatal
, int sipmethod
);
1216 static int __transmit_response(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
, enum xmittype reliable
);
1217 static int retrans_pkt(void *data
);
1218 static int transmit_sip_request(struct sip_pvt
*p
, struct sip_request
*req
);
1219 static int transmit_response_using_temp(ast_string_field callid
, struct sockaddr_in
*sin
, int useglobal_nat
, const int intended_method
, const struct sip_request
*req
, const char *msg
);
1220 static int transmit_response(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
);
1221 static int transmit_response_reliable(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
);
1222 static int transmit_response_with_date(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
);
1223 static int transmit_response_with_sdp(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
, enum xmittype reliable
);
1224 static int transmit_response_with_unsupported(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
, const char *unsupported
);
1225 static int transmit_response_with_auth(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
, const char *rand
, enum xmittype reliable
, const char *header
, int stale
);
1226 static int transmit_response_with_allow(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
, enum xmittype reliable
);
1227 static void transmit_fake_auth_response(struct sip_pvt
*p
, struct sip_request
*req
, int reliable
);
1228 static int transmit_request(struct sip_pvt
*p
, int sipmethod
, int inc
, enum xmittype reliable
, int newbranch
);
1229 static int transmit_request_with_auth(struct sip_pvt
*p
, int sipmethod
, int seqno
, enum xmittype reliable
, int newbranch
);
1230 static int transmit_invite(struct sip_pvt
*p
, int sipmethod
, int sdp
, int init
);
1231 static int transmit_reinvite_with_sdp(struct sip_pvt
*p
);
1232 static int transmit_info_with_digit(struct sip_pvt
*p
, const char digit
, unsigned int duration
);
1233 static int transmit_info_with_vidupdate(struct sip_pvt
*p
);
1234 static int transmit_message_with_text(struct sip_pvt
*p
, const char *text
);
1235 static int transmit_refer(struct sip_pvt
*p
, const char *dest
);
1236 static int transmit_notify_with_mwi(struct sip_pvt
*p
, int newmsgs
, int oldmsgs
, char *vmexten
);
1237 static int transmit_notify_with_sipfrag(struct sip_pvt
*p
, int cseq
, char *message
, int terminate
);
1238 static int transmit_register(struct sip_registry
*r
, int sipmethod
, const char *auth
, const char *authheader
);
1239 static int send_response(struct sip_pvt
*p
, struct sip_request
*req
, enum xmittype reliable
, int seqno
);
1240 static int send_request(struct sip_pvt
*p
, struct sip_request
*req
, enum xmittype reliable
, int seqno
);
1241 static void copy_request(struct sip_request
*dst
, const struct sip_request
*src
);
1242 static void receive_message(struct sip_pvt
*p
, struct sip_request
*req
);
1243 static void parse_moved_contact(struct sip_pvt
*p
, struct sip_request
*req
);
1244 static int sip_send_mwi_to_peer(struct sip_peer
*peer
);
1245 static int does_peer_need_mwi(struct sip_peer
*peer
);
1247 /*--- Dialog management */
1248 static struct sip_pvt
*sip_alloc(ast_string_field callid
, struct sockaddr_in
*sin
,
1249 int useglobal_nat
, const int intended_method
);
1250 static int __sip_autodestruct(void *data
);
1251 static void sip_scheddestroy(struct sip_pvt
*p
, int ms
);
1252 static void sip_cancel_destroy(struct sip_pvt
*p
);
1253 static void sip_destroy(struct sip_pvt
*p
);
1254 static void __sip_destroy(struct sip_pvt
*p
, int lockowner
);
1255 static void __sip_ack(struct sip_pvt
*p
, int seqno
, int resp
, int sipmethod
);
1256 static void __sip_pretend_ack(struct sip_pvt
*p
);
1257 static int __sip_semi_ack(struct sip_pvt
*p
, int seqno
, int resp
, int sipmethod
);
1258 static int auto_congest(void *nothing
);
1259 static int update_call_counter(struct sip_pvt
*fup
, int event
);
1260 static int hangup_sip2cause(int cause
);
1261 static const char *hangup_cause2sip(int cause
);
1262 static struct sip_pvt
*find_call(struct sip_request
*req
, struct sockaddr_in
*sin
, const int intended_method
);
1263 static void free_old_route(struct sip_route
*route
);
1264 static void list_route(struct sip_route
*route
);
1265 static void build_route(struct sip_pvt
*p
, struct sip_request
*req
, int backwards
);
1266 static enum check_auth_result
register_verify(struct sip_pvt
*p
, struct sockaddr_in
*sin
,
1267 struct sip_request
*req
, char *uri
);
1268 static struct sip_pvt
*get_sip_pvt_byid_locked(const char *callid
, const char *totag
, const char *fromtag
);
1269 static void check_pendings(struct sip_pvt
*p
);
1270 static void *sip_park_thread(void *stuff
);
1271 static int sip_park(struct ast_channel
*chan1
, struct ast_channel
*chan2
, struct sip_request
*req
, int seqno
);
1272 static int sip_sipredirect(struct sip_pvt
*p
, const char *dest
);
1274 /*--- Codec handling / SDP */
1275 static void try_suggested_sip_codec(struct sip_pvt
*p
);
1276 static const char* get_sdp_iterate(int* start
, struct sip_request
*req
, const char *name
);
1277 static const char *get_sdp(struct sip_request
*req
, const char *name
);
1278 static int find_sdp(struct sip_request
*req
);
1279 static int process_sdp(struct sip_pvt
*p
, struct sip_request
*req
);
1280 static void add_codec_to_sdp(const struct sip_pvt
*p
, int codec
, int sample_rate
,
1281 char **m_buf
, size_t *m_size
, char **a_buf
, size_t *a_size
,
1282 int debug
, int *min_packet_size
);
1283 static void add_noncodec_to_sdp(const struct sip_pvt
*p
, int format
, int sample_rate
,
1284 char **m_buf
, size_t *m_size
, char **a_buf
, size_t *a_size
,
1286 static enum sip_result
add_sdp(struct sip_request
*resp
, struct sip_pvt
*p
);
1288 /*--- Authentication stuff */
1289 static int reply_digest(struct sip_pvt
*p
, struct sip_request
*req
, char *header
, int sipmethod
, char *digest
, int digest_len
);
1290 static int build_reply_digest(struct sip_pvt
*p
, int method
, char *digest
, int digest_len
);
1291 static enum check_auth_result
check_auth(struct sip_pvt
*p
, struct sip_request
*req
, const char *username
,
1292 const char *secret
, const char *md5secret
, int sipmethod
,
1293 char *uri
, enum xmittype reliable
, int ignore
);
1294 static enum check_auth_result
check_user_full(struct sip_pvt
*p
, struct sip_request
*req
,
1295 int sipmethod
, char *uri
, enum xmittype reliable
,
1296 struct sockaddr_in
*sin
, struct sip_peer
**authpeer
);
1297 static int check_user(struct sip_pvt
*p
, struct sip_request
*req
, int sipmethod
, char *uri
, enum xmittype reliable
, struct sockaddr_in
*sin
);
1299 /*--- Domain handling */
1300 static int check_sip_domain(const char *domain
, char *context
, size_t len
); /* Check if domain is one of our local domains */
1301 static int add_sip_domain(const char *domain
, const enum domain_mode mode
, const char *context
);
1302 static void clear_sip_domains(void);
1304 /*--- SIP realm authentication */
1305 static struct sip_auth
*add_realm_authentication(struct sip_auth
*authlist
, char *configuration
, int lineno
);
1306 static int clear_realm_authentication(struct sip_auth
*authlist
); /* Clear realm authentication list (at reload) */
1307 static struct sip_auth
*find_realm_authentication(struct sip_auth
*authlist
, const char *realm
);
1309 /*--- Misc functions */
1310 static int sip_do_reload(enum channelreloadreason reason
);
1311 static int reload_config(enum channelreloadreason reason
);
1312 static int expire_register(void *data
);
1313 static int sip_sipredirect(struct sip_pvt
*p
, const char *dest
);
1314 static void *do_monitor(void *data
);
1315 static int restart_monitor(void);
1316 static int sip_send_mwi_to_peer(struct sip_peer
*peer
);
1317 static void sip_destroy(struct sip_pvt
*p
);
1318 static int sip_addrcmp(char *name
, struct sockaddr_in
*sin
); /* Support for peer matching */
1319 static int sip_refer_allocate(struct sip_pvt
*p
);
1320 static void ast_quiet_chan(struct ast_channel
*chan
);
1321 static int attempt_transfer(struct sip_dual
*transferer
, struct sip_dual
*target
);
1323 /*--- Device monitoring and Device/extension state handling */
1324 static int cb_extensionstate(char *context
, char* exten
, int state
, void *data
);
1325 static int sip_devicestate(void *data
);
1326 static int sip_poke_noanswer(void *data
);
1327 static int sip_poke_peer(struct sip_peer
*peer
);
1328 static void sip_poke_all_peers(void);
1329 static void sip_peer_hold(struct sip_pvt
*p
, int hold
);
1331 /*--- Applications, functions, CLI and manager command helpers */
1332 static const char *sip_nat_mode(const struct sip_pvt
*p
);
1333 static int sip_show_inuse(int fd
, int argc
, char *argv
[]);
1334 static char *transfermode2str(enum transfermodes mode
) attribute_const
;
1335 static char *nat2str(int nat
) attribute_const
;
1336 static int peer_status(struct sip_peer
*peer
, char *status
, int statuslen
);
1337 static int sip_show_users(int fd
, int argc
, char *argv
[]);
1338 static int _sip_show_peers(int fd
, int *total
, struct mansession
*s
, const struct message
*m
, int argc
, const char *argv
[]);
1339 static int sip_show_peers(int fd
, int argc
, char *argv
[]);
1340 static int sip_show_objects(int fd
, int argc
, char *argv
[]);
1341 static void print_group(int fd
, ast_group_t group
, int crlf
);
1342 static const char *dtmfmode2str(int mode
) attribute_const
;
1343 static const char *insecure2str(int port
, int invite
) attribute_const
;
1344 static void cleanup_stale_contexts(char *new, char *old
);
1345 static void print_codec_to_cli(int fd
, struct ast_codec_pref
*pref
);
1346 static const char *domain_mode_to_text(const enum domain_mode mode
);
1347 static int sip_show_domains(int fd
, int argc
, char *argv
[]);
1348 static int _sip_show_peer(int type
, int fd
, struct mansession
*s
, const struct message
*m
, int argc
, const char *argv
[]);
1349 static int sip_show_peer(int fd
, int argc
, char *argv
[]);
1350 static int sip_show_user(int fd
, int argc
, char *argv
[]);
1351 static int sip_show_registry(int fd
, int argc
, char *argv
[]);
1352 static int sip_show_settings(int fd
, int argc
, char *argv
[]);
1353 static const char *subscription_type2str(enum subscriptiontype subtype
) attribute_pure
;
1354 static const struct cfsubscription_types
*find_subscription_type(enum subscriptiontype subtype
);
1355 static int __sip_show_channels(int fd
, int argc
, char *argv
[], int subscriptions
);
1356 static int sip_show_channels(int fd
, int argc
, char *argv
[]);
1357 static int sip_show_subscriptions(int fd
, int argc
, char *argv
[]);
1358 static int __sip_show_channels(int fd
, int argc
, char *argv
[], int subscriptions
);
1359 static char *complete_sipch(const char *line
, const char *word
, int pos
, int state
);
1360 static char *complete_sip_peer(const char *word
, int state
, int flags2
);
1361 static char *complete_sip_show_peer(const char *line
, const char *word
, int pos
, int state
);
1362 static char *complete_sip_debug_peer(const char *line
, const char *word
, int pos
, int state
);
1363 static char *complete_sip_user(const char *word
, int state
, int flags2
);
1364 static char *complete_sip_show_user(const char *line
, const char *word
, int pos
, int state
);
1365 static char *complete_sipnotify(const char *line
, const char *word
, int pos
, int state
);
1366 static char *complete_sip_prune_realtime_peer(const char *line
, const char *word
, int pos
, int state
);
1367 static char *complete_sip_prune_realtime_user(const char *line
, const char *word
, int pos
, int state
);
1368 static int sip_show_channel(int fd
, int argc
, char *argv
[]);
1369 static int sip_show_history(int fd
, int argc
, char *argv
[]);
1370 static int sip_do_debug_ip(int fd
, int argc
, char *argv
[]);
1371 static int sip_do_debug_peer(int fd
, int argc
, char *argv
[]);
1372 static int sip_do_debug(int fd
, int argc
, char *argv
[]);
1373 static int sip_no_debug(int fd
, int argc
, char *argv
[]);
1374 static int sip_notify(int fd
, int argc
, char *argv
[]);
1375 static int sip_do_history(int fd
, int argc
, char *argv
[]);
1376 static int sip_no_history(int fd
, int argc
, char *argv
[]);
1377 static int func_header_read(struct ast_channel
*chan
, char *function
, char *data
, char *buf
, size_t len
);
1378 static int func_check_sipdomain(struct ast_channel
*chan
, char *cmd
, char *data
, char *buf
, size_t len
);
1379 static int function_sippeer(struct ast_channel
*chan
, char *cmd
, char *data
, char *buf
, size_t len
);
1380 static int function_sipchaninfo_read(struct ast_channel
*chan
, char *cmd
, char *data
, char *buf
, size_t len
);
1381 static int sip_dtmfmode(struct ast_channel
*chan
, void *data
);
1382 static int sip_addheader(struct ast_channel
*chan
, void *data
);
1383 static int sip_do_reload(enum channelreloadreason reason
);
1384 static int sip_reload(int fd
, int argc
, char *argv
[]);
1387 Functions for enabling debug per IP or fully, or enabling history logging for
1390 static void sip_dump_history(struct sip_pvt
*dialog
); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1391 static inline int sip_debug_test_addr(const struct sockaddr_in
*addr
);
1392 static inline int sip_debug_test_pvt(struct sip_pvt
*p
);
1393 static void append_history_full(struct sip_pvt
*p
, const char *fmt
, ...);
1394 static void sip_dump_history(struct sip_pvt
*dialog
);
1396 /*--- Device object handling */
1397 static struct sip_peer
*temp_peer(const char *name
);
1398 static struct sip_peer
*build_peer(const char *name
, struct ast_variable
*v
, struct ast_variable
*alt
, int realtime
);
1399 static struct sip_user
*build_user(const char *name
, struct ast_variable
*v
, int realtime
);
1400 static int update_call_counter(struct sip_pvt
*fup
, int event
);
1401 static void sip_destroy_peer(struct sip_peer
*peer
);
1402 static void sip_destroy_user(struct sip_user
*user
);
1403 static int sip_poke_peer(struct sip_peer
*peer
);
1404 static int sip_poke_peer_s(void *data
);
1405 static void set_peer_defaults(struct sip_peer
*peer
);
1406 static struct sip_peer
*temp_peer(const char *name
);
1407 static void register_peer_exten(struct sip_peer
*peer
, int onoff
);
1408 static struct sip_peer
*find_peer(const char *peer
, struct sockaddr_in
*sin
, int realtime
);
1409 static struct sip_user
*find_user(const char *name
, int realtime
);
1410 static enum parse_register_result
parse_register_contact(struct sip_pvt
*pvt
, struct sip_peer
*p
, struct sip_request
*req
);
1411 static int expire_register(void *data
);
1412 static void reg_source_db(struct sip_peer
*peer
);
1413 static void destroy_association(struct sip_peer
*peer
);
1414 static int handle_common_options(struct ast_flags
*flags
, struct ast_flags
*mask
, struct ast_variable
*v
);
1416 /* Realtime device support */
1417 static void realtime_update_peer(const char *peername
, struct sockaddr_in
*sin
, const char *username
, const char *fullcontact
, int expirey
);
1418 static struct sip_user
*realtime_user(const char *username
);
1419 static void update_peer(struct sip_peer
*p
, int expiry
);
1420 static struct sip_peer
*realtime_peer(const char *peername
, struct sockaddr_in
*sin
);
1421 static int sip_prune_realtime(int fd
, int argc
, char *argv
[]);
1423 /*--- Internal UA client handling (outbound registrations) */
1424 static int ast_sip_ouraddrfor(struct in_addr
*them
, struct in_addr
*us
);
1425 static void sip_registry_destroy(struct sip_registry
*reg
);
1426 static int sip_register(char *value
, int lineno
);
1427 static char *regstate2str(enum sipregistrystate regstate
) attribute_const
;
1428 static int sip_reregister(void *data
);
1429 static int __sip_do_register(struct sip_registry
*r
);
1430 static int sip_reg_timeout(void *data
);
1431 static void sip_send_all_registers(void);
1433 /*--- Parsing SIP requests and responses */
1434 static void append_date(struct sip_request
*req
); /* Append date to SIP packet */
1435 static int determine_firstline_parts(struct sip_request
*req
);
1436 static const struct cfsubscription_types
*find_subscription_type(enum subscriptiontype subtype
);
1437 static const char *gettag(const struct sip_request
*req
, const char *header
, char *tagbuf
, int tagbufsize
);
1438 static int find_sip_method(const char *msg
);
1439 static unsigned int parse_sip_options(struct sip_pvt
*pvt
, const char *supported
);
1440 static void parse_request(struct sip_request
*req
);
1441 static const char *get_header(const struct sip_request
*req
, const char *name
);
1442 static char *referstatus2str(enum referstatus rstatus
) attribute_pure
;
1443 static int method_match(enum sipmethod id
, const char *name
);
1444 static void parse_copy(struct sip_request
*dst
, const struct sip_request
*src
);
1445 static char *get_in_brackets(char *tmp
);
1446 static const char *find_alias(const char *name
, const char *_default
);
1447 static const char *__get_header(const struct sip_request
*req
, const char *name
, int *start
);
1448 static int lws2sws(char *msgbuf
, int len
);
1449 static void extract_uri(struct sip_pvt
*p
, struct sip_request
*req
);
1450 static int get_refer_info(struct sip_pvt
*transferer
, struct sip_request
*outgoing_req
);
1451 static int get_also_info(struct sip_pvt
*p
, struct sip_request
*oreq
);
1452 static int parse_ok_contact(struct sip_pvt
*pvt
, struct sip_request
*req
);
1453 static int set_address_from_contact(struct sip_pvt
*pvt
);
1454 static void check_via(struct sip_pvt
*p
, struct sip_request
*req
);
1455 static char *get_calleridname(const char *input
, char *output
, size_t outputsize
);
1456 static int get_rpid_num(const char *input
, char *output
, int maxlen
);
1457 static int get_rdnis(struct sip_pvt
*p
, struct sip_request
*oreq
);
1458 static int get_destination(struct sip_pvt
*p
, struct sip_request
*oreq
);
1459 static int get_msg_text(char *buf
, int len
, struct sip_request
*req
);
1460 static void free_old_route(struct sip_route
*route
);
1461 static int transmit_state_notify(struct sip_pvt
*p
, int state
, int full
, int timeout
);
1463 /*--- Constructing requests and responses */
1464 static void initialize_initreq(struct sip_pvt
*p
, struct sip_request
*req
);
1465 static int init_req(struct sip_request
*req
, int sipmethod
, const char *recip
);
1466 static int reqprep(struct sip_request
*req
, struct sip_pvt
*p
, int sipmethod
, int seqno
, int newbranch
);
1467 static void initreqprep(struct sip_request
*req
, struct sip_pvt
*p
, int sipmethod
);
1468 static int init_resp(struct sip_request
*resp
, const char *msg
);
1469 static int respprep(struct sip_request
*resp
, struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
);
1470 static const struct sockaddr_in
*sip_real_dst(const struct sip_pvt
*p
);
1471 static void build_via(struct sip_pvt
*p
);
1472 static int create_addr_from_peer(struct sip_pvt
*r
, struct sip_peer
*peer
);
1473 static int create_addr(struct sip_pvt
*dialog
, const char *opeer
);
1474 static char *generate_random_string(char *buf
, size_t size
);
1475 static void build_callid_pvt(struct sip_pvt
*pvt
);
1476 static void build_callid_registry(struct sip_registry
*reg
, struct in_addr ourip
, const char *fromdomain
);
1477 static void make_our_tag(char *tagbuf
, size_t len
);
1478 static int add_header(struct sip_request
*req
, const char *var
, const char *value
);
1479 static int add_header_contentLength(struct sip_request
*req
, int len
);
1480 static int add_line(struct sip_request
*req
, const char *line
);
1481 static int add_text(struct sip_request
*req
, const char *text
);
1482 static int add_digit(struct sip_request
*req
, char digit
, unsigned int duration
);
1483 static int add_vidupdate(struct sip_request
*req
);
1484 static void add_route(struct sip_request
*req
, struct sip_route
*route
);
1485 static int copy_header(struct sip_request
*req
, const struct sip_request
*orig
, const char *field
);
1486 static int copy_all_header(struct sip_request
*req
, const struct sip_request
*orig
, const char *field
);
1487 static int copy_via_headers(struct sip_pvt
*p
, struct sip_request
*req
, const struct sip_request
*orig
, const char *field
);
1488 static void set_destination(struct sip_pvt
*p
, char *uri
);
1489 static void append_date(struct sip_request
*req
);
1490 static void build_contact(struct sip_pvt
*p
);
1491 static void build_rpid(struct sip_pvt
*p
);
1493 /*------Request handling functions */
1494 static int handle_request(struct sip_pvt
*p
, struct sip_request
*req
, struct sockaddr_in
*sin
, int *recount
, int *nounlock
);
1495 static int handle_request_invite(struct sip_pvt
*p
, struct sip_request
*req
, int debug
, int seqno
, struct sockaddr_in
*sin
, int *recount
, char *e
);
1496 static int handle_request_refer(struct sip_pvt
*p
, struct sip_request
*req
, int debug
, int ignore
, int seqno
, int *nounlock
);
1497 static int handle_request_bye(struct sip_pvt
*p
, struct sip_request
*req
);
1498 static int handle_request_register(struct sip_pvt
*p
, struct sip_request
*req
, struct sockaddr_in
*sin
, char *e
);
1499 static int handle_request_cancel(struct sip_pvt
*p
, struct sip_request
*req
);
1500 static int handle_request_message(struct sip_pvt
*p
, struct sip_request
*req
);
1501 static int handle_request_subscribe(struct sip_pvt
*p
, struct sip_request
*req
, struct sockaddr_in
*sin
, int seqno
, char *e
);
1502 static void handle_request_info(struct sip_pvt
*p
, struct sip_request
*req
);
1503 static int handle_request_options(struct sip_pvt
*p
, struct sip_request
*req
);
1504 static int handle_invite_replaces(struct sip_pvt
*p
, struct sip_request
*req
, int debug
, int ignore
, int seqno
, struct sockaddr_in
*sin
);
1505 static int handle_request_notify(struct sip_pvt
*p
, struct sip_request
*req
, struct sockaddr_in
*sin
, int seqno
, char *e
);
1506 static int local_attended_transfer(struct sip_pvt
*transferer
, struct sip_dual
*current
, struct sip_request
*req
, int seqno
);
1508 /*------Response handling functions */
1509 static void handle_response_invite(struct sip_pvt
*p
, int resp
, char *rest
, struct sip_request
*req
, int seqno
);
1510 static void handle_response_refer(struct sip_pvt
*p
, int resp
, char *rest
, struct sip_request
*req
, int seqno
);
1511 static int handle_response_register(struct sip_pvt
*p
, int resp
, char *rest
, struct sip_request
*req
, int ignore
, int seqno
);
1512 static void handle_response(struct sip_pvt
*p
, int resp
, char *rest
, struct sip_request
*req
, int ignore
, int seqno
);
1514 /*----- RTP interface functions */
1515 static int sip_set_rtp_peer(struct ast_channel
*chan
, struct ast_rtp
*rtp
, struct ast_rtp
*vrtp
, int codecs
, int nat_active
);
1516 static enum ast_rtp_get_result
sip_get_rtp_peer(struct ast_channel
*chan
, struct ast_rtp
**rtp
);
1517 static enum ast_rtp_get_result
sip_get_vrtp_peer(struct ast_channel
*chan
, struct ast_rtp
**rtp
);
1518 static int sip_get_codec(struct ast_channel
*chan
);
1519 static struct ast_frame
*sip_rtp_read(struct ast_channel
*ast
, struct sip_pvt
*p
, int *faxdetect
);
1521 /*------ T38 Support --------- */
1522 static int sip_handle_t38_reinvite(struct ast_channel
*chan
, struct sip_pvt
*pvt
, int reinvite
); /*!< T38 negotiation helper function */
1523 static int transmit_response_with_t38_sdp(struct sip_pvt
*p
, char *msg
, struct sip_request
*req
, int retrans
);
1524 static int transmit_reinvite_with_t38_sdp(struct sip_pvt
*p
);
1525 static struct ast_udptl
*sip_get_udptl_peer(struct ast_channel
*chan
);
1526 static int sip_set_udptl_peer(struct ast_channel
*chan
, struct ast_udptl
*udptl
);
1528 /*! \brief Definition of this channel for PBX channel registration */
1529 static const struct ast_channel_tech sip_tech
= {
1531 .description
= "Session Initiation Protocol (SIP)",
1532 .capabilities
= ((AST_FORMAT_MAX_AUDIO
<< 1) - 1),
1533 .properties
= AST_CHAN_TP_WANTSJITTER
| AST_CHAN_TP_CREATESJITTER
,
1534 .requester
= sip_request_call
,
1535 .devicestate
= sip_devicestate
,
1537 .hangup
= sip_hangup
,
1538 .answer
= sip_answer
,
1541 .write_video
= sip_write
,
1542 .indicate
= sip_indicate
,
1543 .transfer
= sip_transfer
,
1545 .send_digit_begin
= sip_senddigit_begin
,
1546 .send_digit_end
= sip_senddigit_end
,
1547 .bridge
= ast_rtp_bridge
,
1548 .send_text
= sip_sendtext
,
1551 /*! \brief This version of the sip channel tech has no send_digit_begin
1552 * callback. This is for use with channels using SIP INFO DTMF so that
1553 * the core knows that the channel doesn't want DTMF BEGIN frames. */
1554 static const struct ast_channel_tech sip_tech_info
= {
1556 .description
= "Session Initiation Protocol (SIP)",
1557 .capabilities
= ((AST_FORMAT_MAX_AUDIO
<< 1) - 1),
1558 .properties
= AST_CHAN_TP_WANTSJITTER
| AST_CHAN_TP_CREATESJITTER
,
1559 .requester
= sip_request_call
,
1560 .devicestate
= sip_devicestate
,
1562 .hangup
= sip_hangup
,
1563 .answer
= sip_answer
,
1566 .write_video
= sip_write
,
1567 .indicate
= sip_indicate
,
1568 .transfer
= sip_transfer
,
1570 .send_digit_end
= sip_senddigit_end
,
1571 .bridge
= ast_rtp_bridge
,
1572 .send_text
= sip_sendtext
,
1575 /**--- some list management macros. **/
1577 #define UNLINK(element, head, prev) do { \
1579 (prev)->next = (element)->next; \
1581 (head) = (element)->next; \
1584 /*! \brief Interface structure with callbacks used to connect to RTP module */
1585 static struct ast_rtp_protocol sip_rtp
= {
1587 get_rtp_info
: sip_get_rtp_peer
,
1588 get_vrtp_info
: sip_get_vrtp_peer
,
1589 set_rtp_peer
: sip_set_rtp_peer
,
1590 get_codec
: sip_get_codec
,
1593 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1594 static struct ast_udptl_protocol sip_udptl
= {
1596 get_udptl_info
: sip_get_udptl_peer
,
1597 set_udptl_peer
: sip_set_udptl_peer
,
1600 /*! \brief Convert transfer status to string */
1601 static char *referstatus2str(enum referstatus rstatus
)
1603 int i
= (sizeof(referstatusstrings
) / sizeof(referstatusstrings
[0]));
1606 for (x
= 0; x
< i
; x
++) {
1607 if (referstatusstrings
[x
].status
== rstatus
)
1608 return (char *) referstatusstrings
[x
].text
;
1613 /*! \brief Initialize the initital request packet in the pvt structure.
1614 This packet is used for creating replies and future requests in
1616 static void initialize_initreq(struct sip_pvt
*p
, struct sip_request
*req
)
1618 if (p
->initreq
.headers
&& option_debug
) {
1619 ast_log(LOG_DEBUG
, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p
->callid
);
1621 /* Use this as the basis */
1622 copy_request(&p
->initreq
, req
);
1623 parse_request(&p
->initreq
);
1624 if (ast_test_flag(req
, SIP_PKT_DEBUG
))
1625 ast_verbose("%d headers, %d lines\n", p
->initreq
.headers
, p
->initreq
.lines
);
1628 static void sip_alreadygone(struct sip_pvt
*dialog
)
1630 if (option_debug
> 2)
1631 ast_log(LOG_DEBUG
, "Setting SIP_ALREADYGONE on dialog %s\n", dialog
->callid
);
1632 ast_set_flag(&dialog
->flags
[0], SIP_ALREADYGONE
);
1636 /*! \brief returns true if 'name' (with optional trailing whitespace)
1637 * matches the sip method 'id'.
1638 * Strictly speaking, SIP methods are case SENSITIVE, but we do
1639 * a case-insensitive comparison to be more tolerant.
1640 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1642 static int method_match(enum sipmethod id
, const char *name
)
1644 int len
= strlen(sip_methods
[id
].text
);
1645 int l_name
= name
? strlen(name
) : 0;
1646 /* true if the string is long enough, and ends with whitespace, and matches */
1647 return (l_name
>= len
&& name
[len
] < 33 &&
1648 !strncasecmp(sip_methods
[id
].text
, name
, len
));
1651 /*! \brief find_sip_method: Find SIP method from header */
1652 static int find_sip_method(const char *msg
)
1656 if (ast_strlen_zero(msg
))
1658 for (i
= 1; i
< (sizeof(sip_methods
) / sizeof(sip_methods
[0])) && !res
; i
++) {
1659 if (method_match(i
, msg
))
1660 res
= sip_methods
[i
].id
;
1665 /*! \brief Parse supported header in incoming packet */
1666 static unsigned int parse_sip_options(struct sip_pvt
*pvt
, const char *supported
)
1670 unsigned int profile
= 0;
1673 if (ast_strlen_zero(supported
) )
1675 temp
= ast_strdupa(supported
);
1677 if (option_debug
> 2 && sipdebug
)
1678 ast_log(LOG_DEBUG
, "Begin: parsing SIP \"Supported: %s\"\n", supported
);
1680 for (next
= temp
; next
; next
= sep
) {
1682 if ( (sep
= strchr(next
, ',')) != NULL
)
1684 next
= ast_skip_blanks(next
);
1685 if (option_debug
> 2 && sipdebug
)
1686 ast_log(LOG_DEBUG
, "Found SIP option: -%s-\n", next
);
1687 for (i
=0; i
< (sizeof(sip_options
) / sizeof(sip_options
[0])); i
++) {
1688 if (!strcasecmp(next
, sip_options
[i
].text
)) {
1689 profile
|= sip_options
[i
].id
;
1691 if (option_debug
> 2 && sipdebug
)
1692 ast_log(LOG_DEBUG
, "Matched SIP option: %s\n", next
);
1696 if (!found
&& option_debug
> 2 && sipdebug
) {
1697 if (!strncasecmp(next
, "x-", 2))
1698 ast_log(LOG_DEBUG
, "Found private SIP option, not supported: %s\n", next
);
1700 ast_log(LOG_DEBUG
, "Found no match for SIP option: %s (Please file bug report!)\n", next
);
1705 pvt
->sipoptions
= profile
;
1709 /*! \brief See if we pass debug IP filter */
1710 static inline int sip_debug_test_addr(const struct sockaddr_in
*addr
)
1714 if (debugaddr
.sin_addr
.s_addr
) {
1715 if (((ntohs(debugaddr
.sin_port
) != 0)
1716 && (debugaddr
.sin_port
!= addr
->sin_port
))
1717 || (debugaddr
.sin_addr
.s_addr
!= addr
->sin_addr
.s_addr
))
1723 /*! \brief The real destination address for a write */
1724 static const struct sockaddr_in
*sip_real_dst(const struct sip_pvt
*p
)
1726 return ast_test_flag(&p
->flags
[0], SIP_NAT
) & SIP_NAT_ROUTE
? &p
->recv
: &p
->sa
;
1729 /*! \brief Display SIP nat mode */
1730 static const char *sip_nat_mode(const struct sip_pvt
*p
)
1732 return ast_test_flag(&p
->flags
[0], SIP_NAT
) & SIP_NAT_ROUTE
? "NAT" : "no NAT";
1735 /*! \brief Test PVT for debugging output */
1736 static inline int sip_debug_test_pvt(struct sip_pvt
*p
)
1740 return sip_debug_test_addr(sip_real_dst(p
));
1743 /*! \brief Transmit SIP message */
1744 static int __sip_xmit(struct sip_pvt
*p
, char *data
, int len
)
1747 const struct sockaddr_in
*dst
= sip_real_dst(p
);
1748 res
= sendto(sipsock
, data
, len
, 0, (const struct sockaddr
*)dst
, sizeof(struct sockaddr_in
));
1751 ast_log(LOG_WARNING
, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data
, len
, ast_inet_ntoa(dst
->sin_addr
), ntohs(dst
->sin_port
), res
, strerror(errno
));
1756 /*! \brief Build a Via header for a request */
1757 static void build_via(struct sip_pvt
*p
)
1759 /* Work around buggy UNIDEN UIP200 firmware */
1760 const char *rport
= ast_test_flag(&p
->flags
[0], SIP_NAT
) & SIP_NAT_RFC3581
? ";rport" : "";
1762 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1763 ast_string_field_build(p
, via
, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1764 ast_inet_ntoa(p
->ourip
), ourport
, p
->branch
, rport
);
1767 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1769 * Using the localaddr structure built up with localnet statements in sip.conf
1770 * apply it to their address to see if we need to substitute our
1771 * externip or can get away with our internal bindaddr
1773 static enum sip_result
ast_sip_ouraddrfor(struct in_addr
*them
, struct in_addr
*us
)
1775 struct sockaddr_in theirs
, ours
;
1777 /* Get our local information */
1778 ast_ouraddrfor(them
, us
);
1779 theirs
.sin_addr
= *them
;
1780 ours
.sin_addr
= *us
;
1782 if (localaddr
&& externip
.sin_addr
.s_addr
&&
1783 (ast_apply_ha(localaddr
, &theirs
)) &&
1784 (!ast_apply_ha(localaddr
, &ours
))) {
1785 if (externexpire
&& time(NULL
) >= externexpire
) {
1786 struct ast_hostent ahp
;
1789 externexpire
= time(NULL
) + externrefresh
;
1790 if ((hp
= ast_gethostbyname(externhost
, &ahp
))) {
1791 memcpy(&externip
.sin_addr
, hp
->h_addr
, sizeof(externip
.sin_addr
));
1793 ast_log(LOG_NOTICE
, "Warning: Re-lookup of '%s' failed!\n", externhost
);
1795 *us
= externip
.sin_addr
;
1797 ast_log(LOG_DEBUG
, "Target address %s is not local, substituting externip\n",
1798 ast_inet_ntoa(*(struct in_addr
*)&them
->s_addr
));
1800 } else if (bindaddr
.sin_addr
.s_addr
)
1801 *us
= bindaddr
.sin_addr
;
1805 /*! \brief Append to SIP dialog history
1806 \return Always returns 0 */
1807 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1809 static void append_history_full(struct sip_pvt
*p
, const char *fmt
, ...)
1810 __attribute__ ((format (printf
, 2, 3)));
1812 /*! \brief Append to SIP dialog history with arg list */
1813 static void append_history_va(struct sip_pvt
*p
, const char *fmt
, va_list ap
)
1815 char buf
[80], *c
= buf
; /* max history length */
1816 struct sip_history
*hist
;
1819 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1820 strsep(&c
, "\r\n"); /* Trim up everything after \r or \n */
1821 l
= strlen(buf
) + 1;
1822 if (!(hist
= ast_calloc(1, sizeof(*hist
) + l
)))
1824 if (!p
->history
&& !(p
->history
= ast_calloc(1, sizeof(*p
->history
)))) {
1828 memcpy(hist
->event
, buf
, l
);
1829 AST_LIST_INSERT_TAIL(p
->history
, hist
, list
);
1832 /*! \brief Append to SIP dialog history with arg list */
1833 static void append_history_full(struct sip_pvt
*p
, const char *fmt
, ...)
1840 append_history_va(p
, fmt
, ap
);
1846 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
1847 static int retrans_pkt(void *data
)
1849 struct sip_pkt
*pkt
= data
, *prev
, *cur
= NULL
;
1850 int reschedule
= DEFAULT_RETRANS
;
1852 /* Lock channel PVT */
1853 ast_mutex_lock(&pkt
->owner
->lock
);
1855 if (pkt
->retrans
< MAX_RETRANS
) {
1857 if (!pkt
->timer_t1
) { /* Re-schedule using timer_a and timer_t1 */
1858 if (sipdebug
&& option_debug
> 3)
1859 ast_log(LOG_DEBUG
, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt
->retransid
, sip_methods
[pkt
->method
].text
, pkt
->method
);
1863 if (sipdebug
&& option_debug
> 3)
1864 ast_log(LOG_DEBUG
, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt
->retransid
, pkt
->retrans
, sip_methods
[pkt
->method
].text
, pkt
->method
);
1868 pkt
->timer_a
= 2 * pkt
->timer_a
;
1870 /* For non-invites, a maximum of 4 secs */
1871 siptimer_a
= pkt
->timer_t1
* pkt
->timer_a
; /* Double each time */
1872 if (pkt
->method
!= SIP_INVITE
&& siptimer_a
> 4000)
1875 /* Reschedule re-transmit */
1876 reschedule
= siptimer_a
;
1877 if (option_debug
> 3)
1878 ast_log(LOG_DEBUG
, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n", pkt
->retrans
+1, siptimer_a
, pkt
->timer_t1
, pkt
->retransid
);
1881 if (sip_debug_test_pvt(pkt
->owner
)) {
1882 const struct sockaddr_in
*dst
= sip_real_dst(pkt
->owner
);
1883 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
1884 pkt
->retrans
, sip_nat_mode(pkt
->owner
),
1885 ast_inet_ntoa(dst
->sin_addr
),
1886 ntohs(dst
->sin_port
), pkt
->data
);
1889 append_history(pkt
->owner
, "ReTx", "%d %s", reschedule
, pkt
->data
);
1890 __sip_xmit(pkt
->owner
, pkt
->data
, pkt
->packetlen
);
1891 ast_mutex_unlock(&pkt
->owner
->lock
);
1894 /* Too many retries */
1895 if (pkt
->owner
&& pkt
->method
!= SIP_OPTIONS
) {
1896 if (ast_test_flag(pkt
, FLAG_FATAL
) || sipdebug
) /* Tell us if it's critical or if we're debugging */
1897 ast_log(LOG_WARNING
, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n", pkt
->owner
->callid
, pkt
->seqno
, (ast_test_flag(pkt
, FLAG_FATAL
)) ? "Critical" : "Non-critical", (ast_test_flag(pkt
, FLAG_RESPONSE
)) ? "Response" : "Request");
1899 if ((pkt
->method
== SIP_OPTIONS
) && sipdebug
)
1900 ast_log(LOG_WARNING
, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt
->owner
->callid
);
1902 append_history(pkt
->owner
, "MaxRetries", "%s", (ast_test_flag(pkt
, FLAG_FATAL
)) ? "(Critical)" : "(Non-critical)");
1904 pkt
->retransid
= -1;
1906 if (ast_test_flag(pkt
, FLAG_FATAL
)) {
1907 while(pkt
->owner
->owner
&& ast_channel_trylock(pkt
->owner
->owner
)) {
1908 ast_mutex_unlock(&pkt
->owner
->lock
); /* SIP_PVT, not channel */
1910 ast_mutex_lock(&pkt
->owner
->lock
);
1912 if (pkt
->owner
->owner
) {
1913 sip_alreadygone(pkt
->owner
);
1914 ast_log(LOG_WARNING
, "Hanging up call %s - no reply to our critical packet.\n", pkt
->owner
->callid
);
1915 ast_queue_hangup(pkt
->owner
->owner
);
1916 ast_channel_unlock(pkt
->owner
->owner
);
1918 /* If no channel owner, destroy now */
1920 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
1921 if (pkt
->method
!= SIP_OPTIONS
)
1922 ast_set_flag(&pkt
->owner
->flags
[0], SIP_NEEDDESTROY
);
1925 /* In any case, go ahead and remove the packet */
1926 for (prev
= NULL
, cur
= pkt
->owner
->packets
; cur
; prev
= cur
, cur
= cur
->next
) {
1932 prev
->next
= cur
->next
;
1934 pkt
->owner
->packets
= cur
->next
;
1935 ast_mutex_unlock(&pkt
->owner
->lock
);
1939 ast_log(LOG_WARNING
, "Weird, couldn't find packet owner!\n");
1941 ast_mutex_unlock(&pkt
->owner
->lock
);
1945 /*! \brief Transmit packet with retransmits
1946 \return 0 on success, -1 on failure to allocate packet
1948 static enum sip_result
__sip_reliable_xmit(struct sip_pvt
*p
, int seqno
, int resp
, char *data
, int len
, int fatal
, int sipmethod
)
1950 struct sip_pkt
*pkt
;
1951 int siptimer_a
= DEFAULT_RETRANS
;
1953 if (!(pkt
= ast_calloc(1, sizeof(*pkt
) + len
+ 1)))
1955 memcpy(pkt
->data
, data
, len
);
1956 pkt
->method
= sipmethod
;
1957 pkt
->packetlen
= len
;
1958 pkt
->next
= p
->packets
;
1962 ast_set_flag(pkt
, FLAG_RESPONSE
);
1963 pkt
->data
[len
] = '\0';
1964 pkt
->timer_t1
= p
->timer_t1
; /* Set SIP timer T1 */
1966 ast_set_flag(pkt
, FLAG_FATAL
);
1968 siptimer_a
= pkt
->timer_t1
* 2;
1970 /* Schedule retransmission */
1971 pkt
->retransid
= ast_sched_add_variable(sched
, siptimer_a
, retrans_pkt
, pkt
, 1);
1972 if (option_debug
> 3 && sipdebug
)
1973 ast_log(LOG_DEBUG
, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt
->retransid
);
1974 pkt
->next
= p
->packets
;
1977 __sip_xmit(pkt
->owner
, pkt
->data
, pkt
->packetlen
); /* Send packet */
1978 if (sipmethod
== SIP_INVITE
) {
1979 /* Note this is a pending invite */
1980 p
->pendinginvite
= seqno
;
1985 /*! \brief Kill a SIP dialog (called by scheduler) */
1986 static int __sip_autodestruct(void *data
)
1988 struct sip_pvt
*p
= data
;
1990 /* If this is a subscription, tell the phone that we got a timeout */
1991 if (p
->subscribed
) {
1992 transmit_state_notify(p
, AST_EXTENSION_DEACTIVATED
, 1, TRUE
); /* Send last notification */
1993 p
->subscribed
= NONE
;
1994 append_history(p
, "Subscribestatus", "timeout");
1995 if (option_debug
> 2)
1996 ast_log(LOG_DEBUG
, "Re-scheduled destruction of SIP subsription %s\n", p
->callid
? p
->callid
: "<unknown>");
1997 return 10000; /* Reschedule this destruction so that we know that it's gone */
2000 /* If we're destroying a subscription, dereference peer object too */
2001 if (p
->subscribed
== MWI_NOTIFICATION
&& p
->relatedpeer
)
2002 ASTOBJ_UNREF(p
->relatedpeer
,sip_destroy_peer
);
2004 /* Reset schedule ID */
2008 ast_log(LOG_DEBUG
, "Auto destroying SIP dialog '%s'\n", p
->callid
);
2009 append_history(p
, "AutoDestroy", "%s", p
->callid
);
2011 ast_log(LOG_WARNING
, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p
->callid
, sip_methods
[p
->method
].text
);
2012 ast_queue_hangup(p
->owner
);
2013 } else if (p
->refer
) {
2014 if (option_debug
> 2)
2015 ast_log(LOG_DEBUG
, "Finally hanging up channel after transfer: %s\n", p
->callid
);
2016 transmit_request_with_auth(p
, SIP_BYE
, 0, XMIT_RELIABLE
, 1);
2017 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
2023 /*! \brief Schedule destruction of SIP dialog */
2024 static void sip_scheddestroy(struct sip_pvt
*p
, int ms
)
2027 if (p
->timer_t1
== 0)
2028 p
->timer_t1
= 500; /* Set timer T1 if not set (RFC 3261) */
2029 ms
= p
->timer_t1
* 64;
2031 if (sip_debug_test_pvt(p
))
2032 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p
->callid
, ms
, sip_methods
[p
->method
].text
);
2033 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
))
2034 append_history(p
, "SchedDestroy", "%d ms", ms
);
2036 if (p
->autokillid
> -1)
2037 ast_sched_del(sched
, p
->autokillid
);
2038 p
->autokillid
= ast_sched_add(sched
, ms
, __sip_autodestruct
, p
);
2041 /*! \brief Cancel destruction of SIP dialog */
2042 static void sip_cancel_destroy(struct sip_pvt
*p
)
2044 if (p
->autokillid
> -1) {
2045 ast_sched_del(sched
, p
->autokillid
);
2046 append_history(p
, "CancelDestroy", "");
2051 /*! \brief Acknowledges receipt of a packet and stops retransmission */
2052 static void __sip_ack(struct sip_pvt
*p
, int seqno
, int resp
, int sipmethod
)
2054 struct sip_pkt
*cur
, *prev
= NULL
;
2056 /* Just in case... */
2060 msg
= sip_methods
[sipmethod
].text
;
2062 ast_mutex_lock(&p
->lock
);
2063 for (cur
= p
->packets
; cur
; prev
= cur
, cur
= cur
->next
) {
2064 if ((cur
->seqno
== seqno
) && ((ast_test_flag(cur
, FLAG_RESPONSE
)) == resp
) &&
2065 ((ast_test_flag(cur
, FLAG_RESPONSE
)) ||
2066 (!strncasecmp(msg
, cur
->data
, strlen(msg
)) && (cur
->data
[strlen(msg
)] < 33)))) {
2067 if (!resp
&& (seqno
== p
->pendinginvite
)) {
2069 ast_log(LOG_DEBUG
, "Acked pending invite %d\n", p
->pendinginvite
);
2070 p
->pendinginvite
= 0;
2072 /* this is our baby */
2074 UNLINK(cur
, p
->packets
, prev
);
2075 if (cur
->retransid
> -1) {
2076 if (sipdebug
&& option_debug
> 3)
2077 ast_log(LOG_DEBUG
, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur
->retransid
);
2078 ast_sched_del(sched
, cur
->retransid
);
2079 cur
->retransid
= -1;
2085 ast_mutex_unlock(&p
->lock
);
2087 ast_log(LOG_DEBUG
, "Stopping retransmission on '%s' of %s %d: Match %s\n", p
->callid
, resp
? "Response" : "Request", seqno
, res
? "Not Found" : "Found");
2090 /*! \brief Pretend to ack all packets
2091 * maybe the lock on p is not strictly necessary but there might be a race */
2092 static void __sip_pretend_ack(struct sip_pvt
*p
)
2094 struct sip_pkt
*cur
= NULL
;
2096 while (p
->packets
) {
2098 if (cur
== p
->packets
) {
2099 ast_log(LOG_WARNING
, "Have a packet that doesn't want to give up! %s\n", sip_methods
[cur
->method
].text
);
2103 method
= (cur
->method
) ? cur
->method
: find_sip_method(cur
->data
);
2104 __sip_ack(p
, cur
->seqno
, ast_test_flag(cur
, FLAG_RESPONSE
), method
);
2108 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2109 static int __sip_semi_ack(struct sip_pvt
*p
, int seqno
, int resp
, int sipmethod
)
2111 struct sip_pkt
*cur
;
2114 for (cur
= p
->packets
; cur
; cur
= cur
->next
) {
2115 if (cur
->seqno
== seqno
&& ast_test_flag(cur
, FLAG_RESPONSE
) == resp
&&
2116 (ast_test_flag(cur
, FLAG_RESPONSE
) || method_match(sipmethod
, cur
->data
))) {
2117 /* this is our baby */
2118 if (cur
->retransid
> -1) {
2119 if (option_debug
> 3 && sipdebug
)
2120 ast_log(LOG_DEBUG
, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur
->retransid
, sip_methods
[sipmethod
].text
);
2121 ast_sched_del(sched
, cur
->retransid
);
2122 cur
->retransid
= -1;
2129 ast_log(LOG_DEBUG
, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p
->callid
, resp
? "Response" : "Request", seqno
, res
? "Not Found" : "Found");
2134 /*! \brief Copy SIP request, parse it */
2135 static void parse_copy(struct sip_request
*dst
, const struct sip_request
*src
)
2137 memset(dst
, 0, sizeof(*dst
));
2138 memcpy(dst
->data
, src
->data
, sizeof(dst
->data
));
2139 dst
->len
= src
->len
;
2143 /*! \brief add a blank line if no body */
2144 static void add_blank(struct sip_request
*req
)
2147 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2148 snprintf(req
->data
+ req
->len
, sizeof(req
->data
) - req
->len
, "\r\n");
2149 req
->len
+= strlen(req
->data
+ req
->len
);
2153 /*! \brief Transmit response on SIP request*/
2154 static int send_response(struct sip_pvt
*p
, struct sip_request
*req
, enum xmittype reliable
, int seqno
)
2159 if (sip_debug_test_pvt(p
)) {
2160 const struct sockaddr_in
*dst
= sip_real_dst(p
);
2162 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
2163 reliable
? "Reliably " : "", sip_nat_mode(p
),
2164 ast_inet_ntoa(dst
->sin_addr
),
2165 ntohs(dst
->sin_port
), req
->data
);
2167 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
)) {
2168 struct sip_request tmp
;
2169 parse_copy(&tmp
, req
);
2170 append_history(p
, reliable
? "TxRespRel" : "TxResp", "%s / %s - %s", tmp
.data
, get_header(&tmp
, "CSeq"),
2171 (tmp
.method
== SIP_RESPONSE
|| tmp
.method
== SIP_UNKNOWN
) ? tmp
.rlPart2
: sip_methods
[tmp
.method
].text
);
2174 __sip_reliable_xmit(p
, seqno
, 1, req
->data
, req
->len
, (reliable
== XMIT_CRITICAL
), req
->method
) :
2175 __sip_xmit(p
, req
->data
, req
->len
);
2181 /*! \brief Send SIP Request to the other part of the dialogue */
2182 static int send_request(struct sip_pvt
*p
, struct sip_request
*req
, enum xmittype reliable
, int seqno
)
2187 if (sip_debug_test_pvt(p
)) {
2188 if (ast_test_flag(&p
->flags
[0], SIP_NAT_ROUTE
))
2189 ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable
? "Reliably " : "", ast_inet_ntoa(p
->recv
.sin_addr
), ntohs(p
->recv
.sin_port
), req
->data
);
2191 ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable
? "Reliably " : "", ast_inet_ntoa(p
->sa
.sin_addr
), ntohs(p
->sa
.sin_port
), req
->data
);
2193 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
)) {
2194 struct sip_request tmp
;
2195 parse_copy(&tmp
, req
);
2196 append_history(p
, reliable
? "TxReqRel" : "TxReq", "%s / %s - %s", tmp
.data
, get_header(&tmp
, "CSeq"), sip_methods
[tmp
.method
].text
);
2199 __sip_reliable_xmit(p
, seqno
, 0, req
->data
, req
->len
, (reliable
> 1), req
->method
) :
2200 __sip_xmit(p
, req
->data
, req
->len
);
2204 /*! \brief Locate closing quote in a string, skipping escaped quotes.
2205 * optionally with a limit on the search.
2206 * start must be past the first quote.
2208 static const char *find_closing_quote(const char *start
, const char *lim
)
2210 char last_char
= '\0';
2212 for (s
= start
; *s
&& s
!= lim
; last_char
= *s
++) {
2213 if (*s
== '"' && last_char
!= '\\')
2219 /*! \brief Pick out text in brackets from character string
2220 \return pointer to terminated stripped string
2221 \param tmp input string that will be modified
2224 "foo" <bar> valid input, returns bar
2225 foo returns the whole string
2226 < "foo ... > returns the string between brackets
2227 < "foo... bogus (missing closing bracket), returns the whole string
2228 XXX maybe should still skip the opening bracket
2230 static char *get_in_brackets(char *tmp
)
2232 const char *parse
= tmp
;
2233 char *first_bracket
;
2236 * Skip any quoted text until we find the part in brackets.
2237 * On any error give up and return the full string.
2239 while ( (first_bracket
= strchr(parse
, '<')) ) {
2240 char *first_quote
= strchr(parse
, '"');
2242 if (!first_quote
|| first_quote
> first_bracket
)
2243 break; /* no need to look at quoted part */
2244 /* the bracket is within quotes, so ignore it */
2245 parse
= find_closing_quote(first_quote
+ 1, NULL
);
2246 if (!*parse
) { /* not found, return full string ? */
2247 /* XXX or be robust and return in-bracket part ? */
2248 ast_log(LOG_WARNING
, "No closing quote found in '%s'\n", tmp
);
2253 if (first_bracket
) {
2254 char *second_bracket
= strchr(first_bracket
+ 1, '>');
2255 if (second_bracket
) {
2256 *second_bracket
= '\0';
2257 tmp
= first_bracket
+ 1;
2259 ast_log(LOG_WARNING
, "No closing bracket found in '%s'\n", tmp
);
2265 /*! \brief Send SIP MESSAGE text within a call
2266 Called from PBX core sendtext() application */
2267 static int sip_sendtext(struct ast_channel
*ast
, const char *text
)
2269 struct sip_pvt
*p
= ast
->tech_pvt
;
2270 int debug
= sip_debug_test_pvt(p
);
2273 ast_verbose("Sending text %s on %s\n", text
, ast
->name
);
2276 if (ast_strlen_zero(text
))
2279 ast_verbose("Really sending text %s on %s\n", text
, ast
->name
);
2280 transmit_message_with_text(p
, text
);
2284 /*! \brief Update peer object in realtime storage
2285 If the Asterisk system name is set in asterisk.conf, we will use
2286 that name and store that in the "regserver" field in the sippeers
2287 table to facilitate multi-server setups.
2289 static void realtime_update_peer(const char *peername
, struct sockaddr_in
*sin
, const char *username
, const char *fullcontact
, int expirey
)
2292 char ipaddr
[INET_ADDRSTRLEN
];
2293 char regseconds
[20];
2295 char *sysname
= ast_config_AST_SYSTEM_NAME
;
2296 char *syslabel
= NULL
;
2298 time_t nowtime
= time(NULL
) + expirey
;
2299 const char *fc
= fullcontact
? "fullcontact" : NULL
;
2301 snprintf(regseconds
, sizeof(regseconds
), "%d", (int)nowtime
); /* Expiration time */
2302 ast_copy_string(ipaddr
, ast_inet_ntoa(sin
->sin_addr
), sizeof(ipaddr
));
2303 snprintf(port
, sizeof(port
), "%d", ntohs(sin
->sin_port
));
2305 if (ast_strlen_zero(sysname
)) /* No system name, disable this */
2307 else if (ast_test_flag(&global_flags
[1], SIP_PAGE2_RTSAVE_SYSNAME
))
2308 syslabel
= "regserver";
2311 ast_update_realtime("sippeers", "name", peername
, "ipaddr", ipaddr
,
2312 "port", port
, "regseconds", regseconds
,
2313 "username", username
, fc
, fullcontact
, syslabel
, sysname
, NULL
); /* note fc and syslabel _can_ be NULL */
2315 ast_update_realtime("sippeers", "name", peername
, "ipaddr", ipaddr
,
2316 "port", port
, "regseconds", regseconds
,
2317 "username", username
, syslabel
, sysname
, NULL
); /* note syslabel _can_ be NULL */
2320 /*! \brief Automatically add peer extension to dial plan */
2321 static void register_peer_exten(struct sip_peer
*peer
, int onoff
)
2324 char *stringp
, *ext
, *context
;
2326 /* XXX note that global_regcontext is both a global 'enable' flag and
2327 * the name of the global regexten context, if not specified
2330 if (ast_strlen_zero(global_regcontext
))
2333 ast_copy_string(multi
, S_OR(peer
->regexten
, peer
->name
), sizeof(multi
));
2335 while ((ext
= strsep(&stringp
, "&"))) {
2336 if ((context
= strchr(ext
, '@'))) {
2337 *context
++ = '\0'; /* split ext@context */
2338 if (!ast_context_find(context
)) {
2339 ast_log(LOG_WARNING
, "Context %s must exist in regcontext= in sip.conf!\n", context
);
2343 context
= global_regcontext
;
2346 ast_add_extension(context
, 1, ext
, 1, NULL
, NULL
, "Noop",
2347 ast_strdup(peer
->name
), ast_free
, "SIP");
2349 ast_context_remove_extension(context
, ext
, 1, NULL
);
2353 /*! \brief Destroy peer object from memory */
2354 static void sip_destroy_peer(struct sip_peer
*peer
)
2356 if (option_debug
> 2)
2357 ast_log(LOG_DEBUG
, "Destroying SIP peer %s\n", peer
->name
);
2359 /* Delete it, it needs to disappear */
2361 sip_destroy(peer
->call
);
2363 if (peer
->mwipvt
) /* We have an active subscription, delete it */
2364 sip_destroy(peer
->mwipvt
);
2366 if (peer
->chanvars
) {
2367 ast_variables_destroy(peer
->chanvars
);
2368 peer
->chanvars
= NULL
;
2370 if (peer
->expire
> -1)
2371 ast_sched_del(sched
, peer
->expire
);
2373 if (peer
->pokeexpire
> -1)
2374 ast_sched_del(sched
, peer
->pokeexpire
);
2375 register_peer_exten(peer
, FALSE
);
2376 ast_free_ha(peer
->ha
);
2377 if (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_SELFDESTRUCT
))
2379 else if (ast_test_flag(&peer
->flags
[0], SIP_REALTIME
))
2383 clear_realm_authentication(peer
->auth
);
2388 /*! \brief Update peer data in database (if used) */
2389 static void update_peer(struct sip_peer
*p
, int expiry
)
2391 int rtcachefriends
= ast_test_flag(&p
->flags
[1], SIP_PAGE2_RTCACHEFRIENDS
);
2392 if (ast_test_flag(&global_flags
[1], SIP_PAGE2_RTUPDATE
) &&
2393 (ast_test_flag(&p
->flags
[0], SIP_REALTIME
) || rtcachefriends
)) {
2394 realtime_update_peer(p
->name
, &p
->addr
, p
->username
, rtcachefriends
? p
->fullcontact
: NULL
, expiry
);
2399 /*! \brief realtime_peer: Get peer from realtime storage
2400 * Checks the "sippeers" realtime family from extconfig.conf
2401 * \todo Consider adding check of port address when matching here to follow the same
2402 * algorithm as for static peers. Will we break anything by adding that?
2404 static struct sip_peer
*realtime_peer(const char *newpeername
, struct sockaddr_in
*sin
)
2406 struct sip_peer
*peer
;
2407 struct ast_variable
*var
= NULL
;
2408 struct ast_variable
*tmp
;
2409 char ipaddr
[INET_ADDRSTRLEN
];
2411 /* First check on peer name */
2413 var
= ast_load_realtime("sippeers", "name", newpeername
, NULL
);
2414 else if (sin
) { /* Then check on IP address for dynamic peers */
2415 ast_copy_string(ipaddr
, ast_inet_ntoa(sin
->sin_addr
), sizeof(ipaddr
));
2416 var
= ast_load_realtime("sippeers", "host", ipaddr
, NULL
); /* First check for fixed IP hosts */
2418 var
= ast_load_realtime("sippeers", "ipaddr", ipaddr
, NULL
); /* Then check for registred hosts */
2424 for (tmp
= var
; tmp
; tmp
= tmp
->next
) {
2425 /* If this is type=user, then skip this object. */
2426 if (!strcasecmp(tmp
->name
, "type") &&
2427 !strcasecmp(tmp
->value
, "user")) {
2428 ast_variables_destroy(var
);
2430 } else if (!newpeername
&& !strcasecmp(tmp
->name
, "name")) {
2431 newpeername
= tmp
->value
;
2435 if (!newpeername
) { /* Did not find peer in realtime */
2436 ast_log(LOG_WARNING
, "Cannot Determine peer name ip=%s\n", ipaddr
);
2437 ast_variables_destroy(var
);
2441 /* Peer found in realtime, now build it in memory */
2442 peer
= build_peer(newpeername
, var
, NULL
, !ast_test_flag(&global_flags
[1], SIP_PAGE2_RTCACHEFRIENDS
));
2444 ast_variables_destroy(var
);
2448 if (ast_test_flag(&global_flags
[1], SIP_PAGE2_RTCACHEFRIENDS
)) {
2450 ast_copy_flags(&peer
->flags
[1],&global_flags
[1], SIP_PAGE2_RTAUTOCLEAR
|SIP_PAGE2_RTCACHEFRIENDS
);
2451 if (ast_test_flag(&global_flags
[1], SIP_PAGE2_RTAUTOCLEAR
)) {
2452 if (peer
->expire
> -1) {
2453 ast_sched_del(sched
, peer
->expire
);
2455 peer
->expire
= ast_sched_add(sched
, (global_rtautoclear
) * 1000, expire_register
, (void *)peer
);
2457 ASTOBJ_CONTAINER_LINK(&peerl
,peer
);
2459 ast_set_flag(&peer
->flags
[0], SIP_REALTIME
);
2461 ast_variables_destroy(var
);
2466 /*! \brief Support routine for find_peer */
2467 static int sip_addrcmp(char *name
, struct sockaddr_in
*sin
)
2469 /* We know name is the first field, so we can cast */
2470 struct sip_peer
*p
= (struct sip_peer
*) name
;
2471 return !(!inaddrcmp(&p
->addr
, sin
) ||
2472 (ast_test_flag(&p
->flags
[0], SIP_INSECURE_PORT
) &&
2473 (p
->addr
.sin_addr
.s_addr
== sin
->sin_addr
.s_addr
)));
2476 /*! \brief Locate peer by name or ip address
2477 * This is used on incoming SIP message to find matching peer on ip
2478 or outgoing message to find matching peer on name */
2479 static struct sip_peer
*find_peer(const char *peer
, struct sockaddr_in
*sin
, int realtime
)
2481 struct sip_peer
*p
= NULL
;
2484 p
= ASTOBJ_CONTAINER_FIND(&peerl
, peer
);
2486 p
= ASTOBJ_CONTAINER_FIND_FULL(&peerl
, sin
, name
, sip_addr_hashfunc
, 1, sip_addrcmp
);
2489 p
= realtime_peer(peer
, sin
);
2494 /*! \brief Remove user object from in-memory storage */
2495 static void sip_destroy_user(struct sip_user
*user
)
2497 if (option_debug
> 2)
2498 ast_log(LOG_DEBUG
, "Destroying user object from memory: %s\n", user
->name
);
2499 ast_free_ha(user
->ha
);
2500 if (user
->chanvars
) {
2501 ast_variables_destroy(user
->chanvars
);
2502 user
->chanvars
= NULL
;
2504 if (ast_test_flag(&user
->flags
[0], SIP_REALTIME
))
2511 /*! \brief Load user from realtime storage
2512 * Loads user from "sipusers" category in realtime (extconfig.conf)
2513 * Users are matched on From: user name (the domain in skipped) */
2514 static struct sip_user
*realtime_user(const char *username
)
2516 struct ast_variable
*var
;
2517 struct ast_variable
*tmp
;
2518 struct sip_user
*user
= NULL
;
2520 var
= ast_load_realtime("sipusers", "name", username
, NULL
);
2525 for (tmp
= var
; tmp
; tmp
= tmp
->next
) {
2526 if (!strcasecmp(tmp
->name
, "type") &&
2527 !strcasecmp(tmp
->value
, "peer")) {
2528 ast_variables_destroy(var
);
2533 user
= build_user(username
, var
, !ast_test_flag(&global_flags
[1], SIP_PAGE2_RTCACHEFRIENDS
));
2535 if (!user
) { /* No user found */
2536 ast_variables_destroy(var
);
2540 if (ast_test_flag(&global_flags
[1], SIP_PAGE2_RTCACHEFRIENDS
)) {
2541 ast_set_flag(&user
->flags
[1], SIP_PAGE2_RTCACHEFRIENDS
);
2543 ASTOBJ_CONTAINER_LINK(&userl
,user
);
2545 /* Move counter from s to r... */
2548 ast_set_flag(&user
->flags
[0], SIP_REALTIME
);
2550 ast_variables_destroy(var
);
2554 /*! \brief Locate user by name
2555 * Locates user by name (From: sip uri user name part) first
2556 * from in-memory list (static configuration) then from
2557 * realtime storage (defined in extconfig.conf) */
2558 static struct sip_user
*find_user(const char *name
, int realtime
)
2560 struct sip_user
*u
= ASTOBJ_CONTAINER_FIND(&userl
, name
);
2562 u
= realtime_user(name
);
2566 /*! \brief Set nat mode on the various data sockets */
2567 static void do_setnat(struct sip_pvt
*p
, int natflags
)
2569 const char *mode
= natflags
? "On" : "Off";
2573 ast_log(LOG_DEBUG
, "Setting NAT on RTP to %s\n", mode
);
2574 ast_rtp_setnat(p
->rtp
, natflags
);
2578 ast_log(LOG_DEBUG
, "Setting NAT on VRTP to %s\n", mode
);
2579 ast_rtp_setnat(p
->vrtp
, natflags
);
2583 ast_log(LOG_DEBUG
, "Setting NAT on UDPTL to %s\n", mode
);
2584 ast_udptl_setnat(p
->udptl
, natflags
);
2588 /*! \brief Create address structure from peer reference.
2589 * return -1 on error, 0 on success.
2591 static int create_addr_from_peer(struct sip_pvt
*dialog
, struct sip_peer
*peer
)
2593 if ((peer
->addr
.sin_addr
.s_addr
|| peer
->defaddr
.sin_addr
.s_addr
) &&
2594 (!peer
->maxms
|| ((peer
->lastms
>= 0) && (peer
->lastms
<= peer
->maxms
)))) {
2595 dialog
->sa
= (peer
->addr
.sin_addr
.s_addr
) ? peer
->addr
: peer
->defaddr
;
2596 dialog
->recv
= dialog
->sa
;
2600 ast_copy_flags(&dialog
->flags
[0], &peer
->flags
[0], SIP_FLAGS_TO_COPY
);
2601 ast_copy_flags(&dialog
->flags
[1], &peer
->flags
[1], SIP_PAGE2_FLAGS_TO_COPY
);
2602 dialog
->capability
= peer
->capability
;
2603 if ((!ast_test_flag(&dialog
->flags
[1], SIP_PAGE2_VIDEOSUPPORT
) || !(dialog
->capability
& AST_FORMAT_VIDEO_MASK
)) && dialog
->vrtp
) {
2604 ast_rtp_destroy(dialog
->vrtp
);
2605 dialog
->vrtp
= NULL
;
2607 dialog
->prefs
= peer
->prefs
;
2608 if (ast_test_flag(&dialog
->flags
[1], SIP_PAGE2_T38SUPPORT
)) {
2609 dialog
->t38
.capability
= global_t38_capability
;
2610 if (dialog
->udptl
) {
2611 if (ast_udptl_get_error_correction_scheme(dialog
->udptl
) == UDPTL_ERROR_CORRECTION_FEC
)
2612 dialog
->t38
.capability
|= T38FAX_UDP_EC_FEC
;
2613 else if (ast_udptl_get_error_correction_scheme(dialog
->udptl
) == UDPTL_ERROR_CORRECTION_REDUNDANCY
)
2614 dialog
->t38
.capability
|= T38FAX_UDP_EC_REDUNDANCY
;
2615 else if (ast_udptl_get_error_correction_scheme(dialog
->udptl
) == UDPTL_ERROR_CORRECTION_NONE
)
2616 dialog
->t38
.capability
|= T38FAX_UDP_EC_NONE
;
2617 dialog
->t38
.capability
|= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF
;
2618 if (option_debug
> 1)
2619 ast_log(LOG_DEBUG
,"Our T38 capability (%d)\n", dialog
->t38
.capability
);
2621 dialog
->t38
.jointcapability
= dialog
->t38
.capability
;
2622 } else if (dialog
->udptl
) {
2623 ast_udptl_destroy(dialog
->udptl
);
2624 dialog
->udptl
= NULL
;
2626 do_setnat(dialog
, ast_test_flag(&dialog
->flags
[0], SIP_NAT
) & SIP_NAT_ROUTE
);
2629 ast_rtp_setdtmf(dialog
->rtp
, ast_test_flag(&dialog
->flags
[0], SIP_DTMF
) == SIP_DTMF_RFC2833
);
2630 ast_rtp_setdtmfcompensate(dialog
->rtp
, ast_test_flag(&dialog
->flags
[1], SIP_PAGE2_RFC2833_COMPENSATE
));
2631 ast_rtp_set_rtptimeout(dialog
->rtp
, peer
->rtptimeout
);
2632 ast_rtp_set_rtpholdtimeout(dialog
->rtp
, peer
->rtpholdtimeout
);
2633 ast_rtp_set_rtpkeepalive(dialog
->rtp
, peer
->rtpkeepalive
);
2634 /* Set Frame packetization */
2635 ast_rtp_codec_setpref(dialog
->rtp
, &dialog
->prefs
);
2636 dialog
->autoframing
= peer
->autoframing
;
2639 ast_rtp_setdtmf(dialog
->vrtp
, 0);
2640 ast_rtp_setdtmfcompensate(dialog
->vrtp
, 0);
2641 ast_rtp_set_rtptimeout(dialog
->vrtp
, peer
->rtptimeout
);
2642 ast_rtp_set_rtpholdtimeout(dialog
->vrtp
, peer
->rtpholdtimeout
);
2643 ast_rtp_set_rtpkeepalive(dialog
->vrtp
, peer
->rtpkeepalive
);
2646 ast_string_field_set(dialog
, peername
, peer
->username
);
2647 ast_string_field_set(dialog
, authname
, peer
->username
);
2648 ast_string_field_set(dialog
, username
, peer
->username
);
2649 ast_string_field_set(dialog
, peersecret
, peer
->secret
);
2650 ast_string_field_set(dialog
, peermd5secret
, peer
->md5secret
);
2651 ast_string_field_set(dialog
, mohsuggest
, peer
->mohsuggest
);
2652 ast_string_field_set(dialog
, mohinterpret
, peer
->mohinterpret
);
2653 ast_string_field_set(dialog
, tohost
, peer
->tohost
);
2654 ast_string_field_set(dialog
, fullcontact
, peer
->fullcontact
);
2655 if (!dialog
->initreq
.headers
&& !ast_strlen_zero(peer
->fromdomain
)) {
2658 tmpcall
= ast_strdupa(dialog
->callid
);
2659 c
= strchr(tmpcall
, '@');
2662 ast_string_field_build(dialog
, callid
, "%s@%s", tmpcall
, peer
->fromdomain
);
2665 if (ast_strlen_zero(dialog
->tohost
))
2666 ast_string_field_set(dialog
, tohost
, ast_inet_ntoa(dialog
->sa
.sin_addr
));
2667 if (!ast_strlen_zero(peer
->fromdomain
))
2668 ast_string_field_set(dialog
, fromdomain
, peer
->fromdomain
);
2669 if (!ast_strlen_zero(peer
->fromuser
))
2670 ast_string_field_set(dialog
, fromuser
, peer
->fromuser
);
2671 dialog
->maxtime
= peer
->maxms
;
2672 dialog
->callgroup
= peer
->callgroup
;
2673 dialog
->pickupgroup
= peer
->pickupgroup
;
2674 dialog
->allowtransfer
= peer
->allowtransfer
;
2675 /* Set timer T1 to RTT for this peer (if known by qualify=) */
2676 /* Minimum is settable or default to 100 ms */
2677 if (peer
->maxms
&& peer
->lastms
)
2678 dialog
->timer_t1
= peer
->lastms
< global_t1min
? global_t1min
: peer
->lastms
;
2679 if ((ast_test_flag(&dialog
->flags
[0], SIP_DTMF
) == SIP_DTMF_RFC2833
) ||
2680 (ast_test_flag(&dialog
->flags
[0], SIP_DTMF
) == SIP_DTMF_AUTO
))
2681 dialog
->noncodeccapability
|= AST_RTP_DTMF
;
2683 dialog
->noncodeccapability
&= ~AST_RTP_DTMF
;
2684 ast_string_field_set(dialog
, context
, peer
->context
);
2685 dialog
->rtptimeout
= peer
->rtptimeout
;
2686 if (peer
->call_limit
)
2687 ast_set_flag(&dialog
->flags
[0], SIP_CALL_LIMIT
);
2688 dialog
->maxcallbitrate
= peer
->maxcallbitrate
;
2693 /*! \brief create address structure from peer name
2694 * Or, if peer not found, find it in the global DNS
2695 * returns TRUE (-1) on failure, FALSE on success */
2696 static int create_addr(struct sip_pvt
*dialog
, const char *opeer
)
2699 struct ast_hostent ahp
;
2703 char host
[MAXHOSTNAMELEN
], *hostn
;
2706 ast_copy_string(peer
, opeer
, sizeof(peer
));
2707 port
= strchr(peer
, ':');
2710 dialog
->sa
.sin_family
= AF_INET
;
2711 dialog
->timer_t1
= 500; /* Default SIP retransmission timer T1 (RFC 3261) */
2712 p
= find_peer(peer
, NULL
, 1);
2715 int res
= create_addr_from_peer(dialog
, p
);
2716 ASTOBJ_UNREF(p
, sip_destroy_peer
);
2720 portno
= port
? atoi(port
) : STANDARD_SIP_PORT
;
2722 char service
[MAXHOSTNAMELEN
];
2726 snprintf(service
, sizeof(service
), "_sip._udp.%s", peer
);
2727 ret
= ast_get_srv(NULL
, host
, sizeof(host
), &tportno
, service
);
2733 hp
= ast_gethostbyname(hostn
, &ahp
);
2735 ast_log(LOG_WARNING
, "No such host: %s\n", peer
);
2738 ast_string_field_set(dialog
, tohost
, peer
);
2739 memcpy(&dialog
->sa
.sin_addr
, hp
->h_addr
, sizeof(dialog
->sa
.sin_addr
));
2740 dialog
->sa
.sin_port
= htons(portno
);
2741 dialog
->recv
= dialog
->sa
;
2745 /*! \brief Scheduled congestion on a call */
2746 static int auto_congest(void *nothing
)
2748 struct sip_pvt
*p
= nothing
;
2750 ast_mutex_lock(&p
->lock
);
2753 /* XXX fails on possible deadlock */
2754 if (!ast_channel_trylock(p
->owner
)) {
2755 ast_log(LOG_NOTICE
, "Auto-congesting %s\n", p
->owner
->name
);
2756 append_history(p
, "Cong", "Auto-congesting (timer)");
2757 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
2758 ast_channel_unlock(p
->owner
);
2761 ast_mutex_unlock(&p
->lock
);
2766 /*! \brief Initiate SIP call from PBX
2767 * used from the dial() application */
2768 static int sip_call(struct ast_channel
*ast
, char *dest
, int timeout
)
2772 struct varshead
*headp
;
2773 struct ast_var_t
*current
;
2774 const char *referer
= NULL
; /* SIP refererer */
2777 if ((ast
->_state
!= AST_STATE_DOWN
) && (ast
->_state
!= AST_STATE_RESERVED
)) {
2778 ast_log(LOG_WARNING
, "sip_call called on %s, neither down nor reserved\n", ast
->name
);
2782 /* Check whether there is vxml_url, distinctive ring variables */
2783 headp
=&ast
->varshead
;
2784 AST_LIST_TRAVERSE(headp
,current
,entries
) {
2785 /* Check whether there is a VXML_URL variable */
2786 if (!p
->options
->vxml_url
&& !strcasecmp(ast_var_name(current
), "VXML_URL")) {
2787 p
->options
->vxml_url
= ast_var_value(current
);
2788 } else if (!p
->options
->uri_options
&& !strcasecmp(ast_var_name(current
), "SIP_URI_OPTIONS")) {
2789 p
->options
->uri_options
= ast_var_value(current
);
2790 } else if (!p
->options
->distinctive_ring
&& !strcasecmp(ast_var_name(current
), "ALERT_INFO")) {
2791 /* Check whether there is a ALERT_INFO variable */
2792 p
->options
->distinctive_ring
= ast_var_value(current
);
2793 } else if (!p
->options
->addsipheaders
&& !strncasecmp(ast_var_name(current
), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2794 /* Check whether there is a variable with a name starting with SIPADDHEADER */
2795 p
->options
->addsipheaders
= 1;
2796 } else if (!strcasecmp(ast_var_name(current
), "SIPTRANSFER")) {
2797 /* This is a transfered call */
2798 p
->options
->transfer
= 1;
2799 } else if (!strcasecmp(ast_var_name(current
), "SIPTRANSFER_REFERER")) {
2800 /* This is the referer */
2801 referer
= ast_var_value(current
);
2802 } else if (!strcasecmp(ast_var_name(current
), "SIPTRANSFER_REPLACES")) {
2803 /* We're replacing a call. */
2804 p
->options
->replaces
= ast_var_value(current
);
2805 } else if (!strcasecmp(ast_var_name(current
), "T38CALL")) {
2806 p
->t38
.state
= T38_LOCAL_DIRECT
;
2808 ast_log(LOG_DEBUG
,"T38State change to %d on channel %s\n", p
->t38
.state
, ast
->name
);
2814 ast_set_flag(&p
->flags
[0], SIP_OUTGOING
);
2816 if (p
->options
->transfer
) {
2820 if (sipdebug
&& option_debug
> 2)
2821 ast_log(LOG_DEBUG
, "Call for %s transfered by %s\n", p
->username
, referer
);
2822 snprintf(buf
, sizeof(buf
)-1, "-> %s (via %s)", p
->cid_name
, referer
);
2824 snprintf(buf
, sizeof(buf
)-1, "-> %s", p
->cid_name
);
2825 ast_string_field_set(p
, cid_name
, buf
);
2828 ast_log(LOG_DEBUG
, "Outgoing Call for %s\n", p
->username
);
2830 res
= update_call_counter(p
, INC_CALL_RINGING
);
2832 p
->callingpres
= ast
->cid
.cid_pres
;
2833 p
->jointcapability
= ast_translate_available_formats(p
->capability
, p
->prefcodec
);
2834 p
->jointnoncodeccapability
= p
->noncodeccapability
;
2836 /* If there are no audio formats left to offer, punt */
2837 if (!(p
->jointcapability
& AST_FORMAT_AUDIO_MASK
)) {
2838 ast_log(LOG_WARNING
, "No audio format found to offer. Cancelling call to %s\n", p
->username
);
2841 p
->t38
.jointcapability
= p
->t38
.capability
;
2842 if (option_debug
> 1)
2843 ast_log(LOG_DEBUG
,"Our T38 capability (%d), joint T38 capability (%d)\n", p
->t38
.capability
, p
->t38
.jointcapability
);
2844 transmit_invite(p
, SIP_INVITE
, 1, 2);
2845 p
->invitestate
= INV_CALLING
;
2847 /* Initialize auto-congest time */
2848 p
->initid
= ast_sched_add(sched
, p
->maxtime
? (p
->maxtime
* 4) : SIP_TRANS_TIMEOUT
, auto_congest
, p
);
2854 /*! \brief Destroy registry object
2855 Objects created with the register= statement in static configuration */
2856 static void sip_registry_destroy(struct sip_registry
*reg
)
2859 if (option_debug
> 2)
2860 ast_log(LOG_DEBUG
, "Destroying registry entry for %s@%s\n", reg
->username
, reg
->hostname
);
2863 /* Clear registry before destroying to ensure
2864 we don't get reentered trying to grab the registry lock */
2865 reg
->call
->registry
= NULL
;
2866 if (option_debug
> 2)
2867 ast_log(LOG_DEBUG
, "Destroying active SIP dialog for registry %s@%s\n", reg
->username
, reg
->hostname
);
2868 sip_destroy(reg
->call
);
2870 if (reg
->expire
> -1)
2871 ast_sched_del(sched
, reg
->expire
);
2872 if (reg
->timeout
> -1)
2873 ast_sched_del(sched
, reg
->timeout
);
2874 ast_string_field_free_pools(reg
);
2880 /*! \brief Execute destruction of SIP dialog structure, release memory */
2881 static void __sip_destroy(struct sip_pvt
*p
, int lockowner
)
2883 struct sip_pvt
*cur
, *prev
= NULL
;
2886 if (sip_debug_test_pvt(p
) || option_debug
> 2)
2887 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p
->callid
, sip_methods
[p
->method
].text
);
2889 if (ast_test_flag(&p
->flags
[0], SIP_INC_COUNT
)) {
2890 update_call_counter(p
, DEC_CALL_LIMIT
);
2891 if (option_debug
> 1)
2892 ast_log(LOG_DEBUG
, "This call did not properly clean up call limits. Call ID %s\n", p
->callid
);
2895 /* Remove link from peer to subscription of MWI */
2896 if (p
->relatedpeer
&& p
->relatedpeer
->mwipvt
)
2897 p
->relatedpeer
->mwipvt
= NULL
;
2900 sip_dump_history(p
);
2905 if (p
->stateid
> -1)
2906 ast_extension_state_del(p
->stateid
, NULL
);
2908 ast_sched_del(sched
, p
->initid
);
2909 if (p
->autokillid
> -1)
2910 ast_sched_del(sched
, p
->autokillid
);
2913 ast_rtp_destroy(p
->rtp
);
2915 ast_rtp_destroy(p
->vrtp
);
2917 ast_udptl_destroy(p
->udptl
);
2921 free_old_route(p
->route
);
2925 if (p
->registry
->call
== p
)
2926 p
->registry
->call
= NULL
;
2927 ASTOBJ_UNREF(p
->registry
, sip_registry_destroy
);
2930 /* Unlink us from the owner if we have one */
2933 ast_channel_lock(p
->owner
);
2935 ast_log(LOG_DEBUG
, "Detaching from %s\n", p
->owner
->name
);
2936 p
->owner
->tech_pvt
= NULL
;
2938 ast_channel_unlock(p
->owner
);
2942 struct sip_history
*hist
;
2943 while( (hist
= AST_LIST_REMOVE_HEAD(p
->history
, list
)) )
2949 for (prev
= NULL
, cur
= iflist
; cur
; prev
= cur
, cur
= cur
->next
) {
2951 UNLINK(cur
, iflist
, prev
);
2956 ast_log(LOG_WARNING
, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p
->callid
);
2960 /* remove all current packets in this dialog */
2961 while((cp
= p
->packets
)) {
2962 p
->packets
= p
->packets
->next
;
2963 if (cp
->retransid
> -1)
2964 ast_sched_del(sched
, cp
->retransid
);
2968 ast_variables_destroy(p
->chanvars
);
2971 ast_mutex_destroy(&p
->lock
);
2973 ast_string_field_free_pools(p
);
2978 /*! \brief update_call_counter: Handle call_limit for SIP users
2979 * Setting a call-limit will cause calls above the limit not to be accepted.
2981 * Remember that for a type=friend, there's one limit for the user and
2982 * another for the peer, not a combined call limit.
2983 * This will cause unexpected behaviour in subscriptions, since a "friend"
2984 * is *two* devices in Asterisk, not one.
2986 * Thought: For realtime, we should propably update storage with inuse counter...
2988 * \return 0 if call is ok (no call limit, below treshold)
2989 * -1 on rejection of call
2992 static int update_call_counter(struct sip_pvt
*fup
, int event
)
2995 int *inuse
= NULL
, *call_limit
= NULL
, *inringing
= NULL
;
2996 int outgoing
= ast_test_flag(&fup
->flags
[1], SIP_PAGE2_OUTGOING_CALL
);
2997 struct sip_user
*u
= NULL
;
2998 struct sip_peer
*p
= NULL
;
3000 if (option_debug
> 2)
3001 ast_log(LOG_DEBUG
, "Updating call counter for %s call\n", outgoing
? "outgoing" : "incoming");
3002 /* Test if we need to check call limits, in order to avoid
3003 realtime lookups if we do not need it */
3004 if (!ast_test_flag(&fup
->flags
[0], SIP_CALL_LIMIT
))
3007 ast_copy_string(name
, fup
->username
, sizeof(name
));
3009 /* Check the list of users only for incoming calls */
3010 if (global_limitonpeers
== FALSE
&& !outgoing
&& (u
= find_user(name
, 1))) {
3012 call_limit
= &u
->call_limit
;
3014 } else if ( (p
= find_peer(ast_strlen_zero(fup
->peername
) ? name
: fup
->peername
, NULL
, 1) ) ) { /* Try to find peer */
3016 call_limit
= &p
->call_limit
;
3017 inringing
= &p
->inRinging
;
3018 ast_copy_string(name
, fup
->peername
, sizeof(name
));
3021 if (option_debug
> 1)
3022 ast_log(LOG_DEBUG
, "%s is not a local device, no call limit\n", name
);
3027 /* incoming and outgoing affects the inUse counter */
3028 case DEC_CALL_LIMIT
:
3030 if (ast_test_flag(&fup
->flags
[0], SIP_INC_COUNT
)) {
3032 ast_clear_flag(&fup
->flags
[0], SIP_INC_COUNT
);
3038 if (ast_test_flag(&fup
->flags
[1], SIP_PAGE2_INC_RINGING
)) {
3042 ast_log(LOG_WARNING
, "Inringing for peer '%s' < 0?\n", fup
->peername
);
3043 ast_clear_flag(&fup
->flags
[1], SIP_PAGE2_INC_RINGING
);
3046 if (ast_test_flag(&fup
->flags
[1], SIP_PAGE2_CALL_ONHOLD
) && global_notifyhold
)
3047 sip_peer_hold(fup
, 0);
3048 if (option_debug
> 1 || sipdebug
) {
3049 ast_log(LOG_DEBUG
, "Call %s %s '%s' removed from call limit %d\n", outgoing
? "to" : "from", u
? "user":"peer", name
, *call_limit
);
3053 case INC_CALL_RINGING
:
3054 case INC_CALL_LIMIT
:
3055 if (*call_limit
> 0 ) {
3056 if (*inuse
>= *call_limit
) {
3057 ast_log(LOG_ERROR
, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing
? "to" : "from", u
? "user":"peer", name
, *call_limit
);
3059 ASTOBJ_UNREF(u
, sip_destroy_user
);
3061 ASTOBJ_UNREF(p
, sip_destroy_peer
);
3065 if (inringing
&& (event
== INC_CALL_RINGING
)) {
3066 if (!ast_test_flag(&fup
->flags
[1], SIP_PAGE2_INC_RINGING
)) {
3068 ast_set_flag(&fup
->flags
[1], SIP_PAGE2_INC_RINGING
);
3073 ast_set_flag(&fup
->flags
[0], SIP_INC_COUNT
);
3074 if (option_debug
> 1 || sipdebug
) {
3075 ast_log(LOG_DEBUG
, "Call %s %s '%s' is %d out of %d\n", outgoing
? "to" : "from", u
? "user":"peer", name
, *inuse
, *call_limit
);
3079 case DEC_CALL_RINGING
:
3081 if (ast_test_flag(&fup
->flags
[1], SIP_PAGE2_INC_RINGING
)) {
3085 ast_log(LOG_WARNING
, "Inringing for peer '%s' < 0?\n", p
->name
);
3086 ast_clear_flag(&fup
->flags
[1], SIP_PAGE2_INC_RINGING
);
3092 ast_log(LOG_ERROR
, "update_call_counter(%s, %d) called with no event!\n", name
, event
);
3095 ast_device_state_changed("SIP/%s", p
->name
);
3096 ASTOBJ_UNREF(p
, sip_destroy_peer
);
3097 } else /* u must be set */
3098 ASTOBJ_UNREF(u
, sip_destroy_user
);
3102 /*! \brief Destroy SIP call structure */
3103 static void sip_destroy(struct sip_pvt
*p
)
3105 ast_mutex_lock(&iflock
);
3106 if (option_debug
> 2)
3107 ast_log(LOG_DEBUG
, "Destroying SIP dialog %s\n", p
->callid
);
3108 __sip_destroy(p
, 1);
3109 ast_mutex_unlock(&iflock
);
3112 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
3113 static int hangup_sip2cause(int cause
)
3115 /* Possible values taken from causes.h */
3118 case 401: /* Unauthorized */
3119 return AST_CAUSE_CALL_REJECTED
;
3120 case 403: /* Not found */
3121 return AST_CAUSE_CALL_REJECTED
;
3122 case 404: /* Not found */
3123 return AST_CAUSE_UNALLOCATED
;
3124 case 405: /* Method not allowed */
3125 return AST_CAUSE_INTERWORKING
;
3126 case 407: /* Proxy authentication required */
3127 return AST_CAUSE_CALL_REJECTED
;
3128 case 408: /* No reaction */
3129 return AST_CAUSE_NO_USER_RESPONSE
;
3130 case 409: /* Conflict */
3131 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE
;
3132 case 410: /* Gone */
3133 return AST_CAUSE_UNALLOCATED
;
3134 case 411: /* Length required */
3135 return AST_CAUSE_INTERWORKING
;
3136 case 413: /* Request entity too large */
3137 return AST_CAUSE_INTERWORKING
;
3138 case 414: /* Request URI too large */
3139 return AST_CAUSE_INTERWORKING
;
3140 case 415: /* Unsupported media type */
3141 return AST_CAUSE_INTERWORKING
;
3142 case 420: /* Bad extension */
3143 return AST_CAUSE_NO_ROUTE_DESTINATION
;
3144 case 480: /* No answer */
3145 return AST_CAUSE_NO_ANSWER
;
3146 case 481: /* No answer */
3147 return AST_CAUSE_INTERWORKING
;
3148 case 482: /* Loop detected */
3149 return AST_CAUSE_INTERWORKING
;
3150 case 483: /* Too many hops */
3151 return AST_CAUSE_NO_ANSWER
;
3152 case 484: /* Address incomplete */
3153 return AST_CAUSE_INVALID_NUMBER_FORMAT
;
3154 case 485: /* Ambigous */
3155 return AST_CAUSE_UNALLOCATED
;
3156 case 486: /* Busy everywhere */
3157 return AST_CAUSE_BUSY
;
3158 case 487: /* Request terminated */
3159 return AST_CAUSE_INTERWORKING
;
3160 case 488: /* No codecs approved */
3161 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
;
3162 case 491: /* Request pending */
3163 return AST_CAUSE_INTERWORKING
;
3164 case 493: /* Undecipherable */
3165 return AST_CAUSE_INTERWORKING
;
3166 case 500: /* Server internal failure */
3167 return AST_CAUSE_FAILURE
;
3168 case 501: /* Call rejected */
3169 return AST_CAUSE_FACILITY_REJECTED
;
3171 return AST_CAUSE_DESTINATION_OUT_OF_ORDER
;
3172 case 503: /* Service unavailable */
3173 return AST_CAUSE_CONGESTION
;
3174 case 504: /* Gateway timeout */
3175 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE
;
3176 case 505: /* SIP version not supported */
3177 return AST_CAUSE_INTERWORKING
;
3178 case 600: /* Busy everywhere */
3179 return AST_CAUSE_USER_BUSY
;
3180 case 603: /* Decline */
3181 return AST_CAUSE_CALL_REJECTED
;
3182 case 604: /* Does not exist anywhere */
3183 return AST_CAUSE_UNALLOCATED
;
3184 case 606: /* Not acceptable */
3185 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
;
3187 return AST_CAUSE_NORMAL
;
3193 /*! \brief Convert Asterisk hangup causes to SIP codes
3195 Possible values from causes.h
3196 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
3197 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
3199 In addition to these, a lot of PRI codes is defined in causes.h
3200 ...should we take care of them too ?
3204 ISUP Cause value SIP response
3205 ---------------- ------------
3206 1 unallocated number 404 Not Found
3207 2 no route to network 404 Not found
3208 3 no route to destination 404 Not found
3209 16 normal call clearing --- (*)
3210 17 user busy 486 Busy here
3211 18 no user responding 408 Request Timeout
3212 19 no answer from the user 480 Temporarily unavailable
3213 20 subscriber absent 480 Temporarily unavailable
3214 21 call rejected 403 Forbidden (+)
3215 22 number changed (w/o diagnostic) 410 Gone
3216 22 number changed (w/ diagnostic) 301 Moved Permanently
3217 23 redirection to new destination 410 Gone
3218 26 non-selected user clearing 404 Not Found (=)
3219 27 destination out of order 502 Bad Gateway
3220 28 address incomplete 484 Address incomplete
3221 29 facility rejected 501 Not implemented
3222 31 normal unspecified 480 Temporarily unavailable
3225 static const char *hangup_cause2sip(int cause
)
3228 case AST_CAUSE_UNALLOCATED
: /* 1 */
3229 case AST_CAUSE_NO_ROUTE_DESTINATION
: /* 3 IAX2: Can't find extension in context */
3230 case AST_CAUSE_NO_ROUTE_TRANSIT_NET
: /* 2 */
3231 return "404 Not Found";
3232 case AST_CAUSE_CONGESTION
: /* 34 */
3233 case AST_CAUSE_SWITCH_CONGESTION
: /* 42 */
3234 return "503 Service Unavailable";
3235 case AST_CAUSE_NO_USER_RESPONSE
: /* 18 */
3236 return "408 Request Timeout";
3237 case AST_CAUSE_NO_ANSWER
: /* 19 */
3238 return "480 Temporarily unavailable";
3239 case AST_CAUSE_CALL_REJECTED
: /* 21 */
3240 return "403 Forbidden";
3241 case AST_CAUSE_NUMBER_CHANGED
: /* 22 */
3243 case AST_CAUSE_NORMAL_UNSPECIFIED
: /* 31 */
3244 return "480 Temporarily unavailable";
3245 case AST_CAUSE_INVALID_NUMBER_FORMAT
:
3246 return "484 Address incomplete";
3247 case AST_CAUSE_USER_BUSY
:
3248 return "486 Busy here";
3249 case AST_CAUSE_FAILURE
:
3250 return "500 Server internal failure";
3251 case AST_CAUSE_FACILITY_REJECTED
: /* 29 */
3252 return "501 Not Implemented";
3253 case AST_CAUSE_CHAN_NOT_IMPLEMENTED
:
3254 return "503 Service Unavailable";
3255 /* Used in chan_iax2 */
3256 case AST_CAUSE_DESTINATION_OUT_OF_ORDER
:
3257 return "502 Bad Gateway";
3258 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
: /* Can't find codec to connect to host */
3259 return "488 Not Acceptable Here";
3261 case AST_CAUSE_NOTDEFINED
:
3264 ast_log(LOG_DEBUG
, "AST hangup cause %d (no match found in SIP)\n", cause
);
3273 /*! \brief sip_hangup: Hangup SIP call
3274 * Part of PBX interface, called from ast_hangup */
3275 static int sip_hangup(struct ast_channel
*ast
)
3277 struct sip_pvt
*p
= ast
->tech_pvt
;
3278 int needcancel
= FALSE
;
3279 int needdestroy
= 0;
3280 struct ast_channel
*oldowner
= ast
;
3284 ast_log(LOG_DEBUG
, "Asked to hangup channel that was not connected\n");
3288 if (ast_test_flag(&p
->flags
[0], SIP_DEFER_BYE_ON_TRANSFER
)) {
3289 if (ast_test_flag(&p
->flags
[0], SIP_INC_COUNT
)) {
3290 if (option_debug
&& sipdebug
)
3291 ast_log(LOG_DEBUG
, "update_call_counter(%s) - decrement call limit counter on hangup\n", p
->username
);
3292 update_call_counter(p
, DEC_CALL_LIMIT
);
3294 if (option_debug
>3)
3295 ast_log(LOG_DEBUG
, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p
->callid
);
3296 if (p
->autokillid
> -1)
3297 sip_cancel_destroy(p
);
3298 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
3299 ast_clear_flag(&p
->flags
[0], SIP_DEFER_BYE_ON_TRANSFER
); /* Really hang up next time */
3300 ast_clear_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
3301 p
->owner
->tech_pvt
= NULL
;
3302 p
->owner
= NULL
; /* Owner will be gone after we return, so take it away */
3306 if (ast_test_flag(ast
, AST_FLAG_ZOMBIE
) && p
->refer
&& option_debug
)
3307 ast_log(LOG_DEBUG
, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast
->name
, p
->callid
);
3310 ast_log(LOG_DEBUG
, "Hangup call %s, SIP callid %s)\n", ast
->name
, p
->callid
);
3313 if (option_debug
&& ast_test_flag(ast
, AST_FLAG_ZOMBIE
))
3314 ast_log(LOG_DEBUG
, "Hanging up zombie call. Be scared.\n");
3316 ast_mutex_lock(&p
->lock
);
3317 if (ast_test_flag(&p
->flags
[0], SIP_INC_COUNT
)) {
3318 if (option_debug
&& sipdebug
)
3319 ast_log(LOG_DEBUG
, "update_call_counter(%s) - decrement call limit counter on hangup\n", p
->username
);
3320 update_call_counter(p
, DEC_CALL_LIMIT
);
3323 /* Determine how to disconnect */
3324 if (p
->owner
!= ast
) {
3325 ast_log(LOG_WARNING
, "Huh? We aren't the owner? Can't hangup call.\n");
3326 ast_mutex_unlock(&p
->lock
);
3329 /* If the call is not UP, we need to send CANCEL instead of BYE */
3330 if (ast
->_state
== AST_STATE_RING
|| ast
->_state
== AST_STATE_RINGING
|| (p
->invitestate
< INV_COMPLETED
&& ast
->_state
!= AST_STATE_UP
)) {
3332 if (option_debug
> 3)
3333 ast_log(LOG_DEBUG
, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast
->_state
));
3338 ast_dsp_free(p
->vad
);
3341 ast
->tech_pvt
= NULL
;
3343 ast_module_unref(ast_module_info
->self
);
3345 /* Do not destroy this pvt until we have timeout or
3346 get an answer to the BYE or INVITE/CANCEL
3347 If we get no answer during retransmit period, drop the call anyway.
3348 (Sorry, mother-in-law, you can't deny a hangup by sending
3349 603 declined to BYE...)
3351 if (ast_test_flag(&p
->flags
[0], SIP_ALREADYGONE
))
3352 needdestroy
= 1; /* Set destroy flag at end of this function */
3353 else if (p
->invitestate
!= INV_CALLING
)
3354 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
3356 /* Start the process if it's not already started */
3357 if (!ast_test_flag(&p
->flags
[0], SIP_ALREADYGONE
) && !ast_strlen_zero(p
->initreq
.data
)) {
3358 if (needcancel
) { /* Outgoing call, not up */
3359 if (ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) {
3360 /* stop retransmitting an INVITE that has not received a response */
3361 __sip_pretend_ack(p
);
3363 /* if we can't send right now, mark it pending */
3364 if (p
->invitestate
== INV_CALLING
) {
3365 /* We can't send anything in CALLING state */
3366 ast_set_flag(&p
->flags
[0], SIP_PENDINGBYE
);
3367 /* Do we need a timer here if we don't hear from them at all? */
3369 /* Send a new request: CANCEL */
3370 transmit_request(p
, SIP_CANCEL
, p
->ocseq
, XMIT_RELIABLE
, FALSE
);
3371 /* Actually don't destroy us yet, wait for the 487 on our original
3372 INVITE, but do set an autodestruct just in case we never get it. */
3374 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
3376 if ( p
->initid
!= -1 ) {
3377 /* channel still up - reverse dec of inUse counter
3378 only if the channel is not auto-congested */
3379 update_call_counter(p
, INC_CALL_LIMIT
);
3381 } else { /* Incoming call, not up */
3383 if (ast
->hangupcause
&& (res
= hangup_cause2sip(ast
->hangupcause
)))
3384 transmit_response_reliable(p
, res
, &p
->initreq
);
3386 transmit_response_reliable(p
, "603 Declined", &p
->initreq
);
3388 } else { /* Call is in UP state, send BYE */
3389 if (!p
->pendinginvite
) {
3390 char *audioqos
= "";
3391 char *videoqos
= "";
3393 audioqos
= ast_rtp_get_quality(p
->rtp
);
3395 videoqos
= ast_rtp_get_quality(p
->vrtp
);
3397 transmit_request_with_auth(p
, SIP_BYE
, 0, XMIT_RELIABLE
, 1);
3399 /* Get RTCP quality before end of call */
3400 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
)) {
3402 append_history(p
, "RTCPaudio", "Quality:%s", audioqos
);
3404 append_history(p
, "RTCPvideo", "Quality:%s", videoqos
);
3406 if (p
->rtp
&& oldowner
)
3407 pbx_builtin_setvar_helper(oldowner
, "RTPAUDIOQOS", audioqos
);
3408 if (p
->vrtp
&& oldowner
)
3409 pbx_builtin_setvar_helper(oldowner
, "RTPVIDEOQOS", videoqos
);
3411 /* Note we will need a BYE when this all settles out
3412 but we can't send one while we have "INVITE" outstanding. */
3413 ast_set_flag(&p
->flags
[0], SIP_PENDINGBYE
);
3414 ast_clear_flag(&p
->flags
[0], SIP_NEEDREINVITE
);
3415 sip_cancel_destroy(p
);
3420 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
3421 ast_mutex_unlock(&p
->lock
);
3425 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
3426 static void try_suggested_sip_codec(struct sip_pvt
*p
)
3431 codec
= pbx_builtin_getvar_helper(p
->owner
, "SIP_CODEC");
3435 fmt
= ast_getformatbyname(codec
);
3437 ast_log(LOG_NOTICE
, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec
);
3438 if (p
->jointcapability
& fmt
) {
3439 p
->jointcapability
&= fmt
;
3440 p
->capability
&= fmt
;
3442 ast_log(LOG_NOTICE
, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
3444 ast_log(LOG_NOTICE
, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec
);
3448 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
3449 * Part of PBX interface */
3450 static int sip_answer(struct ast_channel
*ast
)
3453 struct sip_pvt
*p
= ast
->tech_pvt
;
3455 ast_mutex_lock(&p
->lock
);
3456 if (ast
->_state
!= AST_STATE_UP
) {
3457 try_suggested_sip_codec(p
);
3459 ast_setstate(ast
, AST_STATE_UP
);
3461 ast_log(LOG_DEBUG
, "SIP answering channel: %s\n", ast
->name
);
3462 if (p
->t38
.state
== T38_PEER_DIRECT
) {
3463 p
->t38
.state
= T38_ENABLED
;
3464 if (option_debug
> 1)
3465 ast_log(LOG_DEBUG
,"T38State change to %d on channel %s\n", p
->t38
.state
, ast
->name
);
3466 res
= transmit_response_with_t38_sdp(p
, "200 OK", &p
->initreq
, XMIT_CRITICAL
);
3468 res
= transmit_response_with_sdp(p
, "200 OK", &p
->initreq
, XMIT_CRITICAL
);
3470 ast_mutex_unlock(&p
->lock
);
3474 /*! \brief Send frame to media channel (rtp) */
3475 static int sip_write(struct ast_channel
*ast
, struct ast_frame
*frame
)
3477 struct sip_pvt
*p
= ast
->tech_pvt
;
3480 switch (frame
->frametype
) {
3481 case AST_FRAME_VOICE
:
3482 if (!(frame
->subclass
& ast
->nativeformats
)) {
3483 char s1
[512], s2
[512], s3
[512];
3484 ast_log(LOG_WARNING
, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
3486 ast_getformatname_multiple(s1
, sizeof(s1
) - 1, ast
->nativeformats
& AST_FORMAT_AUDIO_MASK
),
3487 ast
->nativeformats
& AST_FORMAT_AUDIO_MASK
,
3488 ast_getformatname_multiple(s2
, sizeof(s2
) - 1, ast
->readformat
),
3490 ast_getformatname_multiple(s3
, sizeof(s3
) - 1, ast
->writeformat
),
3495 ast_mutex_lock(&p
->lock
);
3497 /* If channel is not up, activate early media session */
3498 if ((ast
->_state
!= AST_STATE_UP
) &&
3499 !ast_test_flag(&p
->flags
[0], SIP_PROGRESS_SENT
) &&
3500 !ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) {
3501 transmit_response_with_sdp(p
, "183 Session Progress", &p
->initreq
, XMIT_UNRELIABLE
);
3502 ast_set_flag(&p
->flags
[0], SIP_PROGRESS_SENT
);
3504 p
->lastrtptx
= time(NULL
);
3505 res
= ast_rtp_write(p
->rtp
, frame
);
3507 ast_mutex_unlock(&p
->lock
);
3510 case AST_FRAME_VIDEO
:
3512 ast_mutex_lock(&p
->lock
);
3514 /* Activate video early media */
3515 if ((ast
->_state
!= AST_STATE_UP
) &&
3516 !ast_test_flag(&p
->flags
[0], SIP_PROGRESS_SENT
) &&
3517 !ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) {
3518 transmit_response_with_sdp(p
, "183 Session Progress", &p
->initreq
, XMIT_UNRELIABLE
);
3519 ast_set_flag(&p
->flags
[0], SIP_PROGRESS_SENT
);
3521 p
->lastrtptx
= time(NULL
);
3522 res
= ast_rtp_write(p
->vrtp
, frame
);
3524 ast_mutex_unlock(&p
->lock
);
3527 case AST_FRAME_IMAGE
:
3530 case AST_FRAME_MODEM
:
3532 ast_mutex_lock(&p
->lock
);
3533 /* UDPTL requires two-way communication, so early media is not needed here.
3534 we simply forget the frames if we get modem frames before the bridge is up.
3535 Fax will re-transmit.
3537 if (p
->udptl
&& ast
->_state
== AST_STATE_UP
)
3538 res
= ast_udptl_write(p
->udptl
, frame
);
3539 ast_mutex_unlock(&p
->lock
);
3543 ast_log(LOG_WARNING
, "Can't send %d type frames with SIP write\n", frame
->frametype
);
3550 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
3551 Basically update any ->owner links */
3552 static int sip_fixup(struct ast_channel
*oldchan
, struct ast_channel
*newchan
)
3557 if (newchan
&& ast_test_flag(newchan
, AST_FLAG_ZOMBIE
) && option_debug
)
3558 ast_log(LOG_DEBUG
, "New channel is zombie\n");
3559 if (oldchan
&& ast_test_flag(oldchan
, AST_FLAG_ZOMBIE
) && option_debug
)
3560 ast_log(LOG_DEBUG
, "Old channel is zombie\n");
3562 if (!newchan
|| !newchan
->tech_pvt
) {
3564 ast_log(LOG_WARNING
, "No new channel! Fixup of %s failed.\n", oldchan
->name
);
3566 ast_log(LOG_WARNING
, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan
->name
);
3569 p
= newchan
->tech_pvt
;
3572 ast_log(LOG_WARNING
, "No pvt after masquerade. Strange things may happen\n");
3576 ast_mutex_lock(&p
->lock
);
3577 append_history(p
, "Masq", "Old channel: %s\n", oldchan
->name
);
3578 append_history(p
, "Masq (cont)", "...new owner: %s\n", newchan
->name
);
3579 if (p
->owner
!= oldchan
)
3580 ast_log(LOG_WARNING
, "old channel wasn't %p but was %p\n", oldchan
, p
->owner
);
3585 if (option_debug
> 2)
3586 ast_log(LOG_DEBUG
, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p
->callid
, p
->owner
->name
, oldchan
->name
);
3588 ast_mutex_unlock(&p
->lock
);
3592 static int sip_senddigit_begin(struct ast_channel
*ast
, char digit
)
3594 struct sip_pvt
*p
= ast
->tech_pvt
;
3597 ast_mutex_lock(&p
->lock
);
3598 switch (ast_test_flag(&p
->flags
[0], SIP_DTMF
)) {
3599 case SIP_DTMF_INBAND
:
3600 res
= -1; /* Tell Asterisk to generate inband indications */
3602 case SIP_DTMF_RFC2833
:
3604 ast_rtp_senddigit_begin(p
->rtp
, digit
);
3609 ast_mutex_unlock(&p
->lock
);
3614 /*! \brief Send DTMF character on SIP channel
3615 within one call, we're able to transmit in many methods simultaneously */
3616 static int sip_senddigit_end(struct ast_channel
*ast
, char digit
, unsigned int duration
)
3618 struct sip_pvt
*p
= ast
->tech_pvt
;
3621 ast_mutex_lock(&p
->lock
);
3622 switch (ast_test_flag(&p
->flags
[0], SIP_DTMF
)) {
3624 transmit_info_with_digit(p
, digit
, duration
);
3626 case SIP_DTMF_RFC2833
:
3628 ast_rtp_senddigit_end(p
->rtp
, digit
);
3630 case SIP_DTMF_INBAND
:
3631 res
= -1; /* Tell Asterisk to stop inband indications */
3634 ast_mutex_unlock(&p
->lock
);
3639 /*! \brief Transfer SIP call */
3640 static int sip_transfer(struct ast_channel
*ast
, const char *dest
)
3642 struct sip_pvt
*p
= ast
->tech_pvt
;
3645 if (dest
== NULL
) /* functions below do not take a NULL */
3647 ast_mutex_lock(&p
->lock
);
3648 if (ast
->_state
== AST_STATE_RING
)
3649 res
= sip_sipredirect(p
, dest
);
3651 res
= transmit_refer(p
, dest
);
3652 ast_mutex_unlock(&p
->lock
);
3656 /*! \brief Play indication to user
3657 * With SIP a lot of indications is sent as messages, letting the device play
3658 the indication - busy signal, congestion etc
3659 \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
3661 static int sip_indicate(struct ast_channel
*ast
, int condition
, const void *data
, size_t datalen
)
3663 struct sip_pvt
*p
= ast
->tech_pvt
;
3666 ast_mutex_lock(&p
->lock
);
3668 case AST_CONTROL_RINGING
:
3669 if (ast
->_state
== AST_STATE_RING
) {
3670 p
->invitestate
= INV_EARLY_MEDIA
;
3671 if (!ast_test_flag(&p
->flags
[0], SIP_PROGRESS_SENT
) ||
3672 (ast_test_flag(&p
->flags
[0], SIP_PROG_INBAND
) == SIP_PROG_INBAND_NEVER
)) {
3673 /* Send 180 ringing if out-of-band seems reasonable */
3674 transmit_response(p
, "180 Ringing", &p
->initreq
);
3675 ast_set_flag(&p
->flags
[0], SIP_RINGING
);
3676 if (ast_test_flag(&p
->flags
[0], SIP_PROG_INBAND
) != SIP_PROG_INBAND_YES
)
3679 /* Well, if it's not reasonable, just send in-band */
3684 case AST_CONTROL_BUSY
:
3685 if (ast
->_state
!= AST_STATE_UP
) {
3686 transmit_response(p
, "486 Busy Here", &p
->initreq
);
3687 p
->invitestate
= INV_COMPLETED
;
3689 ast_softhangup_nolock(ast
, AST_SOFTHANGUP_DEV
);
3694 case AST_CONTROL_CONGESTION
:
3695 if (ast
->_state
!= AST_STATE_UP
) {
3696 transmit_response(p
, "503 Service Unavailable", &p
->initreq
);
3697 p
->invitestate
= INV_COMPLETED
;
3699 ast_softhangup_nolock(ast
, AST_SOFTHANGUP_DEV
);
3704 case AST_CONTROL_PROCEEDING
:
3705 if ((ast
->_state
!= AST_STATE_UP
) &&
3706 !ast_test_flag(&p
->flags
[0], SIP_PROGRESS_SENT
) &&
3707 !ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) {
3708 transmit_response(p
, "100 Trying", &p
->initreq
);
3709 p
->invitestate
= INV_PROCEEDING
;
3714 case AST_CONTROL_PROGRESS
:
3715 if ((ast
->_state
!= AST_STATE_UP
) &&
3716 !ast_test_flag(&p
->flags
[0], SIP_PROGRESS_SENT
) &&
3717 !ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) {
3718 p
->invitestate
= INV_EARLY_MEDIA
;
3719 transmit_response_with_sdp(p
, "183 Session Progress", &p
->initreq
, XMIT_UNRELIABLE
);
3720 ast_set_flag(&p
->flags
[0], SIP_PROGRESS_SENT
);
3725 case AST_CONTROL_HOLD
:
3726 ast_moh_start(ast
, data
, p
->mohinterpret
);
3728 case AST_CONTROL_UNHOLD
:
3731 case AST_CONTROL_VIDUPDATE
: /* Request a video frame update */
3732 if (p
->vrtp
&& !ast_test_flag(&p
->flags
[0], SIP_NOVIDEO
)) {
3733 transmit_info_with_vidupdate(p
);
3734 /* ast_rtcp_send_h261fur(p->vrtp); */
3742 ast_log(LOG_WARNING
, "Don't know how to indicate condition %d\n", condition
);
3746 ast_mutex_unlock(&p
->lock
);
3752 /*! \brief Initiate a call in the SIP channel
3753 called from sip_request_call (calls from the pbx ) for outbound channels
3754 and from handle_request_invite for inbound channels
3757 static struct ast_channel
*sip_new(struct sip_pvt
*i
, int state
, const char *title
)
3759 struct ast_channel
*tmp
;
3760 struct ast_variable
*v
= NULL
;
3765 const char *my_name
; /* pick a good name */
3769 else if ( (my_name
= strchr(i
->fromdomain
,':')) )
3770 my_name
++; /* skip ':' */
3772 my_name
= i
->fromdomain
;
3774 ast_mutex_unlock(&i
->lock
);
3775 /* Don't hold a sip pvt lock while we allocate a channel */
3776 tmp
= ast_channel_alloc(1, state
, i
->cid_num
, i
->cid_name
, "SIP/%s-%08x", my_name
, (int)(long) i
);
3780 ast_log(LOG_WARNING
, "Unable to allocate AST channel structure for SIP channel\n");
3783 ast_mutex_lock(&i
->lock
);
3785 if (ast_test_flag(&i
->flags
[0], SIP_DTMF
) == SIP_DTMF_INFO
)
3786 tmp
->tech
= &sip_tech_info
;
3788 tmp
->tech
= &sip_tech
;
3790 /* Select our native format based on codec preference until we receive
3791 something from another device to the contrary. */
3792 if (i
->jointcapability
) /* The joint capabilities of us and peer */
3793 what
= i
->jointcapability
;
3794 else if (i
->capability
) /* Our configured capability for this peer */
3795 what
= i
->capability
;
3797 what
= global_capability
; /* Global codec support */
3799 /* Set the native formats for audio and merge in video */
3800 tmp
->nativeformats
= ast_codec_choose(&i
->prefs
, what
, 1) | (i
->jointcapability
& AST_FORMAT_VIDEO_MASK
);
3801 if (option_debug
> 2) {
3803 ast_log(LOG_DEBUG
, "*** Our native formats are %s \n", ast_getformatname_multiple(buf
, BUFSIZ
, tmp
->nativeformats
));
3804 ast_log(LOG_DEBUG
, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf
, BUFSIZ
, i
->jointcapability
));
3805 ast_log(LOG_DEBUG
, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf
, BUFSIZ
, i
->capability
));
3806 ast_log(LOG_DEBUG
, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf
, BUFSIZ
, ast_codec_choose(&i
->prefs
, what
, 1)));
3808 ast_log(LOG_DEBUG
, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf
, BUFSIZ
, i
->prefcodec
));
3811 /* XXX Why are we choosing a codec from the native formats?? */
3812 fmt
= ast_best_codec(tmp
->nativeformats
);
3814 /* If we have a prefcodec setting, we have an inbound channel that set a
3815 preferred format for this call. Otherwise, we check the jointcapability
3816 We also check for vrtp. If it's not there, we are not allowed do any video anyway.
3820 needvideo
= i
->prefcodec
& AST_FORMAT_VIDEO_MASK
; /* Outbound call */
3822 needvideo
= i
->jointcapability
& AST_FORMAT_VIDEO_MASK
; /* Inbound call */
3825 if (option_debug
> 2) {
3827 ast_log(LOG_DEBUG
, "This channel can handle video! HOLLYWOOD next!\n");
3829 ast_log(LOG_DEBUG
, "This channel will not be able to handle video.\n");
3834 if (ast_test_flag(&i
->flags
[0], SIP_DTMF
) == SIP_DTMF_INBAND
) {
3835 i
->vad
= ast_dsp_new();
3836 ast_dsp_set_features(i
->vad
, DSP_FEATURE_DTMF_DETECT
);
3837 if (global_relaxdtmf
)
3838 ast_dsp_digitmode(i
->vad
, DSP_DIGITMODE_DTMF
| DSP_DIGITMODE_RELAXDTMF
);
3841 tmp
->fds
[0] = ast_rtp_fd(i
->rtp
);
3842 tmp
->fds
[1] = ast_rtcp_fd(i
->rtp
);
3844 if (needvideo
&& i
->vrtp
) {
3845 tmp
->fds
[2] = ast_rtp_fd(i
->vrtp
);
3846 tmp
->fds
[3] = ast_rtcp_fd(i
->vrtp
);
3849 tmp
->fds
[5] = ast_udptl_fd(i
->udptl
);
3851 if (state
== AST_STATE_RING
)
3853 tmp
->adsicpe
= AST_ADSI_UNAVAILABLE
;
3854 tmp
->writeformat
= fmt
;
3855 tmp
->rawwriteformat
= fmt
;
3856 tmp
->readformat
= fmt
;
3857 tmp
->rawreadformat
= fmt
;
3860 tmp
->callgroup
= i
->callgroup
;
3861 tmp
->pickupgroup
= i
->pickupgroup
;
3862 tmp
->cid
.cid_pres
= i
->callingpres
;
3863 if (!ast_strlen_zero(i
->accountcode
))
3864 ast_string_field_set(tmp
, accountcode
, i
->accountcode
);
3866 tmp
->amaflags
= i
->amaflags
;
3867 if (!ast_strlen_zero(i
->language
))
3868 ast_string_field_set(tmp
, language
, i
->language
);
3870 ast_module_ref(ast_module_info
->self
);
3871 ast_copy_string(tmp
->context
, i
->context
, sizeof(tmp
->context
));
3872 ast_copy_string(tmp
->exten
, i
->exten
, sizeof(tmp
->exten
));
3874 /* Don't use ast_set_callerid() here because it will
3875 * generate an unnecessary NewCallerID event */
3876 tmp
->cid
.cid_num
= ast_strdup(i
->cid_num
);
3877 tmp
->cid
.cid_ani
= ast_strdup(i
->cid_num
);
3878 tmp
->cid
.cid_name
= ast_strdup(i
->cid_name
);
3879 if (!ast_strlen_zero(i
->rdnis
))
3880 tmp
->cid
.cid_rdnis
= ast_strdup(i
->rdnis
);
3882 if (!ast_strlen_zero(i
->exten
) && strcmp(i
->exten
, "s"))
3883 tmp
->cid
.cid_dnid
= ast_strdup(i
->exten
);
3886 if (!ast_strlen_zero(i
->uri
))
3887 pbx_builtin_setvar_helper(tmp
, "SIPURI", i
->uri
);
3888 if (!ast_strlen_zero(i
->domain
))
3889 pbx_builtin_setvar_helper(tmp
, "SIPDOMAIN", i
->domain
);
3890 if (!ast_strlen_zero(i
->useragent
))
3891 pbx_builtin_setvar_helper(tmp
, "SIPUSERAGENT", i
->useragent
);
3892 if (!ast_strlen_zero(i
->callid
))
3893 pbx_builtin_setvar_helper(tmp
, "SIPCALLID", i
->callid
);
3895 ast_jb_configure(tmp
, &global_jbconf
);
3896 if (state
!= AST_STATE_DOWN
&& ast_pbx_start(tmp
)) {
3897 ast_log(LOG_WARNING
, "Unable to start PBX on %s\n", tmp
->name
);
3898 tmp
->hangupcause
= AST_CAUSE_SWITCH_CONGESTION
;
3902 /* Set channel variables for this call from configuration */
3903 for (v
= i
->chanvars
; v
; v
= v
->next
)
3904 pbx_builtin_setvar_helper(tmp
,v
->name
,v
->value
);
3906 if (!ast_test_flag(&i
->flags
[0], SIP_NO_HISTORY
))
3907 append_history(i
, "NewChan", "Channel %s - from %s", tmp
->name
, i
->callid
);
3912 /*! \brief Reads one line of SIP message body */
3913 static char *get_body_by_line(const char *line
, const char *name
, int nameLen
)
3915 if (strncasecmp(line
, name
, nameLen
) == 0 && line
[nameLen
] == '=')
3916 return ast_skip_blanks(line
+ nameLen
+ 1);
3921 /*! \brief Lookup 'name' in the SDP starting
3922 * at the 'start' line. Returns the matching line, and 'start'
3923 * is updated with the next line number.
3925 static const char *get_sdp_iterate(int *start
, struct sip_request
*req
, const char *name
)
3927 int len
= strlen(name
);
3929 while (*start
< req
->sdp_end
) {
3930 const char *r
= get_body_by_line(req
->line
[(*start
)++], name
, len
);
3938 /*! \brief Get a line from an SDP message body */
3939 static const char *get_sdp(struct sip_request
*req
, const char *name
)
3943 return get_sdp_iterate(&dummy
, req
, name
);
3946 /*! \brief Get a specific line from the message body */
3947 static char *get_body(struct sip_request
*req
, char *name
)
3950 int len
= strlen(name
);
3953 for (x
= 0; x
< req
->lines
; x
++) {
3954 r
= get_body_by_line(req
->line
[x
], name
, len
);
3962 /*! \brief Find compressed SIP alias */
3963 static const char *find_alias(const char *name
, const char *_default
)
3965 /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
3966 static const struct cfalias
{
3967 char * const fullname
;
3968 char * const shortname
;
3970 { "Content-Type", "c" },
3971 { "Content-Encoding", "e" },
3975 { "Content-Length", "l" },
3978 { "Supported", "k" },
3979 { "Refer-To", "r" },
3980 { "Referred-By", "b" },
3981 { "Allow-Events", "u" },
3984 { "Accept-Contact", "a" },
3985 { "Reject-Contact", "j" },
3986 { "Request-Disposition", "d" },
3987 { "Session-Expires", "x" },
3988 { "Identity", "y" },
3989 { "Identity-Info", "n" },
3993 for (x
=0; x
<sizeof(aliases
) / sizeof(aliases
[0]); x
++)
3994 if (!strcasecmp(aliases
[x
].fullname
, name
))
3995 return aliases
[x
].shortname
;
4000 static const char *__get_header(const struct sip_request
*req
, const char *name
, int *start
)
4005 * Technically you can place arbitrary whitespace both before and after the ':' in
4006 * a header, although RFC3261 clearly says you shouldn't before, and place just
4007 * one afterwards. If you shouldn't do it, what absolute idiot decided it was
4008 * a good idea to say you can do it, and if you can do it, why in the hell would.
4009 * you say you shouldn't.
4010 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
4011 * and we always allow spaces after that for compatibility.
4013 for (pass
= 0; name
&& pass
< 2;pass
++) {
4014 int x
, len
= strlen(name
);
4015 for (x
=*start
; x
<req
->headers
; x
++) {
4016 if (!strncasecmp(req
->header
[x
], name
, len
)) {
4017 char *r
= req
->header
[x
] + len
; /* skip name */
4018 if (pedanticsipchecking
)
4019 r
= ast_skip_blanks(r
);
4023 return ast_skip_blanks(r
+1);
4027 if (pass
== 0) /* Try aliases */
4028 name
= find_alias(name
, NULL
);
4031 /* Don't return NULL, so get_header is always a valid pointer */
4035 /*! \brief Get header from SIP request */
4036 static const char *get_header(const struct sip_request
*req
, const char *name
)
4039 return __get_header(req
, name
, &start
);
4042 /*! \brief Read RTP from network */
4043 static struct ast_frame
*sip_rtp_read(struct ast_channel
*ast
, struct sip_pvt
*p
, int *faxdetect
)
4045 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
4046 struct ast_frame
*f
;
4049 /* We have no RTP allocated for this channel */
4050 return &ast_null_frame
;
4055 f
= ast_rtp_read(p
->rtp
); /* RTP Audio */
4058 f
= ast_rtcp_read(p
->rtp
); /* RTCP Control Channel */
4061 f
= ast_rtp_read(p
->vrtp
); /* RTP Video */
4064 f
= ast_rtcp_read(p
->vrtp
); /* RTCP Control Channel for video */
4067 f
= ast_udptl_read(p
->udptl
); /* UDPTL for T.38 */
4070 f
= &ast_null_frame
;
4072 /* Don't forward RFC2833 if we're not supposed to */
4073 if (f
&& (f
->frametype
== AST_FRAME_DTMF
) &&
4074 (ast_test_flag(&p
->flags
[0], SIP_DTMF
) != SIP_DTMF_RFC2833
))
4075 return &ast_null_frame
;
4077 /* We already hold the channel lock */
4078 if (!p
->owner
|| f
->frametype
!= AST_FRAME_VOICE
)
4081 if (f
->subclass
!= (p
->owner
->nativeformats
& AST_FORMAT_AUDIO_MASK
)) {
4082 if (!(f
->subclass
& p
->jointcapability
)) {
4084 ast_log(LOG_DEBUG
, "Bogus frame of format '%s' received from '%s'!\n",
4085 ast_getformatname(f
->subclass
), p
->owner
->name
);
4087 return &ast_null_frame
;
4090 ast_log(LOG_DEBUG
, "Oooh, format changed to %d\n", f
->subclass
);
4091 p
->owner
->nativeformats
= (p
->owner
->nativeformats
& AST_FORMAT_VIDEO_MASK
) | f
->subclass
;
4092 ast_set_read_format(p
->owner
, p
->owner
->readformat
);
4093 ast_set_write_format(p
->owner
, p
->owner
->writeformat
);
4096 if ((ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_INBAND
) && p
->vad
) {
4097 f
= ast_dsp_process(p
->owner
, p
->vad
, f
);
4098 if (f
&& f
->frametype
== AST_FRAME_DTMF
) {
4099 if (ast_test_flag(&p
->t38
.t38support
, SIP_PAGE2_T38SUPPORT_UDPTL
) && f
->subclass
== 'f') {
4101 ast_log(LOG_DEBUG
, "Fax CNG detected on %s\n", ast
->name
);
4103 } else if (option_debug
) {
4104 ast_log(LOG_DEBUG
, "* Detected inband DTMF '%c'\n", f
->subclass
);
4112 /*! \brief Read SIP RTP from channel */
4113 static struct ast_frame
*sip_read(struct ast_channel
*ast
)
4115 struct ast_frame
*fr
;
4116 struct sip_pvt
*p
= ast
->tech_pvt
;
4117 int faxdetected
= FALSE
;
4119 ast_mutex_lock(&p
->lock
);
4120 fr
= sip_rtp_read(ast
, p
, &faxdetected
);
4121 p
->lastrtprx
= time(NULL
);
4123 /* If we are NOT bridged to another channel, and we have detected fax tone we issue T38 re-invite to a peer */
4124 /* If we are bridged then it is the responsibility of the SIP device to issue T38 re-invite if it detects CNG or fax preamble */
4125 if (faxdetected
&& ast_test_flag(&p
->t38
.t38support
, SIP_PAGE2_T38SUPPORT_UDPTL
) && (p
->t38
.state
== T38_DISABLED
) && !(ast_bridged_channel(ast
))) {
4126 if (!ast_test_flag(&p
->flags
[0], SIP_GOTREFER
)) {
4127 if (!p
->pendinginvite
) {
4128 if (option_debug
> 2)
4129 ast_log(LOG_DEBUG
, "Sending reinvite on SIP (%s) for T.38 negotiation.\n",ast
->name
);
4130 p
->t38
.state
= T38_LOCAL_REINVITE
;
4131 transmit_reinvite_with_t38_sdp(p
);
4132 if (option_debug
> 1)
4133 ast_log(LOG_DEBUG
, "T38 state changed to %d on channel %s\n", p
->t38
.state
, ast
->name
);
4135 } else if (!ast_test_flag(&p
->flags
[0], SIP_PENDINGBYE
)) {
4136 if (option_debug
> 2)
4137 ast_log(LOG_DEBUG
, "Deferring reinvite on SIP (%s) - it will be re-negotiated for T.38\n", ast
->name
);
4138 ast_set_flag(&p
->flags
[0], SIP_NEEDREINVITE
);
4142 ast_mutex_unlock(&p
->lock
);
4147 /*! \brief Generate 32 byte random string for callid's etc */
4148 static char *generate_random_string(char *buf
, size_t size
)
4154 val
[x
] = ast_random();
4155 snprintf(buf
, size
, "%08lx%08lx%08lx%08lx", val
[0], val
[1], val
[2], val
[3]);
4160 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
4161 static void build_callid_pvt(struct sip_pvt
*pvt
)
4165 const char *host
= S_OR(pvt
->fromdomain
, ast_inet_ntoa(pvt
->ourip
));
4167 ast_string_field_build(pvt
, callid
, "%s@%s", generate_random_string(buf
, sizeof(buf
)), host
);
4171 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
4172 static void build_callid_registry(struct sip_registry
*reg
, struct in_addr ourip
, const char *fromdomain
)
4176 const char *host
= S_OR(fromdomain
, ast_inet_ntoa(ourip
));
4178 ast_string_field_build(reg
, callid
, "%s@%s", generate_random_string(buf
, sizeof(buf
)), host
);
4181 /*! \brief Make our SIP dialog tag */
4182 static void make_our_tag(char *tagbuf
, size_t len
)
4184 snprintf(tagbuf
, len
, "as%08lx", ast_random());
4187 /*! \brief Allocate SIP_PVT structure and set defaults */
4188 static struct sip_pvt
*sip_alloc(ast_string_field callid
, struct sockaddr_in
*sin
,
4189 int useglobal_nat
, const int intended_method
)
4193 if (!(p
= ast_calloc(1, sizeof(*p
))))
4196 if (ast_string_field_init(p
, 512)) {
4201 ast_mutex_init(&p
->lock
);
4203 p
->method
= intended_method
;
4206 p
->subscribed
= NONE
;
4208 p
->prefs
= default_prefs
; /* Set default codecs for this call */
4210 if (intended_method
!= SIP_OPTIONS
) /* Peerpoke has it's own system */
4211 p
->timer_t1
= 500; /* Default SIP retransmission timer T1 (RFC 3261) */
4215 if (ast_sip_ouraddrfor(&p
->sa
.sin_addr
, &p
->ourip
))
4220 /* Copy global flags to this PVT at setup. */
4221 ast_copy_flags(&p
->flags
[0], &global_flags
[0], SIP_FLAGS_TO_COPY
);
4222 ast_copy_flags(&p
->flags
[1], &global_flags
[1], SIP_PAGE2_FLAGS_TO_COPY
);
4224 ast_set2_flag(&p
->flags
[0], !recordhistory
, SIP_NO_HISTORY
);
4226 p
->branch
= ast_random();
4227 make_our_tag(p
->tag
, sizeof(p
->tag
));
4228 p
->ocseq
= INITIAL_CSEQ
;
4230 if (sip_methods
[intended_method
].need_rtp
) {
4231 p
->rtp
= ast_rtp_new_with_bindaddr(sched
, io
, 1, 0, bindaddr
.sin_addr
);
4232 /* If the global videosupport flag is on, we always create a RTP interface for video */
4233 if (ast_test_flag(&p
->flags
[1], SIP_PAGE2_VIDEOSUPPORT
))
4234 p
->vrtp
= ast_rtp_new_with_bindaddr(sched
, io
, 1, 0, bindaddr
.sin_addr
);
4235 if (ast_test_flag(&p
->flags
[1], SIP_PAGE2_T38SUPPORT
))
4236 p
->udptl
= ast_udptl_new_with_bindaddr(sched
, io
, 0, bindaddr
.sin_addr
);
4237 if (!p
->rtp
|| (ast_test_flag(&p
->flags
[1], SIP_PAGE2_VIDEOSUPPORT
) && !p
->vrtp
)) {
4238 ast_log(LOG_WARNING
, "Unable to create RTP audio %s session: %s\n",
4239 ast_test_flag(&p
->flags
[1], SIP_PAGE2_VIDEOSUPPORT
) ? "and video" : "", strerror(errno
));
4240 ast_mutex_destroy(&p
->lock
);
4242 ast_variables_destroy(p
->chanvars
);
4248 ast_rtp_setdtmf(p
->rtp
, ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_RFC2833
);
4249 ast_rtp_setdtmfcompensate(p
->rtp
, ast_test_flag(&p
->flags
[1], SIP_PAGE2_RFC2833_COMPENSATE
));
4250 ast_rtp_settos(p
->rtp
, global_tos_audio
);
4251 ast_rtp_set_rtptimeout(p
->rtp
, global_rtptimeout
);
4252 ast_rtp_set_rtpholdtimeout(p
->rtp
, global_rtpholdtimeout
);
4253 ast_rtp_set_rtpkeepalive(p
->rtp
, global_rtpkeepalive
);
4255 ast_rtp_settos(p
->vrtp
, global_tos_video
);
4256 ast_rtp_setdtmf(p
->vrtp
, 0);
4257 ast_rtp_setdtmfcompensate(p
->vrtp
, 0);
4258 ast_rtp_set_rtptimeout(p
->vrtp
, global_rtptimeout
);
4259 ast_rtp_set_rtpholdtimeout(p
->vrtp
, global_rtpholdtimeout
);
4260 ast_rtp_set_rtpkeepalive(p
->vrtp
, global_rtpkeepalive
);
4263 ast_udptl_settos(p
->udptl
, global_tos_audio
);
4264 p
->maxcallbitrate
= default_maxcallbitrate
;
4267 if (useglobal_nat
&& sin
) {
4268 /* Setup NAT structure according to global settings if we have an address */
4269 ast_copy_flags(&p
->flags
[0], &global_flags
[0], SIP_NAT
);
4271 do_setnat(p
, ast_test_flag(&p
->flags
[0], SIP_NAT
) & SIP_NAT_ROUTE
);
4274 if (p
->method
!= SIP_REGISTER
)
4275 ast_string_field_set(p
, fromdomain
, default_fromdomain
);
4278 build_callid_pvt(p
);
4280 ast_string_field_set(p
, callid
, callid
);
4281 /* Assign default music on hold class */
4282 ast_string_field_set(p
, mohinterpret
, default_mohinterpret
);
4283 ast_string_field_set(p
, mohsuggest
, default_mohsuggest
);
4284 p
->capability
= global_capability
;
4285 p
->allowtransfer
= global_allowtransfer
;
4286 if ((ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_RFC2833
) ||
4287 (ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_AUTO
))
4288 p
->noncodeccapability
|= AST_RTP_DTMF
;
4290 p
->t38
.capability
= global_t38_capability
;
4291 if (ast_udptl_get_error_correction_scheme(p
->udptl
) == UDPTL_ERROR_CORRECTION_REDUNDANCY
)
4292 p
->t38
.capability
|= T38FAX_UDP_EC_REDUNDANCY
;
4293 else if (ast_udptl_get_error_correction_scheme(p
->udptl
) == UDPTL_ERROR_CORRECTION_FEC
)
4294 p
->t38
.capability
|= T38FAX_UDP_EC_FEC
;
4295 else if (ast_udptl_get_error_correction_scheme(p
->udptl
) == UDPTL_ERROR_CORRECTION_NONE
)
4296 p
->t38
.capability
|= T38FAX_UDP_EC_NONE
;
4297 p
->t38
.capability
|= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF
;
4298 p
->t38
.jointcapability
= p
->t38
.capability
;
4300 ast_string_field_set(p
, context
, default_context
);
4302 /* Add to active dialog list */
4303 ast_mutex_lock(&iflock
);
4306 ast_mutex_unlock(&iflock
);
4308 ast_log(LOG_DEBUG
, "Allocating new SIP dialog for %s - %s (%s)\n", callid
? callid
: "(No Call-ID)", sip_methods
[intended_method
].text
, p
->rtp
? "With RTP" : "No RTP");
4312 /*! \brief Connect incoming SIP message to current dialog or create new dialog structure
4313 Called by handle_request, sipsock_read */
4314 static struct sip_pvt
*find_call(struct sip_request
*req
, struct sockaddr_in
*sin
, const int intended_method
)
4316 struct sip_pvt
*p
= NULL
;
4317 char *tag
= ""; /* note, tag is never NULL */
4320 const char *callid
= get_header(req
, "Call-ID");
4321 const char *from
= get_header(req
, "From");
4322 const char *to
= get_header(req
, "To");
4323 const char *cseq
= get_header(req
, "Cseq");
4325 /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
4326 /* get_header always returns non-NULL so we must use ast_strlen_zero() */
4327 if (ast_strlen_zero(callid
) || ast_strlen_zero(to
) ||
4328 ast_strlen_zero(from
) || ast_strlen_zero(cseq
))
4329 return NULL
; /* Invalid packet */
4331 if (pedanticsipchecking
) {
4332 /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
4333 we need more to identify a branch - so we have to check branch, from
4334 and to tags to identify a call leg.
4335 For Asterisk to behave correctly, you need to turn on pedanticsipchecking
4338 if (gettag(req
, "To", totag
, sizeof(totag
)))
4339 ast_set_flag(req
, SIP_PKT_WITH_TOTAG
); /* Used in handle_request/response */
4340 gettag(req
, "From", fromtag
, sizeof(fromtag
));
4342 tag
= (req
->method
== SIP_RESPONSE
) ? totag
: fromtag
;
4344 if (option_debug
> 4 )
4345 ast_log(LOG_DEBUG
, "= Looking for Call ID: %s (Checking %s) --From tag %s --To-tag %s \n", callid
, req
->method
==SIP_RESPONSE
? "To" : "From", fromtag
, totag
);
4348 ast_mutex_lock(&iflock
);
4349 for (p
= iflist
; p
; p
= p
->next
) {
4350 /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
4352 if (req
->method
== SIP_REGISTER
)
4353 found
= (!strcmp(p
->callid
, callid
));
4355 found
= (!strcmp(p
->callid
, callid
) &&
4356 (!pedanticsipchecking
|| !tag
|| ast_strlen_zero(p
->theirtag
) || !strcmp(p
->theirtag
, tag
))) ;
4358 if (option_debug
> 4)
4359 ast_log(LOG_DEBUG
, "= %s Their Call ID: %s Their Tag %s Our tag: %s\n", found
? "Found" : "No match", p
->callid
, p
->theirtag
, p
->tag
);
4361 /* If we get a new request within an existing to-tag - check the to tag as well */
4362 if (pedanticsipchecking
&& found
&& req
->method
!= SIP_RESPONSE
) { /* SIP Request */
4363 if (p
->tag
[0] == '\0' && totag
[0]) {
4364 /* We have no to tag, but they have. Wrong dialog */
4366 } else if (totag
[0]) { /* Both have tags, compare them */
4367 if (strcmp(totag
, p
->tag
)) {
4368 found
= FALSE
; /* This is not our packet */
4371 if (!found
&& option_debug
> 4)
4372 ast_log(LOG_DEBUG
, "= Being pedantic: This is not our match on request: Call ID: %s Ourtag <null> Totag %s Method %s\n", p
->callid
, totag
, sip_methods
[req
->method
].text
);
4377 /* Found the call */
4378 ast_mutex_lock(&p
->lock
);
4379 ast_mutex_unlock(&iflock
);
4383 ast_mutex_unlock(&iflock
);
4385 /* See if the method is capable of creating a dialog */
4386 if (sip_methods
[intended_method
].can_create
== CAN_CREATE_DIALOG
) {
4387 if (intended_method
== SIP_REFER
) {
4388 /* We do support REFER, but not outside of a dialog yet */
4389 transmit_response_using_temp(callid
, sin
, 1, intended_method
, req
, "603 Declined (no dialog)");
4390 } else if (intended_method
== SIP_NOTIFY
) {
4391 /* We do not support out-of-dialog NOTIFY either,
4392 like voicemail notification, so cancel that early */
4393 transmit_response_using_temp(callid
, sin
, 1, intended_method
, req
, "489 Bad event");
4395 /* Ok, time to create a new SIP dialog object, a pvt */
4396 if ((p
= sip_alloc(callid
, sin
, 1, intended_method
))) {
4397 /* Ok, we've created a dialog, let's go and process it */
4398 ast_mutex_lock(&p
->lock
);
4400 /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
4401 getting a dialog from sip_alloc.
4403 Without a dialog we can't retransmit and handle ACKs and all that, but at least
4404 send an error message.
4406 Sorry, we apologize for the inconvienience
4408 transmit_response_using_temp(callid
, sin
, 1, intended_method
, req
, "500 Server internal error");
4409 if (option_debug
> 3)
4410 ast_log(LOG_DEBUG
, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
4414 } else if( sip_methods
[intended_method
].can_create
== CAN_CREATE_DIALOG_UNSUPPORTED_METHOD
) {
4415 /* A method we do not support, let's take it on the volley */
4416 transmit_response_using_temp(callid
, sin
, 1, intended_method
, req
, "501 Method Not Implemented");
4417 } else if (intended_method
!= SIP_RESPONSE
&& intended_method
!= SIP_ACK
) {
4418 /* This is a request outside of a dialog that we don't know about
4419 ...never reply to an ACK!
4421 transmit_response_using_temp(callid
, sin
, 1, intended_method
, req
, "481 Call leg/transaction does not exist");
4423 /* We do not respond to responses for dialogs that we don't know about, we just drop
4424 the session quickly */
4429 /*! \brief Parse register=> line in sip.conf and add to registry */
4430 static int sip_register(char *value
, int lineno
)
4432 struct sip_registry
*reg
;
4434 char username
[256] = "";
4435 char *hostname
=NULL
, *secret
=NULL
, *authuser
=NULL
;
4441 ast_copy_string(username
, value
, sizeof(username
));
4442 /* First split around the last '@' then parse the two components. */
4443 hostname
= strrchr(username
, '@'); /* allow @ in the first part */
4446 if (ast_strlen_zero(username
) || ast_strlen_zero(hostname
)) {
4447 ast_log(LOG_WARNING
, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno
);
4450 /* split user[:secret[:authuser]] */
4451 secret
= strchr(username
, ':');
4454 authuser
= strchr(secret
, ':');
4458 /* split host[:port][/contact] */
4459 contact
= strchr(hostname
, '/');
4462 if (ast_strlen_zero(contact
))
4464 porta
= strchr(hostname
, ':');
4467 portnum
= atoi(porta
);
4469 ast_log(LOG_WARNING
, "%s is not a valid port number at line %d\n", porta
, lineno
);
4473 if (!(reg
= ast_calloc(1, sizeof(*reg
)))) {
4474 ast_log(LOG_ERROR
, "Out of memory. Can't allocate SIP registry entry\n");
4478 if (ast_string_field_init(reg
, 256)) {
4479 ast_log(LOG_ERROR
, "Out of memory. Can't allocate SIP registry strings\n");
4486 ast_string_field_set(reg
, contact
, contact
);
4488 ast_string_field_set(reg
, username
, username
);
4490 ast_string_field_set(reg
, hostname
, hostname
);
4492 ast_string_field_set(reg
, authuser
, authuser
);
4494 ast_string_field_set(reg
, secret
, secret
);
4497 reg
->refresh
= default_expiry
;
4498 reg
->portno
= portnum
;
4499 reg
->callid_valid
= FALSE
;
4500 reg
->ocseq
= INITIAL_CSEQ
;
4501 ASTOBJ_CONTAINER_LINK(®l
, reg
); /* Add the new registry entry to the list */
4502 ASTOBJ_UNREF(reg
,sip_registry_destroy
);
4506 /*! \brief Parse multiline SIP headers into one header
4507 This is enabled if pedanticsipchecking is enabled */
4508 static int lws2sws(char *msgbuf
, int len
)
4514 /* Eliminate all CRs */
4515 if (msgbuf
[h
] == '\r') {
4519 /* Check for end-of-line */
4520 if (msgbuf
[h
] == '\n') {
4521 /* Check for end-of-message */
4524 /* Check for a continuation line */
4525 if (msgbuf
[h
+ 1] == ' ' || msgbuf
[h
+ 1] == '\t') {
4526 /* Merge continuation line */
4530 /* Propagate LF and start new line */
4531 msgbuf
[t
++] = msgbuf
[h
++];
4535 if (msgbuf
[h
] == ' ' || msgbuf
[h
] == '\t') {
4540 msgbuf
[t
++] = msgbuf
[h
++];
4544 msgbuf
[t
++] = msgbuf
[h
++];
4552 /*! \brief Parse a SIP message
4553 \note this function is used both on incoming and outgoing packets
4555 static void parse_request(struct sip_request
*req
)
4557 /* Divide fields by NULL's */
4563 /* First header starts immediately */
4567 /* We've got a new header */
4570 if (sipdebug
&& option_debug
> 3)
4571 ast_log(LOG_DEBUG
, "Header %d: %s (%d)\n", f
, req
->header
[f
], (int) strlen(req
->header
[f
]));
4572 if (ast_strlen_zero(req
->header
[f
])) {
4573 /* Line by itself means we're now in content */
4577 if (f
>= SIP_MAX_HEADERS
- 1) {
4578 ast_log(LOG_WARNING
, "Too many SIP headers. Ignoring.\n");
4581 req
->header
[f
] = c
+ 1;
4582 } else if (*c
== '\r') {
4583 /* Ignore but eliminate \r's */
4588 /* Check for last header */
4589 if (!ast_strlen_zero(req
->header
[f
])) {
4590 if (sipdebug
&& option_debug
> 3)
4591 ast_log(LOG_DEBUG
, "Header %d: %s (%d)\n", f
, req
->header
[f
], (int) strlen(req
->header
[f
]));
4595 /* Now we process any mime content */
4600 /* We've got a new line */
4602 if (sipdebug
&& option_debug
> 3)
4603 ast_log(LOG_DEBUG
, "Line: %s (%d)\n", req
->line
[f
], (int) strlen(req
->line
[f
]));
4604 if (f
>= SIP_MAX_LINES
- 1) {
4605 ast_log(LOG_WARNING
, "Too many SDP lines. Ignoring.\n");
4608 req
->line
[f
] = c
+ 1;
4609 } else if (*c
== '\r') {
4610 /* Ignore and eliminate \r's */
4615 /* Check for last line */
4616 if (!ast_strlen_zero(req
->line
[f
]))
4620 ast_log(LOG_WARNING
, "Odd content, extra stuff left over ('%s')\n", c
);
4621 /* Split up the first line parts */
4622 determine_firstline_parts(req
);
4626 \brief Determine whether a SIP message contains an SDP in its body
4627 \param req the SIP request to process
4628 \return 1 if SDP found, 0 if not found
4630 Also updates req->sdp_start and req->sdp_end to indicate where the SDP
4631 lives in the message body.
4633 static int find_sdp(struct sip_request
*req
)
4635 const char *content_type
;
4639 int boundaryisquoted
= FALSE
;
4641 content_type
= get_header(req
, "Content-Type");
4643 /* if the body contains only SDP, this is easy */
4644 if (!strcasecmp(content_type
, "application/sdp")) {
4646 req
->sdp_end
= req
->lines
;
4650 /* if it's not multipart/mixed, there cannot be an SDP */
4651 if (strncasecmp(content_type
, "multipart/mixed", 15))
4654 /* if there is no boundary marker, it's invalid */
4655 if (!(search
= strcasestr(content_type
, ";boundary=")))
4659 if (ast_strlen_zero(search
))
4662 /* If the boundary is quoted with ", remove quote */
4663 if (*search
== '\"') {
4665 boundaryisquoted
= TRUE
;
4668 /* make a duplicate of the string, with two extra characters
4670 boundary
= ast_strdupa(search
- 2);
4671 boundary
[0] = boundary
[1] = '-';
4673 /* Remove final quote */
4674 if (boundaryisquoted
)
4675 boundary
[strlen(boundary
) - 1] = '\0';
4677 /* search for the boundary marker, but stop when there are not enough
4678 lines left for it, the Content-Type header and at least one line of
4680 for (x
= 0; x
< (req
->lines
- 2); x
++) {
4681 if (!strncasecmp(req
->line
[x
], boundary
, strlen(boundary
)) &&
4682 !strcasecmp(req
->line
[x
+ 1], "Content-Type: application/sdp")) {
4686 /* search for the end of the body part */
4687 for ( ; x
< req
->lines
; x
++) {
4688 if (!strncasecmp(req
->line
[x
], boundary
, strlen(boundary
)))
4699 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
4700 If offer is rejected, we will not change any properties of the call
4701 Return 0 on success, a negative value on errors.
4702 Must be called after find_sdp().
4704 static int process_sdp(struct sip_pvt
*p
, struct sip_request
*req
)
4706 const char *m
; /* SDP media offer */
4711 int portno
= -1; /*!< RTP Audio port number */
4712 int vportno
= -1; /*!< RTP Video port number */
4713 int udptlportno
= -1;
4714 int peert38capability
= 0;
4718 /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
4719 int peercapability
= 0, peernoncodeccapability
= 0;
4720 int vpeercapability
= 0, vpeernoncodeccapability
= 0;
4721 struct sockaddr_in sin
; /*!< media socket address */
4722 struct sockaddr_in vsin
; /*!< Video socket address */
4725 struct hostent
*hp
; /*!< RTP Audio host IP */
4726 struct hostent
*vhp
= NULL
; /*!< RTP video host IP */
4727 struct ast_hostent audiohp
;
4728 struct ast_hostent videohp
;
4730 int destiterator
= 0;
4734 struct ast_rtp
*newaudiortp
, *newvideortp
; /* Buffers for codec handling */
4735 int newjointcapability
; /* Negotiated capability */
4736 int newpeercapability
;
4737 int newnoncodeccapability
;
4738 int numberofmediastreams
= 0;
4739 int debug
= sip_debug_test_pvt(p
);
4741 int found_rtpmap_codecs
[32];
4742 int last_rtpmap_codec
=0;
4745 ast_log(LOG_ERROR
, "Got SDP but have no RTP session allocated.\n");
4749 /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
4750 newaudiortp
= alloca(ast_rtp_alloc_size());
4751 memset(newaudiortp
, 0, ast_rtp_alloc_size());
4752 ast_rtp_new_init(newaudiortp
);
4753 ast_rtp_pt_clear(newaudiortp
);
4755 newvideortp
= alloca(ast_rtp_alloc_size());
4756 memset(newvideortp
, 0, ast_rtp_alloc_size());
4757 ast_rtp_new_init(newvideortp
);
4758 ast_rtp_pt_clear(newvideortp
);
4760 /* Update our last rtprx when we receive an SDP, too */
4761 p
->lastrtprx
= p
->lastrtptx
= time(NULL
); /* XXX why both ? */
4764 /* Try to find first media stream */
4765 m
= get_sdp(req
, "m");
4766 destiterator
= req
->sdp_start
;
4767 c
= get_sdp_iterate(&destiterator
, req
, "c");
4768 if (ast_strlen_zero(m
) || ast_strlen_zero(c
)) {
4769 ast_log(LOG_WARNING
, "Insufficient information for SDP (m = '%s', c = '%s')\n", m
, c
);
4773 /* Check for IPv4 address (not IPv6 yet) */
4774 if (sscanf(c
, "IN IP4 %256s", host
) != 1) {
4775 ast_log(LOG_WARNING
, "Invalid host in c= line, '%s'\n", c
);
4779 /* XXX This could block for a long time, and block the main thread! XXX */
4780 hp
= ast_gethostbyname(host
, &audiohp
);
4782 ast_log(LOG_WARNING
, "Unable to lookup host in c= line, '%s'\n", c
);
4785 vhp
= hp
; /* Copy to video address as default too */
4787 iterator
= req
->sdp_start
;
4788 ast_set_flag(&p
->flags
[0], SIP_NOVIDEO
);
4791 /* Find media streams in this SDP offer */
4792 while ((m
= get_sdp_iterate(&iterator
, req
, "m"))[0] != '\0') {
4797 if ((sscanf(m
, "audio %d/%d RTP/AVP %n", &x
, &numberofports
, &len
) == 2) ||
4798 (sscanf(m
, "audio %d RTP/AVP %n", &x
, &len
) == 1)) {
4800 numberofmediastreams
++;
4801 /* Found audio stream in this media definition */
4803 /* Scan through the RTP payload types specified in a "m=" line: */
4804 for (codecs
= m
+ len
; !ast_strlen_zero(codecs
); codecs
= ast_skip_blanks(codecs
+ len
)) {
4805 if (sscanf(codecs
, "%d%n", &codec
, &len
) != 1) {
4806 ast_log(LOG_WARNING
, "Error in codec string '%s'\n", codecs
);
4810 ast_verbose("Found RTP audio format %d\n", codec
);
4811 ast_rtp_set_m_type(newaudiortp
, codec
);
4813 } else if ((sscanf(m
, "video %d/%d RTP/AVP %n", &x
, &numberofports
, &len
) == 2) ||
4814 (sscanf(m
, "video %d RTP/AVP %n", &x
, &len
) == 1)) {
4815 /* If it is not audio - is it video ? */
4816 ast_clear_flag(&p
->flags
[0], SIP_NOVIDEO
);
4817 numberofmediastreams
++;
4819 /* Scan through the RTP payload types specified in a "m=" line: */
4820 for (codecs
= m
+ len
; !ast_strlen_zero(codecs
); codecs
= ast_skip_blanks(codecs
+ len
)) {
4821 if (sscanf(codecs
, "%d%n", &codec
, &len
) != 1) {
4822 ast_log(LOG_WARNING
, "Error in codec string '%s'\n", codecs
);
4826 ast_verbose("Found RTP video format %d\n", codec
);
4827 ast_rtp_set_m_type(newvideortp
, codec
);
4829 } else if (p
->udptl
&& ( (sscanf(m
, "image %d udptl t38%n", &x
, &len
) == 1) ||
4830 (sscanf(m
, "image %d UDPTL t38%n", &x
, &len
) == 1) )) {
4832 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p
->callid
);
4834 numberofmediastreams
++;
4836 if (p
->owner
&& p
->lastinvite
) {
4837 p
->t38
.state
= T38_PEER_REINVITE
; /* T38 Offered in re-invite from remote party */
4838 if (option_debug
> 1)
4839 ast_log(LOG_DEBUG
, "T38 state changed to %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>" );
4841 p
->t38
.state
= T38_PEER_DIRECT
; /* T38 Offered directly from peer in first invite */
4842 if (option_debug
> 1)
4843 ast_log(LOG_DEBUG
, "T38 state changed to %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>");
4846 ast_log(LOG_WARNING
, "Unsupported SDP media type in offer: %s\n", m
);
4847 if (numberofports
> 1)
4848 ast_log(LOG_WARNING
, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports
);
4851 /* Check for Media-description-level-address for audio */
4852 c
= get_sdp_iterate(&destiterator
, req
, "c");
4853 if (!ast_strlen_zero(c
)) {
4854 if (sscanf(c
, "IN IP4 %256s", host
) != 1) {
4855 ast_log(LOG_WARNING
, "Invalid secondary host in c= line, '%s'\n", c
);
4857 /* XXX This could block for a long time, and block the main thread! XXX */
4859 if ( !(hp
= ast_gethostbyname(host
, &audiohp
)))
4860 ast_log(LOG_WARNING
, "Unable to lookup RTP Audio host in secondary c= line, '%s'\n", c
);
4861 } else if (!(vhp
= ast_gethostbyname(host
, &videohp
)))
4862 ast_log(LOG_WARNING
, "Unable to lookup RTP video host in secondary c= line, '%s'\n", c
);
4867 if (portno
== -1 && vportno
== -1 && udptlportno
== -1)
4868 /* No acceptable offer found in SDP - we have no ports */
4869 /* Do not change RTP or VRTP if this is a re-invite */
4872 if (numberofmediastreams
> 2)
4873 /* We have too many fax, audio and/or video media streams, fail this offer */
4876 /* RTP addresses and ports for audio and video */
4877 sin
.sin_family
= AF_INET
;
4878 vsin
.sin_family
= AF_INET
;
4879 memcpy(&sin
.sin_addr
, hp
->h_addr
, sizeof(sin
.sin_addr
));
4881 memcpy(&vsin
.sin_addr
, vhp
->h_addr
, sizeof(vsin
.sin_addr
));
4883 /* Setup UDPTL port number */
4885 if (udptlportno
> 0) {
4886 sin
.sin_port
= htons(udptlportno
);
4887 ast_udptl_set_peer(p
->udptl
, &sin
);
4889 ast_log(LOG_DEBUG
,"Peer T.38 UDPTL is at port %s:%d\n",ast_inet_ntoa(sin
.sin_addr
), ntohs(sin
.sin_port
));
4891 ast_udptl_stop(p
->udptl
);
4893 ast_log(LOG_DEBUG
, "Peer doesn't provide T.38 UDPTL\n");
4900 sin
.sin_port
= htons(portno
);
4901 ast_rtp_set_peer(p
->rtp
, &sin
);
4903 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin
.sin_addr
), ntohs(sin
.sin_port
));
4905 if (udptlportno
> 0) {
4907 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session. Callid %s\n", p
->callid
);
4909 ast_rtp_stop(p
->rtp
);
4911 ast_verbose("Peer doesn't provide audio. Callid %s\n", p
->callid
);
4915 /* Setup video port number */
4917 vsin
.sin_port
= htons(vportno
);
4919 /* Next, scan through each "a=rtpmap:" line, noting each
4920 * specified RTP payload type (with corresponding MIME subtype):
4922 /* XXX This needs to be done per media stream, since it's media stream specific */
4923 iterator
= req
->sdp_start
;
4924 while ((a
= get_sdp_iterate(&iterator
, req
, "a"))[0] != '\0') {
4925 char* mimeSubtype
= ast_strdupa(a
); /* ensures we have enough space */
4926 if (option_debug
> 1) {
4927 int breakout
= FALSE
;
4929 /* If we're debugging, check for unsupported sdp options */
4930 if (!strncasecmp(a
, "rtcp:", (size_t) 5)) {
4932 ast_verbose("Got unsupported a:rtcp in SDP offer \n");
4934 } else if (!strncasecmp(a
, "fmtp:", (size_t) 5)) {
4935 /* Format parameters: Not supported */
4936 /* Note: This is used for codec parameters, like bitrate for
4937 G722 and video formats for H263 and H264
4938 See RFC2327 for an example */
4940 ast_verbose("Got unsupported a:fmtp in SDP offer \n");
4942 } else if (!strncasecmp(a
, "framerate:", (size_t) 10)) {
4943 /* Video stuff: Not supported */
4945 ast_verbose("Got unsupported a:framerate in SDP offer \n");
4947 } else if (!strncasecmp(a
, "maxprate:", (size_t) 9)) {
4948 /* Video stuff: Not supported */
4950 ast_verbose("Got unsupported a:maxprate in SDP offer \n");
4952 } else if (!strncasecmp(a
, "crypto:", (size_t) 7)) {
4953 /* SRTP stuff, not yet supported */
4955 ast_verbose("Got unsupported a:crypto in SDP offer \n");
4958 if (breakout
) /* We have a match, skip to next header */
4961 if (!strcasecmp(a
, "sendonly")) {
4964 } else if (!strcasecmp(a
, "inactive")) {
4967 } else if (!strcasecmp(a
, "sendrecv")) {
4970 } else if (strlen(a
) > 5 && !strncasecmp(a
, "ptime", 5)) {
4971 char *tmp
= strrchr(a
, ':');
4972 long int framing
= 0;
4975 framing
= strtol(tmp
, NULL
, 10);
4976 if (framing
== LONG_MIN
|| framing
== LONG_MAX
) {
4979 ast_log(LOG_DEBUG
, "Can't read framing from SDP: %s\n", a
);
4982 if (framing
&& last_rtpmap_codec
) {
4983 if (p
->autoframing
) {
4984 struct ast_codec_pref
*pref
= ast_rtp_codec_getpref(p
->rtp
);
4987 for (codec_n
= 0; codec_n
< last_rtpmap_codec
; codec_n
++) {
4988 format
= ast_rtp_codec_getformat(found_rtpmap_codecs
[codec_n
]);
4989 if (!format
) /* non-codec or not found */
4992 ast_log(LOG_DEBUG
, "Setting framing for %d to %ld\n", format
, framing
);
4993 ast_codec_pref_setsize(pref
, format
, framing
);
4995 ast_rtp_codec_setpref(p
->rtp
, pref
);
4998 memset(&found_rtpmap_codecs
, 0, sizeof(found_rtpmap_codecs
));
4999 last_rtpmap_codec
= 0;
5001 } else if (sscanf(a
, "rtpmap: %u %[^/]/", &codec
, mimeSubtype
) == 2) {
5002 /* We have a rtpmap to handle */
5004 ast_verbose("Found description format %s for ID %d\n", mimeSubtype
, codec
);
5005 found_rtpmap_codecs
[last_rtpmap_codec
] = codec
;
5006 last_rtpmap_codec
++;
5008 /* Note: should really look at the 'freq' and '#chans' params too */
5009 ast_rtp_set_rtpmap_type(newaudiortp
, codec
, "audio", mimeSubtype
,
5010 ast_test_flag(&p
->flags
[0], SIP_G726_NONSTANDARD
) ? AST_RTP_OPT_G726_NONSTANDARD
: 0);
5012 ast_rtp_set_rtpmap_type(newvideortp
, codec
, "video", mimeSubtype
, 0);
5016 if (udptlportno
!= -1) {
5021 /* Scan trough the a= lines for T38 attributes and set apropriate fileds */
5022 iterator
= req
->sdp_start
;
5023 while ((a
= get_sdp_iterate(&iterator
, req
, "a"))[0] != '\0') {
5024 if ((sscanf(a
, "T38FaxMaxBuffer:%d", &x
) == 1)) {
5026 if (option_debug
> 2)
5027 ast_log(LOG_DEBUG
, "MaxBufferSize:%d\n",x
);
5028 } else if ((sscanf(a
, "T38MaxBitRate:%d", &x
) == 1)) {
5030 if (option_debug
> 2)
5031 ast_log(LOG_DEBUG
,"T38MaxBitRate: %d\n",x
);
5034 peert38capability
|= T38FAX_RATE_14400
| T38FAX_RATE_12000
| T38FAX_RATE_9600
| T38FAX_RATE_7200
| T38FAX_RATE_4800
| T38FAX_RATE_2400
;
5037 peert38capability
|= T38FAX_RATE_12000
| T38FAX_RATE_9600
| T38FAX_RATE_7200
| T38FAX_RATE_4800
| T38FAX_RATE_2400
;
5040 peert38capability
|= T38FAX_RATE_9600
| T38FAX_RATE_7200
| T38FAX_RATE_4800
| T38FAX_RATE_2400
;
5043 peert38capability
|= T38FAX_RATE_7200
| T38FAX_RATE_4800
| T38FAX_RATE_2400
;
5046 peert38capability
|= T38FAX_RATE_4800
| T38FAX_RATE_2400
;
5049 peert38capability
|= T38FAX_RATE_2400
;
5052 } else if ((sscanf(a
, "T38FaxVersion:%d", &x
) == 1)) {
5054 if (option_debug
> 2)
5055 ast_log(LOG_DEBUG
, "FaxVersion: %d\n",x
);
5057 peert38capability
|= T38FAX_VERSION_0
;
5059 peert38capability
|= T38FAX_VERSION_1
;
5060 } else if ((sscanf(a
, "T38FaxMaxDatagram:%d", &x
) == 1)) {
5062 if (option_debug
> 2)
5063 ast_log(LOG_DEBUG
, "FaxMaxDatagram: %d\n",x
);
5064 ast_udptl_set_far_max_datagram(p
->udptl
, x
);
5065 ast_udptl_set_local_max_datagram(p
->udptl
, x
);
5066 } else if ((sscanf(a
, "T38FaxFillBitRemoval:%d", &x
) == 1)) {
5068 if (option_debug
> 2)
5069 ast_log(LOG_DEBUG
, "FillBitRemoval: %d\n",x
);
5071 peert38capability
|= T38FAX_FILL_BIT_REMOVAL
;
5072 } else if ((sscanf(a
, "T38FaxTranscodingMMR:%d", &x
) == 1)) {
5074 if (option_debug
> 2)
5075 ast_log(LOG_DEBUG
, "Transcoding MMR: %d\n",x
);
5077 peert38capability
|= T38FAX_TRANSCODING_MMR
;
5079 if ((sscanf(a
, "T38FaxTranscodingJBIG:%d", &x
) == 1)) {
5081 if (option_debug
> 2)
5082 ast_log(LOG_DEBUG
, "Transcoding JBIG: %d\n",x
);
5084 peert38capability
|= T38FAX_TRANSCODING_JBIG
;
5085 } else if ((sscanf(a
, "T38FaxRateManagement:%s", s
) == 1)) {
5087 if (option_debug
> 2)
5088 ast_log(LOG_DEBUG
, "RateMangement: %s\n", s
);
5089 if (!strcasecmp(s
, "localTCF"))
5090 peert38capability
|= T38FAX_RATE_MANAGEMENT_LOCAL_TCF
;
5091 else if (!strcasecmp(s
, "transferredTCF"))
5092 peert38capability
|= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF
;
5093 } else if ((sscanf(a
, "T38FaxUdpEC:%s", s
) == 1)) {
5095 if (option_debug
> 2)
5096 ast_log(LOG_DEBUG
, "UDP EC: %s\n", s
);
5097 if (!strcasecmp(s
, "t38UDPRedundancy")) {
5098 peert38capability
|= T38FAX_UDP_EC_REDUNDANCY
;
5099 ast_udptl_set_error_correction_scheme(p
->udptl
, UDPTL_ERROR_CORRECTION_REDUNDANCY
);
5100 } else if (!strcasecmp(s
, "t38UDPFEC")) {
5101 peert38capability
|= T38FAX_UDP_EC_FEC
;
5102 ast_udptl_set_error_correction_scheme(p
->udptl
, UDPTL_ERROR_CORRECTION_FEC
);
5104 peert38capability
|= T38FAX_UDP_EC_NONE
;
5105 ast_udptl_set_error_correction_scheme(p
->udptl
, UDPTL_ERROR_CORRECTION_NONE
);
5109 if (found
) { /* Some cisco equipment returns nothing beside c= and m= lines in 200 OK T38 SDP */
5110 p
->t38
.peercapability
= peert38capability
;
5111 p
->t38
.jointcapability
= (peert38capability
& 255); /* Put everything beside supported speeds settings */
5112 peert38capability
&= (T38FAX_RATE_14400
| T38FAX_RATE_12000
| T38FAX_RATE_9600
| T38FAX_RATE_7200
| T38FAX_RATE_4800
| T38FAX_RATE_2400
);
5113 p
->t38
.jointcapability
|= (peert38capability
& p
->t38
.capability
); /* Put the lower of our's and peer's speed */
5116 ast_log(LOG_DEBUG
, "Our T38 capability = (%d), peer T38 capability (%d), joint T38 capability (%d)\n",
5118 p
->t38
.peercapability
,
5119 p
->t38
.jointcapability
);
5121 p
->t38
.state
= T38_DISABLED
;
5122 if (option_debug
> 2)
5123 ast_log(LOG_DEBUG
, "T38 state changed to %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>");
5126 /* Now gather all of the codecs that we are asked for: */
5127 ast_rtp_get_current_formats(newaudiortp
, &peercapability
, &peernoncodeccapability
);
5128 ast_rtp_get_current_formats(newvideortp
, &vpeercapability
, &vpeernoncodeccapability
);
5130 newjointcapability
= p
->capability
& (peercapability
| vpeercapability
);
5131 newpeercapability
= (peercapability
| vpeercapability
);
5132 newnoncodeccapability
= p
->noncodeccapability
& peernoncodeccapability
;
5136 /* shame on whoever coded this.... */
5137 char s1
[BUFSIZ
], s2
[BUFSIZ
], s3
[BUFSIZ
], s4
[BUFSIZ
];
5139 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
5140 ast_getformatname_multiple(s1
, BUFSIZ
, p
->capability
),
5141 ast_getformatname_multiple(s2
, BUFSIZ
, newpeercapability
),
5142 ast_getformatname_multiple(s3
, BUFSIZ
, vpeercapability
),
5143 ast_getformatname_multiple(s4
, BUFSIZ
, newjointcapability
));
5145 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
5146 ast_rtp_lookup_mime_multiple(s1
, BUFSIZ
, p
->noncodeccapability
, 0, 0),
5147 ast_rtp_lookup_mime_multiple(s2
, BUFSIZ
, peernoncodeccapability
, 0, 0),
5148 ast_rtp_lookup_mime_multiple(s3
, BUFSIZ
, newnoncodeccapability
, 0, 0));
5150 if (!newjointcapability
) {
5151 /* If T.38 was not negotiated either, totally bail out... */
5152 if (!p
->t38
.jointcapability
) {
5153 ast_log(LOG_NOTICE
, "No compatible codecs, not accepting this offer!\n");
5154 /* Do NOT Change current setting */
5157 if (option_debug
> 2)
5158 ast_log(LOG_DEBUG
, "Have T.38 but no audio codecs, accepting offer anyway\n");
5163 /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
5164 they are acceptable */
5165 p
->jointcapability
= newjointcapability
; /* Our joint codec profile for this call */
5166 p
->peercapability
= newpeercapability
; /* The other sides capability in latest offer */
5167 p
->jointnoncodeccapability
= newnoncodeccapability
; /* DTMF capabilities */
5169 ast_rtp_pt_copy(p
->rtp
, newaudiortp
);
5171 ast_rtp_pt_copy(p
->vrtp
, newvideortp
);
5173 if (ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_AUTO
) {
5174 ast_clear_flag(&p
->flags
[0], SIP_DTMF
);
5175 if (newnoncodeccapability
& AST_RTP_DTMF
) {
5176 /* XXX Would it be reasonable to drop the DSP at this point? XXX */
5177 ast_set_flag(&p
->flags
[0], SIP_DTMF_RFC2833
);
5178 /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
5179 ast_rtp_setdtmf(p
->rtp
, 1);
5180 ast_rtp_setdtmfcompensate(p
->rtp
, ast_test_flag(&p
->flags
[1], SIP_PAGE2_RFC2833_COMPENSATE
));
5182 ast_set_flag(&p
->flags
[0], SIP_DTMF_INBAND
);
5186 /* Setup audio port number */
5187 if (p
->rtp
&& sin
.sin_port
) {
5188 ast_rtp_set_peer(p
->rtp
, &sin
);
5190 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin
.sin_addr
), ntohs(sin
.sin_port
));
5193 /* Setup video port number */
5194 if (p
->vrtp
&& vsin
.sin_port
) {
5195 ast_rtp_set_peer(p
->vrtp
, &vsin
);
5197 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin
.sin_addr
), ntohs(vsin
.sin_port
));
5200 /* Ok, we're going with this offer */
5201 if (option_debug
> 1) {
5203 ast_log(LOG_DEBUG
, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf
, BUFSIZ
, p
->jointcapability
));
5206 if (!p
->owner
) /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
5209 if (option_debug
> 3)
5210 ast_log(LOG_DEBUG
, "We have an owner, now see if we need to change this call\n");
5212 if (!(p
->owner
->nativeformats
& p
->jointcapability
) && (p
->jointcapability
& AST_FORMAT_AUDIO_MASK
)) {
5214 char s1
[BUFSIZ
], s2
[BUFSIZ
];
5215 ast_log(LOG_DEBUG
, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
5216 ast_getformatname_multiple(s1
, BUFSIZ
, p
->jointcapability
),
5217 ast_getformatname_multiple(s2
, BUFSIZ
, p
->owner
->nativeformats
));
5219 p
->owner
->nativeformats
= ast_codec_choose(&p
->prefs
, p
->jointcapability
, 1) | (p
->capability
& vpeercapability
);
5220 ast_set_read_format(p
->owner
, p
->owner
->readformat
);
5221 ast_set_write_format(p
->owner
, p
->owner
->writeformat
);
5224 if (sin
.sin_addr
.s_addr
&& !sendonly
) {
5225 ast_queue_control(p
->owner
, AST_CONTROL_UNHOLD
);
5226 /* Activate a re-invite */
5227 ast_queue_frame(p
->owner
, &ast_null_frame
);
5228 } else if (!sin
.sin_addr
.s_addr
|| sendonly
) {
5229 ast_queue_control_data(p
->owner
, AST_CONTROL_HOLD
,
5230 S_OR(p
->mohsuggest
, NULL
),
5231 !ast_strlen_zero(p
->mohsuggest
) ? strlen(p
->mohsuggest
) + 1 : 0);
5233 ast_rtp_stop(p
->rtp
);
5234 /* RTCP needs to go ahead, even if we're on hold!!! */
5235 /* Activate a re-invite */
5236 ast_queue_frame(p
->owner
, &ast_null_frame
);
5239 /* Manager Hold and Unhold events must be generated, if necessary */
5240 if (sin
.sin_addr
.s_addr
&& !sendonly
) {
5241 if (ast_test_flag(&p
->flags
[1], SIP_PAGE2_CALL_ONHOLD
)) {
5242 append_history(p
, "Unhold", "%s", req
->data
);
5243 if (global_callevents
)
5244 manager_event(EVENT_FLAG_CALL
, "Unhold",
5248 p
->owner
->uniqueid
);
5249 if (global_notifyhold
)
5250 sip_peer_hold(p
, 0);
5252 ast_clear_flag(&p
->flags
[1], SIP_PAGE2_CALL_ONHOLD
); /* Clear both flags */
5253 } else if (!sin
.sin_addr
.s_addr
|| sendonly
) {
5254 /* No address for RTP, we're on hold */
5255 append_history(p
, "Hold", "%s", req
->data
);
5257 if (global_callevents
&& !ast_test_flag(&p
->flags
[1], SIP_PAGE2_CALL_ONHOLD
)) {
5258 manager_event(EVENT_FLAG_CALL
, "Hold",
5262 p
->owner
->uniqueid
);
5264 if (sendonly
== 1) /* One directional hold (sendonly/recvonly) */
5265 ast_set_flag(&p
->flags
[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR
);
5266 else if (sendonly
== 2) /* Inactive stream */
5267 ast_set_flag(&p
->flags
[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE
);
5268 if (global_notifyhold
)
5269 sip_peer_hold(p
, 1);
5276 /*! \brief Add header to SIP message */
5277 static int add_header(struct sip_request
*req
, const char *var
, const char *value
)
5279 int maxlen
= sizeof(req
->data
) - 4 - req
->len
; /* 4 bytes are for two \r\n ? */
5281 if (req
->headers
== SIP_MAX_HEADERS
) {
5282 ast_log(LOG_WARNING
, "Out of SIP header space\n");
5287 ast_log(LOG_WARNING
, "Can't add more headers when lines have been added\n");
5292 ast_log(LOG_WARNING
, "Out of space, can't add anymore (%s:%s)\n", var
, value
);
5296 req
->header
[req
->headers
] = req
->data
+ req
->len
;
5299 var
= find_alias(var
, var
);
5301 snprintf(req
->header
[req
->headers
], maxlen
, "%s: %s\r\n", var
, value
);
5302 req
->len
+= strlen(req
->header
[req
->headers
]);
5304 if (req
->headers
< SIP_MAX_HEADERS
)
5307 ast_log(LOG_WARNING
, "Out of SIP header space... Will generate broken SIP message\n");
5312 /*! \brief Add 'Content-Length' header to SIP message */
5313 static int add_header_contentLength(struct sip_request
*req
, int len
)
5317 snprintf(clen
, sizeof(clen
), "%d", len
);
5318 return add_header(req
, "Content-Length", clen
);
5321 /*! \brief Add content (not header) to SIP message */
5322 static int add_line(struct sip_request
*req
, const char *line
)
5324 if (req
->lines
== SIP_MAX_LINES
) {
5325 ast_log(LOG_WARNING
, "Out of SIP line space\n");
5329 /* Add extra empty return */
5330 snprintf(req
->data
+ req
->len
, sizeof(req
->data
) - req
->len
, "\r\n");
5331 req
->len
+= strlen(req
->data
+ req
->len
);
5333 if (req
->len
>= sizeof(req
->data
) - 4) {
5334 ast_log(LOG_WARNING
, "Out of space, can't add anymore\n");
5337 req
->line
[req
->lines
] = req
->data
+ req
->len
;
5338 snprintf(req
->line
[req
->lines
], sizeof(req
->data
) - req
->len
, "%s", line
);
5339 req
->len
+= strlen(req
->line
[req
->lines
]);
5344 /*! \brief Copy one header field from one request to another */
5345 static int copy_header(struct sip_request
*req
, const struct sip_request
*orig
, const char *field
)
5347 const char *tmp
= get_header(orig
, field
);
5349 if (!ast_strlen_zero(tmp
)) /* Add what we're responding to */
5350 return add_header(req
, field
, tmp
);
5351 ast_log(LOG_NOTICE
, "No field '%s' present to copy\n", field
);
5355 /*! \brief Copy all headers from one request to another */
5356 static int copy_all_header(struct sip_request
*req
, const struct sip_request
*orig
, const char *field
)
5361 const char *tmp
= __get_header(orig
, field
, &start
);
5363 if (ast_strlen_zero(tmp
))
5365 /* Add what we're responding to */
5366 add_header(req
, field
, tmp
);
5369 return copied
? 0 : -1;
5372 /*! \brief Copy SIP VIA Headers from the request to the response
5373 \note If the client indicates that it wishes to know the port we received from,
5374 it adds ;rport without an argument to the topmost via header. We need to
5375 add the port number (from our point of view) to that parameter.
5376 We always add ;received=<ip address> to the topmost via header.
5377 Received: RFC 3261, rport RFC 3581 */
5378 static int copy_via_headers(struct sip_pvt
*p
, struct sip_request
*req
, const struct sip_request
*orig
, const char *field
)
5385 const char *oh
= __get_header(orig
, field
, &start
);
5387 if (ast_strlen_zero(oh
))
5390 if (!copied
) { /* Only check for empty rport in topmost via header */
5391 char leftmost
[256], *others
, *rport
;
5393 /* Only work on leftmost value */
5394 ast_copy_string(leftmost
, oh
, sizeof(leftmost
));
5395 others
= strchr(leftmost
, ',');
5399 /* Find ;rport; (empty request) */
5400 rport
= strstr(leftmost
, ";rport");
5401 if (rport
&& *(rport
+6) == '=')
5402 rport
= NULL
; /* We already have a parameter to rport */
5404 /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting) */
5405 if (rport
&& ((ast_test_flag(&p
->flags
[0], SIP_NAT
) == SIP_NAT_ALWAYS
) || (ast_test_flag(&p
->flags
[0], SIP_NAT
) == SIP_NAT_RFC3581
))) {
5406 /* We need to add received port - rport */
5409 rport
= strstr(leftmost
, ";rport");
5412 end
= strchr(rport
+ 1, ';');
5414 memmove(rport
, end
, strlen(end
) + 1);
5419 /* Add rport to first VIA header if requested */
5420 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
5421 leftmost
, ast_inet_ntoa(p
->recv
.sin_addr
),
5422 ntohs(p
->recv
.sin_port
),
5423 others
? "," : "", others
? others
: "");
5425 /* We should *always* add a received to the topmost via */
5426 snprintf(new, sizeof(new), "%s;received=%s%s%s",
5427 leftmost
, ast_inet_ntoa(p
->recv
.sin_addr
),
5428 others
? "," : "", others
? others
: "");
5430 oh
= new; /* the header to copy */
5431 } /* else add the following via headers untouched */
5432 add_header(req
, field
, oh
);
5436 ast_log(LOG_NOTICE
, "No header field '%s' present to copy\n", field
);
5442 /*! \brief Add route header into request per learned route */
5443 static void add_route(struct sip_request
*req
, struct sip_route
*route
)
5445 char r
[BUFSIZ
*2], *p
;
5446 int n
, rem
= sizeof(r
);
5452 for (;route
; route
= route
->next
) {
5453 n
= strlen(route
->hop
);
5454 if (rem
< n
+3) /* we need room for ",<route>" */
5456 if (p
!= r
) { /* add a separator after fist route */
5461 ast_copy_string(p
, route
->hop
, rem
); /* cannot fail */
5467 add_header(req
, "Route", r
);
5470 /*! \brief Set destination from SIP URI */
5471 static void set_destination(struct sip_pvt
*p
, char *uri
)
5473 char *h
, *maddr
, hostname
[256];
5476 struct ast_hostent ahp
;
5477 int debug
=sip_debug_test_pvt(p
);
5479 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
5480 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
5483 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri
);
5485 /* Find and parse hostname */
5486 h
= strchr(uri
, '@');
5491 if (strncmp(h
, "sip:", 4) == 0)
5493 else if (strncmp(h
, "sips:", 5) == 0)
5496 hn
= strcspn(h
, ":;>") + 1;
5497 if (hn
> sizeof(hostname
))
5498 hn
= sizeof(hostname
);
5499 ast_copy_string(hostname
, h
, hn
);
5500 /* XXX bug here if string has been trimmed to sizeof(hostname) */
5503 /* Is "port" present? if not default to STANDARD_SIP_PORT */
5507 port
= strtol(h
, &h
, 10);
5510 port
= STANDARD_SIP_PORT
;
5512 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
5513 maddr
= strstr(h
, "maddr=");
5516 hn
= strspn(maddr
, "0123456789.") + 1;
5517 if (hn
> sizeof(hostname
))
5518 hn
= sizeof(hostname
);
5519 ast_copy_string(hostname
, maddr
, hn
);
5522 hp
= ast_gethostbyname(hostname
, &ahp
);
5524 ast_log(LOG_WARNING
, "Can't find address for host '%s'\n", hostname
);
5527 p
->sa
.sin_family
= AF_INET
;
5528 memcpy(&p
->sa
.sin_addr
, hp
->h_addr
, sizeof(p
->sa
.sin_addr
));
5529 p
->sa
.sin_port
= htons(port
);
5531 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p
->sa
.sin_addr
), port
);
5534 /*! \brief Initialize SIP response, based on SIP request */
5535 static int init_resp(struct sip_request
*resp
, const char *msg
)
5537 /* Initialize a response */
5538 memset(resp
, 0, sizeof(*resp
));
5539 resp
->method
= SIP_RESPONSE
;
5540 resp
->header
[0] = resp
->data
;
5541 snprintf(resp
->header
[0], sizeof(resp
->data
), "SIP/2.0 %s\r\n", msg
);
5542 resp
->len
= strlen(resp
->header
[0]);
5547 /*! \brief Initialize SIP request */
5548 static int init_req(struct sip_request
*req
, int sipmethod
, const char *recip
)
5550 /* Initialize a request */
5551 memset(req
, 0, sizeof(*req
));
5552 req
->method
= sipmethod
;
5553 req
->header
[0] = req
->data
;
5554 snprintf(req
->header
[0], sizeof(req
->data
), "%s %s SIP/2.0\r\n", sip_methods
[sipmethod
].text
, recip
);
5555 req
->len
= strlen(req
->header
[0]);
5561 /*! \brief Prepare SIP response packet */
5562 static int respprep(struct sip_request
*resp
, struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
)
5567 init_resp(resp
, msg
);
5568 copy_via_headers(p
, resp
, req
, "Via");
5570 copy_all_header(resp
, req
, "Record-Route");
5571 copy_header(resp
, req
, "From");
5572 ot
= get_header(req
, "To");
5573 if (!strcasestr(ot
, "tag=") && strncmp(msg
, "100", 3)) {
5574 /* Add the proper tag if we don't have it already. If they have specified
5575 their tag, use it. Otherwise, use our own tag */
5576 if (!ast_strlen_zero(p
->theirtag
) && ast_test_flag(&p
->flags
[0], SIP_OUTGOING
))
5577 snprintf(newto
, sizeof(newto
), "%s;tag=%s", ot
, p
->theirtag
);
5578 else if (p
->tag
&& !ast_test_flag(&p
->flags
[0], SIP_OUTGOING
))
5579 snprintf(newto
, sizeof(newto
), "%s;tag=%s", ot
, p
->tag
);
5581 ast_copy_string(newto
, ot
, sizeof(newto
));
5584 add_header(resp
, "To", ot
);
5585 copy_header(resp
, req
, "Call-ID");
5586 copy_header(resp
, req
, "CSeq");
5587 add_header(resp
, "User-Agent", global_useragent
);
5588 add_header(resp
, "Allow", ALLOWED_METHODS
);
5589 add_header(resp
, "Supported", SUPPORTED_EXTENSIONS
);
5590 if (msg
[0] == '2' && (p
->method
== SIP_SUBSCRIBE
|| p
->method
== SIP_REGISTER
)) {
5591 /* For registration responses, we also need expiry and
5595 snprintf(tmp
, sizeof(tmp
), "%d", p
->expiry
);
5596 add_header(resp
, "Expires", tmp
);
5597 if (p
->expiry
) { /* Only add contact if we have an expiry time */
5599 snprintf(contact
, sizeof(contact
), "%s;expires=%d", p
->our_contact
, p
->expiry
);
5600 add_header(resp
, "Contact", contact
); /* Not when we unregister */
5602 } else if (msg
[0] != '4' && p
->our_contact
[0]) {
5603 add_header(resp
, "Contact", p
->our_contact
);
5608 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
5609 static int reqprep(struct sip_request
*req
, struct sip_pvt
*p
, int sipmethod
, int seqno
, int newbranch
)
5611 struct sip_request
*orig
= &p
->initreq
;
5616 const char *ot
, *of
;
5617 int is_strict
= FALSE
; /*!< Strict routing flag */
5619 memset(req
, 0, sizeof(struct sip_request
));
5621 snprintf(p
->lastmsg
, sizeof(p
->lastmsg
), "Tx: %s", sip_methods
[sipmethod
].text
);
5629 p
->branch
^= ast_random();
5633 /* Check for strict or loose router */
5634 if (p
->route
&& !ast_strlen_zero(p
->route
->hop
) && strstr(p
->route
->hop
,";lr") == NULL
) {
5637 ast_log(LOG_DEBUG
, "Strict routing enforced for session %s\n", p
->callid
);
5640 if (sipmethod
== SIP_CANCEL
)
5641 c
= p
->initreq
.rlPart2
; /* Use original URI */
5642 else if (sipmethod
== SIP_ACK
) {
5643 /* Use URI from Contact: in 200 OK (if INVITE)
5644 (we only have the contacturi on INVITEs) */
5645 if (!ast_strlen_zero(p
->okcontacturi
))
5646 c
= is_strict
? p
->route
->hop
: p
->okcontacturi
;
5648 c
= p
->initreq
.rlPart2
;
5649 } else if (!ast_strlen_zero(p
->okcontacturi
))
5650 c
= is_strict
? p
->route
->hop
: p
->okcontacturi
; /* Use for BYE or REINVITE */
5651 else if (!ast_strlen_zero(p
->uri
))
5655 /* We have no URI, use To: or From: header as URI (depending on direction) */
5656 ast_copy_string(stripped
, get_header(orig
, (ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) ? "To" : "From"),
5658 n
= get_in_brackets(stripped
);
5659 c
= strsep(&n
, ";"); /* trim ; and beyond */
5661 init_req(req
, sipmethod
, c
);
5663 snprintf(tmp
, sizeof(tmp
), "%d %s", seqno
, sip_methods
[sipmethod
].text
);
5665 add_header(req
, "Via", p
->via
);
5667 set_destination(p
, p
->route
->hop
);
5668 add_route(req
, is_strict
? p
->route
->next
: p
->route
);
5671 ot
= get_header(orig
, "To");
5672 of
= get_header(orig
, "From");
5674 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
5675 as our original request, including tag (or presumably lack thereof) */
5676 if (!strcasestr(ot
, "tag=") && sipmethod
!= SIP_CANCEL
) {
5677 /* Add the proper tag if we don't have it already. If they have specified
5678 their tag, use it. Otherwise, use our own tag */
5679 if (ast_test_flag(&p
->flags
[0], SIP_OUTGOING
) && !ast_strlen_zero(p
->theirtag
))
5680 snprintf(newto
, sizeof(newto
), "%s;tag=%s", ot
, p
->theirtag
);
5681 else if (!ast_test_flag(&p
->flags
[0], SIP_OUTGOING
))
5682 snprintf(newto
, sizeof(newto
), "%s;tag=%s", ot
, p
->tag
);
5684 snprintf(newto
, sizeof(newto
), "%s", ot
);
5688 if (ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) {
5689 add_header(req
, "From", of
);
5690 add_header(req
, "To", ot
);
5692 add_header(req
, "From", ot
);
5693 add_header(req
, "To", of
);
5695 /* Do not add Contact for MESSAGE, BYE and Cancel requests */
5696 if (sipmethod
!= SIP_BYE
&& sipmethod
!= SIP_CANCEL
&& sipmethod
!= SIP_MESSAGE
)
5697 add_header(req
, "Contact", p
->our_contact
);
5699 copy_header(req
, orig
, "Call-ID");
5700 add_header(req
, "CSeq", tmp
);
5702 add_header(req
, "User-Agent", global_useragent
);
5703 add_header(req
, "Max-Forwards", DEFAULT_MAX_FORWARDS
);
5705 if (!ast_strlen_zero(p
->rpid
))
5706 add_header(req
, "Remote-Party-ID", p
->rpid
);
5711 /*! \brief Base transmit response function */
5712 static int __transmit_response(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
, enum xmittype reliable
)
5714 struct sip_request resp
;
5717 if (reliable
&& (sscanf(get_header(req
, "CSeq"), "%d ", &seqno
) != 1)) {
5718 ast_log(LOG_WARNING
, "Unable to determine sequence number from '%s'\n", get_header(req
, "CSeq"));
5721 respprep(&resp
, p
, msg
, req
);
5722 add_header_contentLength(&resp
, 0);
5723 /* If we are cancelling an incoming invite for some reason, add information
5724 about the reason why we are doing this in clear text */
5725 if (p
->method
== SIP_INVITE
&& msg
[0] != '1' && p
->owner
&& p
->owner
->hangupcause
) {
5728 add_header(&resp
, "X-Asterisk-HangupCause", ast_cause2str(p
->owner
->hangupcause
));
5729 snprintf(buf
, sizeof(buf
), "%d", p
->owner
->hangupcause
);
5730 add_header(&resp
, "X-Asterisk-HangupCauseCode", buf
);
5732 return send_response(p
, &resp
, reliable
, seqno
);
5735 static void temp_pvt_cleanup(void *data
)
5737 struct sip_pvt
*p
= data
;
5739 ast_string_field_free_pools(p
);
5744 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
5745 static int transmit_response_using_temp(ast_string_field callid
, struct sockaddr_in
*sin
, int useglobal_nat
, const int intended_method
, const struct sip_request
*req
, const char *msg
)
5747 struct sip_pvt
*p
= NULL
;
5749 if (!(p
= ast_threadstorage_get(&ts_temp_pvt
, sizeof(*p
)))) {
5750 ast_log(LOG_NOTICE
, "Failed to get temporary pvt\n");
5754 /* if the structure was just allocated, initialize it */
5755 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
)) {
5756 ast_set_flag(&p
->flags
[0], SIP_NO_HISTORY
);
5757 if (ast_string_field_init(p
, 512))
5761 /* Initialize the bare minimum */
5762 p
->method
= intended_method
;
5766 if (ast_sip_ouraddrfor(&p
->sa
.sin_addr
, &p
->ourip
))
5771 p
->branch
= ast_random();
5772 make_our_tag(p
->tag
, sizeof(p
->tag
));
5773 p
->ocseq
= INITIAL_CSEQ
;
5775 if (useglobal_nat
&& sin
) {
5776 ast_copy_flags(&p
->flags
[0], &global_flags
[0], SIP_NAT
);
5778 do_setnat(p
, ast_test_flag(&p
->flags
[0], SIP_NAT
) & SIP_NAT_ROUTE
);
5781 ast_string_field_set(p
, fromdomain
, default_fromdomain
);
5783 ast_string_field_set(p
, callid
, callid
);
5785 /* Use this temporary pvt structure to send the message */
5786 __transmit_response(p
, msg
, req
, XMIT_UNRELIABLE
);
5788 /* Free the string fields, but not the pool space */
5789 ast_string_field_free_all(p
);
5794 /*! \brief Transmit response, no retransmits */
5795 static int transmit_response(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
)
5797 return __transmit_response(p
, msg
, req
, XMIT_UNRELIABLE
);
5800 /*! \brief Transmit response, no retransmits */
5801 static int transmit_response_with_unsupported(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
, const char *unsupported
)
5803 struct sip_request resp
;
5804 respprep(&resp
, p
, msg
, req
);
5806 add_header(&resp
, "Unsupported", unsupported
);
5807 return send_response(p
, &resp
, XMIT_UNRELIABLE
, 0);
5810 /*! \brief Transmit response, Make sure you get an ACK
5811 This is only used for responses to INVITEs, where we need to make sure we get an ACK
5813 static int transmit_response_reliable(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
)
5815 return __transmit_response(p
, msg
, req
, XMIT_CRITICAL
);
5818 /*! \brief Append date to SIP message */
5819 static void append_date(struct sip_request
*req
)
5823 time_t t
= time(NULL
);
5826 strftime(tmpdat
, sizeof(tmpdat
), "%a, %d %b %Y %T GMT", &tm
);
5827 add_header(req
, "Date", tmpdat
);
5830 /*! \brief Append date and content length before transmitting response */
5831 static int transmit_response_with_date(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
)
5833 struct sip_request resp
;
5834 respprep(&resp
, p
, msg
, req
);
5836 add_header_contentLength(&resp
, 0);
5837 return send_response(p
, &resp
, XMIT_UNRELIABLE
, 0);
5840 /*! \brief Append Accept header, content length before transmitting response */
5841 static int transmit_response_with_allow(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
, enum xmittype reliable
)
5843 struct sip_request resp
;
5844 respprep(&resp
, p
, msg
, req
);
5845 add_header(&resp
, "Accept", "application/sdp");
5846 add_header_contentLength(&resp
, 0);
5847 return send_response(p
, &resp
, reliable
, 0);
5850 /*! \brief Respond with authorization request */
5851 static int transmit_response_with_auth(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
, const char *randdata
, enum xmittype reliable
, const char *header
, int stale
)
5853 struct sip_request resp
;
5857 if (reliable
&& (sscanf(get_header(req
, "CSeq"), "%d ", &seqno
) != 1)) {
5858 ast_log(LOG_WARNING
, "Unable to determine sequence number from '%s'\n", get_header(req
, "CSeq"));
5861 /* Stale means that they sent us correct authentication, but
5862 based it on an old challenge (nonce) */
5863 snprintf(tmp
, sizeof(tmp
), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm
, randdata
, stale
? ", stale=true" : "");
5864 respprep(&resp
, p
, msg
, req
);
5865 add_header(&resp
, header
, tmp
);
5866 add_header_contentLength(&resp
, 0);
5867 append_history(p
, "AuthChal", "Auth challenge sent for %s - nc %d", p
->username
, p
->noncecount
);
5868 return send_response(p
, &resp
, reliable
, seqno
);
5871 /*! \brief Add text body to SIP message */
5872 static int add_text(struct sip_request
*req
, const char *text
)
5874 /* XXX Convert \n's to \r\n's XXX */
5875 add_header(req
, "Content-Type", "text/plain");
5876 add_header_contentLength(req
, strlen(text
));
5877 add_line(req
, text
);
5881 /*! \brief Add DTMF INFO tone to sip message */
5882 /* Always adds default duration 250 ms, regardless of what came in over the line */
5883 static int add_digit(struct sip_request
*req
, char digit
, unsigned int duration
)
5887 snprintf(tmp
, sizeof(tmp
), "Signal=%c\r\nDuration=%u\r\n", digit
, duration
);
5888 add_header(req
, "Content-Type", "application/dtmf-relay");
5889 add_header_contentLength(req
, strlen(tmp
));
5894 /*! \brief add XML encoded media control with update
5895 \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
5896 static int add_vidupdate(struct sip_request
*req
)
5898 const char *xml_is_a_huge_waste_of_space
=
5899 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
5900 " <media_control>\r\n"
5901 " <vc_primitive>\r\n"
5903 " <picture_fast_update>\r\n"
5904 " </picture_fast_update>\r\n"
5905 " </to_encoder>\r\n"
5906 " </vc_primitive>\r\n"
5907 " </media_control>\r\n";
5908 add_header(req
, "Content-Type", "application/media_control+xml");
5909 add_header_contentLength(req
, strlen(xml_is_a_huge_waste_of_space
));
5910 add_line(req
, xml_is_a_huge_waste_of_space
);
5914 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
5915 static void add_codec_to_sdp(const struct sip_pvt
*p
, int codec
, int sample_rate
,
5916 char **m_buf
, size_t *m_size
, char **a_buf
, size_t *a_size
,
5917 int debug
, int *min_packet_size
)
5920 struct ast_format_list fmt
;
5924 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec
, ast_getformatname(codec
));
5925 if ((rtp_code
= ast_rtp_lookup_code(p
->rtp
, 1, codec
)) == -1)
5929 struct ast_codec_pref
*pref
= ast_rtp_codec_getpref(p
->rtp
);
5930 fmt
= ast_codec_pref_getsize(pref
, codec
);
5931 } else /* I dont see how you couldn't have p->rtp, but good to check for and error out if not there like earlier code */
5933 ast_build_string(m_buf
, m_size
, " %d", rtp_code
);
5934 ast_build_string(a_buf
, a_size
, "a=rtpmap:%d %s/%d\r\n", rtp_code
,
5935 ast_rtp_lookup_mime_subtype(1, codec
,
5936 ast_test_flag(&p
->flags
[0], SIP_G726_NONSTANDARD
) ? AST_RTP_OPT_G726_NONSTANDARD
: 0),
5938 if (codec
== AST_FORMAT_G729A
) {
5939 /* Indicate that we don't support VAD (G.729 annex B) */
5940 ast_build_string(a_buf
, a_size
, "a=fmtp:%d annexb=no\r\n", rtp_code
);
5941 } else if (codec
== AST_FORMAT_ILBC
) {
5942 /* Add information about us using only 20/30 ms packetization */
5943 ast_build_string(a_buf
, a_size
, "a=fmtp:%d mode=%d\r\n", rtp_code
, fmt
.cur_ms
);
5946 if (fmt
.cur_ms
&& (fmt
.cur_ms
< *min_packet_size
))
5947 *min_packet_size
= fmt
.cur_ms
;
5949 /* Our first codec packetization processed cannot be less than zero */
5950 if ((*min_packet_size
) == 0 && fmt
.cur_ms
)
5951 *min_packet_size
= fmt
.cur_ms
;
5954 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
5955 static int t38_get_rate(int t38cap
)
5957 int maxrate
= (t38cap
& (T38FAX_RATE_14400
| T38FAX_RATE_12000
| T38FAX_RATE_9600
| T38FAX_RATE_7200
| T38FAX_RATE_4800
| T38FAX_RATE_2400
));
5959 if (maxrate
& T38FAX_RATE_14400
) {
5960 if (option_debug
> 1)
5961 ast_log(LOG_DEBUG
, "T38MaxFaxRate 14400 found\n");
5963 } else if (maxrate
& T38FAX_RATE_12000
) {
5964 if (option_debug
> 1)
5965 ast_log(LOG_DEBUG
, "T38MaxFaxRate 12000 found\n");
5967 } else if (maxrate
& T38FAX_RATE_9600
) {
5968 if (option_debug
> 1)
5969 ast_log(LOG_DEBUG
, "T38MaxFaxRate 9600 found\n");
5971 } else if (maxrate
& T38FAX_RATE_7200
) {
5972 if (option_debug
> 1)
5973 ast_log(LOG_DEBUG
, "T38MaxFaxRate 7200 found\n");
5975 } else if (maxrate
& T38FAX_RATE_4800
) {
5976 if (option_debug
> 1)
5977 ast_log(LOG_DEBUG
, "T38MaxFaxRate 4800 found\n");
5979 } else if (maxrate
& T38FAX_RATE_2400
) {
5980 if (option_debug
> 1)
5981 ast_log(LOG_DEBUG
, "T38MaxFaxRate 2400 found\n");
5984 if (option_debug
> 1)
5985 ast_log(LOG_DEBUG
, "Strange, T38MaxFaxRate NOT found in peers T38 SDP.\n");
5990 /*! \brief Add T.38 Session Description Protocol message */
5991 static int add_t38_sdp(struct sip_request
*resp
, struct sip_pvt
*p
)
5995 struct sockaddr_in udptlsin
;
6003 char *m_modem_next
= m_modem
;
6004 size_t m_modem_left
= sizeof(m_modem
);
6005 char *a_modem_next
= a_modem
;
6006 size_t a_modem_left
= sizeof(a_modem
);
6007 struct sockaddr_in udptldest
= { 0, };
6010 debug
= sip_debug_test_pvt(p
);
6013 ast_log(LOG_WARNING
, "No way to add SDP without an UDPTL structure\n");
6017 if (!p
->sessionid
) {
6018 p
->sessionid
= getpid();
6019 p
->sessionversion
= p
->sessionid
;
6021 p
->sessionversion
++;
6023 /* Our T.38 end is */
6024 ast_udptl_get_us(p
->udptl
, &udptlsin
);
6026 /* Determine T.38 UDPTL destination */
6027 if (p
->udptlredirip
.sin_addr
.s_addr
) {
6028 udptldest
.sin_port
= p
->udptlredirip
.sin_port
;
6029 udptldest
.sin_addr
= p
->udptlredirip
.sin_addr
;
6031 udptldest
.sin_addr
= p
->ourip
;
6032 udptldest
.sin_port
= udptlsin
.sin_port
;
6036 ast_log(LOG_DEBUG
, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p
->ourip
), ntohs(udptlsin
.sin_port
));
6038 /* We break with the "recommendation" and send our IP, in order that our
6039 peer doesn't have to ast_gethostbyname() us */
6042 ast_log(LOG_DEBUG
, "Our T38 capability (%d), peer T38 capability (%d), joint capability (%d)\n",
6044 p
->t38
.peercapability
,
6045 p
->t38
.jointcapability
);
6047 snprintf(v
, sizeof(v
), "v=0\r\n");
6048 snprintf(o
, sizeof(o
), "o=root %d %d IN IP4 %s\r\n", p
->sessionid
, p
->sessionversion
, ast_inet_ntoa(udptldest
.sin_addr
));
6049 snprintf(s
, sizeof(s
), "s=session\r\n");
6050 snprintf(c
, sizeof(c
), "c=IN IP4 %s\r\n", ast_inet_ntoa(udptldest
.sin_addr
));
6051 snprintf(t
, sizeof(t
), "t=0 0\r\n");
6052 ast_build_string(&m_modem_next
, &m_modem_left
, "m=image %d udptl t38\r\n", ntohs(udptldest
.sin_port
));
6054 if ((p
->t38
.jointcapability
& T38FAX_VERSION
) == T38FAX_VERSION_0
)
6055 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38FaxVersion:0\r\n");
6056 if ((p
->t38
.jointcapability
& T38FAX_VERSION
) == T38FAX_VERSION_1
)
6057 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38FaxVersion:1\r\n");
6058 if ((x
= t38_get_rate(p
->t38
.jointcapability
)))
6059 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38MaxBitRate:%d\r\n",x
);
6060 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38FaxFillBitRemoval:%d\r\n", (p
->t38
.jointcapability
& T38FAX_FILL_BIT_REMOVAL
) ? 1 : 0);
6061 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38FaxTranscodingMMR:%d\r\n", (p
->t38
.jointcapability
& T38FAX_TRANSCODING_MMR
) ? 1 : 0);
6062 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38FaxTranscodingJBIG:%d\r\n", (p
->t38
.jointcapability
& T38FAX_TRANSCODING_JBIG
) ? 1 : 0);
6063 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38FaxRateManagement:%s\r\n", (p
->t38
.jointcapability
& T38FAX_RATE_MANAGEMENT_LOCAL_TCF
) ? "localTCF" : "transferredTCF");
6064 x
= ast_udptl_get_local_max_datagram(p
->udptl
);
6065 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38FaxMaxBuffer:%d\r\n",x
);
6066 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38FaxMaxDatagram:%d\r\n",x
);
6067 if (p
->t38
.jointcapability
!= T38FAX_UDP_EC_NONE
)
6068 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38FaxUdpEC:%s\r\n", (p
->t38
.jointcapability
& T38FAX_UDP_EC_REDUNDANCY
) ? "t38UDPRedundancy" : "t38UDPFEC");
6069 len
= strlen(v
) + strlen(s
) + strlen(o
) + strlen(c
) + strlen(t
) + strlen(m_modem
) + strlen(a_modem
);
6070 add_header(resp
, "Content-Type", "application/sdp");
6071 add_header_contentLength(resp
, len
);
6077 add_line(resp
, m_modem
);
6078 add_line(resp
, a_modem
);
6080 /* Update lastrtprx when we send our SDP */
6081 p
->lastrtprx
= p
->lastrtptx
= time(NULL
);
6087 /*! \brief Add RFC 2833 DTMF offer to SDP */
6088 static void add_noncodec_to_sdp(const struct sip_pvt
*p
, int format
, int sample_rate
,
6089 char **m_buf
, size_t *m_size
, char **a_buf
, size_t *a_size
,
6095 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format
, ast_rtp_lookup_mime_subtype(0, format
, 0));
6096 if ((rtp_code
= ast_rtp_lookup_code(p
->rtp
, 0, format
)) == -1)
6099 ast_build_string(m_buf
, m_size
, " %d", rtp_code
);
6100 ast_build_string(a_buf
, a_size
, "a=rtpmap:%d %s/%d\r\n", rtp_code
,
6101 ast_rtp_lookup_mime_subtype(0, format
, 0),
6103 if (format
== AST_RTP_DTMF
)
6104 /* Indicate we support DTMF and FLASH... */
6105 ast_build_string(a_buf
, a_size
, "a=fmtp:%d 0-16\r\n", rtp_code
);
6108 #define SDP_SAMPLE_RATE(x) (x == AST_FORMAT_G722) ? 16000 : 8000
6110 /*! \brief Add Session Description Protocol message */
6111 static enum sip_result
add_sdp(struct sip_request
*resp
, struct sip_pvt
*p
)
6114 int alreadysent
= 0;
6116 struct sockaddr_in sin
;
6117 struct sockaddr_in vsin
;
6118 struct sockaddr_in dest
;
6119 struct sockaddr_in vdest
= { 0, };
6122 char *version
= "v=0\r\n"; /* Protocol version */
6123 char *subject
= "s=session\r\n"; /* Subject of the session */
6124 char owner
[256]; /* Session owner/creator */
6125 char connection
[256]; /* Connection data */
6126 char *stime
= "t=0 0\r\n"; /* Time the session is active */
6127 char bandwidth
[256] = ""; /* Max bitrate */
6129 char m_audio
[256]; /* Media declaration line for audio */
6130 char m_video
[256]; /* Media declaration line for video */
6131 char a_audio
[1024]; /* Attributes for audio */
6132 char a_video
[1024]; /* Attributes for video */
6133 char *m_audio_next
= m_audio
;
6134 char *m_video_next
= m_video
;
6135 size_t m_audio_left
= sizeof(m_audio
);
6136 size_t m_video_left
= sizeof(m_video
);
6137 char *a_audio_next
= a_audio
;
6138 char *a_video_next
= a_video
;
6139 size_t a_audio_left
= sizeof(a_audio
);
6140 size_t a_video_left
= sizeof(a_video
);
6144 int needvideo
= FALSE
;
6145 int debug
= sip_debug_test_pvt(p
);
6146 int min_audio_packet_size
= 0;
6147 int min_video_packet_size
= 0;
6149 m_video
[0] = '\0'; /* Reset the video media string if it's not needed */
6152 ast_log(LOG_WARNING
, "No way to add SDP without an RTP structure\n");
6156 /* Set RTP Session ID and version */
6157 if (!p
->sessionid
) {
6158 p
->sessionid
= getpid();
6159 p
->sessionversion
= p
->sessionid
;
6161 p
->sessionversion
++;
6163 /* Get our addresses */
6164 ast_rtp_get_us(p
->rtp
, &sin
);
6166 ast_rtp_get_us(p
->vrtp
, &vsin
);
6168 /* Is this a re-invite to move the media out, then use the original offer from caller */
6169 if (p
->redirip
.sin_addr
.s_addr
) {
6170 dest
.sin_port
= p
->redirip
.sin_port
;
6171 dest
.sin_addr
= p
->redirip
.sin_addr
;
6173 dest
.sin_addr
= p
->ourip
;
6174 dest
.sin_port
= sin
.sin_port
;
6177 capability
= p
->jointcapability
;
6180 if (option_debug
> 1) {
6181 char codecbuf
[BUFSIZ
];
6182 ast_log(LOG_DEBUG
, "** Our capability: %s Video flag: %s\n", ast_getformatname_multiple(codecbuf
, sizeof(codecbuf
), capability
), ast_test_flag(&p
->flags
[0], SIP_NOVIDEO
) ? "True" : "False");
6183 ast_log(LOG_DEBUG
, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf
, sizeof(codecbuf
), p
->prefcodec
));
6186 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
6187 if (ast_test_flag(&p
->t38
.t38support
, SIP_PAGE2_T38SUPPORT_RTP
)) {
6188 ast_build_string(&m_audio_next
, &m_audio_left
, " %d", 191);
6189 ast_build_string(&a_audio_next
, &a_audio_left
, "a=rtpmap:%d %s/%d\r\n", 191, "t38", 8000);
6193 /* Check if we need video in this call */
6194 if ((capability
& AST_FORMAT_VIDEO_MASK
) && !ast_test_flag(&p
->flags
[0], SIP_NOVIDEO
)) {
6197 if (option_debug
> 1)
6198 ast_log(LOG_DEBUG
, "This call needs video offers!\n");
6199 } else if (option_debug
> 1)
6200 ast_log(LOG_DEBUG
, "This call needs video offers, but there's no video support enabled!\n");
6204 /* Ok, we need video. Let's add what we need for video and set codecs.
6205 Video is handled differently than audio since we can not transcode. */
6207 /* Determine video destination */
6208 if (p
->vredirip
.sin_addr
.s_addr
) {
6209 vdest
.sin_addr
= p
->vredirip
.sin_addr
;
6210 vdest
.sin_port
= p
->vredirip
.sin_port
;
6212 vdest
.sin_addr
= p
->ourip
;
6213 vdest
.sin_port
= vsin
.sin_port
;
6215 ast_build_string(&m_video_next
, &m_video_left
, "m=video %d RTP/AVP", ntohs(vdest
.sin_port
));
6217 /* Build max bitrate string */
6218 if (p
->maxcallbitrate
)
6219 snprintf(bandwidth
, sizeof(bandwidth
), "b=CT:%d\r\n", p
->maxcallbitrate
);
6221 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p
->ourip
), ntohs(vsin
.sin_port
));
6225 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p
->ourip
), ntohs(sin
.sin_port
));
6227 /* Start building generic SDP headers */
6229 /* We break with the "recommendation" and send our IP, in order that our
6230 peer doesn't have to ast_gethostbyname() us */
6232 snprintf(owner
, sizeof(owner
), "o=root %d %d IN IP4 %s\r\n", p
->sessionid
, p
->sessionversion
, ast_inet_ntoa(dest
.sin_addr
));
6233 snprintf(connection
, sizeof(connection
), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest
.sin_addr
));
6234 ast_build_string(&m_audio_next
, &m_audio_left
, "m=audio %d RTP/AVP", ntohs(dest
.sin_port
));
6236 if (ast_test_flag(&p
->flags
[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR
))
6237 hold
= "a=recvonly\r\n";
6238 else if (ast_test_flag(&p
->flags
[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE
))
6239 hold
= "a=inactive\r\n";
6241 hold
= "a=sendrecv\r\n";
6243 /* Now, start adding audio codecs. These are added in this order:
6244 - First what was requested by the calling channel
6245 - Then preferences in order from sip.conf device config for this peer/user
6246 - Then other codecs in capabilities, including video
6249 /* Prefer the audio codec we were requested to use, first, no matter what
6250 Note that p->prefcodec can include video codecs, so mask them out
6252 if (capability
& p
->prefcodec
) {
6253 int codec
= p
->prefcodec
& AST_FORMAT_AUDIO_MASK
;
6255 add_codec_to_sdp(p
, codec
, SDP_SAMPLE_RATE(codec
),
6256 &m_audio_next
, &m_audio_left
,
6257 &a_audio_next
, &a_audio_left
,
6258 debug
, &min_audio_packet_size
);
6259 alreadysent
|= codec
;
6262 /* Start by sending our preferred audio codecs */
6263 for (x
= 0; x
< 32; x
++) {
6266 if (!(codec
= ast_codec_pref_index(&p
->prefs
, x
)))
6269 if (!(capability
& codec
))
6272 if (alreadysent
& codec
)
6275 add_codec_to_sdp(p
, codec
, SDP_SAMPLE_RATE(codec
),
6276 &m_audio_next
, &m_audio_left
,
6277 &a_audio_next
, &a_audio_left
,
6278 debug
, &min_audio_packet_size
);
6279 alreadysent
|= codec
;
6282 /* Now send any other common audio and video codecs, and non-codec formats: */
6283 for (x
= 1; x
<= (needvideo
? AST_FORMAT_MAX_VIDEO
: AST_FORMAT_MAX_AUDIO
); x
<<= 1) {
6284 if (!(capability
& x
)) /* Codec not requested */
6287 if (alreadysent
& x
) /* Already added to SDP */
6290 if (x
<= AST_FORMAT_MAX_AUDIO
)
6291 add_codec_to_sdp(p
, x
, SDP_SAMPLE_RATE(x
),
6292 &m_audio_next
, &m_audio_left
,
6293 &a_audio_next
, &a_audio_left
,
6294 debug
, &min_audio_packet_size
);
6296 add_codec_to_sdp(p
, x
, 90000,
6297 &m_video_next
, &m_video_left
,
6298 &a_video_next
, &a_video_left
,
6299 debug
, &min_video_packet_size
);
6302 /* Now add DTMF RFC2833 telephony-event as a codec */
6303 for (x
= 1; x
<= AST_RTP_MAX
; x
<<= 1) {
6304 if (!(p
->jointnoncodeccapability
& x
))
6307 add_noncodec_to_sdp(p
, x
, 8000,
6308 &m_audio_next
, &m_audio_left
,
6309 &a_audio_next
, &a_audio_left
,
6313 if (option_debug
> 2)
6314 ast_log(LOG_DEBUG
, "-- Done with adding codecs to SDP\n");
6316 if (!p
->owner
|| !ast_internal_timing_enabled(p
->owner
))
6317 ast_build_string(&a_audio_next
, &a_audio_left
, "a=silenceSupp:off - - - -\r\n");
6319 if (min_audio_packet_size
)
6320 ast_build_string(&a_audio_next
, &a_audio_left
, "a=ptime:%d\r\n", min_audio_packet_size
);
6322 if (min_video_packet_size
)
6323 ast_build_string(&a_video_next
, &a_video_left
, "a=ptime:%d\r\n", min_video_packet_size
);
6325 if ((m_audio_left
< 2) || (m_video_left
< 2) || (a_audio_left
== 0) || (a_video_left
== 0))
6326 ast_log(LOG_WARNING
, "SIP SDP may be truncated due to undersized buffer!!\n");
6328 ast_build_string(&m_audio_next
, &m_audio_left
, "\r\n");
6330 ast_build_string(&m_video_next
, &m_video_left
, "\r\n");
6332 len
= strlen(version
) + strlen(subject
) + strlen(owner
) + strlen(connection
) + strlen(stime
) + strlen(m_audio
) + strlen(a_audio
) + strlen(hold
);
6333 if (needvideo
) /* only if video response is appropriate */
6334 len
+= strlen(m_video
) + strlen(a_video
) + strlen(bandwidth
) + strlen(hold
);
6336 add_header(resp
, "Content-Type", "application/sdp");
6337 add_header_contentLength(resp
, len
);
6338 add_line(resp
, version
);
6339 add_line(resp
, owner
);
6340 add_line(resp
, subject
);
6341 add_line(resp
, connection
);
6342 if (needvideo
) /* only if video response is appropriate */
6343 add_line(resp
, bandwidth
);
6344 add_line(resp
, stime
);
6345 add_line(resp
, m_audio
);
6346 add_line(resp
, a_audio
);
6347 add_line(resp
, hold
);
6348 if (needvideo
) { /* only if video response is appropriate */
6349 add_line(resp
, m_video
);
6350 add_line(resp
, a_video
);
6351 add_line(resp
, hold
); /* Repeat hold for the video stream */
6354 /* Update lastrtprx when we send our SDP */
6355 p
->lastrtprx
= p
->lastrtptx
= time(NULL
); /* XXX why both ? */
6357 if (option_debug
> 2) {
6359 ast_log(LOG_DEBUG
, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf
, BUFSIZ
, capability
));
6365 /*! \brief Used for 200 OK and 183 early media */
6366 static int transmit_response_with_t38_sdp(struct sip_pvt
*p
, char *msg
, struct sip_request
*req
, int retrans
)
6368 struct sip_request resp
;
6371 if (sscanf(get_header(req
, "CSeq"), "%d ", &seqno
) != 1) {
6372 ast_log(LOG_WARNING
, "Unable to get seqno from '%s'\n", get_header(req
, "CSeq"));
6375 respprep(&resp
, p
, msg
, req
);
6377 ast_udptl_offered_from_local(p
->udptl
, 0);
6378 add_t38_sdp(&resp
, p
);
6380 ast_log(LOG_ERROR
, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p
->callid
);
6381 if (retrans
&& !p
->pendinginvite
)
6382 p
->pendinginvite
= seqno
; /* Buggy clients sends ACK on RINGING too */
6383 return send_response(p
, &resp
, retrans
, seqno
);
6386 /*! \brief copy SIP request (mostly used to save request for responses) */
6387 static void copy_request(struct sip_request
*dst
, const struct sip_request
*src
)
6391 offset
= ((void *)dst
) - ((void *)src
);
6392 /* First copy stuff */
6393 memcpy(dst
, src
, sizeof(*dst
));
6394 /* Now fix pointer arithmetic */
6395 for (x
=0; x
< src
->headers
; x
++)
6396 dst
->header
[x
] += offset
;
6397 for (x
=0; x
< src
->lines
; x
++)
6398 dst
->line
[x
] += offset
;
6401 /*! \brief Used for 200 OK and 183 early media */
6402 static int transmit_response_with_sdp(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
, enum xmittype reliable
)
6404 struct sip_request resp
;
6406 if (sscanf(get_header(req
, "CSeq"), "%d ", &seqno
) != 1) {
6407 ast_log(LOG_WARNING
, "Unable to get seqno from '%s'\n", get_header(req
, "CSeq"));
6410 respprep(&resp
, p
, msg
, req
);
6412 if (!p
->autoframing
&& !ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) {
6414 ast_log(LOG_DEBUG
, "Setting framing from config on incoming call\n");
6415 ast_rtp_codec_setpref(p
->rtp
, &p
->prefs
);
6417 try_suggested_sip_codec(p
);
6420 ast_log(LOG_ERROR
, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p
->callid
);
6421 if (reliable
&& !p
->pendinginvite
)
6422 p
->pendinginvite
= seqno
; /* Buggy clients sends ACK on RINGING too */
6423 return send_response(p
, &resp
, reliable
, seqno
);
6426 /*! \brief Parse first line of incoming SIP request */
6427 static int determine_firstline_parts(struct sip_request
*req
)
6429 char *e
= ast_skip_blanks(req
->header
[0]); /* there shouldn't be any */
6433 req
->rlPart1
= e
; /* method or protocol */
6434 e
= ast_skip_nonblanks(e
);
6437 /* Get URI or status code */
6438 e
= ast_skip_blanks(e
);
6443 if (!strcasecmp(req
->rlPart1
, "SIP/2.0") ) { /* We have a response */
6444 if (strlen(e
) < 3) /* status code is 3 digits */
6447 } else { /* We have a request */
6448 if ( *e
== '<' ) { /* XXX the spec says it must not be in <> ! */
6449 ast_log(LOG_WARNING
, "bogus uri in <> %s\n", e
);
6454 req
->rlPart2
= e
; /* URI */
6455 e
= ast_skip_nonblanks(e
);
6458 e
= ast_skip_blanks(e
);
6459 if (strcasecmp(e
, "SIP/2.0") ) {
6460 ast_log(LOG_WARNING
, "Bad request protocol %s\n", e
);
6467 /*! \brief Transmit reinvite with SDP
6468 \note A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
6469 INVITE that opened the SIP dialogue
6470 We reinvite so that the audio stream (RTP) go directly between
6471 the SIP UAs. SIP Signalling stays with * in the path.
6473 static int transmit_reinvite_with_sdp(struct sip_pvt
*p
)
6475 struct sip_request req
;
6477 reqprep(&req
, p
, ast_test_flag(&p
->flags
[0], SIP_REINVITE_UPDATE
) ? SIP_UPDATE
: SIP_INVITE
, 0, 1);
6479 add_header(&req
, "Allow", ALLOWED_METHODS
);
6480 add_header(&req
, "Supported", SUPPORTED_EXTENSIONS
);
6482 add_header(&req
, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
6483 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
))
6484 append_history(p
, "ReInv", "Re-invite sent");
6486 /* Use this as the basis */
6487 initialize_initreq(p
, &req
);
6488 p
->lastinvite
= p
->ocseq
;
6489 ast_set_flag(&p
->flags
[0], SIP_OUTGOING
); /* Change direction of this dialog */
6490 return send_request(p
, &req
, XMIT_CRITICAL
, p
->ocseq
);
6493 /*! \brief Transmit reinvite with T38 SDP
6494 We reinvite so that the T38 processing can take place.
6495 SIP Signalling stays with * in the path.
6497 static int transmit_reinvite_with_t38_sdp(struct sip_pvt
*p
)
6499 struct sip_request req
;
6501 reqprep(&req
, p
, ast_test_flag(&p
->flags
[0], SIP_REINVITE_UPDATE
) ? SIP_UPDATE
: SIP_INVITE
, 0, 1);
6503 add_header(&req
, "Allow", ALLOWED_METHODS
);
6504 add_header(&req
, "Supported", SUPPORTED_EXTENSIONS
);
6506 add_header(&req
, "X-asterisk-info", "SIP re-invite (T38 switchover)");
6507 ast_udptl_offered_from_local(p
->udptl
, 1);
6508 add_t38_sdp(&req
, p
);
6509 /* Use this as the basis */
6510 initialize_initreq(p
, &req
);
6511 ast_set_flag(&p
->flags
[0], SIP_OUTGOING
); /* Change direction of this dialog */
6512 p
->lastinvite
= p
->ocseq
;
6513 return send_request(p
, &req
, XMIT_CRITICAL
, p
->ocseq
);
6516 /*! \brief Check Contact: URI of SIP message */
6517 static void extract_uri(struct sip_pvt
*p
, struct sip_request
*req
)
6522 ast_copy_string(stripped
, get_header(req
, "Contact"), sizeof(stripped
));
6523 c
= get_in_brackets(stripped
);
6524 c
= strsep(&c
, ";"); /* trim ; and beyond */
6525 if (!ast_strlen_zero(c
))
6526 ast_string_field_set(p
, uri
, c
);
6529 /*! \brief Build contact header - the contact header we send out */
6530 static void build_contact(struct sip_pvt
*p
)
6532 /* Construct Contact: header */
6533 if (ourport
!= STANDARD_SIP_PORT
)
6534 ast_string_field_build(p
, our_contact
, "<sip:%s%s%s:%d>", p
->exten
, ast_strlen_zero(p
->exten
) ? "" : "@", ast_inet_ntoa(p
->ourip
), ourport
);
6536 ast_string_field_build(p
, our_contact
, "<sip:%s%s%s>", p
->exten
, ast_strlen_zero(p
->exten
) ? "" : "@", ast_inet_ntoa(p
->ourip
));
6539 /*! \brief Build the Remote Party-ID & From using callingpres options */
6540 static void build_rpid(struct sip_pvt
*p
)
6542 int send_pres_tags
= TRUE
;
6543 const char *privacy
=NULL
;
6544 const char *screen
=NULL
;
6546 const char *clid
= default_callerid
;
6547 const char *clin
= NULL
;
6548 const char *fromdomain
;
6550 if (!ast_strlen_zero(p
->rpid
) || !ast_strlen_zero(p
->rpid_from
))
6553 if (p
->owner
&& p
->owner
->cid
.cid_num
)
6554 clid
= p
->owner
->cid
.cid_num
;
6555 if (p
->owner
&& p
->owner
->cid
.cid_name
)
6556 clin
= p
->owner
->cid
.cid_name
;
6557 if (ast_strlen_zero(clin
))
6560 switch (p
->callingpres
) {
6561 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED
:
6565 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN
:
6569 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN
:
6573 case AST_PRES_ALLOWED_NETWORK_NUMBER
:
6577 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED
:
6581 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN
:
6585 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN
:
6589 case AST_PRES_PROHIB_NETWORK_NUMBER
:
6593 case AST_PRES_NUMBER_NOT_AVAILABLE
:
6594 send_pres_tags
= FALSE
;
6597 ast_log(LOG_WARNING
, "Unsupported callingpres (%d)\n", p
->callingpres
);
6598 if ((p
->callingpres
& AST_PRES_RESTRICTION
) != AST_PRES_ALLOWED
)
6606 fromdomain
= S_OR(p
->fromdomain
, ast_inet_ntoa(p
->ourip
));
6608 snprintf(buf
, sizeof(buf
), "\"%s\" <sip:%s@%s>", clin
, clid
, fromdomain
);
6610 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
), ";privacy=%s;screen=%s", privacy
, screen
);
6611 ast_string_field_set(p
, rpid
, buf
);
6613 ast_string_field_build(p
, rpid_from
, "\"%s\" <sip:%s@%s>;tag=%s", clin
,
6614 S_OR(p
->fromuser
, clid
),
6615 fromdomain
, p
->tag
);
6618 /*! \brief Initiate new SIP request to peer/user */
6619 static void initreqprep(struct sip_request
*req
, struct sip_pvt
*p
, int sipmethod
)
6621 char invite_buf
[256] = "";
6622 char *invite
= invite_buf
;
6623 size_t invite_max
= sizeof(invite_buf
);
6627 char tmp2
[BUFSIZ
/2];
6628 const char *l
= NULL
, *n
= NULL
;
6629 const char *urioptions
= "";
6631 if (ast_test_flag(&p
->flags
[0], SIP_USEREQPHONE
)) {
6632 const char *s
= p
->username
; /* being a string field, cannot be NULL */
6634 /* Test p->username against allowed characters in AST_DIGIT_ANY
6635 If it matches the allowed characters list, then sipuser = ";user=phone"
6636 If not, then sipuser = ""
6638 /* + is allowed in first position in a tel: uri */
6642 if (!strchr(AST_DIGIT_ANYNUM
, *s
) )
6645 /* If we have only digits, add ;user=phone to the uri */
6647 urioptions
= ";user=phone";
6651 snprintf(p
->lastmsg
, sizeof(p
->lastmsg
), "Init: %s", sip_methods
[sipmethod
].text
);
6654 l
= p
->owner
->cid
.cid_num
;
6655 n
= p
->owner
->cid
.cid_name
;
6657 /* if we are not sending RPID and user wants his callerid restricted */
6658 if (!ast_test_flag(&p
->flags
[0], SIP_SENDRPID
) &&
6659 ((p
->callingpres
& AST_PRES_RESTRICTION
) != AST_PRES_ALLOWED
)) {
6660 l
= CALLERID_UNKNOWN
;
6663 if (ast_strlen_zero(l
))
6664 l
= default_callerid
;
6665 if (ast_strlen_zero(n
))
6667 /* Allow user to be overridden */
6668 if (!ast_strlen_zero(p
->fromuser
))
6670 else /* Save for any further attempts */
6671 ast_string_field_set(p
, fromuser
, l
);
6673 /* Allow user to be overridden */
6674 if (!ast_strlen_zero(p
->fromname
))
6676 else /* Save for any further attempts */
6677 ast_string_field_set(p
, fromname
, n
);
6679 if (pedanticsipchecking
) {
6680 ast_uri_encode(n
, tmp
, sizeof(tmp
), 0);
6682 ast_uri_encode(l
, tmp2
, sizeof(tmp2
), 0);
6686 if (ourport
!= STANDARD_SIP_PORT
&& ast_strlen_zero(p
->fromdomain
))
6687 snprintf(from
, sizeof(from
), "\"%s\" <sip:%s@%s:%d>;tag=%s", n
, l
, S_OR(p
->fromdomain
, ast_inet_ntoa(p
->ourip
)), ourport
, p
->tag
);
6689 snprintf(from
, sizeof(from
), "\"%s\" <sip:%s@%s>;tag=%s", n
, l
, S_OR(p
->fromdomain
, ast_inet_ntoa(p
->ourip
)), p
->tag
);
6691 /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
6692 if (!ast_strlen_zero(p
->fullcontact
)) {
6693 /* If we have full contact, trust it */
6694 ast_build_string(&invite
, &invite_max
, "%s", p
->fullcontact
);
6696 /* Otherwise, use the username while waiting for registration */
6697 ast_build_string(&invite
, &invite_max
, "sip:");
6698 if (!ast_strlen_zero(p
->username
)) {
6700 if (pedanticsipchecking
) {
6701 ast_uri_encode(n
, tmp
, sizeof(tmp
), 0);
6704 ast_build_string(&invite
, &invite_max
, "%s@", n
);
6706 ast_build_string(&invite
, &invite_max
, "%s", p
->tohost
);
6707 if (ntohs(p
->sa
.sin_port
) != STANDARD_SIP_PORT
)
6708 ast_build_string(&invite
, &invite_max
, ":%d", ntohs(p
->sa
.sin_port
));
6709 ast_build_string(&invite
, &invite_max
, "%s", urioptions
);
6712 /* If custom URI options have been provided, append them */
6713 if (p
->options
&& p
->options
->uri_options
)
6714 ast_build_string(&invite
, &invite_max
, ";%s", p
->options
->uri_options
);
6716 ast_string_field_set(p
, uri
, invite_buf
);
6718 if (sipmethod
== SIP_NOTIFY
&& !ast_strlen_zero(p
->theirtag
)) {
6719 /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
6720 snprintf(to
, sizeof(to
), "<sip:%s>;tag=%s", p
->uri
, p
->theirtag
);
6721 } else if (p
->options
&& p
->options
->vxml_url
) {
6722 /* If there is a VXML URL append it to the SIP URL */
6723 snprintf(to
, sizeof(to
), "<%s>;%s", p
->uri
, p
->options
->vxml_url
);
6725 snprintf(to
, sizeof(to
), "<%s>", p
->uri
);
6727 init_req(req
, sipmethod
, p
->uri
);
6728 snprintf(tmp
, sizeof(tmp
), "%d %s", ++p
->ocseq
, sip_methods
[sipmethod
].text
);
6730 add_header(req
, "Via", p
->via
);
6731 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
6732 * OTOH, then we won't have anything in p->route anyway */
6733 /* Build Remote Party-ID and From */
6734 if (ast_test_flag(&p
->flags
[0], SIP_SENDRPID
) && (sipmethod
== SIP_INVITE
)) {
6736 add_header(req
, "From", p
->rpid_from
);
6738 add_header(req
, "From", from
);
6739 add_header(req
, "To", to
);
6740 ast_string_field_set(p
, exten
, l
);
6742 add_header(req
, "Contact", p
->our_contact
);
6743 add_header(req
, "Call-ID", p
->callid
);
6744 add_header(req
, "CSeq", tmp
);
6745 add_header(req
, "User-Agent", global_useragent
);
6746 add_header(req
, "Max-Forwards", DEFAULT_MAX_FORWARDS
);
6747 if (!ast_strlen_zero(p
->rpid
))
6748 add_header(req
, "Remote-Party-ID", p
->rpid
);
6751 /*! \brief Build REFER/INVITE/OPTIONS message and transmit it */
6752 static int transmit_invite(struct sip_pvt
*p
, int sipmethod
, int sdp
, int init
)
6754 struct sip_request req
;
6756 req
.method
= sipmethod
;
6757 if (init
) { /* Seems like init always is 2 */
6758 /* Bump branch even on initial requests */
6759 p
->branch
^= ast_random();
6762 initreqprep(&req
, p
, sipmethod
);
6764 reqprep(&req
, p
, sipmethod
, 0, 1);
6766 reqprep(&req
, p
, sipmethod
, 0, 1);
6768 if (p
->options
&& p
->options
->auth
)
6769 add_header(&req
, p
->options
->authheader
, p
->options
->auth
);
6771 if (sipmethod
== SIP_REFER
) { /* Call transfer */
6774 if (!ast_strlen_zero(p
->refer
->refer_to
))
6775 add_header(&req
, "Refer-To", p
->refer
->refer_to
);
6776 if (!ast_strlen_zero(p
->refer
->referred_by
)) {
6777 sprintf(buf
, "%s <%s>", p
->refer
->referred_by_name
, p
->refer
->referred_by
);
6778 add_header(&req
, "Referred-By", buf
);
6782 /* This new INVITE is part of an attended transfer. Make sure that the
6783 other end knows and replace the current call with this new call */
6784 if (p
->options
&& p
->options
->replaces
&& !ast_strlen_zero(p
->options
->replaces
)) {
6785 add_header(&req
, "Replaces", p
->options
->replaces
);
6786 add_header(&req
, "Require", "replaces");
6789 add_header(&req
, "Allow", ALLOWED_METHODS
);
6790 add_header(&req
, "Supported", SUPPORTED_EXTENSIONS
);
6791 if (p
->options
&& p
->options
->addsipheaders
&& p
->owner
) {
6792 struct ast_channel
*ast
= p
->owner
; /* The owner channel */
6793 struct varshead
*headp
= &ast
->varshead
;
6796 ast_log(LOG_WARNING
,"No Headp for the channel...ooops!\n");
6798 const struct ast_var_t
*current
;
6799 AST_LIST_TRAVERSE(headp
, current
, entries
) {
6800 /* SIPADDHEADER: Add SIP header to outgoing call */
6801 if (!strncasecmp(ast_var_name(current
), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
6802 char *content
, *end
;
6803 const char *header
= ast_var_value(current
);
6804 char *headdup
= ast_strdupa(header
);
6806 /* Strip of the starting " (if it's there) */
6807 if (*headdup
== '"')
6809 if ((content
= strchr(headdup
, ':'))) {
6811 content
= ast_skip_blanks(content
); /* Skip white space */
6812 /* Strip the ending " (if it's there) */
6813 end
= content
+ strlen(content
) -1;
6817 add_header(&req
, headdup
, content
);
6819 ast_log(LOG_DEBUG
, "Adding SIP Header \"%s\" with content :%s: \n", headdup
, content
);
6826 if (p
->udptl
&& p
->t38
.state
== T38_LOCAL_DIRECT
) {
6827 ast_udptl_offered_from_local(p
->udptl
, 1);
6829 ast_log(LOG_DEBUG
, "T38 is in state %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>");
6830 add_t38_sdp(&req
, p
);
6834 add_header_contentLength(&req
, 0);
6837 if (!p
->initreq
.headers
)
6838 initialize_initreq(p
, &req
);
6839 p
->lastinvite
= p
->ocseq
;
6840 return send_request(p
, &req
, init
? XMIT_CRITICAL
: XMIT_RELIABLE
, p
->ocseq
);
6843 /*! \brief Used in the SUBSCRIBE notification subsystem */
6844 static int transmit_state_notify(struct sip_pvt
*p
, int state
, int full
, int timeout
)
6846 char tmp
[4000], from
[256], to
[256];
6847 char *t
= tmp
, *c
, *mfrom
, *mto
;
6848 size_t maxbytes
= sizeof(tmp
);
6849 struct sip_request req
;
6850 char hint
[AST_MAX_EXTENSION
];
6851 char *statestring
= "terminated";
6852 const struct cfsubscription_types
*subscriptiontype
;
6853 enum state
{ NOTIFY_OPEN
, NOTIFY_INUSE
, NOTIFY_CLOSED
} local_state
= NOTIFY_OPEN
;
6854 char *pidfstate
= "--";
6855 char *pidfnote
= "Ready";
6857 memset(from
, 0, sizeof(from
));
6858 memset(to
, 0, sizeof(to
));
6859 memset(tmp
, 0, sizeof(tmp
));
6862 case (AST_EXTENSION_RINGING
| AST_EXTENSION_INUSE
):
6863 statestring
= (global_notifyringing
) ? "early" : "confirmed";
6864 local_state
= NOTIFY_INUSE
;
6866 pidfnote
= "Ringing";
6868 case AST_EXTENSION_RINGING
:
6869 statestring
= "early";
6870 local_state
= NOTIFY_INUSE
;
6872 pidfnote
= "Ringing";
6874 case AST_EXTENSION_INUSE
:
6875 statestring
= "confirmed";
6876 local_state
= NOTIFY_INUSE
;
6878 pidfnote
= "On the phone";
6880 case AST_EXTENSION_BUSY
:
6881 statestring
= "confirmed";
6882 local_state
= NOTIFY_CLOSED
;
6884 pidfnote
= "On the phone";
6886 case AST_EXTENSION_UNAVAILABLE
:
6887 statestring
= "terminated";
6888 local_state
= NOTIFY_CLOSED
;
6890 pidfnote
= "Unavailable";
6892 case AST_EXTENSION_ONHOLD
:
6893 statestring
= "confirmed";
6894 local_state
= NOTIFY_INUSE
;
6896 pidfnote
= "On Hold";
6898 case AST_EXTENSION_NOT_INUSE
:
6900 /* Default setting */
6904 subscriptiontype
= find_subscription_type(p
->subscribed
);
6906 /* Check which device/devices we are watching and if they are registered */
6907 if (ast_get_hint(hint
, sizeof(hint
), NULL
, 0, NULL
, p
->context
, p
->exten
)) {
6908 /* If they are not registered, we will override notification and show no availability */
6909 if (ast_device_state(hint
) == AST_DEVICE_UNAVAILABLE
) {
6910 local_state
= NOTIFY_CLOSED
;
6912 pidfnote
= "Not online";
6916 ast_copy_string(from
, get_header(&p
->initreq
, "From"), sizeof(from
));
6917 c
= get_in_brackets(from
);
6918 if (strncmp(c
, "sip:", 4)) {
6919 ast_log(LOG_WARNING
, "Huh? Not a SIP header (%s)?\n", c
);
6922 mfrom
= strsep(&c
, ";"); /* trim ; and beyond */
6924 ast_copy_string(to
, get_header(&p
->initreq
, "To"), sizeof(to
));
6925 c
= get_in_brackets(to
);
6926 if (strncmp(c
, "sip:", 4)) {
6927 ast_log(LOG_WARNING
, "Huh? Not a SIP header (%s)?\n", c
);
6930 mto
= strsep(&c
, ";"); /* trim ; and beyond */
6932 reqprep(&req
, p
, SIP_NOTIFY
, 0, 1);
6935 add_header(&req
, "Event", subscriptiontype
->event
);
6936 add_header(&req
, "Content-Type", subscriptiontype
->mediatype
);
6938 case AST_EXTENSION_DEACTIVATED
:
6940 add_header(&req
, "Subscription-State", "terminated;reason=timeout");
6942 add_header(&req
, "Subscription-State", "terminated;reason=probation");
6943 add_header(&req
, "Retry-After", "60");
6946 case AST_EXTENSION_REMOVED
:
6947 add_header(&req
, "Subscription-State", "terminated;reason=noresource");
6951 add_header(&req
, "Subscription-State", "active");
6953 add_header(&req
, "Subscription-State", "terminated;reason=timeout");
6955 switch (p
->subscribed
) {
6958 ast_build_string(&t
, &maxbytes
, "<?xml version=\"1.0\"?>\n");
6959 ast_build_string(&t
, &maxbytes
, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
6960 ast_build_string(&t
, &maxbytes
, "<presence>\n");
6961 ast_build_string(&t
, &maxbytes
, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom
);
6962 ast_build_string(&t
, &maxbytes
, "<atom id=\"%s\">\n", p
->exten
);
6963 ast_build_string(&t
, &maxbytes
, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto
);
6964 ast_build_string(&t
, &maxbytes
, "<status status=\"%s\" />\n", (local_state
== NOTIFY_OPEN
) ? "open" : (local_state
== NOTIFY_INUSE
) ? "inuse" : "closed");
6965 ast_build_string(&t
, &maxbytes
, "<msnsubstatus substatus=\"%s\" />\n", (local_state
== NOTIFY_OPEN
) ? "online" : (local_state
== NOTIFY_INUSE
) ? "onthephone" : "offline");
6966 ast_build_string(&t
, &maxbytes
, "</address>\n</atom>\n</presence>\n");
6968 case PIDF_XML
: /* Eyebeam supports this format */
6969 ast_build_string(&t
, &maxbytes
, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
6970 ast_build_string(&t
, &maxbytes
, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" \nxmlns:pp=\"urn:ietf:params:xml:ns:pidf:person\"\nxmlns:es=\"urn:ietf:params:xml:ns:pidf:rpid:status:rpid-status\"\nxmlns:ep=\"urn:ietf:params:xml:ns:pidf:rpid:rpid-person\"\nentity=\"%s\">\n", mfrom
);
6971 ast_build_string(&t
, &maxbytes
, "<pp:person><status>\n");
6972 if (pidfstate
[0] != '-')
6973 ast_build_string(&t
, &maxbytes
, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate
);
6974 ast_build_string(&t
, &maxbytes
, "</status></pp:person>\n");
6975 ast_build_string(&t
, &maxbytes
, "<note>%s</note>\n", pidfnote
); /* Note */
6976 ast_build_string(&t
, &maxbytes
, "<tuple id=\"%s\">\n", p
->exten
); /* Tuple start */
6977 ast_build_string(&t
, &maxbytes
, "<contact priority=\"1\">%s</contact>\n", mto
);
6978 if (pidfstate
[0] == 'b') /* Busy? Still open ... */
6979 ast_build_string(&t
, &maxbytes
, "<status><basic>open</basic></status>\n");
6981 ast_build_string(&t
, &maxbytes
, "<status><basic>%s</basic></status>\n", (local_state
!= NOTIFY_CLOSED
) ? "open" : "closed");
6982 ast_build_string(&t
, &maxbytes
, "</tuple>\n</presence>\n");
6984 case DIALOG_INFO_XML
: /* SNOM subscribes in this format */
6985 ast_build_string(&t
, &maxbytes
, "<?xml version=\"1.0\"?>\n");
6986 ast_build_string(&t
, &maxbytes
, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p
->dialogver
++, full
? "full":"partial", mto
);
6987 if ((state
& AST_EXTENSION_RINGING
) && global_notifyringing
)
6988 ast_build_string(&t
, &maxbytes
, "<dialog id=\"%s\" direction=\"recipient\">\n", p
->exten
);
6990 ast_build_string(&t
, &maxbytes
, "<dialog id=\"%s\">\n", p
->exten
);
6991 ast_build_string(&t
, &maxbytes
, "<state>%s</state>\n", statestring
);
6992 if (state
== AST_EXTENSION_ONHOLD
) {
6993 ast_build_string(&t
, &maxbytes
, "<local>\n<target uri=\"%s\">\n"
6994 "<param pname=\"+sip.rendering\" pvalue=\"no\">\n"
6995 "</target>\n</local>\n", mto
);
6997 ast_build_string(&t
, &maxbytes
, "</dialog>\n</dialog-info>\n");
7004 if (t
> tmp
+ sizeof(tmp
))
7005 ast_log(LOG_WARNING
, "Buffer overflow detected!! (Please file a bug report)\n");
7007 add_header_contentLength(&req
, strlen(tmp
));
7008 add_line(&req
, tmp
);
7010 return send_request(p
, &req
, XMIT_RELIABLE
, p
->ocseq
);
7013 /*! \brief Notify user of messages waiting in voicemail
7014 \note - Notification only works for registered peers with mailbox= definitions
7016 - We use the SIP Event package message-summary
7017 MIME type defaults to "application/simple-message-summary";
7019 static int transmit_notify_with_mwi(struct sip_pvt
*p
, int newmsgs
, int oldmsgs
, char *vmexten
)
7021 struct sip_request req
;
7024 size_t maxbytes
= sizeof(tmp
);
7026 initreqprep(&req
, p
, SIP_NOTIFY
);
7027 add_header(&req
, "Event", "message-summary");
7028 add_header(&req
, "Content-Type", default_notifymime
);
7030 ast_build_string(&t
, &maxbytes
, "Messages-Waiting: %s\r\n", newmsgs
? "yes" : "no");
7031 ast_build_string(&t
, &maxbytes
, "Message-Account: sip:%s@%s\r\n",
7032 S_OR(vmexten
, default_vmexten
), S_OR(p
->fromdomain
, ast_inet_ntoa(p
->ourip
)));
7033 /* Cisco has a bug in the SIP stack where it can't accept the
7034 (0/0) notification. This can temporarily be disabled in
7035 sip.conf with the "buggymwi" option */
7036 ast_build_string(&t
, &maxbytes
, "Voice-Message: %d/%d%s\r\n", newmsgs
, oldmsgs
, (ast_test_flag(&p
->flags
[1], SIP_PAGE2_BUGGY_MWI
) ? "" : " (0/0)"));
7038 if (p
->subscribed
) {
7040 add_header(&req
, "Subscription-State", "active");
7042 add_header(&req
, "Subscription-State", "terminated;reason=timeout");
7045 if (t
> tmp
+ sizeof(tmp
))
7046 ast_log(LOG_WARNING
, "Buffer overflow detected!! (Please file a bug report)\n");
7048 add_header_contentLength(&req
, strlen(tmp
));
7049 add_line(&req
, tmp
);
7051 if (!p
->initreq
.headers
)
7052 initialize_initreq(p
, &req
);
7053 return send_request(p
, &req
, XMIT_RELIABLE
, p
->ocseq
);
7056 /*! \brief Transmit SIP request unreliably (only used in sip_notify subsystem) */
7057 static int transmit_sip_request(struct sip_pvt
*p
, struct sip_request
*req
)
7059 if (!p
->initreq
.headers
) /* Initialize first request before sending */
7060 initialize_initreq(p
, req
);
7061 return send_request(p
, req
, XMIT_UNRELIABLE
, p
->ocseq
);
7064 /*! \brief Notify a transferring party of the status of transfer */
7065 static int transmit_notify_with_sipfrag(struct sip_pvt
*p
, int cseq
, char *message
, int terminate
)
7067 struct sip_request req
;
7070 reqprep(&req
, p
, SIP_NOTIFY
, 0, 1);
7071 snprintf(tmp
, sizeof(tmp
), "refer;id=%d", cseq
);
7072 add_header(&req
, "Event", tmp
);
7073 add_header(&req
, "Subscription-state", terminate
? "terminated;reason=noresource" : "active");
7074 add_header(&req
, "Content-Type", "message/sipfrag;version=2.0");
7075 add_header(&req
, "Allow", ALLOWED_METHODS
);
7076 add_header(&req
, "Supported", SUPPORTED_EXTENSIONS
);
7078 snprintf(tmp
, sizeof(tmp
), "SIP/2.0 %s\r\n", message
);
7079 add_header_contentLength(&req
, strlen(tmp
));
7080 add_line(&req
, tmp
);
7082 if (!p
->initreq
.headers
)
7083 initialize_initreq(p
, &req
);
7085 return send_request(p
, &req
, XMIT_RELIABLE
, p
->ocseq
);
7088 /*! \brief Convert registration state status to string */
7089 static char *regstate2str(enum sipregistrystate regstate
)
7092 case REG_STATE_FAILED
:
7094 case REG_STATE_UNREGISTERED
:
7095 return "Unregistered";
7096 case REG_STATE_REGSENT
:
7097 return "Request Sent";
7098 case REG_STATE_AUTHSENT
:
7099 return "Auth. Sent";
7100 case REG_STATE_REGISTERED
:
7101 return "Registered";
7102 case REG_STATE_REJECTED
:
7104 case REG_STATE_TIMEOUT
:
7106 case REG_STATE_NOAUTH
:
7107 return "No Authentication";
7113 /*! \brief Update registration with SIP Proxy */
7114 static int sip_reregister(void *data
)
7116 /* if we are here, we know that we need to reregister. */
7117 struct sip_registry
*r
= ASTOBJ_REF((struct sip_registry
*) data
);
7119 /* if we couldn't get a reference to the registry object, punt */
7123 if (r
->call
&& !ast_test_flag(&r
->call
->flags
[0], SIP_NO_HISTORY
))
7124 append_history(r
->call
, "RegistryRenew", "Account: %s@%s", r
->username
, r
->hostname
);
7125 /* Since registry's are only added/removed by the the monitor thread, this
7126 may be overkill to reference/dereference at all here */
7128 ast_log(LOG_NOTICE
, " -- Re-registration for %s@%s\n", r
->username
, r
->hostname
);
7131 __sip_do_register(r
);
7132 ASTOBJ_UNREF(r
, sip_registry_destroy
);
7136 /*! \brief Register with SIP proxy */
7137 static int __sip_do_register(struct sip_registry
*r
)
7141 res
= transmit_register(r
, SIP_REGISTER
, NULL
, NULL
);
7145 /*! \brief Registration timeout, register again */
7146 static int sip_reg_timeout(void *data
)
7149 /* if we are here, our registration timed out, so we'll just do it over */
7150 struct sip_registry
*r
= ASTOBJ_REF((struct sip_registry
*) data
);
7154 /* if we couldn't get a reference to the registry object, punt */
7158 ast_log(LOG_NOTICE
, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r
->username
, r
->hostname
, r
->regattempts
);
7160 /* Unlink us, destroy old call. Locking is not relevant here because all this happens
7161 in the single SIP manager thread. */
7164 ASTOBJ_UNREF(p
->registry
, sip_registry_destroy
);
7166 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
7167 /* Pretend to ACK anything just in case */
7168 __sip_pretend_ack(p
); /* XXX we need p locked, not sure we have */
7170 /* If we have a limit, stop registration and give up */
7171 if (global_regattempts_max
&& (r
->regattempts
> global_regattempts_max
)) {
7172 /* Ok, enough is enough. Don't try any more */
7173 /* We could add an external notification here...
7174 steal it from app_voicemail :-) */
7175 ast_log(LOG_NOTICE
, " -- Giving up forever trying to register '%s@%s'\n", r
->username
, r
->hostname
);
7176 r
->regstate
= REG_STATE_FAILED
;
7178 r
->regstate
= REG_STATE_UNREGISTERED
;
7180 res
=transmit_register(r
, SIP_REGISTER
, NULL
, NULL
);
7182 manager_event(EVENT_FLAG_SYSTEM
, "Registry", "ChannelDriver: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r
->username
, r
->hostname
, regstate2str(r
->regstate
));
7183 ASTOBJ_UNREF(r
, sip_registry_destroy
);
7187 /*! \brief Transmit register to SIP proxy or UA */
7188 static int transmit_register(struct sip_registry
*r
, int sipmethod
, const char *auth
, const char *authheader
)
7190 struct sip_request req
;
7197 /* exit if we are already in process with this registrar ?*/
7198 if ( r
== NULL
|| ((auth
==NULL
) && (r
->regstate
==REG_STATE_REGSENT
|| r
->regstate
==REG_STATE_AUTHSENT
))) {
7199 ast_log(LOG_NOTICE
, "Strange, trying to register %s@%s when registration already pending\n", r
->username
, r
->hostname
);
7203 if (r
->call
) { /* We have a registration */
7205 ast_log(LOG_WARNING
, "Already have a REGISTER going on to %s@%s?? \n", r
->username
, r
->hostname
);
7209 make_our_tag(p
->tag
, sizeof(p
->tag
)); /* create a new local tag for every register attempt */
7210 ast_string_field_free(p
, theirtag
); /* forget their old tag, so we don't match tags when getting response */
7213 /* Build callid for registration if we haven't registered before */
7214 if (!r
->callid_valid
) {
7215 build_callid_registry(r
, __ourip
, default_fromdomain
);
7216 r
->callid_valid
= TRUE
;
7218 /* Allocate SIP packet for registration */
7219 if (!(p
= sip_alloc( r
->callid
, NULL
, 0, SIP_REGISTER
))) {
7220 ast_log(LOG_WARNING
, "Unable to allocate registration transaction (memory or socket error)\n");
7223 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
))
7224 append_history(p
, "RegistryInit", "Account: %s@%s", r
->username
, r
->hostname
);
7225 /* Find address to hostname */
7226 if (create_addr(p
, r
->hostname
)) {
7227 /* we have what we hope is a temporary network error,
7228 * probably DNS. We need to reschedule a registration try */
7230 if (r
->timeout
> -1) {
7231 ast_sched_del(sched
, r
->timeout
);
7232 r
->timeout
= ast_sched_add(sched
, global_reg_timeout
*1000, sip_reg_timeout
, r
);
7233 ast_log(LOG_WARNING
, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r
->username
, r
->hostname
, r
->timeout
);
7235 r
->timeout
= ast_sched_add(sched
, global_reg_timeout
*1000, sip_reg_timeout
, r
);
7236 ast_log(LOG_WARNING
, "Probably a DNS error for registration to %s@%s, trying REGISTER again (after %d seconds)\n", r
->username
, r
->hostname
, global_reg_timeout
);
7241 /* Copy back Call-ID in case create_addr changed it */
7242 ast_string_field_set(r
, callid
, p
->callid
);
7244 p
->sa
.sin_port
= htons(r
->portno
);
7245 else /* Set registry port to the port set from the peer definition/srv or default */
7246 r
->portno
= ntohs(p
->sa
.sin_port
);
7247 ast_set_flag(&p
->flags
[0], SIP_OUTGOING
); /* Registration is outgoing call */
7248 r
->call
=p
; /* Save pointer to SIP packet */
7249 p
->registry
= ASTOBJ_REF(r
); /* Add pointer to registry in packet */
7250 if (!ast_strlen_zero(r
->secret
)) /* Secret (password) */
7251 ast_string_field_set(p
, peersecret
, r
->secret
);
7252 if (!ast_strlen_zero(r
->md5secret
))
7253 ast_string_field_set(p
, peermd5secret
, r
->md5secret
);
7254 /* User name in this realm
7255 - if authuser is set, use that, otherwise use username */
7256 if (!ast_strlen_zero(r
->authuser
)) {
7257 ast_string_field_set(p
, peername
, r
->authuser
);
7258 ast_string_field_set(p
, authname
, r
->authuser
);
7259 } else if (!ast_strlen_zero(r
->username
)) {
7260 ast_string_field_set(p
, peername
, r
->username
);
7261 ast_string_field_set(p
, authname
, r
->username
);
7262 ast_string_field_set(p
, fromuser
, r
->username
);
7264 if (!ast_strlen_zero(r
->username
))
7265 ast_string_field_set(p
, username
, r
->username
);
7266 /* Save extension in packet */
7267 ast_string_field_set(p
, exten
, r
->contact
);
7270 check which address we should use in our contact header
7271 based on whether the remote host is on the external or
7272 internal network so we can register through nat
7274 if (ast_sip_ouraddrfor(&p
->sa
.sin_addr
, &p
->ourip
))
7275 p
->ourip
= bindaddr
.sin_addr
;
7279 /* set up a timeout */
7281 if (r
->timeout
> -1) {
7282 ast_log(LOG_WARNING
, "Still have a registration timeout, #%d - deleting it\n", r
->timeout
);
7283 ast_sched_del(sched
, r
->timeout
);
7285 r
->timeout
= ast_sched_add(sched
, global_reg_timeout
* 1000, sip_reg_timeout
, r
);
7287 ast_log(LOG_DEBUG
, "Scheduled a registration timeout for %s id #%d \n", r
->hostname
, r
->timeout
);
7290 if (strchr(r
->username
, '@')) {
7291 snprintf(from
, sizeof(from
), "<sip:%s>;tag=%s", r
->username
, p
->tag
);
7292 if (!ast_strlen_zero(p
->theirtag
))
7293 snprintf(to
, sizeof(to
), "<sip:%s>;tag=%s", r
->username
, p
->theirtag
);
7295 snprintf(to
, sizeof(to
), "<sip:%s>", r
->username
);
7297 snprintf(from
, sizeof(from
), "<sip:%s@%s>;tag=%s", r
->username
, p
->tohost
, p
->tag
);
7298 if (!ast_strlen_zero(p
->theirtag
))
7299 snprintf(to
, sizeof(to
), "<sip:%s@%s>;tag=%s", r
->username
, p
->tohost
, p
->theirtag
);
7301 snprintf(to
, sizeof(to
), "<sip:%s@%s>", r
->username
, p
->tohost
);
7304 /* Fromdomain is what we are registering to, regardless of actual
7305 host name from SRV */
7306 snprintf(addr
, sizeof(addr
), "sip:%s", S_OR(p
->fromdomain
, r
->hostname
));
7307 ast_string_field_set(p
, uri
, addr
);
7309 p
->branch
^= ast_random();
7311 init_req(&req
, sipmethod
, addr
);
7314 snprintf(tmp
, sizeof(tmp
), "%u %s", ++r
->ocseq
, sip_methods
[sipmethod
].text
);
7315 p
->ocseq
= r
->ocseq
;
7318 add_header(&req
, "Via", p
->via
);
7319 add_header(&req
, "From", from
);
7320 add_header(&req
, "To", to
);
7321 add_header(&req
, "Call-ID", p
->callid
);
7322 add_header(&req
, "CSeq", tmp
);
7323 add_header(&req
, "User-Agent", global_useragent
);
7324 add_header(&req
, "Max-Forwards", DEFAULT_MAX_FORWARDS
);
7327 if (auth
) /* Add auth header */
7328 add_header(&req
, authheader
, auth
);
7329 else if (!ast_strlen_zero(r
->nonce
)) {
7332 /* We have auth data to reuse, build a digest header! */
7334 ast_log(LOG_DEBUG
, " >>> Re-using Auth data for %s@%s\n", r
->username
, r
->hostname
);
7335 ast_string_field_set(p
, realm
, r
->realm
);
7336 ast_string_field_set(p
, nonce
, r
->nonce
);
7337 ast_string_field_set(p
, domain
, r
->domain
);
7338 ast_string_field_set(p
, opaque
, r
->opaque
);
7339 ast_string_field_set(p
, qop
, r
->qop
);
7341 p
->noncecount
= r
->noncecount
;
7343 memset(digest
,0,sizeof(digest
));
7344 if(!build_reply_digest(p
, sipmethod
, digest
, sizeof(digest
)))
7345 add_header(&req
, "Authorization", digest
);
7347 ast_log(LOG_NOTICE
, "No authorization available for authentication of registration to %s@%s\n", r
->username
, r
->hostname
);
7351 snprintf(tmp
, sizeof(tmp
), "%d", default_expiry
);
7352 add_header(&req
, "Expires", tmp
);
7353 add_header(&req
, "Contact", p
->our_contact
);
7354 add_header(&req
, "Event", "registration");
7355 add_header_contentLength(&req
, 0);
7357 initialize_initreq(p
, &req
);
7358 if (sip_debug_test_pvt(p
))
7359 ast_verbose("REGISTER %d headers, %d lines\n", p
->initreq
.headers
, p
->initreq
.lines
);
7360 r
->regstate
= auth
? REG_STATE_AUTHSENT
: REG_STATE_REGSENT
;
7361 r
->regattempts
++; /* Another attempt */
7362 if (option_debug
> 3)
7363 ast_verbose("REGISTER attempt %d to %s@%s\n", r
->regattempts
, r
->username
, r
->hostname
);
7364 return send_request(p
, &req
, XMIT_CRITICAL
, p
->ocseq
);
7367 /*! \brief Transmit text with SIP MESSAGE method */
7368 static int transmit_message_with_text(struct sip_pvt
*p
, const char *text
)
7370 struct sip_request req
;
7372 reqprep(&req
, p
, SIP_MESSAGE
, 0, 1);
7373 add_text(&req
, text
);
7374 return send_request(p
, &req
, XMIT_RELIABLE
, p
->ocseq
);
7377 /*! \brief Allocate SIP refer structure */
7378 static int sip_refer_allocate(struct sip_pvt
*p
)
7380 p
->refer
= ast_calloc(1, sizeof(struct sip_refer
));
7381 return p
->refer
? 1 : 0;
7384 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
7385 \note this is currently broken as we have no way of telling the dialplan
7386 engine whether a transfer succeeds or fails.
7387 \todo Fix the transfer() dialplan function so that a transfer may fail
7389 static int transmit_refer(struct sip_pvt
*p
, const char *dest
)
7391 struct sip_request req
= {
7399 char *theirtag
= ast_strdupa(p
->theirtag
);
7401 if (option_debug
|| sipdebug
)
7402 ast_log(LOG_DEBUG
, "SIP transfer of %s to %s\n", p
->callid
, dest
);
7404 /* Are we transfering an inbound or outbound call ? */
7405 if (ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) {
7406 of
= get_header(&p
->initreq
, "To");
7410 of
= get_header(&p
->initreq
, "From");
7415 ast_copy_string(from
, of
, sizeof(from
));
7416 of
= get_in_brackets(from
);
7417 ast_string_field_set(p
, from
, of
);
7418 if (strncmp(of
, "sip:", 4))
7419 ast_log(LOG_NOTICE
, "From address missing 'sip:', using it anyway\n");
7422 /* Get just the username part */
7423 if ((c
= strchr(dest
, '@')))
7425 else if ((c
= strchr(of
, '@')))
7428 snprintf(referto
, sizeof(referto
), "<sip:%s@%s>", dest
, c
);
7430 snprintf(referto
, sizeof(referto
), "<sip:%s>", dest
);
7432 /* save in case we get 407 challenge */
7433 sip_refer_allocate(p
);
7434 ast_copy_string(p
->refer
->refer_to
, referto
, sizeof(p
->refer
->refer_to
));
7435 ast_copy_string(p
->refer
->referred_by
, p
->our_contact
, sizeof(p
->refer
->referred_by
));
7436 p
->refer
->status
= REFER_SENT
; /* Set refer status */
7438 reqprep(&req
, p
, SIP_REFER
, 0, 1);
7439 add_header(&req
, "Max-Forwards", DEFAULT_MAX_FORWARDS
);
7441 add_header(&req
, "Refer-To", referto
);
7442 add_header(&req
, "Allow", ALLOWED_METHODS
);
7443 add_header(&req
, "Supported", SUPPORTED_EXTENSIONS
);
7444 if (!ast_strlen_zero(p
->our_contact
))
7445 add_header(&req
, "Referred-By", p
->our_contact
);
7447 return send_request(p
, &req
, XMIT_RELIABLE
, p
->ocseq
);
7448 /* We should propably wait for a NOTIFY here until we ack the transfer */
7449 /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
7451 /*! \todo In theory, we should hang around and wait for a reply, before
7452 returning to the dial plan here. Don't know really how that would
7453 affect the transfer() app or the pbx, but, well, to make this
7454 useful we should have a STATUS code on transfer().
7459 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
7460 static int transmit_info_with_digit(struct sip_pvt
*p
, const char digit
, unsigned int duration
)
7462 struct sip_request req
;
7464 reqprep(&req
, p
, SIP_INFO
, 0, 1);
7465 add_digit(&req
, digit
, duration
);
7466 return send_request(p
, &req
, XMIT_RELIABLE
, p
->ocseq
);
7469 /*! \brief Send SIP INFO with video update request */
7470 static int transmit_info_with_vidupdate(struct sip_pvt
*p
)
7472 struct sip_request req
;
7474 reqprep(&req
, p
, SIP_INFO
, 0, 1);
7475 add_vidupdate(&req
);
7476 return send_request(p
, &req
, XMIT_RELIABLE
, p
->ocseq
);
7479 /*! \brief Transmit generic SIP request */
7480 static int transmit_request(struct sip_pvt
*p
, int sipmethod
, int seqno
, enum xmittype reliable
, int newbranch
)
7482 struct sip_request resp
;
7484 if (sipmethod
== SIP_ACK
)
7485 p
->invitestate
= INV_CONFIRMED
;
7487 reqprep(&resp
, p
, sipmethod
, seqno
, newbranch
);
7488 add_header_contentLength(&resp
, 0);
7489 return send_request(p
, &resp
, reliable
, seqno
? seqno
: p
->ocseq
);
7492 /*! \brief Transmit SIP request, auth added */
7493 static int transmit_request_with_auth(struct sip_pvt
*p
, int sipmethod
, int seqno
, enum xmittype reliable
, int newbranch
)
7495 struct sip_request resp
;
7497 reqprep(&resp
, p
, sipmethod
, seqno
, newbranch
);
7498 if (!ast_strlen_zero(p
->realm
)) {
7501 memset(digest
, 0, sizeof(digest
));
7502 if(!build_reply_digest(p
, sipmethod
, digest
, sizeof(digest
))) {
7503 if (p
->options
&& p
->options
->auth_type
== PROXY_AUTH
)
7504 add_header(&resp
, "Proxy-Authorization", digest
);
7505 else if (p
->options
&& p
->options
->auth_type
== WWW_AUTH
)
7506 add_header(&resp
, "Authorization", digest
);
7507 else /* Default, to be backwards compatible (maybe being too careful, but leaving it for now) */
7508 add_header(&resp
, "Proxy-Authorization", digest
);
7510 ast_log(LOG_WARNING
, "No authentication available for call %s\n", p
->callid
);
7512 /* If we are hanging up and know a cause for that, send it in clear text to make
7513 debugging easier. */
7514 if (sipmethod
== SIP_BYE
&& p
->owner
&& p
->owner
->hangupcause
) {
7517 add_header(&resp
, "X-Asterisk-HangupCause", ast_cause2str(p
->owner
->hangupcause
));
7518 snprintf(buf
, sizeof(buf
), "%d", p
->owner
->hangupcause
);
7519 add_header(&resp
, "X-Asterisk-HangupCauseCode", buf
);
7522 add_header_contentLength(&resp
, 0);
7523 return send_request(p
, &resp
, reliable
, seqno
? seqno
: p
->ocseq
);
7526 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
7527 static void destroy_association(struct sip_peer
*peer
)
7529 if (!ast_test_flag(&global_flags
[1], SIP_PAGE2_IGNOREREGEXPIRE
)) {
7530 if (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_RT_FROMCONTACT
))
7531 ast_update_realtime("sippeers", "name", peer
->name
, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "username", "", "regserver", "", NULL
);
7533 ast_db_del("SIP/Registry", peer
->name
);
7537 /*! \brief Expire registration of SIP peer */
7538 static int expire_register(void *data
)
7540 struct sip_peer
*peer
= data
;
7542 if (!peer
) /* Hmmm. We have no peer. Weird. */
7545 memset(&peer
->addr
, 0, sizeof(peer
->addr
));
7547 destroy_association(peer
); /* remove registration data from storage */
7549 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer
->name
);
7550 register_peer_exten(peer
, FALSE
); /* Remove regexten */
7552 ast_device_state_changed("SIP/%s", peer
->name
);
7554 /* Do we need to release this peer from memory?
7555 Only for realtime peers and autocreated peers
7557 if (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_SELFDESTRUCT
) ||
7558 ast_test_flag(&peer
->flags
[1], SIP_PAGE2_RTAUTOCLEAR
)) {
7559 peer
= ASTOBJ_CONTAINER_UNLINK(&peerl
, peer
); /* Remove from peer list */
7560 ASTOBJ_UNREF(peer
, sip_destroy_peer
); /* Remove from memory */
7566 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
7567 static int sip_poke_peer_s(void *data
)
7569 struct sip_peer
*peer
= data
;
7571 peer
->pokeexpire
= -1;
7572 sip_poke_peer(peer
);
7576 /*! \brief Get registration details from Asterisk DB */
7577 static void reg_source_db(struct sip_peer
*peer
)
7583 char *scan
, *addr
, *port_str
, *expiry_str
, *username
, *contact
;
7585 if (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_RT_FROMCONTACT
))
7587 if (ast_db_get("SIP/Registry", peer
->name
, data
, sizeof(data
)))
7591 addr
= strsep(&scan
, ":");
7592 port_str
= strsep(&scan
, ":");
7593 expiry_str
= strsep(&scan
, ":");
7594 username
= strsep(&scan
, ":");
7595 contact
= scan
; /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
7597 if (!inet_aton(addr
, &in
))
7601 port
= atoi(port_str
);
7606 expiry
= atoi(expiry_str
);
7611 ast_copy_string(peer
->username
, username
, sizeof(peer
->username
));
7613 ast_copy_string(peer
->fullcontact
, contact
, sizeof(peer
->fullcontact
));
7615 if (option_debug
> 1)
7616 ast_log(LOG_DEBUG
, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
7617 peer
->name
, peer
->username
, ast_inet_ntoa(in
), port
, expiry
);
7619 memset(&peer
->addr
, 0, sizeof(peer
->addr
));
7620 peer
->addr
.sin_family
= AF_INET
;
7621 peer
->addr
.sin_addr
= in
;
7622 peer
->addr
.sin_port
= htons(port
);
7624 /* SIP isn't up yet, so schedule a poke only, pretty soon */
7625 if (peer
->pokeexpire
> -1)
7626 ast_sched_del(sched
, peer
->pokeexpire
);
7627 peer
->pokeexpire
= ast_sched_add(sched
, ast_random() % 5000 + 1, sip_poke_peer_s
, peer
);
7629 sip_poke_peer(peer
);
7630 if (peer
->expire
> -1)
7631 ast_sched_del(sched
, peer
->expire
);
7632 peer
->expire
= ast_sched_add(sched
, (expiry
+ 10) * 1000, expire_register
, peer
);
7633 register_peer_exten(peer
, TRUE
);
7636 /*! \brief Save contact header for 200 OK on INVITE */
7637 static int parse_ok_contact(struct sip_pvt
*pvt
, struct sip_request
*req
)
7642 /* Look for brackets */
7643 ast_copy_string(contact
, get_header(req
, "Contact"), sizeof(contact
));
7644 c
= get_in_brackets(contact
);
7646 /* Save full contact to call pvt for later bye or re-invite */
7647 ast_string_field_set(pvt
, fullcontact
, c
);
7649 /* Save URI for later ACKs, BYE or RE-invites */
7650 ast_string_field_set(pvt
, okcontacturi
, c
);
7652 /* We should return false for URI:s we can't handle,
7653 like sips:, tel:, mailto:,ldap: etc */
7657 /*! \brief Change the other partys IP address based on given contact */
7658 static int set_address_from_contact(struct sip_pvt
*pvt
)
7661 struct ast_hostent ahp
;
7663 char *c
, *host
, *pt
;
7667 if (ast_test_flag(&pvt
->flags
[0], SIP_NAT_ROUTE
)) {
7668 /* NAT: Don't trust the contact field. Just use what they came to us
7670 pvt
->sa
= pvt
->recv
;
7675 /* Work on a copy */
7676 contact
= ast_strdupa(pvt
->fullcontact
);
7678 /* XXX this code is repeated all over */
7679 /* Make sure it's a SIP URL */
7680 if (strncasecmp(contact
, "sip:", 4)) {
7681 ast_log(LOG_NOTICE
, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact
);
7685 /* Ditch arguments */
7686 /* XXX this code is replicated also shortly below */
7687 contact
= strsep(&contact
, ";"); /* trim ; and beyond */
7690 host
= strchr(contact
, '@');
7691 if (!host
) { /* No username part */
7697 pt
= strchr(host
, ':');
7702 port
= STANDARD_SIP_PORT
;
7704 /* XXX This could block for a long time XXX */
7705 /* We should only do this if it's a name, not an IP */
7706 hp
= ast_gethostbyname(host
, &ahp
);
7708 ast_log(LOG_WARNING
, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host
);
7711 pvt
->sa
.sin_family
= AF_INET
;
7712 memcpy(&pvt
->sa
.sin_addr
, hp
->h_addr
, sizeof(pvt
->sa
.sin_addr
));
7713 pvt
->sa
.sin_port
= htons(port
);
7719 /*! \brief Parse contact header and save registration (peer registration) */
7720 static enum parse_register_result
parse_register_contact(struct sip_pvt
*pvt
, struct sip_peer
*peer
, struct sip_request
*req
)
7722 char contact
[BUFSIZ
];
7724 const char *expires
= get_header(req
, "Expires");
7725 int expiry
= atoi(expires
);
7726 char *curi
, *n
, *pt
;
7728 const char *useragent
;
7730 struct ast_hostent ahp
;
7731 struct sockaddr_in oldsin
;
7733 ast_copy_string(contact
, get_header(req
, "Contact"), sizeof(contact
));
7735 if (ast_strlen_zero(expires
)) { /* No expires header */
7736 expires
= strcasestr(contact
, ";expires=");
7738 /* XXX bug here, we overwrite the string */
7739 expires
= strsep((char **) &expires
, ";"); /* trim ; and beyond */
7740 if (sscanf(expires
+ 9, "%d", &expiry
) != 1)
7741 expiry
= default_expiry
;
7743 /* Nothing has been specified */
7744 expiry
= default_expiry
;
7748 /* Look for brackets */
7750 if (strchr(contact
, '<') == NULL
) /* No <, check for ; and strip it */
7751 strsep(&curi
, ";"); /* This is Header options, not URI options */
7752 curi
= get_in_brackets(contact
);
7754 /* if they did not specify Contact: or Expires:, they are querying
7755 what we currently have stored as their contact address, so return
7758 if (ast_strlen_zero(curi
) && ast_strlen_zero(expires
)) {
7759 /* If we have an active registration, tell them when the registration is going to expire */
7760 if (peer
->expire
> -1 && !ast_strlen_zero(peer
->fullcontact
))
7761 pvt
->expiry
= ast_sched_when(sched
, peer
->expire
);
7762 return PARSE_REGISTER_QUERY
;
7763 } else if (!strcasecmp(curi
, "*") || !expiry
) { /* Unregister this peer */
7764 /* This means remove all registrations and return OK */
7765 memset(&peer
->addr
, 0, sizeof(peer
->addr
));
7766 if (peer
->expire
> -1)
7767 ast_sched_del(sched
, peer
->expire
);
7770 destroy_association(peer
);
7772 register_peer_exten(peer
, 0); /* Add extension from regexten= setting in sip.conf */
7773 peer
->fullcontact
[0] = '\0';
7774 peer
->useragent
[0] = '\0';
7775 peer
->sipoptions
= 0;
7778 if (option_verbose
> 2)
7779 ast_verbose(VERBOSE_PREFIX_3
"Unregistered SIP '%s'\n", peer
->name
);
7780 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer
->name
);
7781 return PARSE_REGISTER_UPDATE
;
7784 /* Store whatever we got as a contact from the client */
7785 ast_copy_string(peer
->fullcontact
, curi
, sizeof(peer
->fullcontact
));
7787 /* For the 200 OK, we should use the received contact */
7788 ast_string_field_build(pvt
, our_contact
, "<%s>", curi
);
7790 /* Make sure it's a SIP URL */
7791 if (strncasecmp(curi
, "sip:", 4)) {
7792 ast_log(LOG_NOTICE
, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", curi
);
7796 curi
= strsep(&curi
, ";");
7798 n
= strchr(curi
, '@');
7804 pt
= strchr(n
, ':');
7809 port
= STANDARD_SIP_PORT
;
7810 oldsin
= peer
->addr
;
7811 if (!ast_test_flag(&peer
->flags
[0], SIP_NAT_ROUTE
)) {
7812 /* XXX This could block for a long time XXX */
7813 hp
= ast_gethostbyname(n
, &ahp
);
7815 ast_log(LOG_WARNING
, "Invalid host '%s'\n", n
);
7816 return PARSE_REGISTER_FAILED
;
7818 peer
->addr
.sin_family
= AF_INET
;
7819 memcpy(&peer
->addr
.sin_addr
, hp
->h_addr
, sizeof(peer
->addr
.sin_addr
));
7820 peer
->addr
.sin_port
= htons(port
);
7822 /* Don't trust the contact field. Just use what they came to us
7824 peer
->addr
= pvt
->recv
;
7827 /* Save SIP options profile */
7828 peer
->sipoptions
= pvt
->sipoptions
;
7830 if (curi
) /* Overwrite the default username from config at registration */
7831 ast_copy_string(peer
->username
, curi
, sizeof(peer
->username
));
7833 peer
->username
[0] = '\0';
7835 if (peer
->expire
> -1) {
7836 ast_sched_del(sched
, peer
->expire
);
7839 if (expiry
> max_expiry
)
7840 expiry
= max_expiry
;
7841 if (expiry
< min_expiry
)
7842 expiry
= min_expiry
;
7843 peer
->expire
= ast_test_flag(&peer
->flags
[0], SIP_REALTIME
) ? -1 :
7844 ast_sched_add(sched
, (expiry
+ 10) * 1000, expire_register
, peer
);
7845 pvt
->expiry
= expiry
;
7846 snprintf(data
, sizeof(data
), "%s:%d:%d:%s:%s", ast_inet_ntoa(peer
->addr
.sin_addr
), ntohs(peer
->addr
.sin_port
), expiry
, peer
->username
, peer
->fullcontact
);
7847 if (!ast_test_flag(&peer
->flags
[1], SIP_PAGE2_RT_FROMCONTACT
))
7848 ast_db_put("SIP/Registry", peer
->name
, data
);
7849 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer
->name
);
7851 /* Is this a new IP address for us? */
7852 if (inaddrcmp(&peer
->addr
, &oldsin
)) {
7853 sip_poke_peer(peer
);
7854 if (option_verbose
> 2)
7855 ast_verbose(VERBOSE_PREFIX_3
"Registered SIP '%s' at %s port %d expires %d\n", peer
->name
, ast_inet_ntoa(peer
->addr
.sin_addr
), ntohs(peer
->addr
.sin_port
), expiry
);
7856 register_peer_exten(peer
, 1);
7859 /* Save User agent */
7860 useragent
= get_header(req
, "User-Agent");
7861 if (strcasecmp(useragent
, peer
->useragent
)) { /* XXX copy if they are different ? */
7862 ast_copy_string(peer
->useragent
, useragent
, sizeof(peer
->useragent
));
7863 if (option_verbose
> 3)
7864 ast_verbose(VERBOSE_PREFIX_3
"Saved useragent \"%s\" for peer %s\n", peer
->useragent
, peer
->name
);
7866 return PARSE_REGISTER_UPDATE
;
7869 /*! \brief Remove route from route list */
7870 static void free_old_route(struct sip_route
*route
)
7872 struct sip_route
*next
;
7881 /*! \brief List all routes - mostly for debugging */
7882 static void list_route(struct sip_route
*route
)
7885 ast_verbose("list_route: no route\n");
7887 for (;route
; route
= route
->next
)
7888 ast_verbose("list_route: hop: <%s>\n", route
->hop
);
7892 /*! \brief Build route list from Record-Route header */
7893 static void build_route(struct sip_pvt
*p
, struct sip_request
*req
, int backwards
)
7895 struct sip_route
*thishop
, *head
, *tail
;
7898 const char *rr
, *contact
, *c
;
7900 /* Once a persistant route is set, don't fool with it */
7901 if (p
->route
&& p
->route_persistant
) {
7903 ast_log(LOG_DEBUG
, "build_route: Retaining previous route: <%s>\n", p
->route
->hop
);
7908 free_old_route(p
->route
);
7912 p
->route_persistant
= backwards
;
7914 /* Build a tailq, then assign it to p->route when done.
7915 * If backwards, we add entries from the head so they end up
7916 * in reverse order. However, we do need to maintain a correct
7917 * tail pointer because the contact is always at the end.
7921 /* 1st we pass through all the hops in any Record-Route headers */
7923 /* Each Record-Route header */
7924 rr
= __get_header(req
, "Record-Route", &start
);
7927 for (; (rr
= strchr(rr
, '<')) ; rr
+= len
) { /* Each route entry */
7929 len
= strcspn(rr
, ">") + 1;
7930 /* Make a struct route */
7931 if ((thishop
= ast_malloc(sizeof(*thishop
) + len
))) {
7932 /* ast_calloc is not needed because all fields are initialized in this block */
7933 ast_copy_string(thishop
->hop
, rr
, len
);
7934 if (option_debug
> 1)
7935 ast_log(LOG_DEBUG
, "build_route: Record-Route hop: <%s>\n", thishop
->hop
);
7938 /* Link in at head so they end up in reverse order */
7939 thishop
->next
= head
;
7941 /* If this was the first then it'll be the tail */
7945 thishop
->next
= NULL
;
7946 /* Link in at the end */
7948 tail
->next
= thishop
;
7957 /* Only append the contact if we are dealing with a strict router */
7958 if (!head
|| (!ast_strlen_zero(head
->hop
) && strstr(head
->hop
,";lr") == NULL
) ) {
7959 /* 2nd append the Contact: if there is one */
7960 /* Can be multiple Contact headers, comma separated values - we just take the first */
7961 contact
= get_header(req
, "Contact");
7962 if (!ast_strlen_zero(contact
)) {
7963 if (option_debug
> 1)
7964 ast_log(LOG_DEBUG
, "build_route: Contact hop: %s\n", contact
);
7965 /* Look for <: delimited address */
7966 c
= strchr(contact
, '<');
7970 len
= strcspn(c
, ">") + 1;
7972 /* No <> - just take the lot */
7974 len
= strlen(contact
) + 1;
7976 if ((thishop
= ast_malloc(sizeof(*thishop
) + len
))) {
7977 /* ast_calloc is not needed because all fields are initialized in this block */
7978 ast_copy_string(thishop
->hop
, c
, len
);
7979 thishop
->next
= NULL
;
7980 /* Goes at the end */
7982 tail
->next
= thishop
;
7989 /* Store as new route */
7992 /* For debugging dump what we ended up with */
7993 if (sip_debug_test_pvt(p
))
7994 list_route(p
->route
);
7998 /*! \brief Check user authorization from peer definition
7999 Some actions, like REGISTER and INVITEs from peers require
8000 authentication (if peer have secret set)
8001 \return 0 on success, non-zero on error
8003 static enum check_auth_result
check_auth(struct sip_pvt
*p
, struct sip_request
*req
, const char *username
,
8004 const char *secret
, const char *md5secret
, int sipmethod
,
8005 char *uri
, enum xmittype reliable
, int ignore
)
8007 const char *response
= "407 Proxy Authentication Required";
8008 const char *reqheader
= "Proxy-Authorization";
8009 const char *respheader
= "Proxy-Authenticate";
8010 const char *authtoken
;
8012 char resp_hash
[256]="";
8013 char tmp
[BUFSIZ
* 2]; /* Make a large enough buffer */
8015 int wrongnonce
= FALSE
;
8017 const char *usednonce
= p
->randdata
;
8019 /* table of recognised keywords, and their value in the digest */
8020 enum keys
{ K_RESP
, K_URI
, K_USER
, K_NONCE
, K_LAST
};
8025 [K_RESP
] = { "response=", "" },
8026 [K_URI
] = { "uri=", "" },
8027 [K_USER
] = { "username=", "" },
8028 [K_NONCE
] = { "nonce=", "" },
8029 [K_LAST
] = { NULL
, NULL
}
8032 /* Always OK if no secret */
8033 if (ast_strlen_zero(secret
) && ast_strlen_zero(md5secret
))
8034 return AUTH_SUCCESSFUL
;
8035 if (sipmethod
== SIP_REGISTER
|| sipmethod
== SIP_SUBSCRIBE
) {
8036 /* On a REGISTER, we have to use 401 and its family of headers instead of 407 and its family
8037 of headers -- GO SIP! Whoo hoo! Two things that do the same thing but are used in
8038 different circumstances! What a surprise. */
8039 response
= "401 Unauthorized";
8040 reqheader
= "Authorization";
8041 respheader
= "WWW-Authenticate";
8043 authtoken
= get_header(req
, reqheader
);
8044 if (ignore
&& !ast_strlen_zero(p
->randdata
) && ast_strlen_zero(authtoken
)) {
8045 /* This is a retransmitted invite/register/etc, don't reconstruct authentication
8048 /* Resend message if this was NOT a reliable delivery. Otherwise the
8049 retransmission should get it */
8050 transmit_response_with_auth(p
, response
, req
, p
->randdata
, reliable
, respheader
, 0);
8051 /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
8052 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
8054 return AUTH_CHALLENGE_SENT
;
8055 } else if (ast_strlen_zero(p
->randdata
) || ast_strlen_zero(authtoken
)) {
8056 /* We have no auth, so issue challenge and request authentication */
8057 ast_string_field_build(p
, randdata
, "%08lx", ast_random()); /* Create nonce for challenge */
8058 transmit_response_with_auth(p
, response
, req
, p
->randdata
, reliable
, respheader
, 0);
8059 /* Schedule auto destroy in 32 seconds */
8060 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
8061 return AUTH_CHALLENGE_SENT
;
8064 /* --- We have auth, so check it */
8066 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
8067 an example in the spec of just what it is you're doing a hash on. */
8070 /* Make a copy of the response and parse it */
8071 ast_copy_string(tmp
, authtoken
, sizeof(tmp
));
8074 while(c
&& *(c
= ast_skip_blanks(c
)) ) { /* lookup for keys */
8075 for (i
= keys
; i
->key
!= NULL
; i
++) {
8076 const char *separator
= ","; /* default */
8078 if (strncasecmp(c
, i
->key
, strlen(i
->key
)) != 0)
8080 /* Found. Skip keyword, take text in quotes or up to the separator. */
8081 c
+= strlen(i
->key
);
8082 if (*c
== '"') { /* in quotes. Skip first and look for last */
8087 strsep(&c
, separator
);
8090 if (i
->key
== NULL
) /* not found, jump after space or comma */
8094 /* Verify that digest username matches the username we auth as */
8095 if (strcmp(username
, keys
[K_USER
].s
)) {
8096 ast_log(LOG_WARNING
, "username mismatch, have <%s>, digest has <%s>\n",
8097 username
, keys
[K_USER
].s
);
8098 /* Oops, we're trying something here */
8099 return AUTH_USERNAME_MISMATCH
;
8102 /* Verify nonce from request matches our nonce. If not, send 401 with new nonce */
8103 if (strcasecmp(p
->randdata
, keys
[K_NONCE
].s
)) { /* XXX it was 'n'casecmp ? */
8105 usednonce
= keys
[K_NONCE
].s
;
8108 if (!ast_strlen_zero(md5secret
))
8109 ast_copy_string(a1_hash
, md5secret
, sizeof(a1_hash
));
8112 snprintf(a1
, sizeof(a1
), "%s:%s:%s", username
, global_realm
, secret
);
8113 ast_md5_hash(a1_hash
, a1
);
8116 /* compute the expected response to compare with what we received */
8122 snprintf(a2
, sizeof(a2
), "%s:%s", sip_methods
[sipmethod
].text
,
8123 S_OR(keys
[K_URI
].s
, uri
));
8124 ast_md5_hash(a2_hash
, a2
);
8125 snprintf(resp
, sizeof(resp
), "%s:%s:%s", a1_hash
, usednonce
, a2_hash
);
8126 ast_md5_hash(resp_hash
, resp
);
8129 good_response
= keys
[K_RESP
].s
&&
8130 !strncasecmp(keys
[K_RESP
].s
, resp_hash
, strlen(resp_hash
));
8132 ast_string_field_build(p
, randdata
, "%08lx", ast_random());
8133 if (good_response
) {
8135 ast_log(LOG_NOTICE
, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req
, "To"));
8136 /* We got working auth token, based on stale nonce . */
8137 transmit_response_with_auth(p
, response
, req
, p
->randdata
, reliable
, respheader
, TRUE
);
8139 /* Everything was wrong, so give the device one more try with a new challenge */
8141 ast_log(LOG_NOTICE
, "Bad authentication received from '%s'\n", get_header(req
, "To"));
8142 transmit_response_with_auth(p
, response
, req
, p
->randdata
, reliable
, respheader
, FALSE
);
8145 /* Schedule auto destroy in 32 seconds */
8146 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
8147 return AUTH_CHALLENGE_SENT
;
8149 if (good_response
) {
8150 append_history(p
, "AuthOK", "Auth challenge succesful for %s", username
);
8151 return AUTH_SUCCESSFUL
;
8154 /* Ok, we have a bad username/secret pair */
8155 /* Challenge again, and again, and again */
8156 transmit_response_with_auth(p
, response
, req
, p
->randdata
, reliable
, respheader
, 0);
8157 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
8159 return AUTH_CHALLENGE_SENT
;
8162 /*! \brief Change onhold state of a peer using a pvt structure */
8163 static void sip_peer_hold(struct sip_pvt
*p
, int hold
)
8165 struct sip_peer
*peer
= find_peer(p
->peername
, NULL
, 1);
8170 /* If they put someone on hold, increment the value... otherwise decrement it */
8176 /* Request device state update */
8177 ast_device_state_changed("SIP/%s", peer
->name
);
8182 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
8183 \note If you add an "hint" priority to the extension in the dial plan,
8184 you will get notifications on device state changes */
8185 static int cb_extensionstate(char *context
, char* exten
, int state
, void *data
)
8187 struct sip_pvt
*p
= data
;
8190 case AST_EXTENSION_DEACTIVATED
: /* Retry after a while */
8191 case AST_EXTENSION_REMOVED
: /* Extension is gone */
8192 if (p
->autokillid
> -1)
8193 sip_cancel_destroy(p
); /* Remove subscription expiry for renewals */
8194 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
); /* Delete subscription in 32 secs */
8195 ast_verbose(VERBOSE_PREFIX_2
"Extension state: Watcher for hint %s %s. Notify User %s\n", exten
, state
== AST_EXTENSION_DEACTIVATED
? "deactivated" : "removed", p
->username
);
8197 p
->subscribed
= NONE
;
8198 append_history(p
, "Subscribestatus", "%s", state
== AST_EXTENSION_REMOVED
? "HintRemoved" : "Deactivated");
8200 default: /* Tell user */
8201 p
->laststate
= state
;
8204 if (p
->subscribed
!= NONE
) /* Only send state NOTIFY if we know the format */
8205 transmit_state_notify(p
, state
, 1, FALSE
);
8207 if (option_verbose
> 1)
8208 ast_verbose(VERBOSE_PREFIX_1
"Extension Changed %s new state %s for Notify User %s\n", exten
, ast_extension_state2str(state
), p
->username
);
8212 /*! \brief Send a fake 401 Unauthorized response when the administrator
8213 wants to hide the names of local users/peers from fishers
8215 static void transmit_fake_auth_response(struct sip_pvt
*p
, struct sip_request
*req
, int reliable
)
8217 ast_string_field_build(p
, randdata
, "%08lx", ast_random()); /* Create nonce for challenge */
8218 transmit_response_with_auth(p
, "401 Unauthorized", req
, p
->randdata
, reliable
, "WWW-Authenticate", 0);
8221 /*! \brief Verify registration of user
8222 - Registration is done in several steps, first a REGISTER without auth
8223 to get a challenge (nonce) then a second one with auth
8224 - Registration requests are only matched with peers that are marked as "dynamic"
8226 static enum check_auth_result
register_verify(struct sip_pvt
*p
, struct sockaddr_in
*sin
,
8227 struct sip_request
*req
, char *uri
)
8229 enum check_auth_result res
= AUTH_NOT_FOUND
;
8230 struct sip_peer
*peer
;
8238 while(*t
&& (*t
> 32) && (*t
!= ';'))
8242 ast_copy_string(tmp
, get_header(req
, "To"), sizeof(tmp
));
8243 if (pedanticsipchecking
)
8244 ast_uri_decode(tmp
);
8246 c
= get_in_brackets(tmp
);
8247 c
= strsep(&c
, ";"); /* Ditch ;user=phone */
8249 if (!strncmp(c
, "sip:", 4)) {
8253 ast_log(LOG_NOTICE
, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c
, ast_inet_ntoa(sin
->sin_addr
));
8256 /* Strip off the domain name */
8257 if ((c
= strchr(name
, '@'))) {
8260 if ((c
= strchr(domain
, ':'))) /* Remove :port */
8262 if (!AST_LIST_EMPTY(&domain_list
)) {
8263 if (!check_sip_domain(domain
, NULL
, 0)) {
8264 transmit_response(p
, "404 Not found (unknown domain)", &p
->initreq
);
8265 return AUTH_UNKNOWN_DOMAIN
;
8270 ast_string_field_set(p
, exten
, name
);
8272 peer
= find_peer(name
, NULL
, 1);
8273 if (!(peer
&& ast_apply_ha(peer
->ha
, sin
))) {
8274 /* Peer fails ACL check */
8276 ASTOBJ_UNREF(peer
, sip_destroy_peer
);
8280 /* Set Frame packetization */
8282 ast_rtp_codec_setpref(p
->rtp
, &peer
->prefs
);
8283 p
->autoframing
= peer
->autoframing
;
8285 if (!ast_test_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
)) {
8286 ast_log(LOG_ERROR
, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer
->name
);
8288 ast_copy_flags(&p
->flags
[0], &peer
->flags
[0], SIP_NAT
);
8289 transmit_response(p
, "100 Trying", req
);
8290 if (!(res
= check_auth(p
, req
, peer
->name
, peer
->secret
, peer
->md5secret
, SIP_REGISTER
, uri
, XMIT_UNRELIABLE
, ast_test_flag(req
, SIP_PKT_IGNORE
)))) {
8291 sip_cancel_destroy(p
);
8293 /* We have a succesful registration attemp with proper authentication,
8294 now, update the peer */
8295 switch (parse_register_contact(p
, peer
, req
)) {
8296 case PARSE_REGISTER_FAILED
:
8297 ast_log(LOG_WARNING
, "Failed to parse contact info\n");
8298 transmit_response_with_date(p
, "400 Bad Request", req
);
8299 peer
->lastmsgssent
= -1;
8302 case PARSE_REGISTER_QUERY
:
8303 transmit_response_with_date(p
, "200 OK", req
);
8304 peer
->lastmsgssent
= -1;
8307 case PARSE_REGISTER_UPDATE
:
8308 update_peer(peer
, p
->expiry
);
8309 /* Say OK and ask subsystem to retransmit msg counter */
8310 transmit_response_with_date(p
, "200 OK", req
);
8311 if (!ast_test_flag((&peer
->flags
[1]), SIP_PAGE2_SUBSCRIBEMWIONLY
))
8312 peer
->lastmsgssent
= -1;
8319 if (!peer
&& autocreatepeer
) {
8320 /* Create peer if we have autocreate mode enabled */
8321 peer
= temp_peer(name
);
8323 ASTOBJ_CONTAINER_LINK(&peerl
, peer
);
8324 sip_cancel_destroy(p
);
8325 switch (parse_register_contact(p
, peer
, req
)) {
8326 case PARSE_REGISTER_FAILED
:
8327 ast_log(LOG_WARNING
, "Failed to parse contact info\n");
8328 transmit_response_with_date(p
, "400 Bad Request", req
);
8329 peer
->lastmsgssent
= -1;
8332 case PARSE_REGISTER_QUERY
:
8333 transmit_response_with_date(p
, "200 OK", req
);
8334 peer
->lastmsgssent
= -1;
8337 case PARSE_REGISTER_UPDATE
:
8338 /* Say OK and ask subsystem to retransmit msg counter */
8339 transmit_response_with_date(p
, "200 OK", req
);
8340 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer
->name
);
8341 peer
->lastmsgssent
= -1;
8348 ast_device_state_changed("SIP/%s", peer
->name
);
8352 case AUTH_SECRET_FAILED
:
8353 /* Wrong password in authentication. Go away, don't try again until you fixed it */
8354 transmit_response(p
, "403 Forbidden (Bad auth)", &p
->initreq
);
8356 case AUTH_USERNAME_MISMATCH
:
8357 /* Username and digest username does not match.
8358 Asterisk uses the From: username for authentication. We need the
8359 users to use the same authentication user name until we support
8360 proper authentication by digest auth name */
8361 transmit_response(p
, "403 Authentication user name does not match account name", &p
->initreq
);
8363 case AUTH_NOT_FOUND
:
8364 if (global_alwaysauthreject
) {
8365 transmit_fake_auth_response(p
, &p
->initreq
, 1);
8368 transmit_response(p
, "404 Not found", &p
->initreq
);
8374 if (option_debug
> 1) {
8375 const char *reason
= "";
8378 case AUTH_SECRET_FAILED
:
8379 reason
= "Bad password";
8381 case AUTH_USERNAME_MISMATCH
:
8382 reason
= "Bad digest user";
8384 case AUTH_NOT_FOUND
:
8385 reason
= "Peer not found";
8390 ast_log(LOG_DEBUG
, "SIP REGISTER attempt failed for %s : %s\n",
8391 peer
->name
, reason
);
8395 ASTOBJ_UNREF(peer
, sip_destroy_peer
);
8400 /*! \brief Get referring dnis */
8401 static int get_rdnis(struct sip_pvt
*p
, struct sip_request
*oreq
)
8403 char tmp
[256], *c
, *a
;
8404 struct sip_request
*req
;
8409 ast_copy_string(tmp
, get_header(req
, "Diversion"), sizeof(tmp
));
8410 if (ast_strlen_zero(tmp
))
8412 c
= get_in_brackets(tmp
);
8413 if (strncmp(c
, "sip:", 4)) {
8414 ast_log(LOG_WARNING
, "Huh? Not an RDNIS SIP header (%s)?\n", c
);
8419 strsep(&a
, "@;"); /* trim anything after @ or ; */
8420 if (sip_debug_test_pvt(p
))
8421 ast_verbose("RDNIS is %s\n", c
);
8422 ast_string_field_set(p
, rdnis
, c
);
8427 /*! \brief Find out who the call is for
8428 We use the INVITE uri to find out
8430 static int get_destination(struct sip_pvt
*p
, struct sip_request
*oreq
)
8432 char tmp
[256] = "", *uri
, *a
;
8433 char tmpf
[256] = "", *from
;
8434 struct sip_request
*req
;
8441 /* Find the request URI */
8443 ast_copy_string(tmp
, req
->rlPart2
, sizeof(tmp
));
8445 if (pedanticsipchecking
)
8446 ast_uri_decode(tmp
);
8448 uri
= get_in_brackets(tmp
);
8450 if (strncmp(uri
, "sip:", 4)) {
8451 ast_log(LOG_WARNING
, "Huh? Not a SIP header (%s)?\n", uri
);
8456 /* Now find the From: caller ID and name */
8457 ast_copy_string(tmpf
, get_header(req
, "From"), sizeof(tmpf
));
8458 if (!ast_strlen_zero(tmpf
)) {
8459 if (pedanticsipchecking
)
8460 ast_uri_decode(tmpf
);
8461 from
= get_in_brackets(tmpf
);
8466 if (!ast_strlen_zero(from
)) {
8467 if (strncmp(from
, "sip:", 4)) {
8468 ast_log(LOG_WARNING
, "Huh? Not a SIP header (%s)?\n", from
);
8472 if ((a
= strchr(from
, '@')))
8475 a
= from
; /* just a domain */
8476 from
= strsep(&from
, ";"); /* Remove userinfo options */
8477 a
= strsep(&a
, ";"); /* Remove URI options */
8478 ast_string_field_set(p
, fromdomain
, a
);
8481 /* Skip any options and find the domain */
8483 /* Get the target domain */
8484 if ((a
= strchr(uri
, '@'))) {
8486 } else { /* No username part */
8488 uri
= "s"; /* Set extension to "s" */
8490 colon
= strchr(a
, ':'); /* Remove :port */
8494 uri
= strsep(&uri
, ";"); /* Remove userinfo options */
8495 a
= strsep(&a
, ";"); /* Remove URI options */
8497 ast_string_field_set(p
, domain
, a
);
8499 if (!AST_LIST_EMPTY(&domain_list
)) {
8500 char domain_context
[AST_MAX_EXTENSION
];
8502 domain_context
[0] = '\0';
8503 if (!check_sip_domain(p
->domain
, domain_context
, sizeof(domain_context
))) {
8504 if (!allow_external_domains
&& (req
->method
== SIP_INVITE
|| req
->method
== SIP_REFER
)) {
8506 ast_log(LOG_DEBUG
, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods
[req
->method
].text
, p
->domain
);
8510 /* If we have a context defined, overwrite the original context */
8511 if (!ast_strlen_zero(domain_context
))
8512 ast_string_field_set(p
, context
, domain_context
);
8515 if (sip_debug_test_pvt(p
))
8516 ast_verbose("Looking for %s in %s (domain %s)\n", uri
, p
->context
, p
->domain
);
8518 /* Check the dialplan for the username part of the request URI,
8519 the domain will be stored in the SIPDOMAIN variable
8520 Return 0 if we have a matching extension */
8521 if (ast_exists_extension(NULL
, p
->context
, uri
, 1, from
) ||
8522 !strcmp(uri
, ast_pickup_ext())) {
8524 ast_string_field_set(p
, exten
, uri
);
8528 /* Return 1 for pickup extension or overlap dialling support (if we support it) */
8529 if((ast_test_flag(&global_flags
[1], SIP_PAGE2_ALLOWOVERLAP
) &&
8530 ast_canmatch_extension(NULL
, p
->context
, uri
, 1, from
)) ||
8531 !strncmp(uri
, ast_pickup_ext(), strlen(uri
))) {
8538 /*! \brief Lock interface lock and find matching pvt lock
8539 - Their tag is fromtag, our tag is to-tag
8540 - This means that in some transactions, totag needs to be their tag :-)
8541 depending upon the direction
8543 static struct sip_pvt
*get_sip_pvt_byid_locked(const char *callid
, const char *totag
, const char *fromtag
)
8545 struct sip_pvt
*sip_pvt_ptr
;
8547 ast_mutex_lock(&iflock
);
8549 if (option_debug
> 3 && totag
)
8550 ast_log(LOG_DEBUG
, "Looking for callid %s (fromtag %s totag %s)\n", callid
, fromtag
? fromtag
: "<no fromtag>", totag
? totag
: "<no totag>");
8552 /* Search interfaces and find the match */
8553 for (sip_pvt_ptr
= iflist
; sip_pvt_ptr
; sip_pvt_ptr
= sip_pvt_ptr
->next
) {
8554 if (!strcmp(sip_pvt_ptr
->callid
, callid
)) {
8556 char *ourtag
= sip_pvt_ptr
->tag
;
8558 /* Go ahead and lock it (and its owner) before returning */
8559 ast_mutex_lock(&sip_pvt_ptr
->lock
);
8561 /* Check if tags match. If not, this is not the call we want
8562 (With a forking SIP proxy, several call legs share the
8563 call id, but have different tags)
8565 if (pedanticsipchecking
&& (strcmp(fromtag
, sip_pvt_ptr
->theirtag
) || strcmp(totag
, ourtag
)))
8569 ast_mutex_unlock(&sip_pvt_ptr
->lock
);
8573 if (option_debug
> 3 && totag
)
8574 ast_log(LOG_DEBUG
, "Matched %s call - their tag is %s Our tag is %s\n",
8575 ast_test_flag(&sip_pvt_ptr
->flags
[0], SIP_OUTGOING
) ? "OUTGOING": "INCOMING",
8576 sip_pvt_ptr
->theirtag
, sip_pvt_ptr
->tag
);
8578 /* deadlock avoidance... */
8579 while (sip_pvt_ptr
->owner
&& ast_channel_trylock(sip_pvt_ptr
->owner
)) {
8580 ast_mutex_unlock(&sip_pvt_ptr
->lock
);
8582 ast_mutex_lock(&sip_pvt_ptr
->lock
);
8587 ast_mutex_unlock(&iflock
);
8588 if (option_debug
> 3 && !sip_pvt_ptr
)
8589 ast_log(LOG_DEBUG
, "Found no match for callid %s to-tag %s from-tag %s\n", callid
, totag
, fromtag
);
8593 /*! \brief Call transfer support (the REFER method)
8594 * Extracts Refer headers into pvt dialog structure */
8595 static int get_refer_info(struct sip_pvt
*transferer
, struct sip_request
*outgoing_req
)
8598 const char *p_referred_by
= NULL
;
8599 char *h_refer_to
= NULL
;
8600 char *h_referred_by
= NULL
;
8602 const char *p_refer_to
;
8603 char *referred_by_uri
= NULL
;
8605 struct sip_request
*req
= NULL
;
8606 const char *transfer_context
= NULL
;
8607 struct sip_refer
*referdata
;
8611 referdata
= transferer
->refer
;
8614 req
= &transferer
->initreq
;
8616 p_refer_to
= get_header(req
, "Refer-To");
8617 if (ast_strlen_zero(p_refer_to
)) {
8618 ast_log(LOG_WARNING
, "Refer-To Header missing. Skipping transfer.\n");
8619 return -2; /* Syntax error */
8621 h_refer_to
= ast_strdupa(p_refer_to
);
8622 refer_to
= get_in_brackets(h_refer_to
);
8623 if (pedanticsipchecking
)
8624 ast_uri_decode(refer_to
);
8626 if (strncasecmp(refer_to
, "sip:", 4)) {
8627 ast_log(LOG_WARNING
, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to
);
8630 refer_to
+= 4; /* Skip sip: */
8632 /* Get referred by header if it exists */
8633 p_referred_by
= get_header(req
, "Referred-By");
8634 if (!ast_strlen_zero(p_referred_by
)) {
8636 h_referred_by
= ast_strdupa(p_referred_by
);
8637 if (pedanticsipchecking
)
8638 ast_uri_decode(h_referred_by
);
8640 /* Store referrer's caller ID name */
8641 ast_copy_string(referdata
->referred_by_name
, h_referred_by
, sizeof(referdata
->referred_by_name
));
8642 if ((lessthan
= strchr(referdata
->referred_by_name
, '<'))) {
8643 *(lessthan
- 1) = '\0'; /* Space */
8646 referred_by_uri
= get_in_brackets(h_referred_by
);
8647 if(strncasecmp(referred_by_uri
, "sip:", 4)) {
8648 ast_log(LOG_WARNING
, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri
);
8649 referred_by_uri
= (char *) NULL
;
8651 referred_by_uri
+= 4; /* Skip sip: */
8655 /* Check for arguments in the refer_to header */
8656 if ((ptr
= strchr(refer_to
, '?'))) { /* Search for arguments */
8658 if (!strncasecmp(ptr
, "REPLACES=", 9)) {
8659 char *to
= NULL
, *from
= NULL
;
8661 /* This is an attended transfer */
8662 referdata
->attendedtransfer
= 1;
8663 ast_copy_string(referdata
->replaces_callid
, ptr
+9, sizeof(referdata
->replaces_callid
));
8664 ast_uri_decode(referdata
->replaces_callid
);
8665 if ((ptr
= strchr(referdata
->replaces_callid
, ';'))) /* Find options */ {
8670 /* Find the different tags before we destroy the string */
8671 to
= strcasestr(ptr
, "to-tag=");
8672 from
= strcasestr(ptr
, "from-tag=");
8675 /* Grab the to header */
8678 if ((to
= strchr(ptr
, '&')))
8680 if ((to
= strchr(ptr
, ';')))
8682 ast_copy_string(referdata
->replaces_callid_totag
, ptr
, sizeof(referdata
->replaces_callid_totag
));
8687 if ((to
= strchr(ptr
, '&')))
8689 if ((to
= strchr(ptr
, ';')))
8691 ast_copy_string(referdata
->replaces_callid_fromtag
, ptr
, sizeof(referdata
->replaces_callid_fromtag
));
8694 if (option_debug
> 1) {
8695 if (!pedanticsipchecking
)
8696 ast_log(LOG_DEBUG
,"Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata
->replaces_callid
);
8698 ast_log(LOG_DEBUG
,"Attended transfer: Will use Replace-Call-ID : %s F-tag: %s T-tag: %s\n", referdata
->replaces_callid
, referdata
->replaces_callid_fromtag
? referdata
->replaces_callid_fromtag
: "<none>", referdata
->replaces_callid_totag
? referdata
->replaces_callid_totag
: "<none>" );
8703 if ((ptr
= strchr(refer_to
, '@'))) { /* Separate domain */
8707 if ((urioption
= strchr(ptr
, ';')))
8708 *urioption
++ = '\0';
8709 /* Save the domain for the dial plan */
8710 ast_copy_string(referdata
->refer_to_domain
, ptr
, sizeof(referdata
->refer_to_domain
));
8712 ast_copy_string(referdata
->refer_to_urioption
, urioption
, sizeof(referdata
->refer_to_urioption
));
8715 if ((ptr
= strchr(refer_to
, ';'))) /* Remove options */
8717 ast_copy_string(referdata
->refer_to
, refer_to
, sizeof(referdata
->refer_to
));
8719 if (referred_by_uri
) {
8720 if ((ptr
= strchr(referred_by_uri
, ';'))) /* Remove options */
8722 ast_copy_string(referdata
->referred_by
, referred_by_uri
, sizeof(referdata
->referred_by
));
8724 referdata
->referred_by
[0] = '\0';
8727 /* Determine transfer context */
8728 if (transferer
->owner
) /* Mimic behaviour in res_features.c */
8729 transfer_context
= pbx_builtin_getvar_helper(transferer
->owner
, "TRANSFER_CONTEXT");
8731 /* By default, use the context in the channel sending the REFER */
8732 if (ast_strlen_zero(transfer_context
)) {
8733 transfer_context
= S_OR(transferer
->owner
->macrocontext
,
8734 S_OR(transferer
->context
, default_context
));
8737 ast_copy_string(referdata
->refer_to_context
, transfer_context
, sizeof(referdata
->refer_to_context
));
8739 /* Either an existing extension or the parking extension */
8740 if (ast_exists_extension(NULL
, transfer_context
, refer_to
, 1, NULL
) ) {
8741 if (sip_debug_test_pvt(transferer
)) {
8742 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to
, transfer_context
, referred_by_uri
);
8744 /* We are ready to transfer to the extension */
8747 if (sip_debug_test_pvt(transferer
))
8748 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to
, transfer_context
);
8750 /* Failure, we can't find this extension */
8755 /*! \brief Call transfer support (old way, deprecated by the IETF)--*/
8756 static int get_also_info(struct sip_pvt
*p
, struct sip_request
*oreq
)
8758 char tmp
[256] = "", *c
, *a
;
8759 struct sip_request
*req
= oreq
? oreq
: &p
->initreq
;
8760 struct sip_refer
*referdata
= p
->refer
;
8761 const char *transfer_context
= NULL
;
8763 ast_copy_string(tmp
, get_header(req
, "Also"), sizeof(tmp
));
8764 c
= get_in_brackets(tmp
);
8766 if (pedanticsipchecking
)
8769 if (strncmp(c
, "sip:", 4)) {
8770 ast_log(LOG_WARNING
, "Huh? Not a SIP header in Also: transfer (%s)?\n", c
);
8774 if ((a
= strchr(c
, ';'))) /* Remove arguments */
8777 if ((a
= strchr(c
, '@'))) { /* Separate Domain */
8779 ast_copy_string(referdata
->refer_to_domain
, a
, sizeof(referdata
->refer_to_domain
));
8782 if (sip_debug_test_pvt(p
))
8783 ast_verbose("Looking for %s in %s\n", c
, p
->context
);
8785 if (p
->owner
) /* Mimic behaviour in res_features.c */
8786 transfer_context
= pbx_builtin_getvar_helper(p
->owner
, "TRANSFER_CONTEXT");
8788 /* By default, use the context in the channel sending the REFER */
8789 if (ast_strlen_zero(transfer_context
)) {
8790 transfer_context
= S_OR(p
->owner
->macrocontext
,
8791 S_OR(p
->context
, default_context
));
8793 if (ast_exists_extension(NULL
, transfer_context
, c
, 1, NULL
)) {
8794 /* This is a blind transfer */
8796 ast_log(LOG_DEBUG
,"SIP Bye-also transfer to Extension %s@%s \n", c
, transfer_context
);
8797 ast_copy_string(referdata
->refer_to
, c
, sizeof(referdata
->refer_to
));
8798 ast_copy_string(referdata
->referred_by
, "", sizeof(referdata
->referred_by
));
8799 ast_copy_string(referdata
->refer_contact
, "", sizeof(referdata
->refer_contact
));
8800 referdata
->refer_call
= NULL
;
8801 /* Set new context */
8802 ast_string_field_set(p
, context
, transfer_context
);
8804 } else if (ast_canmatch_extension(NULL
, p
->context
, c
, 1, NULL
)) {
8810 /*! \brief check Via: header for hostname, port and rport request/answer */
8811 static void check_via(struct sip_pvt
*p
, struct sip_request
*req
)
8816 struct ast_hostent ahp
;
8818 ast_copy_string(via
, get_header(req
, "Via"), sizeof(via
));
8820 /* Work on the leftmost value of the topmost Via header */
8821 c
= strchr(via
, ',');
8825 /* Check for rport */
8826 c
= strstr(via
, ";rport");
8827 if (c
&& (c
[6] != '=')) /* rport query, not answer */
8828 ast_set_flag(&p
->flags
[0], SIP_NAT_ROUTE
);
8830 c
= strchr(via
, ';');
8834 c
= strchr(via
, ' ');
8837 c
= ast_skip_blanks(c
+1);
8838 if (strcasecmp(via
, "SIP/2.0/UDP")) {
8839 ast_log(LOG_WARNING
, "Don't know how to respond via '%s'\n", via
);
8842 pt
= strchr(c
, ':');
8844 *pt
++ = '\0'; /* remember port pointer */
8845 hp
= ast_gethostbyname(c
, &ahp
);
8847 ast_log(LOG_WARNING
, "'%s' is not a valid host\n", c
);
8850 memset(&p
->sa
, 0, sizeof(p
->sa
));
8851 p
->sa
.sin_family
= AF_INET
;
8852 memcpy(&p
->sa
.sin_addr
, hp
->h_addr
, sizeof(p
->sa
.sin_addr
));
8853 p
->sa
.sin_port
= htons(pt
? atoi(pt
) : STANDARD_SIP_PORT
);
8855 if (sip_debug_test_pvt(p
)) {
8856 const struct sockaddr_in
*dst
= sip_real_dst(p
);
8857 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst
->sin_addr
), ntohs(dst
->sin_port
), sip_nat_mode(p
));
8862 /*! \brief Get caller id name from SIP headers */
8863 static char *get_calleridname(const char *input
, char *output
, size_t outputsize
)
8865 const char *end
= strchr(input
,'<'); /* first_bracket */
8866 const char *tmp
= strchr(input
,'"'); /* first quote */
8868 int maxbytes
= outputsize
- 1;
8870 if (!end
|| end
== input
) /* we require a part in brackets */
8873 end
--; /* move just before "<" */
8875 if (tmp
&& tmp
<= end
) {
8876 /* The quote (tmp) precedes the bracket (end+1).
8877 * Find the matching quote and return the content.
8879 end
= strchr(tmp
+1, '"');
8882 bytes
= (int) (end
- tmp
);
8883 /* protect the output buffer */
8884 if (bytes
> maxbytes
)
8886 ast_copy_string(output
, tmp
+ 1, bytes
);
8888 /* No quoted string, or it is inside brackets. */
8889 /* clear the empty characters in the begining*/
8890 input
= ast_skip_blanks(input
);
8891 /* clear the empty characters in the end */
8892 while(*end
&& *end
< 33 && end
> input
)
8895 bytes
= (int) (end
- input
) + 2;
8896 /* protect the output buffer */
8897 if (bytes
> maxbytes
)
8899 ast_copy_string(output
, input
, bytes
);
8906 /*! \brief Get caller id number from Remote-Party-ID header field
8907 * Returns true if number should be restricted (privacy setting found)
8908 * output is set to NULL if no number found
8910 static int get_rpid_num(const char *input
, char *output
, int maxlen
)
8915 start
= strchr(input
,':');
8922 /* we found "number" */
8923 ast_copy_string(output
,start
,maxlen
);
8924 output
[maxlen
-1] = '\0';
8926 end
= strchr(output
,'@');
8931 if (strstr(input
,"privacy=full") || strstr(input
,"privacy=uri"))
8932 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED
;
8938 /*! \brief Check if matching user or peer is defined
8939 Match user on From: user name and peer on IP/port
8940 This is used on first invite (not re-invites) and subscribe requests
8941 \return 0 on success, non-zero on failure
8943 static enum check_auth_result
check_user_full(struct sip_pvt
*p
, struct sip_request
*req
,
8944 int sipmethod
, char *uri
, enum xmittype reliable
,
8945 struct sockaddr_in
*sin
, struct sip_peer
**authpeer
)
8947 struct sip_user
*user
= NULL
;
8948 struct sip_peer
*peer
;
8953 enum check_auth_result res
= AUTH_SUCCESSFUL
;
8955 char calleridname
[50];
8956 int debug
=sip_debug_test_addr(sin
);
8957 struct ast_variable
*tmpvar
= NULL
, *v
= NULL
;
8958 char *uri2
= ast_strdupa(uri
);
8962 while (*t
&& *t
> 32 && *t
!= ';')
8965 ast_copy_string(from
, get_header(req
, "From"), sizeof(from
)); /* XXX bug in original code, overwrote string */
8966 if (pedanticsipchecking
)
8967 ast_uri_decode(from
);
8968 /* XXX here tries to map the username for invite things */
8969 memset(calleridname
, 0, sizeof(calleridname
));
8970 get_calleridname(from
, calleridname
, sizeof(calleridname
));
8971 if (calleridname
[0])
8972 ast_string_field_set(p
, cid_name
, calleridname
);
8974 rpid
= get_header(req
, "Remote-Party-ID");
8975 memset(rpid_num
, 0, sizeof(rpid_num
));
8976 if (!ast_strlen_zero(rpid
))
8977 p
->callingpres
= get_rpid_num(rpid
, rpid_num
, sizeof(rpid_num
));
8979 of
= get_in_brackets(from
);
8980 if (ast_strlen_zero(p
->exten
)) {
8982 if (!strncmp(t
, "sip:", 4))
8984 ast_string_field_set(p
, exten
, t
);
8985 t
= strchr(p
->exten
, '@');
8988 if (ast_strlen_zero(p
->our_contact
))
8991 /* save the URI part of the From header */
8992 ast_string_field_set(p
, from
, of
);
8993 if (strncmp(of
, "sip:", 4)) {
8994 ast_log(LOG_NOTICE
, "From address missing 'sip:', using it anyway\n");
8997 /* Get just the username part */
8998 if ((c
= strchr(of
, '@'))) {
9001 if ((c
= strchr(of
, ':')))
9003 tmp
= ast_strdupa(of
);
9004 if (ast_is_shrinkable_phonenumber(tmp
))
9005 ast_shrink_phone_number(tmp
);
9006 ast_string_field_set(p
, cid_num
, tmp
);
9008 if (ast_strlen_zero(of
))
9009 return AUTH_SUCCESSFUL
;
9011 if (!authpeer
) /* If we are looking for a peer, don't check the user objects (or realtime) */
9012 user
= find_user(of
, 1);
9014 /* Find user based on user name in the from header */
9015 if (user
&& ast_apply_ha(user
->ha
, sin
)) {
9016 ast_copy_flags(&p
->flags
[0], &user
->flags
[0], SIP_FLAGS_TO_COPY
);
9017 ast_copy_flags(&p
->flags
[1], &user
->flags
[1], SIP_PAGE2_FLAGS_TO_COPY
);
9018 /* copy channel vars */
9019 for (v
= user
->chanvars
; v
; v
= v
->next
) {
9020 if ((tmpvar
= ast_variable_new(v
->name
, v
->value
))) {
9021 tmpvar
->next
= p
->chanvars
;
9022 p
->chanvars
= tmpvar
;
9025 p
->prefs
= user
->prefs
;
9026 /* Set Frame packetization */
9028 ast_rtp_codec_setpref(p
->rtp
, &p
->prefs
);
9029 p
->autoframing
= user
->autoframing
;
9031 /* replace callerid if rpid found, and not restricted */
9032 if (!ast_strlen_zero(rpid_num
) && ast_test_flag(&p
->flags
[0], SIP_TRUSTRPID
)) {
9035 ast_string_field_set(p
, cid_name
, calleridname
);
9036 tmp
= ast_strdupa(rpid_num
);
9037 if (ast_is_shrinkable_phonenumber(tmp
))
9038 ast_shrink_phone_number(tmp
);
9039 ast_string_field_set(p
, cid_num
, tmp
);
9042 do_setnat(p
, ast_test_flag(&p
->flags
[0], SIP_NAT_ROUTE
) );
9044 if (!(res
= check_auth(p
, req
, user
->name
, user
->secret
, user
->md5secret
, sipmethod
, uri2
, reliable
, ast_test_flag(req
, SIP_PKT_IGNORE
)))) {
9045 sip_cancel_destroy(p
);
9046 ast_copy_flags(&p
->flags
[0], &user
->flags
[0], SIP_FLAGS_TO_COPY
);
9047 ast_copy_flags(&p
->flags
[1], &user
->flags
[1], SIP_PAGE2_FLAGS_TO_COPY
);
9048 /* Copy SIP extensions profile from INVITE */
9050 user
->sipoptions
= p
->sipoptions
;
9052 /* If we have a call limit, set flag */
9053 if (user
->call_limit
)
9054 ast_set_flag(&p
->flags
[0], SIP_CALL_LIMIT
);
9055 if (!ast_strlen_zero(user
->context
))
9056 ast_string_field_set(p
, context
, user
->context
);
9057 if (!ast_strlen_zero(user
->cid_num
) && !ast_strlen_zero(p
->cid_num
)) {
9058 char *tmp
= ast_strdupa(user
->cid_num
);
9059 if (ast_is_shrinkable_phonenumber(tmp
))
9060 ast_shrink_phone_number(tmp
);
9061 ast_string_field_set(p
, cid_num
, tmp
);
9063 if (!ast_strlen_zero(user
->cid_name
) && !ast_strlen_zero(p
->cid_num
))
9064 ast_string_field_set(p
, cid_name
, user
->cid_name
);
9065 ast_string_field_set(p
, username
, user
->name
);
9066 ast_string_field_set(p
, peername
, user
->name
);
9067 ast_string_field_set(p
, peersecret
, user
->secret
);
9068 ast_string_field_set(p
, peermd5secret
, user
->md5secret
);
9069 ast_string_field_set(p
, subscribecontext
, user
->subscribecontext
);
9070 ast_string_field_set(p
, accountcode
, user
->accountcode
);
9071 ast_string_field_set(p
, language
, user
->language
);
9072 ast_string_field_set(p
, mohsuggest
, user
->mohsuggest
);
9073 ast_string_field_set(p
, mohinterpret
, user
->mohinterpret
);
9074 p
->allowtransfer
= user
->allowtransfer
;
9075 p
->amaflags
= user
->amaflags
;
9076 p
->callgroup
= user
->callgroup
;
9077 p
->pickupgroup
= user
->pickupgroup
;
9078 if (user
->callingpres
) /* User callingpres setting will override RPID header */
9079 p
->callingpres
= user
->callingpres
;
9081 /* Set default codec settings for this call */
9082 p
->capability
= user
->capability
; /* User codec choice */
9083 p
->jointcapability
= user
->capability
; /* Our codecs */
9084 if (p
->peercapability
) /* AND with peer's codecs */
9085 p
->jointcapability
&= p
->peercapability
;
9086 if ((ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_RFC2833
) ||
9087 (ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_AUTO
))
9088 p
->noncodeccapability
|= AST_RTP_DTMF
;
9090 p
->noncodeccapability
&= ~AST_RTP_DTMF
;
9091 if (p
->t38
.peercapability
)
9092 p
->t38
.jointcapability
&= p
->t38
.peercapability
;
9093 p
->maxcallbitrate
= user
->maxcallbitrate
;
9094 /* If we do not support video, remove video from call structure */
9095 if ((!ast_test_flag(&p
->flags
[1], SIP_PAGE2_VIDEOSUPPORT
) || !(p
->capability
& AST_FORMAT_VIDEO_MASK
)) && p
->vrtp
) {
9096 ast_rtp_destroy(p
->vrtp
);
9101 ast_verbose("Found user '%s'\n", user
->name
);
9104 if (!authpeer
&& debug
)
9105 ast_verbose("Found user '%s', but fails host access\n", user
->name
);
9106 ASTOBJ_UNREF(user
,sip_destroy_user
);
9112 /* If we didn't find a user match, check for peers */
9113 if (sipmethod
== SIP_SUBSCRIBE
)
9114 /* For subscribes, match on peer name only */
9115 peer
= find_peer(of
, NULL
, 1);
9117 /* Look for peer based on the IP address we received data from */
9118 /* If peer is registered from this IP address or have this as a default
9119 IP address, this call is from the peer
9121 peer
= find_peer(NULL
, &p
->recv
, 1);
9124 /* Set Frame packetization */
9126 ast_rtp_codec_setpref(p
->rtp
, &peer
->prefs
);
9127 p
->autoframing
= peer
->autoframing
;
9130 ast_verbose("Found peer '%s'\n", peer
->name
);
9133 ast_copy_flags(&p
->flags
[0], &peer
->flags
[0], SIP_FLAGS_TO_COPY
);
9134 ast_copy_flags(&p
->flags
[1], &peer
->flags
[1], SIP_PAGE2_FLAGS_TO_COPY
);
9136 /* Copy SIP extensions profile to peer */
9138 peer
->sipoptions
= p
->sipoptions
;
9140 /* replace callerid if rpid found, and not restricted */
9141 if (!ast_strlen_zero(rpid_num
) && ast_test_flag(&p
->flags
[0], SIP_TRUSTRPID
)) {
9142 char *tmp
= ast_strdupa(rpid_num
);
9144 ast_string_field_set(p
, cid_name
, calleridname
);
9145 if (ast_is_shrinkable_phonenumber(tmp
))
9146 ast_shrink_phone_number(tmp
);
9147 ast_string_field_set(p
, cid_num
, tmp
);
9149 do_setnat(p
, ast_test_flag(&p
->flags
[0], SIP_NAT_ROUTE
));
9151 ast_string_field_set(p
, peersecret
, peer
->secret
);
9152 ast_string_field_set(p
, peermd5secret
, peer
->md5secret
);
9153 ast_string_field_set(p
, subscribecontext
, peer
->subscribecontext
);
9154 ast_string_field_set(p
, mohinterpret
, peer
->mohinterpret
);
9155 ast_string_field_set(p
, mohsuggest
, peer
->mohsuggest
);
9156 if (peer
->callingpres
) /* Peer calling pres setting will override RPID */
9157 p
->callingpres
= peer
->callingpres
;
9158 if (peer
->maxms
&& peer
->lastms
)
9159 p
->timer_t1
= peer
->lastms
;
9160 if (ast_test_flag(&peer
->flags
[0], SIP_INSECURE_INVITE
)) {
9161 /* Pretend there is no required authentication */
9162 ast_string_field_free(p
, peersecret
);
9163 ast_string_field_free(p
, peermd5secret
);
9165 if (!(res
= check_auth(p
, req
, peer
->name
, p
->peersecret
, p
->peermd5secret
, sipmethod
, uri2
, reliable
, ast_test_flag(req
, SIP_PKT_IGNORE
)))) {
9166 ast_copy_flags(&p
->flags
[0], &peer
->flags
[0], SIP_FLAGS_TO_COPY
);
9167 ast_copy_flags(&p
->flags
[1], &peer
->flags
[1], SIP_PAGE2_FLAGS_TO_COPY
);
9168 /* If we have a call limit, set flag */
9169 if (peer
->call_limit
)
9170 ast_set_flag(&p
->flags
[0], SIP_CALL_LIMIT
);
9171 ast_string_field_set(p
, peername
, peer
->name
);
9172 ast_string_field_set(p
, authname
, peer
->name
);
9174 /* copy channel vars */
9175 for (v
= peer
->chanvars
; v
; v
= v
->next
) {
9176 if ((tmpvar
= ast_variable_new(v
->name
, v
->value
))) {
9177 tmpvar
->next
= p
->chanvars
;
9178 p
->chanvars
= tmpvar
;
9182 (*authpeer
) = ASTOBJ_REF(peer
); /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
9185 if (!ast_strlen_zero(peer
->username
)) {
9186 ast_string_field_set(p
, username
, peer
->username
);
9187 /* Use the default username for authentication on outbound calls */
9188 /* XXX this takes the name from the caller... can we override ? */
9189 ast_string_field_set(p
, authname
, peer
->username
);
9191 if (!ast_strlen_zero(peer
->cid_num
) && !ast_strlen_zero(p
->cid_num
)) {
9192 char *tmp
= ast_strdupa(peer
->cid_num
);
9193 if (ast_is_shrinkable_phonenumber(tmp
))
9194 ast_shrink_phone_number(tmp
);
9195 ast_string_field_set(p
, cid_num
, tmp
);
9197 if (!ast_strlen_zero(peer
->cid_name
) && !ast_strlen_zero(p
->cid_name
))
9198 ast_string_field_set(p
, cid_name
, peer
->cid_name
);
9199 ast_string_field_set(p
, fullcontact
, peer
->fullcontact
);
9200 if (!ast_strlen_zero(peer
->context
))
9201 ast_string_field_set(p
, context
, peer
->context
);
9202 ast_string_field_set(p
, peersecret
, peer
->secret
);
9203 ast_string_field_set(p
, peermd5secret
, peer
->md5secret
);
9204 ast_string_field_set(p
, language
, peer
->language
);
9205 ast_string_field_set(p
, accountcode
, peer
->accountcode
);
9206 p
->amaflags
= peer
->amaflags
;
9207 p
->callgroup
= peer
->callgroup
;
9208 p
->pickupgroup
= peer
->pickupgroup
;
9209 p
->capability
= peer
->capability
;
9210 p
->prefs
= peer
->prefs
;
9211 p
->jointcapability
= peer
->capability
;
9212 if (p
->peercapability
)
9213 p
->jointcapability
&= p
->peercapability
;
9214 p
->maxcallbitrate
= peer
->maxcallbitrate
;
9215 if ((!ast_test_flag(&p
->flags
[1], SIP_PAGE2_VIDEOSUPPORT
) || !(p
->capability
& AST_FORMAT_VIDEO_MASK
)) && p
->vrtp
) {
9216 ast_rtp_destroy(p
->vrtp
);
9219 if ((ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_RFC2833
) ||
9220 (ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_AUTO
))
9221 p
->noncodeccapability
|= AST_RTP_DTMF
;
9223 p
->noncodeccapability
&= ~AST_RTP_DTMF
;
9224 if (p
->t38
.peercapability
)
9225 p
->t38
.jointcapability
&= p
->t38
.peercapability
;
9227 ASTOBJ_UNREF(peer
, sip_destroy_peer
);
9230 ast_verbose("Found no matching peer or user for '%s:%d'\n", ast_inet_ntoa(p
->recv
.sin_addr
), ntohs(p
->recv
.sin_port
));
9232 /* do we allow guests? */
9233 if (!global_allowguest
) {
9234 if (global_alwaysauthreject
)
9235 res
= AUTH_FAKE_AUTH
; /* reject with fake authorization request */
9237 res
= AUTH_SECRET_FAILED
; /* we don't want any guests, authentication will fail */
9244 ASTOBJ_UNREF(user
, sip_destroy_user
);
9248 /*! \brief Find user
9249 If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
9251 static int check_user(struct sip_pvt
*p
, struct sip_request
*req
, int sipmethod
, char *uri
, enum xmittype reliable
, struct sockaddr_in
*sin
)
9253 return check_user_full(p
, req
, sipmethod
, uri
, reliable
, sin
, NULL
);
9256 /*! \brief Get text out of a SIP MESSAGE packet */
9257 static int get_msg_text(char *buf
, int len
, struct sip_request
*req
)
9263 y
= len
- strlen(buf
) - 5;
9266 for (x
=0;x
<req
->lines
;x
++) {
9267 strncat(buf
, req
->line
[x
], y
); /* safe */
9268 y
-= strlen(req
->line
[x
]) + 1;
9272 strcat(buf
, "\n"); /* safe */
9278 /*! \brief Receive SIP MESSAGE method messages
9279 \note We only handle messages within current calls currently
9280 Reference: RFC 3428 */
9281 static void receive_message(struct sip_pvt
*p
, struct sip_request
*req
)
9285 const char *content_type
= get_header(req
, "Content-Type");
9287 if (strcmp(content_type
, "text/plain")) { /* No text/plain attachment */
9288 transmit_response(p
, "415 Unsupported Media Type", req
); /* Good enough, or? */
9289 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
9293 if (get_msg_text(buf
, sizeof(buf
), req
)) {
9294 ast_log(LOG_WARNING
, "Unable to retrieve text from %s\n", p
->callid
);
9295 transmit_response(p
, "202 Accepted", req
);
9296 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
9301 if (sip_debug_test_pvt(p
))
9302 ast_verbose("Message received: '%s'\n", buf
);
9303 memset(&f
, 0, sizeof(f
));
9304 f
.frametype
= AST_FRAME_TEXT
;
9308 f
.datalen
= strlen(buf
);
9309 ast_queue_frame(p
->owner
, &f
);
9310 transmit_response(p
, "202 Accepted", req
); /* We respond 202 accepted, since we relay the message */
9311 } else { /* Message outside of a call, we do not support that */
9312 ast_log(LOG_WARNING
,"Received message to %s from %s, dropped it...\n Content-Type:%s\n Message: %s\n", get_header(req
,"To"), get_header(req
,"From"), content_type
, buf
);
9313 transmit_response(p
, "405 Method Not Allowed", req
); /* Good enough, or? */
9315 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
9319 /*! \brief CLI Command to show calls within limits set by call_limit */
9320 static int sip_show_inuse(int fd
, int argc
, char *argv
[])
9322 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
9323 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
9326 int showall
= FALSE
;
9329 return RESULT_SHOWUSAGE
;
9331 if (argc
== 4 && !strcmp(argv
[3],"all"))
9334 ast_cli(fd
, FORMAT
, "* User name", "In use", "Limit");
9335 ASTOBJ_CONTAINER_TRAVERSE(&userl
, 1, do {
9336 ASTOBJ_RDLOCK(iterator
);
9337 if (iterator
->call_limit
)
9338 snprintf(ilimits
, sizeof(ilimits
), "%d", iterator
->call_limit
);
9340 ast_copy_string(ilimits
, "N/A", sizeof(ilimits
));
9341 snprintf(iused
, sizeof(iused
), "%d", iterator
->inUse
);
9342 if (showall
|| iterator
->call_limit
)
9343 ast_cli(fd
, FORMAT2
, iterator
->name
, iused
, ilimits
);
9344 ASTOBJ_UNLOCK(iterator
);
9347 ast_cli(fd
, FORMAT
, "* Peer name", "In use", "Limit");
9349 ASTOBJ_CONTAINER_TRAVERSE(&peerl
, 1, do {
9350 ASTOBJ_RDLOCK(iterator
);
9351 if (iterator
->call_limit
)
9352 snprintf(ilimits
, sizeof(ilimits
), "%d", iterator
->call_limit
);
9354 ast_copy_string(ilimits
, "N/A", sizeof(ilimits
));
9355 snprintf(iused
, sizeof(iused
), "%d/%d", iterator
->inUse
, iterator
->inRinging
);
9356 if (showall
|| iterator
->call_limit
)
9357 ast_cli(fd
, FORMAT2
, iterator
->name
, iused
, ilimits
);
9358 ASTOBJ_UNLOCK(iterator
);
9361 return RESULT_SUCCESS
;
9366 /*! \brief Convert transfer mode to text string */
9367 static char *transfermode2str(enum transfermodes mode
)
9369 if (mode
== TRANSFER_OPENFORALL
)
9371 else if (mode
== TRANSFER_CLOSED
)
9376 /*! \brief Convert NAT setting to text string */
9377 static char *nat2str(int nat
)
9384 case SIP_NAT_ALWAYS
:
9386 case SIP_NAT_RFC3581
:
9393 /*! \brief Report Peer status in character string
9394 * \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
9396 static int peer_status(struct sip_peer
*peer
, char *status
, int statuslen
)
9400 if (peer
->lastms
< 0) {
9401 ast_copy_string(status
, "UNREACHABLE", statuslen
);
9402 } else if (peer
->lastms
> peer
->maxms
) {
9403 snprintf(status
, statuslen
, "LAGGED (%d ms)", peer
->lastms
);
9405 } else if (peer
->lastms
) {
9406 snprintf(status
, statuslen
, "OK (%d ms)", peer
->lastms
);
9409 ast_copy_string(status
, "UNKNOWN", statuslen
);
9412 ast_copy_string(status
, "Unmonitored", statuslen
);
9413 /* Checking if port is 0 */
9419 /*! \brief CLI Command 'SIP Show Users' */
9420 static int sip_show_users(int fd
, int argc
, char *argv
[])
9423 int havepattern
= FALSE
;
9425 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
9429 if (!strcasecmp(argv
[3], "like")) {
9430 if (regcomp(®exbuf
, argv
[4], REG_EXTENDED
| REG_NOSUB
))
9431 return RESULT_SHOWUSAGE
;
9434 return RESULT_SHOWUSAGE
;
9438 return RESULT_SHOWUSAGE
;
9441 ast_cli(fd
, FORMAT
, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
9442 ASTOBJ_CONTAINER_TRAVERSE(&userl
, 1, do {
9443 ASTOBJ_RDLOCK(iterator
);
9445 if (havepattern
&& regexec(®exbuf
, iterator
->name
, 0, NULL
, 0)) {
9446 ASTOBJ_UNLOCK(iterator
);
9450 ast_cli(fd
, FORMAT
, iterator
->name
,
9452 iterator
->accountcode
,
9454 iterator
->ha
? "Yes" : "No",
9455 nat2str(ast_test_flag(&iterator
->flags
[0], SIP_NAT
)));
9456 ASTOBJ_UNLOCK(iterator
);
9463 return RESULT_SUCCESS
;
9467 static char mandescr_show_peers
[] =
9468 "Description: Lists SIP peers in text format with details on current status.\n"
9470 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
9472 /*! \brief Show SIP peers in the manager API */
9473 /* Inspired from chan_iax2 */
9474 static int manager_sip_show_peers(struct mansession
*s
, const struct message
*m
)
9476 const char *id
= astman_get_header(m
,"ActionID");
9477 const char *a
[] = {"sip", "show", "peers"};
9478 char idtext
[256] = "";
9481 if (!ast_strlen_zero(id
))
9482 snprintf(idtext
, sizeof(idtext
), "ActionID: %s\r\n", id
);
9484 astman_send_ack(s
, m
, "Peer status list will follow");
9485 /* List the peers in separate manager events */
9486 _sip_show_peers(-1, &total
, s
, m
, 3, a
);
9487 /* Send final confirmation */
9489 "Event: PeerlistComplete\r\n"
9492 "\r\n", total
, idtext
);
9496 /*! \brief CLI Show Peers command */
9497 static int sip_show_peers(int fd
, int argc
, char *argv
[])
9499 return _sip_show_peers(fd
, NULL
, NULL
, NULL
, argc
, (const char **) argv
);
9502 /*! \brief _sip_show_peers: Execute sip show peers command */
9503 static int _sip_show_peers(int fd
, int *total
, struct mansession
*s
, const struct message
*m
, int argc
, const char *argv
[])
9506 int havepattern
= FALSE
;
9508 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %-10s\n"
9509 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %-10s\n"
9512 int total_peers
= 0;
9513 int peers_mon_online
= 0;
9514 int peers_mon_offline
= 0;
9515 int peers_unmon_offline
= 0;
9516 int peers_unmon_online
= 0;
9518 char idtext
[256] = "";
9521 realtimepeers
= ast_check_realtime("sippeers");
9523 if (s
) { /* Manager - get ActionID */
9524 id
= astman_get_header(m
,"ActionID");
9525 if (!ast_strlen_zero(id
))
9526 snprintf(idtext
, sizeof(idtext
), "ActionID: %s\r\n", id
);
9531 if (!strcasecmp(argv
[3], "like")) {
9532 if (regcomp(®exbuf
, argv
[4], REG_EXTENDED
| REG_NOSUB
))
9533 return RESULT_SHOWUSAGE
;
9536 return RESULT_SHOWUSAGE
;
9540 return RESULT_SHOWUSAGE
;
9543 if (!s
) /* Normal list */
9544 ast_cli(fd
, FORMAT2
, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers
? "Realtime" : ""));
9546 ASTOBJ_CONTAINER_TRAVERSE(&peerl
, 1, do {
9547 char status
[20] = "";
9551 ASTOBJ_RDLOCK(iterator
);
9553 if (havepattern
&& regexec(®exbuf
, iterator
->name
, 0, NULL
, 0)) {
9554 ASTOBJ_UNLOCK(iterator
);
9558 if (!ast_strlen_zero(iterator
->username
) && !s
)
9559 snprintf(name
, sizeof(name
), "%s/%s", iterator
->name
, iterator
->username
);
9561 ast_copy_string(name
, iterator
->name
, sizeof(name
));
9563 pstatus
= peer_status(iterator
, status
, sizeof(status
));
9566 else if (pstatus
== 0)
9567 peers_mon_offline
++;
9569 if (iterator
->addr
.sin_port
== 0)
9570 peers_unmon_offline
++;
9572 peers_unmon_online
++;
9575 snprintf(srch
, sizeof(srch
), FORMAT
, name
,
9576 iterator
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(iterator
->addr
.sin_addr
) : "(Unspecified)",
9577 ast_test_flag(&iterator
->flags
[1], SIP_PAGE2_DYNAMIC
) ? " D " : " ", /* Dynamic or not? */
9578 ast_test_flag(&iterator
->flags
[0], SIP_NAT_ROUTE
) ? " N " : " ", /* NAT=yes? */
9579 iterator
->ha
? " A " : " ", /* permit/deny */
9580 ntohs(iterator
->addr
.sin_port
), status
,
9581 realtimepeers
? (ast_test_flag(&iterator
->flags
[0], SIP_REALTIME
) ? "Cached RT":"") : "");
9583 if (!s
) {/* Normal CLI list */
9584 ast_cli(fd
, FORMAT
, name
,
9585 iterator
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(iterator
->addr
.sin_addr
) : "(Unspecified)",
9586 ast_test_flag(&iterator
->flags
[1], SIP_PAGE2_DYNAMIC
) ? " D " : " ", /* Dynamic or not? */
9587 ast_test_flag(&iterator
->flags
[0], SIP_NAT_ROUTE
) ? " N " : " ", /* NAT=yes? */
9588 iterator
->ha
? " A " : " ", /* permit/deny */
9590 ntohs(iterator
->addr
.sin_port
), status
,
9591 realtimepeers
? (ast_test_flag(&iterator
->flags
[0], SIP_REALTIME
) ? "Cached RT":"") : "");
9592 } else { /* Manager format */
9593 /* The names here need to be the same as other channels */
9595 "Event: PeerEntry\r\n%s"
9596 "Channeltype: SIP\r\n"
9597 "ObjectName: %s\r\n"
9598 "ChanObjectType: peer\r\n" /* "peer" or "user" */
9602 "Natsupport: %s\r\n"
9603 "VideoSupport: %s\r\n"
9606 "RealtimeDevice: %s\r\n\r\n",
9609 iterator
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(iterator
->addr
.sin_addr
) : "-none-",
9610 ntohs(iterator
->addr
.sin_port
),
9611 ast_test_flag(&iterator
->flags
[1], SIP_PAGE2_DYNAMIC
) ? "yes" : "no", /* Dynamic or not? */
9612 ast_test_flag(&iterator
->flags
[0], SIP_NAT_ROUTE
) ? "yes" : "no", /* NAT=yes? */
9613 ast_test_flag(&iterator
->flags
[1], SIP_PAGE2_VIDEOSUPPORT
) ? "yes" : "no", /* VIDEOSUPPORT=yes? */
9614 iterator
->ha
? "yes" : "no", /* permit/deny */
9616 realtimepeers
? (ast_test_flag(&iterator
->flags
[0], SIP_REALTIME
) ? "yes":"no") : "no");
9619 ASTOBJ_UNLOCK(iterator
);
9625 ast_cli(fd
, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
9626 total_peers
, peers_mon_online
, peers_mon_offline
, peers_unmon_online
, peers_unmon_offline
);
9632 *total
= total_peers
;
9635 return RESULT_SUCCESS
;
9640 /*! \brief List all allocated SIP Objects (realtime or static) */
9641 static int sip_show_objects(int fd
, int argc
, char *argv
[])
9645 return RESULT_SHOWUSAGE
;
9646 ast_cli(fd
, "-= User objects: %d static, %d realtime =-\n\n", suserobjs
, ruserobjs
);
9647 ASTOBJ_CONTAINER_DUMP(fd
, tmp
, sizeof(tmp
), &userl
);
9648 ast_cli(fd
, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs
, rpeerobjs
, apeerobjs
);
9649 ASTOBJ_CONTAINER_DUMP(fd
, tmp
, sizeof(tmp
), &peerl
);
9650 ast_cli(fd
, "-= Registry objects: %d =-\n\n", regobjs
);
9651 ASTOBJ_CONTAINER_DUMP(fd
, tmp
, sizeof(tmp
), ®l
);
9652 return RESULT_SUCCESS
;
9654 /*! \brief Print call group and pickup group */
9655 static void print_group(int fd
, ast_group_t group
, int crlf
)
9658 ast_cli(fd
, crlf
? "%s\r\n" : "%s\n", ast_print_group(buf
, sizeof(buf
), group
) );
9661 /*! \brief Convert DTMF mode to printable string */
9662 static const char *dtmfmode2str(int mode
)
9665 case SIP_DTMF_RFC2833
:
9669 case SIP_DTMF_INBAND
:
9677 /*! \brief Convert Insecure setting to printable string */
9678 static const char *insecure2str(int port
, int invite
)
9681 return "port,invite";
9690 /*! \brief Destroy disused contexts between reloads
9691 Only used in reload_config so the code for regcontext doesn't get ugly
9693 static void cleanup_stale_contexts(char *new, char *old
)
9695 char *oldcontext
, *newcontext
, *stalecontext
, *stringp
, newlist
[AST_MAX_CONTEXT
];
9697 while ((oldcontext
= strsep(&old
, "&"))) {
9698 stalecontext
= '\0';
9699 ast_copy_string(newlist
, new, sizeof(newlist
));
9701 while ((newcontext
= strsep(&stringp
, "&"))) {
9702 if (strcmp(newcontext
, oldcontext
) == 0) {
9703 /* This is not the context you're looking for */
9704 stalecontext
= '\0';
9706 } else if (strcmp(newcontext
, oldcontext
)) {
9707 stalecontext
= oldcontext
;
9712 ast_context_destroy(ast_context_find(stalecontext
), "SIP");
9716 /*! \brief Remove temporary realtime objects from memory (CLI) */
9717 static int sip_prune_realtime(int fd
, int argc
, char *argv
[])
9719 struct sip_peer
*peer
;
9720 struct sip_user
*user
;
9721 int pruneuser
= FALSE
;
9722 int prunepeer
= FALSE
;
9729 if (!strcasecmp(argv
[3], "user"))
9730 return RESULT_SHOWUSAGE
;
9731 if (!strcasecmp(argv
[3], "peer"))
9732 return RESULT_SHOWUSAGE
;
9733 if (!strcasecmp(argv
[3], "like"))
9734 return RESULT_SHOWUSAGE
;
9735 if (!strcasecmp(argv
[3], "all")) {
9737 pruneuser
= prunepeer
= TRUE
;
9739 pruneuser
= prunepeer
= TRUE
;
9744 if (!strcasecmp(argv
[4], "like"))
9745 return RESULT_SHOWUSAGE
;
9746 if (!strcasecmp(argv
[3], "all"))
9747 return RESULT_SHOWUSAGE
;
9748 if (!strcasecmp(argv
[3], "like")) {
9751 pruneuser
= prunepeer
= TRUE
;
9752 } else if (!strcasecmp(argv
[3], "user")) {
9754 if (!strcasecmp(argv
[4], "all"))
9758 } else if (!strcasecmp(argv
[3], "peer")) {
9760 if (!strcasecmp(argv
[4], "all"))
9765 return RESULT_SHOWUSAGE
;
9768 if (strcasecmp(argv
[4], "like"))
9769 return RESULT_SHOWUSAGE
;
9770 if (!strcasecmp(argv
[3], "user")) {
9773 } else if (!strcasecmp(argv
[3], "peer")) {
9777 return RESULT_SHOWUSAGE
;
9780 return RESULT_SHOWUSAGE
;
9783 if (multi
&& name
) {
9784 if (regcomp(®exbuf
, name
, REG_EXTENDED
| REG_NOSUB
))
9785 return RESULT_SHOWUSAGE
;
9792 ASTOBJ_CONTAINER_WRLOCK(&peerl
);
9793 ASTOBJ_CONTAINER_TRAVERSE(&peerl
, 1, do {
9794 ASTOBJ_RDLOCK(iterator
);
9795 if (name
&& regexec(®exbuf
, iterator
->name
, 0, NULL
, 0)) {
9796 ASTOBJ_UNLOCK(iterator
);
9799 if (ast_test_flag(&iterator
->flags
[1], SIP_PAGE2_RTCACHEFRIENDS
)) {
9800 ASTOBJ_MARK(iterator
);
9803 ASTOBJ_UNLOCK(iterator
);
9806 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl
, sip_destroy_peer
);
9807 ast_cli(fd
, "%d peers pruned.\n", pruned
);
9809 ast_cli(fd
, "No peers found to prune.\n");
9810 ASTOBJ_CONTAINER_UNLOCK(&peerl
);
9815 ASTOBJ_CONTAINER_WRLOCK(&userl
);
9816 ASTOBJ_CONTAINER_TRAVERSE(&userl
, 1, do {
9817 ASTOBJ_RDLOCK(iterator
);
9818 if (name
&& regexec(®exbuf
, iterator
->name
, 0, NULL
, 0)) {
9819 ASTOBJ_UNLOCK(iterator
);
9822 if (ast_test_flag(&iterator
->flags
[1], SIP_PAGE2_RTCACHEFRIENDS
)) {
9823 ASTOBJ_MARK(iterator
);
9826 ASTOBJ_UNLOCK(iterator
);
9829 ASTOBJ_CONTAINER_PRUNE_MARKED(&userl
, sip_destroy_user
);
9830 ast_cli(fd
, "%d users pruned.\n", pruned
);
9832 ast_cli(fd
, "No users found to prune.\n");
9833 ASTOBJ_CONTAINER_UNLOCK(&userl
);
9837 if ((peer
= ASTOBJ_CONTAINER_FIND_UNLINK(&peerl
, name
))) {
9838 if (!ast_test_flag(&peer
->flags
[1], SIP_PAGE2_RTCACHEFRIENDS
)) {
9839 ast_cli(fd
, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name
);
9840 ASTOBJ_CONTAINER_LINK(&peerl
, peer
);
9842 ast_cli(fd
, "Peer '%s' pruned.\n", name
);
9843 ASTOBJ_UNREF(peer
, sip_destroy_peer
);
9845 ast_cli(fd
, "Peer '%s' not found.\n", name
);
9848 if ((user
= ASTOBJ_CONTAINER_FIND_UNLINK(&userl
, name
))) {
9849 if (!ast_test_flag(&user
->flags
[1], SIP_PAGE2_RTCACHEFRIENDS
)) {
9850 ast_cli(fd
, "User '%s' is not a Realtime user, cannot be pruned.\n", name
);
9851 ASTOBJ_CONTAINER_LINK(&userl
, user
);
9853 ast_cli(fd
, "User '%s' pruned.\n", name
);
9854 ASTOBJ_UNREF(user
, sip_destroy_user
);
9856 ast_cli(fd
, "User '%s' not found.\n", name
);
9860 return RESULT_SUCCESS
;
9863 /*! \brief Print codec list from preference to CLI/manager */
9864 static void print_codec_to_cli(int fd
, struct ast_codec_pref
*pref
)
9868 for(x
= 0; x
< 32 ; x
++) {
9869 codec
= ast_codec_pref_index(pref
, x
);
9872 ast_cli(fd
, "%s", ast_getformatname(codec
));
9873 ast_cli(fd
, ":%d", pref
->framing
[x
]);
9874 if (x
< 31 && ast_codec_pref_index(pref
, x
+ 1))
9878 ast_cli(fd
, "none");
9881 /*! \brief Print domain mode to cli */
9882 static const char *domain_mode_to_text(const enum domain_mode mode
)
9885 case SIP_DOMAIN_AUTO
:
9886 return "[Automatic]";
9887 case SIP_DOMAIN_CONFIG
:
9888 return "[Configured]";
9894 /*! \brief CLI command to list local domains */
9895 static int sip_show_domains(int fd
, int argc
, char *argv
[])
9898 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
9900 if (AST_LIST_EMPTY(&domain_list
)) {
9901 ast_cli(fd
, "SIP Domain support not enabled.\n\n");
9902 return RESULT_SUCCESS
;
9904 ast_cli(fd
, FORMAT
, "Our local SIP domains:", "Context", "Set by");
9905 AST_LIST_LOCK(&domain_list
);
9906 AST_LIST_TRAVERSE(&domain_list
, d
, list
)
9907 ast_cli(fd
, FORMAT
, d
->domain
, S_OR(d
->context
, "(default)"),
9908 domain_mode_to_text(d
->mode
));
9909 AST_LIST_UNLOCK(&domain_list
);
9911 return RESULT_SUCCESS
;
9916 static char mandescr_show_peer
[] =
9917 "Description: Show one SIP peer with details on current status.\n"
9919 " Peer: <name> The peer name you want to check.\n"
9920 " ActionID: <id> Optional action ID for this AMI transaction.\n";
9922 /*! \brief Show SIP peers in the manager API */
9923 static int manager_sip_show_peer(struct mansession
*s
, const struct message
*m
)
9925 const char *id
= astman_get_header(m
,"ActionID");
9930 peer
= astman_get_header(m
,"Peer");
9931 if (ast_strlen_zero(peer
)) {
9932 astman_send_error(s
, m
, "Peer: <name> missing.\n");
9940 if (!ast_strlen_zero(id
))
9941 astman_append(s
, "ActionID: %s\r\n",id
);
9942 ret
= _sip_show_peer(1, -1, s
, m
, 4, a
);
9943 astman_append(s
, "\r\n\r\n" );
9949 /*! \brief Show one peer in detail */
9950 static int sip_show_peer(int fd
, int argc
, char *argv
[])
9952 return _sip_show_peer(0, fd
, NULL
, NULL
, argc
, (const char **) argv
);
9955 /*! \brief Show one peer in detail (main function) */
9956 static int _sip_show_peer(int type
, int fd
, struct mansession
*s
, const struct message
*m
, int argc
, const char *argv
[])
9958 char status
[30] = "";
9960 struct sip_peer
*peer
;
9961 char codec_buf
[512];
9962 struct ast_codec_pref
*pref
;
9963 struct ast_variable
*v
;
9964 struct sip_auth
*auth
;
9965 int x
= 0, codec
= 0, load_realtime
;
9968 realtimepeers
= ast_check_realtime("sippeers");
9971 return RESULT_SHOWUSAGE
;
9973 load_realtime
= (argc
== 5 && !strcmp(argv
[4], "load")) ? TRUE
: FALSE
;
9974 peer
= find_peer(argv
[3], NULL
, load_realtime
);
9975 if (s
) { /* Manager */
9977 astman_append(s
, "Response: Success\r\n");
9979 snprintf (cbuf
, sizeof(cbuf
), "Peer %s not found.\n", argv
[3]);
9980 astman_send_error(s
, m
, cbuf
);
9984 if (peer
&& type
==0 ) { /* Normal listing */
9986 ast_cli(fd
, " * Name : %s\n", peer
->name
);
9987 if (realtimepeers
) { /* Realtime is enabled */
9988 ast_cli(fd
, " Realtime peer: %s\n", ast_test_flag(&peer
->flags
[0], SIP_REALTIME
) ? "Yes, cached" : "No");
9990 ast_cli(fd
, " Secret : %s\n", ast_strlen_zero(peer
->secret
)?"<Not set>":"<Set>");
9991 ast_cli(fd
, " MD5Secret : %s\n", ast_strlen_zero(peer
->md5secret
)?"<Not set>":"<Set>");
9992 for (auth
= peer
->auth
; auth
; auth
= auth
->next
) {
9993 ast_cli(fd
, " Realm-auth : Realm %-15.15s User %-10.20s ", auth
->realm
, auth
->username
);
9994 ast_cli(fd
, "%s\n", !ast_strlen_zero(auth
->secret
)?"<Secret set>":(!ast_strlen_zero(auth
->md5secret
)?"<MD5secret set>" : "<Not set>"));
9996 ast_cli(fd
, " Context : %s\n", peer
->context
);
9997 ast_cli(fd
, " Subscr.Cont. : %s\n", S_OR(peer
->subscribecontext
, "<Not set>") );
9998 ast_cli(fd
, " Language : %s\n", peer
->language
);
9999 if (!ast_strlen_zero(peer
->accountcode
))
10000 ast_cli(fd
, " Accountcode : %s\n", peer
->accountcode
);
10001 ast_cli(fd
, " AMA flags : %s\n", ast_cdr_flags2str(peer
->amaflags
));
10002 ast_cli(fd
, " Transfer mode: %s\n", transfermode2str(peer
->allowtransfer
));
10003 ast_cli(fd
, " CallingPres : %s\n", ast_describe_caller_presentation(peer
->callingpres
));
10004 if (!ast_strlen_zero(peer
->fromuser
))
10005 ast_cli(fd
, " FromUser : %s\n", peer
->fromuser
);
10006 if (!ast_strlen_zero(peer
->fromdomain
))
10007 ast_cli(fd
, " FromDomain : %s\n", peer
->fromdomain
);
10008 ast_cli(fd
, " Callgroup : ");
10009 print_group(fd
, peer
->callgroup
, 0);
10010 ast_cli(fd
, " Pickupgroup : ");
10011 print_group(fd
, peer
->pickupgroup
, 0);
10012 ast_cli(fd
, " Mailbox : %s\n", peer
->mailbox
);
10013 ast_cli(fd
, " VM Extension : %s\n", peer
->vmexten
);
10014 ast_cli(fd
, " LastMsgsSent : %d/%d\n", (peer
->lastmsgssent
& 0x7fff0000) >> 16, peer
->lastmsgssent
& 0xffff);
10015 ast_cli(fd
, " Call limit : %d\n", peer
->call_limit
);
10016 ast_cli(fd
, " Dynamic : %s\n", (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
)?"Yes":"No"));
10017 ast_cli(fd
, " Callerid : %s\n", ast_callerid_merge(cbuf
, sizeof(cbuf
), peer
->cid_name
, peer
->cid_num
, "<unspecified>"));
10018 ast_cli(fd
, " MaxCallBR : %d kbps\n", peer
->maxcallbitrate
);
10019 ast_cli(fd
, " Expire : %ld\n", ast_sched_when(sched
, peer
->expire
));
10020 ast_cli(fd
, " Insecure : %s\n", insecure2str(ast_test_flag(&peer
->flags
[0], SIP_INSECURE_PORT
), ast_test_flag(&peer
->flags
[0], SIP_INSECURE_INVITE
)));
10021 ast_cli(fd
, " Nat : %s\n", nat2str(ast_test_flag(&peer
->flags
[0], SIP_NAT
)));
10022 ast_cli(fd
, " ACL : %s\n", (peer
->ha
?"Yes":"No"));
10023 ast_cli(fd
, " T38 pt UDPTL : %s\n", ast_test_flag(&peer
->flags
[1], SIP_PAGE2_T38SUPPORT_UDPTL
)?"Yes":"No");
10024 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10025 ast_cli(fd
, " T38 pt RTP : %s\n", ast_test_flag(&peer
->flags
[1], SIP_PAGE2_T38SUPPORT_RTP
)?"Yes":"No");
10026 ast_cli(fd
, " T38 pt TCP : %s\n", ast_test_flag(&peer
->flags
[1], SIP_PAGE2_T38SUPPORT_TCP
)?"Yes":"No");
10028 ast_cli(fd
, " CanReinvite : %s\n", ast_test_flag(&peer
->flags
[0], SIP_CAN_REINVITE
)?"Yes":"No");
10029 ast_cli(fd
, " PromiscRedir : %s\n", ast_test_flag(&peer
->flags
[0], SIP_PROMISCREDIR
)?"Yes":"No");
10030 ast_cli(fd
, " User=Phone : %s\n", ast_test_flag(&peer
->flags
[0], SIP_USEREQPHONE
)?"Yes":"No");
10031 ast_cli(fd
, " Video Support: %s\n", ast_test_flag(&peer
->flags
[1], SIP_PAGE2_VIDEOSUPPORT
)?"Yes":"No");
10032 ast_cli(fd
, " Trust RPID : %s\n", ast_test_flag(&peer
->flags
[0], SIP_TRUSTRPID
) ? "Yes" : "No");
10033 ast_cli(fd
, " Send RPID : %s\n", ast_test_flag(&peer
->flags
[0], SIP_SENDRPID
) ? "Yes" : "No");
10034 ast_cli(fd
, " Subscriptions: %s\n", ast_test_flag(&peer
->flags
[1], SIP_PAGE2_ALLOWSUBSCRIBE
) ? "Yes" : "No");
10035 ast_cli(fd
, " Overlap dial : %s\n", ast_test_flag(&peer
->flags
[1], SIP_PAGE2_ALLOWOVERLAP
) ? "Yes" : "No");
10037 /* - is enumerated */
10038 ast_cli(fd
, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer
->flags
[0], SIP_DTMF
)));
10039 ast_cli(fd
, " LastMsg : %d\n", peer
->lastmsg
);
10040 ast_cli(fd
, " ToHost : %s\n", peer
->tohost
);
10041 ast_cli(fd
, " Addr->IP : %s Port %d\n", peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(peer
->addr
.sin_addr
) : "(Unspecified)", ntohs(peer
->addr
.sin_port
));
10042 ast_cli(fd
, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer
->defaddr
.sin_addr
), ntohs(peer
->defaddr
.sin_port
));
10043 if (!ast_strlen_zero(global_regcontext
))
10044 ast_cli(fd
, " Reg. exten : %s\n", peer
->regexten
);
10045 ast_cli(fd
, " Def. Username: %s\n", peer
->username
);
10046 ast_cli(fd
, " SIP Options : ");
10047 if (peer
->sipoptions
) {
10048 int lastoption
= -1;
10049 for (x
=0 ; (x
< (sizeof(sip_options
) / sizeof(sip_options
[0]))); x
++) {
10050 if (sip_options
[x
].id
!= lastoption
) {
10051 if (peer
->sipoptions
& sip_options
[x
].id
)
10052 ast_cli(fd
, "%s ", sip_options
[x
].text
);
10057 ast_cli(fd
, "(none)");
10060 ast_cli(fd
, " Codecs : ");
10061 ast_getformatname_multiple(codec_buf
, sizeof(codec_buf
) -1, peer
->capability
);
10062 ast_cli(fd
, "%s\n", codec_buf
);
10063 ast_cli(fd
, " Codec Order : (");
10064 print_codec_to_cli(fd
, &peer
->prefs
);
10065 ast_cli(fd
, ")\n");
10067 ast_cli(fd
, " Auto-Framing: %s \n", peer
->autoframing
? "Yes" : "No");
10068 ast_cli(fd
, " Status : ");
10069 peer_status(peer
, status
, sizeof(status
));
10070 ast_cli(fd
, "%s\n",status
);
10071 ast_cli(fd
, " Useragent : %s\n", peer
->useragent
);
10072 ast_cli(fd
, " Reg. Contact : %s\n", peer
->fullcontact
);
10073 if (peer
->chanvars
) {
10074 ast_cli(fd
, " Variables :\n");
10075 for (v
= peer
->chanvars
; v
; v
= v
->next
)
10076 ast_cli(fd
, " %s = %s\n", v
->name
, v
->value
);
10079 ASTOBJ_UNREF(peer
,sip_destroy_peer
);
10080 } else if (peer
&& type
== 1) { /* manager listing */
10082 astman_append(s
, "Channeltype: SIP\r\n");
10083 astman_append(s
, "ObjectName: %s\r\n", peer
->name
);
10084 astman_append(s
, "ChanObjectType: peer\r\n");
10085 astman_append(s
, "SecretExist: %s\r\n", ast_strlen_zero(peer
->secret
)?"N":"Y");
10086 astman_append(s
, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer
->md5secret
)?"N":"Y");
10087 astman_append(s
, "Context: %s\r\n", peer
->context
);
10088 astman_append(s
, "Language: %s\r\n", peer
->language
);
10089 if (!ast_strlen_zero(peer
->accountcode
))
10090 astman_append(s
, "Accountcode: %s\r\n", peer
->accountcode
);
10091 astman_append(s
, "AMAflags: %s\r\n", ast_cdr_flags2str(peer
->amaflags
));
10092 astman_append(s
, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer
->callingpres
));
10093 if (!ast_strlen_zero(peer
->fromuser
))
10094 astman_append(s
, "SIP-FromUser: %s\r\n", peer
->fromuser
);
10095 if (!ast_strlen_zero(peer
->fromdomain
))
10096 astman_append(s
, "SIP-FromDomain: %s\r\n", peer
->fromdomain
);
10097 astman_append(s
, "Callgroup: ");
10098 astman_append(s
, "%s\r\n", ast_print_group(buf
, sizeof(buf
), peer
->callgroup
));
10099 astman_append(s
, "Pickupgroup: ");
10100 astman_append(s
, "%s\r\n", ast_print_group(buf
, sizeof(buf
), peer
->pickupgroup
));
10101 astman_append(s
, "VoiceMailbox: %s\r\n", peer
->mailbox
);
10102 astman_append(s
, "TransferMode: %s\r\n", transfermode2str(peer
->allowtransfer
));
10103 astman_append(s
, "LastMsgsSent: %d\r\n", peer
->lastmsgssent
);
10104 astman_append(s
, "Call limit: %d\r\n", peer
->call_limit
);
10105 astman_append(s
, "MaxCallBR: %d kbps\r\n", peer
->maxcallbitrate
);
10106 astman_append(s
, "Dynamic: %s\r\n", (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
)?"Y":"N"));
10107 astman_append(s
, "Callerid: %s\r\n", ast_callerid_merge(cbuf
, sizeof(cbuf
), peer
->cid_name
, peer
->cid_num
, ""));
10108 astman_append(s
, "RegExpire: %ld seconds\r\n", ast_sched_when(sched
,peer
->expire
));
10109 astman_append(s
, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer
->flags
[0], SIP_INSECURE_PORT
), ast_test_flag(&peer
->flags
[0], SIP_INSECURE_INVITE
)));
10110 astman_append(s
, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer
->flags
[0], SIP_NAT
)));
10111 astman_append(s
, "ACL: %s\r\n", (peer
->ha
?"Y":"N"));
10112 astman_append(s
, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer
->flags
[0], SIP_CAN_REINVITE
)?"Y":"N"));
10113 astman_append(s
, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer
->flags
[0], SIP_PROMISCREDIR
)?"Y":"N"));
10114 astman_append(s
, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer
->flags
[0], SIP_USEREQPHONE
)?"Y":"N"));
10115 astman_append(s
, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_VIDEOSUPPORT
)?"Y":"N"));
10117 /* - is enumerated */
10118 astman_append(s
, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer
->flags
[0], SIP_DTMF
)));
10119 astman_append(s
, "SIPLastMsg: %d\r\n", peer
->lastmsg
);
10120 astman_append(s
, "ToHost: %s\r\n", peer
->tohost
);
10121 astman_append(s
, "Address-IP: %s\r\nAddress-Port: %d\r\n", peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(peer
->addr
.sin_addr
) : "", ntohs(peer
->addr
.sin_port
));
10122 astman_append(s
, "Default-addr-IP: %s\r\nDefault-addr-port: %d\r\n", ast_inet_ntoa(peer
->defaddr
.sin_addr
), ntohs(peer
->defaddr
.sin_port
));
10123 astman_append(s
, "Default-Username: %s\r\n", peer
->username
);
10124 if (!ast_strlen_zero(global_regcontext
))
10125 astman_append(s
, "RegExtension: %s\r\n", peer
->regexten
);
10126 astman_append(s
, "Codecs: ");
10127 ast_getformatname_multiple(codec_buf
, sizeof(codec_buf
) -1, peer
->capability
);
10128 astman_append(s
, "%s\r\n", codec_buf
);
10129 astman_append(s
, "CodecOrder: ");
10130 pref
= &peer
->prefs
;
10131 for(x
= 0; x
< 32 ; x
++) {
10132 codec
= ast_codec_pref_index(pref
,x
);
10135 astman_append(s
, "%s", ast_getformatname(codec
));
10136 if (x
< 31 && ast_codec_pref_index(pref
,x
+1))
10137 astman_append(s
, ",");
10140 astman_append(s
, "\r\n");
10141 astman_append(s
, "Status: ");
10142 peer_status(peer
, status
, sizeof(status
));
10143 astman_append(s
, "%s\r\n", status
);
10144 astman_append(s
, "SIP-Useragent: %s\r\n", peer
->useragent
);
10145 astman_append(s
, "Reg-Contact : %s\r\n", peer
->fullcontact
);
10146 if (peer
->chanvars
) {
10147 for (v
= peer
->chanvars
; v
; v
= v
->next
) {
10148 astman_append(s
, "ChanVariable:\n");
10149 astman_append(s
, " %s,%s\r\n", v
->name
, v
->value
);
10153 ASTOBJ_UNREF(peer
,sip_destroy_peer
);
10156 ast_cli(fd
,"Peer %s not found.\n", argv
[3]);
10160 return RESULT_SUCCESS
;
10163 /*! \brief Show one user in detail */
10164 static int sip_show_user(int fd
, int argc
, char *argv
[])
10167 struct sip_user
*user
;
10168 struct ast_variable
*v
;
10172 return RESULT_SHOWUSAGE
;
10174 /* Load from realtime storage? */
10175 load_realtime
= (argc
== 5 && !strcmp(argv
[4], "load")) ? TRUE
: FALSE
;
10177 user
= find_user(argv
[3], load_realtime
);
10179 ast_cli(fd
,"\n\n");
10180 ast_cli(fd
, " * Name : %s\n", user
->name
);
10181 ast_cli(fd
, " Secret : %s\n", ast_strlen_zero(user
->secret
)?"<Not set>":"<Set>");
10182 ast_cli(fd
, " MD5Secret : %s\n", ast_strlen_zero(user
->md5secret
)?"<Not set>":"<Set>");
10183 ast_cli(fd
, " Context : %s\n", user
->context
);
10184 ast_cli(fd
, " Language : %s\n", user
->language
);
10185 if (!ast_strlen_zero(user
->accountcode
))
10186 ast_cli(fd
, " Accountcode : %s\n", user
->accountcode
);
10187 ast_cli(fd
, " AMA flags : %s\n", ast_cdr_flags2str(user
->amaflags
));
10188 ast_cli(fd
, " Transfer mode: %s\n", transfermode2str(user
->allowtransfer
));
10189 ast_cli(fd
, " MaxCallBR : %d kbps\n", user
->maxcallbitrate
);
10190 ast_cli(fd
, " CallingPres : %s\n", ast_describe_caller_presentation(user
->callingpres
));
10191 ast_cli(fd
, " Call limit : %d\n", user
->call_limit
);
10192 ast_cli(fd
, " Callgroup : ");
10193 print_group(fd
, user
->callgroup
, 0);
10194 ast_cli(fd
, " Pickupgroup : ");
10195 print_group(fd
, user
->pickupgroup
, 0);
10196 ast_cli(fd
, " Callerid : %s\n", ast_callerid_merge(cbuf
, sizeof(cbuf
), user
->cid_name
, user
->cid_num
, "<unspecified>"));
10197 ast_cli(fd
, " ACL : %s\n", (user
->ha
?"Yes":"No"));
10198 ast_cli(fd
, " Codec Order : (");
10199 print_codec_to_cli(fd
, &user
->prefs
);
10200 ast_cli(fd
, ")\n");
10202 ast_cli(fd
, " Auto-Framing: %s \n", user
->autoframing
? "Yes" : "No");
10203 if (user
->chanvars
) {
10204 ast_cli(fd
, " Variables :\n");
10205 for (v
= user
->chanvars
; v
; v
= v
->next
)
10206 ast_cli(fd
, " %s = %s\n", v
->name
, v
->value
);
10209 ASTOBJ_UNREF(user
,sip_destroy_user
);
10211 ast_cli(fd
,"User %s not found.\n", argv
[3]);
10215 return RESULT_SUCCESS
;
10218 /*! \brief Show SIP Registry (registrations with other SIP proxies */
10219 static int sip_show_registry(int fd
, int argc
, char *argv
[])
10221 #define FORMAT2 "%-30.30s %-12.12s %8.8s %-20.20s %-25.25s\n"
10222 #define FORMAT "%-30.30s %-12.12s %8d %-20.20s %-25.25s\n"
10229 return RESULT_SHOWUSAGE
;
10230 ast_cli(fd
, FORMAT2
, "Host", "Username", "Refresh", "State", "Reg.Time");
10231 ASTOBJ_CONTAINER_TRAVERSE(®l
, 1, do {
10232 ASTOBJ_RDLOCK(iterator
);
10233 snprintf(host
, sizeof(host
), "%s:%d", iterator
->hostname
, iterator
->portno
? iterator
->portno
: STANDARD_SIP_PORT
);
10234 if (iterator
->regtime
) {
10235 ast_localtime(&iterator
->regtime
, &tm
, NULL
);
10236 strftime(tmpdat
, sizeof(tmpdat
), "%a, %d %b %Y %T", &tm
);
10240 ast_cli(fd
, FORMAT
, host
, iterator
->username
, iterator
->refresh
, regstate2str(iterator
->regstate
), tmpdat
);
10241 ASTOBJ_UNLOCK(iterator
);
10243 return RESULT_SUCCESS
;
10248 /*! \brief List global settings for the SIP channel */
10249 static int sip_show_settings(int fd
, int argc
, char *argv
[])
10253 char codec_buf
[BUFSIZ
];
10255 realtimepeers
= ast_check_realtime("sippeers");
10256 realtimeusers
= ast_check_realtime("sipusers");
10259 return RESULT_SHOWUSAGE
;
10260 ast_cli(fd
, "\n\nGlobal Settings:\n");
10261 ast_cli(fd
, "----------------\n");
10262 ast_cli(fd
, " SIP Port: %d\n", ntohs(bindaddr
.sin_port
));
10263 ast_cli(fd
, " Bindaddress: %s\n", ast_inet_ntoa(bindaddr
.sin_addr
));
10264 ast_cli(fd
, " Videosupport: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_VIDEOSUPPORT
) ? "Yes" : "No");
10265 ast_cli(fd
, " AutoCreatePeer: %s\n", autocreatepeer
? "Yes" : "No");
10266 ast_cli(fd
, " Allow unknown access: %s\n", global_allowguest
? "Yes" : "No");
10267 ast_cli(fd
, " Allow subscriptions: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_ALLOWSUBSCRIBE
) ? "Yes" : "No");
10268 ast_cli(fd
, " Allow overlap dialing: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_ALLOWOVERLAP
) ? "Yes" : "No");
10269 ast_cli(fd
, " Promsic. redir: %s\n", ast_test_flag(&global_flags
[0], SIP_PROMISCREDIR
) ? "Yes" : "No");
10270 ast_cli(fd
, " SIP domain support: %s\n", AST_LIST_EMPTY(&domain_list
) ? "No" : "Yes");
10271 ast_cli(fd
, " Call to non-local dom.: %s\n", allow_external_domains
? "Yes" : "No");
10272 ast_cli(fd
, " URI user is phone no: %s\n", ast_test_flag(&global_flags
[0], SIP_USEREQPHONE
) ? "Yes" : "No");
10273 ast_cli(fd
, " Our auth realm %s\n", global_realm
);
10274 ast_cli(fd
, " Realm. auth: %s\n", authl
? "Yes": "No");
10275 ast_cli(fd
, " Always auth rejects: %s\n", global_alwaysauthreject
? "Yes" : "No");
10276 ast_cli(fd
, " Call limit peers only: %s\n", global_limitonpeers
? "Yes" : "No");
10277 ast_cli(fd
, " Direct RTP setup: %s\n", global_directrtpsetup
? "Yes" : "No");
10278 ast_cli(fd
, " User Agent: %s\n", global_useragent
);
10279 ast_cli(fd
, " MWI checking interval: %d secs\n", global_mwitime
);
10280 ast_cli(fd
, " Reg. context: %s\n", S_OR(global_regcontext
, "(not set)"));
10281 ast_cli(fd
, " Caller ID: %s\n", default_callerid
);
10282 ast_cli(fd
, " From: Domain: %s\n", default_fromdomain
);
10283 ast_cli(fd
, " Record SIP history: %s\n", recordhistory
? "On" : "Off");
10284 ast_cli(fd
, " Call Events: %s\n", global_callevents
? "On" : "Off");
10285 ast_cli(fd
, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip
));
10286 ast_cli(fd
, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio
));
10287 ast_cli(fd
, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video
));
10288 ast_cli(fd
, " T38 fax pt UDPTL: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_T38SUPPORT_UDPTL
) ? "Yes" : "No");
10289 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10290 ast_cli(fd
, " T38 fax pt RTP: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_T38SUPPORT_RTP
) ? "Yes" : "No");
10291 ast_cli(fd
, " T38 fax pt TCP: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_T38SUPPORT_TCP
) ? "Yes" : "No");
10293 ast_cli(fd
, " RFC2833 Compensation: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_RFC2833_COMPENSATE
) ? "Yes" : "No");
10294 if (!realtimepeers
&& !realtimeusers
)
10295 ast_cli(fd
, " SIP realtime: Disabled\n" );
10297 ast_cli(fd
, " SIP realtime: Enabled\n" );
10299 ast_cli(fd
, "\nGlobal Signalling Settings:\n");
10300 ast_cli(fd
, "---------------------------\n");
10301 ast_cli(fd
, " Codecs: ");
10302 ast_getformatname_multiple(codec_buf
, sizeof(codec_buf
) -1, global_capability
);
10303 ast_cli(fd
, "%s\n", codec_buf
);
10304 ast_cli(fd
, " Codec Order: ");
10305 print_codec_to_cli(fd
, &default_prefs
);
10307 ast_cli(fd
, " T1 minimum: %d\n", global_t1min
);
10308 ast_cli(fd
, " Relax DTMF: %s\n", global_relaxdtmf
? "Yes" : "No");
10309 ast_cli(fd
, " Compact SIP headers: %s\n", compactheaders
? "Yes" : "No");
10310 ast_cli(fd
, " RTP Keepalive: %d %s\n", global_rtpkeepalive
, global_rtpkeepalive
? "" : "(Disabled)" );
10311 ast_cli(fd
, " RTP Timeout: %d %s\n", global_rtptimeout
, global_rtptimeout
? "" : "(Disabled)" );
10312 ast_cli(fd
, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout
, global_rtpholdtimeout
? "" : "(Disabled)");
10313 ast_cli(fd
, " MWI NOTIFY mime type: %s\n", default_notifymime
);
10314 ast_cli(fd
, " DNS SRV lookup: %s\n", srvlookup
? "Yes" : "No");
10315 ast_cli(fd
, " Pedantic SIP support: %s\n", pedanticsipchecking
? "Yes" : "No");
10316 ast_cli(fd
, " Reg. min duration %d secs\n", min_expiry
);
10317 ast_cli(fd
, " Reg. max duration: %d secs\n", max_expiry
);
10318 ast_cli(fd
, " Reg. default duration: %d secs\n", default_expiry
);
10319 ast_cli(fd
, " Outbound reg. timeout: %d secs\n", global_reg_timeout
);
10320 ast_cli(fd
, " Outbound reg. attempts: %d\n", global_regattempts_max
);
10321 ast_cli(fd
, " Notify ringing state: %s\n", global_notifyringing
? "Yes" : "No");
10322 ast_cli(fd
, " Notify hold state: %s\n", global_notifyhold
? "Yes" : "No");
10323 ast_cli(fd
, " SIP Transfer mode: %s\n", transfermode2str(global_allowtransfer
));
10324 ast_cli(fd
, " Max Call Bitrate: %d kbps\r\n", default_maxcallbitrate
);
10325 ast_cli(fd
, " Auto-Framing: %s \r\n", global_autoframing
? "Yes" : "No");
10326 ast_cli(fd
, "\nDefault Settings:\n");
10327 ast_cli(fd
, "-----------------\n");
10328 ast_cli(fd
, " Context: %s\n", default_context
);
10329 ast_cli(fd
, " Nat: %s\n", nat2str(ast_test_flag(&global_flags
[0], SIP_NAT
)));
10330 ast_cli(fd
, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags
[0], SIP_DTMF
)));
10331 ast_cli(fd
, " Qualify: %d\n", default_qualify
);
10332 ast_cli(fd
, " Use ClientCode: %s\n", ast_test_flag(&global_flags
[0], SIP_USECLIENTCODE
) ? "Yes" : "No");
10333 ast_cli(fd
, " Progress inband: %s\n", (ast_test_flag(&global_flags
[0], SIP_PROG_INBAND
) == SIP_PROG_INBAND_NEVER
) ? "Never" : (ast_test_flag(&global_flags
[0], SIP_PROG_INBAND
) == SIP_PROG_INBAND_NO
) ? "No" : "Yes" );
10334 ast_cli(fd
, " Language: %s\n", S_OR(default_language
, "(Defaults to English)"));
10335 ast_cli(fd
, " MOH Interpret: %s\n", default_mohinterpret
);
10336 ast_cli(fd
, " MOH Suggest: %s\n", default_mohsuggest
);
10337 ast_cli(fd
, " Voice Mail Extension: %s\n", default_vmexten
);
10340 if (realtimepeers
|| realtimeusers
) {
10341 ast_cli(fd
, "\nRealtime SIP Settings:\n");
10342 ast_cli(fd
, "----------------------\n");
10343 ast_cli(fd
, " Realtime Peers: %s\n", realtimepeers
? "Yes" : "No");
10344 ast_cli(fd
, " Realtime Users: %s\n", realtimeusers
? "Yes" : "No");
10345 ast_cli(fd
, " Cache Friends: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_RTCACHEFRIENDS
) ? "Yes" : "No");
10346 ast_cli(fd
, " Update: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_RTUPDATE
) ? "Yes" : "No");
10347 ast_cli(fd
, " Ignore Reg. Expire: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_IGNOREREGEXPIRE
) ? "Yes" : "No");
10348 ast_cli(fd
, " Save sys. name: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_RTSAVE_SYSNAME
) ? "Yes" : "No");
10349 ast_cli(fd
, " Auto Clear: %d\n", global_rtautoclear
);
10351 ast_cli(fd
, "\n----\n");
10352 return RESULT_SUCCESS
;
10355 /*! \brief Show subscription type in string format */
10356 static const char *subscription_type2str(enum subscriptiontype subtype
)
10360 for (i
= 1; (i
< (sizeof(subscription_types
) / sizeof(subscription_types
[0]))); i
++) {
10361 if (subscription_types
[i
].type
== subtype
) {
10362 return subscription_types
[i
].text
;
10365 return subscription_types
[0].text
;
10368 /*! \brief Find subscription type in array */
10369 static const struct cfsubscription_types
*find_subscription_type(enum subscriptiontype subtype
)
10373 for (i
= 1; (i
< (sizeof(subscription_types
) / sizeof(subscription_types
[0]))); i
++) {
10374 if (subscription_types
[i
].type
== subtype
) {
10375 return &subscription_types
[i
];
10378 return &subscription_types
[0];
10381 /*! \brief Show active SIP channels */
10382 static int sip_show_channels(int fd
, int argc
, char *argv
[])
10384 return __sip_show_channels(fd
, argc
, argv
, 0);
10387 /*! \brief Show active SIP subscriptions */
10388 static int sip_show_subscriptions(int fd
, int argc
, char *argv
[])
10390 return __sip_show_channels(fd
, argc
, argv
, 1);
10393 /*! \brief SIP show channels CLI (main function) */
10394 static int __sip_show_channels(int fd
, int argc
, char *argv
[], int subscriptions
)
10396 #define FORMAT3 "%-15.15s %-10.10s %-11.11s %-15.15s %-13.13s %-15.15s %-10.10s\n"
10397 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-4.4s %-7.7s %-15.15s\n"
10398 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-4.4s %-3.3s %-3.3s %-15.15s %-10.10s\n"
10399 struct sip_pvt
*cur
;
10401 char *referstatus
= NULL
;
10404 return RESULT_SHOWUSAGE
;
10405 ast_mutex_lock(&iflock
);
10407 if (!subscriptions
)
10408 ast_cli(fd
, FORMAT2
, "Peer", "User/ANR", "Call ID", "Seq (Tx/Rx)", "Format", "Hold", "Last Message");
10410 ast_cli(fd
, FORMAT3
, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox");
10411 for (; cur
; cur
= cur
->next
) {
10413 if (cur
->refer
) { /* SIP transfer in progress */
10414 referstatus
= referstatus2str(cur
->refer
->status
);
10416 if (cur
->subscribed
== NONE
&& !subscriptions
) {
10417 ast_cli(fd
, FORMAT
, ast_inet_ntoa(cur
->sa
.sin_addr
),
10418 S_OR(cur
->username
, S_OR(cur
->cid_num
, "(None)")),
10420 cur
->ocseq
, cur
->icseq
,
10421 ast_getformatname(cur
->owner
? cur
->owner
->nativeformats
: 0),
10422 ast_test_flag(&cur
->flags
[1], SIP_PAGE2_CALL_ONHOLD
) ? "Yes" : "No",
10423 ast_test_flag(&cur
->flags
[0], SIP_NEEDDESTROY
) ? "(d)" : "",
10429 if (cur
->subscribed
!= NONE
&& subscriptions
) {
10430 ast_cli(fd
, FORMAT3
, ast_inet_ntoa(cur
->sa
.sin_addr
),
10431 S_OR(cur
->username
, S_OR(cur
->cid_num
, "(None)")),
10433 /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
10434 cur
->subscribed
== MWI_NOTIFICATION
? "--" : cur
->subscribeuri
,
10435 cur
->subscribed
== MWI_NOTIFICATION
? "<none>" : ast_extension_state2str(cur
->laststate
),
10436 subscription_type2str(cur
->subscribed
),
10437 cur
->subscribed
== MWI_NOTIFICATION
? (cur
->relatedpeer
? cur
->relatedpeer
->mailbox
: "<none>") : "<none>"
10442 ast_mutex_unlock(&iflock
);
10443 if (!subscriptions
)
10444 ast_cli(fd
, "%d active SIP channel%s\n", numchans
, (numchans
!= 1) ? "s" : "");
10446 ast_cli(fd
, "%d active SIP subscription%s\n", numchans
, (numchans
!= 1) ? "s" : "");
10447 return RESULT_SUCCESS
;
10453 /*! \brief Support routine for 'sip show channel' CLI */
10454 static char *complete_sipch(const char *line
, const char *word
, int pos
, int state
)
10457 struct sip_pvt
*cur
;
10459 int wordlen
= strlen(word
);
10461 ast_mutex_lock(&iflock
);
10462 for (cur
= iflist
; cur
; cur
= cur
->next
) {
10463 if (!strncasecmp(word
, cur
->callid
, wordlen
) && ++which
> state
) {
10464 c
= ast_strdup(cur
->callid
);
10468 ast_mutex_unlock(&iflock
);
10472 /*! \brief Do completion on peer name */
10473 static char *complete_sip_peer(const char *word
, int state
, int flags2
)
10475 char *result
= NULL
;
10476 int wordlen
= strlen(word
);
10479 ASTOBJ_CONTAINER_TRAVERSE(&peerl
, !result
, do {
10480 /* locking of the object is not required because only the name and flags are being compared */
10481 if (!strncasecmp(word
, iterator
->name
, wordlen
) &&
10482 (!flags2
|| ast_test_flag(&iterator
->flags
[1], flags2
)) &&
10484 result
= ast_strdup(iterator
->name
);
10489 /*! \brief Support routine for 'sip show peer' CLI */
10490 static char *complete_sip_show_peer(const char *line
, const char *word
, int pos
, int state
)
10493 return complete_sip_peer(word
, state
, 0);
10498 /*! \brief Support routine for 'sip debug peer' CLI */
10499 static char *complete_sip_debug_peer(const char *line
, const char *word
, int pos
, int state
)
10502 return complete_sip_peer(word
, state
, 0);
10507 /*! \brief Do completion on user name */
10508 static char *complete_sip_user(const char *word
, int state
, int flags2
)
10510 char *result
= NULL
;
10511 int wordlen
= strlen(word
);
10514 ASTOBJ_CONTAINER_TRAVERSE(&userl
, !result
, do {
10515 /* locking of the object is not required because only the name and flags are being compared */
10516 if (!strncasecmp(word
, iterator
->name
, wordlen
)) {
10517 if (flags2
&& !ast_test_flag(&iterator
->flags
[1], flags2
))
10519 if (++which
> state
) {
10520 result
= ast_strdup(iterator
->name
);
10527 /*! \brief Support routine for 'sip show user' CLI */
10528 static char *complete_sip_show_user(const char *line
, const char *word
, int pos
, int state
)
10531 return complete_sip_user(word
, state
, 0);
10536 /*! \brief Support routine for 'sip notify' CLI */
10537 static char *complete_sipnotify(const char *line
, const char *word
, int pos
, int state
)
10544 int wordlen
= strlen(word
);
10546 /* do completion for notify type */
10551 while ( (cat
= ast_category_browse(notify_types
, cat
)) ) {
10552 if (!strncasecmp(word
, cat
, wordlen
) && ++which
> state
) {
10553 c
= ast_strdup(cat
);
10561 return complete_sip_peer(word
, state
, 0);
10566 /*! \brief Support routine for 'sip prune realtime peer' CLI */
10567 static char *complete_sip_prune_realtime_peer(const char *line
, const char *word
, int pos
, int state
)
10570 return complete_sip_peer(word
, state
, SIP_PAGE2_RTCACHEFRIENDS
);
10574 /*! \brief Support routine for 'sip prune realtime user' CLI */
10575 static char *complete_sip_prune_realtime_user(const char *line
, const char *word
, int pos
, int state
)
10578 return complete_sip_user(word
, state
, SIP_PAGE2_RTCACHEFRIENDS
);
10583 /*! \brief Show details of one active dialog */
10584 static int sip_show_channel(int fd
, int argc
, char *argv
[])
10586 struct sip_pvt
*cur
;
10591 return RESULT_SHOWUSAGE
;
10592 len
= strlen(argv
[3]);
10593 ast_mutex_lock(&iflock
);
10594 for (cur
= iflist
; cur
; cur
= cur
->next
) {
10595 if (!strncasecmp(cur
->callid
, argv
[3], len
)) {
10596 char formatbuf
[BUFSIZ
/2];
10598 if (cur
->subscribed
!= NONE
)
10599 ast_cli(fd
, " * Subscription (type: %s)\n", subscription_type2str(cur
->subscribed
));
10601 ast_cli(fd
, " * SIP Call\n");
10602 ast_cli(fd
, " Curr. trans. direction: %s\n", ast_test_flag(&cur
->flags
[0], SIP_OUTGOING
) ? "Outgoing" : "Incoming");
10603 ast_cli(fd
, " Call-ID: %s\n", cur
->callid
);
10604 ast_cli(fd
, " Owner channel ID: %s\n", cur
->owner
? cur
->owner
->name
: "<none>");
10605 ast_cli(fd
, " Our Codec Capability: %d\n", cur
->capability
);
10606 ast_cli(fd
, " Non-Codec Capability (DTMF): %d\n", cur
->noncodeccapability
);
10607 ast_cli(fd
, " Their Codec Capability: %d\n", cur
->peercapability
);
10608 ast_cli(fd
, " Joint Codec Capability: %d\n", cur
->jointcapability
);
10609 ast_cli(fd
, " Format: %s\n", ast_getformatname_multiple(formatbuf
, sizeof(formatbuf
), cur
->owner
? cur
->owner
->nativeformats
: 0) );
10610 ast_cli(fd
, " MaxCallBR: %d kbps\n", cur
->maxcallbitrate
);
10611 ast_cli(fd
, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur
->sa
.sin_addr
), ntohs(cur
->sa
.sin_port
));
10612 ast_cli(fd
, " Received Address: %s:%d\n", ast_inet_ntoa(cur
->recv
.sin_addr
), ntohs(cur
->recv
.sin_port
));
10613 ast_cli(fd
, " SIP Transfer mode: %s\n", transfermode2str(cur
->allowtransfer
));
10614 ast_cli(fd
, " NAT Support: %s\n", nat2str(ast_test_flag(&cur
->flags
[0], SIP_NAT
)));
10615 ast_cli(fd
, " Audio IP: %s %s\n", ast_inet_ntoa(cur
->redirip
.sin_addr
.s_addr
? cur
->redirip
.sin_addr
: cur
->ourip
), cur
->redirip
.sin_addr
.s_addr
? "(Outside bridge)" : "(local)" );
10616 ast_cli(fd
, " Our Tag: %s\n", cur
->tag
);
10617 ast_cli(fd
, " Their Tag: %s\n", cur
->theirtag
);
10618 ast_cli(fd
, " SIP User agent: %s\n", cur
->useragent
);
10619 if (!ast_strlen_zero(cur
->username
))
10620 ast_cli(fd
, " Username: %s\n", cur
->username
);
10621 if (!ast_strlen_zero(cur
->peername
))
10622 ast_cli(fd
, " Peername: %s\n", cur
->peername
);
10623 if (!ast_strlen_zero(cur
->uri
))
10624 ast_cli(fd
, " Original uri: %s\n", cur
->uri
);
10625 if (!ast_strlen_zero(cur
->cid_num
))
10626 ast_cli(fd
, " Caller-ID: %s\n", cur
->cid_num
);
10627 ast_cli(fd
, " Need Destroy: %d\n", ast_test_flag(&cur
->flags
[0], SIP_NEEDDESTROY
));
10628 ast_cli(fd
, " Last Message: %s\n", cur
->lastmsg
);
10629 ast_cli(fd
, " Promiscuous Redir: %s\n", ast_test_flag(&cur
->flags
[0], SIP_PROMISCREDIR
) ? "Yes" : "No");
10630 ast_cli(fd
, " Route: %s\n", cur
->route
? cur
->route
->hop
: "N/A");
10631 ast_cli(fd
, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur
->flags
[0], SIP_DTMF
)));
10632 ast_cli(fd
, " SIP Options: ");
10633 if (cur
->sipoptions
) {
10635 for (x
=0 ; (x
< (sizeof(sip_options
) / sizeof(sip_options
[0]))); x
++) {
10636 if (cur
->sipoptions
& sip_options
[x
].id
)
10637 ast_cli(fd
, "%s ", sip_options
[x
].text
);
10640 ast_cli(fd
, "(none)\n");
10641 ast_cli(fd
, "\n\n");
10645 ast_mutex_unlock(&iflock
);
10647 ast_cli(fd
, "No such SIP Call ID starting with '%s'\n", argv
[3]);
10648 return RESULT_SUCCESS
;
10651 /*! \brief Show history details of one dialog */
10652 static int sip_show_history(int fd
, int argc
, char *argv
[])
10654 struct sip_pvt
*cur
;
10659 return RESULT_SHOWUSAGE
;
10660 if (!recordhistory
)
10661 ast_cli(fd
, "\n***Note: History recording is currently DISABLED. Use 'sip history' to ENABLE.\n");
10662 len
= strlen(argv
[3]);
10663 ast_mutex_lock(&iflock
);
10664 for (cur
= iflist
; cur
; cur
= cur
->next
) {
10665 if (!strncasecmp(cur
->callid
, argv
[3], len
)) {
10666 struct sip_history
*hist
;
10670 if (cur
->subscribed
!= NONE
)
10671 ast_cli(fd
, " * Subscription\n");
10673 ast_cli(fd
, " * SIP Call\n");
10675 AST_LIST_TRAVERSE(cur
->history
, hist
, list
)
10676 ast_cli(fd
, "%d. %s\n", ++x
, hist
->event
);
10678 ast_cli(fd
, "Call '%s' has no history\n", cur
->callid
);
10682 ast_mutex_unlock(&iflock
);
10684 ast_cli(fd
, "No such SIP Call ID starting with '%s'\n", argv
[3]);
10685 return RESULT_SUCCESS
;
10688 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
10689 static void sip_dump_history(struct sip_pvt
*dialog
)
10692 struct sip_history
*hist
;
10693 static int errmsg
= 0;
10698 if (!option_debug
&& !sipdebug
) {
10700 ast_log(LOG_NOTICE
, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
10706 ast_log(LOG_DEBUG
, "\n---------- SIP HISTORY for '%s' \n", dialog
->callid
);
10707 if (dialog
->subscribed
)
10708 ast_log(LOG_DEBUG
, " * Subscription\n");
10710 ast_log(LOG_DEBUG
, " * SIP Call\n");
10711 if (dialog
->history
)
10712 AST_LIST_TRAVERSE(dialog
->history
, hist
, list
)
10713 ast_log(LOG_DEBUG
, " %-3.3d. %s\n", ++x
, hist
->event
);
10715 ast_log(LOG_DEBUG
, "Call '%s' has no history\n", dialog
->callid
);
10716 ast_log(LOG_DEBUG
, "\n---------- END SIP HISTORY for '%s' \n", dialog
->callid
);
10720 /*! \brief Receive SIP INFO Message
10721 \note Doesn't read the duration of the DTMF signal */
10722 static void handle_request_info(struct sip_pvt
*p
, struct sip_request
*req
)
10725 unsigned int event
;
10726 const char *c
= get_header(req
, "Content-Type");
10728 /* Need to check the media/type */
10729 if (!strcasecmp(c
, "application/dtmf-relay") ||
10730 !strcasecmp(c
, "application/vnd.nortelnetworks.digits")) {
10731 unsigned int duration
= 0;
10733 /* Try getting the "signal=" part */
10734 if (ast_strlen_zero(c
= get_body(req
, "Signal")) && ast_strlen_zero(c
= get_body(req
, "d"))) {
10735 ast_log(LOG_WARNING
, "Unable to retrieve DTMF signal from INFO message from %s\n", p
->callid
);
10736 transmit_response(p
, "200 OK", req
); /* Should return error */
10739 ast_copy_string(buf
, c
, sizeof(buf
));
10742 if (!ast_strlen_zero((c
= get_body(req
, "Duration"))))
10743 duration
= atoi(c
);
10745 duration
= 100; /* 100 ms */
10747 if (!p
->owner
) { /* not a PBX call */
10748 transmit_response(p
, "481 Call leg/transaction does not exist", req
);
10749 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
10753 if (ast_strlen_zero(buf
)) {
10754 transmit_response(p
, "200 OK", req
);
10760 else if (buf
[0] == '#')
10762 else if ((buf
[0] >= 'A') && (buf
[0] <= 'D'))
10763 event
= 12 + buf
[0] - 'A';
10767 /* send a FLASH event */
10768 struct ast_frame f
= { AST_FRAME_CONTROL
, AST_CONTROL_FLASH
, };
10769 ast_queue_frame(p
->owner
, &f
);
10771 ast_verbose("* DTMF-relay event received: FLASH\n");
10773 /* send a DTMF event */
10774 struct ast_frame f
= { AST_FRAME_DTMF
, };
10776 f
.subclass
= '0' + event
;
10777 } else if (event
< 11) {
10779 } else if (event
< 12) {
10781 } else if (event
< 16) {
10782 f
.subclass
= 'A' + (event
- 12);
10785 ast_queue_frame(p
->owner
, &f
);
10787 ast_verbose("* DTMF-relay event received: %c\n", f
.subclass
);
10789 transmit_response(p
, "200 OK", req
);
10791 } else if (!strcasecmp(c
, "application/media_control+xml")) {
10792 /* Eh, we'll just assume it's a fast picture update for now */
10794 ast_queue_control(p
->owner
, AST_CONTROL_VIDUPDATE
);
10795 transmit_response(p
, "200 OK", req
);
10797 } else if (!ast_strlen_zero(c
= get_header(req
, "X-ClientCode"))) {
10798 /* Client code (from SNOM phone) */
10799 if (ast_test_flag(&p
->flags
[0], SIP_USECLIENTCODE
)) {
10800 if (p
->owner
&& p
->owner
->cdr
)
10801 ast_cdr_setuserfield(p
->owner
, c
);
10802 if (p
->owner
&& ast_bridged_channel(p
->owner
) && ast_bridged_channel(p
->owner
)->cdr
)
10803 ast_cdr_setuserfield(ast_bridged_channel(p
->owner
), c
);
10804 transmit_response(p
, "200 OK", req
);
10806 transmit_response(p
, "403 Unauthorized", req
);
10810 /* Other type of INFO message, not really understood by Asterisk */
10811 /* if (get_msg_text(buf, sizeof(buf), req)) { */
10813 ast_log(LOG_WARNING
, "Unable to parse INFO message from %s. Content %s\n", p
->callid
, buf
);
10814 transmit_response(p
, "415 Unsupported media type", req
);
10818 /*! \brief Enable SIP Debugging in CLI */
10819 static int sip_do_debug_ip(int fd
, int argc
, char *argv
[])
10821 struct hostent
*hp
;
10822 struct ast_hostent ahp
;
10826 /* sip set debug ip <ip> */
10828 return RESULT_SHOWUSAGE
;
10833 hp
= ast_gethostbyname(arg
, &ahp
);
10835 return RESULT_SHOWUSAGE
;
10837 debugaddr
.sin_family
= AF_INET
;
10838 memcpy(&debugaddr
.sin_addr
, hp
->h_addr
, sizeof(debugaddr
.sin_addr
));
10839 debugaddr
.sin_port
= htons(port
);
10841 ast_cli(fd
, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr
.sin_addr
));
10843 ast_cli(fd
, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr
.sin_addr
), port
);
10845 ast_set_flag(&global_flags
[1], SIP_PAGE2_DEBUG_CONSOLE
);
10847 return RESULT_SUCCESS
;
10850 /*! \brief sip_do_debug_peer: Turn on SIP debugging with peer mask */
10851 static int sip_do_debug_peer(int fd
, int argc
, char *argv
[])
10853 struct sip_peer
*peer
;
10855 return RESULT_SHOWUSAGE
;
10856 peer
= find_peer(argv
[4], NULL
, 1);
10858 if (peer
->addr
.sin_addr
.s_addr
) {
10859 debugaddr
.sin_family
= AF_INET
;
10860 debugaddr
.sin_addr
= peer
->addr
.sin_addr
;
10861 debugaddr
.sin_port
= peer
->addr
.sin_port
;
10862 ast_cli(fd
, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr
.sin_addr
), ntohs(debugaddr
.sin_port
));
10863 ast_set_flag(&global_flags
[1], SIP_PAGE2_DEBUG_CONSOLE
);
10865 ast_cli(fd
, "Unable to get IP address of peer '%s'\n", argv
[4]);
10866 ASTOBJ_UNREF(peer
,sip_destroy_peer
);
10868 ast_cli(fd
, "No such peer '%s'\n", argv
[4]);
10869 return RESULT_SUCCESS
;
10872 /*! \brief Turn on SIP debugging (CLI command) */
10873 static int sip_do_debug(int fd
, int argc
, char *argv
[])
10875 int oldsipdebug
= sipdebug_console
;
10878 return RESULT_SHOWUSAGE
;
10879 else if (strcmp(argv
[3], "ip") == 0)
10880 return sip_do_debug_ip(fd
, argc
, argv
);
10881 else if (strcmp(argv
[3], "peer") == 0)
10882 return sip_do_debug_peer(fd
, argc
, argv
);
10884 return RESULT_SHOWUSAGE
;
10886 ast_set_flag(&global_flags
[1], SIP_PAGE2_DEBUG_CONSOLE
);
10887 memset(&debugaddr
, 0, sizeof(debugaddr
));
10888 ast_cli(fd
, "SIP Debugging %senabled\n", oldsipdebug
? "re-" : "");
10889 return RESULT_SUCCESS
;
10892 static int sip_do_debug_deprecated(int fd
, int argc
, char *argv
[])
10894 int oldsipdebug
= sipdebug_console
;
10895 char *newargv
[6] = { "sip", "set", "debug", NULL
};
10898 return RESULT_SHOWUSAGE
;
10899 else if (strcmp(argv
[2], "ip") == 0) {
10900 newargv
[3] = argv
[2];
10901 newargv
[4] = argv
[3];
10902 return sip_do_debug_ip(fd
, argc
+ 1, newargv
);
10903 } else if (strcmp(argv
[2], "peer") == 0) {
10904 newargv
[3] = argv
[2];
10905 newargv
[4] = argv
[3];
10906 return sip_do_debug_peer(fd
, argc
+ 1, newargv
);
10908 return RESULT_SHOWUSAGE
;
10910 ast_set_flag(&global_flags
[1], SIP_PAGE2_DEBUG_CONSOLE
);
10911 memset(&debugaddr
, 0, sizeof(debugaddr
));
10912 ast_cli(fd
, "SIP Debugging %senabled\n", oldsipdebug
? "re-" : "");
10913 return RESULT_SUCCESS
;
10916 /*! \brief Cli command to send SIP notify to peer */
10917 static int sip_notify(int fd
, int argc
, char *argv
[])
10919 struct ast_variable
*varlist
;
10923 return RESULT_SHOWUSAGE
;
10925 if (!notify_types
) {
10926 ast_cli(fd
, "No %s file found, or no types listed there\n", notify_config
);
10927 return RESULT_FAILURE
;
10930 varlist
= ast_variable_browse(notify_types
, argv
[2]);
10933 ast_cli(fd
, "Unable to find notify type '%s'\n", argv
[2]);
10934 return RESULT_FAILURE
;
10937 for (i
= 3; i
< argc
; i
++) {
10939 struct sip_request req
;
10940 struct ast_variable
*var
;
10942 if (!(p
= sip_alloc(NULL
, NULL
, 0, SIP_NOTIFY
))) {
10943 ast_log(LOG_WARNING
, "Unable to build sip pvt data for notify (memory/socket error)\n");
10944 return RESULT_FAILURE
;
10947 if (create_addr(p
, argv
[i
])) {
10948 /* Maybe they're not registered, etc. */
10950 ast_cli(fd
, "Could not create address for '%s'\n", argv
[i
]);
10954 initreqprep(&req
, p
, SIP_NOTIFY
);
10956 for (var
= varlist
; var
; var
= var
->next
)
10957 add_header(&req
, var
->name
, var
->value
);
10959 /* Recalculate our side, and recalculate Call ID */
10960 if (ast_sip_ouraddrfor(&p
->sa
.sin_addr
, &p
->ourip
))
10961 p
->ourip
= __ourip
;
10963 build_callid_pvt(p
);
10964 ast_cli(fd
, "Sending NOTIFY of type '%s' to '%s'\n", argv
[2], argv
[i
]);
10965 transmit_sip_request(p
, &req
);
10966 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
10969 return RESULT_SUCCESS
;
10972 /*! \brief Disable SIP Debugging in CLI */
10973 static int sip_no_debug(int fd
, int argc
, char *argv
[])
10976 return RESULT_SHOWUSAGE
;
10977 ast_clear_flag(&global_flags
[1], SIP_PAGE2_DEBUG_CONSOLE
);
10978 ast_cli(fd
, "SIP Debugging Disabled\n");
10979 return RESULT_SUCCESS
;
10982 static int sip_no_debug_deprecated(int fd
, int argc
, char *argv
[])
10985 return RESULT_SHOWUSAGE
;
10986 ast_clear_flag(&global_flags
[1], SIP_PAGE2_DEBUG_CONSOLE
);
10987 ast_cli(fd
, "SIP Debugging Disabled\n");
10988 return RESULT_SUCCESS
;
10991 /*! \brief Enable SIP History logging (CLI) */
10992 static int sip_do_history(int fd
, int argc
, char *argv
[])
10995 return RESULT_SHOWUSAGE
;
10997 recordhistory
= TRUE
;
10998 ast_cli(fd
, "SIP History Recording Enabled (use 'sip show history')\n");
10999 return RESULT_SUCCESS
;
11002 /*! \brief Disable SIP History logging (CLI) */
11003 static int sip_no_history(int fd
, int argc
, char *argv
[])
11006 return RESULT_SHOWUSAGE
;
11008 recordhistory
= FALSE
;
11009 ast_cli(fd
, "SIP History Recording Disabled\n");
11010 return RESULT_SUCCESS
;
11013 /*! \brief Authenticate for outbound registration */
11014 static int do_register_auth(struct sip_pvt
*p
, struct sip_request
*req
, char *header
, char *respheader
)
11018 memset(digest
,0,sizeof(digest
));
11019 if (reply_digest(p
, req
, header
, SIP_REGISTER
, digest
, sizeof(digest
))) {
11020 /* There's nothing to use for authentication */
11021 /* No digest challenge in request */
11022 if (sip_debug_test_pvt(p
) && p
->registry
)
11023 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p
->registry
->hostname
);
11024 /* No old challenge */
11027 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
))
11028 append_history(p
, "RegistryAuth", "Try: %d", p
->authtries
);
11029 if (sip_debug_test_pvt(p
) && p
->registry
)
11030 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p
->registry
->hostname
);
11031 return transmit_register(p
->registry
, SIP_REGISTER
, digest
, respheader
);
11034 /*! \brief Add authentication on outbound SIP packet */
11035 static int do_proxy_auth(struct sip_pvt
*p
, struct sip_request
*req
, char *header
, char *respheader
, int sipmethod
, int init
)
11039 if (!p
->options
&& !(p
->options
= ast_calloc(1, sizeof(*p
->options
))))
11043 if (option_debug
> 1)
11044 ast_log(LOG_DEBUG
, "Auth attempt %d on %s\n", p
->authtries
, sip_methods
[sipmethod
].text
);
11045 memset(digest
, 0, sizeof(digest
));
11046 if (reply_digest(p
, req
, header
, sipmethod
, digest
, sizeof(digest
) )) {
11047 /* No way to authenticate */
11050 /* Now we have a reply digest */
11051 p
->options
->auth
= digest
;
11052 p
->options
->authheader
= respheader
;
11053 return transmit_invite(p
, sipmethod
, sipmethod
== SIP_INVITE
, init
);
11056 /*! \brief reply to authentication for outbound registrations
11057 \return Returns -1 if we have no auth
11058 \note This is used for register= servers in sip.conf, SIP proxies we register
11059 with for receiving calls from. */
11060 static int reply_digest(struct sip_pvt
*p
, struct sip_request
*req
, char *header
, int sipmethod
, char *digest
, int digest_len
)
11064 char oldnonce
[256];
11066 /* table of recognised keywords, and places where they should be copied */
11071 { "realm=", ast_string_field_index(p
, realm
) },
11072 { "nonce=", ast_string_field_index(p
, nonce
) },
11073 { "opaque=", ast_string_field_index(p
, opaque
) },
11074 { "qop=", ast_string_field_index(p
, qop
) },
11075 { "domain=", ast_string_field_index(p
, domain
) },
11079 ast_copy_string(tmp
, get_header(req
, header
), sizeof(tmp
));
11080 if (ast_strlen_zero(tmp
))
11082 if (strncasecmp(tmp
, "Digest ", strlen("Digest "))) {
11083 ast_log(LOG_WARNING
, "missing Digest.\n");
11086 c
= tmp
+ strlen("Digest ");
11087 ast_copy_string(oldnonce
, p
->nonce
, sizeof(oldnonce
));
11088 while (c
&& *(c
= ast_skip_blanks(c
))) { /* lookup for keys */
11089 for (i
= keys
; i
->key
!= NULL
; i
++) {
11090 char *src
, *separator
;
11091 if (strncasecmp(c
, i
->key
, strlen(i
->key
)) != 0)
11093 /* Found. Skip keyword, take text in quotes or up to the separator. */
11094 c
+= strlen(i
->key
);
11102 strsep(&c
, separator
); /* clear separator and move ptr */
11103 ast_string_field_index_set(p
, i
->field_index
, src
);
11106 if (i
->key
== NULL
) /* not found, try ',' */
11109 /* Reset nonce count */
11110 if (strcmp(p
->nonce
, oldnonce
))
11113 /* Save auth data for following registrations */
11115 struct sip_registry
*r
= p
->registry
;
11117 if (strcmp(r
->nonce
, p
->nonce
)) {
11118 ast_string_field_set(r
, realm
, p
->realm
);
11119 ast_string_field_set(r
, nonce
, p
->nonce
);
11120 ast_string_field_set(r
, domain
, p
->domain
);
11121 ast_string_field_set(r
, opaque
, p
->opaque
);
11122 ast_string_field_set(r
, qop
, p
->qop
);
11126 return build_reply_digest(p
, sipmethod
, digest
, digest_len
);
11129 /*! \brief Build reply digest
11130 \return Returns -1 if we have no auth
11131 \note Build digest challenge for authentication of peers (for registration)
11132 and users (for calls). Also used for authentication of CANCEL and BYE
11134 static int build_reply_digest(struct sip_pvt
*p
, int method
, char* digest
, int digest_len
)
11141 char resp_hash
[256];
11144 const char *username
;
11145 const char *secret
;
11146 const char *md5secret
;
11147 struct sip_auth
*auth
= NULL
; /* Realm authentication */
11149 if (!ast_strlen_zero(p
->domain
))
11150 ast_copy_string(uri
, p
->domain
, sizeof(uri
));
11151 else if (!ast_strlen_zero(p
->uri
))
11152 ast_copy_string(uri
, p
->uri
, sizeof(uri
));
11154 snprintf(uri
, sizeof(uri
), "sip:%s@%s",p
->username
, ast_inet_ntoa(p
->sa
.sin_addr
));
11156 snprintf(cnonce
, sizeof(cnonce
), "%08lx", ast_random());
11158 /* Check if we have separate auth credentials */
11159 if ((auth
= find_realm_authentication(authl
, p
->realm
))) {
11160 ast_log(LOG_WARNING
, "use realm [%s] from peer [%s][%s]\n",
11161 auth
->username
, p
->peername
, p
->username
);
11162 username
= auth
->username
;
11163 secret
= auth
->secret
;
11164 md5secret
= auth
->md5secret
;
11166 ast_log(LOG_DEBUG
,"Using realm %s authentication for call %s\n", p
->realm
, p
->callid
);
11168 /* No authentication, use peer or register= config */
11169 username
= p
->authname
;
11170 secret
= p
->peersecret
;
11171 md5secret
= p
->peermd5secret
;
11173 if (ast_strlen_zero(username
)) /* We have no authentication */
11176 /* Calculate SIP digest response */
11177 snprintf(a1
,sizeof(a1
),"%s:%s:%s", username
, p
->realm
, secret
);
11178 snprintf(a2
,sizeof(a2
),"%s:%s", sip_methods
[method
].text
, uri
);
11179 if (!ast_strlen_zero(md5secret
))
11180 ast_copy_string(a1_hash
, md5secret
, sizeof(a1_hash
));
11182 ast_md5_hash(a1_hash
,a1
);
11183 ast_md5_hash(a2_hash
,a2
);
11186 if (!ast_strlen_zero(p
->qop
))
11187 snprintf(resp
,sizeof(resp
),"%s:%s:%08x:%s:%s:%s", a1_hash
, p
->nonce
, p
->noncecount
, cnonce
, "auth", a2_hash
);
11189 snprintf(resp
,sizeof(resp
),"%s:%s:%s", a1_hash
, p
->nonce
, a2_hash
);
11190 ast_md5_hash(resp_hash
, resp
);
11191 /* XXX We hard code our qop to "auth" for now. XXX */
11192 if (!ast_strlen_zero(p
->qop
))
11193 snprintf(digest
, digest_len
, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\", opaque=\"%s\", qop=auth, cnonce=\"%s\", nc=%08x", username
, p
->realm
, uri
, p
->nonce
, resp_hash
, p
->opaque
, cnonce
, p
->noncecount
);
11195 snprintf(digest
, digest_len
, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\", opaque=\"%s\"", username
, p
->realm
, uri
, p
->nonce
, resp_hash
, p
->opaque
);
11197 append_history(p
, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username
, p
->realm
, p
->noncecount
);
11202 static char show_domains_usage
[] =
11203 "Usage: sip show domains\n"
11204 " Lists all configured SIP local domains.\n"
11205 " Asterisk only responds to SIP messages to local domains.\n";
11207 static char notify_usage
[] =
11208 "Usage: sip notify <type> <peer> [<peer>...]\n"
11209 " Send a NOTIFY message to a SIP peer or peers\n"
11210 " Message types are defined in sip_notify.conf\n";
11212 static char show_users_usage
[] =
11213 "Usage: sip show users [like <pattern>]\n"
11214 " Lists all known SIP users.\n"
11215 " Optional regular expression pattern is used to filter the user list.\n";
11217 static char show_user_usage
[] =
11218 "Usage: sip show user <name> [load]\n"
11219 " Shows all details on one SIP user and the current status.\n"
11220 " Option \"load\" forces lookup of peer in realtime storage.\n";
11222 static char show_inuse_usage
[] =
11223 "Usage: sip show inuse [all]\n"
11224 " List all SIP users and peers usage counters and limits.\n"
11225 " Add option \"all\" to show all devices, not only those with a limit.\n";
11227 static char show_channels_usage
[] =
11228 "Usage: sip show channels\n"
11229 " Lists all currently active SIP channels.\n";
11231 static char show_channel_usage
[] =
11232 "Usage: sip show channel <channel>\n"
11233 " Provides detailed status on a given SIP channel.\n";
11235 static char show_history_usage
[] =
11236 "Usage: sip show history <channel>\n"
11237 " Provides detailed dialog history on a given SIP channel.\n";
11239 static char show_peers_usage
[] =
11240 "Usage: sip show peers [like <pattern>]\n"
11241 " Lists all known SIP peers.\n"
11242 " Optional regular expression pattern is used to filter the peer list.\n";
11244 static char show_peer_usage
[] =
11245 "Usage: sip show peer <name> [load]\n"
11246 " Shows all details on one SIP peer and the current status.\n"
11247 " Option \"load\" forces lookup of peer in realtime storage.\n";
11249 static char prune_realtime_usage
[] =
11250 "Usage: sip prune realtime [peer|user] [<name>|all|like <pattern>]\n"
11251 " Prunes object(s) from the cache.\n"
11252 " Optional regular expression pattern is used to filter the objects.\n";
11254 static char show_reg_usage
[] =
11255 "Usage: sip show registry\n"
11256 " Lists all registration requests and status.\n";
11258 static char debug_usage
[] =
11259 "Usage: sip set debug\n"
11260 " Enables dumping of SIP packets for debugging purposes\n\n"
11261 " sip set debug ip <host[:PORT]>\n"
11262 " Enables dumping of SIP packets to and from host.\n\n"
11263 " sip set debug peer <peername>\n"
11264 " Enables dumping of SIP packets to and from host.\n"
11265 " Require peer to be registered.\n";
11267 static char no_debug_usage
[] =
11268 "Usage: sip set debug off\n"
11269 " Disables dumping of SIP packets for debugging purposes\n";
11271 static char no_history_usage
[] =
11272 "Usage: sip history off\n"
11273 " Disables recording of SIP dialog history for debugging purposes\n";
11275 static char history_usage
[] =
11276 "Usage: sip history\n"
11277 " Enables recording of SIP dialog history for debugging purposes.\n"
11278 "Use 'sip show history' to view the history of a call number.\n";
11280 static char sip_reload_usage
[] =
11281 "Usage: sip reload\n"
11282 " Reloads SIP configuration from sip.conf\n";
11284 static char show_subscriptions_usage
[] =
11285 "Usage: sip show subscriptions\n"
11286 " Lists active SIP subscriptions for extension states\n";
11288 static char show_objects_usage
[] =
11289 "Usage: sip show objects\n"
11290 " Lists status of known SIP objects\n";
11292 static char show_settings_usage
[] =
11293 "Usage: sip show settings\n"
11294 " Provides detailed list of the configuration of the SIP channel.\n";
11296 /*! \brief Read SIP header (dialplan function) */
11297 static int func_header_read(struct ast_channel
*chan
, char *function
, char *data
, char *buf
, size_t len
)
11300 const char *content
= NULL
;
11301 AST_DECLARE_APP_ARGS(args
,
11302 AST_APP_ARG(header
);
11303 AST_APP_ARG(number
);
11305 int i
, number
, start
= 0;
11307 if (ast_strlen_zero(data
)) {
11308 ast_log(LOG_WARNING
, "This function requires a header name.\n");
11312 ast_channel_lock(chan
);
11313 if (chan
->tech
!= &sip_tech
&& chan
->tech
!= &sip_tech_info
) {
11314 ast_log(LOG_WARNING
, "This function can only be used on SIP channels.\n");
11315 ast_channel_unlock(chan
);
11319 AST_STANDARD_APP_ARGS(args
, data
);
11320 if (!args
.number
) {
11323 sscanf(args
.number
, "%d", &number
);
11328 p
= chan
->tech_pvt
;
11330 /* If there is no private structure, this channel is no longer alive */
11332 ast_channel_unlock(chan
);
11336 for (i
= 0; i
< number
; i
++)
11337 content
= __get_header(&p
->initreq
, args
.header
, &start
);
11339 if (ast_strlen_zero(content
)) {
11340 ast_channel_unlock(chan
);
11344 ast_copy_string(buf
, content
, len
);
11345 ast_channel_unlock(chan
);
11350 static struct ast_custom_function sip_header_function
= {
11351 .name
= "SIP_HEADER",
11352 .synopsis
= "Gets the specified SIP header",
11353 .syntax
= "SIP_HEADER(<name>[,<number>])",
11354 .desc
= "Since there are several headers (such as Via) which can occur multiple\n"
11355 "times, SIP_HEADER takes an optional second argument to specify which header with\n"
11356 "that name to retrieve. Headers start at offset 1.\n",
11357 .read
= func_header_read
,
11360 /*! \brief Dial plan function to check if domain is local */
11361 static int func_check_sipdomain(struct ast_channel
*chan
, char *cmd
, char *data
, char *buf
, size_t len
)
11363 if (ast_strlen_zero(data
)) {
11364 ast_log(LOG_WARNING
, "CHECKSIPDOMAIN requires an argument - A domain name\n");
11367 if (check_sip_domain(data
, NULL
, 0))
11368 ast_copy_string(buf
, data
, len
);
11374 static struct ast_custom_function checksipdomain_function
= {
11375 .name
= "CHECKSIPDOMAIN",
11376 .synopsis
= "Checks if domain is a local domain",
11377 .syntax
= "CHECKSIPDOMAIN(<domain|IP>)",
11378 .read
= func_check_sipdomain
,
11379 .desc
= "This function checks if the domain in the argument is configured\n"
11380 "as a local SIP domain that this Asterisk server is configured to handle.\n"
11381 "Returns the domain name if it is locally handled, otherwise an empty string.\n"
11382 "Check the domain= configuration in sip.conf\n",
11385 /*! \brief ${SIPPEER()} Dialplan function - reads peer data */
11386 static int function_sippeer(struct ast_channel
*chan
, char *cmd
, char *data
, char *buf
, size_t len
)
11388 struct sip_peer
*peer
;
11391 if ((colname
= strchr(data
, ':'))) /*! \todo Will be deprecated after 1.4 */
11393 else if ((colname
= strchr(data
, '|')))
11398 if (!(peer
= find_peer(data
, NULL
, 1)))
11401 if (!strcasecmp(colname
, "ip")) {
11402 ast_copy_string(buf
, peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(peer
->addr
.sin_addr
) : "", len
);
11403 } else if (!strcasecmp(colname
, "status")) {
11404 peer_status(peer
, buf
, len
);
11405 } else if (!strcasecmp(colname
, "language")) {
11406 ast_copy_string(buf
, peer
->language
, len
);
11407 } else if (!strcasecmp(colname
, "regexten")) {
11408 ast_copy_string(buf
, peer
->regexten
, len
);
11409 } else if (!strcasecmp(colname
, "limit")) {
11410 snprintf(buf
, len
, "%d", peer
->call_limit
);
11411 } else if (!strcasecmp(colname
, "curcalls")) {
11412 snprintf(buf
, len
, "%d", peer
->inUse
);
11413 } else if (!strcasecmp(colname
, "accountcode")) {
11414 ast_copy_string(buf
, peer
->accountcode
, len
);
11415 } else if (!strcasecmp(colname
, "useragent")) {
11416 ast_copy_string(buf
, peer
->useragent
, len
);
11417 } else if (!strcasecmp(colname
, "mailbox")) {
11418 ast_copy_string(buf
, peer
->mailbox
, len
);
11419 } else if (!strcasecmp(colname
, "context")) {
11420 ast_copy_string(buf
, peer
->context
, len
);
11421 } else if (!strcasecmp(colname
, "expire")) {
11422 snprintf(buf
, len
, "%d", peer
->expire
);
11423 } else if (!strcasecmp(colname
, "dynamic")) {
11424 ast_copy_string(buf
, (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
) ? "yes" : "no"), len
);
11425 } else if (!strcasecmp(colname
, "callerid_name")) {
11426 ast_copy_string(buf
, peer
->cid_name
, len
);
11427 } else if (!strcasecmp(colname
, "callerid_num")) {
11428 ast_copy_string(buf
, peer
->cid_num
, len
);
11429 } else if (!strcasecmp(colname
, "codecs")) {
11430 ast_getformatname_multiple(buf
, len
-1, peer
->capability
);
11431 } else if (!strncasecmp(colname
, "codec[", 6)) {
11433 int index
= 0, codec
= 0;
11435 codecnum
= colname
+ 6; /* move past the '[' */
11436 codecnum
= strsep(&codecnum
, "]"); /* trim trailing ']' if any */
11437 index
= atoi(codecnum
);
11438 if((codec
= ast_codec_pref_index(&peer
->prefs
, index
))) {
11439 ast_copy_string(buf
, ast_getformatname(codec
), len
);
11443 ASTOBJ_UNREF(peer
, sip_destroy_peer
);
11448 /*! \brief Structure to declare a dialplan function: SIPPEER */
11449 struct ast_custom_function sippeer_function
= {
11451 .synopsis
= "Gets SIP peer information",
11452 .syntax
= "SIPPEER(<peername>[|item])",
11453 .read
= function_sippeer
,
11454 .desc
= "Valid items are:\n"
11455 "- ip (default) The IP address.\n"
11456 "- mailbox The configured mailbox.\n"
11457 "- context The configured context.\n"
11458 "- expire The epoch time of the next expire.\n"
11459 "- dynamic Is it dynamic? (yes/no).\n"
11460 "- callerid_name The configured Caller ID name.\n"
11461 "- callerid_num The configured Caller ID number.\n"
11462 "- codecs The configured codecs.\n"
11463 "- status Status (if qualify=yes).\n"
11464 "- regexten Registration extension\n"
11465 "- limit Call limit (call-limit)\n"
11466 "- curcalls Current amount of calls \n"
11467 " Only available if call-limit is set\n"
11468 "- language Default language for peer\n"
11469 "- accountcode Account code for this peer\n"
11470 "- useragent Current user agent id for peer\n"
11471 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
11475 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
11476 static int function_sipchaninfo_read(struct ast_channel
*chan
, char *cmd
, char *data
, char *buf
, size_t len
)
11483 ast_log(LOG_WARNING
, "This function requires a parameter name.\n");
11487 ast_channel_lock(chan
);
11488 if (chan
->tech
!= &sip_tech
&& chan
->tech
!= &sip_tech_info
) {
11489 ast_log(LOG_WARNING
, "This function can only be used on SIP channels.\n");
11490 ast_channel_unlock(chan
);
11494 p
= chan
->tech_pvt
;
11496 /* If there is no private structure, this channel is no longer alive */
11498 ast_channel_unlock(chan
);
11502 if (!strcasecmp(data
, "peerip")) {
11503 ast_copy_string(buf
, p
->sa
.sin_addr
.s_addr
? ast_inet_ntoa(p
->sa
.sin_addr
) : "", len
);
11504 } else if (!strcasecmp(data
, "recvip")) {
11505 ast_copy_string(buf
, p
->recv
.sin_addr
.s_addr
? ast_inet_ntoa(p
->recv
.sin_addr
) : "", len
);
11506 } else if (!strcasecmp(data
, "from")) {
11507 ast_copy_string(buf
, p
->from
, len
);
11508 } else if (!strcasecmp(data
, "uri")) {
11509 ast_copy_string(buf
, p
->uri
, len
);
11510 } else if (!strcasecmp(data
, "useragent")) {
11511 ast_copy_string(buf
, p
->useragent
, len
);
11512 } else if (!strcasecmp(data
, "peername")) {
11513 ast_copy_string(buf
, p
->peername
, len
);
11514 } else if (!strcasecmp(data
, "t38passthrough")) {
11515 if (p
->t38
.state
== T38_DISABLED
)
11516 ast_copy_string(buf
, "0", sizeof("0"));
11517 else /* T38 is offered or enabled in this call */
11518 ast_copy_string(buf
, "1", sizeof("1"));
11520 ast_channel_unlock(chan
);
11523 ast_channel_unlock(chan
);
11528 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
11529 static struct ast_custom_function sipchaninfo_function
= {
11530 .name
= "SIPCHANINFO",
11531 .synopsis
= "Gets the specified SIP parameter from the current channel",
11532 .syntax
= "SIPCHANINFO(item)",
11533 .read
= function_sipchaninfo_read
,
11534 .desc
= "Valid items are:\n"
11535 "- peerip The IP address of the peer.\n"
11536 "- recvip The source IP address of the peer.\n"
11537 "- from The URI from the From: header.\n"
11538 "- uri The URI from the Contact: header.\n"
11539 "- useragent The useragent.\n"
11540 "- peername The name of the peer.\n"
11541 "- t38passthrough 1 if T38 is offered or enabled in this channel, otherwise 0\n"
11544 /*! \brief Parse 302 Moved temporalily response */
11545 static void parse_moved_contact(struct sip_pvt
*p
, struct sip_request
*req
)
11551 ast_copy_string(tmp
, get_header(req
, "Contact"), sizeof(tmp
));
11552 s
= get_in_brackets(tmp
);
11553 s
= strsep(&s
, ";"); /* strip ; and beyond */
11554 if (ast_test_flag(&p
->flags
[0], SIP_PROMISCREDIR
)) {
11555 if (!strncasecmp(s
, "sip:", 4))
11557 e
= strchr(s
, '/');
11561 ast_log(LOG_DEBUG
, "Found promiscuous redirection to 'SIP/%s'\n", s
);
11563 ast_string_field_build(p
->owner
, call_forward
, "SIP/%s", s
);
11565 e
= strchr(tmp
, '@');
11570 /* No username part */
11573 e
= strchr(tmp
, '/');
11576 if (!strncasecmp(s
, "sip:", 4))
11578 if (option_debug
> 1)
11579 ast_log(LOG_DEBUG
, "Received 302 Redirect to extension '%s' (domain %s)\n", s
, domain
);
11581 pbx_builtin_setvar_helper(p
->owner
, "SIPDOMAIN", domain
);
11582 ast_string_field_set(p
->owner
, call_forward
, s
);
11587 /*! \brief Check pending actions on SIP call */
11588 static void check_pendings(struct sip_pvt
*p
)
11590 if (ast_test_flag(&p
->flags
[0], SIP_PENDINGBYE
)) {
11591 /* if we can't BYE, then this is really a pending CANCEL */
11592 if (p
->invitestate
== INV_PROCEEDING
|| p
->invitestate
== INV_EARLY_MEDIA
)
11593 transmit_request(p
, SIP_CANCEL
, p
->ocseq
, XMIT_RELIABLE
, FALSE
);
11594 /* Actually don't destroy us yet, wait for the 487 on our original
11595 INVITE, but do set an autodestruct just in case we never get it. */
11597 transmit_request_with_auth(p
, SIP_BYE
, 0, XMIT_RELIABLE
, TRUE
);
11598 ast_clear_flag(&p
->flags
[0], SIP_PENDINGBYE
);
11599 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
11600 } else if (ast_test_flag(&p
->flags
[0], SIP_NEEDREINVITE
)) {
11602 ast_log(LOG_DEBUG
, "Sending pending reinvite on '%s'\n", p
->callid
);
11603 /* Didn't get to reinvite yet, so do it now */
11604 transmit_reinvite_with_sdp(p
);
11605 ast_clear_flag(&p
->flags
[0], SIP_NEEDREINVITE
);
11609 /*! \brief Handle SIP response to INVITE dialogue */
11610 static void handle_response_invite(struct sip_pvt
*p
, int resp
, char *rest
, struct sip_request
*req
, int seqno
)
11612 int outgoing
= ast_test_flag(&p
->flags
[0], SIP_OUTGOING
);
11614 int reinvite
= (p
->owner
&& p
->owner
->_state
== AST_STATE_UP
);
11615 struct ast_channel
*bridgepeer
= NULL
;
11617 if (option_debug
> 3) {
11619 ast_log(LOG_DEBUG
, "SIP response %d to RE-invite on %s call %s\n", resp
, outgoing
? "outgoing" : "incoming", p
->callid
);
11621 ast_log(LOG_DEBUG
, "SIP response %d to standard invite\n", resp
);
11624 if (ast_test_flag(&p
->flags
[0], SIP_ALREADYGONE
)) { /* This call is already gone */
11626 ast_log(LOG_DEBUG
, "Got response on call that is already terminated: %s (ignoring)\n", p
->callid
);
11630 /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
11631 if (p
->initid
> -1) {
11632 /* Don't auto congest anymore since we've gotten something useful back */
11633 ast_sched_del(sched
, p
->initid
);
11637 /* RFC3261 says we must treat every 1xx response (but not 100)
11638 that we don't recognize as if it was 183.
11640 if (resp
> 100 && resp
< 200 && resp
!=101 && resp
!= 180 && resp
!= 183)
11643 /* Any response between 100 and 199 is PROCEEDING */
11644 if (resp
>= 100 && resp
< 200 && p
->invitestate
== INV_CALLING
)
11645 p
->invitestate
= INV_PROCEEDING
;
11647 /* Final response, not 200 ? */
11648 if (resp
>= 300 && (p
->invitestate
== INV_CALLING
|| p
->invitestate
== INV_PROCEEDING
|| p
->invitestate
== INV_EARLY_MEDIA
))
11649 p
->invitestate
= INV_COMPLETED
;
11653 case 100: /* Trying */
11654 case 101: /* Dialog establishment */
11655 if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
11656 sip_cancel_destroy(p
);
11660 case 180: /* 180 Ringing */
11661 if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
11662 sip_cancel_destroy(p
);
11663 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && p
->owner
) {
11664 ast_queue_control(p
->owner
, AST_CONTROL_RINGING
);
11665 if (p
->owner
->_state
!= AST_STATE_UP
) {
11666 ast_setstate(p
->owner
, AST_STATE_RINGING
);
11669 if (find_sdp(req
)) {
11670 p
->invitestate
= INV_EARLY_MEDIA
;
11671 res
= process_sdp(p
, req
);
11672 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && p
->owner
) {
11673 /* Queue a progress frame only if we have SDP in 180 */
11674 ast_queue_control(p
->owner
, AST_CONTROL_PROGRESS
);
11680 case 183: /* Session progress */
11681 if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
11682 sip_cancel_destroy(p
);
11683 /* Ignore 183 Session progress without SDP */
11684 if (find_sdp(req
)) {
11685 p
->invitestate
= INV_EARLY_MEDIA
;
11686 res
= process_sdp(p
, req
);
11687 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && p
->owner
) {
11688 /* Queue a progress frame */
11689 ast_queue_control(p
->owner
, AST_CONTROL_PROGRESS
);
11695 case 200: /* 200 OK on invite - someone's answering our call */
11696 if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
11697 sip_cancel_destroy(p
);
11699 if (find_sdp(req
)) {
11700 if ((res
= process_sdp(p
, req
)) && !ast_test_flag(req
, SIP_PKT_IGNORE
))
11702 /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
11703 /* For re-invites, we try to recover */
11704 ast_set_flag(&p
->flags
[0], SIP_PENDINGBYE
);
11707 /* Parse contact header for continued conversation */
11708 /* When we get 200 OK, we know which device (and IP) to contact for this call */
11709 /* This is important when we have a SIP proxy between us and the phone */
11711 update_call_counter(p
, DEC_CALL_RINGING
);
11712 parse_ok_contact(p
, req
);
11713 if(set_address_from_contact(p
)) {
11714 /* Bad contact - we don't know how to reach this device */
11715 /* We need to ACK, but then send a bye */
11716 /* OEJ: Possible issue that may need a check:
11717 If we have a proxy route between us and the device,
11718 should we care about resolving the contact
11719 or should we just send it?
11721 if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
11722 ast_set_flag(&p
->flags
[0], SIP_PENDINGBYE
);
11725 /* Save Record-Route for any later requests we make on this dialogue */
11726 build_route(p
, req
, 1);
11729 if (p
->owner
&& (p
->owner
->_state
== AST_STATE_UP
) && (bridgepeer
= ast_bridged_channel(p
->owner
))) { /* if this is a re-invite */
11730 struct sip_pvt
*bridgepvt
= NULL
;
11732 if (!bridgepeer
->tech
) {
11733 ast_log(LOG_WARNING
, "Ooooh.. no tech! That's REALLY bad\n");
11736 if (bridgepeer
->tech
== &sip_tech
|| bridgepeer
->tech
== &sip_tech_info
) {
11737 bridgepvt
= (struct sip_pvt
*)(bridgepeer
->tech_pvt
);
11738 if (bridgepvt
->udptl
) {
11739 if (p
->t38
.state
== T38_PEER_REINVITE
) {
11740 sip_handle_t38_reinvite(bridgepeer
, p
, 0);
11741 ast_rtp_set_rtptimers_onhold(p
->rtp
);
11743 ast_rtp_set_rtptimers_onhold(p
->vrtp
); /* Turn off RTP timers while we send fax */
11744 } else if (p
->t38
.state
== T38_DISABLED
&& bridgepeer
&& (bridgepvt
->t38
.state
== T38_ENABLED
)) {
11745 ast_log(LOG_WARNING
, "RTP re-inivte after T38 session not handled yet !\n");
11746 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
11747 /* XXXX Should we really destroy this session here, without any response at all??? */
11748 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
11751 if (option_debug
> 1)
11752 ast_log(LOG_DEBUG
, "Strange... The other side of the bridge does not have a udptl struct\n");
11753 ast_mutex_lock(&bridgepvt
->lock
);
11754 bridgepvt
->t38
.state
= T38_DISABLED
;
11755 ast_mutex_unlock(&bridgepvt
->lock
);
11757 ast_log(LOG_DEBUG
,"T38 state changed to %d on channel %s\n", bridgepvt
->t38
.state
, bridgepeer
->tech
->type
);
11758 p
->t38
.state
= T38_DISABLED
;
11759 if (option_debug
> 1)
11760 ast_log(LOG_DEBUG
,"T38 state changed to %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>");
11763 /* Other side is not a SIP channel */
11764 if (option_debug
> 1)
11765 ast_log(LOG_DEBUG
, "Strange... The other side of the bridge is not a SIP channel\n");
11766 p
->t38
.state
= T38_DISABLED
;
11767 if (option_debug
> 1)
11768 ast_log(LOG_DEBUG
,"T38 state changed to %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>");
11771 if ((p
->t38
.state
== T38_LOCAL_REINVITE
) || (p
->t38
.state
== T38_LOCAL_DIRECT
)) {
11772 /* If there was T38 reinvite and we are supposed to answer with 200 OK than this should set us to T38 negotiated mode */
11773 p
->t38
.state
= T38_ENABLED
;
11775 ast_log(LOG_DEBUG
, "T38 changed state to %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>");
11778 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && p
->owner
) {
11780 ast_queue_control(p
->owner
, AST_CONTROL_ANSWER
);
11781 } else { /* RE-invite */
11782 ast_queue_frame(p
->owner
, &ast_null_frame
);
11785 /* It's possible we're getting an 200 OK after we've tried to disconnect
11786 by sending CANCEL */
11787 /* First send ACK, then send bye */
11788 if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
11789 ast_set_flag(&p
->flags
[0], SIP_PENDINGBYE
);
11791 /* If I understand this right, the branch is different for a non-200 ACK only */
11792 p
->invitestate
= INV_TERMINATED
;
11793 transmit_request(p
, SIP_ACK
, seqno
, XMIT_UNRELIABLE
, TRUE
);
11796 case 407: /* Proxy authentication */
11797 case 401: /* Www auth */
11799 transmit_request(p
, SIP_ACK
, seqno
, XMIT_UNRELIABLE
, FALSE
);
11801 p
->options
->auth_type
= (resp
== 401 ? WWW_AUTH
: PROXY_AUTH
);
11804 ast_string_field_free(p
, theirtag
); /* forget their old tag, so we don't match tags when getting response */
11805 if (!ast_test_flag(req
, SIP_PKT_IGNORE
)) {
11806 char *authenticate
= (resp
== 401 ? "WWW-Authenticate" : "Proxy-Authenticate");
11807 char *authorization
= (resp
== 401 ? "Authorization" : "Proxy-Authorization");
11808 if (p
->authtries
< MAX_AUTHTRIES
)
11809 p
->invitestate
= INV_CALLING
;
11810 if ((p
->authtries
== MAX_AUTHTRIES
) || do_proxy_auth(p
, req
, authenticate
, authorization
, SIP_INVITE
, 1)) {
11811 ast_log(LOG_NOTICE
, "Failed to authenticate on INVITE to '%s'\n", get_header(&p
->initreq
, "From"));
11812 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11813 sip_alreadygone(p
);
11815 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
11820 case 403: /* Forbidden */
11822 transmit_request(p
, SIP_ACK
, seqno
, XMIT_UNRELIABLE
, FALSE
);
11823 ast_log(LOG_WARNING
, "Received response: \"Forbidden\" from '%s'\n", get_header(&p
->initreq
, "From"));
11824 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && p
->owner
)
11825 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
11826 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11827 sip_alreadygone(p
);
11830 case 404: /* Not found */
11831 transmit_request(p
, SIP_ACK
, seqno
, XMIT_UNRELIABLE
, FALSE
);
11832 if (p
->owner
&& !ast_test_flag(req
, SIP_PKT_IGNORE
))
11833 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
11834 sip_alreadygone(p
);
11837 case 481: /* Call leg does not exist */
11838 /* Could be REFER caused INVITE with replaces */
11839 ast_log(LOG_WARNING
, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p
->callid
);
11840 transmit_request(p
, SIP_ACK
, seqno
, XMIT_UNRELIABLE
, FALSE
);
11842 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
11843 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
11845 case 487: /* Cancelled transaction */
11846 /* We have sent CANCEL on an outbound INVITE
11847 This transaction is already scheduled to be killed by sip_hangup().
11849 transmit_request(p
, SIP_ACK
, seqno
, 0, 0);
11850 if (p
->owner
&& !ast_test_flag(req
, SIP_PKT_IGNORE
))
11851 ast_queue_hangup(p
->owner
);
11852 else if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
11853 update_call_counter(p
, DEC_CALL_LIMIT
);
11855 case 488: /* Not acceptable here */
11856 transmit_request(p
, SIP_ACK
, seqno
, XMIT_UNRELIABLE
, FALSE
);
11857 if (reinvite
&& p
->udptl
) {
11858 /* If this is a T.38 call, we should go back to
11859 audio. If this is an audio call - something went
11860 terribly wrong since we don't renegotiate codecs,
11863 p
->t38
.state
= T38_DISABLED
;
11864 /* Try to reset RTP timers */
11865 ast_rtp_set_rtptimers_onhold(p
->rtp
);
11866 ast_log(LOG_ERROR
, "Got error on T.38 re-invite. Bad configuration. Peer needs to have T.38 disabled.\n");
11868 /*! \bug Is there any way we can go back to the audio call on both
11871 /* While figuring that out, hangup the call */
11872 if (p
->owner
&& !ast_test_flag(req
, SIP_PKT_IGNORE
))
11873 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
11874 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11876 /* We can't set up this call, so give up */
11877 if (p
->owner
&& !ast_test_flag(req
, SIP_PKT_IGNORE
))
11878 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
11879 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11882 case 491: /* Pending */
11883 /* we really should have to wait a while, then retransmit */
11884 /* We should support the retry-after at some point */
11885 /* At this point, we treat this as a congestion */
11886 transmit_request(p
, SIP_ACK
, seqno
, XMIT_UNRELIABLE
, FALSE
);
11887 if (p
->owner
&& !ast_test_flag(req
, SIP_PKT_IGNORE
))
11888 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
11889 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11892 case 501: /* Not implemented */
11893 transmit_request(p
, SIP_ACK
, seqno
, 0, 0);
11895 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
11900 /* \brief Handle SIP response in REFER transaction
11901 We've sent a REFER, now handle responses to it
11903 static void handle_response_refer(struct sip_pvt
*p
, int resp
, char *rest
, struct sip_request
*req
, int seqno
)
11905 char *auth
= "Proxy-Authenticate";
11906 char *auth2
= "Proxy-Authorization";
11908 /* If no refer structure exists, then do nothing */
11913 case 202: /* Transfer accepted */
11914 /* We need to do something here */
11915 /* The transferee is now sending INVITE to target */
11916 p
->refer
->status
= REFER_ACCEPTED
;
11917 /* Now wait for next message */
11918 if (option_debug
> 2)
11919 ast_log(LOG_DEBUG
, "Got 202 accepted on transfer\n");
11920 /* We should hang along, waiting for NOTIFY's here */
11923 case 401: /* Not www-authorized on SIP method */
11924 case 407: /* Proxy auth */
11925 if (ast_strlen_zero(p
->authname
)) {
11926 ast_log(LOG_WARNING
, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
11927 ast_inet_ntoa(p
->recv
.sin_addr
), ntohs(p
->recv
.sin_port
));
11928 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11931 auth
= "WWW-Authenticate";
11932 auth2
= "Authorization";
11934 if ((p
->authtries
> 1) || do_proxy_auth(p
, req
, auth
, auth2
, SIP_REFER
, 0)) {
11935 ast_log(LOG_NOTICE
, "Failed to authenticate on REFER to '%s'\n", get_header(&p
->initreq
, "From"));
11936 p
->refer
->status
= REFER_NOAUTH
;
11937 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11940 case 481: /* Call leg does not exist */
11942 /* A transfer with Replaces did not work */
11943 /* OEJ: We should Set flag, cancel the REFER, go back
11944 to original call - but right now we can't */
11945 ast_log(LOG_WARNING
, "Remote host can't match REFER request to call '%s'. Giving up.\n", p
->callid
);
11947 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
11948 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11951 case 500: /* Server error */
11952 case 501: /* Method not implemented */
11953 /* Return to the current call onhold */
11954 /* Status flag needed to be reset */
11955 ast_log(LOG_NOTICE
, "SIP transfer to %s failed, call miserably fails. \n", p
->refer
->refer_to
);
11956 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11957 p
->refer
->status
= REFER_FAILED
;
11959 case 603: /* Transfer declined */
11960 ast_log(LOG_NOTICE
, "SIP transfer to %s declined, call miserably fails. \n", p
->refer
->refer_to
);
11961 p
->refer
->status
= REFER_FAILED
;
11962 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11967 /*! \brief Handle responses on REGISTER to services */
11968 static int handle_response_register(struct sip_pvt
*p
, int resp
, char *rest
, struct sip_request
*req
, int ignore
, int seqno
)
11970 int expires
, expires_ms
;
11971 struct sip_registry
*r
;
11975 case 401: /* Unauthorized */
11976 if ((p
->authtries
== MAX_AUTHTRIES
) || do_register_auth(p
, req
, "WWW-Authenticate", "Authorization")) {
11977 ast_log(LOG_NOTICE
, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p
->registry
->username
, p
->registry
->hostname
, p
->authtries
);
11978 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11981 case 403: /* Forbidden */
11982 ast_log(LOG_WARNING
, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p
->registry
->username
, p
->registry
->hostname
);
11983 if (global_regattempts_max
)
11984 p
->registry
->regattempts
= global_regattempts_max
+1;
11985 ast_sched_del(sched
, r
->timeout
);
11987 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11989 case 404: /* Not found */
11990 ast_log(LOG_WARNING
, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p
->registry
->username
,p
->registry
->hostname
);
11991 if (global_regattempts_max
)
11992 p
->registry
->regattempts
= global_regattempts_max
+1;
11993 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11995 ast_sched_del(sched
, r
->timeout
);
11998 case 407: /* Proxy auth */
11999 if ((p
->authtries
== MAX_AUTHTRIES
) || do_register_auth(p
, req
, "Proxy-Authenticate", "Proxy-Authorization")) {
12000 ast_log(LOG_NOTICE
, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p
->initreq
, "From"), p
->authtries
);
12001 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12004 case 479: /* SER: Not able to process the URI - address is wrong in register*/
12005 ast_log(LOG_WARNING
, "Got error 479 on register to %s@%s, giving up (check config)\n", p
->registry
->username
,p
->registry
->hostname
);
12006 if (global_regattempts_max
)
12007 p
->registry
->regattempts
= global_regattempts_max
+1;
12008 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12010 ast_sched_del(sched
, r
->timeout
);
12013 case 200: /* 200 OK */
12015 ast_log(LOG_WARNING
, "Got 200 OK on REGISTER that isn't a register\n");
12016 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12020 r
->regstate
= REG_STATE_REGISTERED
;
12021 r
->regtime
= time(NULL
); /* Reset time of last succesful registration */
12022 manager_event(EVENT_FLAG_SYSTEM
, "Registry", "ChannelDriver: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r
->hostname
, regstate2str(r
->regstate
));
12023 r
->regattempts
= 0;
12025 ast_log(LOG_DEBUG
, "Registration successful\n");
12026 if (r
->timeout
> -1) {
12028 ast_log(LOG_DEBUG
, "Cancelling timeout %d\n", r
->timeout
);
12029 ast_sched_del(sched
, r
->timeout
);
12033 p
->registry
= NULL
;
12034 /* Let this one hang around until we have all the responses */
12035 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
12036 /* ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); */
12038 /* set us up for re-registering */
12039 /* figure out how long we got registered for */
12040 if (r
->expire
> -1)
12041 ast_sched_del(sched
, r
->expire
);
12042 /* according to section 6.13 of RFC, contact headers override
12043 expires headers, so check those first */
12046 /* XXX todo: try to save the extra call */
12047 if (!ast_strlen_zero(get_header(req
, "Contact"))) {
12048 const char *contact
= NULL
;
12049 const char *tmptmp
= NULL
;
12052 contact
= __get_header(req
, "Contact", &start
);
12053 /* this loop ensures we get a contact header about our register request */
12054 if(!ast_strlen_zero(contact
)) {
12055 if( (tmptmp
=strstr(contact
, p
->our_contact
))) {
12062 tmptmp
= strcasestr(contact
, "expires=");
12064 if (sscanf(tmptmp
+ 8, "%d;", &expires
) != 1)
12070 expires
=atoi(get_header(req
, "expires"));
12072 expires
=default_expiry
;
12074 expires_ms
= expires
* 1000;
12075 if (expires
<= EXPIRY_GUARD_LIMIT
)
12076 expires_ms
-= MAX((expires_ms
* EXPIRY_GUARD_PCT
),EXPIRY_GUARD_MIN
);
12078 expires_ms
-= EXPIRY_GUARD_SECS
* 1000;
12080 ast_log(LOG_NOTICE
, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r
->hostname
, expires
, expires_ms
/1000);
12082 r
->refresh
= (int) expires_ms
/ 1000;
12084 /* Schedule re-registration before we expire */
12085 r
->expire
=ast_sched_add(sched
, expires_ms
, sip_reregister
, r
);
12086 ASTOBJ_UNREF(r
, sip_registry_destroy
);
12091 /*! \brief Handle qualification responses (OPTIONS) */
12092 static void handle_response_peerpoke(struct sip_pvt
*p
, int resp
, struct sip_request
*req
)
12094 struct sip_peer
*peer
= p
->relatedpeer
;
12095 int statechanged
, is_reachable
, was_reachable
;
12096 int pingtime
= ast_tvdiff_ms(ast_tvnow(), peer
->ps
);
12099 * Compute the response time to a ping (goes in peer->lastms.)
12100 * -1 means did not respond, 0 means unknown,
12101 * 1..maxms is a valid response, >maxms means late response.
12103 if (pingtime
< 1) /* zero = unknown, so round up to 1 */
12106 /* Now determine new state and whether it has changed.
12107 * Use some helper variables to simplify the writing
12108 * of the expressions.
12110 was_reachable
= peer
->lastms
> 0 && peer
->lastms
<= peer
->maxms
;
12111 is_reachable
= pingtime
<= peer
->maxms
;
12112 statechanged
= peer
->lastms
== 0 /* yes, unknown before */
12113 || was_reachable
!= is_reachable
;
12115 peer
->lastms
= pingtime
;
12117 if (statechanged
) {
12118 const char *s
= is_reachable
? "Reachable" : "Lagged";
12120 ast_log(LOG_NOTICE
, "Peer '%s' is now %s. (%dms / %dms)\n",
12121 peer
->name
, s
, pingtime
, peer
->maxms
);
12122 ast_device_state_changed("SIP/%s", peer
->name
);
12123 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus",
12124 "Peer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
12125 peer
->name
, s
, pingtime
);
12128 if (peer
->pokeexpire
> -1)
12129 ast_sched_del(sched
, peer
->pokeexpire
);
12130 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12132 /* Try again eventually */
12133 peer
->pokeexpire
= ast_sched_add(sched
,
12134 is_reachable
? DEFAULT_FREQ_OK
: DEFAULT_FREQ_NOTOK
,
12135 sip_poke_peer_s
, peer
);
12138 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
12139 static void stop_media_flows(struct sip_pvt
*p
)
12141 /* Immediately stop RTP, VRTP and UDPTL as applicable */
12143 ast_rtp_stop(p
->rtp
);
12145 ast_rtp_stop(p
->vrtp
);
12147 ast_udptl_stop(p
->udptl
);
12150 /*! \brief Handle SIP response in dialogue */
12151 /* XXX only called by handle_request */
12152 static void handle_response(struct sip_pvt
*p
, int resp
, char *rest
, struct sip_request
*req
, int ignore
, int seqno
)
12154 struct ast_channel
*owner
;
12157 const char *c
= get_header(req
, "Cseq");
12158 const char *msg
= strchr(c
, ' ');
12164 sipmethod
= find_sip_method(msg
);
12168 owner
->hangupcause
= hangup_sip2cause(resp
);
12170 /* Acknowledge whatever it is destined for */
12171 if ((resp
>= 100) && (resp
<= 199))
12172 __sip_semi_ack(p
, seqno
, 0, sipmethod
);
12174 __sip_ack(p
, seqno
, 0, sipmethod
);
12176 /* Get their tag if we haven't already */
12177 if (ast_strlen_zero(p
->theirtag
) || (resp
>= 200)) {
12180 gettag(req
, "To", tag
, sizeof(tag
));
12181 ast_string_field_set(p
, theirtag
, tag
);
12183 if (p
->relatedpeer
&& p
->method
== SIP_OPTIONS
) {
12184 /* We don't really care what the response is, just that it replied back.
12185 Well, as long as it's not a 100 response... since we might
12186 need to hang around for something more "definitive" */
12188 handle_response_peerpoke(p
, resp
, req
);
12189 } else if (ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) {
12191 case 100: /* 100 Trying */
12192 case 101: /* 101 Dialog establishment */
12193 if (sipmethod
== SIP_INVITE
)
12194 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12196 case 183: /* 183 Session Progress */
12197 if (sipmethod
== SIP_INVITE
)
12198 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12200 case 180: /* 180 Ringing */
12201 if (sipmethod
== SIP_INVITE
)
12202 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12204 case 200: /* 200 OK */
12205 p
->authtries
= 0; /* Reset authentication counter */
12206 if (sipmethod
== SIP_MESSAGE
) {
12207 /* We successfully transmitted a message */
12208 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12209 } else if (sipmethod
== SIP_INVITE
) {
12210 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12211 } else if (sipmethod
== SIP_NOTIFY
) {
12212 /* They got the notify, this is the end */
12215 ast_log(LOG_WARNING
, "Notify answer on an owned channel? - %s\n", p
->owner
->name
);
12216 ast_queue_hangup(p
->owner
);
12217 } else if (option_debug
> 3)
12218 ast_log(LOG_DEBUG
, "Got OK on REFER Notify message\n");
12220 if (p
->subscribed
== NONE
)
12221 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12223 } else if (sipmethod
== SIP_REGISTER
)
12224 res
= handle_response_register(p
, resp
, rest
, req
, ignore
, seqno
);
12225 else if (sipmethod
== SIP_BYE
) /* Ok, we're ready to go */
12226 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12228 case 202: /* Transfer accepted */
12229 if (sipmethod
== SIP_REFER
)
12230 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12232 case 401: /* Not www-authorized on SIP method */
12233 if (sipmethod
== SIP_INVITE
)
12234 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12235 else if (sipmethod
== SIP_REFER
)
12236 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12237 else if (p
->registry
&& sipmethod
== SIP_REGISTER
)
12238 res
= handle_response_register(p
, resp
, rest
, req
, ignore
, seqno
);
12240 ast_log(LOG_WARNING
, "Got authentication request (401) on unknown %s to '%s'\n", sip_methods
[sipmethod
].text
, get_header(req
, "To"));
12241 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12244 case 403: /* Forbidden - we failed authentication */
12245 if (sipmethod
== SIP_INVITE
)
12246 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12247 else if (p
->registry
&& sipmethod
== SIP_REGISTER
)
12248 res
= handle_response_register(p
, resp
, rest
, req
, ignore
, seqno
);
12250 ast_log(LOG_WARNING
, "Forbidden - maybe wrong password on authentication for %s\n", msg
);
12251 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12254 case 404: /* Not found */
12255 if (p
->registry
&& sipmethod
== SIP_REGISTER
)
12256 res
= handle_response_register(p
, resp
, rest
, req
, ignore
, seqno
);
12257 else if (sipmethod
== SIP_INVITE
)
12258 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12260 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
12262 case 407: /* Proxy auth required */
12263 if (sipmethod
== SIP_INVITE
)
12264 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12265 else if (sipmethod
== SIP_REFER
)
12266 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12267 else if (p
->registry
&& sipmethod
== SIP_REGISTER
)
12268 res
= handle_response_register(p
, resp
, rest
, req
, ignore
, seqno
);
12269 else if (sipmethod
== SIP_BYE
) {
12270 if (ast_strlen_zero(p
->authname
))
12271 ast_log(LOG_WARNING
, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12272 msg
, ast_inet_ntoa(p
->recv
.sin_addr
), ntohs(p
->recv
.sin_port
));
12273 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12274 if ((p
->authtries
== MAX_AUTHTRIES
) || do_proxy_auth(p
, req
, "Proxy-Authenticate", "Proxy-Authorization", sipmethod
, 0)) {
12275 ast_log(LOG_NOTICE
, "Failed to authenticate on %s to '%s'\n", msg
, get_header(&p
->initreq
, "From"));
12276 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12278 } else /* We can't handle this, giving up in a bad way */
12279 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12282 case 481: /* Call leg does not exist */
12283 if (sipmethod
== SIP_INVITE
) {
12284 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12285 } else if (sipmethod
== SIP_REFER
) {
12286 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12287 } else if (sipmethod
== SIP_BYE
) {
12288 /* The other side has no transaction to bye,
12289 just assume it's all right then */
12290 ast_log(LOG_WARNING
, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods
[sipmethod
].text
, p
->callid
);
12291 } else if (sipmethod
== SIP_CANCEL
) {
12292 /* The other side has no transaction to cancel,
12293 just assume it's all right then */
12294 ast_log(LOG_WARNING
, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods
[sipmethod
].text
, p
->callid
);
12296 ast_log(LOG_WARNING
, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods
[sipmethod
].text
, p
->callid
);
12297 /* Guessing that this is not an important request */
12301 if (sipmethod
== SIP_INVITE
)
12302 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12304 case 488: /* Not acceptable here - codec error */
12305 if (sipmethod
== SIP_INVITE
)
12306 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12308 case 491: /* Pending */
12309 if (sipmethod
== SIP_INVITE
)
12310 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12313 ast_log(LOG_DEBUG
, "Got 491 on %s, unspported. Call ID %s\n", sip_methods
[sipmethod
].text
, p
->callid
);
12314 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12317 case 501: /* Not Implemented */
12318 if (sipmethod
== SIP_INVITE
)
12319 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12320 else if (sipmethod
== SIP_REFER
)
12321 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12323 ast_log(LOG_WARNING
, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p
->sa
.sin_addr
), msg
);
12325 case 603: /* Declined transfer */
12326 if (sipmethod
== SIP_REFER
) {
12327 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12332 if ((resp
>= 300) && (resp
< 700)) {
12333 /* Fatal response */
12334 if ((option_verbose
> 2) && (resp
!= 487))
12335 ast_verbose(VERBOSE_PREFIX_3
"Got SIP response %d \"%s\" back from %s\n", resp
, rest
, ast_inet_ntoa(p
->sa
.sin_addr
));
12337 stop_media_flows(p
); /* Immediately stop RTP, VRTP and UDPTL as applicable */
12339 /* XXX Locking issues?? XXX */
12341 case 300: /* Multiple Choices */
12342 case 301: /* Moved permenantly */
12343 case 302: /* Moved temporarily */
12344 case 305: /* Use Proxy */
12345 parse_moved_contact(p
, req
);
12347 case 486: /* Busy here */
12348 case 600: /* Busy everywhere */
12349 case 603: /* Decline */
12351 ast_queue_control(p
->owner
, AST_CONTROL_BUSY
);
12354 \note SIP is incapable of performing a hairpin call, which
12355 is yet another failure of not having a layer 2 (again, YAY
12356 IETF for thinking ahead). So we treat this as a call
12357 forward and hope we end up at the right place... */
12359 ast_log(LOG_DEBUG
, "Hairpin detected, setting up call forward for what it's worth\n");
12361 ast_string_field_build(p
->owner
, call_forward
,
12362 "Local/%s@%s", p
->username
, p
->context
);
12364 case 480: /* Temporarily Unavailable */
12365 case 404: /* Not Found */
12366 case 410: /* Gone */
12367 case 400: /* Bad Request */
12368 case 500: /* Server error */
12369 if (sipmethod
== SIP_REFER
) {
12370 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12374 case 503: /* Service Unavailable */
12375 case 504: /* Server Timeout */
12377 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
12382 ast_queue_hangup(p
->owner
);
12385 /* ACK on invite */
12386 if (sipmethod
== SIP_INVITE
)
12387 transmit_request(p
, SIP_ACK
, seqno
, XMIT_UNRELIABLE
, FALSE
);
12388 sip_alreadygone(p
);
12390 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12391 } else if ((resp
>= 100) && (resp
< 200)) {
12392 if (sipmethod
== SIP_INVITE
) {
12393 if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
12394 sip_cancel_destroy(p
);
12396 process_sdp(p
, req
);
12398 /* Queue a progress frame */
12399 ast_queue_control(p
->owner
, AST_CONTROL_PROGRESS
);
12403 ast_log(LOG_NOTICE
, "Dont know how to handle a %d %s response from %s\n", resp
, rest
, p
->owner
? p
->owner
->name
: ast_inet_ntoa(p
->sa
.sin_addr
));
12406 /* Responses to OUTGOING SIP requests on INCOMING calls
12407 get handled here. As well as out-of-call message responses */
12408 if (ast_test_flag(req
, SIP_PKT_DEBUG
))
12409 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg
);
12411 if (sipmethod
== SIP_INVITE
&& resp
== 200) {
12412 /* Tags in early session is replaced by the tag in 200 OK, which is
12413 the final reply to our INVITE */
12416 gettag(req
, "To", tag
, sizeof(tag
));
12417 ast_string_field_set(p
, theirtag
, tag
);
12422 if (sipmethod
== SIP_INVITE
) {
12423 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12424 } else if (sipmethod
== SIP_CANCEL
) {
12426 ast_log(LOG_DEBUG
, "Got 200 OK on CANCEL\n");
12428 /* Wait for 487, then destroy */
12429 } else if (sipmethod
== SIP_NOTIFY
) {
12430 /* They got the notify, this is the end */
12434 ast_log(LOG_DEBUG
, "Got 200 OK on NOTIFY for transfer\n");
12436 ast_log(LOG_WARNING
, "Notify answer on an owned channel?\n");
12437 /* ast_queue_hangup(p->owner); Disabled */
12439 if (!p
->subscribed
&& !p
->refer
)
12440 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12442 } else if (sipmethod
== SIP_BYE
)
12443 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12444 else if (sipmethod
== SIP_MESSAGE
)
12445 /* We successfully transmitted a message */
12446 /* XXX Why destroy this pvt after message transfer? Bad */
12447 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12448 else if (sipmethod
== SIP_BYE
)
12449 /* Ok, we're ready to go */
12450 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12452 case 202: /* Transfer accepted */
12453 if (sipmethod
== SIP_REFER
)
12454 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12456 case 401: /* www-auth */
12458 if (sipmethod
== SIP_REFER
)
12459 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12460 else if (sipmethod
== SIP_INVITE
)
12461 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12462 else if (sipmethod
== SIP_BYE
) {
12463 char *auth
, *auth2
;
12465 auth
= (resp
== 407 ? "Proxy-Authenticate" : "WWW-Authenticate");
12466 auth2
= (resp
== 407 ? "Proxy-Authorization" : "Authorization");
12467 if ((p
->authtries
== MAX_AUTHTRIES
) || do_proxy_auth(p
, req
, auth
, auth2
, sipmethod
, 0)) {
12468 ast_log(LOG_NOTICE
, "Failed to authenticate on %s to '%s'\n", msg
, get_header(&p
->initreq
, "From"));
12469 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12473 case 481: /* Call leg does not exist */
12474 if (sipmethod
== SIP_INVITE
) {
12475 /* Re-invite failed */
12476 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12477 } else if (sipmethod
== SIP_BYE
) {
12478 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12479 } else if (sipdebug
) {
12480 ast_log (LOG_DEBUG
, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods
[sipmethod
].text
, p
->callid
);
12483 case 501: /* Not Implemented */
12484 if (sipmethod
== SIP_INVITE
)
12485 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12486 else if (sipmethod
== SIP_REFER
)
12487 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12489 case 603: /* Declined transfer */
12490 if (sipmethod
== SIP_REFER
) {
12491 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12495 default: /* Errors without handlers */
12496 if ((resp
>= 100) && (resp
< 200)) {
12497 if (sipmethod
== SIP_INVITE
) { /* re-invite */
12498 if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
12499 sip_cancel_destroy(p
);
12502 if ((resp
>= 300) && (resp
< 700)) {
12503 if ((option_verbose
> 2) && (resp
!= 487))
12504 ast_verbose(VERBOSE_PREFIX_3
"Incoming call: Got SIP response %d \"%s\" back from %s\n", resp
, rest
, ast_inet_ntoa(p
->sa
.sin_addr
));
12506 case 488: /* Not acceptable here - codec error */
12507 case 603: /* Decline */
12508 case 500: /* Server error */
12509 case 503: /* Service Unavailable */
12510 case 504: /* Server timeout */
12512 if (sipmethod
== SIP_INVITE
) { /* re-invite failed */
12513 sip_cancel_destroy(p
);
12524 /*! \brief Park SIP call support function
12525 Starts in a new thread, then parks the call
12526 XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
12527 audio can't be heard before hangup
12529 static void *sip_park_thread(void *stuff
)
12531 struct ast_channel
*transferee
, *transferer
; /* Chan1: The transferee, Chan2: The transferer */
12532 struct sip_dual
*d
;
12533 struct sip_request req
;
12538 transferee
= d
->chan1
;
12539 transferer
= d
->chan2
;
12540 copy_request(&req
, &d
->req
);
12543 if (!transferee
|| !transferer
) {
12544 ast_log(LOG_ERROR
, "Missing channels for parking! Transferer %s Transferee %s\n", transferer
? "<available>" : "<missing>", transferee
? "<available>" : "<missing>" );
12547 if (option_debug
> 3)
12548 ast_log(LOG_DEBUG
, "SIP Park: Transferer channel %s, Transferee %s\n", transferer
->name
, transferee
->name
);
12550 ast_channel_lock(transferee
);
12551 if (ast_do_masquerade(transferee
)) {
12552 ast_log(LOG_WARNING
, "Masquerade failed.\n");
12553 transmit_response(transferer
->tech_pvt
, "503 Internal error", &req
);
12554 ast_channel_unlock(transferee
);
12557 ast_channel_unlock(transferee
);
12559 res
= ast_park_call(transferee
, transferer
, 0, &ext
);
12562 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
12564 transmit_message_with_text(transferer
->tech_pvt
, "Unable to park call.\n");
12566 /* Then tell the transferer what happened */
12567 sprintf(buf
, "Call parked on extension '%d'", ext
);
12568 transmit_message_with_text(transferer
->tech_pvt
, buf
);
12572 /* Any way back to the current call??? */
12573 /* Transmit response to the REFER request */
12574 transmit_response(transferer
->tech_pvt
, "202 Accepted", &req
);
12576 /* Transfer succeeded */
12577 append_history(transferer
->tech_pvt
, "SIPpark","Parked call on %d", ext
);
12578 transmit_notify_with_sipfrag(transferer
->tech_pvt
, d
->seqno
, "200 OK", TRUE
);
12579 transferer
->hangupcause
= AST_CAUSE_NORMAL_CLEARING
;
12580 ast_hangup(transferer
); /* This will cause a BYE */
12582 ast_log(LOG_DEBUG
, "SIP Call parked on extension '%d'\n", ext
);
12584 transmit_notify_with_sipfrag(transferer
->tech_pvt
, d
->seqno
, "503 Service Unavailable", TRUE
);
12585 append_history(transferer
->tech_pvt
, "SIPpark","Parking failed\n");
12587 ast_log(LOG_DEBUG
, "SIP Call parked failed \n");
12588 /* Do not hangup call */
12593 /*! \brief Park a call using the subsystem in res_features.c
12594 This is executed in a separate thread
12596 static int sip_park(struct ast_channel
*chan1
, struct ast_channel
*chan2
, struct sip_request
*req
, int seqno
)
12598 struct sip_dual
*d
;
12599 struct ast_channel
*transferee
, *transferer
;
12600 /* Chan2m: The transferer, chan1m: The transferee */
12603 transferee
= ast_channel_alloc(0, AST_STATE_DOWN
, 0, 0, "Parking/%s", chan1
->name
);
12604 transferer
= ast_channel_alloc(0, AST_STATE_DOWN
, 0, 0, "SIPPeer/%s", chan2
->name
);
12605 if ((!transferer
) || (!transferee
)) {
12607 transferee
->hangupcause
= AST_CAUSE_SWITCH_CONGESTION
;
12608 ast_hangup(transferee
);
12611 transferer
->hangupcause
= AST_CAUSE_SWITCH_CONGESTION
;
12612 ast_hangup(transferer
);
12617 /* Make formats okay */
12618 transferee
->readformat
= chan1
->readformat
;
12619 transferee
->writeformat
= chan1
->writeformat
;
12621 /* Prepare for taking over the channel */
12622 ast_channel_masquerade(transferee
, chan1
);
12624 /* Setup the extensions and such */
12625 ast_copy_string(transferee
->context
, chan1
->context
, sizeof(transferee
->context
));
12626 ast_copy_string(transferee
->exten
, chan1
->exten
, sizeof(transferee
->exten
));
12627 transferee
->priority
= chan1
->priority
;
12629 /* We make a clone of the peer channel too, so we can play
12630 back the announcement */
12632 /* Make formats okay */
12633 transferer
->readformat
= chan2
->readformat
;
12634 transferer
->writeformat
= chan2
->writeformat
;
12636 /* Prepare for taking over the channel */
12637 ast_channel_masquerade(transferer
, chan2
);
12639 /* Setup the extensions and such */
12640 ast_copy_string(transferer
->context
, chan2
->context
, sizeof(transferer
->context
));
12641 ast_copy_string(transferer
->exten
, chan2
->exten
, sizeof(transferer
->exten
));
12642 transferer
->priority
= chan2
->priority
;
12644 ast_channel_lock(transferer
);
12645 if (ast_do_masquerade(transferer
)) {
12646 ast_log(LOG_WARNING
, "Masquerade failed :(\n");
12647 ast_channel_unlock(transferer
);
12648 transferer
->hangupcause
= AST_CAUSE_SWITCH_CONGESTION
;
12649 ast_hangup(transferer
);
12652 ast_channel_unlock(transferer
);
12653 if (!transferer
|| !transferee
) {
12656 ast_log(LOG_DEBUG
, "No transferer channel, giving up parking\n");
12660 ast_log(LOG_DEBUG
, "No transferee channel, giving up parking\n");
12664 if ((d
= ast_calloc(1, sizeof(*d
)))) {
12665 pthread_attr_t attr
;
12667 pthread_attr_init(&attr
);
12668 pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
);
12670 /* Save original request for followup */
12671 copy_request(&d
->req
, req
);
12672 d
->chan1
= transferee
; /* Transferee */
12673 d
->chan2
= transferer
; /* Transferer */
12675 if (ast_pthread_create_background(&th
, &attr
, sip_park_thread
, d
) < 0) {
12676 /* Could not start thread */
12677 free(d
); /* We don't need it anymore. If thread is created, d will be free'd
12678 by sip_park_thread() */
12679 pthread_attr_destroy(&attr
);
12682 pthread_attr_destroy(&attr
);
12687 /*! \brief Turn off generator data
12688 XXX Does this function belong in the SIP channel?
12690 static void ast_quiet_chan(struct ast_channel
*chan
)
12692 if (chan
&& chan
->_state
== AST_STATE_UP
) {
12693 if (chan
->generatordata
)
12694 ast_deactivate_generator(chan
);
12698 /*! \brief Attempt transfer of SIP call
12699 This fix for attended transfers on a local PBX */
12700 static int attempt_transfer(struct sip_dual
*transferer
, struct sip_dual
*target
)
12703 struct ast_channel
*peera
= NULL
,
12709 /* We will try to connect the transferee with the target and hangup
12710 all channels to the transferer */
12711 if (option_debug
> 3) {
12712 ast_log(LOG_DEBUG
, "Sip transfer:--------------------\n");
12713 if (transferer
->chan1
)
12714 ast_log(LOG_DEBUG
, "-- Transferer to PBX channel: %s State %s\n", transferer
->chan1
->name
, ast_state2str(transferer
->chan1
->_state
));
12716 ast_log(LOG_DEBUG
, "-- No transferer first channel - odd??? \n");
12718 ast_log(LOG_DEBUG
, "-- Transferer to PBX second channel (target): %s State %s\n", target
->chan1
->name
, ast_state2str(target
->chan1
->_state
));
12720 ast_log(LOG_DEBUG
, "-- No target first channel ---\n");
12721 if (transferer
->chan2
)
12722 ast_log(LOG_DEBUG
, "-- Bridged call to transferee: %s State %s\n", transferer
->chan2
->name
, ast_state2str(transferer
->chan2
->_state
));
12724 ast_log(LOG_DEBUG
, "-- No bridged call to transferee\n");
12726 ast_log(LOG_DEBUG
, "-- Bridged call to transfer target: %s State %s\n", target
->chan2
? target
->chan2
->name
: "<none>", target
->chan2
? ast_state2str(target
->chan2
->_state
) : "(none)");
12728 ast_log(LOG_DEBUG
, "-- No target second channel ---\n");
12729 ast_log(LOG_DEBUG
, "-- END Sip transfer:--------------------\n");
12731 if (transferer
->chan2
) { /* We have a bridge on the transferer's channel */
12732 peera
= transferer
->chan1
; /* Transferer - PBX -> transferee channel * the one we hangup */
12733 peerb
= target
->chan1
; /* Transferer - PBX -> target channel - This will get lost in masq */
12734 peerc
= transferer
->chan2
; /* Asterisk to Transferee */
12735 peerd
= target
->chan2
; /* Asterisk to Target */
12736 if (option_debug
> 2)
12737 ast_log(LOG_DEBUG
, "SIP transfer: Four channels to handle\n");
12738 } else if (target
->chan2
) { /* Transferer has no bridge (IVR), but transferee */
12739 peera
= target
->chan1
; /* Transferer to PBX -> target channel */
12740 peerb
= transferer
->chan1
; /* Transferer to IVR*/
12741 peerc
= target
->chan2
; /* Asterisk to Target */
12742 peerd
= transferer
->chan2
; /* Nothing */
12743 if (option_debug
> 2)
12744 ast_log(LOG_DEBUG
, "SIP transfer: Three channels to handle\n");
12747 if (peera
&& peerb
&& peerc
&& (peerb
!= peerc
)) {
12748 ast_quiet_chan(peera
); /* Stop generators */
12749 ast_quiet_chan(peerb
);
12750 ast_quiet_chan(peerc
);
12752 ast_quiet_chan(peerd
);
12754 /* Fix CDRs so they're attached to the remaining channel */
12755 if (peera
->cdr
&& peerb
->cdr
)
12756 peerb
->cdr
= ast_cdr_append(peerb
->cdr
, peera
->cdr
);
12757 else if (peera
->cdr
)
12758 peerb
->cdr
= peera
->cdr
;
12761 if (peerb
->cdr
&& peerc
->cdr
)
12762 peerb
->cdr
= ast_cdr_append(peerb
->cdr
, peerc
->cdr
);
12763 else if (peerc
->cdr
)
12764 peerb
->cdr
= peerc
->cdr
;
12767 if (option_debug
> 3)
12768 ast_log(LOG_DEBUG
, "SIP transfer: trying to masquerade %s into %s\n", peerc
->name
, peerb
->name
);
12769 if (ast_channel_masquerade(peerb
, peerc
)) {
12770 ast_log(LOG_WARNING
, "Failed to masquerade %s into %s\n", peerb
->name
, peerc
->name
);
12773 ast_log(LOG_DEBUG
, "SIP transfer: Succeeded to masquerade channels.\n");
12776 ast_log(LOG_NOTICE
, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
12777 if (transferer
->chan1
)
12778 ast_softhangup_nolock(transferer
->chan1
, AST_SOFTHANGUP_DEV
);
12780 ast_softhangup_nolock(target
->chan1
, AST_SOFTHANGUP_DEV
);
12786 /*! \brief Get tag from packet
12788 * \return Returns the pointer to the provided tag buffer,
12789 * or NULL if the tag was not found.
12791 static const char *gettag(const struct sip_request
*req
, const char *header
, char *tagbuf
, int tagbufsize
)
12793 const char *thetag
;
12797 tagbuf
[0] = '\0'; /* reset the buffer */
12798 thetag
= get_header(req
, header
);
12799 thetag
= strcasestr(thetag
, ";tag=");
12802 ast_copy_string(tagbuf
, thetag
, tagbufsize
);
12803 return strsep(&tagbuf
, ";");
12808 /*! \brief Handle incoming notifications */
12809 static int handle_request_notify(struct sip_pvt
*p
, struct sip_request
*req
, struct sockaddr_in
*sin
, int seqno
, char *e
)
12811 /* This is mostly a skeleton for future improvements */
12812 /* Mostly created to return proper answers on notifications on outbound REFER's */
12814 const char *event
= get_header(req
, "Event");
12815 char *eventid
= NULL
;
12818 if( (sep
= strchr(event
, ';')) ) { /* XXX bug here - overwriting string ? */
12823 if (option_debug
> 1 && sipdebug
)
12824 ast_log(LOG_DEBUG
, "Got NOTIFY Event: %s\n", event
);
12826 if (strcmp(event
, "refer")) {
12827 /* We don't understand this event. */
12828 /* Here's room to implement incoming voicemail notifications :-) */
12829 transmit_response(p
, "489 Bad event", req
);
12832 /* Save nesting depth for now, since there might be other events we will
12833 support in the future */
12835 /* Handle REFER notifications */
12840 int success
= TRUE
;
12842 /* EventID for each transfer... EventID is basically the REFER cseq
12844 We are getting notifications on a call that we transfered
12845 We should hangup when we are getting a 200 OK in a sipfrag
12846 Check if we have an owner of this event */
12848 /* Check the content type */
12849 if (strncasecmp(get_header(req
, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
12850 /* We need a sipfrag */
12851 transmit_response(p
, "400 Bad request", req
);
12852 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
12856 /* Get the text of the attachment */
12857 if (get_msg_text(buf
, sizeof(buf
), req
)) {
12858 ast_log(LOG_WARNING
, "Unable to retrieve attachment from NOTIFY %s\n", p
->callid
);
12859 transmit_response(p
, "400 Bad request", req
);
12860 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
12866 A minimal, but complete, implementation can respond with a single
12867 NOTIFY containing either the body:
12870 if the subscription is pending, the body:
12872 if the reference was successful, the body:
12873 SIP/2.0 503 Service Unavailable
12874 if the reference failed, or the body:
12875 SIP/2.0 603 Declined
12877 if the REFER request was accepted before approval to follow the
12878 reference could be obtained and that approval was subsequently denied
12879 (see Section 2.4.7).
12881 If there are several REFERs in the same dialog, we need to
12882 match the ID of the event header...
12884 if (option_debug
> 2)
12885 ast_log(LOG_DEBUG
, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf
);
12886 cmd
= ast_skip_blanks(buf
);
12888 /* We are at SIP/2.0 */
12889 while(*code
&& (*code
> 32)) { /* Search white space */
12893 code
= ast_skip_blanks(code
);
12896 while(*sep
&& (*sep
> 32)) { /* Search white space */
12899 *sep
++ = '\0'; /* Response string */
12900 respcode
= atoi(code
);
12901 switch (respcode
) {
12902 case 100: /* Trying: */
12903 case 101: /* dialog establishment */
12904 /* Don't do anything yet */
12906 case 183: /* Ringing: */
12907 /* Don't do anything yet */
12909 case 200: /* OK: The new call is up, hangup this call */
12910 /* Hangup the call that we are replacing */
12912 case 301: /* Moved permenantly */
12913 case 302: /* Moved temporarily */
12914 /* Do we get the header in the packet in this case? */
12917 case 503: /* Service Unavailable: The new call failed */
12918 /* Cancel transfer, continue the call */
12921 case 603: /* Declined: Not accepted */
12922 /* Cancel transfer, continue the current call */
12927 ast_log(LOG_NOTICE
, "Transfer failed. Sorry. Nothing further to do with this call\n");
12930 /* Confirm that we received this packet */
12931 transmit_response(p
, "200 OK", req
);
12934 if (!p
->lastinvite
)
12935 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
12940 /*! \brief Handle incoming OPTIONS request */
12941 static int handle_request_options(struct sip_pvt
*p
, struct sip_request
*req
)
12945 res
= get_destination(p
, req
);
12947 /* XXX Should we authenticate OPTIONS? XXX */
12948 if (ast_strlen_zero(p
->context
))
12949 ast_string_field_set(p
, context
, default_context
);
12951 transmit_response_with_allow(p
, "404 Not Found", req
, 0);
12953 transmit_response_with_allow(p
, "200 OK", req
, 0);
12954 /* Destroy if this OPTIONS was the opening request, but not if
12955 it's in the middle of a normal call flow. */
12956 if (!p
->lastinvite
)
12957 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
12962 /*! \brief Handle the transfer part of INVITE with a replaces: header,
12963 meaning a target pickup or an attended transfer */
12964 static int handle_invite_replaces(struct sip_pvt
*p
, struct sip_request
*req
, int debug
, int ignore
, int seqno
, struct sockaddr_in
*sin
)
12966 struct ast_frame
*f
;
12967 int earlyreplace
= 0;
12968 int oneleggedreplace
= 0; /* Call with no bridge, propably IVR or voice message */
12969 struct ast_channel
*c
= p
->owner
; /* Our incoming call */
12970 struct ast_channel
*replacecall
= p
->refer
->refer_call
->owner
; /* The channel we're about to take over */
12971 struct ast_channel
*targetcall
; /* The bridge to the take-over target */
12973 /* Check if we're in ring state */
12974 if (replacecall
->_state
== AST_STATE_RING
)
12977 /* Check if we have a bridge */
12978 if (!(targetcall
= ast_bridged_channel(replacecall
))) {
12979 /* We have no bridge */
12980 if (!earlyreplace
) {
12981 if (option_debug
> 1)
12982 ast_log(LOG_DEBUG
, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall
->name
);
12983 oneleggedreplace
= 1;
12986 if (option_debug
> 3 && targetcall
&& targetcall
->_state
== AST_STATE_RINGING
)
12987 ast_log(LOG_DEBUG
, "SIP transfer: Target channel is in ringing state\n");
12989 if (option_debug
> 3) {
12991 ast_log(LOG_DEBUG
, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall
->name
, replacecall
->name
);
12993 ast_log(LOG_DEBUG
, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall
->name
);
12997 ast_log(LOG_NOTICE
, "Ignoring this INVITE with replaces in a stupid way.\n");
12998 /* We should answer something here. If we are here, the
12999 call we are replacing exists, so an accepted
13001 transmit_response_with_sdp(p
, "200 OK", req
, XMIT_RELIABLE
);
13002 /* Do something more clever here */
13003 ast_channel_unlock(c
);
13004 ast_mutex_unlock(&p
->refer
->refer_call
->lock
);
13008 /* What to do if no channel ??? */
13009 ast_log(LOG_ERROR
, "Unable to create new channel. Invite/replace failed.\n");
13010 transmit_response_reliable(p
, "503 Service Unavailable", req
);
13011 append_history(p
, "Xfer", "INVITE/Replace Failed. No new channel.");
13012 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13013 ast_mutex_unlock(&p
->refer
->refer_call
->lock
);
13016 append_history(p
, "Xfer", "INVITE/Replace received");
13017 /* We have three channels to play with
13018 channel c: New incoming call
13019 targetcall: Call from PBX to target
13020 p->refer->refer_call: SIP pvt dialog from transferer to pbx.
13021 replacecall: The owner of the previous
13022 We need to masq C into refer_call to connect to
13024 If we are talking to internal audio stream, target call is null.
13027 /* Fake call progress */
13028 transmit_response(p
, "100 Trying", req
);
13029 ast_setstate(c
, AST_STATE_RING
);
13031 /* Masquerade the new call into the referred call to connect to target call
13032 Targetcall is not touched by the masq */
13034 /* Answer the incoming call and set channel to UP state */
13035 transmit_response_with_sdp(p
, "200 OK", req
, XMIT_RELIABLE
);
13036 ast_setstate(c
, AST_STATE_UP
);
13038 /* Stop music on hold and other generators */
13039 ast_quiet_chan(replacecall
);
13040 ast_quiet_chan(targetcall
);
13041 if (option_debug
> 3)
13042 ast_log(LOG_DEBUG
, "Invite/Replaces: preparing to masquerade %s into %s\n", c
->name
, replacecall
->name
);
13043 /* Unlock clone, but not original (replacecall) */
13044 ast_channel_unlock(c
);
13047 ast_mutex_unlock(&p
->refer
->refer_call
->lock
);
13049 /* Make sure that the masq does not free our PVT for the old call */
13050 ast_set_flag(&p
->refer
->refer_call
->flags
[0], SIP_DEFER_BYE_ON_TRANSFER
); /* Delay hangup */
13052 /* Prepare the masquerade - if this does not happen, we will be gone */
13053 if(ast_channel_masquerade(replacecall
, c
))
13054 ast_log(LOG_ERROR
, "Failed to masquerade C into Replacecall\n");
13055 else if (option_debug
> 3)
13056 ast_log(LOG_DEBUG
, "Invite/Replaces: Going to masquerade %s into %s\n", c
->name
, replacecall
->name
);
13058 /* The masquerade will happen as soon as someone reads a frame from the channel */
13060 /* C should now be in place of replacecall */
13061 /* ast_read needs to lock channel */
13062 ast_channel_unlock(c
);
13064 if (earlyreplace
|| oneleggedreplace
) {
13065 /* Force the masq to happen */
13066 if ((f
= ast_read(replacecall
))) { /* Force the masq to happen */
13069 if (option_debug
> 3)
13070 ast_log(LOG_DEBUG
, "Invite/Replace: Could successfully read frame from RING channel!\n");
13072 ast_log(LOG_WARNING
, "Invite/Replace: Could not read frame from RING channel \n");
13074 c
->hangupcause
= AST_CAUSE_SWITCH_CONGESTION
;
13075 ast_channel_unlock(replacecall
);
13076 } else { /* Bridged call, UP channel */
13077 if ((f
= ast_read(replacecall
))) { /* Force the masq to happen */
13081 if (option_debug
> 2)
13082 ast_log(LOG_DEBUG
, "Invite/Replace: Could successfully read frame from channel! Masq done.\n");
13084 ast_log(LOG_WARNING
, "Invite/Replace: Could not read frame from channel. Transfer failed\n");
13086 ast_channel_unlock(replacecall
);
13088 ast_mutex_unlock(&p
->refer
->refer_call
->lock
);
13090 ast_setstate(c
, AST_STATE_DOWN
);
13091 if (option_debug
> 3) {
13092 struct ast_channel
*test
;
13093 ast_log(LOG_DEBUG
, "After transfer:----------------------------\n");
13094 ast_log(LOG_DEBUG
, " -- C: %s State %s\n", c
->name
, ast_state2str(c
->_state
));
13096 ast_log(LOG_DEBUG
, " -- replacecall: %s State %s\n", replacecall
->name
, ast_state2str(replacecall
->_state
));
13098 ast_log(LOG_DEBUG
, " -- P->owner: %s State %s\n", p
->owner
->name
, ast_state2str(p
->owner
->_state
));
13099 test
= ast_bridged_channel(p
->owner
);
13101 ast_log(LOG_DEBUG
, " -- Call bridged to P->owner: %s State %s\n", test
->name
, ast_state2str(test
->_state
));
13103 ast_log(LOG_DEBUG
, " -- No call bridged to C->owner \n");
13105 ast_log(LOG_DEBUG
, " -- No channel yet \n");
13106 ast_log(LOG_DEBUG
, "End After transfer:----------------------------\n");
13109 ast_channel_unlock(p
->owner
); /* Unlock new owner */
13110 ast_mutex_unlock(&p
->lock
); /* Unlock SIP structure */
13112 /* The call should be down with no ast_channel, so hang it up */
13113 c
->tech_pvt
= NULL
;
13119 /*! \brief Handle incoming INVITE request
13120 \note If the INVITE has a Replaces header, it is part of an
13121 * attended transfer. If so, we do not go through the dial
13122 * plan but tries to find the active call and masquerade
13125 static int handle_request_invite(struct sip_pvt
*p
, struct sip_request
*req
, int debug
, int seqno
, struct sockaddr_in
*sin
, int *recount
, char *e
)
13129 const char *p_replaces
;
13130 char *replace_id
= NULL
;
13131 const char *required
;
13132 unsigned int required_profile
= 0;
13133 struct ast_channel
*c
= NULL
; /* New channel */
13135 /* Find out what they support */
13136 if (!p
->sipoptions
) {
13137 const char *supported
= get_header(req
, "Supported");
13138 if (!ast_strlen_zero(supported
))
13139 parse_sip_options(p
, supported
);
13142 /* Find out what they require */
13143 required
= get_header(req
, "Require");
13144 if (!ast_strlen_zero(required
)) {
13145 required_profile
= parse_sip_options(NULL
, required
);
13146 if (required_profile
&& required_profile
!= SIP_OPT_REPLACES
) {
13147 /* At this point we only support REPLACES */
13148 transmit_response_with_unsupported(p
, "420 Bad extension (unsupported)", req
, required
);
13149 ast_log(LOG_WARNING
,"Received SIP INVITE with unsupported required extension: %s\n", required
);
13150 p
->invitestate
= INV_COMPLETED
;
13151 if (!p
->lastinvite
)
13152 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13157 /* Check if this is a loop */
13158 if (ast_test_flag(&p
->flags
[0], SIP_OUTGOING
) && p
->owner
&& (p
->owner
->_state
!= AST_STATE_UP
)) {
13159 /* This is a call to ourself. Send ourselves an error code and stop
13160 processing immediately, as SIP really has no good mechanism for
13161 being able to call yourself */
13162 /* If pedantic is on, we need to check the tags. If they're different, this is
13163 in fact a forked call through a SIP proxy somewhere. */
13164 transmit_response(p
, "482 Loop Detected", req
);
13165 p
->invitestate
= INV_COMPLETED
;
13166 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13170 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && p
->pendinginvite
) {
13171 /* We already have a pending invite. Sorry. You are on hold. */
13172 transmit_response(p
, "491 Request Pending", req
);
13174 ast_log(LOG_DEBUG
, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p
->callid
);
13175 /* Don't destroy dialog here */
13179 p_replaces
= get_header(req
, "Replaces");
13180 if (!ast_strlen_zero(p_replaces
)) {
13181 /* We have a replaces header */
13183 char *fromtag
= NULL
;
13184 char *totag
= NULL
;
13189 if (option_debug
> 2)
13190 ast_log(LOG_DEBUG
, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p
->callid
);
13191 transmit_response(p
, "400 Bad request", req
); /* The best way to not not accept the transfer */
13192 /* Do not destroy existing call */
13196 if (sipdebug
&& option_debug
> 2)
13197 ast_log(LOG_DEBUG
, "INVITE part of call transfer. Replaces [%s]\n", p_replaces
);
13198 /* Create a buffer we can manipulate */
13199 replace_id
= ast_strdupa(p_replaces
);
13200 ast_uri_decode(replace_id
);
13202 if (!p
->refer
&& !sip_refer_allocate(p
)) {
13203 transmit_response(p
, "500 Server Internal Error", req
);
13204 append_history(p
, "Xfer", "INVITE/Replace Failed. Out of memory.");
13205 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13206 p
->invitestate
= INV_COMPLETED
;
13210 /* Todo: (When we find phones that support this)
13211 if the replaces header contains ";early-only"
13212 we can only replace the call in early
13213 stage, not after it's up.
13215 If it's not in early mode, 486 Busy.
13218 /* Skip leading whitespace */
13219 replace_id
= ast_skip_blanks(replace_id
);
13221 start
= replace_id
;
13222 while ( (ptr
= strsep(&start
, ";")) ) {
13223 ptr
= ast_skip_blanks(ptr
); /* XXX maybe unnecessary ? */
13224 if ( (to
= strcasestr(ptr
, "to-tag=") ) )
13225 totag
= to
+ 7; /* skip the keyword */
13226 else if ( (to
= strcasestr(ptr
, "from-tag=") ) ) {
13227 fromtag
= to
+ 9; /* skip the keyword */
13228 fromtag
= strsep(&fromtag
, "&"); /* trim what ? */
13232 if (sipdebug
&& option_debug
> 3)
13233 ast_log(LOG_DEBUG
,"Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n", replace_id
, fromtag
? fromtag
: "<no from tag>", totag
? totag
: "<no to tag>");
13236 /* Try to find call that we are replacing
13237 If we have a Replaces header, we need to cancel that call if we succeed with this call
13239 if ((p
->refer
->refer_call
= get_sip_pvt_byid_locked(replace_id
, totag
, fromtag
)) == NULL
) {
13240 ast_log(LOG_NOTICE
, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id
);
13241 transmit_response(p
, "481 Call Leg Does Not Exist (Replaces)", req
);
13245 /* At this point, bot the pvt and the owner of the call to be replaced is locked */
13247 /* The matched call is the call from the transferer to Asterisk .
13248 We want to bridge the bridged part of the call to the
13249 incoming invite, thus taking over the refered call */
13251 if (p
->refer
->refer_call
== p
) {
13252 ast_log(LOG_NOTICE
, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id
, p
->callid
);
13253 p
->refer
->refer_call
= NULL
;
13254 transmit_response(p
, "400 Bad request", req
); /* The best way to not not accept the transfer */
13258 if (!error
&& !p
->refer
->refer_call
->owner
) {
13259 /* Oops, someting wrong anyway, no owner, no call */
13260 ast_log(LOG_NOTICE
, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id
);
13261 /* Check for better return code */
13262 transmit_response(p
, "481 Call Leg Does Not Exist (Replace)", req
);
13266 if (!error
&& p
->refer
->refer_call
->owner
->_state
!= AST_STATE_RING
&& p
->refer
->refer_call
->owner
->_state
!= AST_STATE_UP
) {
13267 ast_log(LOG_NOTICE
, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id
);
13268 transmit_response(p
, "603 Declined (Replaces)", req
);
13272 if (error
) { /* Give up this dialog */
13273 append_history(p
, "Xfer", "INVITE/Replace Failed.");
13274 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13275 ast_mutex_unlock(&p
->lock
);
13276 if (p
->refer
->refer_call
) {
13277 ast_mutex_unlock(&p
->refer
->refer_call
->lock
);
13278 ast_channel_unlock(p
->refer
->refer_call
->owner
);
13280 p
->invitestate
= INV_COMPLETED
;
13286 /* Check if this is an INVITE that sets up a new dialog or
13287 a re-invite in an existing dialog */
13289 if (!ast_test_flag(req
, SIP_PKT_IGNORE
)) {
13290 int newcall
= (p
->initreq
.headers
? TRUE
: FALSE
);
13292 sip_cancel_destroy(p
);
13293 /* This also counts as a pending invite */
13294 p
->pendinginvite
= seqno
;
13297 copy_request(&p
->initreq
, req
); /* Save this INVITE as the transaction basis */
13298 if (!p
->owner
) { /* Not a re-invite */
13300 ast_verbose("Using INVITE request as basis request - %s\n", p
->callid
);
13302 append_history(p
, "Invite", "New call: %s", p
->callid
);
13303 parse_ok_contact(p
, req
);
13304 } else { /* Re-invite on existing call */
13305 ast_clear_flag(&p
->flags
[0], SIP_OUTGOING
); /* This is now an inbound dialog */
13306 /* Handle SDP here if we already have an owner */
13307 if (find_sdp(req
)) {
13308 if (process_sdp(p
, req
)) {
13309 transmit_response(p
, "488 Not acceptable here", req
);
13310 if (!p
->lastinvite
)
13311 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13315 p
->jointcapability
= p
->capability
;
13317 ast_log(LOG_DEBUG
, "Hm.... No sdp for the moment\n");
13319 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
)) /* This is a response, note what it was for */
13320 append_history(p
, "ReInv", "Re-invite received");
13323 ast_verbose("Ignoring this INVITE request\n");
13326 if (!p
->lastinvite
&& !ast_test_flag(req
, SIP_PKT_IGNORE
) && !p
->owner
) {
13327 /* This is a new invite */
13328 /* Handle authentication if this is our first invite */
13329 res
= check_user(p
, req
, SIP_INVITE
, e
, XMIT_RELIABLE
, sin
);
13330 if (res
== AUTH_CHALLENGE_SENT
) {
13331 p
->invitestate
= INV_COMPLETED
; /* Needs to restart in another INVITE transaction */
13334 if (res
< 0) { /* Something failed in authentication */
13335 if (res
== AUTH_FAKE_AUTH
) {
13336 ast_log(LOG_NOTICE
, "Sending fake auth rejection for user %s\n", get_header(req
, "From"));
13337 transmit_fake_auth_response(p
, req
, 1);
13339 ast_log(LOG_NOTICE
, "Failed to authenticate user %s\n", get_header(req
, "From"));
13340 transmit_response_reliable(p
, "403 Forbidden", req
);
13342 p
->invitestate
= INV_COMPLETED
;
13343 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13344 ast_string_field_free(p
, theirtag
);
13348 /* We have a succesful authentication, process the SDP portion if there is one */
13349 if (find_sdp(req
)) {
13350 if (process_sdp(p
, req
)) {
13351 /* Unacceptable codecs */
13352 transmit_response_reliable(p
, "488 Not acceptable here", req
);
13353 p
->invitestate
= INV_COMPLETED
;
13354 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13356 ast_log(LOG_DEBUG
, "No compatible codecs for this SIP call.\n");
13359 } else { /* No SDP in invite, call control session */
13360 p
->jointcapability
= p
->capability
;
13361 if (option_debug
> 1)
13362 ast_log(LOG_DEBUG
, "No SDP in Invite, third party call control\n");
13365 /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
13366 /* This seems redundant ... see !p-owner above */
13368 ast_queue_frame(p
->owner
, &ast_null_frame
);
13371 /* Initialize the context if it hasn't been already */
13372 if (ast_strlen_zero(p
->context
))
13373 ast_string_field_set(p
, context
, default_context
);
13376 /* Check number of concurrent calls -vs- incoming limit HERE */
13378 ast_log(LOG_DEBUG
, "Checking SIP call limits for device %s\n", p
->username
);
13379 if ((res
= update_call_counter(p
, INC_CALL_LIMIT
))) {
13381 ast_log(LOG_NOTICE
, "Failed to place call for user %s, too many calls\n", p
->username
);
13382 transmit_response_reliable(p
, "480 Temporarily Unavailable (Call limit) ", req
);
13383 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13384 p
->invitestate
= INV_COMPLETED
;
13388 gotdest
= get_destination(p
, NULL
); /* Get destination right away */
13389 get_rdnis(p
, NULL
); /* Get redirect information */
13390 extract_uri(p
, req
); /* Get the Contact URI */
13391 build_contact(p
); /* Build our contact header */
13394 ast_rtp_setdtmf(p
->rtp
, ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_RFC2833
);
13395 ast_rtp_setdtmfcompensate(p
->rtp
, ast_test_flag(&p
->flags
[1], SIP_PAGE2_RFC2833_COMPENSATE
));
13398 if (!replace_id
&& gotdest
) { /* No matching extension found */
13399 if (gotdest
== 1 && ast_test_flag(&p
->flags
[1], SIP_PAGE2_ALLOWOVERLAP
))
13400 transmit_response_reliable(p
, "484 Address Incomplete", req
);
13402 transmit_response_reliable(p
, "404 Not Found", req
);
13403 p
->invitestate
= INV_COMPLETED
;
13404 update_call_counter(p
, DEC_CALL_LIMIT
);
13405 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13408 /* If no extension was specified, use the s one */
13409 /* Basically for calling to IP/Host name only */
13410 if (ast_strlen_zero(p
->exten
))
13411 ast_string_field_set(p
, exten
, "s");
13412 /* Initialize our tag */
13414 make_our_tag(p
->tag
, sizeof(p
->tag
));
13416 /* First invitation - create the channel */
13417 c
= sip_new(p
, AST_STATE_DOWN
, S_OR(p
->username
, NULL
));
13420 /* Save Record-Route for any later requests we make on this dialogue */
13421 build_route(p
, req
, 0);
13424 /* Pre-lock the call */
13425 ast_channel_lock(c
);
13429 if (option_debug
> 1 && sipdebug
) {
13430 if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
13431 ast_log(LOG_DEBUG
, "Got a SIP re-invite for call %s\n", p
->callid
);
13433 ast_log(LOG_DEBUG
, "Got a SIP re-transmit of INVITE for call %s\n", p
->callid
);
13438 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && p
)
13439 p
->lastinvite
= seqno
;
13441 if (replace_id
) { /* Attended transfer or call pickup - we're the target */
13442 /* Go and take over the target call */
13443 if (sipdebug
&& option_debug
> 3)
13444 ast_log(LOG_DEBUG
, "Sending this call to the invite/replcaes handler %s\n", p
->callid
);
13445 return handle_invite_replaces(p
, req
, debug
, ast_test_flag(req
, SIP_PKT_IGNORE
), seqno
, sin
);
13449 if (c
) { /* We have a call -either a new call or an old one (RE-INVITE) */
13450 switch(c
->_state
) {
13451 case AST_STATE_DOWN
:
13452 if (option_debug
> 1)
13453 ast_log(LOG_DEBUG
, "%s: New call is still down.... Trying... \n", c
->name
);
13454 transmit_response(p
, "100 Trying", req
);
13455 p
->invitestate
= INV_PROCEEDING
;
13456 ast_setstate(c
, AST_STATE_RING
);
13457 if (strcmp(p
->exten
, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
13458 enum ast_pbx_result res
;
13460 res
= ast_pbx_start(c
);
13463 case AST_PBX_FAILED
:
13464 ast_log(LOG_WARNING
, "Failed to start PBX :(\n");
13465 p
->invitestate
= INV_COMPLETED
;
13466 if (ast_test_flag(req
, SIP_PKT_IGNORE
))
13467 transmit_response(p
, "503 Unavailable", req
);
13469 transmit_response_reliable(p
, "503 Unavailable", req
);
13471 case AST_PBX_CALL_LIMIT
:
13472 ast_log(LOG_WARNING
, "Failed to start PBX (call limit reached) \n");
13473 p
->invitestate
= INV_COMPLETED
;
13474 if (ast_test_flag(req
, SIP_PKT_IGNORE
))
13475 transmit_response(p
, "480 Temporarily Unavailable", req
);
13477 transmit_response_reliable(p
, "480 Temporarily Unavailable", req
);
13479 case AST_PBX_SUCCESS
:
13480 /* nothing to do */
13486 /* Unlock locks so ast_hangup can do its magic */
13487 ast_mutex_unlock(&c
->lock
);
13488 ast_mutex_unlock(&p
->lock
);
13490 ast_mutex_lock(&p
->lock
);
13493 } else { /* Pickup call in call group */
13494 ast_channel_unlock(c
);
13495 if (ast_pickup_call(c
)) {
13496 ast_log(LOG_NOTICE
, "Nothing to pick up for %s\n", p
->callid
);
13497 if (ast_test_flag(req
, SIP_PKT_IGNORE
))
13498 transmit_response(p
, "503 Unavailable", req
); /* OEJ - Right answer? */
13500 transmit_response_reliable(p
, "503 Unavailable", req
);
13501 sip_alreadygone(p
);
13502 /* Unlock locks so ast_hangup can do its magic */
13503 ast_mutex_unlock(&p
->lock
);
13504 c
->hangupcause
= AST_CAUSE_CALL_REJECTED
;
13506 ast_mutex_unlock(&p
->lock
);
13507 ast_setstate(c
, AST_STATE_DOWN
);
13508 c
->hangupcause
= AST_CAUSE_NORMAL_CLEARING
;
13510 p
->invitestate
= INV_COMPLETED
;
13512 ast_mutex_lock(&p
->lock
);
13516 case AST_STATE_RING
:
13517 transmit_response(p
, "100 Trying", req
);
13518 p
->invitestate
= INV_PROCEEDING
;
13520 case AST_STATE_RINGING
:
13521 transmit_response(p
, "180 Ringing", req
);
13522 p
->invitestate
= INV_PROCEEDING
;
13525 if (option_debug
> 1)
13526 ast_log(LOG_DEBUG
, "%s: This call is UP.... \n", c
->name
);
13528 if (p
->t38
.state
== T38_PEER_REINVITE
) {
13529 struct ast_channel
*bridgepeer
= NULL
;
13530 struct sip_pvt
*bridgepvt
= NULL
;
13532 if ((bridgepeer
= ast_bridged_channel(p
->owner
))) {
13533 /* We have a bridge, and this is re-invite to switchover to T38 so we send re-invite with T38 SDP, to other side of bridge*/
13534 /*! XXX: we should also check here does the other side supports t38 at all !!! XXX */
13535 if (bridgepeer
->tech
== &sip_tech
|| bridgepeer
->tech
== &sip_tech_info
) {
13536 bridgepvt
= (struct sip_pvt
*)bridgepeer
->tech_pvt
;
13537 if (bridgepvt
->t38
.state
== T38_DISABLED
) {
13538 if (bridgepvt
->udptl
) { /* If everything is OK with other side's udptl struct */
13539 /* Send re-invite to the bridged channel */
13540 sip_handle_t38_reinvite(bridgepeer
, p
, 1);
13541 } else { /* Something is wrong with peers udptl struct */
13542 ast_log(LOG_WARNING
, "Strange... The other side of the bridge don't have udptl struct\n");
13543 ast_mutex_lock(&bridgepvt
->lock
);
13544 bridgepvt
->t38
.state
= T38_DISABLED
;
13545 ast_mutex_unlock(&bridgepvt
->lock
);
13546 if (option_debug
> 1)
13547 ast_log(LOG_DEBUG
,"T38 state changed to %d on channel %s\n", bridgepvt
->t38
.state
, bridgepeer
->name
);
13548 if (ast_test_flag(req
, SIP_PKT_IGNORE
))
13549 transmit_response(p
, "488 Not acceptable here", req
);
13551 transmit_response_reliable(p
, "488 Not acceptable here", req
);
13555 /* The other side is already setup for T.38 most likely so we need to acknowledge this too */
13556 transmit_response_with_t38_sdp(p
, "200 OK", req
, XMIT_CRITICAL
);
13557 p
->t38
.state
= T38_ENABLED
;
13559 ast_log(LOG_DEBUG
, "T38 state changed to %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>");
13562 /* Other side is not a SIP channel */
13563 if (ast_test_flag(req
, SIP_PKT_IGNORE
))
13564 transmit_response(p
, "488 Not acceptable here", req
);
13566 transmit_response_reliable(p
, "488 Not acceptable here", req
);
13567 p
->t38
.state
= T38_DISABLED
;
13568 if (option_debug
> 1)
13569 ast_log(LOG_DEBUG
,"T38 state changed to %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>");
13571 if (!p
->lastinvite
) /* Only destroy if this is *not* a re-invite */
13572 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13575 /* we are not bridged in a call */
13576 transmit_response_with_t38_sdp(p
, "200 OK", req
, XMIT_CRITICAL
);
13577 p
->t38
.state
= T38_ENABLED
;
13579 ast_log(LOG_DEBUG
,"T38 state changed to %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>");
13581 } else if (p
->t38
.state
== T38_DISABLED
) { /* Channel doesn't have T38 offered or enabled */
13584 /* If we are bridged to a channel that has T38 enabled than this is a case of RTP re-invite after T38 session */
13585 /* so handle it here (re-invite other party to RTP) */
13586 struct ast_channel
*bridgepeer
= NULL
;
13587 struct sip_pvt
*bridgepvt
= NULL
;
13588 if ((bridgepeer
= ast_bridged_channel(p
->owner
))) {
13589 if (bridgepeer
->tech
== &sip_tech
|| bridgepeer
->tech
== &sip_tech_info
) {
13590 bridgepvt
= (struct sip_pvt
*)bridgepeer
->tech_pvt
;
13591 /* Does the bridged peer have T38 ? */
13592 if (bridgepvt
->t38
.state
== T38_ENABLED
) {
13593 ast_log(LOG_WARNING
, "RTP re-invite after T38 session not handled yet !\n");
13594 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
13595 if (ast_test_flag(req
, SIP_PKT_IGNORE
))
13596 transmit_response(p
, "488 Not Acceptable Here (unsupported)", req
);
13598 transmit_response_reliable(p
, "488 Not Acceptable Here (unsupported)", req
);
13601 /* No bridged peer with T38 enabled*/
13604 /* Respond to normal re-invite */
13606 transmit_response_with_sdp(p
, "200 OK", req
, XMIT_CRITICAL
);
13609 p
->invitestate
= INV_TERMINATED
;
13612 ast_log(LOG_WARNING
, "Don't know how to handle INVITE in state %d\n", c
->_state
);
13613 transmit_response(p
, "100 Trying", req
);
13617 if (p
&& (p
->autokillid
== -1)) {
13620 if (!p
->jointcapability
)
13621 msg
= "488 Not Acceptable Here (codec error)";
13623 ast_log(LOG_NOTICE
, "Unable to create/find SIP channel for this INVITE\n");
13624 msg
= "503 Unavailable";
13626 if (ast_test_flag(req
, SIP_PKT_IGNORE
))
13627 transmit_response(p
, msg
, req
);
13629 transmit_response_reliable(p
, msg
, req
);
13630 p
->invitestate
= INV_COMPLETED
;
13631 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13637 /*! \brief Find all call legs and bridge transferee with target
13638 * called from handle_request_refer */
13639 static int local_attended_transfer(struct sip_pvt
*transferer
, struct sip_dual
*current
, struct sip_request
*req
, int seqno
)
13641 struct sip_dual target
; /* Chan 1: Call from tranferer to Asterisk */
13642 /* Chan 2: Call from Asterisk to target */
13644 struct sip_pvt
*targetcall_pvt
;
13646 /* Check if the call ID of the replaces header does exist locally */
13647 if (!(targetcall_pvt
= get_sip_pvt_byid_locked(transferer
->refer
->replaces_callid
, transferer
->refer
->replaces_callid_totag
,
13648 transferer
->refer
->replaces_callid_fromtag
))) {
13649 if (transferer
->refer
->localtransfer
) {
13650 /* We did not find the refered call. Sorry, can't accept then */
13651 transmit_response(transferer
, "202 Accepted", req
);
13652 /* Let's fake a response from someone else in order
13653 to follow the standard */
13654 transmit_notify_with_sipfrag(transferer
, seqno
, "481 Call leg/transaction does not exist", TRUE
);
13655 append_history(transferer
, "Xfer", "Refer failed");
13656 ast_clear_flag(&transferer
->flags
[0], SIP_GOTREFER
);
13657 transferer
->refer
->status
= REFER_FAILED
;
13660 /* Fall through for remote transfers that we did not find locally */
13661 if (option_debug
> 2)
13662 ast_log(LOG_DEBUG
, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
13666 /* Ok, we can accept this transfer */
13667 transmit_response(transferer
, "202 Accepted", req
);
13668 append_history(transferer
, "Xfer", "Refer accepted");
13669 if (!targetcall_pvt
->owner
) { /* No active channel */
13670 if (option_debug
> 3)
13671 ast_log(LOG_DEBUG
, "SIP attended transfer: Error: No owner of target call\n");
13672 /* Cancel transfer */
13673 transmit_notify_with_sipfrag(transferer
, seqno
, "503 Service Unavailable", TRUE
);
13674 append_history(transferer
, "Xfer", "Refer failed");
13675 ast_clear_flag(&transferer
->flags
[0], SIP_GOTREFER
);
13676 transferer
->refer
->status
= REFER_FAILED
;
13677 ast_mutex_unlock(&targetcall_pvt
->lock
);
13678 ast_channel_unlock(current
->chan1
);
13679 ast_channel_unlock(targetcall_pvt
->owner
);
13683 /* We have a channel, find the bridge */
13684 target
.chan1
= targetcall_pvt
->owner
; /* Transferer to Asterisk */
13685 target
.chan2
= ast_bridged_channel(targetcall_pvt
->owner
); /* Asterisk to target */
13687 if (!target
.chan2
|| !(target
.chan2
->_state
== AST_STATE_UP
|| target
.chan2
->_state
== AST_STATE_RINGING
) ) {
13688 /* Wrong state of new channel */
13689 if (option_debug
> 3) {
13691 ast_log(LOG_DEBUG
, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target
.chan2
->_state
));
13692 else if (target
.chan1
->_state
!= AST_STATE_RING
)
13693 ast_log(LOG_DEBUG
, "SIP attended transfer: Error: No target channel\n");
13695 ast_log(LOG_DEBUG
, "SIP attended transfer: Attempting transfer in ringing state\n");
13700 if (option_debug
> 3 && sipdebug
) {
13701 if (current
->chan2
) /* We have two bridges */
13702 ast_log(LOG_DEBUG
, "SIP attended transfer: trying to bridge %s and %s\n", target
.chan1
->name
, current
->chan2
->name
);
13703 else /* One bridge, propably transfer of IVR/voicemail etc */
13704 ast_log(LOG_DEBUG
, "SIP attended transfer: trying to make %s take over (masq) %s\n", target
.chan1
->name
, current
->chan1
->name
);
13707 ast_set_flag(&transferer
->flags
[0], SIP_DEFER_BYE_ON_TRANSFER
); /* Delay hangup */
13709 /* Perform the transfer */
13710 res
= attempt_transfer(current
, &target
);
13711 ast_mutex_unlock(&targetcall_pvt
->lock
);
13713 /* Failed transfer */
13714 /* Could find better message, but they will get the point */
13715 transmit_notify_with_sipfrag(transferer
, seqno
, "486 Busy", TRUE
);
13716 append_history(transferer
, "Xfer", "Refer failed");
13717 if (targetcall_pvt
->owner
)
13718 ast_channel_unlock(targetcall_pvt
->owner
);
13719 /* Right now, we have to hangup, sorry. Bridge is destroyed */
13720 ast_hangup(transferer
->owner
);
13722 /* Transfer succeeded! */
13724 /* Tell transferer that we're done. */
13725 transmit_notify_with_sipfrag(transferer
, seqno
, "200 OK", TRUE
);
13726 append_history(transferer
, "Xfer", "Refer succeeded");
13727 transferer
->refer
->status
= REFER_200OK
;
13728 if (targetcall_pvt
->owner
) {
13730 ast_log(LOG_DEBUG
, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt
->owner
->name
);
13731 ast_channel_unlock(targetcall_pvt
->owner
);
13738 /*! \brief Handle incoming REFER request */
13739 /*! \page SIP_REFER SIP transfer Support (REFER)
13741 REFER is used for call transfer in SIP. We get a REFER
13742 to place a new call with an INVITE somwhere and then
13743 keep the transferor up-to-date of the transfer. If the
13744 transfer fails, get back on line with the orginal call.
13746 - REFER can be sent outside or inside of a dialog.
13747 Asterisk only accepts REFER inside of a dialog.
13749 - If we get a replaces header, it is an attended transfer
13751 \par Blind transfers
13752 The transferor provides the transferee
13753 with the transfer targets contact. The signalling between
13754 transferer or transferee should not be cancelled, so the
13755 call is recoverable if the transfer target can not be reached
13758 In this case, Asterisk receives a TRANSFER from
13759 the transferor, thus is the transferee. We should
13760 try to set up a call to the contact provided
13761 and if that fails, re-connect the current session.
13762 If the new call is set up, we issue a hangup.
13763 In this scenario, we are following section 5.2
13764 in the SIP CC Transfer draft. (Transfer without
13767 \par Transfer with consultation hold
13768 In this case, the transferor
13769 talks to the transfer target before the transfer takes place.
13770 This is implemented with SIP hold and transfer.
13771 Note: The invite From: string could indicate a transfer.
13772 (Section 6. Transfer with consultation hold)
13773 The transferor places the transferee on hold, starts a call
13774 with the transfer target to alert them to the impending
13775 transfer, terminates the connection with the target, then
13776 proceeds with the transfer (as in Blind transfer above)
13778 \par Attended transfer
13779 The transferor places the transferee
13780 on hold, calls the transfer target to alert them,
13781 places the target on hold, then proceeds with the transfer
13782 using a Replaces header field in the Refer-to header. This
13783 will force the transfee to send an Invite to the target,
13784 with a replaces header that instructs the target to
13785 hangup the call between the transferor and the target.
13786 In this case, the Refer/to: uses the AOR address. (The same
13787 URI that the transferee used to establish the session with
13788 the transfer target (To: ). The Require: replaces header should
13789 be in the INVITE to avoid the wrong UA in a forked SIP proxy
13790 scenario to answer and have no call to replace with.
13792 The referred-by header is *NOT* required, but if we get it,
13793 can be copied into the INVITE to the transfer target to
13794 inform the target about the transferor
13796 "Any REFER request has to be appropriately authenticated.".
13798 We can't destroy dialogs, since we want the call to continue.
13801 static int handle_request_refer(struct sip_pvt
*p
, struct sip_request
*req
, int debug
, int ignore
, int seqno
, int *nounlock
)
13803 struct sip_dual current
; /* Chan1: Call between asterisk and transferer */
13804 /* Chan2: Call between asterisk and transferee */
13808 if (ast_test_flag(req
, SIP_PKT_DEBUG
))
13809 ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n", p
->callid
, ast_test_flag(&p
->flags
[0], SIP_OUTGOING
) ? "callee" : "caller");
13812 /* This is a REFER outside of an existing SIP dialog */
13813 /* We can't handle that, so decline it */
13814 if (option_debug
> 2)
13815 ast_log(LOG_DEBUG
, "Call %s: Declined REFER, outside of dialog...\n", p
->callid
);
13816 transmit_response(p
, "603 Declined (No dialog)", req
);
13817 if (!ast_test_flag(req
, SIP_PKT_IGNORE
)) {
13818 append_history(p
, "Xfer", "Refer failed. Outside of dialog.");
13819 sip_alreadygone(p
);
13820 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
13826 /* Check if transfer is allowed from this device */
13827 if (p
->allowtransfer
== TRANSFER_CLOSED
) {
13828 /* Transfer not allowed, decline */
13829 transmit_response(p
, "603 Declined (policy)", req
);
13830 append_history(p
, "Xfer", "Refer failed. Allowtransfer == closed.");
13831 /* Do not destroy SIP session */
13835 if(!ignore
&& ast_test_flag(&p
->flags
[0], SIP_GOTREFER
)) {
13836 /* Already have a pending REFER */
13837 transmit_response(p
, "491 Request pending", req
);
13838 append_history(p
, "Xfer", "Refer failed. Request pending.");
13842 /* Allocate memory for call transfer data */
13843 if (!p
->refer
&& !sip_refer_allocate(p
)) {
13844 transmit_response(p
, "500 Internal Server Error", req
);
13845 append_history(p
, "Xfer", "Refer failed. Memory allocation error.");
13849 res
= get_refer_info(p
, req
); /* Extract headers */
13851 p
->refer
->status
= REFER_SENT
;
13855 case -2: /* Syntax error */
13856 transmit_response(p
, "400 Bad Request (Refer-to missing)", req
);
13857 append_history(p
, "Xfer", "Refer failed. Refer-to missing.");
13858 if (ast_test_flag(req
, SIP_PKT_DEBUG
) && option_debug
)
13859 ast_log(LOG_DEBUG
, "SIP transfer to black hole can't be handled (no refer-to: )\n");
13862 transmit_response(p
, "603 Declined (Non sip: uri)", req
);
13863 append_history(p
, "Xfer", "Refer failed. Non SIP uri");
13864 if (ast_test_flag(req
, SIP_PKT_DEBUG
) && option_debug
)
13865 ast_log(LOG_DEBUG
, "SIP transfer to non-SIP uri denied\n");
13868 /* Refer-to extension not found, fake a failed transfer */
13869 transmit_response(p
, "202 Accepted", req
);
13870 append_history(p
, "Xfer", "Refer failed. Bad extension.");
13871 transmit_notify_with_sipfrag(p
, seqno
, "404 Not found", TRUE
);
13872 ast_clear_flag(&p
->flags
[0], SIP_GOTREFER
);
13873 if (ast_test_flag(req
, SIP_PKT_DEBUG
) && option_debug
)
13874 ast_log(LOG_DEBUG
, "SIP transfer to bad extension: %s\n", p
->refer
->refer_to
);
13879 if (ast_strlen_zero(p
->context
))
13880 ast_string_field_set(p
, context
, default_context
);
13882 /* If we do not support SIP domains, all transfers are local */
13883 if (allow_external_domains
&& check_sip_domain(p
->refer
->refer_to_domain
, NULL
, 0)) {
13884 p
->refer
->localtransfer
= 1;
13885 if (sipdebug
&& option_debug
> 2)
13886 ast_log(LOG_DEBUG
, "This SIP transfer is local : %s\n", p
->refer
->refer_to_domain
);
13887 } else if (AST_LIST_EMPTY(&domain_list
)) {
13888 /* This PBX don't bother with SIP domains, so all transfers are local */
13889 p
->refer
->localtransfer
= 1;
13891 if (sipdebug
&& option_debug
> 2)
13892 ast_log(LOG_DEBUG
, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p
->refer
->refer_to_domain
);
13894 /* Is this a repeat of a current request? Ignore it */
13895 /* Don't know what else to do right now. */
13899 /* If this is a blind transfer, we have the following
13900 channels to work with:
13901 - chan1, chan2: The current call between transferer and transferee (2 channels)
13902 - target_channel: A new call from the transferee to the target (1 channel)
13903 We need to stay tuned to what happens in order to be able
13904 to bring back the call to the transferer */
13906 /* If this is a attended transfer, we should have all call legs within reach:
13907 - chan1, chan2: The call between the transferer and transferee (2 channels)
13908 - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
13909 We want to bridge chan2 with targetcall_pvt!
13911 The replaces call id in the refer message points
13912 to the call leg between Asterisk and the transferer.
13913 So we need to connect the target and the transferee channel
13914 and hangup the two other channels silently
13916 If the target is non-local, the call ID could be on a remote
13917 machine and we need to send an INVITE with replaces to the
13918 target. We basically handle this as a blind transfer
13919 and let the sip_call function catch that we need replaces
13920 header in the INVITE.
13924 /* Get the transferer's channel */
13925 current
.chan1
= p
->owner
;
13927 /* Find the other part of the bridge (2) - transferee */
13928 current
.chan2
= ast_bridged_channel(current
.chan1
);
13930 if (sipdebug
&& option_debug
> 2)
13931 ast_log(LOG_DEBUG
, "SIP %s transfer: Transferer channel %s, transferee channel %s\n", p
->refer
->attendedtransfer
? "attended" : "blind", current
.chan1
->name
, current
.chan2
? current
.chan2
->name
: "<none>");
13933 if (!current
.chan2
&& !p
->refer
->attendedtransfer
) {
13934 /* No bridged channel, propably IVR or echo or similar... */
13935 /* Guess we should masquerade or something here */
13936 /* Until we figure it out, refuse transfer of such calls */
13937 if (sipdebug
&& option_debug
> 2)
13938 ast_log(LOG_DEBUG
,"Refused SIP transfer on non-bridged channel.\n");
13939 p
->refer
->status
= REFER_FAILED
;
13940 append_history(p
, "Xfer", "Refer failed. Non-bridged channel.");
13941 transmit_response(p
, "603 Declined", req
);
13945 if (current
.chan2
) {
13946 if (sipdebug
&& option_debug
> 3)
13947 ast_log(LOG_DEBUG
, "Got SIP transfer, applying to bridged peer '%s'\n", current
.chan2
->name
);
13949 ast_queue_control(current
.chan1
, AST_CONTROL_UNHOLD
);
13952 ast_set_flag(&p
->flags
[0], SIP_GOTREFER
);
13954 /* Attended transfer: Find all call legs and bridge transferee with target*/
13955 if (p
->refer
->attendedtransfer
) {
13956 if ((res
= local_attended_transfer(p
, ¤t
, req
, seqno
)))
13957 return res
; /* We're done with the transfer */
13958 /* Fall through for remote transfers that we did not find locally */
13959 if (sipdebug
&& option_debug
> 3)
13960 ast_log(LOG_DEBUG
, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
13961 /* Fallthrough if we can't find the call leg internally */
13965 /* Parking a call */
13966 if (p
->refer
->localtransfer
&& !strcmp(p
->refer
->refer_to
, ast_parking_ext())) {
13967 /* Must release c's lock now, because it will not longer be accessible after the transfer! */
13969 ast_channel_unlock(current
.chan1
);
13970 copy_request(¤t
.req
, req
);
13971 ast_clear_flag(&p
->flags
[0], SIP_GOTREFER
);
13972 p
->refer
->status
= REFER_200OK
;
13973 append_history(p
, "Xfer", "REFER to call parking.");
13974 if (sipdebug
&& option_debug
> 3)
13975 ast_log(LOG_DEBUG
, "SIP transfer to parking: trying to park %s. Parked by %s\n", current
.chan2
->name
, current
.chan1
->name
);
13976 sip_park(current
.chan2
, current
.chan1
, req
, seqno
);
13980 /* Blind transfers and remote attended xfers */
13981 transmit_response(p
, "202 Accepted", req
);
13983 if (current
.chan1
&& current
.chan2
) {
13984 if (option_debug
> 2)
13985 ast_log(LOG_DEBUG
, "chan1->name: %s\n", current
.chan1
->name
);
13986 pbx_builtin_setvar_helper(current
.chan1
, "BLINDTRANSFER", current
.chan2
->name
);
13988 if (current
.chan2
) {
13989 pbx_builtin_setvar_helper(current
.chan2
, "BLINDTRANSFER", current
.chan1
->name
);
13990 pbx_builtin_setvar_helper(current
.chan2
, "SIPDOMAIN", p
->refer
->refer_to_domain
);
13991 pbx_builtin_setvar_helper(current
.chan2
, "SIPTRANSFER", "yes");
13992 /* One for the new channel */
13993 pbx_builtin_setvar_helper(current
.chan2
, "_SIPTRANSFER", "yes");
13994 /* Attended transfer to remote host, prepare headers for the INVITE */
13995 if (p
->refer
->referred_by
)
13996 pbx_builtin_setvar_helper(current
.chan2
, "_SIPTRANSFER_REFERER", p
->refer
->referred_by
);
13998 /* Generate a Replaces string to be used in the INVITE during attended transfer */
13999 if (p
->refer
->replaces_callid
&& !ast_strlen_zero(p
->refer
->replaces_callid
)) {
14000 char tempheader
[BUFSIZ
];
14001 snprintf(tempheader
, sizeof(tempheader
), "%s%s%s%s%s", p
->refer
->replaces_callid
,
14002 p
->refer
->replaces_callid_totag
? ";to-tag=" : "",
14003 p
->refer
->replaces_callid_totag
,
14004 p
->refer
->replaces_callid_fromtag
? ";from-tag=" : "",
14005 p
->refer
->replaces_callid_fromtag
);
14007 pbx_builtin_setvar_helper(current
.chan2
, "_SIPTRANSFER_REPLACES", tempheader
);
14009 /* Must release lock now, because it will not longer
14010 be accessible after the transfer! */
14012 ast_channel_unlock(current
.chan1
);
14013 ast_channel_unlock(current
.chan2
);
14015 /* Connect the call */
14017 /* FAKE ringing if not attended transfer */
14018 if (!p
->refer
->attendedtransfer
)
14019 transmit_notify_with_sipfrag(p
, seqno
, "183 Ringing", FALSE
);
14021 /* For blind transfer, this will lead to a new call */
14022 /* For attended transfer to remote host, this will lead to
14023 a new SIP call with a replaces header, if the dial plan allows it
14025 if (!current
.chan2
) {
14026 /* We have no bridge, so we're talking with Asterisk somehow */
14027 /* We need to masquerade this call */
14028 /* What to do to fix this situation:
14029 * Set up the new call in a new channel
14030 * Let the new channel masq into this channel
14031 Please add that code here :-)
14033 p
->refer
->status
= REFER_FAILED
;
14034 transmit_notify_with_sipfrag(p
, seqno
, "503 Service Unavailable (can't handle one-legged xfers)", TRUE
);
14035 ast_clear_flag(&p
->flags
[0], SIP_GOTREFER
);
14036 append_history(p
, "Xfer", "Refer failed (only bridged calls).");
14039 ast_set_flag(&p
->flags
[0], SIP_DEFER_BYE_ON_TRANSFER
); /* Delay hangup */
14041 /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
14042 servers - generate an INVITE with Replaces. Either way, let the dial plan decided */
14043 res
= ast_async_goto(current
.chan2
, p
->refer
->refer_to_context
, p
->refer
->refer_to
, 1);
14046 /* Success - we have a new channel */
14047 if (option_debug
> 2)
14048 ast_log(LOG_DEBUG
, "%s transfer succeeded. Telling transferer.\n", p
->refer
->attendedtransfer
? "Attended" : "Blind");
14049 transmit_notify_with_sipfrag(p
, seqno
, "200 Ok", TRUE
);
14050 if (p
->refer
->localtransfer
)
14051 p
->refer
->status
= REFER_200OK
;
14053 p
->owner
->hangupcause
= AST_CAUSE_NORMAL_CLEARING
;
14054 append_history(p
, "Xfer", "Refer succeeded.");
14055 ast_clear_flag(&p
->flags
[0], SIP_GOTREFER
);
14056 /* Do not hangup call, the other side do that when we say 200 OK */
14057 /* We could possibly implement a timer here, auto congestion */
14060 ast_clear_flag(&p
->flags
[0], SIP_DEFER_BYE_ON_TRANSFER
); /* Don't delay hangup */
14061 if (option_debug
> 2)
14062 ast_log(LOG_DEBUG
, "%s transfer failed. Resuming original call.\n", p
->refer
->attendedtransfer
? "Attended" : "Blind");
14063 append_history(p
, "Xfer", "Refer failed.");
14064 /* Failure of some kind */
14065 p
->refer
->status
= REFER_FAILED
;
14066 transmit_notify_with_sipfrag(p
, seqno
, "503 Service Unavailable", TRUE
);
14067 ast_clear_flag(&p
->flags
[0], SIP_GOTREFER
);
14073 /*! \brief Handle incoming CANCEL request */
14074 static int handle_request_cancel(struct sip_pvt
*p
, struct sip_request
*req
)
14078 sip_alreadygone(p
);
14079 p
->invitestate
= INV_CANCELLED
;
14081 if (p
->owner
&& p
->owner
->_state
== AST_STATE_UP
) {
14082 /* This call is up, cancel is ignored, we need a bye */
14083 transmit_response(p
, "200 OK", req
);
14085 ast_log(LOG_DEBUG
, "Got CANCEL on an answered call. Ignoring... \n");
14088 stop_media_flows(p
); /* Immediately stop RTP, VRTP and UDPTL as applicable */
14091 ast_queue_hangup(p
->owner
);
14093 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
14094 if (p
->initreq
.len
> 0) {
14095 transmit_response_reliable(p
, "487 Request Terminated", &p
->initreq
);
14096 transmit_response(p
, "200 OK", req
);
14099 transmit_response(p
, "481 Call Leg Does Not Exist", req
);
14104 /*! \brief Handle incoming BYE request */
14105 static int handle_request_bye(struct sip_pvt
*p
, struct sip_request
*req
)
14107 struct ast_channel
*c
=NULL
;
14109 struct ast_channel
*bridged_to
;
14111 /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
14112 if (p
->pendinginvite
&& !ast_test_flag(&p
->flags
[0], SIP_OUTGOING
) && !ast_test_flag(req
, SIP_PKT_IGNORE
) && !p
->owner
)
14113 transmit_response_reliable(p
, "487 Request Terminated", &p
->initreq
);
14115 p
->invitestate
= INV_TERMINATED
;
14117 copy_request(&p
->initreq
, req
);
14119 sip_alreadygone(p
);
14121 /* Get RTCP quality before end of call */
14122 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
) || p
->owner
) {
14123 char *audioqos
, *videoqos
;
14125 audioqos
= ast_rtp_get_quality(p
->rtp
);
14126 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
))
14127 append_history(p
, "RTCPaudio", "Quality:%s", audioqos
);
14129 pbx_builtin_setvar_helper(p
->owner
, "RTPAUDIOQOS", audioqos
);
14132 videoqos
= ast_rtp_get_quality(p
->vrtp
);
14133 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
))
14134 append_history(p
, "RTCPvideo", "Quality:%s", videoqos
);
14136 pbx_builtin_setvar_helper(p
->owner
, "RTPVIDEOQOS", videoqos
);
14140 stop_media_flows(p
); /* Immediately stop RTP, VRTP and UDPTL as applicable */
14142 if (!ast_strlen_zero(get_header(req
, "Also"))) {
14143 ast_log(LOG_NOTICE
, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
14144 ast_inet_ntoa(p
->recv
.sin_addr
));
14145 if (ast_strlen_zero(p
->context
))
14146 ast_string_field_set(p
, context
, default_context
);
14147 res
= get_also_info(p
, req
);
14151 bridged_to
= ast_bridged_channel(c
);
14153 /* Don't actually hangup here... */
14154 ast_queue_control(c
, AST_CONTROL_UNHOLD
);
14155 ast_async_goto(bridged_to
, p
->context
, p
->refer
->refer_to
,1);
14157 ast_queue_hangup(p
->owner
);
14160 ast_log(LOG_WARNING
, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p
->recv
.sin_addr
));
14162 ast_queue_hangup(p
->owner
);
14164 } else if (p
->owner
) {
14165 ast_queue_hangup(p
->owner
);
14166 if (option_debug
> 2)
14167 ast_log(LOG_DEBUG
, "Received bye, issuing owner hangup\n");
14169 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
14170 if (option_debug
> 2)
14171 ast_log(LOG_DEBUG
, "Received bye, no owner, selfdestruct soon.\n");
14173 transmit_response(p
, "200 OK", req
);
14178 /*! \brief Handle incoming MESSAGE request */
14179 static int handle_request_message(struct sip_pvt
*p
, struct sip_request
*req
)
14181 if (!ast_test_flag(req
, SIP_PKT_IGNORE
)) {
14182 if (ast_test_flag(req
, SIP_PKT_DEBUG
))
14183 ast_verbose("Receiving message!\n");
14184 receive_message(p
, req
);
14186 transmit_response(p
, "202 Accepted", req
);
14190 /*! \brief Handle incoming SUBSCRIBE request */
14191 static int handle_request_subscribe(struct sip_pvt
*p
, struct sip_request
*req
, struct sockaddr_in
*sin
, int seqno
, char *e
)
14195 int firststate
= AST_EXTENSION_REMOVED
;
14196 struct sip_peer
*authpeer
= NULL
;
14197 const char *eventheader
= get_header(req
, "Event"); /* Get Event package name */
14198 const char *accept
= get_header(req
, "Accept");
14199 int resubscribe
= (p
->subscribed
!= NONE
);
14200 char *temp
, *event
;
14202 if (p
->initreq
.headers
) {
14203 /* We already have a dialog */
14204 if (p
->initreq
.method
!= SIP_SUBSCRIBE
) {
14205 /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
14206 /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
14207 transmit_response(p
, "403 Forbidden (within dialog)", req
);
14208 /* Do not destroy session, since we will break the call if we do */
14210 ast_log(LOG_DEBUG
, "Got a subscription within the context of another call, can't handle that - %s (Method %s)\n", p
->callid
, sip_methods
[p
->initreq
.method
].text
);
14212 } else if (ast_test_flag(req
, SIP_PKT_DEBUG
)) {
14213 if (option_debug
) {
14215 ast_log(LOG_DEBUG
, "Got a re-subscribe on existing subscription %s\n", p
->callid
);
14217 ast_log(LOG_DEBUG
, "Got a new subscription %s (possibly with auth)\n", p
->callid
);
14222 /* Check if we have a global disallow setting on subscriptions.
14223 if so, we don't have to check peer/user settings after auth, which saves a lot of processing
14225 if (!global_allowsubscribe
) {
14226 transmit_response(p
, "403 Forbidden (policy)", req
);
14227 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14231 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && !resubscribe
) { /* Set up dialog, new subscription */
14232 /* Use this as the basis */
14233 if (ast_test_flag(req
, SIP_PKT_DEBUG
))
14234 ast_verbose("Creating new subscription\n");
14236 copy_request(&p
->initreq
, req
);
14238 } else if (ast_test_flag(req
, SIP_PKT_DEBUG
) && ast_test_flag(req
, SIP_PKT_IGNORE
))
14239 ast_verbose("Ignoring this SUBSCRIBE request\n");
14241 /* Find parameters to Event: header value and remove them for now */
14242 if (ast_strlen_zero(eventheader
)) {
14243 transmit_response(p
, "489 Bad Event", req
);
14244 if (option_debug
> 1)
14245 ast_log(LOG_DEBUG
, "Received SIP subscribe for unknown event package: <none>\n");
14246 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14250 if ( (strchr(eventheader
, ';'))) {
14251 event
= ast_strdupa(eventheader
); /* Since eventheader is a const, we can't change it */
14252 temp
= strchr(event
, ';');
14253 *temp
= '\0'; /* Remove any options for now */
14254 /* We might need to use them later :-) */
14256 event
= (char *) eventheader
; /* XXX is this legal ? */
14258 /* Handle authentication */
14259 res
= check_user_full(p
, req
, SIP_SUBSCRIBE
, e
, 0, sin
, &authpeer
);
14260 /* if an authentication response was sent, we are done here */
14261 if (res
== AUTH_CHALLENGE_SENT
) {
14263 ASTOBJ_UNREF(authpeer
, sip_destroy_peer
);
14267 if (res
== AUTH_FAKE_AUTH
) {
14268 ast_log(LOG_NOTICE
, "Sending fake auth rejection for user %s\n", get_header(req
, "From"));
14269 transmit_fake_auth_response(p
, req
, 1);
14271 ast_log(LOG_NOTICE
, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req
, "From"));
14272 transmit_response_reliable(p
, "403 Forbidden", req
);
14274 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14276 ASTOBJ_UNREF(authpeer
, sip_destroy_peer
);
14280 /* Check if this user/peer is allowed to subscribe at all */
14281 if (!ast_test_flag(&p
->flags
[1], SIP_PAGE2_ALLOWSUBSCRIBE
)) {
14282 transmit_response(p
, "403 Forbidden (policy)", req
);
14283 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14285 ASTOBJ_UNREF(authpeer
, sip_destroy_peer
);
14289 /* Get destination right away */
14290 gotdest
= get_destination(p
, NULL
);
14292 /* Initialize the context if it hasn't been already;
14293 note this is done _after_ handling any domain lookups,
14294 because the context specified there is for calls, not
14297 if (!ast_strlen_zero(p
->subscribecontext
))
14298 ast_string_field_set(p
, context
, p
->subscribecontext
);
14299 else if (ast_strlen_zero(p
->context
))
14300 ast_string_field_set(p
, context
, default_context
);
14304 transmit_response(p
, "404 Not Found", req
);
14305 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14307 ASTOBJ_UNREF(authpeer
, sip_destroy_peer
);
14311 /* Initialize tag for new subscriptions */
14312 if (ast_strlen_zero(p
->tag
))
14313 make_our_tag(p
->tag
, sizeof(p
->tag
));
14315 if (!strcmp(event
, "presence") || !strcmp(event
, "dialog")) { /* Presence, RFC 3842 */
14316 if (authpeer
) /* No need for authpeer here */
14317 ASTOBJ_UNREF(authpeer
, sip_destroy_peer
);
14319 /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
14320 /* Polycom phones only handle xpidf+xml, even if they say they can
14321 handle pidf+xml as well
14323 if (strstr(p
->useragent
, "Polycom")) {
14324 p
->subscribed
= XPIDF_XML
;
14325 } else if (strstr(accept
, "application/pidf+xml")) {
14326 p
->subscribed
= PIDF_XML
; /* RFC 3863 format */
14327 } else if (strstr(accept
, "application/dialog-info+xml")) {
14328 p
->subscribed
= DIALOG_INFO_XML
;
14329 /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
14330 } else if (strstr(accept
, "application/cpim-pidf+xml")) {
14331 p
->subscribed
= CPIM_PIDF_XML
; /* RFC 3863 format */
14332 } else if (strstr(accept
, "application/xpidf+xml")) {
14333 p
->subscribed
= XPIDF_XML
; /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
14335 /* Can't find a format for events that we know about */
14336 transmit_response(p
, "489 Bad Event", req
);
14337 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14340 } else if (!strcmp(event
, "message-summary")) {
14341 if (!ast_strlen_zero(accept
) && strcmp(accept
, "application/simple-message-summary")) {
14342 /* Format requested that we do not support */
14343 transmit_response(p
, "406 Not Acceptable", req
);
14344 if (option_debug
> 1)
14345 ast_log(LOG_DEBUG
, "Received SIP mailbox subscription for unknown format: %s\n", accept
);
14346 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14347 if (authpeer
) /* No need for authpeer here */
14348 ASTOBJ_UNREF(authpeer
, sip_destroy_peer
);
14351 /* Looks like they actually want a mailbox status
14352 This version of Asterisk supports mailbox subscriptions
14353 The subscribed URI needs to exist in the dial plan
14354 In most devices, this is configurable to the voicemailmain extension you use
14356 if (!authpeer
|| ast_strlen_zero(authpeer
->mailbox
)) {
14357 transmit_response(p
, "404 Not found (no mailbox)", req
);
14358 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14359 ast_log(LOG_NOTICE
, "Received SIP subscribe for peer without mailbox: %s\n", authpeer
->name
);
14360 if (authpeer
) /* No need for authpeer here */
14361 ASTOBJ_UNREF(authpeer
, sip_destroy_peer
);
14365 p
->subscribed
= MWI_NOTIFICATION
;
14366 if (authpeer
->mwipvt
&& authpeer
->mwipvt
!= p
) /* Destroy old PVT if this is a new one */
14367 /* We only allow one subscription per peer */
14368 sip_destroy(authpeer
->mwipvt
);
14369 authpeer
->mwipvt
= p
; /* Link from peer to pvt */
14370 p
->relatedpeer
= authpeer
; /* Link from pvt to peer */
14371 } else { /* At this point, Asterisk does not understand the specified event */
14372 transmit_response(p
, "489 Bad Event", req
);
14373 if (option_debug
> 1)
14374 ast_log(LOG_DEBUG
, "Received SIP subscribe for unknown event package: %s\n", event
);
14375 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14376 if (authpeer
) /* No need for authpeer here */
14377 ASTOBJ_UNREF(authpeer
, sip_destroy_peer
);
14381 if (p
->subscribed
!= MWI_NOTIFICATION
&& !resubscribe
)
14382 p
->stateid
= ast_extension_state_add(p
->context
, p
->exten
, cb_extensionstate
, p
);
14384 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && p
)
14385 p
->lastinvite
= seqno
;
14386 if (p
&& !ast_test_flag(&p
->flags
[0], SIP_NEEDDESTROY
)) {
14387 p
->expiry
= atoi(get_header(req
, "Expires"));
14389 /* check if the requested expiry-time is within the approved limits from sip.conf */
14390 if (p
->expiry
> max_expiry
)
14391 p
->expiry
= max_expiry
;
14392 if (p
->expiry
< min_expiry
&& p
->expiry
> 0)
14393 p
->expiry
= min_expiry
;
14395 if (sipdebug
|| option_debug
> 1) {
14396 if (p
->subscribed
== MWI_NOTIFICATION
&& p
->relatedpeer
)
14397 ast_log(LOG_DEBUG
, "Adding subscription for mailbox notification - peer %s Mailbox %s\n", p
->relatedpeer
->name
, p
->relatedpeer
->mailbox
);
14399 ast_log(LOG_DEBUG
, "Adding subscription for extension %s context %s for peer %s\n", p
->exten
, p
->context
, p
->username
);
14401 if (p
->autokillid
> -1)
14402 sip_cancel_destroy(p
); /* Remove subscription expiry for renewals */
14404 sip_scheddestroy(p
, (p
->expiry
+ 10) * 1000); /* Set timer for destruction of call at expiration */
14406 if (p
->subscribed
== MWI_NOTIFICATION
) {
14407 transmit_response(p
, "200 OK", req
);
14408 if (p
->relatedpeer
) { /* Send first notification */
14409 ASTOBJ_WRLOCK(p
->relatedpeer
);
14410 sip_send_mwi_to_peer(p
->relatedpeer
);
14411 ASTOBJ_UNLOCK(p
->relatedpeer
);
14414 struct sip_pvt
*p_old
;
14416 if ((firststate
= ast_extension_state(NULL
, p
->context
, p
->exten
)) < 0) {
14418 ast_log(LOG_NOTICE
, "Got SUBSCRIBE for extension %s@%s from %s, but there is no hint for that extension.\n", p
->exten
, p
->context
, ast_inet_ntoa(p
->sa
.sin_addr
));
14419 transmit_response(p
, "404 Not found", req
);
14420 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14424 transmit_response(p
, "200 OK", req
);
14425 transmit_state_notify(p
, firststate
, 1, FALSE
); /* Send first notification */
14426 append_history(p
, "Subscribestatus", "%s", ast_extension_state2str(firststate
));
14427 /* hide the 'complete' exten/context in the refer_to field for later display */
14428 ast_string_field_build(p
, subscribeuri
, "%s@%s", p
->exten
, p
->context
);
14430 /* remove any old subscription from this peer for the same exten/context,
14431 as the peer has obviously forgotten about it and it's wasteful to wait
14432 for it to expire and send NOTIFY messages to the peer only to have them
14433 ignored (or generate errors)
14435 ast_mutex_lock(&iflock
);
14436 for (p_old
= iflist
; p_old
; p_old
= p_old
->next
) {
14439 if (p_old
->initreq
.method
!= SIP_SUBSCRIBE
)
14441 if (p_old
->subscribed
== NONE
)
14443 ast_mutex_lock(&p_old
->lock
);
14444 if (!strcmp(p_old
->username
, p
->username
)) {
14445 if (!strcmp(p_old
->exten
, p
->exten
) &&
14446 !strcmp(p_old
->context
, p
->context
)) {
14447 ast_set_flag(&p_old
->flags
[0], SIP_NEEDDESTROY
);
14448 ast_mutex_unlock(&p_old
->lock
);
14452 ast_mutex_unlock(&p_old
->lock
);
14454 ast_mutex_unlock(&iflock
);
14457 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14462 /*! \brief Handle incoming REGISTER request */
14463 static int handle_request_register(struct sip_pvt
*p
, struct sip_request
*req
, struct sockaddr_in
*sin
, char *e
)
14465 enum check_auth_result res
;
14467 /* Use this as the basis */
14468 if (ast_test_flag(req
, SIP_PKT_DEBUG
))
14469 ast_verbose("Using latest REGISTER request as basis request\n");
14470 copy_request(&p
->initreq
, req
);
14472 if ((res
= register_verify(p
, sin
, req
, e
)) < 0) {
14473 const char *reason
= "";
14476 case AUTH_SECRET_FAILED
:
14477 reason
= "Wrong password";
14479 case AUTH_USERNAME_MISMATCH
:
14480 reason
= "Username/auth name mismatch";
14482 case AUTH_NOT_FOUND
:
14483 reason
= "No matching peer found";
14485 case AUTH_UNKNOWN_DOMAIN
:
14486 reason
= "Not a local domain";
14491 ast_log(LOG_NOTICE
, "Registration from '%s' failed for '%s' - %s\n",
14492 get_header(req
, "To"), ast_inet_ntoa(sin
->sin_addr
),
14496 /* Destroy the session, but keep us around for just a bit in case they don't
14498 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
14500 append_history(p
, "RegRequest", "%s : Account %s", res
? "Failed": "Succeeded", get_header(req
, "To"));
14504 /*! \brief Handle incoming SIP requests (methods)
14505 \note This is where all incoming requests go first */
14506 /* called with p and p->owner locked */
14507 static int handle_request(struct sip_pvt
*p
, struct sip_request
*req
, struct sockaddr_in
*sin
, int *recount
, int *nounlock
)
14509 /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
14510 relatively static */
14513 const char *useragent
;
14516 int ignore
= FALSE
;
14519 int debug
= sip_debug_test_pvt(p
);
14523 /* Get Method and Cseq */
14524 cseq
= get_header(req
, "Cseq");
14525 cmd
= req
->header
[0];
14527 /* Must have Cseq */
14528 if (ast_strlen_zero(cmd
) || ast_strlen_zero(cseq
)) {
14529 ast_log(LOG_ERROR
, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
14532 if (!error
&& sscanf(cseq
, "%d%n", &seqno
, &len
) != 1) {
14533 ast_log(LOG_ERROR
, "No seqno in '%s'. Dropping incomplete message.\n", cmd
);
14537 if (!p
->initreq
.headers
) /* New call */
14538 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
); /* Make sure we destroy this dialog */
14541 /* Get the command XXX */
14543 cmd
= req
->rlPart1
;
14546 /* Save useragent of the client */
14547 useragent
= get_header(req
, "User-Agent");
14548 if (!ast_strlen_zero(useragent
))
14549 ast_string_field_set(p
, useragent
, useragent
);
14551 /* Find out SIP method for incoming request */
14552 if (req
->method
== SIP_RESPONSE
) { /* Response to our request */
14553 /* Response to our request -- Do some sanity checks */
14554 if (!p
->initreq
.headers
) {
14556 ast_log(LOG_DEBUG
, "That's odd... Got a response on a call we dont know about. Cseq %d Cmd %s\n", seqno
, cmd
);
14557 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14559 } else if (p
->ocseq
&& (p
->ocseq
< seqno
)) {
14561 ast_log(LOG_DEBUG
, "Ignoring out of order response %d (expecting %d)\n", seqno
, p
->ocseq
);
14563 } else if (p
->ocseq
&& (p
->ocseq
!= seqno
)) {
14564 /* ignore means "don't do anything with it" but still have to
14565 respond appropriately */
14567 ast_set_flag(req
, SIP_PKT_IGNORE
);
14568 ast_set_flag(req
, SIP_PKT_IGNORE_RESP
);
14569 append_history(p
, "Ignore", "Ignoring this retransmit\n");
14572 e
= ast_skip_blanks(e
);
14573 if (sscanf(e
, "%d %n", &respid
, &len
) != 1) {
14574 ast_log(LOG_WARNING
, "Invalid response: '%s'\n", e
);
14576 /* More SIP ridiculousness, we have to ignore bogus contacts in 100 etc responses */
14577 if ((respid
== 200) || ((respid
>= 300) && (respid
<= 399)))
14578 extract_uri(p
, req
);
14579 handle_response(p
, respid
, e
+ len
, req
, ignore
, seqno
);
14584 /* New SIP request coming in
14585 (could be new request in existing SIP dialog as well...)
14588 p
->method
= req
->method
; /* Find out which SIP method they are using */
14589 if (option_debug
> 3)
14590 ast_log(LOG_DEBUG
, "**** Received %s (%d) - Command in SIP %s\n", sip_methods
[p
->method
].text
, sip_methods
[p
->method
].id
, cmd
);
14592 if (p
->icseq
&& (p
->icseq
> seqno
)) {
14594 ast_log(LOG_DEBUG
, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno
, p
->icseq
);
14595 if (req
->method
!= SIP_ACK
)
14596 transmit_response(p
, "503 Server error", req
); /* We must respond according to RFC 3261 sec 12.2 */
14598 } else if (p
->icseq
&&
14599 p
->icseq
== seqno
&&
14600 req
->method
!= SIP_ACK
&&
14601 (p
->method
!= SIP_CANCEL
|| ast_test_flag(&p
->flags
[0], SIP_ALREADYGONE
))) {
14602 /* ignore means "don't do anything with it" but still have to
14603 respond appropriately. We do this if we receive a repeat of
14604 the last sequence number */
14606 ast_set_flag(req
, SIP_PKT_IGNORE
);
14607 ast_set_flag(req
, SIP_PKT_IGNORE_REQ
);
14608 if (option_debug
> 2)
14609 ast_log(LOG_DEBUG
, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods
[p
->method
].text
, p
->icseq
, seqno
);
14612 if (seqno
>= p
->icseq
)
14613 /* Next should follow monotonically (but not necessarily
14614 incrementally -- thanks again to the genius authors of SIP --
14618 /* Find their tag if we haven't got it */
14619 if (ast_strlen_zero(p
->theirtag
)) {
14622 gettag(req
, "From", tag
, sizeof(tag
));
14623 ast_string_field_set(p
, theirtag
, tag
);
14625 snprintf(p
->lastmsg
, sizeof(p
->lastmsg
), "Rx: %s", cmd
);
14627 if (pedanticsipchecking
) {
14628 /* If this is a request packet without a from tag, it's not
14629 correct according to RFC 3261 */
14630 /* Check if this a new request in a new dialog with a totag already attached to it,
14631 RFC 3261 - section 12.2 - and we don't want to mess with recovery */
14632 if (!p
->initreq
.headers
&& ast_test_flag(req
, SIP_PKT_WITH_TOTAG
)) {
14633 /* If this is a first request and it got a to-tag, it is not for us */
14634 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && req
->method
== SIP_INVITE
) {
14635 transmit_response_reliable(p
, "481 Call/Transaction Does Not Exist", req
);
14636 /* Will cease to exist after ACK */
14637 } else if (req
->method
!= SIP_ACK
) {
14638 transmit_response(p
, "481 Call/Transaction Does Not Exist", req
);
14639 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
14645 /* Handle various incoming SIP methods in requests */
14646 switch (p
->method
) {
14648 res
= handle_request_options(p
, req
);
14651 res
= handle_request_invite(p
, req
, debug
, seqno
, sin
, recount
, e
);
14654 res
= handle_request_refer(p
, req
, debug
, ignore
, seqno
, nounlock
);
14657 res
= handle_request_cancel(p
, req
);
14660 res
= handle_request_bye(p
, req
);
14663 res
= handle_request_message(p
, req
);
14665 case SIP_SUBSCRIBE
:
14666 res
= handle_request_subscribe(p
, req
, sin
, seqno
, e
);
14669 res
= handle_request_register(p
, req
, sin
, e
);
14672 if (ast_test_flag(req
, SIP_PKT_DEBUG
))
14673 ast_verbose("Receiving INFO!\n");
14675 handle_request_info(p
, req
);
14676 else /* if ignoring, transmit response */
14677 transmit_response(p
, "200 OK", req
);
14680 res
= handle_request_notify(p
, req
, sin
, seqno
, e
);
14683 /* Make sure we don't ignore this */
14684 if (seqno
== p
->pendinginvite
) {
14685 p
->invitestate
= INV_TERMINATED
;
14686 p
->pendinginvite
= 0;
14687 __sip_ack(p
, seqno
, FLAG_RESPONSE
, 0);
14688 if (find_sdp(req
)) {
14689 if (process_sdp(p
, req
))
14694 /* Got an ACK that we did not match. Ignore silently */
14695 if (!p
->lastinvite
&& ast_strlen_zero(p
->randdata
))
14696 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14699 transmit_response_with_allow(p
, "501 Method Not Implemented", req
, 0);
14700 ast_log(LOG_NOTICE
, "Unknown SIP command '%s' from '%s'\n",
14701 cmd
, ast_inet_ntoa(p
->sa
.sin_addr
));
14702 /* If this is some new method, and we don't have a call, destroy it now */
14703 if (!p
->initreq
.headers
)
14704 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14710 /*! \brief Read data from SIP socket
14711 \note sipsock_read locks the owner channel while we are processing the SIP message
14712 \return 1 on error, 0 on success
14713 \note Successful messages is connected to SIP call and forwarded to handle_request()
14715 static int sipsock_read(int *id
, int fd
, short events
, void *ignore
)
14717 struct sip_request req
;
14718 struct sockaddr_in sin
= { 0, };
14721 socklen_t len
= sizeof(sin
);
14726 memset(&req
, 0, sizeof(req
));
14727 res
= recvfrom(sipsock
, req
.data
, sizeof(req
.data
) - 1, 0, (struct sockaddr
*)&sin
, &len
);
14729 #if !defined(__FreeBSD__)
14730 if (errno
== EAGAIN
)
14731 ast_log(LOG_NOTICE
, "SIP: Received packet with bad UDP checksum\n");
14734 if (errno
!= ECONNREFUSED
)
14735 ast_log(LOG_WARNING
, "Recv error: %s\n", strerror(errno
));
14738 if (option_debug
&& res
== sizeof(req
.data
)) {
14739 ast_log(LOG_DEBUG
, "Received packet exceeds buffer. Data is possibly lost\n");
14740 req
.data
[sizeof(req
.data
) - 1] = '\0';
14742 req
.data
[res
] = '\0';
14744 if(sip_debug_test_addr(&sin
)) /* Set the debug flag early on packet level */
14745 ast_set_flag(&req
, SIP_PKT_DEBUG
);
14746 if (pedanticsipchecking
)
14747 req
.len
= lws2sws(req
.data
, req
.len
); /* Fix multiline headers */
14748 if (ast_test_flag(&req
, SIP_PKT_DEBUG
))
14749 ast_verbose("\n<--- SIP read from %s:%d --->\n%s\n<------------->\n", ast_inet_ntoa(sin
.sin_addr
), ntohs(sin
.sin_port
), req
.data
);
14751 parse_request(&req
);
14752 req
.method
= find_sip_method(req
.rlPart1
);
14754 if (ast_test_flag(&req
, SIP_PKT_DEBUG
))
14755 ast_verbose("--- (%d headers %d lines)%s ---\n", req
.headers
, req
.lines
, (req
.headers
+ req
.lines
== 0) ? " Nat keepalive" : "");
14757 if (req
.headers
< 2) /* Must have at least two headers */
14760 /* Process request, with netlock held, and with usual deadlock avoidance */
14761 for (lockretry
= 100; lockretry
> 0; lockretry
--) {
14762 ast_mutex_lock(&netlock
);
14764 /* Find the active SIP dialog or create a new one */
14765 p
= find_call(&req
, &sin
, req
.method
); /* returns p locked */
14768 ast_log(LOG_DEBUG
, "Invalid SIP message - rejected , no callid, len %d\n", req
.len
);
14769 ast_mutex_unlock(&netlock
);
14772 /* Go ahead and lock the owner if it has one -- we may need it */
14773 /* becaues this is deadlock-prone, we need to try and unlock if failed */
14774 if (!p
->owner
|| !ast_channel_trylock(p
->owner
))
14775 break; /* locking succeeded */
14777 ast_log(LOG_DEBUG
, "Failed to grab owner channel lock, trying again. (SIP call %s)\n", p
->callid
);
14778 ast_mutex_unlock(&p
->lock
);
14779 ast_mutex_unlock(&netlock
);
14780 /* Sleep for a very short amount of time */
14785 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
)) /* This is a request or response, note what it was for */
14786 append_history(p
, "Rx", "%s / %s / %s", req
.data
, get_header(&req
, "CSeq"), req
.rlPart2
);
14789 ast_log(LOG_ERROR
, "We could NOT get the channel lock for %s! \n", S_OR(p
->owner
->name
, "- no channel name ??? - "));
14790 ast_log(LOG_ERROR
, "SIP transaction failed: %s \n", p
->callid
);
14791 if (req
.method
!= SIP_ACK
)
14792 transmit_response(p
, "503 Server error", &req
); /* We must respond according to RFC 3261 sec 12.2 */
14793 /* XXX We could add retry-after to make sure they come back */
14794 append_history(p
, "LockFail", "Owner lock failed, transaction failed.");
14798 if (handle_request(p
, &req
, &sin
, &recount
, &nounlock
) == -1) {
14799 /* Request failed */
14801 ast_log(LOG_DEBUG
, "SIP message could not be handled, bad request: %-70.70s\n", p
->callid
[0] ? p
->callid
: "<no callid>");
14804 if (p
->owner
&& !nounlock
)
14805 ast_channel_unlock(p
->owner
);
14806 ast_mutex_unlock(&p
->lock
);
14807 ast_mutex_unlock(&netlock
);
14809 ast_update_use_count();
14814 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
14815 static int sip_send_mwi_to_peer(struct sip_peer
*peer
)
14817 /* Called with peerl lock, but releases it */
14819 int newmsgs
, oldmsgs
;
14821 /* Check for messages */
14822 ast_app_inboxcount(peer
->mailbox
, &newmsgs
, &oldmsgs
);
14824 peer
->lastmsgcheck
= time(NULL
);
14826 /* Return now if it's the same thing we told them last time */
14827 if (((newmsgs
> 0x7fff ? 0x7fff0000 : (newmsgs
<< 16)) | (oldmsgs
> 0xffff ? 0xffff : oldmsgs
)) == peer
->lastmsgssent
) {
14832 peer
->lastmsgssent
= ((newmsgs
> 0x7fff ? 0x7fff0000 : (newmsgs
<< 16)) | (oldmsgs
> 0xffff ? 0xffff : oldmsgs
));
14834 if (peer
->mwipvt
) {
14835 /* Base message on subscription */
14838 /* Build temporary dialog for this message */
14839 if (!(p
= sip_alloc(NULL
, NULL
, 0, SIP_NOTIFY
)))
14841 if (create_addr_from_peer(p
, peer
)) {
14842 /* Maybe they're not registered, etc. */
14846 /* Recalculate our side, and recalculate Call ID */
14847 if (ast_sip_ouraddrfor(&p
->sa
.sin_addr
, &p
->ourip
))
14848 p
->ourip
= __ourip
;
14850 build_callid_pvt(p
);
14851 /* Destroy this session after 32 secs */
14852 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
14855 ast_set_flag(&p
->flags
[0], SIP_OUTGOING
);
14856 transmit_notify_with_mwi(p
, newmsgs
, oldmsgs
, peer
->vmexten
);
14860 /*! \brief Check whether peer needs a new MWI notification check */
14861 static int does_peer_need_mwi(struct sip_peer
*peer
)
14863 time_t t
= time(NULL
);
14865 if (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_SUBSCRIBEMWIONLY
) &&
14866 !peer
->mwipvt
) { /* We don't have a subscription */
14867 peer
->lastmsgcheck
= t
; /* Reset timer */
14871 if (!ast_strlen_zero(peer
->mailbox
) && (t
- peer
->lastmsgcheck
) > global_mwitime
)
14878 /*! \brief The SIP monitoring thread
14879 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
14880 (and thus do not have a separate thread) indefinitely
14882 static void *do_monitor(void *data
)
14885 struct sip_pvt
*sip
;
14886 struct sip_peer
*peer
= NULL
;
14888 int fastrestart
= FALSE
;
14889 int lastpeernum
= -1;
14893 /* Add an I/O event to our SIP UDP socket */
14895 sipsock_read_id
= ast_io_add(io
, sipsock
, sipsock_read
, AST_IO_IN
, NULL
);
14897 /* From here on out, we die whenever asked */
14899 /* Check for a reload request */
14900 ast_mutex_lock(&sip_reload_lock
);
14901 reloading
= sip_reloading
;
14902 sip_reloading
= FALSE
;
14903 ast_mutex_unlock(&sip_reload_lock
);
14905 if (option_verbose
> 0)
14906 ast_verbose(VERBOSE_PREFIX_1
"Reloading SIP\n");
14907 sip_do_reload(sip_reloadreason
);
14909 /* Change the I/O fd of our UDP socket */
14911 sipsock_read_id
= ast_io_change(io
, sipsock_read_id
, sipsock
, NULL
, 0, NULL
);
14913 /* Check for interfaces needing to be killed */
14914 ast_mutex_lock(&iflock
);
14917 /* don't scan the interface list if it hasn't been a reasonable period
14918 of time since the last time we did it (when MWI is being sent, we can
14919 get back to this point every millisecond or less)
14921 for (sip
= iflist
; !fastrestart
&& sip
; sip
= sip
->next
) {
14922 ast_mutex_lock(&sip
->lock
);
14923 /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
14924 if (sip
->rtp
&& sip
->owner
&&
14925 (sip
->owner
->_state
== AST_STATE_UP
) &&
14926 !sip
->redirip
.sin_addr
.s_addr
) {
14927 if (sip
->lastrtptx
&&
14928 ast_rtp_get_rtpkeepalive(sip
->rtp
) &&
14929 (t
> sip
->lastrtptx
+ ast_rtp_get_rtpkeepalive(sip
->rtp
))) {
14930 /* Need to send an empty RTP packet */
14931 sip
->lastrtptx
= time(NULL
);
14932 ast_rtp_sendcng(sip
->rtp
, 0);
14934 if (sip
->lastrtprx
&&
14935 (ast_rtp_get_rtptimeout(sip
->rtp
) || ast_rtp_get_rtpholdtimeout(sip
->rtp
)) &&
14936 (t
> sip
->lastrtprx
+ ast_rtp_get_rtptimeout(sip
->rtp
))) {
14937 /* Might be a timeout now -- see if we're on hold */
14938 struct sockaddr_in sin
;
14939 ast_rtp_get_peer(sip
->rtp
, &sin
);
14940 if (sin
.sin_addr
.s_addr
||
14941 (ast_rtp_get_rtpholdtimeout(sip
->rtp
) &&
14942 (t
> sip
->lastrtprx
+ ast_rtp_get_rtpholdtimeout(sip
->rtp
)))) {
14943 /* Needs a hangup */
14944 if (ast_rtp_get_rtptimeout(sip
->rtp
)) {
14945 while (sip
->owner
&& ast_channel_trylock(sip
->owner
)) {
14946 ast_mutex_unlock(&sip
->lock
);
14948 ast_mutex_lock(&sip
->lock
);
14951 if (!(ast_rtp_get_bridged(sip
->rtp
))) {
14952 ast_log(LOG_NOTICE
,
14953 "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
14955 (long) (t
- sip
->lastrtprx
));
14956 /* Issue a softhangup */
14957 ast_softhangup_nolock(sip
->owner
, AST_SOFTHANGUP_DEV
);
14959 ast_log(LOG_NOTICE
, "'%s' will not be disconnected in %ld seconds because it is directly bridged to another RTP stream\n", sip
->owner
->name
, (long) (t
- sip
->lastrtprx
));
14960 ast_channel_unlock(sip
->owner
);
14961 /* forget the timeouts for this call, since a hangup
14962 has already been requested and we don't want to
14963 repeatedly request hangups
14965 ast_rtp_set_rtptimeout(sip
->rtp
, 0);
14966 ast_rtp_set_rtpholdtimeout(sip
->rtp
, 0);
14968 ast_rtp_set_rtptimeout(sip
->vrtp
, 0);
14969 ast_rtp_set_rtpholdtimeout(sip
->vrtp
, 0);
14976 /* If we have sessions that needs to be destroyed, do it now */
14977 if (ast_test_flag(&sip
->flags
[0], SIP_NEEDDESTROY
) && !sip
->packets
&&
14979 ast_mutex_unlock(&sip
->lock
);
14980 __sip_destroy(sip
, 1);
14981 goto restartsearch
;
14983 ast_mutex_unlock(&sip
->lock
);
14985 ast_mutex_unlock(&iflock
);
14987 pthread_testcancel();
14988 /* Wait for sched or io */
14989 res
= ast_sched_wait(sched
);
14990 if ((res
< 0) || (res
> 1000))
14992 /* If we might need to send more mailboxes, don't wait long at all.*/
14995 res
= ast_io_wait(io
, res
);
14996 if (option_debug
&& res
> 20)
14997 ast_log(LOG_DEBUG
, "chan_sip: ast_io_wait ran %d all at once\n", res
);
14998 ast_mutex_lock(&monlock
);
15000 res
= ast_sched_runq(sched
);
15001 if (option_debug
&& res
>= 20)
15002 ast_log(LOG_DEBUG
, "chan_sip: ast_sched_runq ran %d all at once\n", res
);
15005 /* Send MWI notifications to peers - static and cached realtime peers */
15007 fastrestart
= FALSE
;
15010 /* Find next peer that needs mwi */
15011 ASTOBJ_CONTAINER_TRAVERSE(&peerl
, !peer
, do {
15012 if ((curpeernum
> lastpeernum
) && does_peer_need_mwi(iterator
)) {
15013 fastrestart
= TRUE
;
15014 lastpeernum
= curpeernum
;
15015 peer
= ASTOBJ_REF(iterator
);
15020 /* Send MWI to the peer */
15022 ASTOBJ_WRLOCK(peer
);
15023 sip_send_mwi_to_peer(peer
);
15024 ASTOBJ_UNLOCK(peer
);
15025 ASTOBJ_UNREF(peer
,sip_destroy_peer
);
15027 /* Reset where we come from */
15030 ast_mutex_unlock(&monlock
);
15032 /* Never reached */
15037 /*! \brief Start the channel monitor thread */
15038 static int restart_monitor(void)
15040 /* If we're supposed to be stopped -- stay stopped */
15041 if (monitor_thread
== AST_PTHREADT_STOP
)
15043 ast_mutex_lock(&monlock
);
15044 if (monitor_thread
== pthread_self()) {
15045 ast_mutex_unlock(&monlock
);
15046 ast_log(LOG_WARNING
, "Cannot kill myself\n");
15049 if (monitor_thread
!= AST_PTHREADT_NULL
) {
15050 /* Wake up the thread */
15051 pthread_kill(monitor_thread
, SIGURG
);
15053 /* Start a new monitor */
15054 if (ast_pthread_create_background(&monitor_thread
, NULL
, do_monitor
, NULL
) < 0) {
15055 ast_mutex_unlock(&monlock
);
15056 ast_log(LOG_ERROR
, "Unable to start monitor thread.\n");
15060 ast_mutex_unlock(&monlock
);
15064 /*! \brief React to lack of answer to Qualify poke */
15065 static int sip_poke_noanswer(void *data
)
15067 struct sip_peer
*peer
= data
;
15069 peer
->pokeexpire
= -1;
15070 if (peer
->lastms
> -1) {
15071 ast_log(LOG_NOTICE
, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer
->name
, peer
->lastms
);
15072 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer
->name
, -1);
15075 sip_destroy(peer
->call
);
15078 ast_device_state_changed("SIP/%s", peer
->name
);
15079 /* Try again quickly */
15080 peer
->pokeexpire
= ast_sched_add(sched
, DEFAULT_FREQ_NOTOK
, sip_poke_peer_s
, peer
);
15084 /*! \brief Check availability of peer, also keep NAT open
15085 \note This is done with the interval in qualify= configuration option
15086 Default is 2 seconds */
15087 static int sip_poke_peer(struct sip_peer
*peer
)
15091 if (!peer
->maxms
|| !peer
->addr
.sin_addr
.s_addr
) {
15092 /* IF we have no IP, or this isn't to be monitored, return
15093 imeediately after clearing things out */
15094 if (peer
->pokeexpire
> -1)
15095 ast_sched_del(sched
, peer
->pokeexpire
);
15097 peer
->pokeexpire
= -1;
15103 ast_log(LOG_NOTICE
, "Still have a QUALIFY dialog active, deleting\n");
15104 sip_destroy(peer
->call
);
15106 if (!(p
= peer
->call
= sip_alloc(NULL
, NULL
, 0, SIP_OPTIONS
)))
15109 p
->sa
= peer
->addr
;
15110 p
->recv
= peer
->addr
;
15111 ast_copy_flags(&p
->flags
[0], &peer
->flags
[0], SIP_FLAGS_TO_COPY
);
15112 ast_copy_flags(&p
->flags
[1], &peer
->flags
[1], SIP_PAGE2_FLAGS_TO_COPY
);
15114 /* Send OPTIONs to peer's fullcontact */
15115 if (!ast_strlen_zero(peer
->fullcontact
))
15116 ast_string_field_set(p
, fullcontact
, peer
->fullcontact
);
15118 if (!ast_strlen_zero(peer
->tohost
))
15119 ast_string_field_set(p
, tohost
, peer
->tohost
);
15121 ast_string_field_set(p
, tohost
, ast_inet_ntoa(peer
->addr
.sin_addr
));
15123 /* Recalculate our side, and recalculate Call ID */
15124 if (ast_sip_ouraddrfor(&p
->sa
.sin_addr
, &p
->ourip
))
15125 p
->ourip
= __ourip
;
15127 build_callid_pvt(p
);
15129 if (peer
->pokeexpire
> -1)
15130 ast_sched_del(sched
, peer
->pokeexpire
);
15131 p
->relatedpeer
= peer
;
15132 ast_set_flag(&p
->flags
[0], SIP_OUTGOING
);
15133 #ifdef VOCAL_DATA_HACK
15134 ast_copy_string(p
->username
, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p
->username
));
15135 transmit_invite(p
, SIP_INVITE
, 0, 2);
15137 transmit_invite(p
, SIP_OPTIONS
, 0, 2);
15139 gettimeofday(&peer
->ps
, NULL
);
15140 peer
->pokeexpire
= ast_sched_add(sched
, DEFAULT_MAXMS
* 2, sip_poke_noanswer
, peer
);
15145 /*! \brief Part of PBX channel interface
15147 \par Return values:---
15149 If we have qualify on and the device is not reachable, regardless of registration
15150 state we return AST_DEVICE_UNAVAILABLE
15152 For peers with call limit:
15153 - not registered AST_DEVICE_UNAVAILABLE
15154 - registered, no call AST_DEVICE_NOT_INUSE
15155 - registered, active calls AST_DEVICE_INUSE
15156 - registered, call limit reached AST_DEVICE_BUSY
15157 - registered, onhold AST_DEVICE_ONHOLD
15158 - registered, ringing AST_DEVICE_RINGING
15160 For peers without call limit:
15161 - not registered AST_DEVICE_UNAVAILABLE
15162 - registered AST_DEVICE_NOT_INUSE
15163 - fixed IP (!dynamic) AST_DEVICE_NOT_INUSE
15165 Peers that does not have a known call and can't be reached by OPTIONS
15166 - unreachable AST_DEVICE_UNAVAILABLE
15168 If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
15169 out a state by walking the channel list.
15171 The queue system (\ref app_queue.c) treats a member as "active"
15172 if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
15174 When placing a call to the queue member, queue system sets a member to busy if
15175 != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
15178 static int sip_devicestate(void *data
)
15183 struct hostent
*hp
;
15184 struct ast_hostent ahp
;
15185 struct sip_peer
*p
;
15187 int res
= AST_DEVICE_INVALID
;
15189 /* make sure data is not null. Maybe unnecessary, but better be safe */
15190 host
= ast_strdupa(data
? data
: "");
15191 if ((tmp
= strchr(host
, '@')))
15194 if (option_debug
> 2)
15195 ast_log(LOG_DEBUG
, "Checking device state for peer %s\n", host
);
15197 if ((p
= find_peer(host
, NULL
, 1))) {
15198 if (p
->addr
.sin_addr
.s_addr
|| p
->defaddr
.sin_addr
.s_addr
) {
15199 /* we have an address for the peer */
15201 /* Check status in this order
15204 - Busy (enforced only by call limit)
15205 - Inuse (we have a call)
15206 - Unreachable (qualify)
15207 If we don't find any of these state, report AST_DEVICE_NOT_INUSE
15208 for registered devices */
15211 /* First check for hold or ring states */
15212 res
= AST_DEVICE_ONHOLD
;
15213 else if (p
->inRinging
) {
15214 if (p
->inRinging
== p
->inUse
)
15215 res
= AST_DEVICE_RINGING
;
15217 res
= AST_DEVICE_RINGINUSE
;
15218 } else if (p
->call_limit
&& (p
->inUse
== p
->call_limit
))
15219 /* check call limit */
15220 res
= AST_DEVICE_BUSY
;
15221 else if (p
->call_limit
&& p
->inUse
)
15222 /* Not busy, but we do have a call */
15223 res
= AST_DEVICE_INUSE
;
15224 else if (p
->maxms
&& (p
->lastms
> p
->maxms
))
15225 /* We don't have a call. Are we reachable at all? Requires qualify= */
15226 res
= AST_DEVICE_UNAVAILABLE
;
15227 else /* Default reply if we're registered and have no other data */
15228 res
= AST_DEVICE_NOT_INUSE
;
15230 /* there is no address, it's unavailable */
15231 res
= AST_DEVICE_UNAVAILABLE
;
15233 ASTOBJ_UNREF(p
,sip_destroy_peer
);
15235 hp
= ast_gethostbyname(host
, &ahp
);
15237 res
= AST_DEVICE_UNKNOWN
;
15243 /*! \brief PBX interface function -build SIP pvt structure
15244 SIP calls initiated by the PBX arrive here */
15245 static struct ast_channel
*sip_request_call(const char *type
, int format
, void *data
, int *cause
)
15249 struct ast_channel
*tmpc
= NULL
;
15254 oldformat
= format
;
15255 if (!(format
&= ((AST_FORMAT_MAX_AUDIO
<< 1) - 1))) {
15256 ast_log(LOG_NOTICE
, "Asked to get a channel of unsupported format %s while capability is %s\n", ast_getformatname(oldformat
), ast_getformatname(global_capability
));
15257 *cause
= AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
; /* Can't find codec to connect to host */
15261 ast_log(LOG_DEBUG
, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp
, sizeof(tmp
), oldformat
));
15263 if (!(p
= sip_alloc(NULL
, NULL
, 0, SIP_INVITE
))) {
15264 ast_log(LOG_ERROR
, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", (char *)data
);
15265 *cause
= AST_CAUSE_SWITCH_CONGESTION
;
15269 ast_set_flag(&p
->flags
[1], SIP_PAGE2_OUTGOING_CALL
);
15271 if (!(p
->options
= ast_calloc(1, sizeof(*p
->options
)))) {
15273 ast_log(LOG_ERROR
, "Unable to build option SIP data structure - Out of memory\n");
15274 *cause
= AST_CAUSE_SWITCH_CONGESTION
;
15278 ast_copy_string(tmp
, dest
, sizeof(tmp
));
15279 host
= strchr(tmp
, '@');
15284 ext
= strchr(tmp
, '/');
15290 if (create_addr(p
, host
)) {
15291 *cause
= AST_CAUSE_UNREGISTERED
;
15292 if (option_debug
> 2)
15293 ast_log(LOG_DEBUG
, "Cant create SIP call - target device not registred\n");
15297 if (ast_strlen_zero(p
->peername
) && ext
)
15298 ast_string_field_set(p
, peername
, ext
);
15299 /* Recalculate our side, and recalculate Call ID */
15300 if (ast_sip_ouraddrfor(&p
->sa
.sin_addr
, &p
->ourip
))
15301 p
->ourip
= __ourip
;
15303 build_callid_pvt(p
);
15305 /* We have an extension to call, don't use the full contact here */
15306 /* This to enable dialing registered peers with extension dialling,
15307 like SIP/peername/extension
15308 SIP/peername will still use the full contact */
15310 ast_string_field_set(p
, username
, ext
);
15311 ast_string_field_free(p
, fullcontact
);
15314 printf("Setting up to call extension '%s' at '%s'\n", ext
? ext
: "<none>", host
);
15316 p
->prefcodec
= oldformat
; /* Format for this call */
15317 ast_mutex_lock(&p
->lock
);
15318 tmpc
= sip_new(p
, AST_STATE_DOWN
, host
); /* Place the call */
15319 ast_mutex_unlock(&p
->lock
);
15322 ast_update_use_count();
15328 \brief Handle flag-type options common to configuration of devices - users and peers
15329 \param flags array of two struct ast_flags
15330 \param mask array of two struct ast_flags
15331 \param v linked list of config variables to process
15332 \returns non-zero if any config options were handled, zero otherwise
15334 static int handle_common_options(struct ast_flags
*flags
, struct ast_flags
*mask
, struct ast_variable
*v
)
15337 static int dep_insecure_very
= 0;
15338 static int dep_insecure_yes
= 0;
15340 if (!strcasecmp(v
->name
, "trustrpid")) {
15341 ast_set_flag(&mask
[0], SIP_TRUSTRPID
);
15342 ast_set2_flag(&flags
[0], ast_true(v
->value
), SIP_TRUSTRPID
);
15344 } else if (!strcasecmp(v
->name
, "sendrpid")) {
15345 ast_set_flag(&mask
[0], SIP_SENDRPID
);
15346 ast_set2_flag(&flags
[0], ast_true(v
->value
), SIP_SENDRPID
);
15348 } else if (!strcasecmp(v
->name
, "g726nonstandard")) {
15349 ast_set_flag(&mask
[0], SIP_G726_NONSTANDARD
);
15350 ast_set2_flag(&flags
[0], ast_true(v
->value
), SIP_G726_NONSTANDARD
);
15352 } else if (!strcasecmp(v
->name
, "useclientcode")) {
15353 ast_set_flag(&mask
[0], SIP_USECLIENTCODE
);
15354 ast_set2_flag(&flags
[0], ast_true(v
->value
), SIP_USECLIENTCODE
);
15356 } else if (!strcasecmp(v
->name
, "dtmfmode")) {
15357 ast_set_flag(&mask
[0], SIP_DTMF
);
15358 ast_clear_flag(&flags
[0], SIP_DTMF
);
15359 if (!strcasecmp(v
->value
, "inband"))
15360 ast_set_flag(&flags
[0], SIP_DTMF_INBAND
);
15361 else if (!strcasecmp(v
->value
, "rfc2833"))
15362 ast_set_flag(&flags
[0], SIP_DTMF_RFC2833
);
15363 else if (!strcasecmp(v
->value
, "info"))
15364 ast_set_flag(&flags
[0], SIP_DTMF_INFO
);
15365 else if (!strcasecmp(v
->value
, "auto"))
15366 ast_set_flag(&flags
[0], SIP_DTMF_AUTO
);
15368 ast_log(LOG_WARNING
, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v
->value
, v
->lineno
);
15369 ast_set_flag(&flags
[0], SIP_DTMF_RFC2833
);
15372 } else if (!strcasecmp(v
->name
, "nat")) {
15373 ast_set_flag(&mask
[0], SIP_NAT
);
15374 ast_clear_flag(&flags
[0], SIP_NAT
);
15375 if (!strcasecmp(v
->value
, "never"))
15376 ast_set_flag(&flags
[0], SIP_NAT_NEVER
);
15377 else if (!strcasecmp(v
->value
, "route"))
15378 ast_set_flag(&flags
[0], SIP_NAT_ROUTE
);
15379 else if (ast_true(v
->value
))
15380 ast_set_flag(&flags
[0], SIP_NAT_ALWAYS
);
15382 ast_set_flag(&flags
[0], SIP_NAT_RFC3581
);
15384 } else if (!strcasecmp(v
->name
, "canreinvite")) {
15385 ast_set_flag(&mask
[0], SIP_REINVITE
);
15386 ast_clear_flag(&flags
[0], SIP_REINVITE
);
15387 if (ast_true(v
->value
)) {
15388 ast_set_flag(&flags
[0], SIP_CAN_REINVITE
| SIP_CAN_REINVITE_NAT
);
15389 } else if (!ast_false(v
->value
)) {
15391 char *word
, *next
= buf
;
15393 ast_copy_string(buf
, v
->value
, sizeof(buf
));
15394 while ((word
= strsep(&next
, ","))) {
15395 if (!strcasecmp(word
, "update")) {
15396 ast_set_flag(&flags
[0], SIP_REINVITE_UPDATE
| SIP_CAN_REINVITE
);
15397 } else if (!strcasecmp(word
, "nonat")) {
15398 ast_set_flag(&flags
[0], SIP_CAN_REINVITE
);
15399 ast_clear_flag(&flags
[0], SIP_CAN_REINVITE_NAT
);
15401 ast_log(LOG_WARNING
, "Unknown canreinvite mode '%s' on line %d\n", v
->value
, v
->lineno
);
15406 } else if (!strcasecmp(v
->name
, "insecure")) {
15407 ast_set_flag(&mask
[0], SIP_INSECURE_PORT
| SIP_INSECURE_INVITE
);
15408 ast_clear_flag(&flags
[0], SIP_INSECURE_PORT
| SIP_INSECURE_INVITE
);
15409 if (!strcasecmp(v
->value
, "very")) {
15410 ast_set_flag(&flags
[0], SIP_INSECURE_PORT
| SIP_INSECURE_INVITE
);
15411 if (!dep_insecure_very
) {
15412 ast_log(LOG_WARNING
, "insecure=very at line %d is deprecated; use insecure=port,invite instead\n", v
->lineno
);
15413 dep_insecure_very
= 1;
15416 else if (ast_true(v
->value
)) {
15417 ast_set_flag(&flags
[0], SIP_INSECURE_PORT
);
15418 if (!dep_insecure_yes
) {
15419 ast_log(LOG_WARNING
, "insecure=%s at line %d is deprecated; use insecure=port instead\n", v
->value
, v
->lineno
);
15420 dep_insecure_yes
= 1;
15423 else if (!ast_false(v
->value
)) {
15427 ast_copy_string(buf
, v
->value
, sizeof(buf
));
15429 while ((word
= strsep(&next
, ","))) {
15430 if (!strcasecmp(word
, "port"))
15431 ast_set_flag(&flags
[0], SIP_INSECURE_PORT
);
15432 else if (!strcasecmp(word
, "invite"))
15433 ast_set_flag(&flags
[0], SIP_INSECURE_INVITE
);
15435 ast_log(LOG_WARNING
, "Unknown insecure mode '%s' on line %d\n", v
->value
, v
->lineno
);
15439 } else if (!strcasecmp(v
->name
, "progressinband")) {
15440 ast_set_flag(&mask
[0], SIP_PROG_INBAND
);
15441 ast_clear_flag(&flags
[0], SIP_PROG_INBAND
);
15442 if (ast_true(v
->value
))
15443 ast_set_flag(&flags
[0], SIP_PROG_INBAND_YES
);
15444 else if (strcasecmp(v
->value
, "never"))
15445 ast_set_flag(&flags
[0], SIP_PROG_INBAND_NO
);
15447 } else if (!strcasecmp(v
->name
, "promiscredir")) {
15448 ast_set_flag(&mask
[0], SIP_PROMISCREDIR
);
15449 ast_set2_flag(&flags
[0], ast_true(v
->value
), SIP_PROMISCREDIR
);
15451 } else if (!strcasecmp(v
->name
, "videosupport")) {
15452 ast_set_flag(&mask
[1], SIP_PAGE2_VIDEOSUPPORT
);
15453 ast_set2_flag(&flags
[1], ast_true(v
->value
), SIP_PAGE2_VIDEOSUPPORT
);
15455 } else if (!strcasecmp(v
->name
, "allowoverlap")) {
15456 ast_set_flag(&mask
[1], SIP_PAGE2_ALLOWOVERLAP
);
15457 ast_set2_flag(&flags
[1], ast_true(v
->value
), SIP_PAGE2_ALLOWOVERLAP
);
15459 } else if (!strcasecmp(v
->name
, "allowsubscribe")) {
15460 ast_set_flag(&mask
[1], SIP_PAGE2_ALLOWSUBSCRIBE
);
15461 ast_set2_flag(&flags
[1], ast_true(v
->value
), SIP_PAGE2_ALLOWSUBSCRIBE
);
15463 } else if (!strcasecmp(v
->name
, "t38pt_udptl")) {
15464 ast_set_flag(&mask
[1], SIP_PAGE2_T38SUPPORT_UDPTL
);
15465 ast_set2_flag(&flags
[1], ast_true(v
->value
), SIP_PAGE2_T38SUPPORT_UDPTL
);
15467 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
15468 } else if (!strcasecmp(v
->name
, "t38pt_rtp")) {
15469 ast_set_flag(&mask
[1], SIP_PAGE2_T38SUPPORT_RTP
);
15470 ast_set2_flag(&flags
[1], ast_true(v
->value
), SIP_PAGE2_T38SUPPORT_RTP
);
15472 } else if (!strcasecmp(v
->name
, "t38pt_tcp")) {
15473 ast_set_flag(&mask
[1], SIP_PAGE2_T38SUPPORT_TCP
);
15474 ast_set2_flag(&flags
[1], ast_true(v
->value
), SIP_PAGE2_T38SUPPORT_TCP
);
15477 } else if (!strcasecmp(v
->name
, "rfc2833compensate")) {
15478 ast_set_flag(&mask
[1], SIP_PAGE2_RFC2833_COMPENSATE
);
15479 ast_set2_flag(&flags
[1], ast_true(v
->value
), SIP_PAGE2_RFC2833_COMPENSATE
);
15481 } else if (!strcasecmp(v
->name
, "buggymwi")) {
15482 ast_set_flag(&mask
[1], SIP_PAGE2_BUGGY_MWI
);
15483 ast_set2_flag(&flags
[1], ast_true(v
->value
), SIP_PAGE2_BUGGY_MWI
);
15490 /*! \brief Add SIP domain to list of domains we are responsible for */
15491 static int add_sip_domain(const char *domain
, const enum domain_mode mode
, const char *context
)
15495 if (ast_strlen_zero(domain
)) {
15496 ast_log(LOG_WARNING
, "Zero length domain.\n");
15500 if (!(d
= ast_calloc(1, sizeof(*d
))))
15503 ast_copy_string(d
->domain
, domain
, sizeof(d
->domain
));
15505 if (!ast_strlen_zero(context
))
15506 ast_copy_string(d
->context
, context
, sizeof(d
->context
));
15510 AST_LIST_LOCK(&domain_list
);
15511 AST_LIST_INSERT_TAIL(&domain_list
, d
, list
);
15512 AST_LIST_UNLOCK(&domain_list
);
15515 ast_log(LOG_DEBUG
, "Added local SIP domain '%s'\n", domain
);
15520 /*! \brief check_sip_domain: Check if domain part of uri is local to our server */
15521 static int check_sip_domain(const char *domain
, char *context
, size_t len
)
15526 AST_LIST_LOCK(&domain_list
);
15527 AST_LIST_TRAVERSE(&domain_list
, d
, list
) {
15528 if (strcasecmp(d
->domain
, domain
))
15531 if (len
&& !ast_strlen_zero(d
->context
))
15532 ast_copy_string(context
, d
->context
, len
);
15537 AST_LIST_UNLOCK(&domain_list
);
15542 /*! \brief Clear our domain list (at reload) */
15543 static void clear_sip_domains(void)
15547 AST_LIST_LOCK(&domain_list
);
15548 while ((d
= AST_LIST_REMOVE_HEAD(&domain_list
, list
)))
15550 AST_LIST_UNLOCK(&domain_list
);
15554 /*! \brief Add realm authentication in list */
15555 static struct sip_auth
*add_realm_authentication(struct sip_auth
*authlist
, char *configuration
, int lineno
)
15557 char authcopy
[256];
15558 char *username
=NULL
, *realm
=NULL
, *secret
=NULL
, *md5secret
=NULL
;
15560 struct sip_auth
*a
, *b
, *auth
;
15562 if (ast_strlen_zero(configuration
))
15566 ast_log(LOG_DEBUG
, "Auth config :: %s\n", configuration
);
15568 ast_copy_string(authcopy
, configuration
, sizeof(authcopy
));
15569 stringp
= authcopy
;
15571 username
= stringp
;
15572 realm
= strrchr(stringp
, '@');
15575 if (ast_strlen_zero(username
) || ast_strlen_zero(realm
)) {
15576 ast_log(LOG_WARNING
, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno
);
15579 stringp
= username
;
15580 username
= strsep(&stringp
, ":");
15582 secret
= strsep(&stringp
, ":");
15584 stringp
= username
;
15585 md5secret
= strsep(&stringp
,"#");
15588 if (!(auth
= ast_calloc(1, sizeof(*auth
))))
15591 ast_copy_string(auth
->realm
, realm
, sizeof(auth
->realm
));
15592 ast_copy_string(auth
->username
, username
, sizeof(auth
->username
));
15594 ast_copy_string(auth
->secret
, secret
, sizeof(auth
->secret
));
15596 ast_copy_string(auth
->md5secret
, md5secret
, sizeof(auth
->md5secret
));
15598 /* find the end of the list */
15599 for (b
= NULL
, a
= authlist
; a
; b
= a
, a
= a
->next
)
15602 b
->next
= auth
; /* Add structure add end of list */
15606 if (option_verbose
> 2)
15607 ast_verbose("Added authentication for realm %s\n", realm
);
15613 /*! \brief Clear realm authentication list (at reload) */
15614 static int clear_realm_authentication(struct sip_auth
*authlist
)
15616 struct sip_auth
*a
= authlist
;
15617 struct sip_auth
*b
;
15628 /*! \brief Find authentication for a specific realm */
15629 static struct sip_auth
*find_realm_authentication(struct sip_auth
*authlist
, const char *realm
)
15631 struct sip_auth
*a
;
15633 for (a
= authlist
; a
; a
= a
->next
) {
15634 if (!strcasecmp(a
->realm
, realm
))
15641 /*! \brief Initiate a SIP user structure from configuration (configuration or realtime) */
15642 static struct sip_user
*build_user(const char *name
, struct ast_variable
*v
, int realtime
)
15644 struct sip_user
*user
;
15646 struct ast_ha
*oldha
= NULL
;
15647 char *varname
= NULL
, *varval
= NULL
;
15648 struct ast_variable
*tmpvar
= NULL
;
15649 struct ast_flags userflags
[2] = {{(0)}};
15650 struct ast_flags mask
[2] = {{(0)}};
15653 if (!(user
= ast_calloc(1, sizeof(*user
))))
15658 ast_copy_string(user
->name
, name
, sizeof(user
->name
));
15661 ast_copy_flags(&user
->flags
[0], &global_flags
[0], SIP_FLAGS_TO_COPY
);
15662 ast_copy_flags(&user
->flags
[1], &global_flags
[1], SIP_PAGE2_FLAGS_TO_COPY
);
15663 user
->capability
= global_capability
;
15664 user
->allowtransfer
= global_allowtransfer
;
15665 user
->maxcallbitrate
= default_maxcallbitrate
;
15666 user
->autoframing
= global_autoframing
;
15667 user
->prefs
= default_prefs
;
15668 /* set default context */
15669 strcpy(user
->context
, default_context
);
15670 strcpy(user
->language
, default_language
);
15671 strcpy(user
->mohinterpret
, default_mohinterpret
);
15672 strcpy(user
->mohsuggest
, default_mohsuggest
);
15673 for (; v
; v
= v
->next
) {
15674 if (handle_common_options(&userflags
[0], &mask
[0], v
))
15677 if (!strcasecmp(v
->name
, "context")) {
15678 ast_copy_string(user
->context
, v
->value
, sizeof(user
->context
));
15679 } else if (!strcasecmp(v
->name
, "subscribecontext")) {
15680 ast_copy_string(user
->subscribecontext
, v
->value
, sizeof(user
->subscribecontext
));
15681 } else if (!strcasecmp(v
->name
, "setvar")) {
15682 varname
= ast_strdupa(v
->value
);
15683 if ((varval
= strchr(varname
,'='))) {
15685 if ((tmpvar
= ast_variable_new(varname
, varval
))) {
15686 tmpvar
->next
= user
->chanvars
;
15687 user
->chanvars
= tmpvar
;
15690 } else if (!strcasecmp(v
->name
, "permit") ||
15691 !strcasecmp(v
->name
, "deny")) {
15692 user
->ha
= ast_append_ha(v
->name
, v
->value
, user
->ha
);
15693 } else if (!strcasecmp(v
->name
, "allowtransfer")) {
15694 user
->allowtransfer
= ast_true(v
->value
) ? TRANSFER_OPENFORALL
: TRANSFER_CLOSED
;
15695 } else if (!strcasecmp(v
->name
, "secret")) {
15696 ast_copy_string(user
->secret
, v
->value
, sizeof(user
->secret
));
15697 } else if (!strcasecmp(v
->name
, "md5secret")) {
15698 ast_copy_string(user
->md5secret
, v
->value
, sizeof(user
->md5secret
));
15699 } else if (!strcasecmp(v
->name
, "callerid")) {
15700 ast_callerid_split(v
->value
, user
->cid_name
, sizeof(user
->cid_name
), user
->cid_num
, sizeof(user
->cid_num
));
15701 } else if (!strcasecmp(v
->name
, "fullname")) {
15702 ast_copy_string(user
->cid_name
, v
->value
, sizeof(user
->cid_name
));
15703 } else if (!strcasecmp(v
->name
, "cid_number")) {
15704 ast_copy_string(user
->cid_num
, v
->value
, sizeof(user
->cid_num
));
15705 } else if (!strcasecmp(v
->name
, "callgroup")) {
15706 user
->callgroup
= ast_get_group(v
->value
);
15707 } else if (!strcasecmp(v
->name
, "pickupgroup")) {
15708 user
->pickupgroup
= ast_get_group(v
->value
);
15709 } else if (!strcasecmp(v
->name
, "language")) {
15710 ast_copy_string(user
->language
, v
->value
, sizeof(user
->language
));
15711 } else if (!strcasecmp(v
->name
, "mohinterpret")
15712 || !strcasecmp(v
->name
, "musicclass") || !strcasecmp(v
->name
, "musiconhold")) {
15713 ast_copy_string(user
->mohinterpret
, v
->value
, sizeof(user
->mohinterpret
));
15714 } else if (!strcasecmp(v
->name
, "mohsuggest")) {
15715 ast_copy_string(user
->mohsuggest
, v
->value
, sizeof(user
->mohsuggest
));
15716 } else if (!strcasecmp(v
->name
, "accountcode")) {
15717 ast_copy_string(user
->accountcode
, v
->value
, sizeof(user
->accountcode
));
15718 } else if (!strcasecmp(v
->name
, "call-limit")) {
15719 user
->call_limit
= atoi(v
->value
);
15720 if (user
->call_limit
< 0)
15721 user
->call_limit
= 0;
15722 } else if (!strcasecmp(v
->name
, "amaflags")) {
15723 format
= ast_cdr_amaflags2int(v
->value
);
15725 ast_log(LOG_WARNING
, "Invalid AMA Flags: %s at line %d\n", v
->value
, v
->lineno
);
15727 user
->amaflags
= format
;
15729 } else if (!strcasecmp(v
->name
, "allow")) {
15730 ast_parse_allow_disallow(&user
->prefs
, &user
->capability
, v
->value
, 1);
15731 } else if (!strcasecmp(v
->name
, "disallow")) {
15732 ast_parse_allow_disallow(&user
->prefs
, &user
->capability
, v
->value
, 0);
15733 } else if (!strcasecmp(v
->name
, "autoframing")) {
15734 user
->autoframing
= ast_true(v
->value
);
15735 } else if (!strcasecmp(v
->name
, "callingpres")) {
15736 user
->callingpres
= ast_parse_caller_presentation(v
->value
);
15737 if (user
->callingpres
== -1)
15738 user
->callingpres
= atoi(v
->value
);
15739 } else if (!strcasecmp(v
->name
, "maxcallbitrate")) {
15740 user
->maxcallbitrate
= atoi(v
->value
);
15741 if (user
->maxcallbitrate
< 0)
15742 user
->maxcallbitrate
= default_maxcallbitrate
;
15745 ast_copy_flags(&user
->flags
[0], &userflags
[0], mask
[0].flags
);
15746 ast_copy_flags(&user
->flags
[1], &userflags
[1], mask
[1].flags
);
15747 if (ast_test_flag(&user
->flags
[1], SIP_PAGE2_ALLOWSUBSCRIBE
))
15748 global_allowsubscribe
= TRUE
; /* No global ban any more */
15749 ast_free_ha(oldha
);
15753 /*! \brief Set peer defaults before configuring specific configurations */
15754 static void set_peer_defaults(struct sip_peer
*peer
)
15756 if (peer
->expire
== 0) {
15757 /* Don't reset expire or port time during reload
15758 if we have an active registration
15761 peer
->pokeexpire
= -1;
15762 peer
->addr
.sin_port
= htons(STANDARD_SIP_PORT
);
15764 ast_copy_flags(&peer
->flags
[0], &global_flags
[0], SIP_FLAGS_TO_COPY
);
15765 ast_copy_flags(&peer
->flags
[1], &global_flags
[1], SIP_PAGE2_FLAGS_TO_COPY
);
15766 strcpy(peer
->context
, default_context
);
15767 strcpy(peer
->subscribecontext
, default_subscribecontext
);
15768 strcpy(peer
->language
, default_language
);
15769 strcpy(peer
->mohinterpret
, default_mohinterpret
);
15770 strcpy(peer
->mohsuggest
, default_mohsuggest
);
15771 peer
->addr
.sin_family
= AF_INET
;
15772 peer
->defaddr
.sin_family
= AF_INET
;
15773 peer
->capability
= global_capability
;
15774 peer
->maxcallbitrate
= default_maxcallbitrate
;
15775 peer
->rtptimeout
= global_rtptimeout
;
15776 peer
->rtpholdtimeout
= global_rtpholdtimeout
;
15777 peer
->rtpkeepalive
= global_rtpkeepalive
;
15778 peer
->allowtransfer
= global_allowtransfer
;
15779 peer
->autoframing
= global_autoframing
;
15780 strcpy(peer
->vmexten
, default_vmexten
);
15781 peer
->secret
[0] = '\0';
15782 peer
->md5secret
[0] = '\0';
15783 peer
->cid_num
[0] = '\0';
15784 peer
->cid_name
[0] = '\0';
15785 peer
->fromdomain
[0] = '\0';
15786 peer
->fromuser
[0] = '\0';
15787 peer
->regexten
[0] = '\0';
15788 peer
->mailbox
[0] = '\0';
15789 peer
->callgroup
= 0;
15790 peer
->pickupgroup
= 0;
15791 peer
->maxms
= default_qualify
;
15792 peer
->prefs
= default_prefs
;
15795 /*! \brief Create temporary peer (used in autocreatepeer mode) */
15796 static struct sip_peer
*temp_peer(const char *name
)
15798 struct sip_peer
*peer
;
15800 if (!(peer
= ast_calloc(1, sizeof(*peer
))))
15805 set_peer_defaults(peer
);
15807 ast_copy_string(peer
->name
, name
, sizeof(peer
->name
));
15809 ast_set_flag(&peer
->flags
[1], SIP_PAGE2_SELFDESTRUCT
);
15810 ast_set_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
);
15811 peer
->prefs
= default_prefs
;
15812 reg_source_db(peer
);
15817 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
15818 static struct sip_peer
*build_peer(const char *name
, struct ast_variable
*v
, struct ast_variable
*alt
, int realtime
)
15820 struct sip_peer
*peer
= NULL
;
15821 struct ast_ha
*oldha
= NULL
;
15822 int obproxyfound
=0;
15825 int format
=0; /* Ama flags */
15826 time_t regseconds
= 0;
15827 char *varname
= NULL
, *varval
= NULL
;
15828 struct ast_variable
*tmpvar
= NULL
;
15829 struct ast_flags peerflags
[2] = {{(0)}};
15830 struct ast_flags mask
[2] = {{(0)}};
15834 /* Note we do NOT use find_peer here, to avoid realtime recursion */
15835 /* We also use a case-sensitive comparison (unlike find_peer) so
15836 that case changes made to the peer name will be properly handled
15839 peer
= ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl
, name
, name
, 0, 0, strcmp
);
15842 /* Already in the list, remove it and it will be added back (or FREE'd) */
15844 if (!(peer
->objflags
& ASTOBJ_FLAG_MARKED
))
15847 if (!(peer
= ast_calloc(1, sizeof(*peer
))))
15856 /* Note that our peer HAS had its reference count incrased */
15858 peer
->lastmsgssent
= -1;
15861 set_peer_defaults(peer
); /* Set peer defaults */
15863 if (!found
&& name
)
15864 ast_copy_string(peer
->name
, name
, sizeof(peer
->name
));
15866 /* If we have channel variables, remove them (reload) */
15867 if (peer
->chanvars
) {
15868 ast_variables_destroy(peer
->chanvars
);
15869 peer
->chanvars
= NULL
;
15870 /* XXX should unregister ? */
15872 for (; v
|| ((v
= alt
) && !(alt
=NULL
)); v
= v
->next
) {
15873 if (handle_common_options(&peerflags
[0], &mask
[0], v
))
15875 if (realtime
&& !strcasecmp(v
->name
, "regseconds")) {
15876 ast_get_time_t(v
->value
, ®seconds
, 0, NULL
);
15877 } else if (realtime
&& !strcasecmp(v
->name
, "ipaddr") && !ast_strlen_zero(v
->value
) ) {
15878 inet_aton(v
->value
, &(peer
->addr
.sin_addr
));
15879 } else if (realtime
&& !strcasecmp(v
->name
, "name"))
15880 ast_copy_string(peer
->name
, v
->value
, sizeof(peer
->name
));
15881 else if (realtime
&& !strcasecmp(v
->name
, "fullcontact")) {
15882 ast_copy_string(peer
->fullcontact
, v
->value
, sizeof(peer
->fullcontact
));
15883 ast_set_flag(&peer
->flags
[1], SIP_PAGE2_RT_FROMCONTACT
);
15884 } else if (!strcasecmp(v
->name
, "secret"))
15885 ast_copy_string(peer
->secret
, v
->value
, sizeof(peer
->secret
));
15886 else if (!strcasecmp(v
->name
, "md5secret"))
15887 ast_copy_string(peer
->md5secret
, v
->value
, sizeof(peer
->md5secret
));
15888 else if (!strcasecmp(v
->name
, "auth"))
15889 peer
->auth
= add_realm_authentication(peer
->auth
, v
->value
, v
->lineno
);
15890 else if (!strcasecmp(v
->name
, "callerid")) {
15891 ast_callerid_split(v
->value
, peer
->cid_name
, sizeof(peer
->cid_name
), peer
->cid_num
, sizeof(peer
->cid_num
));
15892 } else if (!strcasecmp(v
->name
, "fullname")) {
15893 ast_copy_string(peer
->cid_name
, v
->value
, sizeof(peer
->cid_name
));
15894 } else if (!strcasecmp(v
->name
, "cid_number")) {
15895 ast_copy_string(peer
->cid_num
, v
->value
, sizeof(peer
->cid_num
));
15896 } else if (!strcasecmp(v
->name
, "context")) {
15897 ast_copy_string(peer
->context
, v
->value
, sizeof(peer
->context
));
15898 } else if (!strcasecmp(v
->name
, "subscribecontext")) {
15899 ast_copy_string(peer
->subscribecontext
, v
->value
, sizeof(peer
->subscribecontext
));
15900 } else if (!strcasecmp(v
->name
, "fromdomain")) {
15901 ast_copy_string(peer
->fromdomain
, v
->value
, sizeof(peer
->fromdomain
));
15902 } else if (!strcasecmp(v
->name
, "usereqphone")) {
15903 ast_set2_flag(&peer
->flags
[0], ast_true(v
->value
), SIP_USEREQPHONE
);
15904 } else if (!strcasecmp(v
->name
, "fromuser")) {
15905 ast_copy_string(peer
->fromuser
, v
->value
, sizeof(peer
->fromuser
));
15906 } else if (!strcasecmp(v
->name
, "host") || !strcasecmp(v
->name
, "outboundproxy")) {
15907 if (!strcasecmp(v
->value
, "dynamic")) {
15908 if (!strcasecmp(v
->name
, "outboundproxy") || obproxyfound
) {
15909 ast_log(LOG_WARNING
, "You can't have a dynamic outbound proxy, you big silly head at line %d.\n", v
->lineno
);
15911 /* They'll register with us */
15912 ast_set_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
);
15914 /* Initialize stuff iff we're not found, otherwise
15915 we keep going with what we had */
15916 memset(&peer
->addr
.sin_addr
, 0, 4);
15917 if (peer
->addr
.sin_port
) {
15918 /* If we've already got a port, make it the default rather than absolute */
15919 peer
->defaddr
.sin_port
= peer
->addr
.sin_port
;
15920 peer
->addr
.sin_port
= 0;
15925 /* Non-dynamic. Make sure we become that way if we're not */
15926 if (peer
->expire
> -1)
15927 ast_sched_del(sched
, peer
->expire
);
15929 ast_clear_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
);
15930 if (!obproxyfound
|| !strcasecmp(v
->name
, "outboundproxy")) {
15931 if (ast_get_ip_or_srv(&peer
->addr
, v
->value
, srvlookup
? "_sip._udp" : NULL
)) {
15932 ASTOBJ_UNREF(peer
, sip_destroy_peer
);
15936 if (!strcasecmp(v
->name
, "outboundproxy"))
15939 ast_copy_string(peer
->tohost
, v
->value
, sizeof(peer
->tohost
));
15940 if (!peer
->addr
.sin_port
)
15941 peer
->addr
.sin_port
= htons(STANDARD_SIP_PORT
);
15944 } else if (!strcasecmp(v
->name
, "defaultip")) {
15945 if (ast_get_ip(&peer
->defaddr
, v
->value
)) {
15946 ASTOBJ_UNREF(peer
, sip_destroy_peer
);
15949 } else if (!strcasecmp(v
->name
, "permit") || !strcasecmp(v
->name
, "deny")) {
15950 peer
->ha
= ast_append_ha(v
->name
, v
->value
, peer
->ha
);
15951 } else if (!strcasecmp(v
->name
, "port")) {
15952 if (!realtime
&& ast_test_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
))
15953 peer
->defaddr
.sin_port
= htons(atoi(v
->value
));
15955 peer
->addr
.sin_port
= htons(atoi(v
->value
));
15956 } else if (!strcasecmp(v
->name
, "callingpres")) {
15957 peer
->callingpres
= ast_parse_caller_presentation(v
->value
);
15958 if (peer
->callingpres
== -1)
15959 peer
->callingpres
= atoi(v
->value
);
15960 } else if (!strcasecmp(v
->name
, "username")) {
15961 ast_copy_string(peer
->username
, v
->value
, sizeof(peer
->username
));
15962 } else if (!strcasecmp(v
->name
, "language")) {
15963 ast_copy_string(peer
->language
, v
->value
, sizeof(peer
->language
));
15964 } else if (!strcasecmp(v
->name
, "regexten")) {
15965 ast_copy_string(peer
->regexten
, v
->value
, sizeof(peer
->regexten
));
15966 } else if (!strcasecmp(v
->name
, "call-limit") || !strcasecmp(v
->name
, "incominglimit")) {
15967 peer
->call_limit
= atoi(v
->value
);
15968 if (peer
->call_limit
< 0)
15969 peer
->call_limit
= 0;
15970 } else if (!strcasecmp(v
->name
, "amaflags")) {
15971 format
= ast_cdr_amaflags2int(v
->value
);
15973 ast_log(LOG_WARNING
, "Invalid AMA Flags for peer: %s at line %d\n", v
->value
, v
->lineno
);
15975 peer
->amaflags
= format
;
15977 } else if (!strcasecmp(v
->name
, "accountcode")) {
15978 ast_copy_string(peer
->accountcode
, v
->value
, sizeof(peer
->accountcode
));
15979 } else if (!strcasecmp(v
->name
, "mohinterpret")
15980 || !strcasecmp(v
->name
, "musicclass") || !strcasecmp(v
->name
, "musiconhold")) {
15981 ast_copy_string(peer
->mohinterpret
, v
->value
, sizeof(peer
->mohinterpret
));
15982 } else if (!strcasecmp(v
->name
, "mohsuggest")) {
15983 ast_copy_string(peer
->mohsuggest
, v
->value
, sizeof(peer
->mohsuggest
));
15984 } else if (!strcasecmp(v
->name
, "mailbox")) {
15985 ast_copy_string(peer
->mailbox
, v
->value
, sizeof(peer
->mailbox
));
15986 } else if (!strcasecmp(v
->name
, "subscribemwi")) {
15987 ast_set2_flag(&peer
->flags
[1], ast_true(v
->value
), SIP_PAGE2_SUBSCRIBEMWIONLY
);
15988 } else if (!strcasecmp(v
->name
, "vmexten")) {
15989 ast_copy_string(peer
->vmexten
, v
->value
, sizeof(peer
->vmexten
));
15990 } else if (!strcasecmp(v
->name
, "callgroup")) {
15991 peer
->callgroup
= ast_get_group(v
->value
);
15992 } else if (!strcasecmp(v
->name
, "allowtransfer")) {
15993 peer
->allowtransfer
= ast_true(v
->value
) ? TRANSFER_OPENFORALL
: TRANSFER_CLOSED
;
15994 } else if (!strcasecmp(v
->name
, "pickupgroup")) {
15995 peer
->pickupgroup
= ast_get_group(v
->value
);
15996 } else if (!strcasecmp(v
->name
, "allow")) {
15997 ast_parse_allow_disallow(&peer
->prefs
, &peer
->capability
, v
->value
, 1);
15998 } else if (!strcasecmp(v
->name
, "disallow")) {
15999 ast_parse_allow_disallow(&peer
->prefs
, &peer
->capability
, v
->value
, 0);
16000 } else if (!strcasecmp(v
->name
, "autoframing")) {
16001 peer
->autoframing
= ast_true(v
->value
);
16002 } else if (!strcasecmp(v
->name
, "rtptimeout")) {
16003 if ((sscanf(v
->value
, "%d", &peer
->rtptimeout
) != 1) || (peer
->rtptimeout
< 0)) {
16004 ast_log(LOG_WARNING
, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v
->value
, v
->lineno
);
16005 peer
->rtptimeout
= global_rtptimeout
;
16007 } else if (!strcasecmp(v
->name
, "rtpholdtimeout")) {
16008 if ((sscanf(v
->value
, "%d", &peer
->rtpholdtimeout
) != 1) || (peer
->rtpholdtimeout
< 0)) {
16009 ast_log(LOG_WARNING
, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v
->value
, v
->lineno
);
16010 peer
->rtpholdtimeout
= global_rtpholdtimeout
;
16012 } else if (!strcasecmp(v
->name
, "rtpkeepalive")) {
16013 if ((sscanf(v
->value
, "%d", &peer
->rtpkeepalive
) != 1) || (peer
->rtpkeepalive
< 0)) {
16014 ast_log(LOG_WARNING
, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v
->value
, v
->lineno
);
16015 peer
->rtpkeepalive
= global_rtpkeepalive
;
16017 } else if (!strcasecmp(v
->name
, "setvar")) {
16018 /* Set peer channel variable */
16019 varname
= ast_strdupa(v
->value
);
16020 if ((varval
= strchr(varname
, '='))) {
16022 if ((tmpvar
= ast_variable_new(varname
, varval
))) {
16023 tmpvar
->next
= peer
->chanvars
;
16024 peer
->chanvars
= tmpvar
;
16027 } else if (!strcasecmp(v
->name
, "qualify")) {
16028 if (!strcasecmp(v
->value
, "no")) {
16030 } else if (!strcasecmp(v
->value
, "yes")) {
16031 peer
->maxms
= DEFAULT_MAXMS
;
16032 } else if (sscanf(v
->value
, "%d", &peer
->maxms
) != 1) {
16033 ast_log(LOG_WARNING
, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", peer
->name
, v
->lineno
);
16036 } else if (!strcasecmp(v
->name
, "maxcallbitrate")) {
16037 peer
->maxcallbitrate
= atoi(v
->value
);
16038 if (peer
->maxcallbitrate
< 0)
16039 peer
->maxcallbitrate
= default_maxcallbitrate
;
16042 if (!ast_test_flag(&global_flags
[1], SIP_PAGE2_IGNOREREGEXPIRE
) && ast_test_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
) && realtime
) {
16043 time_t nowtime
= time(NULL
);
16045 if ((nowtime
- regseconds
) > 0) {
16046 destroy_association(peer
);
16047 memset(&peer
->addr
, 0, sizeof(peer
->addr
));
16049 ast_log(LOG_DEBUG
, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime
- regseconds
), (int)regseconds
, (int)nowtime
);
16052 ast_copy_flags(&peer
->flags
[0], &peerflags
[0], mask
[0].flags
);
16053 ast_copy_flags(&peer
->flags
[1], &peerflags
[1], mask
[1].flags
);
16054 if (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_ALLOWSUBSCRIBE
))
16055 global_allowsubscribe
= TRUE
; /* No global ban any more */
16056 if (!found
&& ast_test_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
) && !ast_test_flag(&peer
->flags
[0], SIP_REALTIME
))
16057 reg_source_db(peer
);
16058 ASTOBJ_UNMARK(peer
);
16059 ast_free_ha(oldha
);
16063 /*! \brief Re-read SIP.conf config file
16064 \note This function reloads all config data, except for
16065 active peers (with registrations). They will only
16066 change configuration data at restart, not at reload.
16067 SIP debug and recordhistory state will not change
16069 static int reload_config(enum channelreloadreason reason
)
16071 struct ast_config
*cfg
, *ucfg
;
16072 struct ast_variable
*v
;
16073 struct sip_peer
*peer
;
16074 struct sip_user
*user
;
16075 struct ast_hostent ahp
;
16076 char *cat
, *stringp
, *context
, *oldregcontext
;
16077 char newcontexts
[AST_MAX_CONTEXT
], oldcontexts
[AST_MAX_CONTEXT
];
16078 struct hostent
*hp
;
16080 struct ast_flags dummy
[2];
16081 int auto_sip_domains
= FALSE
;
16082 struct sockaddr_in old_bindaddr
= bindaddr
;
16083 int registry_count
= 0, peer_count
= 0, user_count
= 0;
16084 unsigned int temp_tos
= 0;
16085 struct ast_flags debugflag
= {0};
16087 cfg
= ast_config_load(config
);
16089 /* We *must* have a config file otherwise stop immediately */
16091 ast_log(LOG_NOTICE
, "Unable to load config %s\n", config
);
16095 /* Initialize copy of current global_regcontext for later use in removing stale contexts */
16096 ast_copy_string(oldcontexts
, global_regcontext
, sizeof(oldcontexts
));
16097 oldregcontext
= oldcontexts
;
16099 /* Clear all flags before setting default values */
16100 /* Preserve debugging settings for console */
16101 ast_copy_flags(&debugflag
, &global_flags
[1], SIP_PAGE2_DEBUG_CONSOLE
);
16102 ast_clear_flag(&global_flags
[0], AST_FLAGS_ALL
);
16103 ast_clear_flag(&global_flags
[1], AST_FLAGS_ALL
);
16104 ast_copy_flags(&global_flags
[1], &debugflag
, SIP_PAGE2_DEBUG_CONSOLE
);
16106 /* Reset IP addresses */
16107 memset(&bindaddr
, 0, sizeof(bindaddr
));
16108 memset(&localaddr
, 0, sizeof(localaddr
));
16109 memset(&externip
, 0, sizeof(externip
));
16110 memset(&default_prefs
, 0 , sizeof(default_prefs
));
16111 outboundproxyip
.sin_port
= htons(STANDARD_SIP_PORT
);
16112 outboundproxyip
.sin_family
= AF_INET
; /* Type of address: IPv4 */
16113 ourport
= STANDARD_SIP_PORT
;
16114 srvlookup
= DEFAULT_SRVLOOKUP
;
16115 global_tos_sip
= DEFAULT_TOS_SIP
;
16116 global_tos_audio
= DEFAULT_TOS_AUDIO
;
16117 global_tos_video
= DEFAULT_TOS_VIDEO
;
16118 externhost
[0] = '\0'; /* External host name (for behind NAT DynDNS support) */
16119 externexpire
= 0; /* Expiration for DNS re-issuing */
16120 externrefresh
= 10;
16121 memset(&outboundproxyip
, 0, sizeof(outboundproxyip
));
16123 /* Reset channel settings to default before re-configuring */
16124 allow_external_domains
= DEFAULT_ALLOW_EXT_DOM
; /* Allow external invites */
16125 global_regcontext
[0] = '\0';
16126 expiry
= DEFAULT_EXPIRY
;
16127 global_notifyringing
= DEFAULT_NOTIFYRINGING
;
16128 global_limitonpeers
= FALSE
;
16129 global_directrtpsetup
= FALSE
; /* Experimental feature, disabled by default */
16130 global_notifyhold
= FALSE
;
16131 global_alwaysauthreject
= 0;
16132 global_allowsubscribe
= FALSE
;
16133 ast_copy_string(global_useragent
, DEFAULT_USERAGENT
, sizeof(global_useragent
));
16134 ast_copy_string(default_notifymime
, DEFAULT_NOTIFYMIME
, sizeof(default_notifymime
));
16135 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME
))
16136 ast_copy_string(global_realm
, DEFAULT_REALM
, sizeof(global_realm
));
16138 ast_copy_string(global_realm
, ast_config_AST_SYSTEM_NAME
, sizeof(global_realm
));
16139 ast_copy_string(default_callerid
, DEFAULT_CALLERID
, sizeof(default_callerid
));
16140 compactheaders
= DEFAULT_COMPACTHEADERS
;
16141 global_reg_timeout
= DEFAULT_REGISTRATION_TIMEOUT
;
16142 global_regattempts_max
= 0;
16143 pedanticsipchecking
= DEFAULT_PEDANTIC
;
16144 global_mwitime
= DEFAULT_MWITIME
;
16145 autocreatepeer
= DEFAULT_AUTOCREATEPEER
;
16146 global_autoframing
= 0;
16147 global_allowguest
= DEFAULT_ALLOWGUEST
;
16148 global_rtptimeout
= 0;
16149 global_rtpholdtimeout
= 0;
16150 global_rtpkeepalive
= 0;
16151 global_allowtransfer
= TRANSFER_OPENFORALL
; /* Merrily accept all transfers by default */
16152 global_rtautoclear
= 120;
16153 ast_set_flag(&global_flags
[1], SIP_PAGE2_ALLOWSUBSCRIBE
); /* Default for peers, users: TRUE */
16154 ast_set_flag(&global_flags
[1], SIP_PAGE2_ALLOWOVERLAP
); /* Default for peers, users: TRUE */
16155 ast_set_flag(&global_flags
[1], SIP_PAGE2_RTUPDATE
);
16157 /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for peers and users */
16158 ast_copy_string(default_context
, DEFAULT_CONTEXT
, sizeof(default_context
));
16159 default_subscribecontext
[0] = '\0';
16160 default_language
[0] = '\0';
16161 default_fromdomain
[0] = '\0';
16162 default_qualify
= DEFAULT_QUALIFY
;
16163 default_maxcallbitrate
= DEFAULT_MAX_CALL_BITRATE
;
16164 ast_copy_string(default_mohinterpret
, DEFAULT_MOHINTERPRET
, sizeof(default_mohinterpret
));
16165 ast_copy_string(default_mohsuggest
, DEFAULT_MOHSUGGEST
, sizeof(default_mohsuggest
));
16166 ast_copy_string(default_vmexten
, DEFAULT_VMEXTEN
, sizeof(default_vmexten
));
16167 ast_set_flag(&global_flags
[0], SIP_DTMF_RFC2833
); /*!< Default DTMF setting: RFC2833 */
16168 ast_set_flag(&global_flags
[0], SIP_NAT_RFC3581
); /*!< NAT support if requested by device with rport */
16169 ast_set_flag(&global_flags
[0], SIP_CAN_REINVITE
); /*!< Allow re-invites */
16171 /* Debugging settings, always default to off */
16172 dumphistory
= FALSE
;
16173 recordhistory
= FALSE
;
16174 ast_clear_flag(&global_flags
[1], SIP_PAGE2_DEBUG_CONFIG
);
16176 /* Misc settings for the channel */
16177 global_relaxdtmf
= FALSE
;
16178 global_callevents
= FALSE
;
16179 global_t1min
= DEFAULT_T1MIN
;
16181 /* Copy the default jb config over global_jbconf */
16182 memcpy(&global_jbconf
, &default_jbconf
, sizeof(struct ast_jb_conf
));
16184 ast_clear_flag(&global_flags
[1], SIP_PAGE2_VIDEOSUPPORT
);
16186 /* Read the [general] config section of sip.conf (or from realtime config) */
16187 for (v
= ast_variable_browse(cfg
, "general"); v
; v
= v
->next
) {
16188 if (handle_common_options(&global_flags
[0], &dummy
[0], v
))
16190 /* handle jb conf */
16191 if (!ast_jb_read_conf(&global_jbconf
, v
->name
, v
->value
))
16194 /* Create the interface list */
16195 if (!strcasecmp(v
->name
, "context")) {
16196 ast_copy_string(default_context
, v
->value
, sizeof(default_context
));
16197 } else if (!strcasecmp(v
->name
, "allowguest")) {
16198 global_allowguest
= ast_true(v
->value
) ? 1 : 0;
16199 } else if (!strcasecmp(v
->name
, "realm")) {
16200 ast_copy_string(global_realm
, v
->value
, sizeof(global_realm
));
16201 } else if (!strcasecmp(v
->name
, "useragent")) {
16202 ast_copy_string(global_useragent
, v
->value
, sizeof(global_useragent
));
16204 ast_log(LOG_DEBUG
, "Setting SIP channel User-Agent Name to %s\n", global_useragent
);
16205 } else if (!strcasecmp(v
->name
, "allowtransfer")) {
16206 global_allowtransfer
= ast_true(v
->value
) ? TRANSFER_OPENFORALL
: TRANSFER_CLOSED
;
16207 } else if (!strcasecmp(v
->name
, "rtcachefriends")) {
16208 ast_set2_flag(&global_flags
[1], ast_true(v
->value
), SIP_PAGE2_RTCACHEFRIENDS
);
16209 } else if (!strcasecmp(v
->name
, "rtsavesysname")) {
16210 ast_set2_flag(&global_flags
[1], ast_true(v
->value
), SIP_PAGE2_RTSAVE_SYSNAME
);
16211 } else if (!strcasecmp(v
->name
, "rtupdate")) {
16212 ast_set2_flag(&global_flags
[1], ast_true(v
->value
), SIP_PAGE2_RTUPDATE
);
16213 } else if (!strcasecmp(v
->name
, "ignoreregexpire")) {
16214 ast_set2_flag(&global_flags
[1], ast_true(v
->value
), SIP_PAGE2_IGNOREREGEXPIRE
);
16215 } else if (!strcasecmp(v
->name
, "t1min")) {
16216 global_t1min
= atoi(v
->value
);
16217 } else if (!strcasecmp(v
->name
, "rtautoclear")) {
16218 int i
= atoi(v
->value
);
16220 global_rtautoclear
= i
;
16223 ast_set2_flag(&global_flags
[1], i
|| ast_true(v
->value
), SIP_PAGE2_RTAUTOCLEAR
);
16224 } else if (!strcasecmp(v
->name
, "usereqphone")) {
16225 ast_set2_flag(&global_flags
[0], ast_true(v
->value
), SIP_USEREQPHONE
);
16226 } else if (!strcasecmp(v
->name
, "relaxdtmf")) {
16227 global_relaxdtmf
= ast_true(v
->value
);
16228 } else if (!strcasecmp(v
->name
, "checkmwi")) {
16229 if ((sscanf(v
->value
, "%d", &global_mwitime
) != 1) || (global_mwitime
< 0)) {
16230 ast_log(LOG_WARNING
, "'%s' is not a valid MWI time setting at line %d. Using default (10).\n", v
->value
, v
->lineno
);
16231 global_mwitime
= DEFAULT_MWITIME
;
16233 } else if (!strcasecmp(v
->name
, "vmexten")) {
16234 ast_copy_string(default_vmexten
, v
->value
, sizeof(default_vmexten
));
16235 } else if (!strcasecmp(v
->name
, "rtptimeout")) {
16236 if ((sscanf(v
->value
, "%d", &global_rtptimeout
) != 1) || (global_rtptimeout
< 0)) {
16237 ast_log(LOG_WARNING
, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v
->value
, v
->lineno
);
16238 global_rtptimeout
= 0;
16240 } else if (!strcasecmp(v
->name
, "rtpholdtimeout")) {
16241 if ((sscanf(v
->value
, "%d", &global_rtpholdtimeout
) != 1) || (global_rtpholdtimeout
< 0)) {
16242 ast_log(LOG_WARNING
, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v
->value
, v
->lineno
);
16243 global_rtpholdtimeout
= 0;
16245 } else if (!strcasecmp(v
->name
, "rtpkeepalive")) {
16246 if ((sscanf(v
->value
, "%d", &global_rtpkeepalive
) != 1) || (global_rtpkeepalive
< 0)) {
16247 ast_log(LOG_WARNING
, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v
->value
, v
->lineno
);
16248 global_rtpkeepalive
= 0;
16250 } else if (!strcasecmp(v
->name
, "compactheaders")) {
16251 compactheaders
= ast_true(v
->value
);
16252 } else if (!strcasecmp(v
->name
, "notifymimetype")) {
16253 ast_copy_string(default_notifymime
, v
->value
, sizeof(default_notifymime
));
16254 } else if (!strcasecmp(v
->name
, "limitonpeers")) {
16255 global_limitonpeers
= ast_true(v
->value
);
16256 } else if (!strcasecmp(v
->name
, "directrtpsetup")) {
16257 global_directrtpsetup
= ast_true(v
->value
);
16258 } else if (!strcasecmp(v
->name
, "notifyringing")) {
16259 global_notifyringing
= ast_true(v
->value
);
16260 } else if (!strcasecmp(v
->name
, "notifyhold")) {
16261 global_notifyhold
= ast_true(v
->value
);
16262 } else if (!strcasecmp(v
->name
, "alwaysauthreject")) {
16263 global_alwaysauthreject
= ast_true(v
->value
);
16264 } else if (!strcasecmp(v
->name
, "mohinterpret")
16265 || !strcasecmp(v
->name
, "musicclass") || !strcasecmp(v
->name
, "musiconhold")) {
16266 ast_copy_string(default_mohinterpret
, v
->value
, sizeof(default_mohinterpret
));
16267 } else if (!strcasecmp(v
->name
, "mohsuggest")) {
16268 ast_copy_string(default_mohsuggest
, v
->value
, sizeof(default_mohsuggest
));
16269 } else if (!strcasecmp(v
->name
, "language")) {
16270 ast_copy_string(default_language
, v
->value
, sizeof(default_language
));
16271 } else if (!strcasecmp(v
->name
, "regcontext")) {
16272 ast_copy_string(newcontexts
, v
->value
, sizeof(newcontexts
));
16273 stringp
= newcontexts
;
16274 /* Let's remove any contexts that are no longer defined in regcontext */
16275 cleanup_stale_contexts(stringp
, oldregcontext
);
16276 /* Create contexts if they don't exist already */
16277 while ((context
= strsep(&stringp
, "&"))) {
16278 if (!ast_context_find(context
))
16279 ast_context_create(NULL
, context
,"SIP");
16281 ast_copy_string(global_regcontext
, v
->value
, sizeof(global_regcontext
));
16282 } else if (!strcasecmp(v
->name
, "callerid")) {
16283 ast_copy_string(default_callerid
, v
->value
, sizeof(default_callerid
));
16284 } else if (!strcasecmp(v
->name
, "fromdomain")) {
16285 ast_copy_string(default_fromdomain
, v
->value
, sizeof(default_fromdomain
));
16286 } else if (!strcasecmp(v
->name
, "outboundproxy")) {
16287 if (ast_get_ip_or_srv(&outboundproxyip
, v
->value
, srvlookup
? "_sip._udp" : NULL
) < 0)
16288 ast_log(LOG_WARNING
, "Unable to locate host '%s'\n", v
->value
);
16289 } else if (!strcasecmp(v
->name
, "outboundproxyport")) {
16290 /* Port needs to be after IP */
16291 sscanf(v
->value
, "%d", &format
);
16292 outboundproxyip
.sin_port
= htons(format
);
16293 } else if (!strcasecmp(v
->name
, "autocreatepeer")) {
16294 autocreatepeer
= ast_true(v
->value
);
16295 } else if (!strcasecmp(v
->name
, "srvlookup")) {
16296 srvlookup
= ast_true(v
->value
);
16297 } else if (!strcasecmp(v
->name
, "pedantic")) {
16298 pedanticsipchecking
= ast_true(v
->value
);
16299 } else if (!strcasecmp(v
->name
, "maxexpirey") || !strcasecmp(v
->name
, "maxexpiry")) {
16300 max_expiry
= atoi(v
->value
);
16301 if (max_expiry
< 1)
16302 max_expiry
= DEFAULT_MAX_EXPIRY
;
16303 } else if (!strcasecmp(v
->name
, "minexpirey") || !strcasecmp(v
->name
, "minexpiry")) {
16304 min_expiry
= atoi(v
->value
);
16305 if (min_expiry
< 1)
16306 min_expiry
= DEFAULT_MIN_EXPIRY
;
16307 } else if (!strcasecmp(v
->name
, "defaultexpiry") || !strcasecmp(v
->name
, "defaultexpirey")) {
16308 default_expiry
= atoi(v
->value
);
16309 if (default_expiry
< 1)
16310 default_expiry
= DEFAULT_DEFAULT_EXPIRY
;
16311 } else if (!strcasecmp(v
->name
, "sipdebug")) { /* XXX maybe ast_set2_flags ? */
16312 if (ast_true(v
->value
))
16313 ast_set_flag(&global_flags
[1], SIP_PAGE2_DEBUG_CONFIG
);
16314 } else if (!strcasecmp(v
->name
, "dumphistory")) {
16315 dumphistory
= ast_true(v
->value
);
16316 } else if (!strcasecmp(v
->name
, "recordhistory")) {
16317 recordhistory
= ast_true(v
->value
);
16318 } else if (!strcasecmp(v
->name
, "registertimeout")) {
16319 global_reg_timeout
= atoi(v
->value
);
16320 if (global_reg_timeout
< 1)
16321 global_reg_timeout
= DEFAULT_REGISTRATION_TIMEOUT
;
16322 } else if (!strcasecmp(v
->name
, "registerattempts")) {
16323 global_regattempts_max
= atoi(v
->value
);
16324 } else if (!strcasecmp(v
->name
, "bindaddr")) {
16325 if (!(hp
= ast_gethostbyname(v
->value
, &ahp
))) {
16326 ast_log(LOG_WARNING
, "Invalid address: %s\n", v
->value
);
16328 memcpy(&bindaddr
.sin_addr
, hp
->h_addr
, sizeof(bindaddr
.sin_addr
));
16330 } else if (!strcasecmp(v
->name
, "localnet")) {
16332 if (!(na
= ast_append_ha("d", v
->value
, localaddr
)))
16333 ast_log(LOG_WARNING
, "Invalid localnet value: %s\n", v
->value
);
16336 } else if (!strcasecmp(v
->name
, "localmask")) {
16337 ast_log(LOG_WARNING
, "Use of localmask is no long supported -- use localnet with mask syntax\n");
16338 } else if (!strcasecmp(v
->name
, "externip")) {
16339 if (!(hp
= ast_gethostbyname(v
->value
, &ahp
)))
16340 ast_log(LOG_WARNING
, "Invalid address for externip keyword: %s\n", v
->value
);
16342 memcpy(&externip
.sin_addr
, hp
->h_addr
, sizeof(externip
.sin_addr
));
16344 } else if (!strcasecmp(v
->name
, "externhost")) {
16345 ast_copy_string(externhost
, v
->value
, sizeof(externhost
));
16346 if (!(hp
= ast_gethostbyname(externhost
, &ahp
)))
16347 ast_log(LOG_WARNING
, "Invalid address for externhost keyword: %s\n", externhost
);
16349 memcpy(&externip
.sin_addr
, hp
->h_addr
, sizeof(externip
.sin_addr
));
16350 externexpire
= time(NULL
);
16351 } else if (!strcasecmp(v
->name
, "externrefresh")) {
16352 if (sscanf(v
->value
, "%d", &externrefresh
) != 1) {
16353 ast_log(LOG_WARNING
, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v
->value
, v
->lineno
);
16354 externrefresh
= 10;
16356 } else if (!strcasecmp(v
->name
, "allow")) {
16357 ast_parse_allow_disallow(&default_prefs
, &global_capability
, v
->value
, 1);
16358 } else if (!strcasecmp(v
->name
, "disallow")) {
16359 ast_parse_allow_disallow(&default_prefs
, &global_capability
, v
->value
, 0);
16360 } else if (!strcasecmp(v
->name
, "autoframing")) {
16361 global_autoframing
= ast_true(v
->value
);
16362 } else if (!strcasecmp(v
->name
, "allowexternaldomains")) {
16363 allow_external_domains
= ast_true(v
->value
);
16364 } else if (!strcasecmp(v
->name
, "autodomain")) {
16365 auto_sip_domains
= ast_true(v
->value
);
16366 } else if (!strcasecmp(v
->name
, "domain")) {
16367 char *domain
= ast_strdupa(v
->value
);
16368 char *context
= strchr(domain
, ',');
16373 if (option_debug
&& ast_strlen_zero(context
))
16374 ast_log(LOG_DEBUG
, "No context specified at line %d for domain '%s'\n", v
->lineno
, domain
);
16375 if (ast_strlen_zero(domain
))
16376 ast_log(LOG_WARNING
, "Empty domain specified at line %d\n", v
->lineno
);
16378 add_sip_domain(ast_strip(domain
), SIP_DOMAIN_CONFIG
, context
? ast_strip(context
) : "");
16379 } else if (!strcasecmp(v
->name
, "register")) {
16380 if (sip_register(v
->value
, v
->lineno
) == 0)
16382 } else if (!strcasecmp(v
->name
, "tos")) {
16383 if (!ast_str2tos(v
->value
, &temp_tos
)) {
16384 global_tos_sip
= temp_tos
;
16385 global_tos_audio
= temp_tos
;
16386 global_tos_video
= temp_tos
;
16387 ast_log(LOG_WARNING
, "tos value at line %d is deprecated. See doc/ip-tos.txt for more information.\n", v
->lineno
);
16389 ast_log(LOG_WARNING
, "Invalid tos value at line %d, See doc/ip-tos.txt for more information.\n", v
->lineno
);
16390 } else if (!strcasecmp(v
->name
, "tos_sip")) {
16391 if (ast_str2tos(v
->value
, &global_tos_sip
))
16392 ast_log(LOG_WARNING
, "Invalid tos_sip value at line %d, recommended value is 'cs3'. See doc/ip-tos.txt.\n", v
->lineno
);
16393 } else if (!strcasecmp(v
->name
, "tos_audio")) {
16394 if (ast_str2tos(v
->value
, &global_tos_audio
))
16395 ast_log(LOG_WARNING
, "Invalid tos_audio value at line %d, recommended value is 'ef'. See doc/ip-tos.txt.\n", v
->lineno
);
16396 } else if (!strcasecmp(v
->name
, "tos_video")) {
16397 if (ast_str2tos(v
->value
, &global_tos_video
))
16398 ast_log(LOG_WARNING
, "Invalid tos_video value at line %d, recommended value is 'af41'. See doc/ip-tos.txt.\n", v
->lineno
);
16399 } else if (!strcasecmp(v
->name
, "bindport")) {
16400 if (sscanf(v
->value
, "%d", &ourport
) == 1) {
16401 bindaddr
.sin_port
= htons(ourport
);
16403 ast_log(LOG_WARNING
, "Invalid port number '%s' at line %d of %s\n", v
->value
, v
->lineno
, config
);
16405 } else if (!strcasecmp(v
->name
, "qualify")) {
16406 if (!strcasecmp(v
->value
, "no")) {
16407 default_qualify
= 0;
16408 } else if (!strcasecmp(v
->value
, "yes")) {
16409 default_qualify
= DEFAULT_MAXMS
;
16410 } else if (sscanf(v
->value
, "%d", &default_qualify
) != 1) {
16411 ast_log(LOG_WARNING
, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v
->lineno
);
16412 default_qualify
= 0;
16414 } else if (!strcasecmp(v
->name
, "callevents")) {
16415 global_callevents
= ast_true(v
->value
);
16416 } else if (!strcasecmp(v
->name
, "maxcallbitrate")) {
16417 default_maxcallbitrate
= atoi(v
->value
);
16418 if (default_maxcallbitrate
< 0)
16419 default_maxcallbitrate
= DEFAULT_MAX_CALL_BITRATE
;
16423 if (!allow_external_domains
&& AST_LIST_EMPTY(&domain_list
)) {
16424 ast_log(LOG_WARNING
, "To disallow external domains, you need to configure local SIP domains.\n");
16425 allow_external_domains
= 1;
16428 /* Build list of authentication to various SIP realms, i.e. service providers */
16429 for (v
= ast_variable_browse(cfg
, "authentication"); v
; v
= v
->next
) {
16430 /* Format for authentication is auth = username:password@realm */
16431 if (!strcasecmp(v
->name
, "auth"))
16432 authl
= add_realm_authentication(authl
, v
->value
, v
->lineno
);
16435 ucfg
= ast_config_load("users.conf");
16437 struct ast_variable
*gen
;
16438 int genhassip
, genregistersip
;
16439 const char *hassip
, *registersip
;
16441 genhassip
= ast_true(ast_variable_retrieve(ucfg
, "general", "hassip"));
16442 genregistersip
= ast_true(ast_variable_retrieve(ucfg
, "general", "registersip"));
16443 gen
= ast_variable_browse(ucfg
, "general");
16444 cat
= ast_category_browse(ucfg
, NULL
);
16446 if (strcasecmp(cat
, "general")) {
16447 hassip
= ast_variable_retrieve(ucfg
, cat
, "hassip");
16448 registersip
= ast_variable_retrieve(ucfg
, cat
, "registersip");
16449 if (ast_true(hassip
) || (!hassip
&& genhassip
)) {
16450 peer
= build_peer(cat
, gen
, ast_variable_browse(ucfg
, cat
), 0);
16452 ASTOBJ_CONTAINER_LINK(&peerl
,peer
);
16453 ASTOBJ_UNREF(peer
, sip_destroy_peer
);
16457 if (ast_true(registersip
) || (!registersip
&& genregistersip
)) {
16459 const char *host
= ast_variable_retrieve(ucfg
, cat
, "host");
16460 const char *username
= ast_variable_retrieve(ucfg
, cat
, "username");
16461 const char *secret
= ast_variable_retrieve(ucfg
, cat
, "secret");
16462 const char *contact
= ast_variable_retrieve(ucfg
, cat
, "contact");
16464 host
= ast_variable_retrieve(ucfg
, "general", "host");
16466 username
= ast_variable_retrieve(ucfg
, "general", "username");
16468 secret
= ast_variable_retrieve(ucfg
, "general", "secret");
16471 if (!ast_strlen_zero(username
) && !ast_strlen_zero(host
)) {
16472 if (!ast_strlen_zero(secret
))
16473 snprintf(tmp
, sizeof(tmp
), "%s:%s@%s/%s", username
, secret
, host
, contact
);
16475 snprintf(tmp
, sizeof(tmp
), "%s@%s/%s", username
, host
, contact
);
16476 if (sip_register(tmp
, 0) == 0)
16481 cat
= ast_category_browse(ucfg
, cat
);
16483 ast_config_destroy(ucfg
);
16487 /* Load peers, users and friends */
16489 while ( (cat
= ast_category_browse(cfg
, cat
)) ) {
16491 if (!strcasecmp(cat
, "general") || !strcasecmp(cat
, "authentication"))
16493 utype
= ast_variable_retrieve(cfg
, cat
, "type");
16495 ast_log(LOG_WARNING
, "Section '%s' lacks type\n", cat
);
16498 int is_user
= 0, is_peer
= 0;
16499 if (!strcasecmp(utype
, "user"))
16501 else if (!strcasecmp(utype
, "friend"))
16502 is_user
= is_peer
= 1;
16503 else if (!strcasecmp(utype
, "peer"))
16506 ast_log(LOG_WARNING
, "Unknown type '%s' for '%s' in %s\n", utype
, cat
, "sip.conf");
16510 user
= build_user(cat
, ast_variable_browse(cfg
, cat
), 0);
16512 ASTOBJ_CONTAINER_LINK(&userl
,user
);
16513 ASTOBJ_UNREF(user
, sip_destroy_user
);
16518 peer
= build_peer(cat
, ast_variable_browse(cfg
, cat
), NULL
, 0);
16520 ASTOBJ_CONTAINER_LINK(&peerl
,peer
);
16521 ASTOBJ_UNREF(peer
, sip_destroy_peer
);
16527 if (ast_find_ourip(&__ourip
, bindaddr
)) {
16528 ast_log(LOG_WARNING
, "Unable to get own IP address, SIP disabled\n");
16531 if (!ntohs(bindaddr
.sin_port
))
16532 bindaddr
.sin_port
= ntohs(STANDARD_SIP_PORT
);
16533 bindaddr
.sin_family
= AF_INET
;
16534 ast_mutex_lock(&netlock
);
16535 if ((sipsock
> -1) && (memcmp(&old_bindaddr
, &bindaddr
, sizeof(struct sockaddr_in
)))) {
16540 sipsock
= socket(AF_INET
, SOCK_DGRAM
, 0);
16542 ast_log(LOG_WARNING
, "Unable to create SIP socket: %s\n", strerror(errno
));
16545 /* Allow SIP clients on the same host to access us: */
16546 const int reuseFlag
= 1;
16548 setsockopt(sipsock
, SOL_SOCKET
, SO_REUSEADDR
,
16549 (const char*)&reuseFlag
,
16552 ast_enable_packet_fragmentation(sipsock
);
16554 if (bind(sipsock
, (struct sockaddr
*)&bindaddr
, sizeof(bindaddr
)) < 0) {
16555 ast_log(LOG_WARNING
, "Failed to bind to %s:%d: %s\n",
16556 ast_inet_ntoa(bindaddr
.sin_addr
), ntohs(bindaddr
.sin_port
),
16561 if (option_verbose
> 1) {
16562 ast_verbose(VERBOSE_PREFIX_2
"SIP Listening on %s:%d\n",
16563 ast_inet_ntoa(bindaddr
.sin_addr
), ntohs(bindaddr
.sin_port
));
16564 ast_verbose(VERBOSE_PREFIX_2
"Using SIP TOS: %s\n", ast_tos2str(global_tos_sip
));
16566 if (setsockopt(sipsock
, IPPROTO_IP
, IP_TOS
, &global_tos_sip
, sizeof(global_tos_sip
)))
16567 ast_log(LOG_WARNING
, "Unable to set SIP TOS to %s\n", ast_tos2str(global_tos_sip
));
16571 ast_mutex_unlock(&netlock
);
16573 /* Add default domains - host name, IP address and IP:port */
16574 /* Only do this if user added any sip domain with "localdomains" */
16575 /* In order to *not* break backwards compatibility */
16576 /* Some phones address us at IP only, some with additional port number */
16577 if (auto_sip_domains
) {
16578 char temp
[MAXHOSTNAMELEN
];
16580 /* First our default IP address */
16581 if (bindaddr
.sin_addr
.s_addr
)
16582 add_sip_domain(ast_inet_ntoa(bindaddr
.sin_addr
), SIP_DOMAIN_AUTO
, NULL
);
16584 ast_log(LOG_NOTICE
, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
16586 /* Our extern IP address, if configured */
16587 if (externip
.sin_addr
.s_addr
)
16588 add_sip_domain(ast_inet_ntoa(externip
.sin_addr
), SIP_DOMAIN_AUTO
, NULL
);
16590 /* Extern host name (NAT traversal support) */
16591 if (!ast_strlen_zero(externhost
))
16592 add_sip_domain(externhost
, SIP_DOMAIN_AUTO
, NULL
);
16594 /* Our host name */
16595 if (!gethostname(temp
, sizeof(temp
)))
16596 add_sip_domain(temp
, SIP_DOMAIN_AUTO
, NULL
);
16599 /* Release configuration from memory */
16600 ast_config_destroy(cfg
);
16602 /* Load the list of manual NOTIFY types to support */
16604 ast_config_destroy(notify_types
);
16605 notify_types
= ast_config_load(notify_config
);
16607 /* Done, tell the manager */
16608 manager_event(EVENT_FLAG_SYSTEM
, "ChannelReload", "Channel: SIP\r\nReloadReason: %s\r\nRegistry_Count: %d\r\nPeer_Count: %d\r\nUser_Count: %d\r\n\r\n", channelreloadreason2txt(reason
), registry_count
, peer_count
, user_count
);
16613 static struct ast_udptl
*sip_get_udptl_peer(struct ast_channel
*chan
)
16616 struct ast_udptl
*udptl
= NULL
;
16618 p
= chan
->tech_pvt
;
16622 ast_mutex_lock(&p
->lock
);
16623 if (p
->udptl
&& ast_test_flag(&p
->flags
[0], SIP_CAN_REINVITE
))
16625 ast_mutex_unlock(&p
->lock
);
16629 static int sip_set_udptl_peer(struct ast_channel
*chan
, struct ast_udptl
*udptl
)
16633 p
= chan
->tech_pvt
;
16636 ast_mutex_lock(&p
->lock
);
16638 ast_udptl_get_peer(udptl
, &p
->udptlredirip
);
16640 memset(&p
->udptlredirip
, 0, sizeof(p
->udptlredirip
));
16641 if (!ast_test_flag(&p
->flags
[0], SIP_GOTREFER
)) {
16642 if (!p
->pendinginvite
) {
16643 if (option_debug
> 2) {
16644 ast_log(LOG_DEBUG
, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s:%d\n", p
->callid
, ast_inet_ntoa(udptl
? p
->udptlredirip
.sin_addr
: p
->ourip
), udptl
? ntohs(p
->udptlredirip
.sin_port
) : 0);
16646 transmit_reinvite_with_t38_sdp(p
);
16647 } else if (!ast_test_flag(&p
->flags
[0], SIP_PENDINGBYE
)) {
16648 if (option_debug
> 2) {
16649 ast_log(LOG_DEBUG
, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s:%d\n", p
->callid
, ast_inet_ntoa(udptl
? p
->udptlredirip
.sin_addr
: p
->ourip
), udptl
? ntohs(p
->udptlredirip
.sin_port
) : 0);
16651 ast_set_flag(&p
->flags
[0], SIP_NEEDREINVITE
);
16654 /* Reset lastrtprx timer */
16655 p
->lastrtprx
= p
->lastrtptx
= time(NULL
);
16656 ast_mutex_unlock(&p
->lock
);
16660 /*! \brief Handle T38 reinvite
16661 \todo Make sure we don't destroy the call if we can't handle the re-invite.
16662 Nothing should be changed until we have processed the SDP and know that we
16665 static int sip_handle_t38_reinvite(struct ast_channel
*chan
, struct sip_pvt
*pvt
, int reinvite
)
16670 p
= chan
->tech_pvt
;
16671 if (!p
|| !pvt
->udptl
)
16674 /* Setup everything on the other side like offered/responded from first side */
16675 ast_mutex_lock(&p
->lock
);
16677 /*! \todo check if this is not set earlier when setting up the PVT. If not
16678 maybe it should move there. */
16679 p
->t38
.jointcapability
= p
->t38
.peercapability
= pvt
->t38
.jointcapability
;
16681 ast_udptl_set_far_max_datagram(p
->udptl
, ast_udptl_get_local_max_datagram(pvt
->udptl
));
16682 ast_udptl_set_local_max_datagram(p
->udptl
, ast_udptl_get_local_max_datagram(pvt
->udptl
));
16683 ast_udptl_set_error_correction_scheme(p
->udptl
, ast_udptl_get_error_correction_scheme(pvt
->udptl
));
16685 if (reinvite
) { /* If we are handling sending re-invite to the other side of the bridge */
16686 /*! \note The SIP_CAN_REINVITE flag is for RTP media redirects,
16687 not really T38 re-invites which are different. In this
16688 case it's used properly, to see if we can reinvite over
16691 if (ast_test_flag(&p
->flags
[0], SIP_CAN_REINVITE
) && ast_test_flag(&pvt
->flags
[0], SIP_CAN_REINVITE
)) {
16692 ast_udptl_get_peer(pvt
->udptl
, &p
->udptlredirip
);
16695 memset(&p
->udptlredirip
, 0, sizeof(p
->udptlredirip
));
16697 if (!ast_test_flag(&p
->flags
[0], SIP_GOTREFER
)) {
16698 if (!p
->pendinginvite
) {
16699 if (option_debug
> 2) {
16701 ast_log(LOG_DEBUG
, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s:%d\n", p
->callid
, ast_inet_ntoa(p
->udptlredirip
.sin_addr
), ntohs(p
->udptlredirip
.sin_port
));
16703 ast_log(LOG_DEBUG
, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to us (IP %s)\n", p
->callid
, ast_inet_ntoa(p
->ourip
));
16705 transmit_reinvite_with_t38_sdp(p
);
16706 } else if (!ast_test_flag(&p
->flags
[0], SIP_PENDINGBYE
)) {
16707 if (option_debug
> 2) {
16709 ast_log(LOG_DEBUG
, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s:%d\n", p
->callid
, ast_inet_ntoa(p
->udptlredirip
.sin_addr
), ntohs(p
->udptlredirip
.sin_port
));
16711 ast_log(LOG_DEBUG
, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to us (IP %s)\n", p
->callid
, ast_inet_ntoa(p
->ourip
));
16713 ast_set_flag(&p
->flags
[0], SIP_NEEDREINVITE
);
16716 /* Reset lastrtprx timer */
16717 p
->lastrtprx
= p
->lastrtptx
= time(NULL
);
16718 ast_mutex_unlock(&p
->lock
);
16720 } else { /* If we are handling sending 200 OK to the other side of the bridge */
16721 if (ast_test_flag(&p
->flags
[0], SIP_CAN_REINVITE
) && ast_test_flag(&pvt
->flags
[0], SIP_CAN_REINVITE
)) {
16722 ast_udptl_get_peer(pvt
->udptl
, &p
->udptlredirip
);
16725 memset(&p
->udptlredirip
, 0, sizeof(p
->udptlredirip
));
16727 if (option_debug
> 2) {
16729 ast_log(LOG_DEBUG
, "Responding 200 OK on SIP '%s' - It's UDPTL soon redirected to IP %s:%d\n", p
->callid
, ast_inet_ntoa(p
->udptlredirip
.sin_addr
), ntohs(p
->udptlredirip
.sin_port
));
16731 ast_log(LOG_DEBUG
, "Responding 200 OK on SIP '%s' - It's UDPTL soon redirected to us (IP %s)\n", p
->callid
, ast_inet_ntoa(p
->ourip
));
16733 pvt
->t38
.state
= T38_ENABLED
;
16734 p
->t38
.state
= T38_ENABLED
;
16735 if (option_debug
> 1) {
16736 ast_log(LOG_DEBUG
, "T38 changed state to %d on channel %s\n", pvt
->t38
.state
, pvt
->owner
? pvt
->owner
->name
: "<none>");
16737 ast_log(LOG_DEBUG
, "T38 changed state to %d on channel %s\n", p
->t38
.state
, chan
? chan
->name
: "<none>");
16739 transmit_response_with_t38_sdp(p
, "200 OK", &p
->initreq
, XMIT_CRITICAL
);
16740 p
->lastrtprx
= p
->lastrtptx
= time(NULL
);
16741 ast_mutex_unlock(&p
->lock
);
16747 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
16748 static enum ast_rtp_get_result
sip_get_rtp_peer(struct ast_channel
*chan
, struct ast_rtp
**rtp
)
16750 struct sip_pvt
*p
= NULL
;
16751 enum ast_rtp_get_result res
= AST_RTP_TRY_PARTIAL
;
16753 if (!(p
= chan
->tech_pvt
))
16754 return AST_RTP_GET_FAILED
;
16756 ast_mutex_lock(&p
->lock
);
16758 ast_mutex_unlock(&p
->lock
);
16759 return AST_RTP_GET_FAILED
;
16764 if (ast_rtp_getnat(*rtp
) && !ast_test_flag(&p
->flags
[0], SIP_CAN_REINVITE_NAT
))
16765 res
= AST_RTP_TRY_PARTIAL
;
16766 else if (ast_test_flag(&p
->flags
[0], SIP_CAN_REINVITE
))
16767 res
= AST_RTP_TRY_NATIVE
;
16768 else if (ast_test_flag(&global_jbconf
, AST_JB_FORCED
))
16769 res
= AST_RTP_GET_FAILED
;
16771 ast_mutex_unlock(&p
->lock
);
16776 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
16777 static enum ast_rtp_get_result
sip_get_vrtp_peer(struct ast_channel
*chan
, struct ast_rtp
**rtp
)
16779 struct sip_pvt
*p
= NULL
;
16780 enum ast_rtp_get_result res
= AST_RTP_TRY_PARTIAL
;
16782 if (!(p
= chan
->tech_pvt
))
16783 return AST_RTP_GET_FAILED
;
16785 ast_mutex_lock(&p
->lock
);
16787 ast_mutex_unlock(&p
->lock
);
16788 return AST_RTP_GET_FAILED
;
16793 if (ast_test_flag(&p
->flags
[0], SIP_CAN_REINVITE
))
16794 res
= AST_RTP_TRY_NATIVE
;
16796 ast_mutex_unlock(&p
->lock
);
16801 /*! \brief Set the RTP peer for this call */
16802 static int sip_set_rtp_peer(struct ast_channel
*chan
, struct ast_rtp
*rtp
, struct ast_rtp
*vrtp
, int codecs
, int nat_active
)
16807 p
= chan
->tech_pvt
;
16811 /* Disable early RTP bridge */
16812 if (chan
->_state
!= AST_STATE_UP
&& !global_directrtpsetup
) /* We are in early state */
16815 ast_mutex_lock(&p
->lock
);
16816 if (ast_test_flag(&p
->flags
[0], SIP_ALREADYGONE
)) {
16817 /* If we're destroyed, don't bother */
16818 ast_mutex_unlock(&p
->lock
);
16822 /* if this peer cannot handle reinvites of the media stream to devices
16823 that are known to be behind a NAT, then stop the process now
16825 if (nat_active
&& !ast_test_flag(&p
->flags
[0], SIP_CAN_REINVITE_NAT
)) {
16826 ast_mutex_unlock(&p
->lock
);
16831 changed
|= ast_rtp_get_peer(rtp
, &p
->redirip
);
16832 } else if (p
->redirip
.sin_addr
.s_addr
|| ntohs(p
->redirip
.sin_port
) != 0) {
16833 memset(&p
->redirip
, 0, sizeof(p
->redirip
));
16837 changed
|= ast_rtp_get_peer(vrtp
, &p
->vredirip
);
16838 } else if (p
->vredirip
.sin_addr
.s_addr
|| ntohs(p
->vredirip
.sin_port
) != 0) {
16839 memset(&p
->vredirip
, 0, sizeof(p
->vredirip
));
16842 if (codecs
&& (p
->redircodecs
!= codecs
)) {
16843 p
->redircodecs
= codecs
;
16846 if (changed
&& !ast_test_flag(&p
->flags
[0], SIP_GOTREFER
)) {
16847 if (chan
->_state
!= AST_STATE_UP
) { /* We are in early state */
16848 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
))
16849 append_history(p
, "ExtInv", "Initial invite sent with remote bridge proposal.");
16851 ast_log(LOG_DEBUG
, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p
->callid
, ast_inet_ntoa(rtp
? p
->redirip
.sin_addr
: p
->ourip
));
16852 } else if (!p
->pendinginvite
) { /* We are up, and have no outstanding invite */
16853 if (option_debug
> 2) {
16854 ast_log(LOG_DEBUG
, "Sending reinvite on SIP '%s' - It's audio soon redirected to IP %s\n", p
->callid
, ast_inet_ntoa(rtp
? p
->redirip
.sin_addr
: p
->ourip
));
16856 transmit_reinvite_with_sdp(p
);
16857 } else if (!ast_test_flag(&p
->flags
[0], SIP_PENDINGBYE
)) {
16858 if (option_debug
> 2) {
16859 ast_log(LOG_DEBUG
, "Deferring reinvite on SIP '%s' - It's audio will be redirected to IP %s\n", p
->callid
, ast_inet_ntoa(rtp
? p
->redirip
.sin_addr
: p
->ourip
));
16861 /* We have a pending Invite. Send re-invite when we're done with the invite */
16862 ast_set_flag(&p
->flags
[0], SIP_NEEDREINVITE
);
16865 /* Reset lastrtprx timer */
16866 p
->lastrtprx
= p
->lastrtptx
= time(NULL
);
16867 ast_mutex_unlock(&p
->lock
);
16871 static char *synopsis_dtmfmode
= "Change the dtmfmode for a SIP call";
16872 static char *descrip_dtmfmode
= "SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
16873 static char *app_dtmfmode
= "SIPDtmfMode";
16875 static char *app_sipaddheader
= "SIPAddHeader";
16876 static char *synopsis_sipaddheader
= "Add a SIP header to the outbound call";
16878 static char *descrip_sipaddheader
= ""
16879 " SIPAddHeader(Header: Content)\n"
16880 "Adds a header to a SIP call placed with DIAL.\n"
16881 "Remember to user the X-header if you are adding non-standard SIP\n"
16882 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
16883 "Adding the wrong headers may jeopardize the SIP dialog.\n"
16884 "Always returns 0\n";
16887 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
16888 static int sip_dtmfmode(struct ast_channel
*chan
, void *data
)
16893 mode
= (char *)data
;
16895 ast_log(LOG_WARNING
, "This application requires the argument: info, inband, rfc2833\n");
16898 ast_channel_lock(chan
);
16899 if (chan
->tech
!= &sip_tech
&& chan
->tech
!= &sip_tech_info
) {
16900 ast_log(LOG_WARNING
, "Call this application only on SIP incoming calls\n");
16901 ast_channel_unlock(chan
);
16904 p
= chan
->tech_pvt
;
16906 ast_channel_unlock(chan
);
16909 ast_mutex_lock(&p
->lock
);
16910 if (!strcasecmp(mode
,"info")) {
16911 ast_clear_flag(&p
->flags
[0], SIP_DTMF
);
16912 ast_set_flag(&p
->flags
[0], SIP_DTMF_INFO
);
16913 p
->jointnoncodeccapability
&= ~AST_RTP_DTMF
;
16914 } else if (!strcasecmp(mode
,"rfc2833")) {
16915 ast_clear_flag(&p
->flags
[0], SIP_DTMF
);
16916 ast_set_flag(&p
->flags
[0], SIP_DTMF_RFC2833
);
16917 p
->jointnoncodeccapability
|= AST_RTP_DTMF
;
16918 } else if (!strcasecmp(mode
,"inband")) {
16919 ast_clear_flag(&p
->flags
[0], SIP_DTMF
);
16920 ast_set_flag(&p
->flags
[0], SIP_DTMF_INBAND
);
16921 p
->jointnoncodeccapability
&= ~AST_RTP_DTMF
;
16923 ast_log(LOG_WARNING
, "I don't know about this dtmf mode: %s\n",mode
);
16925 ast_rtp_setdtmf(p
->rtp
, ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_RFC2833
);
16926 if (ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_INBAND
) {
16928 p
->vad
= ast_dsp_new();
16929 ast_dsp_set_features(p
->vad
, DSP_FEATURE_DTMF_DETECT
);
16933 ast_dsp_free(p
->vad
);
16937 ast_mutex_unlock(&p
->lock
);
16938 ast_channel_unlock(chan
);
16942 /*! \brief Add a SIP header to an outbound INVITE */
16943 static int sip_addheader(struct ast_channel
*chan
, void *data
)
16948 char *inbuf
= (char *) data
;
16950 if (ast_strlen_zero(inbuf
)) {
16951 ast_log(LOG_WARNING
, "This application requires the argument: Header\n");
16954 ast_channel_lock(chan
);
16956 /* Check for headers */
16957 while (!ok
&& no
<= 50) {
16959 snprintf(varbuf
, sizeof(varbuf
), "_SIPADDHEADER%.2d", no
);
16961 /* Compare without the leading underscore */
16962 if( (pbx_builtin_getvar_helper(chan
, (const char *) varbuf
+ 1) == (const char *) NULL
) )
16966 pbx_builtin_setvar_helper (chan
, varbuf
, inbuf
);
16968 ast_log(LOG_DEBUG
,"SIP Header added \"%s\" as %s\n", inbuf
, varbuf
);
16970 ast_log(LOG_WARNING
, "Too many SIP headers added, max 50\n");
16972 ast_channel_unlock(chan
);
16976 /*! \brief Transfer call before connect with a 302 redirect
16977 \note Called by the transfer() dialplan application through the sip_transfer()
16978 pbx interface function if the call is in ringing state
16979 \todo Fix this function so that we wait for reply to the REFER and
16980 react to errors, denials or other issues the other end might have.
16982 static int sip_sipredirect(struct sip_pvt
*p
, const char *dest
)
16985 char *extension
, *host
, *port
;
16988 cdest
= ast_strdupa(dest
);
16990 extension
= strsep(&cdest
, "@");
16991 host
= strsep(&cdest
, ":");
16992 port
= strsep(&cdest
, ":");
16993 if (ast_strlen_zero(extension
)) {
16994 ast_log(LOG_ERROR
, "Missing mandatory argument: extension\n");
16998 /* we'll issue the redirect message here */
17001 ast_copy_string(tmp
, get_header(&p
->initreq
, "To"), sizeof(tmp
));
17002 if (ast_strlen_zero(tmp
)) {
17003 ast_log(LOG_ERROR
, "Cannot retrieve the 'To' header from the original SIP request!\n");
17006 if ((localtmp
= strstr(tmp
, "sip:")) && (localtmp
= strchr(localtmp
, '@'))) {
17007 char lhost
[80], lport
[80];
17008 memset(lhost
, 0, sizeof(lhost
));
17009 memset(lport
, 0, sizeof(lport
));
17011 /* This is okey because lhost and lport are as big as tmp */
17012 sscanf(localtmp
, "%[^<>:; ]:%[^<>:; ]", lhost
, lport
);
17013 if (ast_strlen_zero(lhost
)) {
17014 ast_log(LOG_ERROR
, "Can't find the host address\n");
17017 host
= ast_strdupa(lhost
);
17018 if (!ast_strlen_zero(lport
)) {
17019 port
= ast_strdupa(lport
);
17024 ast_string_field_build(p
, our_contact
, "Transfer <sip:%s@%s%s%s>", extension
, host
, port
? ":" : "", port
? port
: "");
17025 transmit_response_reliable(p
, "302 Moved Temporarily", &p
->initreq
);
17027 sip_scheddestroy(p
, 32000); /* Make sure we stop send this reply. */
17033 /*! \brief Return SIP UA's codec (part of the RTP interface) */
17034 static int sip_get_codec(struct ast_channel
*chan
)
17036 struct sip_pvt
*p
= chan
->tech_pvt
;
17037 return p
->peercapability
;
17040 /*! \brief Send a poke to all known peers
17041 Space them out 100 ms apart
17042 XXX We might have a cool algorithm for this or use random - any suggestions?
17044 static void sip_poke_all_peers(void)
17048 if (!speerobjs
) /* No peers, just give up */
17051 ASTOBJ_CONTAINER_TRAVERSE(&peerl
, 1, do {
17052 ASTOBJ_WRLOCK(iterator
);
17053 if (iterator
->pokeexpire
> -1)
17054 ast_sched_del(sched
, iterator
->pokeexpire
);
17056 iterator
->pokeexpire
= ast_sched_add(sched
, ms
, sip_poke_peer_s
, iterator
);
17057 ASTOBJ_UNLOCK(iterator
);
17062 /*! \brief Send all known registrations */
17063 static void sip_send_all_registers(void)
17069 regspacing
= default_expiry
* 1000/regobjs
;
17070 if (regspacing
> 100)
17073 ASTOBJ_CONTAINER_TRAVERSE(®l
, 1, do {
17074 ASTOBJ_WRLOCK(iterator
);
17075 if (iterator
->expire
> -1)
17076 ast_sched_del(sched
, iterator
->expire
);
17078 iterator
->expire
= ast_sched_add(sched
, ms
, sip_reregister
, iterator
);
17079 ASTOBJ_UNLOCK(iterator
);
17084 /*! \brief Reload module */
17085 static int sip_do_reload(enum channelreloadreason reason
)
17087 if (option_debug
> 3)
17088 ast_log(LOG_DEBUG
, "--------------- SIP reload started\n");
17090 clear_realm_authentication(authl
);
17091 clear_sip_domains();
17094 /* First, destroy all outstanding registry calls */
17095 /* This is needed, since otherwise active registry entries will not be destroyed */
17096 ASTOBJ_CONTAINER_TRAVERSE(®l
, 1, do {
17097 ASTOBJ_RDLOCK(iterator
);
17098 if (iterator
->call
) {
17099 if (option_debug
> 2)
17100 ast_log(LOG_DEBUG
, "Destroying active SIP dialog for registry %s@%s\n", iterator
->username
, iterator
->hostname
);
17101 /* This will also remove references to the registry */
17102 sip_destroy(iterator
->call
);
17104 ASTOBJ_UNLOCK(iterator
);
17108 /* Then, actually destroy users and registry */
17109 ASTOBJ_CONTAINER_DESTROYALL(&userl
, sip_destroy_user
);
17110 if (option_debug
> 3)
17111 ast_log(LOG_DEBUG
, "--------------- Done destroying user list\n");
17112 ASTOBJ_CONTAINER_DESTROYALL(®l
, sip_registry_destroy
);
17113 if (option_debug
> 3)
17114 ast_log(LOG_DEBUG
, "--------------- Done destroying registry list\n");
17115 ASTOBJ_CONTAINER_MARKALL(&peerl
);
17116 reload_config(reason
);
17118 /* Prune peers who still are supposed to be deleted */
17119 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl
, sip_destroy_peer
);
17120 if (option_debug
> 3)
17121 ast_log(LOG_DEBUG
, "--------------- Done destroying pruned peers\n");
17123 /* Send qualify (OPTIONS) to all peers */
17124 sip_poke_all_peers();
17126 /* Register with all services */
17127 sip_send_all_registers();
17129 if (option_debug
> 3)
17130 ast_log(LOG_DEBUG
, "--------------- SIP reload done\n");
17135 /*! \brief Force reload of module from cli */
17136 static int sip_reload(int fd
, int argc
, char *argv
[])
17138 ast_mutex_lock(&sip_reload_lock
);
17140 ast_verbose("Previous SIP reload not yet done\n");
17142 sip_reloading
= TRUE
;
17144 sip_reloadreason
= CHANNEL_CLI_RELOAD
;
17146 sip_reloadreason
= CHANNEL_MODULE_RELOAD
;
17148 ast_mutex_unlock(&sip_reload_lock
);
17154 /*! \brief Part of Asterisk module interface */
17155 static int reload(void)
17157 return sip_reload(0, 0, NULL
);
17160 static struct ast_cli_entry cli_sip_debug_deprecated
=
17161 { { "sip", "debug", NULL
},
17162 sip_do_debug_deprecated
, "Enable SIP debugging",
17165 static struct ast_cli_entry cli_sip_no_debug_deprecated
=
17166 { { "sip", "no", "debug", NULL
},
17167 sip_no_debug_deprecated
, "Disable SIP debugging",
17170 static struct ast_cli_entry cli_sip
[] = {
17171 { { "sip", "show", "channels", NULL
},
17172 sip_show_channels
, "List active SIP channels",
17173 show_channels_usage
},
17175 { { "sip", "show", "domains", NULL
},
17176 sip_show_domains
, "List our local SIP domains.",
17177 show_domains_usage
},
17179 { { "sip", "show", "inuse", NULL
},
17180 sip_show_inuse
, "List all inuse/limits",
17181 show_inuse_usage
},
17183 { { "sip", "show", "objects", NULL
},
17184 sip_show_objects
, "List all SIP object allocations",
17185 show_objects_usage
},
17187 { { "sip", "show", "peers", NULL
},
17188 sip_show_peers
, "List defined SIP peers",
17189 show_peers_usage
},
17191 { { "sip", "show", "registry", NULL
},
17192 sip_show_registry
, "List SIP registration status",
17195 { { "sip", "show", "settings", NULL
},
17196 sip_show_settings
, "Show SIP global settings",
17197 show_settings_usage
},
17199 { { "sip", "show", "subscriptions", NULL
},
17200 sip_show_subscriptions
, "List active SIP subscriptions",
17201 show_subscriptions_usage
},
17203 { { "sip", "show", "users", NULL
},
17204 sip_show_users
, "List defined SIP users",
17205 show_users_usage
},
17207 { { "sip", "notify", NULL
},
17208 sip_notify
, "Send a notify packet to a SIP peer",
17209 notify_usage
, complete_sipnotify
},
17211 { { "sip", "show", "channel", NULL
},
17212 sip_show_channel
, "Show detailed SIP channel info",
17213 show_channel_usage
, complete_sipch
},
17215 { { "sip", "show", "history", NULL
},
17216 sip_show_history
, "Show SIP dialog history",
17217 show_history_usage
, complete_sipch
},
17219 { { "sip", "show", "peer", NULL
},
17220 sip_show_peer
, "Show details on specific SIP peer",
17221 show_peer_usage
, complete_sip_show_peer
},
17223 { { "sip", "show", "user", NULL
},
17224 sip_show_user
, "Show details on specific SIP user",
17225 show_user_usage
, complete_sip_show_user
},
17227 { { "sip", "prune", "realtime", NULL
},
17228 sip_prune_realtime
, "Prune cached Realtime object(s)",
17229 prune_realtime_usage
},
17231 { { "sip", "prune", "realtime", "peer", NULL
},
17232 sip_prune_realtime
, "Prune cached Realtime peer(s)",
17233 prune_realtime_usage
, complete_sip_prune_realtime_peer
},
17235 { { "sip", "prune", "realtime", "user", NULL
},
17236 sip_prune_realtime
, "Prune cached Realtime user(s)",
17237 prune_realtime_usage
, complete_sip_prune_realtime_user
},
17239 { { "sip", "set", "debug", NULL
},
17240 sip_do_debug
, "Enable SIP debugging",
17241 debug_usage
, NULL
, &cli_sip_debug_deprecated
},
17243 { { "sip", "set", "debug", "ip", NULL
},
17244 sip_do_debug
, "Enable SIP debugging on IP",
17247 { { "sip", "set", "debug", "peer", NULL
},
17248 sip_do_debug
, "Enable SIP debugging on Peername",
17249 debug_usage
, complete_sip_debug_peer
},
17251 { { "sip", "set", "debug", "off", NULL
},
17252 sip_no_debug
, "Disable SIP debugging",
17253 no_debug_usage
, NULL
, &cli_sip_no_debug_deprecated
},
17255 { { "sip", "history", NULL
},
17256 sip_do_history
, "Enable SIP history",
17259 { { "sip", "history", "off", NULL
},
17260 sip_no_history
, "Disable SIP history",
17261 no_history_usage
},
17263 { { "sip", "reload", NULL
},
17264 sip_reload
, "Reload SIP configuration",
17265 sip_reload_usage
},
17268 /*! \brief PBX load module - initialization */
17269 static int load_module(void)
17271 ASTOBJ_CONTAINER_INIT(&userl
); /* User object list */
17272 ASTOBJ_CONTAINER_INIT(&peerl
); /* Peer object list */
17273 ASTOBJ_CONTAINER_INIT(®l
); /* Registry object list */
17275 if (!(sched
= sched_context_create())) {
17276 ast_log(LOG_ERROR
, "Unable to create scheduler context\n");
17277 return AST_MODULE_LOAD_FAILURE
;
17280 if (!(io
= io_context_create())) {
17281 ast_log(LOG_ERROR
, "Unable to create I/O context\n");
17282 sched_context_destroy(sched
);
17283 return AST_MODULE_LOAD_FAILURE
;
17286 sip_reloadreason
= CHANNEL_MODULE_LOAD
;
17288 if(reload_config(sip_reloadreason
)) /* Load the configuration from sip.conf */
17289 return AST_MODULE_LOAD_DECLINE
;
17291 /* Make sure we can register our sip channel type */
17292 if (ast_channel_register(&sip_tech
)) {
17293 ast_log(LOG_ERROR
, "Unable to register channel type 'SIP'\n");
17294 io_context_destroy(io
);
17295 sched_context_destroy(sched
);
17296 return AST_MODULE_LOAD_FAILURE
;
17299 /* Register all CLI functions for SIP */
17300 ast_cli_register_multiple(cli_sip
, sizeof(cli_sip
)/ sizeof(struct ast_cli_entry
));
17302 /* Tell the RTP subdriver that we're here */
17303 ast_rtp_proto_register(&sip_rtp
);
17305 /* Tell the UDPTL subdriver that we're here */
17306 ast_udptl_proto_register(&sip_udptl
);
17308 /* Register dialplan applications */
17309 ast_register_application(app_dtmfmode
, sip_dtmfmode
, synopsis_dtmfmode
, descrip_dtmfmode
);
17310 ast_register_application(app_sipaddheader
, sip_addheader
, synopsis_sipaddheader
, descrip_sipaddheader
);
17312 /* Register dialplan functions */
17313 ast_custom_function_register(&sip_header_function
);
17314 ast_custom_function_register(&sippeer_function
);
17315 ast_custom_function_register(&sipchaninfo_function
);
17316 ast_custom_function_register(&checksipdomain_function
);
17318 /* Register manager commands */
17319 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM
, manager_sip_show_peers
,
17320 "List SIP peers (text format)", mandescr_show_peers
);
17321 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM
, manager_sip_show_peer
,
17322 "Show SIP peer (text format)", mandescr_show_peer
);
17324 sip_poke_all_peers();
17325 sip_send_all_registers();
17327 /* And start the monitor for the first time */
17330 return AST_MODULE_LOAD_SUCCESS
;
17333 /*! \brief PBX unload module API */
17334 static int unload_module(void)
17336 struct sip_pvt
*p
, *pl
;
17338 /* First, take us out of the channel type list */
17339 ast_channel_unregister(&sip_tech
);
17341 /* Unregister dial plan functions */
17342 ast_custom_function_unregister(&sipchaninfo_function
);
17343 ast_custom_function_unregister(&sippeer_function
);
17344 ast_custom_function_unregister(&sip_header_function
);
17345 ast_custom_function_unregister(&checksipdomain_function
);
17347 /* Unregister dial plan applications */
17348 ast_unregister_application(app_dtmfmode
);
17349 ast_unregister_application(app_sipaddheader
);
17351 /* Unregister CLI commands */
17352 ast_cli_unregister_multiple(cli_sip
, sizeof(cli_sip
) / sizeof(struct ast_cli_entry
));
17354 /* Disconnect from the RTP subsystem */
17355 ast_rtp_proto_unregister(&sip_rtp
);
17357 /* Disconnect from UDPTL */
17358 ast_udptl_proto_unregister(&sip_udptl
);
17360 /* Unregister AMI actions */
17361 ast_manager_unregister("SIPpeers");
17362 ast_manager_unregister("SIPshowpeer");
17364 ast_mutex_lock(&iflock
);
17365 /* Hangup all interfaces if they have an owner */
17366 for (p
= iflist
; p
; p
= p
->next
) {
17368 ast_softhangup(p
->owner
, AST_SOFTHANGUP_APPUNLOAD
);
17370 ast_mutex_unlock(&iflock
);
17372 ast_mutex_lock(&monlock
);
17373 if (monitor_thread
&& (monitor_thread
!= AST_PTHREADT_STOP
)) {
17374 pthread_cancel(monitor_thread
);
17375 pthread_kill(monitor_thread
, SIGURG
);
17376 pthread_join(monitor_thread
, NULL
);
17378 monitor_thread
= AST_PTHREADT_STOP
;
17379 ast_mutex_unlock(&monlock
);
17381 ast_mutex_lock(&iflock
);
17382 /* Destroy all the interfaces and free their memory */
17387 __sip_destroy(pl
, TRUE
);
17390 ast_mutex_unlock(&iflock
);
17392 /* Free memory for local network address mask */
17393 ast_free_ha(localaddr
);
17395 ASTOBJ_CONTAINER_DESTROYALL(&userl
, sip_destroy_user
);
17396 ASTOBJ_CONTAINER_DESTROY(&userl
);
17397 ASTOBJ_CONTAINER_DESTROYALL(&peerl
, sip_destroy_peer
);
17398 ASTOBJ_CONTAINER_DESTROY(&peerl
);
17399 ASTOBJ_CONTAINER_DESTROYALL(®l
, sip_registry_destroy
);
17400 ASTOBJ_CONTAINER_DESTROY(®l
);
17402 clear_realm_authentication(authl
);
17403 clear_sip_domains();
17405 sched_context_destroy(sched
);
17410 AST_MODULE_INFO(ASTERISK_GPL_KEY
, AST_MODFLAG_DEFAULT
, "Session Initiation Protocol (SIP)",
17411 .load
= load_module
,
17412 .unload
= unload_module
,