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 XMIT_ERROR -2
159 #define VIDEO_CODEC_MASK 0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
160 #ifndef IPTOS_MINCOST
161 #define IPTOS_MINCOST 0x02
164 /* #define VOCAL_DATA_HACK */
166 #define DEFAULT_DEFAULT_EXPIRY 120
167 #define DEFAULT_MIN_EXPIRY 60
168 #define DEFAULT_MAX_EXPIRY 3600
169 #define DEFAULT_REGISTRATION_TIMEOUT 20
170 #define DEFAULT_MAX_FORWARDS "70"
172 /* guard limit must be larger than guard secs */
173 /* guard min must be < 1000, and should be >= 250 */
174 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
175 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
177 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
178 GUARD_PCT turns out to be lower than this, it
179 will use this time instead.
180 This is in milliseconds. */
181 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
182 below EXPIRY_GUARD_LIMIT */
183 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
185 static int min_expiry
= DEFAULT_MIN_EXPIRY
; /*!< Minimum accepted registration time */
186 static int max_expiry
= DEFAULT_MAX_EXPIRY
; /*!< Maximum accepted registration time */
187 static int default_expiry
= DEFAULT_DEFAULT_EXPIRY
;
188 static int expiry
= DEFAULT_EXPIRY
;
191 #define MAX(a,b) ((a) > (b) ? (a) : (b))
194 #define CALLERID_UNKNOWN "Unknown"
196 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
197 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
198 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
200 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
201 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
202 #define SIP_TRANS_TIMEOUT 32000 /*!< SIP request timeout (rfc 3261) 64*T1
203 \todo Use known T1 for timeout (peerpoke)
205 #define DEFAULT_TRANS_TIMEOUT -1 /* Use default SIP transaction timeout */
206 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
208 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
209 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
210 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
212 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
214 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
215 static struct ast_jb_conf default_jbconf
=
219 .resync_threshold
= -1,
222 static struct ast_jb_conf global_jbconf
;
224 static const char config
[] = "sip.conf";
225 static const char notify_config
[] = "sip_notify.conf";
230 /*! \brief Authorization scheme for call transfers
231 \note Not a bitfield flag, since there are plans for other modes,
232 like "only allow transfers for authenticated devices" */
234 TRANSFER_OPENFORALL
, /*!< Allow all SIP transfers */
235 TRANSFER_CLOSED
, /*!< Allow no SIP transfers */
244 /*! \brief States for the INVITE transaction, not the dialog
245 \note this is for the INVITE that sets up the dialog
248 INV_NONE
= 0, /*!< No state at all, maybe not an INVITE dialog */
249 INV_CALLING
= 1, /*!< Invite sent, no answer */
250 INV_PROCEEDING
= 2, /*!< We got/sent 1xx message */
251 INV_EARLY_MEDIA
= 3, /*!< We got 18x message with to-tag back */
252 INV_COMPLETED
= 4, /*!< Got final response with error. Wait for ACK, then CONFIRMED */
253 INV_CONFIRMED
= 5, /*!< Confirmed response - we've got an ack (Incoming calls only) */
254 INV_TERMINATED
= 6, /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done
255 The only way out of this is a BYE from one side */
256 INV_CANCELLED
= 7, /*!< Transaction cancelled by client or server in non-terminated state */
259 /* Do _NOT_ make any changes to this enum, or the array following it;
260 if you think you are doing the right thing, you are probably
261 not doing the right thing. If you think there are changes
262 needed, get someone else to review them first _before_
263 submitting a patch. If these two lists do not match properly
264 bad things will happen.
268 XMIT_CRITICAL
= 2, /*!< Transmit critical SIP message reliably, with re-transmits.
269 If it fails, it's critical and will cause a teardown of the session */
270 XMIT_RELIABLE
= 1, /*!< Transmit SIP message reliably, with re-transmits */
271 XMIT_UNRELIABLE
= 0, /*!< Transmit SIP message without bothering with re-transmits */
274 enum parse_register_result
{
275 PARSE_REGISTER_FAILED
,
276 PARSE_REGISTER_UPDATE
,
277 PARSE_REGISTER_QUERY
,
280 enum subscriptiontype
{
289 static const struct cfsubscription_types
{
290 enum subscriptiontype type
;
291 const char * const event
;
292 const char * const mediatype
;
293 const char * const text
;
294 } subscription_types
[] = {
295 { NONE
, "-", "unknown", "unknown" },
296 /* RFC 4235: SIP Dialog event package */
297 { DIALOG_INFO_XML
, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
298 { CPIM_PIDF_XML
, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
299 { PIDF_XML
, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
300 { XPIDF_XML
, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
301 { MWI_NOTIFICATION
, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
304 /*! \brief SIP Request methods known by Asterisk */
306 SIP_UNKNOWN
, /* Unknown response */
307 SIP_RESPONSE
, /* Not request, response to outbound request */
313 SIP_PRACK
, /* Not supported at all */
318 SIP_UPDATE
, /* We can send UPDATE; but not accept it */
321 SIP_PUBLISH
, /* Not supported at all */
322 SIP_PING
, /* Not supported at all, no standard but still implemented out there */
325 /*! \brief Authentication types - proxy or www authentication
326 \note Endpoints, like Asterisk, should always use WWW authentication to
327 allow multiple authentications in the same call - to the proxy and
335 /*! \brief Authentication result from check_auth* functions */
336 enum check_auth_result
{
338 AUTH_CHALLENGE_SENT
= 1,
339 AUTH_SECRET_FAILED
= -1,
340 AUTH_USERNAME_MISMATCH
= -2,
343 AUTH_UNKNOWN_DOMAIN
= -5,
344 AUTH_PEER_NOT_DYNAMIC
= -6,
345 AUTH_ACL_FAILED
= -7,
348 /*! \brief States for outbound registrations (with register= lines in sip.conf */
349 enum sipregistrystate
{
350 REG_STATE_UNREGISTERED
= 0, /*!< We are not registred */
351 REG_STATE_REGSENT
, /*!< Registration request sent */
352 REG_STATE_AUTHSENT
, /*!< We have tried to authenticate */
353 REG_STATE_REGISTERED
, /*!< Registred and done */
354 REG_STATE_REJECTED
, /*!< Registration rejected */
355 REG_STATE_TIMEOUT
, /*!< Registration timed out */
356 REG_STATE_NOAUTH
, /*!< We have no accepted credentials */
357 REG_STATE_FAILED
, /*!< Registration failed after several tries */
360 #define CAN_NOT_CREATE_DIALOG 0
361 #define CAN_CREATE_DIALOG 1
362 #define CAN_CREATE_DIALOG_UNSUPPORTED_METHOD 2
364 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
365 static const struct cfsip_methods
{
367 int need_rtp
; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
371 { SIP_UNKNOWN
, RTP
, "-UNKNOWN-", CAN_CREATE_DIALOG
},
372 { SIP_RESPONSE
, NO_RTP
, "SIP/2.0", CAN_NOT_CREATE_DIALOG
},
373 { SIP_REGISTER
, NO_RTP
, "REGISTER", CAN_CREATE_DIALOG
},
374 { SIP_OPTIONS
, NO_RTP
, "OPTIONS", CAN_CREATE_DIALOG
},
375 { SIP_NOTIFY
, NO_RTP
, "NOTIFY", CAN_CREATE_DIALOG
},
376 { SIP_INVITE
, RTP
, "INVITE", CAN_CREATE_DIALOG
},
377 { SIP_ACK
, NO_RTP
, "ACK", CAN_NOT_CREATE_DIALOG
},
378 { SIP_PRACK
, NO_RTP
, "PRACK", CAN_NOT_CREATE_DIALOG
},
379 { SIP_BYE
, NO_RTP
, "BYE", CAN_NOT_CREATE_DIALOG
},
380 { SIP_REFER
, NO_RTP
, "REFER", CAN_CREATE_DIALOG
},
381 { SIP_SUBSCRIBE
, NO_RTP
, "SUBSCRIBE", CAN_CREATE_DIALOG
},
382 { SIP_MESSAGE
, NO_RTP
, "MESSAGE", CAN_CREATE_DIALOG
},
383 { SIP_UPDATE
, NO_RTP
, "UPDATE", CAN_NOT_CREATE_DIALOG
},
384 { SIP_INFO
, NO_RTP
, "INFO", CAN_NOT_CREATE_DIALOG
},
385 { SIP_CANCEL
, NO_RTP
, "CANCEL", CAN_NOT_CREATE_DIALOG
},
386 { SIP_PUBLISH
, NO_RTP
, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD
},
387 { SIP_PING
, NO_RTP
, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD
}
390 /*! Define SIP option tags, used in Require: and Supported: headers
391 We need to be aware of these properties in the phones to use
392 the replace: header. We should not do that without knowing
393 that the other end supports it...
394 This is nothing we can configure, we learn by the dialog
395 Supported: header on the REGISTER (peer) or the INVITE
397 We are not using many of these today, but will in the future.
398 This is documented in RFC 3261
401 #define NOT_SUPPORTED 0
403 #define SIP_OPT_REPLACES (1 << 0)
404 #define SIP_OPT_100REL (1 << 1)
405 #define SIP_OPT_TIMER (1 << 2)
406 #define SIP_OPT_EARLY_SESSION (1 << 3)
407 #define SIP_OPT_JOIN (1 << 4)
408 #define SIP_OPT_PATH (1 << 5)
409 #define SIP_OPT_PREF (1 << 6)
410 #define SIP_OPT_PRECONDITION (1 << 7)
411 #define SIP_OPT_PRIVACY (1 << 8)
412 #define SIP_OPT_SDP_ANAT (1 << 9)
413 #define SIP_OPT_SEC_AGREE (1 << 10)
414 #define SIP_OPT_EVENTLIST (1 << 11)
415 #define SIP_OPT_GRUU (1 << 12)
416 #define SIP_OPT_TARGET_DIALOG (1 << 13)
417 #define SIP_OPT_NOREFERSUB (1 << 14)
418 #define SIP_OPT_HISTINFO (1 << 15)
419 #define SIP_OPT_RESPRIORITY (1 << 16)
421 /*! \brief List of well-known SIP options. If we get this in a require,
422 we should check the list and answer accordingly. */
423 static const struct cfsip_options
{
424 int id
; /*!< Bitmap ID */
425 int supported
; /*!< Supported by Asterisk ? */
426 char * const text
; /*!< Text id, as in standard */
427 } sip_options
[] = { /* XXX used in 3 places */
428 /* RFC3891: Replaces: header for transfer */
429 { SIP_OPT_REPLACES
, SUPPORTED
, "replaces" },
430 /* One version of Polycom firmware has the wrong label */
431 { SIP_OPT_REPLACES
, SUPPORTED
, "replace" },
432 /* RFC3262: PRACK 100% reliability */
433 { SIP_OPT_100REL
, NOT_SUPPORTED
, "100rel" },
434 /* RFC4028: SIP Session Timers */
435 { SIP_OPT_TIMER
, NOT_SUPPORTED
, "timer" },
436 /* RFC3959: SIP Early session support */
437 { SIP_OPT_EARLY_SESSION
, NOT_SUPPORTED
, "early-session" },
438 /* RFC3911: SIP Join header support */
439 { SIP_OPT_JOIN
, NOT_SUPPORTED
, "join" },
440 /* RFC3327: Path support */
441 { SIP_OPT_PATH
, NOT_SUPPORTED
, "path" },
442 /* RFC3840: Callee preferences */
443 { SIP_OPT_PREF
, NOT_SUPPORTED
, "pref" },
444 /* RFC3312: Precondition support */
445 { SIP_OPT_PRECONDITION
, NOT_SUPPORTED
, "precondition" },
446 /* RFC3323: Privacy with proxies*/
447 { SIP_OPT_PRIVACY
, NOT_SUPPORTED
, "privacy" },
448 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
449 { SIP_OPT_SDP_ANAT
, NOT_SUPPORTED
, "sdp-anat" },
450 /* RFC3329: Security agreement mechanism */
451 { SIP_OPT_SEC_AGREE
, NOT_SUPPORTED
, "sec_agree" },
452 /* SIMPLE events: RFC4662 */
453 { SIP_OPT_EVENTLIST
, NOT_SUPPORTED
, "eventlist" },
454 /* GRUU: Globally Routable User Agent URI's */
455 { SIP_OPT_GRUU
, NOT_SUPPORTED
, "gruu" },
456 /* RFC4538: Target-dialog */
457 { SIP_OPT_TARGET_DIALOG
,NOT_SUPPORTED
, "tdialog" },
458 /* Disable the REFER subscription, RFC 4488 */
459 { SIP_OPT_NOREFERSUB
, NOT_SUPPORTED
, "norefersub" },
460 /* ietf-sip-history-info-06.txt */
461 { SIP_OPT_HISTINFO
, NOT_SUPPORTED
, "histinfo" },
462 /* ietf-sip-resource-priority-10.txt */
463 { SIP_OPT_RESPRIORITY
, NOT_SUPPORTED
, "resource-priority" },
467 /*! \brief SIP Methods we support */
468 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
470 /*! \brief SIP Extensions we support */
471 #define SUPPORTED_EXTENSIONS "replaces"
473 /*! \brief Standard SIP port from RFC 3261. DO NOT CHANGE THIS */
474 #define STANDARD_SIP_PORT 5060
475 /* Note: in many SIP headers, absence of a port number implies port 5060,
476 * and this is why we cannot change the above constant.
477 * There is a limited number of places in asterisk where we could,
478 * in principle, use a different "default" port number, but
479 * we do not support this feature at the moment.
482 /* Default values, set and reset in reload_config before reading configuration */
483 /* These are default values in the source. There are other recommended values in the
484 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
485 yet encouraging new behaviour on new installations
487 #define DEFAULT_CONTEXT "default"
488 #define DEFAULT_MOHINTERPRET "default"
489 #define DEFAULT_MOHSUGGEST ""
490 #define DEFAULT_VMEXTEN "asterisk"
491 #define DEFAULT_CALLERID "asterisk"
492 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
493 #define DEFAULT_MWITIME 10
494 #define DEFAULT_ALLOWGUEST TRUE
495 #define DEFAULT_SRVLOOKUP FALSE /*!< Recommended setting is ON */
496 #define DEFAULT_COMPACTHEADERS FALSE
497 #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. */
498 #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. */
499 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
500 #define DEFAULT_ALLOW_EXT_DOM TRUE
501 #define DEFAULT_REALM "asterisk"
502 #define DEFAULT_NOTIFYRINGING TRUE
503 #define DEFAULT_PEDANTIC FALSE
504 #define DEFAULT_AUTOCREATEPEER FALSE
505 #define DEFAULT_QUALIFY FALSE
506 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
507 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
508 #ifndef DEFAULT_USERAGENT
509 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
513 /* Default setttings are used as a channel setting and as a default when
514 configuring devices */
515 static char default_context
[AST_MAX_CONTEXT
];
516 static char default_subscribecontext
[AST_MAX_CONTEXT
];
517 static char default_language
[MAX_LANGUAGE
];
518 static char default_callerid
[AST_MAX_EXTENSION
];
519 static char default_fromdomain
[AST_MAX_EXTENSION
];
520 static char default_notifymime
[AST_MAX_EXTENSION
];
521 static int default_qualify
; /*!< Default Qualify= setting */
522 static char default_vmexten
[AST_MAX_EXTENSION
];
523 static char default_mohinterpret
[MAX_MUSICCLASS
]; /*!< Global setting for moh class to use when put on hold */
524 static char default_mohsuggest
[MAX_MUSICCLASS
]; /*!< Global setting for moh class to suggest when putting
525 * a bridged channel on hold */
526 static int default_maxcallbitrate
; /*!< Maximum bitrate for call */
527 static struct ast_codec_pref default_prefs
; /*!< Default codec prefs */
529 /* Global settings only apply to the channel */
530 static int global_directrtpsetup
; /*!< Enable support for Direct RTP setup (no re-invites) */
531 static int global_limitonpeers
; /*!< Match call limit on peers only */
532 static int global_rtautoclear
;
533 static int global_notifyringing
; /*!< Send notifications on ringing */
534 static int global_notifyhold
; /*!< Send notifications on hold */
535 static int global_alwaysauthreject
; /*!< Send 401 Unauthorized for all failing requests */
536 static int srvlookup
; /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
537 static int pedanticsipchecking
; /*!< Extra checking ? Default off */
538 static int autocreatepeer
; /*!< Auto creation of peers at registration? Default off. */
539 static int global_relaxdtmf
; /*!< Relax DTMF */
540 static int global_rtptimeout
; /*!< Time out call if no RTP */
541 static int global_rtpholdtimeout
;
542 static int global_rtpkeepalive
; /*!< Send RTP keepalives */
543 static int global_reg_timeout
;
544 static int global_regattempts_max
; /*!< Registration attempts before giving up */
545 static int global_allowguest
; /*!< allow unauthenticated users/peers to connect? */
546 static int global_allowsubscribe
; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
547 the global setting is in globals_flags[1] */
548 static int global_mwitime
; /*!< Time between MWI checks for peers */
549 static unsigned int global_tos_sip
; /*!< IP type of service for SIP packets */
550 static unsigned int global_tos_audio
; /*!< IP type of service for audio RTP packets */
551 static unsigned int global_tos_video
; /*!< IP type of service for video RTP packets */
552 static int compactheaders
; /*!< send compact sip headers */
553 static int recordhistory
; /*!< Record SIP history. Off by default */
554 static int dumphistory
; /*!< Dump history to verbose before destroying SIP dialog */
555 static char global_realm
[MAXHOSTNAMELEN
]; /*!< Default realm */
556 static char global_regcontext
[AST_MAX_CONTEXT
]; /*!< Context for auto-extensions */
557 static char global_useragent
[AST_MAX_EXTENSION
]; /*!< Useragent for the SIP channel */
558 static int allow_external_domains
; /*!< Accept calls to external SIP domains? */
559 static int global_callevents
; /*!< Whether we send manager events or not */
560 static int global_t1min
; /*!< T1 roundtrip time minimum */
561 static int global_autoframing
; /*!< Turn autoframing on or off. */
562 static enum transfermodes global_allowtransfer
; /*!< SIP Refer restriction scheme */
564 static int global_matchexterniplocally
; /*!< Match externip/externhost setting against localnet setting */
566 /*! \brief Codecs that we support by default: */
567 static int global_capability
= AST_FORMAT_ULAW
| AST_FORMAT_ALAW
| AST_FORMAT_GSM
| AST_FORMAT_H263
;
569 /* Object counters */
570 static int suserobjs
= 0; /*!< Static users */
571 static int ruserobjs
= 0; /*!< Realtime users */
572 static int speerobjs
= 0; /*!< Statis peers */
573 static int rpeerobjs
= 0; /*!< Realtime peers */
574 static int apeerobjs
= 0; /*!< Autocreated peer objects */
575 static int regobjs
= 0; /*!< Registry objects */
577 static struct ast_flags global_flags
[2] = {{0}}; /*!< global SIP_ flags */
579 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
580 AST_MUTEX_DEFINE_STATIC(iflock
);
582 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
583 when it's doing something critical. */
584 AST_MUTEX_DEFINE_STATIC(netlock
);
586 AST_MUTEX_DEFINE_STATIC(monlock
);
588 AST_MUTEX_DEFINE_STATIC(sip_reload_lock
);
590 /*! \brief This is the thread for the monitor which checks for input on the channels
591 which are not currently in use. */
592 static pthread_t monitor_thread
= AST_PTHREADT_NULL
;
594 static int sip_reloading
= FALSE
; /*!< Flag for avoiding multiple reloads at the same time */
595 static enum channelreloadreason sip_reloadreason
; /*!< Reason for last reload/load of configuration */
597 static struct sched_context
*sched
; /*!< The scheduling context */
598 static struct io_context
*io
; /*!< The IO context */
599 static int *sipsock_read_id
; /*!< ID of IO entry for sipsock FD */
601 #define DEC_CALL_LIMIT 0
602 #define INC_CALL_LIMIT 1
603 #define DEC_CALL_RINGING 2
604 #define INC_CALL_RINGING 3
606 /*! \brief sip_request: The data grabbed from the UDP socket */
608 char *rlPart1
; /*!< SIP Method Name or "SIP/2.0" protocol version */
609 char *rlPart2
; /*!< The Request URI or Response Status */
610 int len
; /*!< Length */
611 int headers
; /*!< # of SIP Headers */
612 int method
; /*!< Method of this request */
613 int lines
; /*!< Body Content */
614 unsigned int flags
; /*!< SIP_PKT Flags for this packet */
615 char *header
[SIP_MAX_HEADERS
];
616 char *line
[SIP_MAX_LINES
];
617 char data
[SIP_MAX_PACKET
];
618 unsigned int sdp_start
; /*!< the line number where the SDP begins */
619 unsigned int sdp_end
; /*!< the line number where the SDP ends */
623 * A sip packet is stored into the data[] buffer, with the header followed
624 * by an empty line and the body of the message.
625 * On outgoing packets, data is accumulated in data[] with len reflecting
626 * the next available byte, headers and lines count the number of lines
627 * in both parts. There are no '\0' in data[0..len-1].
629 * On received packet, the input read from the socket is copied into data[],
630 * len is set and the string is NUL-terminated. Then a parser fills up
631 * the other fields -header[] and line[] to point to the lines of the
632 * message, rlPart1 and rlPart2 parse the first lnie as below:
634 * Requests have in the first line METHOD URI SIP/2.0
635 * rlPart1 = method; rlPart2 = uri;
636 * Responses have in the first line SIP/2.0 code description
637 * rlPart1 = SIP/2.0; rlPart2 = code + description;
641 /*! \brief structure used in transfers */
643 struct ast_channel
*chan1
; /*!< First channel involved */
644 struct ast_channel
*chan2
; /*!< Second channel involved */
645 struct sip_request req
; /*!< Request that caused the transfer (REFER) */
646 int seqno
; /*!< Sequence number */
651 /*! \brief Parameters to the transmit_invite function */
652 struct sip_invite_param
{
653 const char *distinctive_ring
; /*!< Distinctive ring header */
654 int addsipheaders
; /*!< Add extra SIP headers */
655 const char *uri_options
; /*!< URI options to add to the URI */
656 const char *vxml_url
; /*!< VXML url for Cisco phones */
657 char *auth
; /*!< Authentication */
658 char *authheader
; /*!< Auth header */
659 enum sip_auth_type auth_type
; /*!< Authentication type */
660 const char *replaces
; /*!< Replaces header for call transfers */
661 int transfer
; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
664 /*! \brief Structure to save routing information for a SIP session */
666 struct sip_route
*next
;
670 /*! \brief Modes for SIP domain handling in the PBX */
672 SIP_DOMAIN_AUTO
, /*!< This domain is auto-configured */
673 SIP_DOMAIN_CONFIG
, /*!< This domain is from configuration */
676 /*! \brief Domain data structure.
677 \note In the future, we will connect this to a configuration tree specific
681 char domain
[MAXHOSTNAMELEN
]; /*!< SIP domain we are responsible for */
682 char context
[AST_MAX_EXTENSION
]; /*!< Incoming context for this domain */
683 enum domain_mode mode
; /*!< How did we find this domain? */
684 AST_LIST_ENTRY(domain
) list
; /*!< List mechanics */
687 static AST_LIST_HEAD_STATIC(domain_list
, domain
); /*!< The SIP domain list */
690 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
692 AST_LIST_ENTRY(sip_history
) list
;
693 char event
[0]; /* actually more, depending on needs */
696 AST_LIST_HEAD_NOLOCK(sip_history_head
, sip_history
); /*!< history list, entry in sip_pvt */
698 /*! \brief sip_auth: Credentials for authentication to other SIP services */
700 char realm
[AST_MAX_EXTENSION
]; /*!< Realm in which these credentials are valid */
701 char username
[256]; /*!< Username */
702 char secret
[256]; /*!< Secret */
703 char md5secret
[256]; /*!< MD5Secret */
704 struct sip_auth
*next
; /*!< Next auth structure in list */
707 /*--- Various flags for the flags field in the pvt structure */
708 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
709 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed by the monitor thread */
710 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
711 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
712 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
713 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
714 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
715 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
716 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
717 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
718 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
719 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
720 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
721 #define SIP_OUTGOING (1 << 13) /*!< Direction of the last transaction in this dialog */
722 #define SIP_FREE_BIT (1 << 14) /*!< ---- */
723 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 15) /*!< Do not hangup at first ast_hangup */
724 #define SIP_DTMF (3 << 16) /*!< DTMF Support: four settings, uses two bits */
725 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DTMF Support: RTP DTMF - "rfc2833" */
726 #define SIP_DTMF_INBAND (1 << 16) /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
727 #define SIP_DTMF_INFO (2 << 16) /*!< DTMF Support: SIP Info messages - "info" */
728 #define SIP_DTMF_AUTO (3 << 16) /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
730 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
731 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
732 #define SIP_NAT_RFC3581 (1 << 18) /*!< NAT RFC3581 */
733 #define SIP_NAT_ROUTE (2 << 18) /*!< NAT Only ROUTE */
734 #define SIP_NAT_ALWAYS (3 << 18) /*!< NAT Both ROUTE and RFC3581 */
735 /* re-INVITE related settings */
736 #define SIP_REINVITE (7 << 20) /*!< three bits used */
737 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
738 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< allow media reinvite when new peer is behind NAT */
739 #define SIP_REINVITE_UPDATE (4 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
740 /* "insecure" settings */
741 #define SIP_INSECURE_PORT (1 << 23) /*!< don't require matching port for incoming requests */
742 #define SIP_INSECURE_INVITE (1 << 24) /*!< don't require authentication for incoming INVITEs */
743 /* Sending PROGRESS in-band settings */
744 #define SIP_PROG_INBAND (3 << 25) /*!< three settings, uses two bits */
745 #define SIP_PROG_INBAND_NEVER (0 << 25)
746 #define SIP_PROG_INBAND_NO (1 << 25)
747 #define SIP_PROG_INBAND_YES (2 << 25)
748 #define SIP_NO_HISTORY (1 << 27) /*!< Suppress recording request/response history */
749 #define SIP_CALL_LIMIT (1 << 28) /*!< Call limit enforced for this call */
750 #define SIP_SENDRPID (1 << 29) /*!< Remote Party-ID Support */
751 #define SIP_INC_COUNT (1 << 30) /*!< Did this connection increment the counter of in-use calls? */
752 #define SIP_G726_NONSTANDARD (1 << 31) /*!< Use non-standard packing for G726-32 data */
754 #define SIP_FLAGS_TO_COPY \
755 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
756 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
757 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
759 /*--- a new page of flags (for flags[1] */
761 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
762 #define SIP_PAGE2_RTUPDATE (1 << 1)
763 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
764 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
765 #define SIP_PAGE2_RTSAVE_SYSNAME (1 << 5)
766 /* Space for addition of other realtime flags in the future */
767 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 10)
768 #define SIP_PAGE2_DEBUG (3 << 11)
769 #define SIP_PAGE2_DEBUG_CONFIG (1 << 11)
770 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 12)
771 #define SIP_PAGE2_DYNAMIC (1 << 13) /*!< Dynamic Peers register with Asterisk */
772 #define SIP_PAGE2_SELFDESTRUCT (1 << 14) /*!< Automatic peers need to destruct themselves */
773 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15)
774 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< Allow subscriptions from this peer? */
775 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< Allow overlap dialing ? */
776 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< Only issue MWI notification if subscribed to */
777 #define SIP_PAGE2_INC_RINGING (1 << 19) /*!< Did this connection increment the counter of in-use calls? */
778 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< T38 Fax Passthrough Support */
779 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< 20: T38 Fax Passthrough Support */
780 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< 21: T38 Fax Passthrough Support (not implemented) */
781 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< 22: T38 Fax Passthrough Support (not implemented) */
782 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< Call states */
783 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23) /*!< 23: Active hold */
784 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23) /*!< 23: One directional hold */
785 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23) /*!< 23: Inactive hold */
786 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25) /*!< 25: ???? */
787 #define SIP_PAGE2_BUGGY_MWI (1 << 26) /*!< 26: Buggy CISCO MWI fix */
788 #define SIP_PAGE2_OUTGOING_CALL (1 << 27) /*!< 27: Is this an outgoing call? */
790 #define SIP_PAGE2_FLAGS_TO_COPY \
791 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
792 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI)
794 /* SIP packet flags */
795 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
796 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
797 #define SIP_PKT_IGNORE (1 << 2) /*!< This is a re-transmit, ignore it */
798 #define SIP_PKT_IGNORE_RESP (1 << 3) /*!< Resp ignore - ??? */
799 #define SIP_PKT_IGNORE_REQ (1 << 4) /*!< Req ignore - ??? */
801 /* T.38 set of flags */
802 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
803 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
804 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
805 /* Rate management */
806 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
807 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
808 /* UDP Error correction */
809 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
810 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
811 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
812 /* T38 Spec version */
813 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
814 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
815 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
816 /* Maximum Fax Rate */
817 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
818 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
819 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
820 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
821 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
822 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
824 /*!< This is default: NO MMR and JBIG trancoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
825 static int global_t38_capability
= T38FAX_VERSION_0
| T38FAX_RATE_2400
| T38FAX_RATE_4800
| T38FAX_RATE_7200
| T38FAX_RATE_9600
;
827 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
828 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
829 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
831 /*! \brief T38 States for a call */
833 T38_DISABLED
= 0, /*!< Not enabled */
834 T38_LOCAL_DIRECT
, /*!< Offered from local */
835 T38_LOCAL_REINVITE
, /*!< Offered from local - REINVITE */
836 T38_PEER_DIRECT
, /*!< Offered from peer */
837 T38_PEER_REINVITE
, /*!< Offered from peer - REINVITE */
838 T38_ENABLED
/*!< Negotiated (enabled) */
841 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
842 struct t38properties
{
843 struct ast_flags t38support
; /*!< Flag for udptl, rtp or tcp support for this session */
844 int capability
; /*!< Our T38 capability */
845 int peercapability
; /*!< Peers T38 capability */
846 int jointcapability
; /*!< Supported T38 capability at both ends */
847 enum t38state state
; /*!< T.38 state */
850 /*! \brief Parameters to know status of transfer */
852 REFER_IDLE
, /*!< No REFER is in progress */
853 REFER_SENT
, /*!< Sent REFER to transferee */
854 REFER_RECEIVED
, /*!< Received REFER from transferer */
855 REFER_CONFIRMED
, /*!< Refer confirmed with a 100 TRYING */
856 REFER_ACCEPTED
, /*!< Accepted by transferee */
857 REFER_RINGING
, /*!< Target Ringing */
858 REFER_200OK
, /*!< Answered by transfer target */
859 REFER_FAILED
, /*!< REFER declined - go on */
860 REFER_NOAUTH
/*!< We had no auth for REFER */
863 static const struct c_referstatusstring
{
864 enum referstatus status
;
866 } referstatusstrings
[] = {
867 { REFER_IDLE
, "<none>" },
868 { REFER_SENT
, "Request sent" },
869 { REFER_RECEIVED
, "Request received" },
870 { REFER_ACCEPTED
, "Accepted" },
871 { REFER_RINGING
, "Target ringing" },
872 { REFER_200OK
, "Done" },
873 { REFER_FAILED
, "Failed" },
874 { REFER_NOAUTH
, "Failed - auth failure" }
877 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed */
878 /* OEJ: Should be moved to string fields */
880 char refer_to
[AST_MAX_EXTENSION
]; /*!< Place to store REFER-TO extension */
881 char refer_to_domain
[AST_MAX_EXTENSION
]; /*!< Place to store REFER-TO domain */
882 char refer_to_urioption
[AST_MAX_EXTENSION
]; /*!< Place to store REFER-TO uri options */
883 char refer_to_context
[AST_MAX_EXTENSION
]; /*!< Place to store REFER-TO context */
884 char referred_by
[AST_MAX_EXTENSION
]; /*!< Place to store REFERRED-BY extension */
885 char referred_by_name
[AST_MAX_EXTENSION
]; /*!< Place to store REFERRED-BY extension */
886 char refer_contact
[AST_MAX_EXTENSION
]; /*!< Place to store Contact info from a REFER extension */
887 char replaces_callid
[BUFSIZ
]; /*!< Replace info: callid */
888 char replaces_callid_totag
[BUFSIZ
/2]; /*!< Replace info: to-tag */
889 char replaces_callid_fromtag
[BUFSIZ
/2]; /*!< Replace info: from-tag */
890 struct sip_pvt
*refer_call
; /*!< Call we are referring */
891 int attendedtransfer
; /*!< Attended or blind transfer? */
892 int localtransfer
; /*!< Transfer to local domain? */
893 enum referstatus status
; /*!< REFER status */
896 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
897 static struct sip_pvt
{
898 ast_mutex_t lock
; /*!< Dialog private lock */
899 int method
; /*!< SIP method that opened this dialog */
900 enum invitestates invitestate
; /*!< The state of the INVITE transaction only */
901 AST_DECLARE_STRING_FIELDS(
902 AST_STRING_FIELD(callid
); /*!< Global CallID */
903 AST_STRING_FIELD(randdata
); /*!< Random data */
904 AST_STRING_FIELD(accountcode
); /*!< Account code */
905 AST_STRING_FIELD(realm
); /*!< Authorization realm */
906 AST_STRING_FIELD(nonce
); /*!< Authorization nonce */
907 AST_STRING_FIELD(opaque
); /*!< Opaque nonsense */
908 AST_STRING_FIELD(qop
); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
909 AST_STRING_FIELD(domain
); /*!< Authorization domain */
910 AST_STRING_FIELD(from
); /*!< The From: header */
911 AST_STRING_FIELD(useragent
); /*!< User agent in SIP request */
912 AST_STRING_FIELD(exten
); /*!< Extension where to start */
913 AST_STRING_FIELD(context
); /*!< Context for this call */
914 AST_STRING_FIELD(subscribecontext
); /*!< Subscribecontext */
915 AST_STRING_FIELD(subscribeuri
); /*!< Subscribecontext */
916 AST_STRING_FIELD(fromdomain
); /*!< Domain to show in the from field */
917 AST_STRING_FIELD(fromuser
); /*!< User to show in the user field */
918 AST_STRING_FIELD(fromname
); /*!< Name to show in the user field */
919 AST_STRING_FIELD(tohost
); /*!< Host we should put in the "to" field */
920 AST_STRING_FIELD(language
); /*!< Default language for this call */
921 AST_STRING_FIELD(mohinterpret
); /*!< MOH class to use when put on hold */
922 AST_STRING_FIELD(mohsuggest
); /*!< MOH class to suggest when putting a peer on hold */
923 AST_STRING_FIELD(rdnis
); /*!< Referring DNIS */
924 AST_STRING_FIELD(theirtag
); /*!< Their tag */
925 AST_STRING_FIELD(username
); /*!< [user] name */
926 AST_STRING_FIELD(peername
); /*!< [peer] name, not set if [user] */
927 AST_STRING_FIELD(authname
); /*!< Who we use for authentication */
928 AST_STRING_FIELD(uri
); /*!< Original requested URI */
929 AST_STRING_FIELD(okcontacturi
); /*!< URI from the 200 OK on INVITE */
930 AST_STRING_FIELD(peersecret
); /*!< Password */
931 AST_STRING_FIELD(peermd5secret
);
932 AST_STRING_FIELD(cid_num
); /*!< Caller*ID number */
933 AST_STRING_FIELD(cid_name
); /*!< Caller*ID name */
934 AST_STRING_FIELD(via
); /*!< Via: header */
935 AST_STRING_FIELD(fullcontact
); /*!< The Contact: that the UA registers with us */
936 AST_STRING_FIELD(our_contact
); /*!< Our contact header */
937 AST_STRING_FIELD(rpid
); /*!< Our RPID header */
938 AST_STRING_FIELD(rpid_from
); /*!< Our RPID From header */
940 unsigned int ocseq
; /*!< Current outgoing seqno */
941 unsigned int icseq
; /*!< Current incoming seqno */
942 ast_group_t callgroup
; /*!< Call group */
943 ast_group_t pickupgroup
; /*!< Pickup group */
944 int lastinvite
; /*!< Last Cseq of invite */
945 struct ast_flags flags
[2]; /*!< SIP_ flags */
946 int timer_t1
; /*!< SIP timer T1, ms rtt */
947 unsigned int sipoptions
; /*!< Supported SIP options on the other end */
948 struct ast_codec_pref prefs
; /*!< codec prefs */
949 int capability
; /*!< Special capability (codec) */
950 int jointcapability
; /*!< Supported capability at both ends (codecs) */
951 int peercapability
; /*!< Supported peer capability */
952 int prefcodec
; /*!< Preferred codec (outbound only) */
953 int noncodeccapability
; /*!< DTMF RFC2833 telephony-event */
954 int jointnoncodeccapability
; /*!< Joint Non codec capability */
955 int redircodecs
; /*!< Redirect codecs */
956 int maxcallbitrate
; /*!< Maximum Call Bitrate for Video Calls */
957 struct t38properties t38
; /*!< T38 settings */
958 struct sockaddr_in udptlredirip
; /*!< Where our T.38 UDPTL should be going if not to us */
959 struct ast_udptl
*udptl
; /*!< T.38 UDPTL session */
960 int callingpres
; /*!< Calling presentation */
961 int authtries
; /*!< Times we've tried to authenticate */
962 int expiry
; /*!< How long we take to expire */
963 long branch
; /*!< The branch identifier of this session */
964 char tag
[11]; /*!< Our tag for this session */
965 int sessionid
; /*!< SDP Session ID */
966 int sessionversion
; /*!< SDP Session Version */
967 struct sockaddr_in sa
; /*!< Our peer */
968 struct sockaddr_in redirip
; /*!< Where our RTP should be going if not to us */
969 struct sockaddr_in vredirip
; /*!< Where our Video RTP should be going if not to us */
970 time_t lastrtprx
; /*!< Last RTP received */
971 time_t lastrtptx
; /*!< Last RTP sent */
972 int rtptimeout
; /*!< RTP timeout time */
973 struct sockaddr_in recv
; /*!< Received as */
974 struct in_addr ourip
; /*!< Our IP */
975 struct ast_channel
*owner
; /*!< Who owns us (if we have an owner) */
976 struct sip_route
*route
; /*!< Head of linked list of routing steps (fm Record-Route) */
977 int route_persistant
; /*!< Is this the "real" route? */
978 struct sip_auth
*peerauth
; /*!< Realm authentication */
979 int noncecount
; /*!< Nonce-count */
980 char lastmsg
[256]; /*!< Last Message sent/received */
981 int amaflags
; /*!< AMA Flags */
982 int pendinginvite
; /*!< Any pending invite ? (seqno of this) */
983 struct sip_request initreq
; /*!< Request that opened the latest transaction
984 within this SIP dialog */
986 int maxtime
; /*!< Max time for first response */
987 int initid
; /*!< Auto-congest ID if appropriate (scheduler) */
988 int autokillid
; /*!< Auto-kill ID (scheduler) */
989 enum transfermodes allowtransfer
; /*!< REFER: restriction scheme */
990 struct sip_refer
*refer
; /*!< REFER: SIP transfer data structure */
991 enum subscriptiontype subscribed
; /*!< SUBSCRIBE: Is this dialog a subscription? */
992 int stateid
; /*!< SUBSCRIBE: ID for devicestate subscriptions */
993 int laststate
; /*!< SUBSCRIBE: Last known extension state */
994 int dialogver
; /*!< SUBSCRIBE: Version for subscription dialog-info */
996 struct ast_dsp
*vad
; /*!< Voice Activation Detection dsp */
998 struct sip_peer
*relatedpeer
; /*!< If this dialog is related to a peer, which one
999 Used in peerpoke, mwi subscriptions */
1000 struct sip_registry
*registry
; /*!< If this is a REGISTER dialog, to which registry */
1001 struct ast_rtp
*rtp
; /*!< RTP Session */
1002 struct ast_rtp
*vrtp
; /*!< Video RTP session */
1003 struct sip_pkt
*packets
; /*!< Packets scheduled for re-transmission */
1004 struct sip_history_head
*history
; /*!< History of this SIP dialog */
1005 struct ast_variable
*chanvars
; /*!< Channel variables to set for inbound call */
1006 struct sip_pvt
*next
; /*!< Next dialog in chain */
1007 struct sip_invite_param
*options
; /*!< Options for INVITE */
1011 #define FLAG_RESPONSE (1 << 0)
1012 #define FLAG_FATAL (1 << 1)
1014 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */
1016 struct sip_pkt
*next
; /*!< Next packet in linked list */
1017 int retrans
; /*!< Retransmission number */
1018 int method
; /*!< SIP method for this packet */
1019 int seqno
; /*!< Sequence number */
1020 unsigned int flags
; /*!< non-zero if this is a response packet (e.g. 200 OK) */
1021 struct sip_pvt
*owner
; /*!< Owner AST call */
1022 int retransid
; /*!< Retransmission ID */
1023 int timer_a
; /*!< SIP timer A, retransmission timer */
1024 int timer_t1
; /*!< SIP Timer T1, estimated RTT or 500 ms */
1025 int packetlen
; /*!< Length of packet */
1029 /*! \brief Structure for SIP user data. User's place calls to us */
1031 /* Users who can access various contexts */
1032 ASTOBJ_COMPONENTS(struct sip_user
);
1033 char secret
[80]; /*!< Password */
1034 char md5secret
[80]; /*!< Password in md5 */
1035 char context
[AST_MAX_CONTEXT
]; /*!< Default context for incoming calls */
1036 char subscribecontext
[AST_MAX_CONTEXT
]; /* Default context for subscriptions */
1037 char cid_num
[80]; /*!< Caller ID num */
1038 char cid_name
[80]; /*!< Caller ID name */
1039 char accountcode
[AST_MAX_ACCOUNT_CODE
]; /* Account code */
1040 char language
[MAX_LANGUAGE
]; /*!< Default language for this user */
1041 char mohinterpret
[MAX_MUSICCLASS
];/*!< Music on Hold class */
1042 char mohsuggest
[MAX_MUSICCLASS
];/*!< Music on Hold class */
1043 char useragent
[256]; /*!< User agent in SIP request */
1044 struct ast_codec_pref prefs
; /*!< codec prefs */
1045 ast_group_t callgroup
; /*!< Call group */
1046 ast_group_t pickupgroup
; /*!< Pickup Group */
1047 unsigned int sipoptions
; /*!< Supported SIP options */
1048 struct ast_flags flags
[2]; /*!< SIP_ flags */
1049 int amaflags
; /*!< AMA flags for billing */
1050 int callingpres
; /*!< Calling id presentation */
1051 int capability
; /*!< Codec capability */
1052 int inUse
; /*!< Number of calls in use */
1053 int call_limit
; /*!< Limit of concurrent calls */
1054 enum transfermodes allowtransfer
; /*! SIP Refer restriction scheme */
1055 struct ast_ha
*ha
; /*!< ACL setting */
1056 struct ast_variable
*chanvars
; /*!< Variables to set for channel created by user */
1057 int maxcallbitrate
; /*!< Maximum Bitrate for a video call */
1061 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1062 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1064 ASTOBJ_COMPONENTS(struct sip_peer
); /*!< name, refcount, objflags, object pointers */
1065 /*!< peer->name is the unique name of this object */
1066 char secret
[80]; /*!< Password */
1067 char md5secret
[80]; /*!< Password in MD5 */
1068 struct sip_auth
*auth
; /*!< Realm authentication list */
1069 char context
[AST_MAX_CONTEXT
]; /*!< Default context for incoming calls */
1070 char subscribecontext
[AST_MAX_CONTEXT
]; /*!< Default context for subscriptions */
1071 char username
[80]; /*!< Temporary username until registration */
1072 char accountcode
[AST_MAX_ACCOUNT_CODE
]; /*!< Account code */
1073 int amaflags
; /*!< AMA Flags (for billing) */
1074 char tohost
[MAXHOSTNAMELEN
]; /*!< If not dynamic, IP address */
1075 char regexten
[AST_MAX_EXTENSION
]; /*!< Extension to register (if regcontext is used) */
1076 char fromuser
[80]; /*!< From: user when calling this peer */
1077 char fromdomain
[MAXHOSTNAMELEN
]; /*!< From: domain when calling this peer */
1078 char fullcontact
[256]; /*!< Contact registered with us (not in sip.conf) */
1079 char cid_num
[80]; /*!< Caller ID num */
1080 char cid_name
[80]; /*!< Caller ID name */
1081 int callingpres
; /*!< Calling id presentation */
1082 int inUse
; /*!< Number of calls in use */
1083 int inRinging
; /*!< Number of calls ringing */
1084 int onHold
; /*!< Peer has someone on hold */
1085 int call_limit
; /*!< Limit of concurrent calls */
1086 enum transfermodes allowtransfer
; /*! SIP Refer restriction scheme */
1087 char vmexten
[AST_MAX_EXTENSION
]; /*!< Dialplan extension for MWI notify message*/
1088 char mailbox
[AST_MAX_EXTENSION
]; /*!< Mailbox setting for MWI checks */
1089 char language
[MAX_LANGUAGE
]; /*!< Default language for prompts */
1090 char mohinterpret
[MAX_MUSICCLASS
];/*!< Music on Hold class */
1091 char mohsuggest
[MAX_MUSICCLASS
];/*!< Music on Hold class */
1092 char useragent
[256]; /*!< User agent in SIP request (saved from registration) */
1093 struct ast_codec_pref prefs
; /*!< codec prefs */
1095 time_t lastmsgcheck
; /*!< Last time we checked for MWI */
1096 unsigned int sipoptions
; /*!< Supported SIP options */
1097 struct ast_flags flags
[2]; /*!< SIP_ flags */
1098 int expire
; /*!< When to expire this peer registration */
1099 int capability
; /*!< Codec capability */
1100 int rtptimeout
; /*!< RTP timeout */
1101 int rtpholdtimeout
; /*!< RTP Hold Timeout */
1102 int rtpkeepalive
; /*!< Send RTP packets for keepalive */
1103 ast_group_t callgroup
; /*!< Call group */
1104 ast_group_t pickupgroup
; /*!< Pickup group */
1105 struct sockaddr_in addr
; /*!< IP address of peer */
1106 int maxcallbitrate
; /*!< Maximum Bitrate for a video call */
1109 struct sip_pvt
*call
; /*!< Call pointer */
1110 int pokeexpire
; /*!< When to expire poke (qualify= checking) */
1111 int lastms
; /*!< How long last response took (in ms), or -1 for no response */
1112 int maxms
; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1113 struct timeval ps
; /*!< Ping send time */
1115 struct sockaddr_in defaddr
; /*!< Default IP address, used until registration */
1116 struct ast_ha
*ha
; /*!< Access control list */
1117 struct ast_variable
*chanvars
; /*!< Variables to set for channel created by user */
1118 struct sip_pvt
*mwipvt
; /*!< Subscription for MWI */
1125 /*! \brief Registrations with other SIP proxies */
1126 struct sip_registry
{
1127 ASTOBJ_COMPONENTS_FULL(struct sip_registry
,1,1);
1128 AST_DECLARE_STRING_FIELDS(
1129 AST_STRING_FIELD(callid
); /*!< Global Call-ID */
1130 AST_STRING_FIELD(realm
); /*!< Authorization realm */
1131 AST_STRING_FIELD(nonce
); /*!< Authorization nonce */
1132 AST_STRING_FIELD(opaque
); /*!< Opaque nonsense */
1133 AST_STRING_FIELD(qop
); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1134 AST_STRING_FIELD(domain
); /*!< Authorization domain */
1135 AST_STRING_FIELD(username
); /*!< Who we are registering as */
1136 AST_STRING_FIELD(authuser
); /*!< Who we *authenticate* as */
1137 AST_STRING_FIELD(hostname
); /*!< Domain or host we register to */
1138 AST_STRING_FIELD(secret
); /*!< Password in clear text */
1139 AST_STRING_FIELD(md5secret
); /*!< Password in md5 */
1140 AST_STRING_FIELD(contact
); /*!< Contact extension */
1141 AST_STRING_FIELD(random
);
1143 int portno
; /*!< Optional port override */
1144 int expire
; /*!< Sched ID of expiration */
1145 int regattempts
; /*!< Number of attempts (since the last success) */
1146 int timeout
; /*!< sched id of sip_reg_timeout */
1147 int refresh
; /*!< How often to refresh */
1148 struct sip_pvt
*call
; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1149 enum sipregistrystate regstate
; /*!< Registration state (see above) */
1150 time_t regtime
; /*!< Last succesful registration time */
1151 int callid_valid
; /*!< 0 means we haven't chosen callid for this registry yet. */
1152 unsigned int ocseq
; /*!< Sequence number we got to for REGISTERs for this registry */
1153 struct sockaddr_in us
; /*!< Who the server thinks we are */
1154 int noncecount
; /*!< Nonce-count */
1155 char lastmsg
[256]; /*!< Last Message sent/received */
1158 /* --- Linked lists of various objects --------*/
1160 /*! \brief The user list: Users and friends */
1161 static struct ast_user_list
{
1162 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user
);
1165 /*! \brief The peer list: Peers and Friends */
1166 static struct ast_peer_list
{
1167 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer
);
1170 /*! \brief The register list: Other SIP proxys we register with and place calls to */
1171 static struct ast_register_list
{
1172 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry
);
1176 static void temp_pvt_cleanup(void *);
1178 /*! \brief A per-thread temporary pvt structure */
1179 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt
, temp_pvt_init
, temp_pvt_cleanup
);
1181 /*! \todo Move the sip_auth list to AST_LIST */
1182 static struct sip_auth
*authl
= NULL
; /*!< Authentication list for realm authentication */
1185 /* --- Sockets and networking --------------*/
1186 static int sipsock
= -1; /*!< Main socket for SIP network communication */
1187 static struct sockaddr_in bindaddr
= { 0, }; /*!< The address we bind to */
1188 static struct sockaddr_in externip
; /*!< External IP address if we are behind NAT */
1189 static char externhost
[MAXHOSTNAMELEN
]; /*!< External host name (possibly with dynamic DNS and DHCP */
1190 static time_t externexpire
= 0; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1191 static int externrefresh
= 10;
1192 static struct ast_ha
*localaddr
; /*!< List of local networks, on the same side of NAT as this Asterisk */
1193 static struct in_addr __ourip
;
1194 static struct sockaddr_in outboundproxyip
;
1196 static struct sockaddr_in debugaddr
;
1198 static struct ast_config
*notify_types
; /*!< The list of manual NOTIFY types we know how to send */
1200 /*---------------------------- Forward declarations of functions in chan_sip.c */
1201 /*! \note This is added to help splitting up chan_sip.c into several files
1202 in coming releases */
1204 /*--- PBX interface functions */
1205 static struct ast_channel
*sip_request_call(const char *type
, int format
, void *data
, int *cause
);
1206 static int sip_devicestate(void *data
);
1207 static int sip_sendtext(struct ast_channel
*ast
, const char *text
);
1208 static int sip_call(struct ast_channel
*ast
, char *dest
, int timeout
);
1209 static int sip_hangup(struct ast_channel
*ast
);
1210 static int sip_answer(struct ast_channel
*ast
);
1211 static struct ast_frame
*sip_read(struct ast_channel
*ast
);
1212 static int sip_write(struct ast_channel
*ast
, struct ast_frame
*frame
);
1213 static int sip_indicate(struct ast_channel
*ast
, int condition
, const void *data
, size_t datalen
);
1214 static int sip_transfer(struct ast_channel
*ast
, const char *dest
);
1215 static int sip_fixup(struct ast_channel
*oldchan
, struct ast_channel
*newchan
);
1216 static int sip_senddigit_begin(struct ast_channel
*ast
, char digit
);
1217 static int sip_senddigit_end(struct ast_channel
*ast
, char digit
, unsigned int duration
);
1219 /*--- Transmitting responses and requests */
1220 static int sipsock_read(int *id
, int fd
, short events
, void *ignore
);
1221 static int __sip_xmit(struct sip_pvt
*p
, char *data
, int len
);
1222 static int __sip_reliable_xmit(struct sip_pvt
*p
, int seqno
, int resp
, char *data
, int len
, int fatal
, int sipmethod
);
1223 static int __transmit_response(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
, enum xmittype reliable
);
1224 static int retrans_pkt(void *data
);
1225 static int transmit_sip_request(struct sip_pvt
*p
, struct sip_request
*req
);
1226 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
);
1227 static int transmit_response(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
);
1228 static int transmit_response_reliable(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
);
1229 static int transmit_response_with_date(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
);
1230 static int transmit_response_with_sdp(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
, enum xmittype reliable
);
1231 static int transmit_response_with_unsupported(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
, const char *unsupported
);
1232 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
);
1233 static int transmit_response_with_allow(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
, enum xmittype reliable
);
1234 static void transmit_fake_auth_response(struct sip_pvt
*p
, struct sip_request
*req
, int reliable
);
1235 static int transmit_request(struct sip_pvt
*p
, int sipmethod
, int inc
, enum xmittype reliable
, int newbranch
);
1236 static int transmit_request_with_auth(struct sip_pvt
*p
, int sipmethod
, int seqno
, enum xmittype reliable
, int newbranch
);
1237 static int transmit_invite(struct sip_pvt
*p
, int sipmethod
, int sdp
, int init
);
1238 static int transmit_reinvite_with_sdp(struct sip_pvt
*p
);
1239 static int transmit_info_with_digit(struct sip_pvt
*p
, const char digit
, unsigned int duration
);
1240 static int transmit_info_with_vidupdate(struct sip_pvt
*p
);
1241 static int transmit_message_with_text(struct sip_pvt
*p
, const char *text
);
1242 static int transmit_refer(struct sip_pvt
*p
, const char *dest
);
1243 static int transmit_notify_with_mwi(struct sip_pvt
*p
, int newmsgs
, int oldmsgs
, char *vmexten
);
1244 static int transmit_notify_with_sipfrag(struct sip_pvt
*p
, int cseq
, char *message
, int terminate
);
1245 static int transmit_register(struct sip_registry
*r
, int sipmethod
, const char *auth
, const char *authheader
);
1246 static int send_response(struct sip_pvt
*p
, struct sip_request
*req
, enum xmittype reliable
, int seqno
);
1247 static int send_request(struct sip_pvt
*p
, struct sip_request
*req
, enum xmittype reliable
, int seqno
);
1248 static void copy_request(struct sip_request
*dst
, const struct sip_request
*src
);
1249 static void receive_message(struct sip_pvt
*p
, struct sip_request
*req
);
1250 static void parse_moved_contact(struct sip_pvt
*p
, struct sip_request
*req
);
1251 static int sip_send_mwi_to_peer(struct sip_peer
*peer
);
1252 static int does_peer_need_mwi(struct sip_peer
*peer
);
1254 /*--- Dialog management */
1255 static struct sip_pvt
*sip_alloc(ast_string_field callid
, struct sockaddr_in
*sin
,
1256 int useglobal_nat
, const int intended_method
);
1257 static int __sip_autodestruct(void *data
);
1258 static void sip_scheddestroy(struct sip_pvt
*p
, int ms
);
1259 static void sip_cancel_destroy(struct sip_pvt
*p
);
1260 static void sip_destroy(struct sip_pvt
*p
);
1261 static void __sip_destroy(struct sip_pvt
*p
, int lockowner
);
1262 static void __sip_ack(struct sip_pvt
*p
, int seqno
, int resp
, int sipmethod
);
1263 static void __sip_pretend_ack(struct sip_pvt
*p
);
1264 static int __sip_semi_ack(struct sip_pvt
*p
, int seqno
, int resp
, int sipmethod
);
1265 static int auto_congest(void *nothing
);
1266 static int update_call_counter(struct sip_pvt
*fup
, int event
);
1267 static int hangup_sip2cause(int cause
);
1268 static const char *hangup_cause2sip(int cause
);
1269 static struct sip_pvt
*find_call(struct sip_request
*req
, struct sockaddr_in
*sin
, const int intended_method
);
1270 static void free_old_route(struct sip_route
*route
);
1271 static void list_route(struct sip_route
*route
);
1272 static void build_route(struct sip_pvt
*p
, struct sip_request
*req
, int backwards
);
1273 static enum check_auth_result
register_verify(struct sip_pvt
*p
, struct sockaddr_in
*sin
,
1274 struct sip_request
*req
, char *uri
);
1275 static struct sip_pvt
*get_sip_pvt_byid_locked(const char *callid
, const char *totag
, const char *fromtag
);
1276 static void check_pendings(struct sip_pvt
*p
);
1277 static void *sip_park_thread(void *stuff
);
1278 static int sip_park(struct ast_channel
*chan1
, struct ast_channel
*chan2
, struct sip_request
*req
, int seqno
);
1279 static int sip_sipredirect(struct sip_pvt
*p
, const char *dest
);
1281 /*--- Codec handling / SDP */
1282 static void try_suggested_sip_codec(struct sip_pvt
*p
);
1283 static const char* get_sdp_iterate(int* start
, struct sip_request
*req
, const char *name
);
1284 static const char *get_sdp(struct sip_request
*req
, const char *name
);
1285 static int find_sdp(struct sip_request
*req
);
1286 static int process_sdp(struct sip_pvt
*p
, struct sip_request
*req
);
1287 static void add_codec_to_sdp(const struct sip_pvt
*p
, int codec
, int sample_rate
,
1288 char **m_buf
, size_t *m_size
, char **a_buf
, size_t *a_size
,
1289 int debug
, int *min_packet_size
);
1290 static void add_noncodec_to_sdp(const struct sip_pvt
*p
, int format
, int sample_rate
,
1291 char **m_buf
, size_t *m_size
, char **a_buf
, size_t *a_size
,
1293 static enum sip_result
add_sdp(struct sip_request
*resp
, struct sip_pvt
*p
);
1294 static void stop_media_flows(struct sip_pvt
*p
);
1296 /*--- Authentication stuff */
1297 static int reply_digest(struct sip_pvt
*p
, struct sip_request
*req
, char *header
, int sipmethod
, char *digest
, int digest_len
);
1298 static int build_reply_digest(struct sip_pvt
*p
, int method
, char *digest
, int digest_len
);
1299 static enum check_auth_result
check_auth(struct sip_pvt
*p
, struct sip_request
*req
, const char *username
,
1300 const char *secret
, const char *md5secret
, int sipmethod
,
1301 char *uri
, enum xmittype reliable
, int ignore
);
1302 static enum check_auth_result
check_user_full(struct sip_pvt
*p
, struct sip_request
*req
,
1303 int sipmethod
, char *uri
, enum xmittype reliable
,
1304 struct sockaddr_in
*sin
, struct sip_peer
**authpeer
);
1305 static int check_user(struct sip_pvt
*p
, struct sip_request
*req
, int sipmethod
, char *uri
, enum xmittype reliable
, struct sockaddr_in
*sin
);
1307 /*--- Domain handling */
1308 static int check_sip_domain(const char *domain
, char *context
, size_t len
); /* Check if domain is one of our local domains */
1309 static int add_sip_domain(const char *domain
, const enum domain_mode mode
, const char *context
);
1310 static void clear_sip_domains(void);
1312 /*--- SIP realm authentication */
1313 static struct sip_auth
*add_realm_authentication(struct sip_auth
*authlist
, char *configuration
, int lineno
);
1314 static int clear_realm_authentication(struct sip_auth
*authlist
); /* Clear realm authentication list (at reload) */
1315 static struct sip_auth
*find_realm_authentication(struct sip_auth
*authlist
, const char *realm
);
1317 /*--- Misc functions */
1318 static int sip_do_reload(enum channelreloadreason reason
);
1319 static int reload_config(enum channelreloadreason reason
);
1320 static int expire_register(void *data
);
1321 static void *do_monitor(void *data
);
1322 static int restart_monitor(void);
1323 static int sip_send_mwi_to_peer(struct sip_peer
*peer
);
1324 static void sip_destroy(struct sip_pvt
*p
);
1325 static int sip_addrcmp(char *name
, struct sockaddr_in
*sin
); /* Support for peer matching */
1326 static int sip_refer_allocate(struct sip_pvt
*p
);
1327 static void ast_quiet_chan(struct ast_channel
*chan
);
1328 static int attempt_transfer(struct sip_dual
*transferer
, struct sip_dual
*target
);
1330 /*--- Device monitoring and Device/extension state handling */
1331 static int cb_extensionstate(char *context
, char* exten
, int state
, void *data
);
1332 static int sip_devicestate(void *data
);
1333 static int sip_poke_noanswer(void *data
);
1334 static int sip_poke_peer(struct sip_peer
*peer
);
1335 static void sip_poke_all_peers(void);
1336 static void sip_peer_hold(struct sip_pvt
*p
, int hold
);
1338 /*--- Applications, functions, CLI and manager command helpers */
1339 static const char *sip_nat_mode(const struct sip_pvt
*p
);
1340 static int sip_show_inuse(int fd
, int argc
, char *argv
[]);
1341 static char *transfermode2str(enum transfermodes mode
) attribute_const
;
1342 static char *nat2str(int nat
) attribute_const
;
1343 static int peer_status(struct sip_peer
*peer
, char *status
, int statuslen
);
1344 static int sip_show_users(int fd
, int argc
, char *argv
[]);
1345 static int _sip_show_peers(int fd
, int *total
, struct mansession
*s
, const struct message
*m
, int argc
, const char *argv
[]);
1346 static int sip_show_peers(int fd
, int argc
, char *argv
[]);
1347 static int sip_show_objects(int fd
, int argc
, char *argv
[]);
1348 static void print_group(int fd
, ast_group_t group
, int crlf
);
1349 static const char *dtmfmode2str(int mode
) attribute_const
;
1350 static const char *insecure2str(int port
, int invite
) attribute_const
;
1351 static void cleanup_stale_contexts(char *new, char *old
);
1352 static void print_codec_to_cli(int fd
, struct ast_codec_pref
*pref
);
1353 static const char *domain_mode_to_text(const enum domain_mode mode
);
1354 static int sip_show_domains(int fd
, int argc
, char *argv
[]);
1355 static int _sip_show_peer(int type
, int fd
, struct mansession
*s
, const struct message
*m
, int argc
, const char *argv
[]);
1356 static int sip_show_peer(int fd
, int argc
, char *argv
[]);
1357 static int sip_show_user(int fd
, int argc
, char *argv
[]);
1358 static int sip_show_registry(int fd
, int argc
, char *argv
[]);
1359 static int sip_show_settings(int fd
, int argc
, char *argv
[]);
1360 static const char *subscription_type2str(enum subscriptiontype subtype
) attribute_pure
;
1361 static const struct cfsubscription_types
*find_subscription_type(enum subscriptiontype subtype
);
1362 static int __sip_show_channels(int fd
, int argc
, char *argv
[], int subscriptions
);
1363 static int sip_show_channels(int fd
, int argc
, char *argv
[]);
1364 static int sip_show_subscriptions(int fd
, int argc
, char *argv
[]);
1365 static int __sip_show_channels(int fd
, int argc
, char *argv
[], int subscriptions
);
1366 static char *complete_sipch(const char *line
, const char *word
, int pos
, int state
);
1367 static char *complete_sip_peer(const char *word
, int state
, int flags2
);
1368 static char *complete_sip_show_peer(const char *line
, const char *word
, int pos
, int state
);
1369 static char *complete_sip_debug_peer(const char *line
, const char *word
, int pos
, int state
);
1370 static char *complete_sip_user(const char *word
, int state
, int flags2
);
1371 static char *complete_sip_show_user(const char *line
, const char *word
, int pos
, int state
);
1372 static char *complete_sipnotify(const char *line
, const char *word
, int pos
, int state
);
1373 static char *complete_sip_prune_realtime_peer(const char *line
, const char *word
, int pos
, int state
);
1374 static char *complete_sip_prune_realtime_user(const char *line
, const char *word
, int pos
, int state
);
1375 static int sip_show_channel(int fd
, int argc
, char *argv
[]);
1376 static int sip_show_history(int fd
, int argc
, char *argv
[]);
1377 static int sip_do_debug_ip(int fd
, int argc
, char *argv
[]);
1378 static int sip_do_debug_peer(int fd
, int argc
, char *argv
[]);
1379 static int sip_do_debug(int fd
, int argc
, char *argv
[]);
1380 static int sip_no_debug(int fd
, int argc
, char *argv
[]);
1381 static int sip_notify(int fd
, int argc
, char *argv
[]);
1382 static int sip_do_history(int fd
, int argc
, char *argv
[]);
1383 static int sip_no_history(int fd
, int argc
, char *argv
[]);
1384 static int func_header_read(struct ast_channel
*chan
, char *function
, char *data
, char *buf
, size_t len
);
1385 static int func_check_sipdomain(struct ast_channel
*chan
, char *cmd
, char *data
, char *buf
, size_t len
);
1386 static int function_sippeer(struct ast_channel
*chan
, char *cmd
, char *data
, char *buf
, size_t len
);
1387 static int function_sipchaninfo_read(struct ast_channel
*chan
, char *cmd
, char *data
, char *buf
, size_t len
);
1388 static int sip_dtmfmode(struct ast_channel
*chan
, void *data
);
1389 static int sip_addheader(struct ast_channel
*chan
, void *data
);
1390 static int sip_do_reload(enum channelreloadreason reason
);
1391 static int sip_reload(int fd
, int argc
, char *argv
[]);
1392 static int acf_channel_read(struct ast_channel
*chan
, char *funcname
, char *preparse
, char *buf
, size_t buflen
);
1395 Functions for enabling debug per IP or fully, or enabling history logging for
1398 static void sip_dump_history(struct sip_pvt
*dialog
); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1399 static inline int sip_debug_test_addr(const struct sockaddr_in
*addr
);
1400 static inline int sip_debug_test_pvt(struct sip_pvt
*p
);
1401 static void append_history_full(struct sip_pvt
*p
, const char *fmt
, ...);
1402 static void sip_dump_history(struct sip_pvt
*dialog
);
1404 /*--- Device object handling */
1405 static struct sip_peer
*temp_peer(const char *name
);
1406 static struct sip_peer
*build_peer(const char *name
, struct ast_variable
*v
, struct ast_variable
*alt
, int realtime
);
1407 static struct sip_user
*build_user(const char *name
, struct ast_variable
*v
, int realtime
);
1408 static int update_call_counter(struct sip_pvt
*fup
, int event
);
1409 static void sip_destroy_peer(struct sip_peer
*peer
);
1410 static void sip_destroy_user(struct sip_user
*user
);
1411 static int sip_poke_peer(struct sip_peer
*peer
);
1412 static int sip_poke_peer_s(void *data
);
1413 static void set_peer_defaults(struct sip_peer
*peer
);
1414 static struct sip_peer
*temp_peer(const char *name
);
1415 static void register_peer_exten(struct sip_peer
*peer
, int onoff
);
1416 static struct sip_peer
*find_peer(const char *peer
, struct sockaddr_in
*sin
, int realtime
);
1417 static struct sip_user
*find_user(const char *name
, int realtime
);
1418 static enum parse_register_result
parse_register_contact(struct sip_pvt
*pvt
, struct sip_peer
*p
, struct sip_request
*req
);
1419 static int expire_register(void *data
);
1420 static void reg_source_db(struct sip_peer
*peer
);
1421 static void destroy_association(struct sip_peer
*peer
);
1422 static int handle_common_options(struct ast_flags
*flags
, struct ast_flags
*mask
, struct ast_variable
*v
);
1424 /* Realtime device support */
1425 static void realtime_update_peer(const char *peername
, struct sockaddr_in
*sin
, const char *username
, const char *fullcontact
, int expirey
);
1426 static struct sip_user
*realtime_user(const char *username
);
1427 static void update_peer(struct sip_peer
*p
, int expiry
);
1428 static struct sip_peer
*realtime_peer(const char *peername
, struct sockaddr_in
*sin
);
1429 static int sip_prune_realtime(int fd
, int argc
, char *argv
[]);
1431 /*--- Internal UA client handling (outbound registrations) */
1432 static int ast_sip_ouraddrfor(struct in_addr
*them
, struct in_addr
*us
);
1433 static void sip_registry_destroy(struct sip_registry
*reg
);
1434 static int sip_register(char *value
, int lineno
);
1435 static char *regstate2str(enum sipregistrystate regstate
) attribute_const
;
1436 static int sip_reregister(void *data
);
1437 static int __sip_do_register(struct sip_registry
*r
);
1438 static int sip_reg_timeout(void *data
);
1439 static void sip_send_all_registers(void);
1441 /*--- Parsing SIP requests and responses */
1442 static void append_date(struct sip_request
*req
); /* Append date to SIP packet */
1443 static int determine_firstline_parts(struct sip_request
*req
);
1444 static const struct cfsubscription_types
*find_subscription_type(enum subscriptiontype subtype
);
1445 static const char *gettag(const struct sip_request
*req
, const char *header
, char *tagbuf
, int tagbufsize
);
1446 static int find_sip_method(const char *msg
);
1447 static unsigned int parse_sip_options(struct sip_pvt
*pvt
, const char *supported
);
1448 static void parse_request(struct sip_request
*req
);
1449 static const char *get_header(const struct sip_request
*req
, const char *name
);
1450 static char *referstatus2str(enum referstatus rstatus
) attribute_pure
;
1451 static int method_match(enum sipmethod id
, const char *name
);
1452 static void parse_copy(struct sip_request
*dst
, const struct sip_request
*src
);
1453 static char *get_in_brackets(char *tmp
);
1454 static const char *find_alias(const char *name
, const char *_default
);
1455 static const char *__get_header(const struct sip_request
*req
, const char *name
, int *start
);
1456 static int lws2sws(char *msgbuf
, int len
);
1457 static void extract_uri(struct sip_pvt
*p
, struct sip_request
*req
);
1458 static int get_refer_info(struct sip_pvt
*transferer
, struct sip_request
*outgoing_req
);
1459 static int get_also_info(struct sip_pvt
*p
, struct sip_request
*oreq
);
1460 static int parse_ok_contact(struct sip_pvt
*pvt
, struct sip_request
*req
);
1461 static int set_address_from_contact(struct sip_pvt
*pvt
);
1462 static void check_via(struct sip_pvt
*p
, struct sip_request
*req
);
1463 static char *get_calleridname(const char *input
, char *output
, size_t outputsize
);
1464 static int get_rpid_num(const char *input
, char *output
, int maxlen
);
1465 static int get_rdnis(struct sip_pvt
*p
, struct sip_request
*oreq
);
1466 static int get_destination(struct sip_pvt
*p
, struct sip_request
*oreq
);
1467 static int get_msg_text(char *buf
, int len
, struct sip_request
*req
);
1468 static void free_old_route(struct sip_route
*route
);
1469 static int transmit_state_notify(struct sip_pvt
*p
, int state
, int full
, int timeout
);
1471 /*--- Constructing requests and responses */
1472 static void initialize_initreq(struct sip_pvt
*p
, struct sip_request
*req
);
1473 static int init_req(struct sip_request
*req
, int sipmethod
, const char *recip
);
1474 static int reqprep(struct sip_request
*req
, struct sip_pvt
*p
, int sipmethod
, int seqno
, int newbranch
);
1475 static void initreqprep(struct sip_request
*req
, struct sip_pvt
*p
, int sipmethod
);
1476 static int init_resp(struct sip_request
*resp
, const char *msg
);
1477 static int respprep(struct sip_request
*resp
, struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
);
1478 static const struct sockaddr_in
*sip_real_dst(const struct sip_pvt
*p
);
1479 static void build_via(struct sip_pvt
*p
);
1480 static int create_addr_from_peer(struct sip_pvt
*r
, struct sip_peer
*peer
);
1481 static int create_addr(struct sip_pvt
*dialog
, const char *opeer
);
1482 static char *generate_random_string(char *buf
, size_t size
);
1483 static void build_callid_pvt(struct sip_pvt
*pvt
);
1484 static void build_callid_registry(struct sip_registry
*reg
, struct in_addr ourip
, const char *fromdomain
);
1485 static void make_our_tag(char *tagbuf
, size_t len
);
1486 static int add_header(struct sip_request
*req
, const char *var
, const char *value
);
1487 static int add_header_contentLength(struct sip_request
*req
, int len
);
1488 static int add_line(struct sip_request
*req
, const char *line
);
1489 static int add_text(struct sip_request
*req
, const char *text
);
1490 static int add_digit(struct sip_request
*req
, char digit
, unsigned int duration
);
1491 static int add_vidupdate(struct sip_request
*req
);
1492 static void add_route(struct sip_request
*req
, struct sip_route
*route
);
1493 static int copy_header(struct sip_request
*req
, const struct sip_request
*orig
, const char *field
);
1494 static int copy_all_header(struct sip_request
*req
, const struct sip_request
*orig
, const char *field
);
1495 static int copy_via_headers(struct sip_pvt
*p
, struct sip_request
*req
, const struct sip_request
*orig
, const char *field
);
1496 static void set_destination(struct sip_pvt
*p
, char *uri
);
1497 static void append_date(struct sip_request
*req
);
1498 static void build_contact(struct sip_pvt
*p
);
1499 static void build_rpid(struct sip_pvt
*p
);
1501 /*------Request handling functions */
1502 static int handle_request(struct sip_pvt
*p
, struct sip_request
*req
, struct sockaddr_in
*sin
, int *recount
, int *nounlock
);
1503 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
);
1504 static int handle_request_refer(struct sip_pvt
*p
, struct sip_request
*req
, int debug
, int ignore
, int seqno
, int *nounlock
);
1505 static int handle_request_bye(struct sip_pvt
*p
, struct sip_request
*req
);
1506 static int handle_request_register(struct sip_pvt
*p
, struct sip_request
*req
, struct sockaddr_in
*sin
, char *e
);
1507 static int handle_request_cancel(struct sip_pvt
*p
, struct sip_request
*req
);
1508 static int handle_request_message(struct sip_pvt
*p
, struct sip_request
*req
);
1509 static int handle_request_subscribe(struct sip_pvt
*p
, struct sip_request
*req
, struct sockaddr_in
*sin
, int seqno
, char *e
);
1510 static void handle_request_info(struct sip_pvt
*p
, struct sip_request
*req
);
1511 static int handle_request_options(struct sip_pvt
*p
, struct sip_request
*req
);
1512 static int handle_invite_replaces(struct sip_pvt
*p
, struct sip_request
*req
, int debug
, int ignore
, int seqno
, struct sockaddr_in
*sin
);
1513 static int handle_request_notify(struct sip_pvt
*p
, struct sip_request
*req
, struct sockaddr_in
*sin
, int seqno
, char *e
);
1514 static int local_attended_transfer(struct sip_pvt
*transferer
, struct sip_dual
*current
, struct sip_request
*req
, int seqno
);
1516 /*------Response handling functions */
1517 static void handle_response_invite(struct sip_pvt
*p
, int resp
, char *rest
, struct sip_request
*req
, int seqno
);
1518 static void handle_response_refer(struct sip_pvt
*p
, int resp
, char *rest
, struct sip_request
*req
, int seqno
);
1519 static int handle_response_register(struct sip_pvt
*p
, int resp
, char *rest
, struct sip_request
*req
, int ignore
, int seqno
);
1520 static void handle_response(struct sip_pvt
*p
, int resp
, char *rest
, struct sip_request
*req
, int ignore
, int seqno
);
1522 /*----- RTP interface functions */
1523 static int sip_set_rtp_peer(struct ast_channel
*chan
, struct ast_rtp
*rtp
, struct ast_rtp
*vrtp
, int codecs
, int nat_active
);
1524 static enum ast_rtp_get_result
sip_get_rtp_peer(struct ast_channel
*chan
, struct ast_rtp
**rtp
);
1525 static enum ast_rtp_get_result
sip_get_vrtp_peer(struct ast_channel
*chan
, struct ast_rtp
**rtp
);
1526 static int sip_get_codec(struct ast_channel
*chan
);
1527 static struct ast_frame
*sip_rtp_read(struct ast_channel
*ast
, struct sip_pvt
*p
, int *faxdetect
);
1529 /*------ T38 Support --------- */
1530 static int sip_handle_t38_reinvite(struct ast_channel
*chan
, struct sip_pvt
*pvt
, int reinvite
); /*!< T38 negotiation helper function */
1531 static int transmit_response_with_t38_sdp(struct sip_pvt
*p
, char *msg
, struct sip_request
*req
, int retrans
);
1532 static int transmit_reinvite_with_t38_sdp(struct sip_pvt
*p
);
1533 static struct ast_udptl
*sip_get_udptl_peer(struct ast_channel
*chan
);
1534 static int sip_set_udptl_peer(struct ast_channel
*chan
, struct ast_udptl
*udptl
);
1536 /*! \brief Definition of this channel for PBX channel registration */
1537 static const struct ast_channel_tech sip_tech
= {
1539 .description
= "Session Initiation Protocol (SIP)",
1540 .capabilities
= ((AST_FORMAT_MAX_AUDIO
<< 1) - 1),
1541 .properties
= AST_CHAN_TP_WANTSJITTER
| AST_CHAN_TP_CREATESJITTER
,
1542 .requester
= sip_request_call
,
1543 .devicestate
= sip_devicestate
,
1545 .hangup
= sip_hangup
,
1546 .answer
= sip_answer
,
1549 .write_video
= sip_write
,
1550 .indicate
= sip_indicate
,
1551 .transfer
= sip_transfer
,
1553 .send_digit_begin
= sip_senddigit_begin
,
1554 .send_digit_end
= sip_senddigit_end
,
1555 .bridge
= ast_rtp_bridge
,
1556 .send_text
= sip_sendtext
,
1557 .func_channel_read
= acf_channel_read
,
1560 /*! \brief This version of the sip channel tech has no send_digit_begin
1561 * callback. This is for use with channels using SIP INFO DTMF so that
1562 * the core knows that the channel doesn't want DTMF BEGIN frames. */
1563 static const struct ast_channel_tech sip_tech_info
= {
1565 .description
= "Session Initiation Protocol (SIP)",
1566 .capabilities
= ((AST_FORMAT_MAX_AUDIO
<< 1) - 1),
1567 .properties
= AST_CHAN_TP_WANTSJITTER
| AST_CHAN_TP_CREATESJITTER
,
1568 .requester
= sip_request_call
,
1569 .devicestate
= sip_devicestate
,
1571 .hangup
= sip_hangup
,
1572 .answer
= sip_answer
,
1575 .write_video
= sip_write
,
1576 .indicate
= sip_indicate
,
1577 .transfer
= sip_transfer
,
1579 .send_digit_end
= sip_senddigit_end
,
1580 .bridge
= ast_rtp_bridge
,
1581 .send_text
= sip_sendtext
,
1584 /**--- some list management macros. **/
1586 #define UNLINK(element, head, prev) do { \
1588 (prev)->next = (element)->next; \
1590 (head) = (element)->next; \
1593 /*! \brief Interface structure with callbacks used to connect to RTP module */
1594 static struct ast_rtp_protocol sip_rtp
= {
1596 get_rtp_info
: sip_get_rtp_peer
,
1597 get_vrtp_info
: sip_get_vrtp_peer
,
1598 set_rtp_peer
: sip_set_rtp_peer
,
1599 get_codec
: sip_get_codec
,
1602 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1603 static struct ast_udptl_protocol sip_udptl
= {
1605 get_udptl_info
: sip_get_udptl_peer
,
1606 set_udptl_peer
: sip_set_udptl_peer
,
1609 /*! \brief Convert transfer status to string */
1610 static char *referstatus2str(enum referstatus rstatus
)
1612 int i
= (sizeof(referstatusstrings
) / sizeof(referstatusstrings
[0]));
1615 for (x
= 0; x
< i
; x
++) {
1616 if (referstatusstrings
[x
].status
== rstatus
)
1617 return (char *) referstatusstrings
[x
].text
;
1622 /*! \brief Initialize the initital request packet in the pvt structure.
1623 This packet is used for creating replies and future requests in
1625 static void initialize_initreq(struct sip_pvt
*p
, struct sip_request
*req
)
1627 if (p
->initreq
.headers
&& option_debug
) {
1628 ast_log(LOG_DEBUG
, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p
->callid
);
1630 /* Use this as the basis */
1631 copy_request(&p
->initreq
, req
);
1632 parse_request(&p
->initreq
);
1633 if (ast_test_flag(req
, SIP_PKT_DEBUG
))
1634 ast_verbose("%d headers, %d lines\n", p
->initreq
.headers
, p
->initreq
.lines
);
1637 static void sip_alreadygone(struct sip_pvt
*dialog
)
1639 if (option_debug
> 2)
1640 ast_log(LOG_DEBUG
, "Setting SIP_ALREADYGONE on dialog %s\n", dialog
->callid
);
1641 ast_set_flag(&dialog
->flags
[0], SIP_ALREADYGONE
);
1645 /*! \brief returns true if 'name' (with optional trailing whitespace)
1646 * matches the sip method 'id'.
1647 * Strictly speaking, SIP methods are case SENSITIVE, but we do
1648 * a case-insensitive comparison to be more tolerant.
1649 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1651 static int method_match(enum sipmethod id
, const char *name
)
1653 int len
= strlen(sip_methods
[id
].text
);
1654 int l_name
= name
? strlen(name
) : 0;
1655 /* true if the string is long enough, and ends with whitespace, and matches */
1656 return (l_name
>= len
&& name
[len
] < 33 &&
1657 !strncasecmp(sip_methods
[id
].text
, name
, len
));
1660 /*! \brief find_sip_method: Find SIP method from header */
1661 static int find_sip_method(const char *msg
)
1665 if (ast_strlen_zero(msg
))
1667 for (i
= 1; i
< (sizeof(sip_methods
) / sizeof(sip_methods
[0])) && !res
; i
++) {
1668 if (method_match(i
, msg
))
1669 res
= sip_methods
[i
].id
;
1674 /*! \brief Parse supported header in incoming packet */
1675 static unsigned int parse_sip_options(struct sip_pvt
*pvt
, const char *supported
)
1679 unsigned int profile
= 0;
1682 if (ast_strlen_zero(supported
) )
1684 temp
= ast_strdupa(supported
);
1686 if (option_debug
> 2 && sipdebug
)
1687 ast_log(LOG_DEBUG
, "Begin: parsing SIP \"Supported: %s\"\n", supported
);
1689 for (next
= temp
; next
; next
= sep
) {
1691 if ( (sep
= strchr(next
, ',')) != NULL
)
1693 next
= ast_skip_blanks(next
);
1694 if (option_debug
> 2 && sipdebug
)
1695 ast_log(LOG_DEBUG
, "Found SIP option: -%s-\n", next
);
1696 for (i
=0; i
< (sizeof(sip_options
) / sizeof(sip_options
[0])); i
++) {
1697 if (!strcasecmp(next
, sip_options
[i
].text
)) {
1698 profile
|= sip_options
[i
].id
;
1700 if (option_debug
> 2 && sipdebug
)
1701 ast_log(LOG_DEBUG
, "Matched SIP option: %s\n", next
);
1705 if (!found
&& option_debug
> 2 && sipdebug
) {
1706 if (!strncasecmp(next
, "x-", 2))
1707 ast_log(LOG_DEBUG
, "Found private SIP option, not supported: %s\n", next
);
1709 ast_log(LOG_DEBUG
, "Found no match for SIP option: %s (Please file bug report!)\n", next
);
1714 pvt
->sipoptions
= profile
;
1718 /*! \brief See if we pass debug IP filter */
1719 static inline int sip_debug_test_addr(const struct sockaddr_in
*addr
)
1723 if (debugaddr
.sin_addr
.s_addr
) {
1724 if (((ntohs(debugaddr
.sin_port
) != 0)
1725 && (debugaddr
.sin_port
!= addr
->sin_port
))
1726 || (debugaddr
.sin_addr
.s_addr
!= addr
->sin_addr
.s_addr
))
1732 /*! \brief The real destination address for a write */
1733 static const struct sockaddr_in
*sip_real_dst(const struct sip_pvt
*p
)
1735 return ast_test_flag(&p
->flags
[0], SIP_NAT
) & SIP_NAT_ROUTE
? &p
->recv
: &p
->sa
;
1738 /*! \brief Display SIP nat mode */
1739 static const char *sip_nat_mode(const struct sip_pvt
*p
)
1741 return ast_test_flag(&p
->flags
[0], SIP_NAT
) & SIP_NAT_ROUTE
? "NAT" : "no NAT";
1744 /*! \brief Test PVT for debugging output */
1745 static inline int sip_debug_test_pvt(struct sip_pvt
*p
)
1749 return sip_debug_test_addr(sip_real_dst(p
));
1752 /*! \brief Transmit SIP message */
1753 static int __sip_xmit(struct sip_pvt
*p
, char *data
, int len
)
1756 const struct sockaddr_in
*dst
= sip_real_dst(p
);
1757 res
= sendto(sipsock
, data
, len
, 0, (const struct sockaddr
*)dst
, sizeof(struct sockaddr_in
));
1761 case EBADF
: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
1762 case EHOSTUNREACH
: /* Host can't be reached */
1763 case ENETDOWN
: /* Inteface down */
1764 case ENETUNREACH
: /* Network failure */
1765 res
= XMIT_ERROR
; /* Don't bother with trying to transmit again */
1769 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
));
1774 /*! \brief Build a Via header for a request */
1775 static void build_via(struct sip_pvt
*p
)
1777 /* Work around buggy UNIDEN UIP200 firmware */
1778 const char *rport
= ast_test_flag(&p
->flags
[0], SIP_NAT
) & SIP_NAT_RFC3581
? ";rport" : "";
1780 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1781 ast_string_field_build(p
, via
, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1782 ast_inet_ntoa(p
->ourip
), ourport
, p
->branch
, rport
);
1785 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1787 * Using the localaddr structure built up with localnet statements in sip.conf
1788 * apply it to their address to see if we need to substitute our
1789 * externip or can get away with our internal bindaddr
1791 static enum sip_result
ast_sip_ouraddrfor(struct in_addr
*them
, struct in_addr
*us
)
1793 struct sockaddr_in theirs
, ours
;
1795 /* Get our local information */
1796 ast_ouraddrfor(them
, us
);
1797 theirs
.sin_addr
= *them
;
1798 ours
.sin_addr
= *us
;
1800 if (localaddr
&& externip
.sin_addr
.s_addr
&&
1801 (ast_apply_ha(localaddr
, &theirs
)) &&
1802 (!global_matchexterniplocally
|| !ast_apply_ha(localaddr
, &ours
))) {
1803 if (externexpire
&& time(NULL
) >= externexpire
) {
1804 struct ast_hostent ahp
;
1807 externexpire
= time(NULL
) + externrefresh
;
1808 if ((hp
= ast_gethostbyname(externhost
, &ahp
))) {
1809 memcpy(&externip
.sin_addr
, hp
->h_addr
, sizeof(externip
.sin_addr
));
1811 ast_log(LOG_NOTICE
, "Warning: Re-lookup of '%s' failed!\n", externhost
);
1813 *us
= externip
.sin_addr
;
1815 ast_log(LOG_DEBUG
, "Target address %s is not local, substituting externip\n",
1816 ast_inet_ntoa(*(struct in_addr
*)&them
->s_addr
));
1818 } else if (bindaddr
.sin_addr
.s_addr
)
1819 *us
= bindaddr
.sin_addr
;
1823 /*! \brief Append to SIP dialog history
1824 \return Always returns 0 */
1825 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1827 static void append_history_full(struct sip_pvt
*p
, const char *fmt
, ...)
1828 __attribute__ ((format (printf
, 2, 3)));
1830 /*! \brief Append to SIP dialog history with arg list */
1831 static void append_history_va(struct sip_pvt
*p
, const char *fmt
, va_list ap
)
1833 char buf
[80], *c
= buf
; /* max history length */
1834 struct sip_history
*hist
;
1837 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1838 strsep(&c
, "\r\n"); /* Trim up everything after \r or \n */
1839 l
= strlen(buf
) + 1;
1840 if (!(hist
= ast_calloc(1, sizeof(*hist
) + l
)))
1842 if (!p
->history
&& !(p
->history
= ast_calloc(1, sizeof(*p
->history
)))) {
1846 memcpy(hist
->event
, buf
, l
);
1847 AST_LIST_INSERT_TAIL(p
->history
, hist
, list
);
1850 /*! \brief Append to SIP dialog history with arg list */
1851 static void append_history_full(struct sip_pvt
*p
, const char *fmt
, ...)
1858 append_history_va(p
, fmt
, ap
);
1864 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
1865 static int retrans_pkt(void *data
)
1867 struct sip_pkt
*pkt
= data
, *prev
, *cur
= NULL
;
1868 int reschedule
= DEFAULT_RETRANS
;
1871 /* Lock channel PVT */
1872 ast_mutex_lock(&pkt
->owner
->lock
);
1874 if (pkt
->retrans
< MAX_RETRANS
) {
1876 if (!pkt
->timer_t1
) { /* Re-schedule using timer_a and timer_t1 */
1877 if (sipdebug
&& option_debug
> 3)
1878 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
);
1882 if (sipdebug
&& option_debug
> 3)
1883 ast_log(LOG_DEBUG
, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt
->retransid
, pkt
->retrans
, sip_methods
[pkt
->method
].text
, pkt
->method
);
1887 pkt
->timer_a
= 2 * pkt
->timer_a
;
1889 /* For non-invites, a maximum of 4 secs */
1890 siptimer_a
= pkt
->timer_t1
* pkt
->timer_a
; /* Double each time */
1891 if (pkt
->method
!= SIP_INVITE
&& siptimer_a
> 4000)
1894 /* Reschedule re-transmit */
1895 reschedule
= siptimer_a
;
1896 if (option_debug
> 3)
1897 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
);
1900 if (sip_debug_test_pvt(pkt
->owner
)) {
1901 const struct sockaddr_in
*dst
= sip_real_dst(pkt
->owner
);
1902 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
1903 pkt
->retrans
, sip_nat_mode(pkt
->owner
),
1904 ast_inet_ntoa(dst
->sin_addr
),
1905 ntohs(dst
->sin_port
), pkt
->data
);
1908 append_history(pkt
->owner
, "ReTx", "%d %s", reschedule
, pkt
->data
);
1909 xmitres
= __sip_xmit(pkt
->owner
, pkt
->data
, pkt
->packetlen
);
1910 ast_mutex_unlock(&pkt
->owner
->lock
);
1911 if (xmitres
== XMIT_ERROR
)
1912 ast_log(LOG_WARNING
, "Network error on retransmit in dialog %s\n", pkt
->owner
->callid
);
1916 /* Too many retries */
1917 if (pkt
->owner
&& pkt
->method
!= SIP_OPTIONS
&& xmitres
== 0) {
1918 if (ast_test_flag(pkt
, FLAG_FATAL
) || sipdebug
) /* Tell us if it's critical or if we're debugging */
1919 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");
1920 } else if ((pkt
->method
== SIP_OPTIONS
) && sipdebug
) {
1921 ast_log(LOG_WARNING
, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt
->owner
->callid
);
1923 if (xmitres
== XMIT_ERROR
) {
1924 ast_log(LOG_WARNING
, "Transmit error :: Cancelling transmission of transaction in call id %s \n", pkt
->owner
->callid
);
1925 append_history(pkt
->owner
, "XmitErr", "%s", (ast_test_flag(pkt
, FLAG_FATAL
)) ? "(Critical)" : "(Non-critical)");
1927 append_history(pkt
->owner
, "MaxRetries", "%s", (ast_test_flag(pkt
, FLAG_FATAL
)) ? "(Critical)" : "(Non-critical)");
1929 pkt
->retransid
= -1;
1931 if (ast_test_flag(pkt
, FLAG_FATAL
)) {
1932 while(pkt
->owner
->owner
&& ast_channel_trylock(pkt
->owner
->owner
)) {
1933 ast_mutex_unlock(&pkt
->owner
->lock
); /* SIP_PVT, not channel */
1935 ast_mutex_lock(&pkt
->owner
->lock
);
1937 if (pkt
->owner
->owner
) {
1938 sip_alreadygone(pkt
->owner
);
1939 ast_log(LOG_WARNING
, "Hanging up call %s - no reply to our critical packet.\n", pkt
->owner
->callid
);
1940 ast_queue_hangup(pkt
->owner
->owner
);
1941 ast_channel_unlock(pkt
->owner
->owner
);
1943 /* If no channel owner, destroy now */
1945 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
1946 if (pkt
->method
!= SIP_OPTIONS
)
1947 ast_set_flag(&pkt
->owner
->flags
[0], SIP_NEEDDESTROY
);
1950 /* In any case, go ahead and remove the packet */
1951 for (prev
= NULL
, cur
= pkt
->owner
->packets
; cur
; prev
= cur
, cur
= cur
->next
) {
1957 prev
->next
= cur
->next
;
1959 pkt
->owner
->packets
= cur
->next
;
1960 ast_mutex_unlock(&pkt
->owner
->lock
);
1964 ast_log(LOG_WARNING
, "Weird, couldn't find packet owner!\n");
1966 ast_mutex_unlock(&pkt
->owner
->lock
);
1970 /*! \brief Transmit packet with retransmits
1971 \return 0 on success, -1 on failure to allocate packet
1973 static enum sip_result
__sip_reliable_xmit(struct sip_pvt
*p
, int seqno
, int resp
, char *data
, int len
, int fatal
, int sipmethod
)
1975 struct sip_pkt
*pkt
;
1976 int siptimer_a
= DEFAULT_RETRANS
;
1979 if (!(pkt
= ast_calloc(1, sizeof(*pkt
) + len
+ 1)))
1981 memcpy(pkt
->data
, data
, len
);
1982 pkt
->method
= sipmethod
;
1983 pkt
->packetlen
= len
;
1984 pkt
->next
= p
->packets
;
1988 ast_set_flag(pkt
, FLAG_RESPONSE
);
1989 pkt
->data
[len
] = '\0';
1990 pkt
->timer_t1
= p
->timer_t1
; /* Set SIP timer T1 */
1992 ast_set_flag(pkt
, FLAG_FATAL
);
1994 siptimer_a
= pkt
->timer_t1
* 2;
1996 /* Schedule retransmission */
1997 pkt
->retransid
= ast_sched_add_variable(sched
, siptimer_a
, retrans_pkt
, pkt
, 1);
1998 if (option_debug
> 3 && sipdebug
)
1999 ast_log(LOG_DEBUG
, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt
->retransid
);
2000 pkt
->next
= p
->packets
;
2002 if (sipmethod
== SIP_INVITE
) {
2003 /* Note this is a pending invite */
2004 p
->pendinginvite
= seqno
;
2007 xmitres
= __sip_xmit(pkt
->owner
, pkt
->data
, pkt
->packetlen
); /* Send packet */
2009 if (xmitres
== XMIT_ERROR
) { /* Serious network trouble, no need to try again */
2010 append_history(pkt
->owner
, "XmitErr", "%s", (ast_test_flag(pkt
, FLAG_FATAL
)) ? "(Critical)" : "(Non-critical)");
2011 ast_sched_del(sched
, pkt
->retransid
); /* No more retransmission */
2012 pkt
->retransid
= -1;
2018 /*! \brief Kill a SIP dialog (called by scheduler) */
2019 static int __sip_autodestruct(void *data
)
2021 struct sip_pvt
*p
= data
;
2023 /* If this is a subscription, tell the phone that we got a timeout */
2024 if (p
->subscribed
) {
2025 transmit_state_notify(p
, AST_EXTENSION_DEACTIVATED
, 1, TRUE
); /* Send last notification */
2026 p
->subscribed
= NONE
;
2027 append_history(p
, "Subscribestatus", "timeout");
2028 if (option_debug
> 2)
2029 ast_log(LOG_DEBUG
, "Re-scheduled destruction of SIP subsription %s\n", p
->callid
? p
->callid
: "<unknown>");
2030 return 10000; /* Reschedule this destruction so that we know that it's gone */
2033 /* If we're destroying a subscription, dereference peer object too */
2034 if (p
->subscribed
== MWI_NOTIFICATION
&& p
->relatedpeer
)
2035 ASTOBJ_UNREF(p
->relatedpeer
,sip_destroy_peer
);
2037 /* Reset schedule ID */
2041 ast_log(LOG_DEBUG
, "Auto destroying SIP dialog '%s'\n", p
->callid
);
2042 append_history(p
, "AutoDestroy", "%s", p
->callid
);
2044 ast_log(LOG_WARNING
, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p
->callid
, sip_methods
[p
->method
].text
);
2045 ast_queue_hangup(p
->owner
);
2046 } else if (p
->refer
) {
2047 if (option_debug
> 2)
2048 ast_log(LOG_DEBUG
, "Finally hanging up channel after transfer: %s\n", p
->callid
);
2049 transmit_request_with_auth(p
, SIP_BYE
, 0, XMIT_RELIABLE
, 1);
2050 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
2056 /*! \brief Schedule destruction of SIP dialog */
2057 static void sip_scheddestroy(struct sip_pvt
*p
, int ms
)
2060 if (p
->timer_t1
== 0)
2061 p
->timer_t1
= 500; /* Set timer T1 if not set (RFC 3261) */
2062 ms
= p
->timer_t1
* 64;
2064 if (sip_debug_test_pvt(p
))
2065 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p
->callid
, ms
, sip_methods
[p
->method
].text
);
2066 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
))
2067 append_history(p
, "SchedDestroy", "%d ms", ms
);
2069 if (p
->autokillid
> -1)
2070 ast_sched_del(sched
, p
->autokillid
);
2071 p
->autokillid
= ast_sched_add(sched
, ms
, __sip_autodestruct
, p
);
2074 /*! \brief Cancel destruction of SIP dialog */
2075 static void sip_cancel_destroy(struct sip_pvt
*p
)
2077 if (p
->autokillid
> -1) {
2078 ast_sched_del(sched
, p
->autokillid
);
2079 append_history(p
, "CancelDestroy", "");
2084 /*! \brief Acknowledges receipt of a packet and stops retransmission */
2085 static void __sip_ack(struct sip_pvt
*p
, int seqno
, int resp
, int sipmethod
)
2087 struct sip_pkt
*cur
, *prev
= NULL
;
2089 /* Just in case... */
2093 msg
= sip_methods
[sipmethod
].text
;
2095 ast_mutex_lock(&p
->lock
);
2096 for (cur
= p
->packets
; cur
; prev
= cur
, cur
= cur
->next
) {
2097 if ((cur
->seqno
== seqno
) && ((ast_test_flag(cur
, FLAG_RESPONSE
)) == resp
) &&
2098 ((ast_test_flag(cur
, FLAG_RESPONSE
)) ||
2099 (!strncasecmp(msg
, cur
->data
, strlen(msg
)) && (cur
->data
[strlen(msg
)] < 33)))) {
2100 if (!resp
&& (seqno
== p
->pendinginvite
)) {
2102 ast_log(LOG_DEBUG
, "Acked pending invite %d\n", p
->pendinginvite
);
2103 p
->pendinginvite
= 0;
2105 /* this is our baby */
2107 UNLINK(cur
, p
->packets
, prev
);
2108 if (cur
->retransid
> -1) {
2109 if (sipdebug
&& option_debug
> 3)
2110 ast_log(LOG_DEBUG
, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur
->retransid
);
2111 ast_sched_del(sched
, cur
->retransid
);
2112 cur
->retransid
= -1;
2118 ast_mutex_unlock(&p
->lock
);
2120 ast_log(LOG_DEBUG
, "Stopping retransmission on '%s' of %s %d: Match %s\n", p
->callid
, resp
? "Response" : "Request", seqno
, res
? "Not Found" : "Found");
2123 /*! \brief Pretend to ack all packets
2124 * maybe the lock on p is not strictly necessary but there might be a race */
2125 static void __sip_pretend_ack(struct sip_pvt
*p
)
2127 struct sip_pkt
*cur
= NULL
;
2129 while (p
->packets
) {
2131 if (cur
== p
->packets
) {
2132 ast_log(LOG_WARNING
, "Have a packet that doesn't want to give up! %s\n", sip_methods
[cur
->method
].text
);
2136 method
= (cur
->method
) ? cur
->method
: find_sip_method(cur
->data
);
2137 __sip_ack(p
, cur
->seqno
, ast_test_flag(cur
, FLAG_RESPONSE
), method
);
2141 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2142 static int __sip_semi_ack(struct sip_pvt
*p
, int seqno
, int resp
, int sipmethod
)
2144 struct sip_pkt
*cur
;
2147 for (cur
= p
->packets
; cur
; cur
= cur
->next
) {
2148 if (cur
->seqno
== seqno
&& ast_test_flag(cur
, FLAG_RESPONSE
) == resp
&&
2149 (ast_test_flag(cur
, FLAG_RESPONSE
) || method_match(sipmethod
, cur
->data
))) {
2150 /* this is our baby */
2151 if (cur
->retransid
> -1) {
2152 if (option_debug
> 3 && sipdebug
)
2153 ast_log(LOG_DEBUG
, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur
->retransid
, sip_methods
[sipmethod
].text
);
2154 ast_sched_del(sched
, cur
->retransid
);
2155 cur
->retransid
= -1;
2162 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");
2167 /*! \brief Copy SIP request, parse it */
2168 static void parse_copy(struct sip_request
*dst
, const struct sip_request
*src
)
2170 memset(dst
, 0, sizeof(*dst
));
2171 memcpy(dst
->data
, src
->data
, sizeof(dst
->data
));
2172 dst
->len
= src
->len
;
2176 /*! \brief add a blank line if no body */
2177 static void add_blank(struct sip_request
*req
)
2180 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2181 snprintf(req
->data
+ req
->len
, sizeof(req
->data
) - req
->len
, "\r\n");
2182 req
->len
+= strlen(req
->data
+ req
->len
);
2186 /*! \brief Transmit response on SIP request*/
2187 static int send_response(struct sip_pvt
*p
, struct sip_request
*req
, enum xmittype reliable
, int seqno
)
2192 if (sip_debug_test_pvt(p
)) {
2193 const struct sockaddr_in
*dst
= sip_real_dst(p
);
2195 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
2196 reliable
? "Reliably " : "", sip_nat_mode(p
),
2197 ast_inet_ntoa(dst
->sin_addr
),
2198 ntohs(dst
->sin_port
), req
->data
);
2200 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
)) {
2201 struct sip_request tmp
;
2202 parse_copy(&tmp
, req
);
2203 append_history(p
, reliable
? "TxRespRel" : "TxResp", "%s / %s - %s", tmp
.data
, get_header(&tmp
, "CSeq"),
2204 (tmp
.method
== SIP_RESPONSE
|| tmp
.method
== SIP_UNKNOWN
) ? tmp
.rlPart2
: sip_methods
[tmp
.method
].text
);
2207 __sip_reliable_xmit(p
, seqno
, 1, req
->data
, req
->len
, (reliable
== XMIT_CRITICAL
), req
->method
) :
2208 __sip_xmit(p
, req
->data
, req
->len
);
2214 /*! \brief Send SIP Request to the other part of the dialogue */
2215 static int send_request(struct sip_pvt
*p
, struct sip_request
*req
, enum xmittype reliable
, int seqno
)
2220 if (sip_debug_test_pvt(p
)) {
2221 if (ast_test_flag(&p
->flags
[0], SIP_NAT_ROUTE
))
2222 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
);
2224 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
);
2226 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
)) {
2227 struct sip_request tmp
;
2228 parse_copy(&tmp
, req
);
2229 append_history(p
, reliable
? "TxReqRel" : "TxReq", "%s / %s - %s", tmp
.data
, get_header(&tmp
, "CSeq"), sip_methods
[tmp
.method
].text
);
2232 __sip_reliable_xmit(p
, seqno
, 0, req
->data
, req
->len
, (reliable
> 1), req
->method
) :
2233 __sip_xmit(p
, req
->data
, req
->len
);
2237 /*! \brief Locate closing quote in a string, skipping escaped quotes.
2238 * optionally with a limit on the search.
2239 * start must be past the first quote.
2241 static const char *find_closing_quote(const char *start
, const char *lim
)
2243 char last_char
= '\0';
2245 for (s
= start
; *s
&& s
!= lim
; last_char
= *s
++) {
2246 if (*s
== '"' && last_char
!= '\\')
2252 /*! \brief Pick out text in brackets from character string
2253 \return pointer to terminated stripped string
2254 \param tmp input string that will be modified
2257 "foo" <bar> valid input, returns bar
2258 foo returns the whole string
2259 < "foo ... > returns the string between brackets
2260 < "foo... bogus (missing closing bracket), returns the whole string
2261 XXX maybe should still skip the opening bracket
2263 static char *get_in_brackets(char *tmp
)
2265 const char *parse
= tmp
;
2266 char *first_bracket
;
2269 * Skip any quoted text until we find the part in brackets.
2270 * On any error give up and return the full string.
2272 while ( (first_bracket
= strchr(parse
, '<')) ) {
2273 char *first_quote
= strchr(parse
, '"');
2275 if (!first_quote
|| first_quote
> first_bracket
)
2276 break; /* no need to look at quoted part */
2277 /* the bracket is within quotes, so ignore it */
2278 parse
= find_closing_quote(first_quote
+ 1, NULL
);
2279 if (!*parse
) { /* not found, return full string ? */
2280 /* XXX or be robust and return in-bracket part ? */
2281 ast_log(LOG_WARNING
, "No closing quote found in '%s'\n", tmp
);
2286 if (first_bracket
) {
2287 char *second_bracket
= strchr(first_bracket
+ 1, '>');
2288 if (second_bracket
) {
2289 *second_bracket
= '\0';
2290 tmp
= first_bracket
+ 1;
2292 ast_log(LOG_WARNING
, "No closing bracket found in '%s'\n", tmp
);
2298 /*! \brief Send SIP MESSAGE text within a call
2299 Called from PBX core sendtext() application */
2300 static int sip_sendtext(struct ast_channel
*ast
, const char *text
)
2302 struct sip_pvt
*p
= ast
->tech_pvt
;
2303 int debug
= sip_debug_test_pvt(p
);
2306 ast_verbose("Sending text %s on %s\n", text
, ast
->name
);
2309 if (ast_strlen_zero(text
))
2312 ast_verbose("Really sending text %s on %s\n", text
, ast
->name
);
2313 transmit_message_with_text(p
, text
);
2317 /*! \brief Update peer object in realtime storage
2318 If the Asterisk system name is set in asterisk.conf, we will use
2319 that name and store that in the "regserver" field in the sippeers
2320 table to facilitate multi-server setups.
2322 static void realtime_update_peer(const char *peername
, struct sockaddr_in
*sin
, const char *username
, const char *fullcontact
, int expirey
)
2325 char ipaddr
[INET_ADDRSTRLEN
];
2326 char regseconds
[20];
2328 char *sysname
= ast_config_AST_SYSTEM_NAME
;
2329 char *syslabel
= NULL
;
2331 time_t nowtime
= time(NULL
) + expirey
;
2332 const char *fc
= fullcontact
? "fullcontact" : NULL
;
2334 snprintf(regseconds
, sizeof(regseconds
), "%d", (int)nowtime
); /* Expiration time */
2335 ast_copy_string(ipaddr
, ast_inet_ntoa(sin
->sin_addr
), sizeof(ipaddr
));
2336 snprintf(port
, sizeof(port
), "%d", ntohs(sin
->sin_port
));
2338 if (ast_strlen_zero(sysname
)) /* No system name, disable this */
2340 else if (ast_test_flag(&global_flags
[1], SIP_PAGE2_RTSAVE_SYSNAME
))
2341 syslabel
= "regserver";
2344 ast_update_realtime("sippeers", "name", peername
, "ipaddr", ipaddr
,
2345 "port", port
, "regseconds", regseconds
,
2346 "username", username
, fc
, fullcontact
, syslabel
, sysname
, NULL
); /* note fc and syslabel _can_ be NULL */
2348 ast_update_realtime("sippeers", "name", peername
, "ipaddr", ipaddr
,
2349 "port", port
, "regseconds", regseconds
,
2350 "username", username
, syslabel
, sysname
, NULL
); /* note syslabel _can_ be NULL */
2353 /*! \brief Automatically add peer extension to dial plan */
2354 static void register_peer_exten(struct sip_peer
*peer
, int onoff
)
2357 char *stringp
, *ext
, *context
;
2359 /* XXX note that global_regcontext is both a global 'enable' flag and
2360 * the name of the global regexten context, if not specified
2363 if (ast_strlen_zero(global_regcontext
))
2366 ast_copy_string(multi
, S_OR(peer
->regexten
, peer
->name
), sizeof(multi
));
2368 while ((ext
= strsep(&stringp
, "&"))) {
2369 if ((context
= strchr(ext
, '@'))) {
2370 *context
++ = '\0'; /* split ext@context */
2371 if (!ast_context_find(context
)) {
2372 ast_log(LOG_WARNING
, "Context %s must exist in regcontext= in sip.conf!\n", context
);
2376 context
= global_regcontext
;
2379 ast_add_extension(context
, 1, ext
, 1, NULL
, NULL
, "Noop",
2380 ast_strdup(peer
->name
), ast_free
, "SIP");
2382 ast_context_remove_extension(context
, ext
, 1, NULL
);
2386 /*! \brief Destroy peer object from memory */
2387 static void sip_destroy_peer(struct sip_peer
*peer
)
2389 if (option_debug
> 2)
2390 ast_log(LOG_DEBUG
, "Destroying SIP peer %s\n", peer
->name
);
2392 /* Delete it, it needs to disappear */
2394 sip_destroy(peer
->call
);
2396 if (peer
->mwipvt
) /* We have an active subscription, delete it */
2397 sip_destroy(peer
->mwipvt
);
2399 if (peer
->chanvars
) {
2400 ast_variables_destroy(peer
->chanvars
);
2401 peer
->chanvars
= NULL
;
2403 if (peer
->expire
> -1)
2404 ast_sched_del(sched
, peer
->expire
);
2406 if (peer
->pokeexpire
> -1)
2407 ast_sched_del(sched
, peer
->pokeexpire
);
2408 register_peer_exten(peer
, FALSE
);
2409 ast_free_ha(peer
->ha
);
2410 if (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_SELFDESTRUCT
))
2412 else if (ast_test_flag(&peer
->flags
[0], SIP_REALTIME
))
2416 clear_realm_authentication(peer
->auth
);
2421 /*! \brief Update peer data in database (if used) */
2422 static void update_peer(struct sip_peer
*p
, int expiry
)
2424 int rtcachefriends
= ast_test_flag(&p
->flags
[1], SIP_PAGE2_RTCACHEFRIENDS
);
2425 if (ast_test_flag(&global_flags
[1], SIP_PAGE2_RTUPDATE
) &&
2426 (ast_test_flag(&p
->flags
[0], SIP_REALTIME
) || rtcachefriends
)) {
2427 realtime_update_peer(p
->name
, &p
->addr
, p
->username
, rtcachefriends
? p
->fullcontact
: NULL
, expiry
);
2432 /*! \brief realtime_peer: Get peer from realtime storage
2433 * Checks the "sippeers" realtime family from extconfig.conf
2434 * \todo Consider adding check of port address when matching here to follow the same
2435 * algorithm as for static peers. Will we break anything by adding that?
2437 static struct sip_peer
*realtime_peer(const char *newpeername
, struct sockaddr_in
*sin
)
2439 struct sip_peer
*peer
;
2440 struct ast_variable
*var
= NULL
;
2441 struct ast_variable
*tmp
;
2442 char ipaddr
[INET_ADDRSTRLEN
];
2444 /* First check on peer name */
2446 var
= ast_load_realtime("sippeers", "name", newpeername
, NULL
);
2447 else if (sin
) { /* Then check on IP address for dynamic peers */
2448 ast_copy_string(ipaddr
, ast_inet_ntoa(sin
->sin_addr
), sizeof(ipaddr
));
2449 var
= ast_load_realtime("sippeers", "host", ipaddr
, NULL
); /* First check for fixed IP hosts */
2451 var
= ast_load_realtime("sippeers", "ipaddr", ipaddr
, NULL
); /* Then check for registred hosts */
2457 for (tmp
= var
; tmp
; tmp
= tmp
->next
) {
2458 /* If this is type=user, then skip this object. */
2459 if (!strcasecmp(tmp
->name
, "type") &&
2460 !strcasecmp(tmp
->value
, "user")) {
2461 ast_variables_destroy(var
);
2463 } else if (!newpeername
&& !strcasecmp(tmp
->name
, "name")) {
2464 newpeername
= tmp
->value
;
2468 if (!newpeername
) { /* Did not find peer in realtime */
2469 ast_log(LOG_WARNING
, "Cannot Determine peer name ip=%s\n", ipaddr
);
2470 ast_variables_destroy(var
);
2474 /* Peer found in realtime, now build it in memory */
2475 peer
= build_peer(newpeername
, var
, NULL
, !ast_test_flag(&global_flags
[1], SIP_PAGE2_RTCACHEFRIENDS
));
2477 ast_variables_destroy(var
);
2481 if (ast_test_flag(&global_flags
[1], SIP_PAGE2_RTCACHEFRIENDS
)) {
2483 ast_copy_flags(&peer
->flags
[1],&global_flags
[1], SIP_PAGE2_RTAUTOCLEAR
|SIP_PAGE2_RTCACHEFRIENDS
);
2484 if (ast_test_flag(&global_flags
[1], SIP_PAGE2_RTAUTOCLEAR
)) {
2485 if (peer
->expire
> -1) {
2486 ast_sched_del(sched
, peer
->expire
);
2488 peer
->expire
= ast_sched_add(sched
, (global_rtautoclear
) * 1000, expire_register
, (void *)peer
);
2490 ASTOBJ_CONTAINER_LINK(&peerl
,peer
);
2492 ast_set_flag(&peer
->flags
[0], SIP_REALTIME
);
2494 ast_variables_destroy(var
);
2499 /*! \brief Support routine for find_peer */
2500 static int sip_addrcmp(char *name
, struct sockaddr_in
*sin
)
2502 /* We know name is the first field, so we can cast */
2503 struct sip_peer
*p
= (struct sip_peer
*) name
;
2504 return !(!inaddrcmp(&p
->addr
, sin
) ||
2505 (ast_test_flag(&p
->flags
[0], SIP_INSECURE_PORT
) &&
2506 (p
->addr
.sin_addr
.s_addr
== sin
->sin_addr
.s_addr
)));
2509 /*! \brief Locate peer by name or ip address
2510 * This is used on incoming SIP message to find matching peer on ip
2511 or outgoing message to find matching peer on name */
2512 static struct sip_peer
*find_peer(const char *peer
, struct sockaddr_in
*sin
, int realtime
)
2514 struct sip_peer
*p
= NULL
;
2517 p
= ASTOBJ_CONTAINER_FIND(&peerl
, peer
);
2519 p
= ASTOBJ_CONTAINER_FIND_FULL(&peerl
, sin
, name
, sip_addr_hashfunc
, 1, sip_addrcmp
);
2522 p
= realtime_peer(peer
, sin
);
2527 /*! \brief Remove user object from in-memory storage */
2528 static void sip_destroy_user(struct sip_user
*user
)
2530 if (option_debug
> 2)
2531 ast_log(LOG_DEBUG
, "Destroying user object from memory: %s\n", user
->name
);
2532 ast_free_ha(user
->ha
);
2533 if (user
->chanvars
) {
2534 ast_variables_destroy(user
->chanvars
);
2535 user
->chanvars
= NULL
;
2537 if (ast_test_flag(&user
->flags
[0], SIP_REALTIME
))
2544 /*! \brief Load user from realtime storage
2545 * Loads user from "sipusers" category in realtime (extconfig.conf)
2546 * Users are matched on From: user name (the domain in skipped) */
2547 static struct sip_user
*realtime_user(const char *username
)
2549 struct ast_variable
*var
;
2550 struct ast_variable
*tmp
;
2551 struct sip_user
*user
= NULL
;
2553 var
= ast_load_realtime("sipusers", "name", username
, NULL
);
2558 for (tmp
= var
; tmp
; tmp
= tmp
->next
) {
2559 if (!strcasecmp(tmp
->name
, "type") &&
2560 !strcasecmp(tmp
->value
, "peer")) {
2561 ast_variables_destroy(var
);
2566 user
= build_user(username
, var
, !ast_test_flag(&global_flags
[1], SIP_PAGE2_RTCACHEFRIENDS
));
2568 if (!user
) { /* No user found */
2569 ast_variables_destroy(var
);
2573 if (ast_test_flag(&global_flags
[1], SIP_PAGE2_RTCACHEFRIENDS
)) {
2574 ast_set_flag(&user
->flags
[1], SIP_PAGE2_RTCACHEFRIENDS
);
2576 ASTOBJ_CONTAINER_LINK(&userl
,user
);
2578 /* Move counter from s to r... */
2581 ast_set_flag(&user
->flags
[0], SIP_REALTIME
);
2583 ast_variables_destroy(var
);
2587 /*! \brief Locate user by name
2588 * Locates user by name (From: sip uri user name part) first
2589 * from in-memory list (static configuration) then from
2590 * realtime storage (defined in extconfig.conf) */
2591 static struct sip_user
*find_user(const char *name
, int realtime
)
2593 struct sip_user
*u
= ASTOBJ_CONTAINER_FIND(&userl
, name
);
2595 u
= realtime_user(name
);
2599 /*! \brief Set nat mode on the various data sockets */
2600 static void do_setnat(struct sip_pvt
*p
, int natflags
)
2602 const char *mode
= natflags
? "On" : "Off";
2606 ast_log(LOG_DEBUG
, "Setting NAT on RTP to %s\n", mode
);
2607 ast_rtp_setnat(p
->rtp
, natflags
);
2611 ast_log(LOG_DEBUG
, "Setting NAT on VRTP to %s\n", mode
);
2612 ast_rtp_setnat(p
->vrtp
, natflags
);
2616 ast_log(LOG_DEBUG
, "Setting NAT on UDPTL to %s\n", mode
);
2617 ast_udptl_setnat(p
->udptl
, natflags
);
2621 /*! \brief Create address structure from peer reference.
2622 * return -1 on error, 0 on success.
2624 static int create_addr_from_peer(struct sip_pvt
*dialog
, struct sip_peer
*peer
)
2626 if ((peer
->addr
.sin_addr
.s_addr
|| peer
->defaddr
.sin_addr
.s_addr
) &&
2627 (!peer
->maxms
|| ((peer
->lastms
>= 0) && (peer
->lastms
<= peer
->maxms
)))) {
2628 dialog
->sa
= (peer
->addr
.sin_addr
.s_addr
) ? peer
->addr
: peer
->defaddr
;
2629 dialog
->recv
= dialog
->sa
;
2633 ast_copy_flags(&dialog
->flags
[0], &peer
->flags
[0], SIP_FLAGS_TO_COPY
);
2634 ast_copy_flags(&dialog
->flags
[1], &peer
->flags
[1], SIP_PAGE2_FLAGS_TO_COPY
);
2635 dialog
->capability
= peer
->capability
;
2636 if ((!ast_test_flag(&dialog
->flags
[1], SIP_PAGE2_VIDEOSUPPORT
) || !(dialog
->capability
& AST_FORMAT_VIDEO_MASK
)) && dialog
->vrtp
) {
2637 ast_rtp_destroy(dialog
->vrtp
);
2638 dialog
->vrtp
= NULL
;
2640 dialog
->prefs
= peer
->prefs
;
2641 if (ast_test_flag(&dialog
->flags
[1], SIP_PAGE2_T38SUPPORT
)) {
2642 dialog
->t38
.capability
= global_t38_capability
;
2643 if (dialog
->udptl
) {
2644 if (ast_udptl_get_error_correction_scheme(dialog
->udptl
) == UDPTL_ERROR_CORRECTION_FEC
)
2645 dialog
->t38
.capability
|= T38FAX_UDP_EC_FEC
;
2646 else if (ast_udptl_get_error_correction_scheme(dialog
->udptl
) == UDPTL_ERROR_CORRECTION_REDUNDANCY
)
2647 dialog
->t38
.capability
|= T38FAX_UDP_EC_REDUNDANCY
;
2648 else if (ast_udptl_get_error_correction_scheme(dialog
->udptl
) == UDPTL_ERROR_CORRECTION_NONE
)
2649 dialog
->t38
.capability
|= T38FAX_UDP_EC_NONE
;
2650 dialog
->t38
.capability
|= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF
;
2651 if (option_debug
> 1)
2652 ast_log(LOG_DEBUG
,"Our T38 capability (%d)\n", dialog
->t38
.capability
);
2654 dialog
->t38
.jointcapability
= dialog
->t38
.capability
;
2655 } else if (dialog
->udptl
) {
2656 ast_udptl_destroy(dialog
->udptl
);
2657 dialog
->udptl
= NULL
;
2659 do_setnat(dialog
, ast_test_flag(&dialog
->flags
[0], SIP_NAT
) & SIP_NAT_ROUTE
);
2662 ast_rtp_setdtmf(dialog
->rtp
, ast_test_flag(&dialog
->flags
[0], SIP_DTMF
) == SIP_DTMF_RFC2833
);
2663 ast_rtp_setdtmfcompensate(dialog
->rtp
, ast_test_flag(&dialog
->flags
[1], SIP_PAGE2_RFC2833_COMPENSATE
));
2664 ast_rtp_set_rtptimeout(dialog
->rtp
, peer
->rtptimeout
);
2665 ast_rtp_set_rtpholdtimeout(dialog
->rtp
, peer
->rtpholdtimeout
);
2666 ast_rtp_set_rtpkeepalive(dialog
->rtp
, peer
->rtpkeepalive
);
2667 /* Set Frame packetization */
2668 ast_rtp_codec_setpref(dialog
->rtp
, &dialog
->prefs
);
2669 dialog
->autoframing
= peer
->autoframing
;
2672 ast_rtp_setdtmf(dialog
->vrtp
, 0);
2673 ast_rtp_setdtmfcompensate(dialog
->vrtp
, 0);
2674 ast_rtp_set_rtptimeout(dialog
->vrtp
, peer
->rtptimeout
);
2675 ast_rtp_set_rtpholdtimeout(dialog
->vrtp
, peer
->rtpholdtimeout
);
2676 ast_rtp_set_rtpkeepalive(dialog
->vrtp
, peer
->rtpkeepalive
);
2679 ast_string_field_set(dialog
, peername
, peer
->username
);
2680 ast_string_field_set(dialog
, authname
, peer
->username
);
2681 ast_string_field_set(dialog
, username
, peer
->username
);
2682 ast_string_field_set(dialog
, peersecret
, peer
->secret
);
2683 ast_string_field_set(dialog
, peermd5secret
, peer
->md5secret
);
2684 ast_string_field_set(dialog
, mohsuggest
, peer
->mohsuggest
);
2685 ast_string_field_set(dialog
, mohinterpret
, peer
->mohinterpret
);
2686 ast_string_field_set(dialog
, tohost
, peer
->tohost
);
2687 ast_string_field_set(dialog
, fullcontact
, peer
->fullcontact
);
2688 if (!dialog
->initreq
.headers
&& !ast_strlen_zero(peer
->fromdomain
)) {
2691 tmpcall
= ast_strdupa(dialog
->callid
);
2692 c
= strchr(tmpcall
, '@');
2695 ast_string_field_build(dialog
, callid
, "%s@%s", tmpcall
, peer
->fromdomain
);
2698 if (ast_strlen_zero(dialog
->tohost
))
2699 ast_string_field_set(dialog
, tohost
, ast_inet_ntoa(dialog
->sa
.sin_addr
));
2700 if (!ast_strlen_zero(peer
->fromdomain
))
2701 ast_string_field_set(dialog
, fromdomain
, peer
->fromdomain
);
2702 if (!ast_strlen_zero(peer
->fromuser
))
2703 ast_string_field_set(dialog
, fromuser
, peer
->fromuser
);
2704 dialog
->maxtime
= peer
->maxms
;
2705 dialog
->callgroup
= peer
->callgroup
;
2706 dialog
->pickupgroup
= peer
->pickupgroup
;
2707 dialog
->allowtransfer
= peer
->allowtransfer
;
2708 /* Set timer T1 to RTT for this peer (if known by qualify=) */
2709 /* Minimum is settable or default to 100 ms */
2710 if (peer
->maxms
&& peer
->lastms
)
2711 dialog
->timer_t1
= peer
->lastms
< global_t1min
? global_t1min
: peer
->lastms
;
2712 if ((ast_test_flag(&dialog
->flags
[0], SIP_DTMF
) == SIP_DTMF_RFC2833
) ||
2713 (ast_test_flag(&dialog
->flags
[0], SIP_DTMF
) == SIP_DTMF_AUTO
))
2714 dialog
->noncodeccapability
|= AST_RTP_DTMF
;
2716 dialog
->noncodeccapability
&= ~AST_RTP_DTMF
;
2717 ast_string_field_set(dialog
, context
, peer
->context
);
2718 dialog
->rtptimeout
= peer
->rtptimeout
;
2719 if (peer
->call_limit
)
2720 ast_set_flag(&dialog
->flags
[0], SIP_CALL_LIMIT
);
2721 dialog
->maxcallbitrate
= peer
->maxcallbitrate
;
2726 /*! \brief create address structure from peer name
2727 * Or, if peer not found, find it in the global DNS
2728 * returns TRUE (-1) on failure, FALSE on success */
2729 static int create_addr(struct sip_pvt
*dialog
, const char *opeer
)
2732 struct ast_hostent ahp
;
2736 char host
[MAXHOSTNAMELEN
], *hostn
;
2739 ast_copy_string(peer
, opeer
, sizeof(peer
));
2740 port
= strchr(peer
, ':');
2743 dialog
->sa
.sin_family
= AF_INET
;
2744 dialog
->timer_t1
= 500; /* Default SIP retransmission timer T1 (RFC 3261) */
2745 p
= find_peer(peer
, NULL
, 1);
2748 int res
= create_addr_from_peer(dialog
, p
);
2749 ASTOBJ_UNREF(p
, sip_destroy_peer
);
2753 portno
= port
? atoi(port
) : STANDARD_SIP_PORT
;
2755 char service
[MAXHOSTNAMELEN
];
2759 snprintf(service
, sizeof(service
), "_sip._udp.%s", peer
);
2760 ret
= ast_get_srv(NULL
, host
, sizeof(host
), &tportno
, service
);
2766 hp
= ast_gethostbyname(hostn
, &ahp
);
2768 ast_log(LOG_WARNING
, "No such host: %s\n", peer
);
2771 ast_string_field_set(dialog
, tohost
, peer
);
2772 memcpy(&dialog
->sa
.sin_addr
, hp
->h_addr
, sizeof(dialog
->sa
.sin_addr
));
2773 dialog
->sa
.sin_port
= htons(portno
);
2774 dialog
->recv
= dialog
->sa
;
2778 /*! \brief Scheduled congestion on a call */
2779 static int auto_congest(void *nothing
)
2781 struct sip_pvt
*p
= nothing
;
2783 ast_mutex_lock(&p
->lock
);
2786 /* XXX fails on possible deadlock */
2787 if (!ast_channel_trylock(p
->owner
)) {
2788 ast_log(LOG_NOTICE
, "Auto-congesting %s\n", p
->owner
->name
);
2789 append_history(p
, "Cong", "Auto-congesting (timer)");
2790 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
2791 ast_channel_unlock(p
->owner
);
2794 ast_mutex_unlock(&p
->lock
);
2799 /*! \brief Initiate SIP call from PBX
2800 * used from the dial() application */
2801 static int sip_call(struct ast_channel
*ast
, char *dest
, int timeout
)
2803 int res
, xmitres
= 0;
2805 struct varshead
*headp
;
2806 struct ast_var_t
*current
;
2807 const char *referer
= NULL
; /* SIP refererer */
2810 if ((ast
->_state
!= AST_STATE_DOWN
) && (ast
->_state
!= AST_STATE_RESERVED
)) {
2811 ast_log(LOG_WARNING
, "sip_call called on %s, neither down nor reserved\n", ast
->name
);
2815 /* Check whether there is vxml_url, distinctive ring variables */
2816 headp
=&ast
->varshead
;
2817 AST_LIST_TRAVERSE(headp
,current
,entries
) {
2818 /* Check whether there is a VXML_URL variable */
2819 if (!p
->options
->vxml_url
&& !strcasecmp(ast_var_name(current
), "VXML_URL")) {
2820 p
->options
->vxml_url
= ast_var_value(current
);
2821 } else if (!p
->options
->uri_options
&& !strcasecmp(ast_var_name(current
), "SIP_URI_OPTIONS")) {
2822 p
->options
->uri_options
= ast_var_value(current
);
2823 } else if (!p
->options
->distinctive_ring
&& !strcasecmp(ast_var_name(current
), "ALERT_INFO")) {
2824 /* Check whether there is a ALERT_INFO variable */
2825 p
->options
->distinctive_ring
= ast_var_value(current
);
2826 } else if (!p
->options
->addsipheaders
&& !strncasecmp(ast_var_name(current
), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2827 /* Check whether there is a variable with a name starting with SIPADDHEADER */
2828 p
->options
->addsipheaders
= 1;
2829 } else if (!strcasecmp(ast_var_name(current
), "SIPTRANSFER")) {
2830 /* This is a transfered call */
2831 p
->options
->transfer
= 1;
2832 } else if (!strcasecmp(ast_var_name(current
), "SIPTRANSFER_REFERER")) {
2833 /* This is the referer */
2834 referer
= ast_var_value(current
);
2835 } else if (!strcasecmp(ast_var_name(current
), "SIPTRANSFER_REPLACES")) {
2836 /* We're replacing a call. */
2837 p
->options
->replaces
= ast_var_value(current
);
2838 } else if (!strcasecmp(ast_var_name(current
), "T38CALL")) {
2839 p
->t38
.state
= T38_LOCAL_DIRECT
;
2841 ast_log(LOG_DEBUG
,"T38State change to %d on channel %s\n", p
->t38
.state
, ast
->name
);
2847 ast_set_flag(&p
->flags
[0], SIP_OUTGOING
);
2849 if (p
->options
->transfer
) {
2853 if (sipdebug
&& option_debug
> 2)
2854 ast_log(LOG_DEBUG
, "Call for %s transfered by %s\n", p
->username
, referer
);
2855 snprintf(buf
, sizeof(buf
)-1, "-> %s (via %s)", p
->cid_name
, referer
);
2857 snprintf(buf
, sizeof(buf
)-1, "-> %s", p
->cid_name
);
2858 ast_string_field_set(p
, cid_name
, buf
);
2861 ast_log(LOG_DEBUG
, "Outgoing Call for %s\n", p
->username
);
2863 res
= update_call_counter(p
, INC_CALL_RINGING
);
2865 p
->callingpres
= ast
->cid
.cid_pres
;
2866 p
->jointcapability
= ast_translate_available_formats(p
->capability
, p
->prefcodec
);
2867 p
->jointnoncodeccapability
= p
->noncodeccapability
;
2869 /* If there are no audio formats left to offer, punt */
2870 if (!(p
->jointcapability
& AST_FORMAT_AUDIO_MASK
)) {
2871 ast_log(LOG_WARNING
, "No audio format found to offer. Cancelling call to %s\n", p
->username
);
2874 p
->t38
.jointcapability
= p
->t38
.capability
;
2875 if (option_debug
> 1)
2876 ast_log(LOG_DEBUG
,"Our T38 capability (%d), joint T38 capability (%d)\n", p
->t38
.capability
, p
->t38
.jointcapability
);
2877 xmitres
= transmit_invite(p
, SIP_INVITE
, 1, 2);
2878 if (xmitres
== XMIT_ERROR
)
2879 return -1; /* Transmission error */
2881 p
->invitestate
= INV_CALLING
;
2883 /* Initialize auto-congest time */
2884 p
->initid
= ast_sched_add(sched
, p
->maxtime
? (p
->maxtime
* 4) : SIP_TRANS_TIMEOUT
, auto_congest
, p
);
2890 /*! \brief Destroy registry object
2891 Objects created with the register= statement in static configuration */
2892 static void sip_registry_destroy(struct sip_registry
*reg
)
2895 if (option_debug
> 2)
2896 ast_log(LOG_DEBUG
, "Destroying registry entry for %s@%s\n", reg
->username
, reg
->hostname
);
2899 /* Clear registry before destroying to ensure
2900 we don't get reentered trying to grab the registry lock */
2901 reg
->call
->registry
= NULL
;
2902 if (option_debug
> 2)
2903 ast_log(LOG_DEBUG
, "Destroying active SIP dialog for registry %s@%s\n", reg
->username
, reg
->hostname
);
2904 sip_destroy(reg
->call
);
2906 if (reg
->expire
> -1)
2907 ast_sched_del(sched
, reg
->expire
);
2908 if (reg
->timeout
> -1)
2909 ast_sched_del(sched
, reg
->timeout
);
2910 ast_string_field_free_pools(reg
);
2916 /*! \brief Execute destruction of SIP dialog structure, release memory */
2917 static void __sip_destroy(struct sip_pvt
*p
, int lockowner
)
2919 struct sip_pvt
*cur
, *prev
= NULL
;
2922 if (sip_debug_test_pvt(p
) || option_debug
> 2)
2923 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p
->callid
, sip_methods
[p
->method
].text
);
2925 if (ast_test_flag(&p
->flags
[0], SIP_INC_COUNT
)) {
2926 update_call_counter(p
, DEC_CALL_LIMIT
);
2927 if (option_debug
> 1)
2928 ast_log(LOG_DEBUG
, "This call did not properly clean up call limits. Call ID %s\n", p
->callid
);
2931 /* Remove link from peer to subscription of MWI */
2932 if (p
->relatedpeer
&& p
->relatedpeer
->mwipvt
)
2933 p
->relatedpeer
->mwipvt
= NULL
;
2936 sip_dump_history(p
);
2941 if (p
->stateid
> -1)
2942 ast_extension_state_del(p
->stateid
, NULL
);
2944 ast_sched_del(sched
, p
->initid
);
2945 if (p
->autokillid
> -1)
2946 ast_sched_del(sched
, p
->autokillid
);
2949 ast_rtp_destroy(p
->rtp
);
2951 ast_rtp_destroy(p
->vrtp
);
2953 ast_udptl_destroy(p
->udptl
);
2957 free_old_route(p
->route
);
2961 if (p
->registry
->call
== p
)
2962 p
->registry
->call
= NULL
;
2963 ASTOBJ_UNREF(p
->registry
, sip_registry_destroy
);
2966 /* Unlink us from the owner if we have one */
2969 ast_channel_lock(p
->owner
);
2971 ast_log(LOG_DEBUG
, "Detaching from %s\n", p
->owner
->name
);
2972 p
->owner
->tech_pvt
= NULL
;
2974 ast_channel_unlock(p
->owner
);
2978 struct sip_history
*hist
;
2979 while( (hist
= AST_LIST_REMOVE_HEAD(p
->history
, list
)) )
2985 for (prev
= NULL
, cur
= iflist
; cur
; prev
= cur
, cur
= cur
->next
) {
2987 UNLINK(cur
, iflist
, prev
);
2992 ast_log(LOG_WARNING
, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p
->callid
);
2996 /* remove all current packets in this dialog */
2997 while((cp
= p
->packets
)) {
2998 p
->packets
= p
->packets
->next
;
2999 if (cp
->retransid
> -1)
3000 ast_sched_del(sched
, cp
->retransid
);
3004 ast_variables_destroy(p
->chanvars
);
3007 ast_mutex_destroy(&p
->lock
);
3009 ast_string_field_free_pools(p
);
3014 /*! \brief update_call_counter: Handle call_limit for SIP users
3015 * Setting a call-limit will cause calls above the limit not to be accepted.
3017 * Remember that for a type=friend, there's one limit for the user and
3018 * another for the peer, not a combined call limit.
3019 * This will cause unexpected behaviour in subscriptions, since a "friend"
3020 * is *two* devices in Asterisk, not one.
3022 * Thought: For realtime, we should propably update storage with inuse counter...
3024 * \return 0 if call is ok (no call limit, below treshold)
3025 * -1 on rejection of call
3028 static int update_call_counter(struct sip_pvt
*fup
, int event
)
3031 int *inuse
= NULL
, *call_limit
= NULL
, *inringing
= NULL
;
3032 int outgoing
= ast_test_flag(&fup
->flags
[1], SIP_PAGE2_OUTGOING_CALL
);
3033 struct sip_user
*u
= NULL
;
3034 struct sip_peer
*p
= NULL
;
3036 if (option_debug
> 2)
3037 ast_log(LOG_DEBUG
, "Updating call counter for %s call\n", outgoing
? "outgoing" : "incoming");
3038 /* Test if we need to check call limits, in order to avoid
3039 realtime lookups if we do not need it */
3040 if (!ast_test_flag(&fup
->flags
[0], SIP_CALL_LIMIT
))
3043 ast_copy_string(name
, fup
->username
, sizeof(name
));
3045 /* Check the list of users only for incoming calls */
3046 if (global_limitonpeers
== FALSE
&& !outgoing
&& (u
= find_user(name
, 1))) {
3048 call_limit
= &u
->call_limit
;
3050 } else if ( (p
= find_peer(ast_strlen_zero(fup
->peername
) ? name
: fup
->peername
, NULL
, 1) ) ) { /* Try to find peer */
3052 call_limit
= &p
->call_limit
;
3053 inringing
= &p
->inRinging
;
3054 ast_copy_string(name
, fup
->peername
, sizeof(name
));
3057 if (option_debug
> 1)
3058 ast_log(LOG_DEBUG
, "%s is not a local device, no call limit\n", name
);
3063 /* incoming and outgoing affects the inUse counter */
3064 case DEC_CALL_LIMIT
:
3066 if (ast_test_flag(&fup
->flags
[0], SIP_INC_COUNT
)) {
3068 ast_clear_flag(&fup
->flags
[0], SIP_INC_COUNT
);
3074 if (ast_test_flag(&fup
->flags
[1], SIP_PAGE2_INC_RINGING
)) {
3078 ast_log(LOG_WARNING
, "Inringing for peer '%s' < 0?\n", fup
->peername
);
3079 ast_clear_flag(&fup
->flags
[1], SIP_PAGE2_INC_RINGING
);
3082 if (ast_test_flag(&fup
->flags
[1], SIP_PAGE2_CALL_ONHOLD
) && global_notifyhold
)
3083 sip_peer_hold(fup
, 0);
3084 if (option_debug
> 1 || sipdebug
) {
3085 ast_log(LOG_DEBUG
, "Call %s %s '%s' removed from call limit %d\n", outgoing
? "to" : "from", u
? "user":"peer", name
, *call_limit
);
3089 case INC_CALL_RINGING
:
3090 case INC_CALL_LIMIT
:
3091 if (*call_limit
> 0 ) {
3092 if (*inuse
>= *call_limit
) {
3093 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
);
3095 ASTOBJ_UNREF(u
, sip_destroy_user
);
3097 ASTOBJ_UNREF(p
, sip_destroy_peer
);
3101 if (inringing
&& (event
== INC_CALL_RINGING
)) {
3102 if (!ast_test_flag(&fup
->flags
[1], SIP_PAGE2_INC_RINGING
)) {
3104 ast_set_flag(&fup
->flags
[1], SIP_PAGE2_INC_RINGING
);
3109 ast_set_flag(&fup
->flags
[0], SIP_INC_COUNT
);
3110 if (option_debug
> 1 || sipdebug
) {
3111 ast_log(LOG_DEBUG
, "Call %s %s '%s' is %d out of %d\n", outgoing
? "to" : "from", u
? "user":"peer", name
, *inuse
, *call_limit
);
3115 case DEC_CALL_RINGING
:
3117 if (ast_test_flag(&fup
->flags
[1], SIP_PAGE2_INC_RINGING
)) {
3121 ast_log(LOG_WARNING
, "Inringing for peer '%s' < 0?\n", p
->name
);
3122 ast_clear_flag(&fup
->flags
[1], SIP_PAGE2_INC_RINGING
);
3128 ast_log(LOG_ERROR
, "update_call_counter(%s, %d) called with no event!\n", name
, event
);
3131 ast_device_state_changed("SIP/%s", p
->name
);
3132 ASTOBJ_UNREF(p
, sip_destroy_peer
);
3133 } else /* u must be set */
3134 ASTOBJ_UNREF(u
, sip_destroy_user
);
3138 /*! \brief Destroy SIP call structure */
3139 static void sip_destroy(struct sip_pvt
*p
)
3141 ast_mutex_lock(&iflock
);
3142 if (option_debug
> 2)
3143 ast_log(LOG_DEBUG
, "Destroying SIP dialog %s\n", p
->callid
);
3144 __sip_destroy(p
, 1);
3145 ast_mutex_unlock(&iflock
);
3148 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
3149 static int hangup_sip2cause(int cause
)
3151 /* Possible values taken from causes.h */
3154 case 401: /* Unauthorized */
3155 return AST_CAUSE_CALL_REJECTED
;
3156 case 403: /* Not found */
3157 return AST_CAUSE_CALL_REJECTED
;
3158 case 404: /* Not found */
3159 return AST_CAUSE_UNALLOCATED
;
3160 case 405: /* Method not allowed */
3161 return AST_CAUSE_INTERWORKING
;
3162 case 407: /* Proxy authentication required */
3163 return AST_CAUSE_CALL_REJECTED
;
3164 case 408: /* No reaction */
3165 return AST_CAUSE_NO_USER_RESPONSE
;
3166 case 409: /* Conflict */
3167 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE
;
3168 case 410: /* Gone */
3169 return AST_CAUSE_UNALLOCATED
;
3170 case 411: /* Length required */
3171 return AST_CAUSE_INTERWORKING
;
3172 case 413: /* Request entity too large */
3173 return AST_CAUSE_INTERWORKING
;
3174 case 414: /* Request URI too large */
3175 return AST_CAUSE_INTERWORKING
;
3176 case 415: /* Unsupported media type */
3177 return AST_CAUSE_INTERWORKING
;
3178 case 420: /* Bad extension */
3179 return AST_CAUSE_NO_ROUTE_DESTINATION
;
3180 case 480: /* No answer */
3181 return AST_CAUSE_NO_ANSWER
;
3182 case 481: /* No answer */
3183 return AST_CAUSE_INTERWORKING
;
3184 case 482: /* Loop detected */
3185 return AST_CAUSE_INTERWORKING
;
3186 case 483: /* Too many hops */
3187 return AST_CAUSE_NO_ANSWER
;
3188 case 484: /* Address incomplete */
3189 return AST_CAUSE_INVALID_NUMBER_FORMAT
;
3190 case 485: /* Ambigous */
3191 return AST_CAUSE_UNALLOCATED
;
3192 case 486: /* Busy everywhere */
3193 return AST_CAUSE_BUSY
;
3194 case 487: /* Request terminated */
3195 return AST_CAUSE_INTERWORKING
;
3196 case 488: /* No codecs approved */
3197 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
;
3198 case 491: /* Request pending */
3199 return AST_CAUSE_INTERWORKING
;
3200 case 493: /* Undecipherable */
3201 return AST_CAUSE_INTERWORKING
;
3202 case 500: /* Server internal failure */
3203 return AST_CAUSE_FAILURE
;
3204 case 501: /* Call rejected */
3205 return AST_CAUSE_FACILITY_REJECTED
;
3207 return AST_CAUSE_DESTINATION_OUT_OF_ORDER
;
3208 case 503: /* Service unavailable */
3209 return AST_CAUSE_CONGESTION
;
3210 case 504: /* Gateway timeout */
3211 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE
;
3212 case 505: /* SIP version not supported */
3213 return AST_CAUSE_INTERWORKING
;
3214 case 600: /* Busy everywhere */
3215 return AST_CAUSE_USER_BUSY
;
3216 case 603: /* Decline */
3217 return AST_CAUSE_CALL_REJECTED
;
3218 case 604: /* Does not exist anywhere */
3219 return AST_CAUSE_UNALLOCATED
;
3220 case 606: /* Not acceptable */
3221 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
;
3223 return AST_CAUSE_NORMAL
;
3229 /*! \brief Convert Asterisk hangup causes to SIP codes
3231 Possible values from causes.h
3232 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
3233 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
3235 In addition to these, a lot of PRI codes is defined in causes.h
3236 ...should we take care of them too ?
3240 ISUP Cause value SIP response
3241 ---------------- ------------
3242 1 unallocated number 404 Not Found
3243 2 no route to network 404 Not found
3244 3 no route to destination 404 Not found
3245 16 normal call clearing --- (*)
3246 17 user busy 486 Busy here
3247 18 no user responding 408 Request Timeout
3248 19 no answer from the user 480 Temporarily unavailable
3249 20 subscriber absent 480 Temporarily unavailable
3250 21 call rejected 403 Forbidden (+)
3251 22 number changed (w/o diagnostic) 410 Gone
3252 22 number changed (w/ diagnostic) 301 Moved Permanently
3253 23 redirection to new destination 410 Gone
3254 26 non-selected user clearing 404 Not Found (=)
3255 27 destination out of order 502 Bad Gateway
3256 28 address incomplete 484 Address incomplete
3257 29 facility rejected 501 Not implemented
3258 31 normal unspecified 480 Temporarily unavailable
3261 static const char *hangup_cause2sip(int cause
)
3264 case AST_CAUSE_UNALLOCATED
: /* 1 */
3265 case AST_CAUSE_NO_ROUTE_DESTINATION
: /* 3 IAX2: Can't find extension in context */
3266 case AST_CAUSE_NO_ROUTE_TRANSIT_NET
: /* 2 */
3267 return "404 Not Found";
3268 case AST_CAUSE_CONGESTION
: /* 34 */
3269 case AST_CAUSE_SWITCH_CONGESTION
: /* 42 */
3270 return "503 Service Unavailable";
3271 case AST_CAUSE_NO_USER_RESPONSE
: /* 18 */
3272 return "408 Request Timeout";
3273 case AST_CAUSE_NO_ANSWER
: /* 19 */
3274 return "480 Temporarily unavailable";
3275 case AST_CAUSE_CALL_REJECTED
: /* 21 */
3276 return "403 Forbidden";
3277 case AST_CAUSE_NUMBER_CHANGED
: /* 22 */
3279 case AST_CAUSE_NORMAL_UNSPECIFIED
: /* 31 */
3280 return "480 Temporarily unavailable";
3281 case AST_CAUSE_INVALID_NUMBER_FORMAT
:
3282 return "484 Address incomplete";
3283 case AST_CAUSE_USER_BUSY
:
3284 return "486 Busy here";
3285 case AST_CAUSE_FAILURE
:
3286 return "500 Server internal failure";
3287 case AST_CAUSE_FACILITY_REJECTED
: /* 29 */
3288 return "501 Not Implemented";
3289 case AST_CAUSE_CHAN_NOT_IMPLEMENTED
:
3290 return "503 Service Unavailable";
3291 /* Used in chan_iax2 */
3292 case AST_CAUSE_DESTINATION_OUT_OF_ORDER
:
3293 return "502 Bad Gateway";
3294 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
: /* Can't find codec to connect to host */
3295 return "488 Not Acceptable Here";
3297 case AST_CAUSE_NOTDEFINED
:
3300 ast_log(LOG_DEBUG
, "AST hangup cause %d (no match found in SIP)\n", cause
);
3309 /*! \brief sip_hangup: Hangup SIP call
3310 * Part of PBX interface, called from ast_hangup */
3311 static int sip_hangup(struct ast_channel
*ast
)
3313 struct sip_pvt
*p
= ast
->tech_pvt
;
3314 int needcancel
= FALSE
;
3315 int needdestroy
= 0;
3316 struct ast_channel
*oldowner
= ast
;
3320 ast_log(LOG_DEBUG
, "Asked to hangup channel that was not connected\n");
3324 if (ast_test_flag(&p
->flags
[0], SIP_DEFER_BYE_ON_TRANSFER
)) {
3325 if (ast_test_flag(&p
->flags
[0], SIP_INC_COUNT
)) {
3326 if (option_debug
&& sipdebug
)
3327 ast_log(LOG_DEBUG
, "update_call_counter(%s) - decrement call limit counter on hangup\n", p
->username
);
3328 update_call_counter(p
, DEC_CALL_LIMIT
);
3330 if (option_debug
>3)
3331 ast_log(LOG_DEBUG
, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p
->callid
);
3332 if (p
->autokillid
> -1)
3333 sip_cancel_destroy(p
);
3334 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
3335 ast_clear_flag(&p
->flags
[0], SIP_DEFER_BYE_ON_TRANSFER
); /* Really hang up next time */
3336 ast_clear_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
3337 p
->owner
->tech_pvt
= NULL
;
3338 p
->owner
= NULL
; /* Owner will be gone after we return, so take it away */
3342 if (ast_test_flag(ast
, AST_FLAG_ZOMBIE
) && p
->refer
&& option_debug
)
3343 ast_log(LOG_DEBUG
, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast
->name
, p
->callid
);
3346 ast_log(LOG_DEBUG
, "Hangup call %s, SIP callid %s)\n", ast
->name
, p
->callid
);
3349 if (option_debug
&& ast_test_flag(ast
, AST_FLAG_ZOMBIE
))
3350 ast_log(LOG_DEBUG
, "Hanging up zombie call. Be scared.\n");
3352 ast_mutex_lock(&p
->lock
);
3353 if (ast_test_flag(&p
->flags
[0], SIP_INC_COUNT
)) {
3354 if (option_debug
&& sipdebug
)
3355 ast_log(LOG_DEBUG
, "update_call_counter(%s) - decrement call limit counter on hangup\n", p
->username
);
3356 update_call_counter(p
, DEC_CALL_LIMIT
);
3359 /* Determine how to disconnect */
3360 if (p
->owner
!= ast
) {
3361 ast_log(LOG_WARNING
, "Huh? We aren't the owner? Can't hangup call.\n");
3362 ast_mutex_unlock(&p
->lock
);
3365 /* If the call is not UP, we need to send CANCEL instead of BYE */
3366 if (ast
->_state
== AST_STATE_RING
|| ast
->_state
== AST_STATE_RINGING
|| (p
->invitestate
< INV_COMPLETED
&& ast
->_state
!= AST_STATE_UP
)) {
3368 if (option_debug
> 3)
3369 ast_log(LOG_DEBUG
, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast
->_state
));
3372 stop_media_flows(p
); /* Immediately stop RTP, VRTP and UDPTL as applicable */
3376 ast_dsp_free(p
->vad
);
3379 ast
->tech_pvt
= NULL
;
3381 ast_module_unref(ast_module_info
->self
);
3383 /* Do not destroy this pvt until we have timeout or
3384 get an answer to the BYE or INVITE/CANCEL
3385 If we get no answer during retransmit period, drop the call anyway.
3386 (Sorry, mother-in-law, you can't deny a hangup by sending
3387 603 declined to BYE...)
3389 if (ast_test_flag(&p
->flags
[0], SIP_ALREADYGONE
))
3390 needdestroy
= 1; /* Set destroy flag at end of this function */
3391 else if (p
->invitestate
!= INV_CALLING
)
3392 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
3394 /* Start the process if it's not already started */
3395 if (!ast_test_flag(&p
->flags
[0], SIP_ALREADYGONE
) && !ast_strlen_zero(p
->initreq
.data
)) {
3396 if (needcancel
) { /* Outgoing call, not up */
3397 if (ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) {
3398 /* stop retransmitting an INVITE that has not received a response */
3399 __sip_pretend_ack(p
);
3401 /* if we can't send right now, mark it pending */
3402 if (p
->invitestate
== INV_CALLING
) {
3403 /* We can't send anything in CALLING state */
3404 ast_set_flag(&p
->flags
[0], SIP_PENDINGBYE
);
3405 /* Do we need a timer here if we don't hear from them at all? */
3407 /* Send a new request: CANCEL */
3408 transmit_request(p
, SIP_CANCEL
, p
->ocseq
, XMIT_RELIABLE
, FALSE
);
3409 /* Actually don't destroy us yet, wait for the 487 on our original
3410 INVITE, but do set an autodestruct just in case we never get it. */
3412 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
3414 if ( p
->initid
!= -1 ) {
3415 /* channel still up - reverse dec of inUse counter
3416 only if the channel is not auto-congested */
3417 update_call_counter(p
, INC_CALL_LIMIT
);
3419 } else { /* Incoming call, not up */
3421 if (ast
->hangupcause
&& (res
= hangup_cause2sip(ast
->hangupcause
)))
3422 transmit_response_reliable(p
, res
, &p
->initreq
);
3424 transmit_response_reliable(p
, "603 Declined", &p
->initreq
);
3426 } else { /* Call is in UP state, send BYE */
3427 if (!p
->pendinginvite
) {
3428 char *audioqos
= "";
3429 char *videoqos
= "";
3431 audioqos
= ast_rtp_get_quality(p
->rtp
, NULL
);
3433 videoqos
= ast_rtp_get_quality(p
->vrtp
, NULL
);
3435 transmit_request_with_auth(p
, SIP_BYE
, 0, XMIT_RELIABLE
, 1);
3437 /* Get RTCP quality before end of call */
3438 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
)) {
3440 append_history(p
, "RTCPaudio", "Quality:%s", audioqos
);
3442 append_history(p
, "RTCPvideo", "Quality:%s", videoqos
);
3444 if (p
->rtp
&& oldowner
)
3445 pbx_builtin_setvar_helper(oldowner
, "RTPAUDIOQOS", audioqos
);
3446 if (p
->vrtp
&& oldowner
)
3447 pbx_builtin_setvar_helper(oldowner
, "RTPVIDEOQOS", videoqos
);
3449 /* Note we will need a BYE when this all settles out
3450 but we can't send one while we have "INVITE" outstanding. */
3451 ast_set_flag(&p
->flags
[0], SIP_PENDINGBYE
);
3452 ast_clear_flag(&p
->flags
[0], SIP_NEEDREINVITE
);
3453 sip_cancel_destroy(p
);
3458 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
3459 ast_mutex_unlock(&p
->lock
);
3463 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
3464 static void try_suggested_sip_codec(struct sip_pvt
*p
)
3469 codec
= pbx_builtin_getvar_helper(p
->owner
, "SIP_CODEC");
3473 fmt
= ast_getformatbyname(codec
);
3475 ast_log(LOG_NOTICE
, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec
);
3476 if (p
->jointcapability
& fmt
) {
3477 p
->jointcapability
&= fmt
;
3478 p
->capability
&= fmt
;
3480 ast_log(LOG_NOTICE
, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
3482 ast_log(LOG_NOTICE
, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec
);
3486 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
3487 * Part of PBX interface */
3488 static int sip_answer(struct ast_channel
*ast
)
3491 struct sip_pvt
*p
= ast
->tech_pvt
;
3493 ast_mutex_lock(&p
->lock
);
3494 if (ast
->_state
!= AST_STATE_UP
) {
3495 try_suggested_sip_codec(p
);
3497 ast_setstate(ast
, AST_STATE_UP
);
3499 ast_log(LOG_DEBUG
, "SIP answering channel: %s\n", ast
->name
);
3500 if (p
->t38
.state
== T38_PEER_DIRECT
) {
3501 p
->t38
.state
= T38_ENABLED
;
3502 if (option_debug
> 1)
3503 ast_log(LOG_DEBUG
,"T38State change to %d on channel %s\n", p
->t38
.state
, ast
->name
);
3504 res
= transmit_response_with_t38_sdp(p
, "200 OK", &p
->initreq
, XMIT_CRITICAL
);
3506 res
= transmit_response_with_sdp(p
, "200 OK", &p
->initreq
, XMIT_CRITICAL
);
3508 ast_mutex_unlock(&p
->lock
);
3512 /*! \brief Send frame to media channel (rtp) */
3513 static int sip_write(struct ast_channel
*ast
, struct ast_frame
*frame
)
3515 struct sip_pvt
*p
= ast
->tech_pvt
;
3518 switch (frame
->frametype
) {
3519 case AST_FRAME_VOICE
:
3520 if (!(frame
->subclass
& ast
->nativeformats
)) {
3521 char s1
[512], s2
[512], s3
[512];
3522 ast_log(LOG_WARNING
, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
3524 ast_getformatname_multiple(s1
, sizeof(s1
) - 1, ast
->nativeformats
& AST_FORMAT_AUDIO_MASK
),
3525 ast
->nativeformats
& AST_FORMAT_AUDIO_MASK
,
3526 ast_getformatname_multiple(s2
, sizeof(s2
) - 1, ast
->readformat
),
3528 ast_getformatname_multiple(s3
, sizeof(s3
) - 1, ast
->writeformat
),
3533 ast_mutex_lock(&p
->lock
);
3535 /* If channel is not up, activate early media session */
3536 if ((ast
->_state
!= AST_STATE_UP
) &&
3537 !ast_test_flag(&p
->flags
[0], SIP_PROGRESS_SENT
) &&
3538 !ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) {
3539 transmit_response_with_sdp(p
, "183 Session Progress", &p
->initreq
, XMIT_UNRELIABLE
);
3540 ast_set_flag(&p
->flags
[0], SIP_PROGRESS_SENT
);
3542 p
->lastrtptx
= time(NULL
);
3543 res
= ast_rtp_write(p
->rtp
, frame
);
3545 ast_mutex_unlock(&p
->lock
);
3548 case AST_FRAME_VIDEO
:
3550 ast_mutex_lock(&p
->lock
);
3552 /* Activate video early media */
3553 if ((ast
->_state
!= AST_STATE_UP
) &&
3554 !ast_test_flag(&p
->flags
[0], SIP_PROGRESS_SENT
) &&
3555 !ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) {
3556 transmit_response_with_sdp(p
, "183 Session Progress", &p
->initreq
, XMIT_UNRELIABLE
);
3557 ast_set_flag(&p
->flags
[0], SIP_PROGRESS_SENT
);
3559 p
->lastrtptx
= time(NULL
);
3560 res
= ast_rtp_write(p
->vrtp
, frame
);
3562 ast_mutex_unlock(&p
->lock
);
3565 case AST_FRAME_IMAGE
:
3568 case AST_FRAME_MODEM
:
3570 ast_mutex_lock(&p
->lock
);
3571 /* UDPTL requires two-way communication, so early media is not needed here.
3572 we simply forget the frames if we get modem frames before the bridge is up.
3573 Fax will re-transmit.
3575 if (p
->udptl
&& ast
->_state
== AST_STATE_UP
)
3576 res
= ast_udptl_write(p
->udptl
, frame
);
3577 ast_mutex_unlock(&p
->lock
);
3581 ast_log(LOG_WARNING
, "Can't send %d type frames with SIP write\n", frame
->frametype
);
3588 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
3589 Basically update any ->owner links */
3590 static int sip_fixup(struct ast_channel
*oldchan
, struct ast_channel
*newchan
)
3595 if (newchan
&& ast_test_flag(newchan
, AST_FLAG_ZOMBIE
) && option_debug
)
3596 ast_log(LOG_DEBUG
, "New channel is zombie\n");
3597 if (oldchan
&& ast_test_flag(oldchan
, AST_FLAG_ZOMBIE
) && option_debug
)
3598 ast_log(LOG_DEBUG
, "Old channel is zombie\n");
3600 if (!newchan
|| !newchan
->tech_pvt
) {
3602 ast_log(LOG_WARNING
, "No new channel! Fixup of %s failed.\n", oldchan
->name
);
3604 ast_log(LOG_WARNING
, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan
->name
);
3607 p
= newchan
->tech_pvt
;
3610 ast_log(LOG_WARNING
, "No pvt after masquerade. Strange things may happen\n");
3614 ast_mutex_lock(&p
->lock
);
3615 append_history(p
, "Masq", "Old channel: %s\n", oldchan
->name
);
3616 append_history(p
, "Masq (cont)", "...new owner: %s\n", newchan
->name
);
3617 if (p
->owner
!= oldchan
)
3618 ast_log(LOG_WARNING
, "old channel wasn't %p but was %p\n", oldchan
, p
->owner
);
3623 if (option_debug
> 2)
3624 ast_log(LOG_DEBUG
, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p
->callid
, p
->owner
->name
, oldchan
->name
);
3626 ast_mutex_unlock(&p
->lock
);
3630 static int sip_senddigit_begin(struct ast_channel
*ast
, char digit
)
3632 struct sip_pvt
*p
= ast
->tech_pvt
;
3635 ast_mutex_lock(&p
->lock
);
3636 switch (ast_test_flag(&p
->flags
[0], SIP_DTMF
)) {
3637 case SIP_DTMF_INBAND
:
3638 res
= -1; /* Tell Asterisk to generate inband indications */
3640 case SIP_DTMF_RFC2833
:
3642 ast_rtp_senddigit_begin(p
->rtp
, digit
);
3647 ast_mutex_unlock(&p
->lock
);
3652 /*! \brief Send DTMF character on SIP channel
3653 within one call, we're able to transmit in many methods simultaneously */
3654 static int sip_senddigit_end(struct ast_channel
*ast
, char digit
, unsigned int duration
)
3656 struct sip_pvt
*p
= ast
->tech_pvt
;
3659 ast_mutex_lock(&p
->lock
);
3660 switch (ast_test_flag(&p
->flags
[0], SIP_DTMF
)) {
3662 transmit_info_with_digit(p
, digit
, duration
);
3664 case SIP_DTMF_RFC2833
:
3666 ast_rtp_senddigit_end(p
->rtp
, digit
);
3668 case SIP_DTMF_INBAND
:
3669 res
= -1; /* Tell Asterisk to stop inband indications */
3672 ast_mutex_unlock(&p
->lock
);
3677 /*! \brief Transfer SIP call */
3678 static int sip_transfer(struct ast_channel
*ast
, const char *dest
)
3680 struct sip_pvt
*p
= ast
->tech_pvt
;
3683 if (dest
== NULL
) /* functions below do not take a NULL */
3685 ast_mutex_lock(&p
->lock
);
3686 if (ast
->_state
== AST_STATE_RING
)
3687 res
= sip_sipredirect(p
, dest
);
3689 res
= transmit_refer(p
, dest
);
3690 ast_mutex_unlock(&p
->lock
);
3694 /*! \brief Play indication to user
3695 * With SIP a lot of indications is sent as messages, letting the device play
3696 the indication - busy signal, congestion etc
3697 \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
3699 static int sip_indicate(struct ast_channel
*ast
, int condition
, const void *data
, size_t datalen
)
3701 struct sip_pvt
*p
= ast
->tech_pvt
;
3704 ast_mutex_lock(&p
->lock
);
3706 case AST_CONTROL_RINGING
:
3707 if (ast
->_state
== AST_STATE_RING
) {
3708 p
->invitestate
= INV_EARLY_MEDIA
;
3709 if (!ast_test_flag(&p
->flags
[0], SIP_PROGRESS_SENT
) ||
3710 (ast_test_flag(&p
->flags
[0], SIP_PROG_INBAND
) == SIP_PROG_INBAND_NEVER
)) {
3711 /* Send 180 ringing if out-of-band seems reasonable */
3712 transmit_response(p
, "180 Ringing", &p
->initreq
);
3713 ast_set_flag(&p
->flags
[0], SIP_RINGING
);
3714 if (ast_test_flag(&p
->flags
[0], SIP_PROG_INBAND
) != SIP_PROG_INBAND_YES
)
3717 /* Well, if it's not reasonable, just send in-band */
3722 case AST_CONTROL_BUSY
:
3723 if (ast
->_state
!= AST_STATE_UP
) {
3724 transmit_response(p
, "486 Busy Here", &p
->initreq
);
3725 p
->invitestate
= INV_COMPLETED
;
3727 ast_softhangup_nolock(ast
, AST_SOFTHANGUP_DEV
);
3732 case AST_CONTROL_CONGESTION
:
3733 if (ast
->_state
!= AST_STATE_UP
) {
3734 transmit_response(p
, "503 Service Unavailable", &p
->initreq
);
3735 p
->invitestate
= INV_COMPLETED
;
3737 ast_softhangup_nolock(ast
, AST_SOFTHANGUP_DEV
);
3742 case AST_CONTROL_PROCEEDING
:
3743 if ((ast
->_state
!= AST_STATE_UP
) &&
3744 !ast_test_flag(&p
->flags
[0], SIP_PROGRESS_SENT
) &&
3745 !ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) {
3746 transmit_response(p
, "100 Trying", &p
->initreq
);
3747 p
->invitestate
= INV_PROCEEDING
;
3752 case AST_CONTROL_PROGRESS
:
3753 if ((ast
->_state
!= AST_STATE_UP
) &&
3754 !ast_test_flag(&p
->flags
[0], SIP_PROGRESS_SENT
) &&
3755 !ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) {
3756 p
->invitestate
= INV_EARLY_MEDIA
;
3757 transmit_response_with_sdp(p
, "183 Session Progress", &p
->initreq
, XMIT_UNRELIABLE
);
3758 ast_set_flag(&p
->flags
[0], SIP_PROGRESS_SENT
);
3763 case AST_CONTROL_HOLD
:
3764 ast_moh_start(ast
, data
, p
->mohinterpret
);
3766 case AST_CONTROL_UNHOLD
:
3769 case AST_CONTROL_VIDUPDATE
: /* Request a video frame update */
3770 if (p
->vrtp
&& !ast_test_flag(&p
->flags
[0], SIP_NOVIDEO
)) {
3771 transmit_info_with_vidupdate(p
);
3772 /* ast_rtcp_send_h261fur(p->vrtp); */
3780 ast_log(LOG_WARNING
, "Don't know how to indicate condition %d\n", condition
);
3784 ast_mutex_unlock(&p
->lock
);
3790 /*! \brief Initiate a call in the SIP channel
3791 called from sip_request_call (calls from the pbx ) for outbound channels
3792 and from handle_request_invite for inbound channels
3795 static struct ast_channel
*sip_new(struct sip_pvt
*i
, int state
, const char *title
)
3797 struct ast_channel
*tmp
;
3798 struct ast_variable
*v
= NULL
;
3803 const char *my_name
; /* pick a good name */
3807 else if ( (my_name
= strchr(i
->fromdomain
,':')) )
3808 my_name
++; /* skip ':' */
3810 my_name
= i
->fromdomain
;
3812 ast_mutex_unlock(&i
->lock
);
3813 /* Don't hold a sip pvt lock while we allocate a channel */
3814 tmp
= ast_channel_alloc(1, state
, i
->cid_num
, i
->cid_name
, i
->accountcode
, i
->exten
, i
->context
, i
->amaflags
, "SIP/%s-%08x", my_name
, (int)(long) i
);
3818 ast_log(LOG_WARNING
, "Unable to allocate AST channel structure for SIP channel\n");
3821 ast_mutex_lock(&i
->lock
);
3823 if (ast_test_flag(&i
->flags
[0], SIP_DTMF
) == SIP_DTMF_INFO
)
3824 tmp
->tech
= &sip_tech_info
;
3826 tmp
->tech
= &sip_tech
;
3828 /* Select our native format based on codec preference until we receive
3829 something from another device to the contrary. */
3830 if (i
->jointcapability
) /* The joint capabilities of us and peer */
3831 what
= i
->jointcapability
;
3832 else if (i
->capability
) /* Our configured capability for this peer */
3833 what
= i
->capability
;
3835 what
= global_capability
; /* Global codec support */
3837 /* Set the native formats for audio and merge in video */
3838 tmp
->nativeformats
= ast_codec_choose(&i
->prefs
, what
, 1) | (i
->jointcapability
& AST_FORMAT_VIDEO_MASK
);
3839 if (option_debug
> 2) {
3841 ast_log(LOG_DEBUG
, "*** Our native formats are %s \n", ast_getformatname_multiple(buf
, BUFSIZ
, tmp
->nativeformats
));
3842 ast_log(LOG_DEBUG
, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf
, BUFSIZ
, i
->jointcapability
));
3843 ast_log(LOG_DEBUG
, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf
, BUFSIZ
, i
->capability
));
3844 ast_log(LOG_DEBUG
, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf
, BUFSIZ
, ast_codec_choose(&i
->prefs
, what
, 1)));
3846 ast_log(LOG_DEBUG
, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf
, BUFSIZ
, i
->prefcodec
));
3849 /* XXX Why are we choosing a codec from the native formats?? */
3850 fmt
= ast_best_codec(tmp
->nativeformats
);
3852 /* If we have a prefcodec setting, we have an inbound channel that set a
3853 preferred format for this call. Otherwise, we check the jointcapability
3854 We also check for vrtp. If it's not there, we are not allowed do any video anyway.
3858 needvideo
= i
->prefcodec
& AST_FORMAT_VIDEO_MASK
; /* Outbound call */
3860 needvideo
= i
->jointcapability
& AST_FORMAT_VIDEO_MASK
; /* Inbound call */
3863 if (option_debug
> 2) {
3865 ast_log(LOG_DEBUG
, "This channel can handle video! HOLLYWOOD next!\n");
3867 ast_log(LOG_DEBUG
, "This channel will not be able to handle video.\n");
3872 if (ast_test_flag(&i
->flags
[0], SIP_DTMF
) == SIP_DTMF_INBAND
) {
3873 i
->vad
= ast_dsp_new();
3874 ast_dsp_set_features(i
->vad
, DSP_FEATURE_DTMF_DETECT
);
3875 if (global_relaxdtmf
)
3876 ast_dsp_digitmode(i
->vad
, DSP_DIGITMODE_DTMF
| DSP_DIGITMODE_RELAXDTMF
);
3879 tmp
->fds
[0] = ast_rtp_fd(i
->rtp
);
3880 tmp
->fds
[1] = ast_rtcp_fd(i
->rtp
);
3882 if (needvideo
&& i
->vrtp
) {
3883 tmp
->fds
[2] = ast_rtp_fd(i
->vrtp
);
3884 tmp
->fds
[3] = ast_rtcp_fd(i
->vrtp
);
3887 tmp
->fds
[5] = ast_udptl_fd(i
->udptl
);
3889 if (state
== AST_STATE_RING
)
3891 tmp
->adsicpe
= AST_ADSI_UNAVAILABLE
;
3892 tmp
->writeformat
= fmt
;
3893 tmp
->rawwriteformat
= fmt
;
3894 tmp
->readformat
= fmt
;
3895 tmp
->rawreadformat
= fmt
;
3898 tmp
->callgroup
= i
->callgroup
;
3899 tmp
->pickupgroup
= i
->pickupgroup
;
3900 tmp
->cid
.cid_pres
= i
->callingpres
;
3901 if (!ast_strlen_zero(i
->accountcode
))
3902 ast_string_field_set(tmp
, accountcode
, i
->accountcode
);
3904 tmp
->amaflags
= i
->amaflags
;
3905 if (!ast_strlen_zero(i
->language
))
3906 ast_string_field_set(tmp
, language
, i
->language
);
3908 ast_module_ref(ast_module_info
->self
);
3909 ast_copy_string(tmp
->context
, i
->context
, sizeof(tmp
->context
));
3910 ast_copy_string(tmp
->exten
, i
->exten
, sizeof(tmp
->exten
));
3913 /* Don't use ast_set_callerid() here because it will
3914 * generate an unnecessary NewCallerID event */
3915 tmp
->cid
.cid_num
= ast_strdup(i
->cid_num
);
3916 tmp
->cid
.cid_ani
= ast_strdup(i
->cid_num
);
3917 tmp
->cid
.cid_name
= ast_strdup(i
->cid_name
);
3918 if (!ast_strlen_zero(i
->rdnis
))
3919 tmp
->cid
.cid_rdnis
= ast_strdup(i
->rdnis
);
3921 if (!ast_strlen_zero(i
->exten
) && strcmp(i
->exten
, "s"))
3922 tmp
->cid
.cid_dnid
= ast_strdup(i
->exten
);
3925 if (!ast_strlen_zero(i
->uri
))
3926 pbx_builtin_setvar_helper(tmp
, "SIPURI", i
->uri
);
3927 if (!ast_strlen_zero(i
->domain
))
3928 pbx_builtin_setvar_helper(tmp
, "SIPDOMAIN", i
->domain
);
3929 if (!ast_strlen_zero(i
->useragent
))
3930 pbx_builtin_setvar_helper(tmp
, "SIPUSERAGENT", i
->useragent
);
3931 if (!ast_strlen_zero(i
->callid
))
3932 pbx_builtin_setvar_helper(tmp
, "SIPCALLID", i
->callid
);
3934 ast_jb_configure(tmp
, &global_jbconf
);
3936 /* Set channel variables for this call from configuration */
3937 for (v
= i
->chanvars
; v
; v
= v
->next
)
3938 pbx_builtin_setvar_helper(tmp
, v
->name
, v
->value
);
3940 if (state
!= AST_STATE_DOWN
&& ast_pbx_start(tmp
)) {
3941 ast_log(LOG_WARNING
, "Unable to start PBX on %s\n", tmp
->name
);
3942 tmp
->hangupcause
= AST_CAUSE_SWITCH_CONGESTION
;
3947 if (!ast_test_flag(&i
->flags
[0], SIP_NO_HISTORY
))
3948 append_history(i
, "NewChan", "Channel %s - from %s", tmp
->name
, i
->callid
);
3953 /*! \brief Reads one line of SIP message body */
3954 static char *get_body_by_line(const char *line
, const char *name
, int nameLen
)
3956 if (strncasecmp(line
, name
, nameLen
) == 0 && line
[nameLen
] == '=')
3957 return ast_skip_blanks(line
+ nameLen
+ 1);
3962 /*! \brief Lookup 'name' in the SDP starting
3963 * at the 'start' line. Returns the matching line, and 'start'
3964 * is updated with the next line number.
3966 static const char *get_sdp_iterate(int *start
, struct sip_request
*req
, const char *name
)
3968 int len
= strlen(name
);
3970 while (*start
< req
->sdp_end
) {
3971 const char *r
= get_body_by_line(req
->line
[(*start
)++], name
, len
);
3979 /*! \brief Get a line from an SDP message body */
3980 static const char *get_sdp(struct sip_request
*req
, const char *name
)
3984 return get_sdp_iterate(&dummy
, req
, name
);
3987 /*! \brief Get a specific line from the message body */
3988 static char *get_body(struct sip_request
*req
, char *name
)
3991 int len
= strlen(name
);
3994 for (x
= 0; x
< req
->lines
; x
++) {
3995 r
= get_body_by_line(req
->line
[x
], name
, len
);
4003 /*! \brief Find compressed SIP alias */
4004 static const char *find_alias(const char *name
, const char *_default
)
4006 /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
4007 static const struct cfalias
{
4008 char * const fullname
;
4009 char * const shortname
;
4011 { "Content-Type", "c" },
4012 { "Content-Encoding", "e" },
4016 { "Content-Length", "l" },
4019 { "Supported", "k" },
4020 { "Refer-To", "r" },
4021 { "Referred-By", "b" },
4022 { "Allow-Events", "u" },
4025 { "Accept-Contact", "a" },
4026 { "Reject-Contact", "j" },
4027 { "Request-Disposition", "d" },
4028 { "Session-Expires", "x" },
4029 { "Identity", "y" },
4030 { "Identity-Info", "n" },
4034 for (x
=0; x
<sizeof(aliases
) / sizeof(aliases
[0]); x
++)
4035 if (!strcasecmp(aliases
[x
].fullname
, name
))
4036 return aliases
[x
].shortname
;
4041 static const char *__get_header(const struct sip_request
*req
, const char *name
, int *start
)
4046 * Technically you can place arbitrary whitespace both before and after the ':' in
4047 * a header, although RFC3261 clearly says you shouldn't before, and place just
4048 * one afterwards. If you shouldn't do it, what absolute idiot decided it was
4049 * a good idea to say you can do it, and if you can do it, why in the hell would.
4050 * you say you shouldn't.
4051 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
4052 * and we always allow spaces after that for compatibility.
4054 for (pass
= 0; name
&& pass
< 2;pass
++) {
4055 int x
, len
= strlen(name
);
4056 for (x
=*start
; x
<req
->headers
; x
++) {
4057 if (!strncasecmp(req
->header
[x
], name
, len
)) {
4058 char *r
= req
->header
[x
] + len
; /* skip name */
4059 if (pedanticsipchecking
)
4060 r
= ast_skip_blanks(r
);
4064 return ast_skip_blanks(r
+1);
4068 if (pass
== 0) /* Try aliases */
4069 name
= find_alias(name
, NULL
);
4072 /* Don't return NULL, so get_header is always a valid pointer */
4076 /*! \brief Get header from SIP request */
4077 static const char *get_header(const struct sip_request
*req
, const char *name
)
4080 return __get_header(req
, name
, &start
);
4083 /*! \brief Read RTP from network */
4084 static struct ast_frame
*sip_rtp_read(struct ast_channel
*ast
, struct sip_pvt
*p
, int *faxdetect
)
4086 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
4087 struct ast_frame
*f
;
4090 /* We have no RTP allocated for this channel */
4091 return &ast_null_frame
;
4096 f
= ast_rtp_read(p
->rtp
); /* RTP Audio */
4099 f
= ast_rtcp_read(p
->rtp
); /* RTCP Control Channel */
4102 f
= ast_rtp_read(p
->vrtp
); /* RTP Video */
4105 f
= ast_rtcp_read(p
->vrtp
); /* RTCP Control Channel for video */
4108 f
= ast_udptl_read(p
->udptl
); /* UDPTL for T.38 */
4111 f
= &ast_null_frame
;
4113 /* Don't forward RFC2833 if we're not supposed to */
4114 if (f
&& (f
->frametype
== AST_FRAME_DTMF
) &&
4115 (ast_test_flag(&p
->flags
[0], SIP_DTMF
) != SIP_DTMF_RFC2833
))
4116 return &ast_null_frame
;
4118 /* We already hold the channel lock */
4119 if (!p
->owner
|| f
->frametype
!= AST_FRAME_VOICE
)
4122 if (f
->subclass
!= (p
->owner
->nativeformats
& AST_FORMAT_AUDIO_MASK
)) {
4123 if (!(f
->subclass
& p
->jointcapability
)) {
4125 ast_log(LOG_DEBUG
, "Bogus frame of format '%s' received from '%s'!\n",
4126 ast_getformatname(f
->subclass
), p
->owner
->name
);
4128 return &ast_null_frame
;
4131 ast_log(LOG_DEBUG
, "Oooh, format changed to %d\n", f
->subclass
);
4132 p
->owner
->nativeformats
= (p
->owner
->nativeformats
& AST_FORMAT_VIDEO_MASK
) | f
->subclass
;
4133 ast_set_read_format(p
->owner
, p
->owner
->readformat
);
4134 ast_set_write_format(p
->owner
, p
->owner
->writeformat
);
4137 if ((ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_INBAND
) && p
->vad
) {
4138 f
= ast_dsp_process(p
->owner
, p
->vad
, f
);
4139 if (f
&& f
->frametype
== AST_FRAME_DTMF
) {
4140 if (ast_test_flag(&p
->t38
.t38support
, SIP_PAGE2_T38SUPPORT_UDPTL
) && f
->subclass
== 'f') {
4142 ast_log(LOG_DEBUG
, "Fax CNG detected on %s\n", ast
->name
);
4144 } else if (option_debug
) {
4145 ast_log(LOG_DEBUG
, "* Detected inband DTMF '%c'\n", f
->subclass
);
4153 /*! \brief Read SIP RTP from channel */
4154 static struct ast_frame
*sip_read(struct ast_channel
*ast
)
4156 struct ast_frame
*fr
;
4157 struct sip_pvt
*p
= ast
->tech_pvt
;
4158 int faxdetected
= FALSE
;
4160 ast_mutex_lock(&p
->lock
);
4161 fr
= sip_rtp_read(ast
, p
, &faxdetected
);
4162 p
->lastrtprx
= time(NULL
);
4164 /* If we are NOT bridged to another channel, and we have detected fax tone we issue T38 re-invite to a peer */
4165 /* 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 */
4166 if (faxdetected
&& ast_test_flag(&p
->t38
.t38support
, SIP_PAGE2_T38SUPPORT_UDPTL
) && (p
->t38
.state
== T38_DISABLED
) && !(ast_bridged_channel(ast
))) {
4167 if (!ast_test_flag(&p
->flags
[0], SIP_GOTREFER
)) {
4168 if (!p
->pendinginvite
) {
4169 if (option_debug
> 2)
4170 ast_log(LOG_DEBUG
, "Sending reinvite on SIP (%s) for T.38 negotiation.\n",ast
->name
);
4171 p
->t38
.state
= T38_LOCAL_REINVITE
;
4172 transmit_reinvite_with_t38_sdp(p
);
4173 if (option_debug
> 1)
4174 ast_log(LOG_DEBUG
, "T38 state changed to %d on channel %s\n", p
->t38
.state
, ast
->name
);
4176 } else if (!ast_test_flag(&p
->flags
[0], SIP_PENDINGBYE
)) {
4177 if (option_debug
> 2)
4178 ast_log(LOG_DEBUG
, "Deferring reinvite on SIP (%s) - it will be re-negotiated for T.38\n", ast
->name
);
4179 ast_set_flag(&p
->flags
[0], SIP_NEEDREINVITE
);
4183 ast_mutex_unlock(&p
->lock
);
4188 /*! \brief Generate 32 byte random string for callid's etc */
4189 static char *generate_random_string(char *buf
, size_t size
)
4195 val
[x
] = ast_random();
4196 snprintf(buf
, size
, "%08lx%08lx%08lx%08lx", val
[0], val
[1], val
[2], val
[3]);
4201 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
4202 static void build_callid_pvt(struct sip_pvt
*pvt
)
4206 const char *host
= S_OR(pvt
->fromdomain
, ast_inet_ntoa(pvt
->ourip
));
4208 ast_string_field_build(pvt
, callid
, "%s@%s", generate_random_string(buf
, sizeof(buf
)), host
);
4212 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
4213 static void build_callid_registry(struct sip_registry
*reg
, struct in_addr ourip
, const char *fromdomain
)
4217 const char *host
= S_OR(fromdomain
, ast_inet_ntoa(ourip
));
4219 ast_string_field_build(reg
, callid
, "%s@%s", generate_random_string(buf
, sizeof(buf
)), host
);
4222 /*! \brief Make our SIP dialog tag */
4223 static void make_our_tag(char *tagbuf
, size_t len
)
4225 snprintf(tagbuf
, len
, "as%08lx", ast_random());
4228 /*! \brief Allocate SIP_PVT structure and set defaults */
4229 static struct sip_pvt
*sip_alloc(ast_string_field callid
, struct sockaddr_in
*sin
,
4230 int useglobal_nat
, const int intended_method
)
4234 if (!(p
= ast_calloc(1, sizeof(*p
))))
4237 if (ast_string_field_init(p
, 512)) {
4242 ast_mutex_init(&p
->lock
);
4244 p
->method
= intended_method
;
4247 p
->subscribed
= NONE
;
4249 p
->prefs
= default_prefs
; /* Set default codecs for this call */
4251 if (intended_method
!= SIP_OPTIONS
) /* Peerpoke has it's own system */
4252 p
->timer_t1
= 500; /* Default SIP retransmission timer T1 (RFC 3261) */
4256 if (ast_sip_ouraddrfor(&p
->sa
.sin_addr
, &p
->ourip
))
4261 /* Copy global flags to this PVT at setup. */
4262 ast_copy_flags(&p
->flags
[0], &global_flags
[0], SIP_FLAGS_TO_COPY
);
4263 ast_copy_flags(&p
->flags
[1], &global_flags
[1], SIP_PAGE2_FLAGS_TO_COPY
);
4265 ast_set2_flag(&p
->flags
[0], !recordhistory
, SIP_NO_HISTORY
);
4267 p
->branch
= ast_random();
4268 make_our_tag(p
->tag
, sizeof(p
->tag
));
4269 p
->ocseq
= INITIAL_CSEQ
;
4271 if (sip_methods
[intended_method
].need_rtp
) {
4272 p
->rtp
= ast_rtp_new_with_bindaddr(sched
, io
, 1, 0, bindaddr
.sin_addr
);
4273 /* If the global videosupport flag is on, we always create a RTP interface for video */
4274 if (ast_test_flag(&p
->flags
[1], SIP_PAGE2_VIDEOSUPPORT
))
4275 p
->vrtp
= ast_rtp_new_with_bindaddr(sched
, io
, 1, 0, bindaddr
.sin_addr
);
4276 if (ast_test_flag(&p
->flags
[1], SIP_PAGE2_T38SUPPORT
))
4277 p
->udptl
= ast_udptl_new_with_bindaddr(sched
, io
, 0, bindaddr
.sin_addr
);
4278 if (!p
->rtp
|| (ast_test_flag(&p
->flags
[1], SIP_PAGE2_VIDEOSUPPORT
) && !p
->vrtp
)) {
4279 ast_log(LOG_WARNING
, "Unable to create RTP audio %s session: %s\n",
4280 ast_test_flag(&p
->flags
[1], SIP_PAGE2_VIDEOSUPPORT
) ? "and video" : "", strerror(errno
));
4281 ast_mutex_destroy(&p
->lock
);
4283 ast_variables_destroy(p
->chanvars
);
4289 ast_rtp_setdtmf(p
->rtp
, ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_RFC2833
);
4290 ast_rtp_setdtmfcompensate(p
->rtp
, ast_test_flag(&p
->flags
[1], SIP_PAGE2_RFC2833_COMPENSATE
));
4291 ast_rtp_settos(p
->rtp
, global_tos_audio
);
4292 ast_rtp_set_rtptimeout(p
->rtp
, global_rtptimeout
);
4293 ast_rtp_set_rtpholdtimeout(p
->rtp
, global_rtpholdtimeout
);
4294 ast_rtp_set_rtpkeepalive(p
->rtp
, global_rtpkeepalive
);
4296 ast_rtp_settos(p
->vrtp
, global_tos_video
);
4297 ast_rtp_setdtmf(p
->vrtp
, 0);
4298 ast_rtp_setdtmfcompensate(p
->vrtp
, 0);
4299 ast_rtp_set_rtptimeout(p
->vrtp
, global_rtptimeout
);
4300 ast_rtp_set_rtpholdtimeout(p
->vrtp
, global_rtpholdtimeout
);
4301 ast_rtp_set_rtpkeepalive(p
->vrtp
, global_rtpkeepalive
);
4304 ast_udptl_settos(p
->udptl
, global_tos_audio
);
4305 p
->maxcallbitrate
= default_maxcallbitrate
;
4308 if (useglobal_nat
&& sin
) {
4309 /* Setup NAT structure according to global settings if we have an address */
4310 ast_copy_flags(&p
->flags
[0], &global_flags
[0], SIP_NAT
);
4312 do_setnat(p
, ast_test_flag(&p
->flags
[0], SIP_NAT
) & SIP_NAT_ROUTE
);
4315 if (p
->method
!= SIP_REGISTER
)
4316 ast_string_field_set(p
, fromdomain
, default_fromdomain
);
4319 build_callid_pvt(p
);
4321 ast_string_field_set(p
, callid
, callid
);
4322 /* Assign default music on hold class */
4323 ast_string_field_set(p
, mohinterpret
, default_mohinterpret
);
4324 ast_string_field_set(p
, mohsuggest
, default_mohsuggest
);
4325 p
->capability
= global_capability
;
4326 p
->allowtransfer
= global_allowtransfer
;
4327 if ((ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_RFC2833
) ||
4328 (ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_AUTO
))
4329 p
->noncodeccapability
|= AST_RTP_DTMF
;
4331 p
->t38
.capability
= global_t38_capability
;
4332 if (ast_udptl_get_error_correction_scheme(p
->udptl
) == UDPTL_ERROR_CORRECTION_REDUNDANCY
)
4333 p
->t38
.capability
|= T38FAX_UDP_EC_REDUNDANCY
;
4334 else if (ast_udptl_get_error_correction_scheme(p
->udptl
) == UDPTL_ERROR_CORRECTION_FEC
)
4335 p
->t38
.capability
|= T38FAX_UDP_EC_FEC
;
4336 else if (ast_udptl_get_error_correction_scheme(p
->udptl
) == UDPTL_ERROR_CORRECTION_NONE
)
4337 p
->t38
.capability
|= T38FAX_UDP_EC_NONE
;
4338 p
->t38
.capability
|= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF
;
4339 p
->t38
.jointcapability
= p
->t38
.capability
;
4341 ast_string_field_set(p
, context
, default_context
);
4343 /* Add to active dialog list */
4344 ast_mutex_lock(&iflock
);
4347 ast_mutex_unlock(&iflock
);
4349 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");
4353 /*! \brief Connect incoming SIP message to current dialog or create new dialog structure
4354 Called by handle_request, sipsock_read */
4355 static struct sip_pvt
*find_call(struct sip_request
*req
, struct sockaddr_in
*sin
, const int intended_method
)
4357 struct sip_pvt
*p
= NULL
;
4358 char *tag
= ""; /* note, tag is never NULL */
4361 const char *callid
= get_header(req
, "Call-ID");
4362 const char *from
= get_header(req
, "From");
4363 const char *to
= get_header(req
, "To");
4364 const char *cseq
= get_header(req
, "Cseq");
4366 /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
4367 /* get_header always returns non-NULL so we must use ast_strlen_zero() */
4368 if (ast_strlen_zero(callid
) || ast_strlen_zero(to
) ||
4369 ast_strlen_zero(from
) || ast_strlen_zero(cseq
))
4370 return NULL
; /* Invalid packet */
4372 if (pedanticsipchecking
) {
4373 /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
4374 we need more to identify a branch - so we have to check branch, from
4375 and to tags to identify a call leg.
4376 For Asterisk to behave correctly, you need to turn on pedanticsipchecking
4379 if (gettag(req
, "To", totag
, sizeof(totag
)))
4380 ast_set_flag(req
, SIP_PKT_WITH_TOTAG
); /* Used in handle_request/response */
4381 gettag(req
, "From", fromtag
, sizeof(fromtag
));
4383 tag
= (req
->method
== SIP_RESPONSE
) ? totag
: fromtag
;
4385 if (option_debug
> 4 )
4386 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
);
4389 ast_mutex_lock(&iflock
);
4390 for (p
= iflist
; p
; p
= p
->next
) {
4391 /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
4393 if (ast_strlen_zero(p
->callid
))
4395 if (req
->method
== SIP_REGISTER
)
4396 found
= (!strcmp(p
->callid
, callid
));
4398 found
= (!strcmp(p
->callid
, callid
) &&
4399 (!pedanticsipchecking
|| !tag
|| ast_strlen_zero(p
->theirtag
) || !strcmp(p
->theirtag
, tag
))) ;
4401 if (option_debug
> 4)
4402 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
);
4404 /* If we get a new request within an existing to-tag - check the to tag as well */
4405 if (pedanticsipchecking
&& found
&& req
->method
!= SIP_RESPONSE
) { /* SIP Request */
4406 if (p
->tag
[0] == '\0' && totag
[0]) {
4407 /* We have no to tag, but they have. Wrong dialog */
4409 } else if (totag
[0]) { /* Both have tags, compare them */
4410 if (strcmp(totag
, p
->tag
)) {
4411 found
= FALSE
; /* This is not our packet */
4414 if (!found
&& option_debug
> 4)
4415 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
);
4420 /* Found the call */
4421 ast_mutex_lock(&p
->lock
);
4422 ast_mutex_unlock(&iflock
);
4426 ast_mutex_unlock(&iflock
);
4428 /* See if the method is capable of creating a dialog */
4429 if (sip_methods
[intended_method
].can_create
== CAN_CREATE_DIALOG
) {
4430 if (intended_method
== SIP_REFER
) {
4431 /* We do support REFER, but not outside of a dialog yet */
4432 transmit_response_using_temp(callid
, sin
, 1, intended_method
, req
, "603 Declined (no dialog)");
4433 } else if (intended_method
== SIP_NOTIFY
) {
4434 /* We do not support out-of-dialog NOTIFY either,
4435 like voicemail notification, so cancel that early */
4436 transmit_response_using_temp(callid
, sin
, 1, intended_method
, req
, "489 Bad event");
4438 /* Ok, time to create a new SIP dialog object, a pvt */
4439 if ((p
= sip_alloc(callid
, sin
, 1, intended_method
))) {
4440 /* Ok, we've created a dialog, let's go and process it */
4441 ast_mutex_lock(&p
->lock
);
4443 /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
4444 getting a dialog from sip_alloc.
4446 Without a dialog we can't retransmit and handle ACKs and all that, but at least
4447 send an error message.
4449 Sorry, we apologize for the inconvienience
4451 transmit_response_using_temp(callid
, sin
, 1, intended_method
, req
, "500 Server internal error");
4452 if (option_debug
> 3)
4453 ast_log(LOG_DEBUG
, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
4457 } else if( sip_methods
[intended_method
].can_create
== CAN_CREATE_DIALOG_UNSUPPORTED_METHOD
) {
4458 /* A method we do not support, let's take it on the volley */
4459 transmit_response_using_temp(callid
, sin
, 1, intended_method
, req
, "501 Method Not Implemented");
4460 } else if (intended_method
!= SIP_RESPONSE
&& intended_method
!= SIP_ACK
) {
4461 /* This is a request outside of a dialog that we don't know about
4462 ...never reply to an ACK!
4464 transmit_response_using_temp(callid
, sin
, 1, intended_method
, req
, "481 Call leg/transaction does not exist");
4466 /* We do not respond to responses for dialogs that we don't know about, we just drop
4467 the session quickly */
4472 /*! \brief Parse register=> line in sip.conf and add to registry */
4473 static int sip_register(char *value
, int lineno
)
4475 struct sip_registry
*reg
;
4477 char username
[256] = "";
4478 char *hostname
=NULL
, *secret
=NULL
, *authuser
=NULL
;
4484 ast_copy_string(username
, value
, sizeof(username
));
4485 /* First split around the last '@' then parse the two components. */
4486 hostname
= strrchr(username
, '@'); /* allow @ in the first part */
4489 if (ast_strlen_zero(username
) || ast_strlen_zero(hostname
)) {
4490 ast_log(LOG_WARNING
, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno
);
4493 /* split user[:secret[:authuser]] */
4494 secret
= strchr(username
, ':');
4497 authuser
= strchr(secret
, ':');
4501 /* split host[:port][/contact] */
4502 contact
= strchr(hostname
, '/');
4505 if (ast_strlen_zero(contact
))
4507 porta
= strchr(hostname
, ':');
4510 portnum
= atoi(porta
);
4512 ast_log(LOG_WARNING
, "%s is not a valid port number at line %d\n", porta
, lineno
);
4516 if (!(reg
= ast_calloc(1, sizeof(*reg
)))) {
4517 ast_log(LOG_ERROR
, "Out of memory. Can't allocate SIP registry entry\n");
4521 if (ast_string_field_init(reg
, 256)) {
4522 ast_log(LOG_ERROR
, "Out of memory. Can't allocate SIP registry strings\n");
4529 ast_string_field_set(reg
, contact
, contact
);
4531 ast_string_field_set(reg
, username
, username
);
4533 ast_string_field_set(reg
, hostname
, hostname
);
4535 ast_string_field_set(reg
, authuser
, authuser
);
4537 ast_string_field_set(reg
, secret
, secret
);
4540 reg
->refresh
= default_expiry
;
4541 reg
->portno
= portnum
;
4542 reg
->callid_valid
= FALSE
;
4543 reg
->ocseq
= INITIAL_CSEQ
;
4544 ASTOBJ_CONTAINER_LINK(®l
, reg
); /* Add the new registry entry to the list */
4545 ASTOBJ_UNREF(reg
,sip_registry_destroy
);
4549 /*! \brief Parse multiline SIP headers into one header
4550 This is enabled if pedanticsipchecking is enabled */
4551 static int lws2sws(char *msgbuf
, int len
)
4557 /* Eliminate all CRs */
4558 if (msgbuf
[h
] == '\r') {
4562 /* Check for end-of-line */
4563 if (msgbuf
[h
] == '\n') {
4564 /* Check for end-of-message */
4567 /* Check for a continuation line */
4568 if (msgbuf
[h
+ 1] == ' ' || msgbuf
[h
+ 1] == '\t') {
4569 /* Merge continuation line */
4573 /* Propagate LF and start new line */
4574 msgbuf
[t
++] = msgbuf
[h
++];
4578 if (msgbuf
[h
] == ' ' || msgbuf
[h
] == '\t') {
4583 msgbuf
[t
++] = msgbuf
[h
++];
4587 msgbuf
[t
++] = msgbuf
[h
++];
4595 /*! \brief Parse a SIP message
4596 \note this function is used both on incoming and outgoing packets
4598 static void parse_request(struct sip_request
*req
)
4600 /* Divide fields by NULL's */
4606 /* First header starts immediately */
4610 /* We've got a new header */
4613 if (sipdebug
&& option_debug
> 3)
4614 ast_log(LOG_DEBUG
, "Header %d: %s (%d)\n", f
, req
->header
[f
], (int) strlen(req
->header
[f
]));
4615 if (ast_strlen_zero(req
->header
[f
])) {
4616 /* Line by itself means we're now in content */
4620 if (f
>= SIP_MAX_HEADERS
- 1) {
4621 ast_log(LOG_WARNING
, "Too many SIP headers. Ignoring.\n");
4624 req
->header
[f
] = c
+ 1;
4625 } else if (*c
== '\r') {
4626 /* Ignore but eliminate \r's */
4631 /* Check for last header */
4632 if (!ast_strlen_zero(req
->header
[f
])) {
4633 if (sipdebug
&& option_debug
> 3)
4634 ast_log(LOG_DEBUG
, "Header %d: %s (%d)\n", f
, req
->header
[f
], (int) strlen(req
->header
[f
]));
4638 /* Now we process any mime content */
4643 /* We've got a new line */
4645 if (sipdebug
&& option_debug
> 3)
4646 ast_log(LOG_DEBUG
, "Line: %s (%d)\n", req
->line
[f
], (int) strlen(req
->line
[f
]));
4647 if (f
>= SIP_MAX_LINES
- 1) {
4648 ast_log(LOG_WARNING
, "Too many SDP lines. Ignoring.\n");
4651 req
->line
[f
] = c
+ 1;
4652 } else if (*c
== '\r') {
4653 /* Ignore and eliminate \r's */
4658 /* Check for last line */
4659 if (!ast_strlen_zero(req
->line
[f
]))
4663 ast_log(LOG_WARNING
, "Odd content, extra stuff left over ('%s')\n", c
);
4664 /* Split up the first line parts */
4665 determine_firstline_parts(req
);
4669 \brief Determine whether a SIP message contains an SDP in its body
4670 \param req the SIP request to process
4671 \return 1 if SDP found, 0 if not found
4673 Also updates req->sdp_start and req->sdp_end to indicate where the SDP
4674 lives in the message body.
4676 static int find_sdp(struct sip_request
*req
)
4678 const char *content_type
;
4682 int boundaryisquoted
= FALSE
;
4684 content_type
= get_header(req
, "Content-Type");
4686 /* if the body contains only SDP, this is easy */
4687 if (!strcasecmp(content_type
, "application/sdp")) {
4689 req
->sdp_end
= req
->lines
;
4693 /* if it's not multipart/mixed, there cannot be an SDP */
4694 if (strncasecmp(content_type
, "multipart/mixed", 15))
4697 /* if there is no boundary marker, it's invalid */
4698 if (!(search
= strcasestr(content_type
, ";boundary=")))
4702 if (ast_strlen_zero(search
))
4705 /* If the boundary is quoted with ", remove quote */
4706 if (*search
== '\"') {
4708 boundaryisquoted
= TRUE
;
4711 /* make a duplicate of the string, with two extra characters
4713 boundary
= ast_strdupa(search
- 2);
4714 boundary
[0] = boundary
[1] = '-';
4716 /* Remove final quote */
4717 if (boundaryisquoted
)
4718 boundary
[strlen(boundary
) - 1] = '\0';
4720 /* search for the boundary marker, but stop when there are not enough
4721 lines left for it, the Content-Type header and at least one line of
4723 for (x
= 0; x
< (req
->lines
- 2); x
++) {
4724 if (!strncasecmp(req
->line
[x
], boundary
, strlen(boundary
)) &&
4725 !strcasecmp(req
->line
[x
+ 1], "Content-Type: application/sdp")) {
4729 /* search for the end of the body part */
4730 for ( ; x
< req
->lines
; x
++) {
4731 if (!strncasecmp(req
->line
[x
], boundary
, strlen(boundary
)))
4742 /*! \brief Change hold state for a call */
4743 static void change_hold_state(struct sip_pvt
*dialog
, struct sip_request
*req
, int holdstate
, int sendonly
)
4745 if (global_notifyhold
)
4746 sip_peer_hold(dialog
, holdstate
);
4747 if (global_callevents
)
4748 manager_event(EVENT_FLAG_CALL
, holdstate
? "Hold" : "Unhold",
4751 dialog
->owner
->name
,
4752 dialog
->owner
->uniqueid
);
4753 append_history(dialog
, holdstate
? "Hold" : "Unhold", "%s", req
->data
);
4754 if (!holdstate
) { /* Put off remote hold */
4755 ast_clear_flag(&dialog
->flags
[1], SIP_PAGE2_CALL_ONHOLD
); /* Clear both flags */
4758 /* No address for RTP, we're on hold */
4760 if (sendonly
== 1) /* One directional hold (sendonly/recvonly) */
4761 ast_set_flag(&dialog
->flags
[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR
);
4762 else if (sendonly
== 2) /* Inactive stream */
4763 ast_set_flag(&dialog
->flags
[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE
);
4765 ast_set_flag(&dialog
->flags
[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE
);
4769 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
4770 If offer is rejected, we will not change any properties of the call
4771 Return 0 on success, a negative value on errors.
4772 Must be called after find_sdp().
4774 static int process_sdp(struct sip_pvt
*p
, struct sip_request
*req
)
4776 const char *m
; /* SDP media offer */
4781 int portno
= -1; /*!< RTP Audio port number */
4782 int vportno
= -1; /*!< RTP Video port number */
4783 int udptlportno
= -1;
4784 int peert38capability
= 0;
4788 /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
4789 int peercapability
= 0, peernoncodeccapability
= 0;
4790 int vpeercapability
= 0, vpeernoncodeccapability
= 0;
4791 struct sockaddr_in sin
; /*!< media socket address */
4792 struct sockaddr_in vsin
; /*!< Video socket address */
4795 struct hostent
*hp
; /*!< RTP Audio host IP */
4796 struct hostent
*vhp
= NULL
; /*!< RTP video host IP */
4797 struct ast_hostent audiohp
;
4798 struct ast_hostent videohp
;
4800 int destiterator
= 0;
4804 struct ast_rtp
*newaudiortp
, *newvideortp
; /* Buffers for codec handling */
4805 int newjointcapability
; /* Negotiated capability */
4806 int newpeercapability
;
4807 int newnoncodeccapability
;
4808 int numberofmediastreams
= 0;
4809 int debug
= sip_debug_test_pvt(p
);
4811 int found_rtpmap_codecs
[32];
4812 int last_rtpmap_codec
=0;
4815 ast_log(LOG_ERROR
, "Got SDP but have no RTP session allocated.\n");
4819 /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
4820 newaudiortp
= alloca(ast_rtp_alloc_size());
4821 memset(newaudiortp
, 0, ast_rtp_alloc_size());
4822 ast_rtp_new_init(newaudiortp
);
4823 ast_rtp_pt_clear(newaudiortp
);
4825 newvideortp
= alloca(ast_rtp_alloc_size());
4826 memset(newvideortp
, 0, ast_rtp_alloc_size());
4827 ast_rtp_new_init(newvideortp
);
4828 ast_rtp_pt_clear(newvideortp
);
4830 /* Update our last rtprx when we receive an SDP, too */
4831 p
->lastrtprx
= p
->lastrtptx
= time(NULL
); /* XXX why both ? */
4834 /* Try to find first media stream */
4835 m
= get_sdp(req
, "m");
4836 destiterator
= req
->sdp_start
;
4837 c
= get_sdp_iterate(&destiterator
, req
, "c");
4838 if (ast_strlen_zero(m
) || ast_strlen_zero(c
)) {
4839 ast_log(LOG_WARNING
, "Insufficient information for SDP (m = '%s', c = '%s')\n", m
, c
);
4843 /* Check for IPv4 address (not IPv6 yet) */
4844 if (sscanf(c
, "IN IP4 %256s", host
) != 1) {
4845 ast_log(LOG_WARNING
, "Invalid host in c= line, '%s'\n", c
);
4849 /* XXX This could block for a long time, and block the main thread! XXX */
4850 hp
= ast_gethostbyname(host
, &audiohp
);
4852 ast_log(LOG_WARNING
, "Unable to lookup host in c= line, '%s'\n", c
);
4855 vhp
= hp
; /* Copy to video address as default too */
4857 iterator
= req
->sdp_start
;
4858 ast_set_flag(&p
->flags
[0], SIP_NOVIDEO
);
4861 /* Find media streams in this SDP offer */
4862 while ((m
= get_sdp_iterate(&iterator
, req
, "m"))[0] != '\0') {
4867 if ((sscanf(m
, "audio %d/%d RTP/AVP %n", &x
, &numberofports
, &len
) == 2) ||
4868 (sscanf(m
, "audio %d RTP/AVP %n", &x
, &len
) == 1)) {
4870 numberofmediastreams
++;
4871 /* Found audio stream in this media definition */
4873 /* Scan through the RTP payload types specified in a "m=" line: */
4874 for (codecs
= m
+ len
; !ast_strlen_zero(codecs
); codecs
= ast_skip_blanks(codecs
+ len
)) {
4875 if (sscanf(codecs
, "%d%n", &codec
, &len
) != 1) {
4876 ast_log(LOG_WARNING
, "Error in codec string '%s'\n", codecs
);
4880 ast_verbose("Found RTP audio format %d\n", codec
);
4881 ast_rtp_set_m_type(newaudiortp
, codec
);
4883 } else if ((sscanf(m
, "video %d/%d RTP/AVP %n", &x
, &numberofports
, &len
) == 2) ||
4884 (sscanf(m
, "video %d RTP/AVP %n", &x
, &len
) == 1)) {
4885 /* If it is not audio - is it video ? */
4886 ast_clear_flag(&p
->flags
[0], SIP_NOVIDEO
);
4887 numberofmediastreams
++;
4889 /* Scan through the RTP payload types specified in a "m=" line: */
4890 for (codecs
= m
+ len
; !ast_strlen_zero(codecs
); codecs
= ast_skip_blanks(codecs
+ len
)) {
4891 if (sscanf(codecs
, "%d%n", &codec
, &len
) != 1) {
4892 ast_log(LOG_WARNING
, "Error in codec string '%s'\n", codecs
);
4896 ast_verbose("Found RTP video format %d\n", codec
);
4897 ast_rtp_set_m_type(newvideortp
, codec
);
4899 } else if (p
->udptl
&& ( (sscanf(m
, "image %d udptl t38%n", &x
, &len
) == 1) ||
4900 (sscanf(m
, "image %d UDPTL t38%n", &x
, &len
) == 1) )) {
4902 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p
->callid
);
4904 numberofmediastreams
++;
4906 if (p
->owner
&& p
->lastinvite
) {
4907 p
->t38
.state
= T38_PEER_REINVITE
; /* T38 Offered in re-invite from remote party */
4908 if (option_debug
> 1)
4909 ast_log(LOG_DEBUG
, "T38 state changed to %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>" );
4911 p
->t38
.state
= T38_PEER_DIRECT
; /* T38 Offered directly from peer in first invite */
4912 if (option_debug
> 1)
4913 ast_log(LOG_DEBUG
, "T38 state changed to %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>");
4916 ast_log(LOG_WARNING
, "Unsupported SDP media type in offer: %s\n", m
);
4917 if (numberofports
> 1)
4918 ast_log(LOG_WARNING
, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports
);
4921 /* Check for Media-description-level-address for audio */
4922 c
= get_sdp_iterate(&destiterator
, req
, "c");
4923 if (!ast_strlen_zero(c
)) {
4924 if (sscanf(c
, "IN IP4 %256s", host
) != 1) {
4925 ast_log(LOG_WARNING
, "Invalid secondary host in c= line, '%s'\n", c
);
4927 /* XXX This could block for a long time, and block the main thread! XXX */
4929 if ( !(hp
= ast_gethostbyname(host
, &audiohp
))) {
4930 ast_log(LOG_WARNING
, "Unable to lookup RTP Audio host in secondary c= line, '%s'\n", c
);
4933 } else if (!(vhp
= ast_gethostbyname(host
, &videohp
))) {
4934 ast_log(LOG_WARNING
, "Unable to lookup RTP video host in secondary c= line, '%s'\n", c
);
4941 if (portno
== -1 && vportno
== -1 && udptlportno
== -1)
4942 /* No acceptable offer found in SDP - we have no ports */
4943 /* Do not change RTP or VRTP if this is a re-invite */
4946 if (numberofmediastreams
> 2)
4947 /* We have too many fax, audio and/or video media streams, fail this offer */
4950 /* RTP addresses and ports for audio and video */
4951 sin
.sin_family
= AF_INET
;
4952 vsin
.sin_family
= AF_INET
;
4953 memcpy(&sin
.sin_addr
, hp
->h_addr
, sizeof(sin
.sin_addr
));
4955 memcpy(&vsin
.sin_addr
, vhp
->h_addr
, sizeof(vsin
.sin_addr
));
4957 /* Setup UDPTL port number */
4959 if (udptlportno
> 0) {
4960 sin
.sin_port
= htons(udptlportno
);
4961 ast_udptl_set_peer(p
->udptl
, &sin
);
4963 ast_log(LOG_DEBUG
,"Peer T.38 UDPTL is at port %s:%d\n",ast_inet_ntoa(sin
.sin_addr
), ntohs(sin
.sin_port
));
4965 ast_udptl_stop(p
->udptl
);
4967 ast_log(LOG_DEBUG
, "Peer doesn't provide T.38 UDPTL\n");
4974 sin
.sin_port
= htons(portno
);
4975 ast_rtp_set_peer(p
->rtp
, &sin
);
4977 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin
.sin_addr
), ntohs(sin
.sin_port
));
4979 if (udptlportno
> 0) {
4981 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session. Callid %s\n", p
->callid
);
4983 ast_rtp_stop(p
->rtp
);
4985 ast_verbose("Peer doesn't provide audio. Callid %s\n", p
->callid
);
4989 /* Setup video port number */
4991 vsin
.sin_port
= htons(vportno
);
4993 /* Next, scan through each "a=rtpmap:" line, noting each
4994 * specified RTP payload type (with corresponding MIME subtype):
4996 /* XXX This needs to be done per media stream, since it's media stream specific */
4997 iterator
= req
->sdp_start
;
4998 while ((a
= get_sdp_iterate(&iterator
, req
, "a"))[0] != '\0') {
4999 char* mimeSubtype
= ast_strdupa(a
); /* ensures we have enough space */
5000 if (option_debug
> 1) {
5001 int breakout
= FALSE
;
5003 /* If we're debugging, check for unsupported sdp options */
5004 if (!strncasecmp(a
, "rtcp:", (size_t) 5)) {
5006 ast_verbose("Got unsupported a:rtcp in SDP offer \n");
5008 } else if (!strncasecmp(a
, "fmtp:", (size_t) 5)) {
5009 /* Format parameters: Not supported */
5010 /* Note: This is used for codec parameters, like bitrate for
5011 G722 and video formats for H263 and H264
5012 See RFC2327 for an example */
5014 ast_verbose("Got unsupported a:fmtp in SDP offer \n");
5016 } else if (!strncasecmp(a
, "framerate:", (size_t) 10)) {
5017 /* Video stuff: Not supported */
5019 ast_verbose("Got unsupported a:framerate in SDP offer \n");
5021 } else if (!strncasecmp(a
, "maxprate:", (size_t) 9)) {
5022 /* Video stuff: Not supported */
5024 ast_verbose("Got unsupported a:maxprate in SDP offer \n");
5026 } else if (!strncasecmp(a
, "crypto:", (size_t) 7)) {
5027 /* SRTP stuff, not yet supported */
5029 ast_verbose("Got unsupported a:crypto in SDP offer \n");
5032 if (breakout
) /* We have a match, skip to next header */
5035 if (!strcasecmp(a
, "sendonly")) {
5039 } else if (!strcasecmp(a
, "inactive")) {
5043 } else if (!strcasecmp(a
, "sendrecv")) {
5047 } else if (strlen(a
) > 5 && !strncasecmp(a
, "ptime", 5)) {
5048 char *tmp
= strrchr(a
, ':');
5049 long int framing
= 0;
5052 framing
= strtol(tmp
, NULL
, 10);
5053 if (framing
== LONG_MIN
|| framing
== LONG_MAX
) {
5056 ast_log(LOG_DEBUG
, "Can't read framing from SDP: %s\n", a
);
5059 if (framing
&& last_rtpmap_codec
) {
5060 if (p
->autoframing
) {
5061 struct ast_codec_pref
*pref
= ast_rtp_codec_getpref(p
->rtp
);
5064 for (codec_n
= 0; codec_n
< last_rtpmap_codec
; codec_n
++) {
5065 format
= ast_rtp_codec_getformat(found_rtpmap_codecs
[codec_n
]);
5066 if (!format
) /* non-codec or not found */
5069 ast_log(LOG_DEBUG
, "Setting framing for %d to %ld\n", format
, framing
);
5070 ast_codec_pref_setsize(pref
, format
, framing
);
5072 ast_rtp_codec_setpref(p
->rtp
, pref
);
5075 memset(&found_rtpmap_codecs
, 0, sizeof(found_rtpmap_codecs
));
5076 last_rtpmap_codec
= 0;
5078 } else if (sscanf(a
, "rtpmap: %u %[^/]/", &codec
, mimeSubtype
) == 2) {
5079 /* We have a rtpmap to handle */
5081 ast_verbose("Found description format %s for ID %d\n", mimeSubtype
, codec
);
5082 found_rtpmap_codecs
[last_rtpmap_codec
] = codec
;
5083 last_rtpmap_codec
++;
5085 /* Note: should really look at the 'freq' and '#chans' params too */
5086 ast_rtp_set_rtpmap_type(newaudiortp
, codec
, "audio", mimeSubtype
,
5087 ast_test_flag(&p
->flags
[0], SIP_G726_NONSTANDARD
) ? AST_RTP_OPT_G726_NONSTANDARD
: 0);
5089 ast_rtp_set_rtpmap_type(newvideortp
, codec
, "video", mimeSubtype
, 0);
5093 if (udptlportno
!= -1) {
5098 /* Scan trough the a= lines for T38 attributes and set apropriate fileds */
5099 iterator
= req
->sdp_start
;
5100 while ((a
= get_sdp_iterate(&iterator
, req
, "a"))[0] != '\0') {
5101 if ((sscanf(a
, "T38FaxMaxBuffer:%d", &x
) == 1)) {
5103 if (option_debug
> 2)
5104 ast_log(LOG_DEBUG
, "MaxBufferSize:%d\n",x
);
5105 } else if ((sscanf(a
, "T38MaxBitRate:%d", &x
) == 1)) {
5107 if (option_debug
> 2)
5108 ast_log(LOG_DEBUG
,"T38MaxBitRate: %d\n",x
);
5111 peert38capability
|= T38FAX_RATE_14400
| T38FAX_RATE_12000
| T38FAX_RATE_9600
| T38FAX_RATE_7200
| T38FAX_RATE_4800
| T38FAX_RATE_2400
;
5114 peert38capability
|= T38FAX_RATE_12000
| T38FAX_RATE_9600
| T38FAX_RATE_7200
| T38FAX_RATE_4800
| T38FAX_RATE_2400
;
5117 peert38capability
|= T38FAX_RATE_9600
| T38FAX_RATE_7200
| T38FAX_RATE_4800
| T38FAX_RATE_2400
;
5120 peert38capability
|= T38FAX_RATE_7200
| T38FAX_RATE_4800
| T38FAX_RATE_2400
;
5123 peert38capability
|= T38FAX_RATE_4800
| T38FAX_RATE_2400
;
5126 peert38capability
|= T38FAX_RATE_2400
;
5129 } else if ((sscanf(a
, "T38FaxVersion:%d", &x
) == 1)) {
5131 if (option_debug
> 2)
5132 ast_log(LOG_DEBUG
, "FaxVersion: %d\n",x
);
5134 peert38capability
|= T38FAX_VERSION_0
;
5136 peert38capability
|= T38FAX_VERSION_1
;
5137 } else if ((sscanf(a
, "T38FaxMaxDatagram:%d", &x
) == 1)) {
5139 if (option_debug
> 2)
5140 ast_log(LOG_DEBUG
, "FaxMaxDatagram: %d\n",x
);
5141 ast_udptl_set_far_max_datagram(p
->udptl
, x
);
5142 ast_udptl_set_local_max_datagram(p
->udptl
, x
);
5143 } else if ((sscanf(a
, "T38FaxFillBitRemoval:%d", &x
) == 1)) {
5145 if (option_debug
> 2)
5146 ast_log(LOG_DEBUG
, "FillBitRemoval: %d\n",x
);
5148 peert38capability
|= T38FAX_FILL_BIT_REMOVAL
;
5149 } else if ((sscanf(a
, "T38FaxTranscodingMMR:%d", &x
) == 1)) {
5151 if (option_debug
> 2)
5152 ast_log(LOG_DEBUG
, "Transcoding MMR: %d\n",x
);
5154 peert38capability
|= T38FAX_TRANSCODING_MMR
;
5156 if ((sscanf(a
, "T38FaxTranscodingJBIG:%d", &x
) == 1)) {
5158 if (option_debug
> 2)
5159 ast_log(LOG_DEBUG
, "Transcoding JBIG: %d\n",x
);
5161 peert38capability
|= T38FAX_TRANSCODING_JBIG
;
5162 } else if ((sscanf(a
, "T38FaxRateManagement:%255s", s
) == 1)) {
5164 if (option_debug
> 2)
5165 ast_log(LOG_DEBUG
, "RateManagement: %s\n", s
);
5166 if (!strcasecmp(s
, "localTCF"))
5167 peert38capability
|= T38FAX_RATE_MANAGEMENT_LOCAL_TCF
;
5168 else if (!strcasecmp(s
, "transferredTCF"))
5169 peert38capability
|= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF
;
5170 } else if ((sscanf(a
, "T38FaxUdpEC:%255s", s
) == 1)) {
5172 if (option_debug
> 2)
5173 ast_log(LOG_DEBUG
, "UDP EC: %s\n", s
);
5174 if (!strcasecmp(s
, "t38UDPRedundancy")) {
5175 peert38capability
|= T38FAX_UDP_EC_REDUNDANCY
;
5176 ast_udptl_set_error_correction_scheme(p
->udptl
, UDPTL_ERROR_CORRECTION_REDUNDANCY
);
5177 } else if (!strcasecmp(s
, "t38UDPFEC")) {
5178 peert38capability
|= T38FAX_UDP_EC_FEC
;
5179 ast_udptl_set_error_correction_scheme(p
->udptl
, UDPTL_ERROR_CORRECTION_FEC
);
5181 peert38capability
|= T38FAX_UDP_EC_NONE
;
5182 ast_udptl_set_error_correction_scheme(p
->udptl
, UDPTL_ERROR_CORRECTION_NONE
);
5186 if (found
) { /* Some cisco equipment returns nothing beside c= and m= lines in 200 OK T38 SDP */
5187 p
->t38
.peercapability
= peert38capability
;
5188 p
->t38
.jointcapability
= (peert38capability
& 255); /* Put everything beside supported speeds settings */
5189 peert38capability
&= (T38FAX_RATE_14400
| T38FAX_RATE_12000
| T38FAX_RATE_9600
| T38FAX_RATE_7200
| T38FAX_RATE_4800
| T38FAX_RATE_2400
);
5190 p
->t38
.jointcapability
|= (peert38capability
& p
->t38
.capability
); /* Put the lower of our's and peer's speed */
5193 ast_log(LOG_DEBUG
, "Our T38 capability = (%d), peer T38 capability (%d), joint T38 capability (%d)\n",
5195 p
->t38
.peercapability
,
5196 p
->t38
.jointcapability
);
5198 p
->t38
.state
= T38_DISABLED
;
5199 if (option_debug
> 2)
5200 ast_log(LOG_DEBUG
, "T38 state changed to %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>");
5203 /* Now gather all of the codecs that we are asked for: */
5204 ast_rtp_get_current_formats(newaudiortp
, &peercapability
, &peernoncodeccapability
);
5205 ast_rtp_get_current_formats(newvideortp
, &vpeercapability
, &vpeernoncodeccapability
);
5207 newjointcapability
= p
->capability
& (peercapability
| vpeercapability
);
5208 newpeercapability
= (peercapability
| vpeercapability
);
5209 newnoncodeccapability
= p
->noncodeccapability
& peernoncodeccapability
;
5213 /* shame on whoever coded this.... */
5214 char s1
[BUFSIZ
], s2
[BUFSIZ
], s3
[BUFSIZ
], s4
[BUFSIZ
];
5216 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
5217 ast_getformatname_multiple(s1
, BUFSIZ
, p
->capability
),
5218 ast_getformatname_multiple(s2
, BUFSIZ
, newpeercapability
),
5219 ast_getformatname_multiple(s3
, BUFSIZ
, vpeercapability
),
5220 ast_getformatname_multiple(s4
, BUFSIZ
, newjointcapability
));
5222 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
5223 ast_rtp_lookup_mime_multiple(s1
, BUFSIZ
, p
->noncodeccapability
, 0, 0),
5224 ast_rtp_lookup_mime_multiple(s2
, BUFSIZ
, peernoncodeccapability
, 0, 0),
5225 ast_rtp_lookup_mime_multiple(s3
, BUFSIZ
, newnoncodeccapability
, 0, 0));
5227 if (!newjointcapability
) {
5228 /* If T.38 was not negotiated either, totally bail out... */
5229 if (!p
->t38
.jointcapability
) {
5230 ast_log(LOG_NOTICE
, "No compatible codecs, not accepting this offer!\n");
5231 /* Do NOT Change current setting */
5234 if (option_debug
> 2)
5235 ast_log(LOG_DEBUG
, "Have T.38 but no audio codecs, accepting offer anyway\n");
5240 /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
5241 they are acceptable */
5242 p
->jointcapability
= newjointcapability
; /* Our joint codec profile for this call */
5243 p
->peercapability
= newpeercapability
; /* The other sides capability in latest offer */
5244 p
->jointnoncodeccapability
= newnoncodeccapability
; /* DTMF capabilities */
5246 ast_rtp_pt_copy(p
->rtp
, newaudiortp
);
5248 ast_rtp_pt_copy(p
->vrtp
, newvideortp
);
5250 if (ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_AUTO
) {
5251 ast_clear_flag(&p
->flags
[0], SIP_DTMF
);
5252 if (newnoncodeccapability
& AST_RTP_DTMF
) {
5253 /* XXX Would it be reasonable to drop the DSP at this point? XXX */
5254 ast_set_flag(&p
->flags
[0], SIP_DTMF_RFC2833
);
5255 /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
5256 ast_rtp_setdtmf(p
->rtp
, 1);
5257 ast_rtp_setdtmfcompensate(p
->rtp
, ast_test_flag(&p
->flags
[1], SIP_PAGE2_RFC2833_COMPENSATE
));
5259 ast_set_flag(&p
->flags
[0], SIP_DTMF_INBAND
);
5263 /* Setup audio port number */
5264 if (p
->rtp
&& sin
.sin_port
) {
5265 ast_rtp_set_peer(p
->rtp
, &sin
);
5267 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin
.sin_addr
), ntohs(sin
.sin_port
));
5270 /* Setup video port number */
5271 if (p
->vrtp
&& vsin
.sin_port
) {
5272 ast_rtp_set_peer(p
->vrtp
, &vsin
);
5274 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin
.sin_addr
), ntohs(vsin
.sin_port
));
5277 /* Ok, we're going with this offer */
5278 if (option_debug
> 1) {
5280 ast_log(LOG_DEBUG
, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf
, BUFSIZ
, p
->jointcapability
));
5283 if (!p
->owner
) /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
5286 if (option_debug
> 3)
5287 ast_log(LOG_DEBUG
, "We have an owner, now see if we need to change this call\n");
5289 if (!(p
->owner
->nativeformats
& p
->jointcapability
) && (p
->jointcapability
& AST_FORMAT_AUDIO_MASK
)) {
5291 char s1
[BUFSIZ
], s2
[BUFSIZ
];
5292 ast_log(LOG_DEBUG
, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
5293 ast_getformatname_multiple(s1
, BUFSIZ
, p
->jointcapability
),
5294 ast_getformatname_multiple(s2
, BUFSIZ
, p
->owner
->nativeformats
));
5296 p
->owner
->nativeformats
= ast_codec_choose(&p
->prefs
, p
->jointcapability
, 1) | (p
->capability
& vpeercapability
);
5297 ast_set_read_format(p
->owner
, p
->owner
->readformat
);
5298 ast_set_write_format(p
->owner
, p
->owner
->writeformat
);
5301 if (ast_test_flag(&p
->flags
[1], SIP_PAGE2_CALL_ONHOLD
) && sin
.sin_addr
.s_addr
&& (!sendonly
|| sendonly
== -1)) {
5302 ast_queue_control(p
->owner
, AST_CONTROL_UNHOLD
);
5303 /* Activate a re-invite */
5304 ast_queue_frame(p
->owner
, &ast_null_frame
);
5305 } else if (!sin
.sin_addr
.s_addr
|| (sendonly
&& sendonly
!= -1)) {
5306 ast_queue_control_data(p
->owner
, AST_CONTROL_HOLD
,
5307 S_OR(p
->mohsuggest
, NULL
),
5308 !ast_strlen_zero(p
->mohsuggest
) ? strlen(p
->mohsuggest
) + 1 : 0);
5310 ast_rtp_stop(p
->rtp
);
5311 /* RTCP needs to go ahead, even if we're on hold!!! */
5312 /* Activate a re-invite */
5313 ast_queue_frame(p
->owner
, &ast_null_frame
);
5316 /* Manager Hold and Unhold events must be generated, if necessary */
5317 if (ast_test_flag(&p
->flags
[1], SIP_PAGE2_CALL_ONHOLD
) && sin
.sin_addr
.s_addr
&& (!sendonly
|| sendonly
== -1))
5318 change_hold_state(p
, req
, FALSE
, sendonly
);
5319 else if (!sin
.sin_addr
.s_addr
|| (sendonly
&& sendonly
!= -1))
5320 change_hold_state(p
, req
, TRUE
, sendonly
);
5325 /*! \brief Add header to SIP message */
5326 static int add_header(struct sip_request
*req
, const char *var
, const char *value
)
5328 int maxlen
= sizeof(req
->data
) - 4 - req
->len
; /* 4 bytes are for two \r\n ? */
5330 if (req
->headers
== SIP_MAX_HEADERS
) {
5331 ast_log(LOG_WARNING
, "Out of SIP header space\n");
5336 ast_log(LOG_WARNING
, "Can't add more headers when lines have been added\n");
5341 ast_log(LOG_WARNING
, "Out of space, can't add anymore (%s:%s)\n", var
, value
);
5345 req
->header
[req
->headers
] = req
->data
+ req
->len
;
5348 var
= find_alias(var
, var
);
5350 snprintf(req
->header
[req
->headers
], maxlen
, "%s: %s\r\n", var
, value
);
5351 req
->len
+= strlen(req
->header
[req
->headers
]);
5353 if (req
->headers
< SIP_MAX_HEADERS
)
5356 ast_log(LOG_WARNING
, "Out of SIP header space... Will generate broken SIP message\n");
5361 /*! \brief Add 'Content-Length' header to SIP message */
5362 static int add_header_contentLength(struct sip_request
*req
, int len
)
5366 snprintf(clen
, sizeof(clen
), "%d", len
);
5367 return add_header(req
, "Content-Length", clen
);
5370 /*! \brief Add content (not header) to SIP message */
5371 static int add_line(struct sip_request
*req
, const char *line
)
5373 if (req
->lines
== SIP_MAX_LINES
) {
5374 ast_log(LOG_WARNING
, "Out of SIP line space\n");
5378 /* Add extra empty return */
5379 snprintf(req
->data
+ req
->len
, sizeof(req
->data
) - req
->len
, "\r\n");
5380 req
->len
+= strlen(req
->data
+ req
->len
);
5382 if (req
->len
>= sizeof(req
->data
) - 4) {
5383 ast_log(LOG_WARNING
, "Out of space, can't add anymore\n");
5386 req
->line
[req
->lines
] = req
->data
+ req
->len
;
5387 snprintf(req
->line
[req
->lines
], sizeof(req
->data
) - req
->len
, "%s", line
);
5388 req
->len
+= strlen(req
->line
[req
->lines
]);
5393 /*! \brief Copy one header field from one request to another */
5394 static int copy_header(struct sip_request
*req
, const struct sip_request
*orig
, const char *field
)
5396 const char *tmp
= get_header(orig
, field
);
5398 if (!ast_strlen_zero(tmp
)) /* Add what we're responding to */
5399 return add_header(req
, field
, tmp
);
5400 ast_log(LOG_NOTICE
, "No field '%s' present to copy\n", field
);
5404 /*! \brief Copy all headers from one request to another */
5405 static int copy_all_header(struct sip_request
*req
, const struct sip_request
*orig
, const char *field
)
5410 const char *tmp
= __get_header(orig
, field
, &start
);
5412 if (ast_strlen_zero(tmp
))
5414 /* Add what we're responding to */
5415 add_header(req
, field
, tmp
);
5418 return copied
? 0 : -1;
5421 /*! \brief Copy SIP VIA Headers from the request to the response
5422 \note If the client indicates that it wishes to know the port we received from,
5423 it adds ;rport without an argument to the topmost via header. We need to
5424 add the port number (from our point of view) to that parameter.
5425 We always add ;received=<ip address> to the topmost via header.
5426 Received: RFC 3261, rport RFC 3581 */
5427 static int copy_via_headers(struct sip_pvt
*p
, struct sip_request
*req
, const struct sip_request
*orig
, const char *field
)
5434 const char *oh
= __get_header(orig
, field
, &start
);
5436 if (ast_strlen_zero(oh
))
5439 if (!copied
) { /* Only check for empty rport in topmost via header */
5440 char leftmost
[256], *others
, *rport
;
5442 /* Only work on leftmost value */
5443 ast_copy_string(leftmost
, oh
, sizeof(leftmost
));
5444 others
= strchr(leftmost
, ',');
5448 /* Find ;rport; (empty request) */
5449 rport
= strstr(leftmost
, ";rport");
5450 if (rport
&& *(rport
+6) == '=')
5451 rport
= NULL
; /* We already have a parameter to rport */
5453 /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting) */
5454 if (rport
&& ((ast_test_flag(&p
->flags
[0], SIP_NAT
) == SIP_NAT_ALWAYS
) || (ast_test_flag(&p
->flags
[0], SIP_NAT
) == SIP_NAT_RFC3581
))) {
5455 /* We need to add received port - rport */
5458 rport
= strstr(leftmost
, ";rport");
5461 end
= strchr(rport
+ 1, ';');
5463 memmove(rport
, end
, strlen(end
) + 1);
5468 /* Add rport to first VIA header if requested */
5469 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
5470 leftmost
, ast_inet_ntoa(p
->recv
.sin_addr
),
5471 ntohs(p
->recv
.sin_port
),
5472 others
? "," : "", others
? others
: "");
5474 /* We should *always* add a received to the topmost via */
5475 snprintf(new, sizeof(new), "%s;received=%s%s%s",
5476 leftmost
, ast_inet_ntoa(p
->recv
.sin_addr
),
5477 others
? "," : "", others
? others
: "");
5479 oh
= new; /* the header to copy */
5480 } /* else add the following via headers untouched */
5481 add_header(req
, field
, oh
);
5485 ast_log(LOG_NOTICE
, "No header field '%s' present to copy\n", field
);
5491 /*! \brief Add route header into request per learned route */
5492 static void add_route(struct sip_request
*req
, struct sip_route
*route
)
5494 char r
[BUFSIZ
*2], *p
;
5495 int n
, rem
= sizeof(r
);
5501 for (;route
; route
= route
->next
) {
5502 n
= strlen(route
->hop
);
5503 if (rem
< n
+3) /* we need room for ",<route>" */
5505 if (p
!= r
) { /* add a separator after fist route */
5510 ast_copy_string(p
, route
->hop
, rem
); /* cannot fail */
5516 add_header(req
, "Route", r
);
5519 /*! \brief Set destination from SIP URI */
5520 static void set_destination(struct sip_pvt
*p
, char *uri
)
5522 char *h
, *maddr
, hostname
[256];
5525 struct ast_hostent ahp
;
5526 int debug
=sip_debug_test_pvt(p
);
5528 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
5529 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
5532 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri
);
5534 /* Find and parse hostname */
5535 h
= strchr(uri
, '@');
5540 if (strncasecmp(h
, "sip:", 4) == 0)
5542 else if (strncasecmp(h
, "sips:", 5) == 0)
5545 hn
= strcspn(h
, ":;>") + 1;
5546 if (hn
> sizeof(hostname
))
5547 hn
= sizeof(hostname
);
5548 ast_copy_string(hostname
, h
, hn
);
5549 /* XXX bug here if string has been trimmed to sizeof(hostname) */
5552 /* Is "port" present? if not default to STANDARD_SIP_PORT */
5556 port
= strtol(h
, &h
, 10);
5559 port
= STANDARD_SIP_PORT
;
5561 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
5562 maddr
= strstr(h
, "maddr=");
5565 hn
= strspn(maddr
, "0123456789.") + 1;
5566 if (hn
> sizeof(hostname
))
5567 hn
= sizeof(hostname
);
5568 ast_copy_string(hostname
, maddr
, hn
);
5571 hp
= ast_gethostbyname(hostname
, &ahp
);
5573 ast_log(LOG_WARNING
, "Can't find address for host '%s'\n", hostname
);
5576 p
->sa
.sin_family
= AF_INET
;
5577 memcpy(&p
->sa
.sin_addr
, hp
->h_addr
, sizeof(p
->sa
.sin_addr
));
5578 p
->sa
.sin_port
= htons(port
);
5580 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p
->sa
.sin_addr
), port
);
5583 /*! \brief Initialize SIP response, based on SIP request */
5584 static int init_resp(struct sip_request
*resp
, const char *msg
)
5586 /* Initialize a response */
5587 memset(resp
, 0, sizeof(*resp
));
5588 resp
->method
= SIP_RESPONSE
;
5589 resp
->header
[0] = resp
->data
;
5590 snprintf(resp
->header
[0], sizeof(resp
->data
), "SIP/2.0 %s\r\n", msg
);
5591 resp
->len
= strlen(resp
->header
[0]);
5596 /*! \brief Initialize SIP request */
5597 static int init_req(struct sip_request
*req
, int sipmethod
, const char *recip
)
5599 /* Initialize a request */
5600 memset(req
, 0, sizeof(*req
));
5601 req
->method
= sipmethod
;
5602 req
->header
[0] = req
->data
;
5603 snprintf(req
->header
[0], sizeof(req
->data
), "%s %s SIP/2.0\r\n", sip_methods
[sipmethod
].text
, recip
);
5604 req
->len
= strlen(req
->header
[0]);
5610 /*! \brief Prepare SIP response packet */
5611 static int respprep(struct sip_request
*resp
, struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
)
5616 init_resp(resp
, msg
);
5617 copy_via_headers(p
, resp
, req
, "Via");
5619 copy_all_header(resp
, req
, "Record-Route");
5620 copy_header(resp
, req
, "From");
5621 ot
= get_header(req
, "To");
5622 if (!strcasestr(ot
, "tag=") && strncmp(msg
, "100", 3)) {
5623 /* Add the proper tag if we don't have it already. If they have specified
5624 their tag, use it. Otherwise, use our own tag */
5625 if (!ast_strlen_zero(p
->theirtag
) && ast_test_flag(&p
->flags
[0], SIP_OUTGOING
))
5626 snprintf(newto
, sizeof(newto
), "%s;tag=%s", ot
, p
->theirtag
);
5627 else if (p
->tag
&& !ast_test_flag(&p
->flags
[0], SIP_OUTGOING
))
5628 snprintf(newto
, sizeof(newto
), "%s;tag=%s", ot
, p
->tag
);
5630 ast_copy_string(newto
, ot
, sizeof(newto
));
5633 add_header(resp
, "To", ot
);
5634 copy_header(resp
, req
, "Call-ID");
5635 copy_header(resp
, req
, "CSeq");
5636 if (!ast_strlen_zero(global_useragent
))
5637 add_header(resp
, "User-Agent", global_useragent
);
5638 add_header(resp
, "Allow", ALLOWED_METHODS
);
5639 add_header(resp
, "Supported", SUPPORTED_EXTENSIONS
);
5640 if (msg
[0] == '2' && (p
->method
== SIP_SUBSCRIBE
|| p
->method
== SIP_REGISTER
)) {
5641 /* For registration responses, we also need expiry and
5645 snprintf(tmp
, sizeof(tmp
), "%d", p
->expiry
);
5646 add_header(resp
, "Expires", tmp
);
5647 if (p
->expiry
) { /* Only add contact if we have an expiry time */
5648 char contact
[BUFSIZ
];
5649 snprintf(contact
, sizeof(contact
), "%s;expires=%d", p
->our_contact
, p
->expiry
);
5650 add_header(resp
, "Contact", contact
); /* Not when we unregister */
5652 } else if (msg
[0] != '4' && p
->our_contact
[0]) {
5653 add_header(resp
, "Contact", p
->our_contact
);
5658 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
5659 static int reqprep(struct sip_request
*req
, struct sip_pvt
*p
, int sipmethod
, int seqno
, int newbranch
)
5661 struct sip_request
*orig
= &p
->initreq
;
5666 const char *ot
, *of
;
5667 int is_strict
= FALSE
; /*!< Strict routing flag */
5669 memset(req
, 0, sizeof(struct sip_request
));
5671 snprintf(p
->lastmsg
, sizeof(p
->lastmsg
), "Tx: %s", sip_methods
[sipmethod
].text
);
5679 p
->branch
^= ast_random();
5683 /* Check for strict or loose router */
5684 if (p
->route
&& !ast_strlen_zero(p
->route
->hop
) && strstr(p
->route
->hop
,";lr") == NULL
) {
5687 ast_log(LOG_DEBUG
, "Strict routing enforced for session %s\n", p
->callid
);
5690 if (sipmethod
== SIP_CANCEL
)
5691 c
= p
->initreq
.rlPart2
; /* Use original URI */
5692 else if (sipmethod
== SIP_ACK
) {
5693 /* Use URI from Contact: in 200 OK (if INVITE)
5694 (we only have the contacturi on INVITEs) */
5695 if (!ast_strlen_zero(p
->okcontacturi
))
5696 c
= is_strict
? p
->route
->hop
: p
->okcontacturi
;
5698 c
= p
->initreq
.rlPart2
;
5699 } else if (!ast_strlen_zero(p
->okcontacturi
))
5700 c
= is_strict
? p
->route
->hop
: p
->okcontacturi
; /* Use for BYE or REINVITE */
5701 else if (!ast_strlen_zero(p
->uri
))
5705 /* We have no URI, use To: or From: header as URI (depending on direction) */
5706 ast_copy_string(stripped
, get_header(orig
, (ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) ? "To" : "From"),
5708 n
= get_in_brackets(stripped
);
5709 c
= strsep(&n
, ";"); /* trim ; and beyond */
5711 init_req(req
, sipmethod
, c
);
5713 snprintf(tmp
, sizeof(tmp
), "%d %s", seqno
, sip_methods
[sipmethod
].text
);
5715 add_header(req
, "Via", p
->via
);
5717 set_destination(p
, p
->route
->hop
);
5718 add_route(req
, is_strict
? p
->route
->next
: p
->route
);
5721 ot
= get_header(orig
, "To");
5722 of
= get_header(orig
, "From");
5724 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
5725 as our original request, including tag (or presumably lack thereof) */
5726 if (!strcasestr(ot
, "tag=") && sipmethod
!= SIP_CANCEL
) {
5727 /* Add the proper tag if we don't have it already. If they have specified
5728 their tag, use it. Otherwise, use our own tag */
5729 if (ast_test_flag(&p
->flags
[0], SIP_OUTGOING
) && !ast_strlen_zero(p
->theirtag
))
5730 snprintf(newto
, sizeof(newto
), "%s;tag=%s", ot
, p
->theirtag
);
5731 else if (!ast_test_flag(&p
->flags
[0], SIP_OUTGOING
))
5732 snprintf(newto
, sizeof(newto
), "%s;tag=%s", ot
, p
->tag
);
5734 snprintf(newto
, sizeof(newto
), "%s", ot
);
5738 if (ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) {
5739 add_header(req
, "From", of
);
5740 add_header(req
, "To", ot
);
5742 add_header(req
, "From", ot
);
5743 add_header(req
, "To", of
);
5745 /* Do not add Contact for MESSAGE, BYE and Cancel requests */
5746 if (sipmethod
!= SIP_BYE
&& sipmethod
!= SIP_CANCEL
&& sipmethod
!= SIP_MESSAGE
)
5747 add_header(req
, "Contact", p
->our_contact
);
5749 copy_header(req
, orig
, "Call-ID");
5750 add_header(req
, "CSeq", tmp
);
5752 if (!ast_strlen_zero(global_useragent
))
5753 add_header(req
, "User-Agent", global_useragent
);
5754 add_header(req
, "Max-Forwards", DEFAULT_MAX_FORWARDS
);
5756 if (!ast_strlen_zero(p
->rpid
))
5757 add_header(req
, "Remote-Party-ID", p
->rpid
);
5762 /*! \brief Base transmit response function */
5763 static int __transmit_response(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
, enum xmittype reliable
)
5765 struct sip_request resp
;
5768 if (reliable
&& (sscanf(get_header(req
, "CSeq"), "%d ", &seqno
) != 1)) {
5769 ast_log(LOG_WARNING
, "Unable to determine sequence number from '%s'\n", get_header(req
, "CSeq"));
5772 respprep(&resp
, p
, msg
, req
);
5773 add_header_contentLength(&resp
, 0);
5774 /* If we are cancelling an incoming invite for some reason, add information
5775 about the reason why we are doing this in clear text */
5776 if (p
->method
== SIP_INVITE
&& msg
[0] != '1' && p
->owner
&& p
->owner
->hangupcause
) {
5779 add_header(&resp
, "X-Asterisk-HangupCause", ast_cause2str(p
->owner
->hangupcause
));
5780 snprintf(buf
, sizeof(buf
), "%d", p
->owner
->hangupcause
);
5781 add_header(&resp
, "X-Asterisk-HangupCauseCode", buf
);
5783 return send_response(p
, &resp
, reliable
, seqno
);
5786 static void temp_pvt_cleanup(void *data
)
5788 struct sip_pvt
*p
= data
;
5790 ast_string_field_free_pools(p
);
5795 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
5796 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
)
5798 struct sip_pvt
*p
= NULL
;
5800 if (!(p
= ast_threadstorage_get(&ts_temp_pvt
, sizeof(*p
)))) {
5801 ast_log(LOG_NOTICE
, "Failed to get temporary pvt\n");
5805 /* if the structure was just allocated, initialize it */
5806 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
)) {
5807 ast_set_flag(&p
->flags
[0], SIP_NO_HISTORY
);
5808 if (ast_string_field_init(p
, 512))
5812 /* Initialize the bare minimum */
5813 p
->method
= intended_method
;
5817 if (ast_sip_ouraddrfor(&p
->sa
.sin_addr
, &p
->ourip
))
5822 p
->branch
= ast_random();
5823 make_our_tag(p
->tag
, sizeof(p
->tag
));
5824 p
->ocseq
= INITIAL_CSEQ
;
5826 if (useglobal_nat
&& sin
) {
5827 ast_copy_flags(&p
->flags
[0], &global_flags
[0], SIP_NAT
);
5829 do_setnat(p
, ast_test_flag(&p
->flags
[0], SIP_NAT
) & SIP_NAT_ROUTE
);
5832 ast_string_field_set(p
, fromdomain
, default_fromdomain
);
5834 ast_string_field_set(p
, callid
, callid
);
5836 /* Use this temporary pvt structure to send the message */
5837 __transmit_response(p
, msg
, req
, XMIT_UNRELIABLE
);
5839 /* Free the string fields, but not the pool space */
5840 ast_string_field_free_all(p
);
5845 /*! \brief Transmit response, no retransmits */
5846 static int transmit_response(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
)
5848 return __transmit_response(p
, msg
, req
, XMIT_UNRELIABLE
);
5851 /*! \brief Transmit response, no retransmits */
5852 static int transmit_response_with_unsupported(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
, const char *unsupported
)
5854 struct sip_request resp
;
5855 respprep(&resp
, p
, msg
, req
);
5857 add_header(&resp
, "Unsupported", unsupported
);
5858 add_header_contentLength(&resp
, 0);
5859 return send_response(p
, &resp
, XMIT_UNRELIABLE
, 0);
5862 /*! \brief Transmit response, Make sure you get an ACK
5863 This is only used for responses to INVITEs, where we need to make sure we get an ACK
5865 static int transmit_response_reliable(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
)
5867 return __transmit_response(p
, msg
, req
, XMIT_CRITICAL
);
5870 /*! \brief Append date to SIP message */
5871 static void append_date(struct sip_request
*req
)
5875 time_t t
= time(NULL
);
5878 strftime(tmpdat
, sizeof(tmpdat
), "%a, %d %b %Y %T GMT", &tm
);
5879 add_header(req
, "Date", tmpdat
);
5882 /*! \brief Append date and content length before transmitting response */
5883 static int transmit_response_with_date(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
)
5885 struct sip_request resp
;
5886 respprep(&resp
, p
, msg
, req
);
5888 add_header_contentLength(&resp
, 0);
5889 return send_response(p
, &resp
, XMIT_UNRELIABLE
, 0);
5892 /*! \brief Append Accept header, content length before transmitting response */
5893 static int transmit_response_with_allow(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
, enum xmittype reliable
)
5895 struct sip_request resp
;
5896 respprep(&resp
, p
, msg
, req
);
5897 add_header(&resp
, "Accept", "application/sdp");
5898 add_header_contentLength(&resp
, 0);
5899 return send_response(p
, &resp
, reliable
, 0);
5902 /*! \brief Respond with authorization request */
5903 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
)
5905 struct sip_request resp
;
5909 if (reliable
&& (sscanf(get_header(req
, "CSeq"), "%d ", &seqno
) != 1)) {
5910 ast_log(LOG_WARNING
, "Unable to determine sequence number from '%s'\n", get_header(req
, "CSeq"));
5913 /* Stale means that they sent us correct authentication, but
5914 based it on an old challenge (nonce) */
5915 snprintf(tmp
, sizeof(tmp
), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm
, randdata
, stale
? ", stale=true" : "");
5916 respprep(&resp
, p
, msg
, req
);
5917 add_header(&resp
, header
, tmp
);
5918 add_header_contentLength(&resp
, 0);
5919 append_history(p
, "AuthChal", "Auth challenge sent for %s - nc %d", p
->username
, p
->noncecount
);
5920 return send_response(p
, &resp
, reliable
, seqno
);
5923 /*! \brief Add text body to SIP message */
5924 static int add_text(struct sip_request
*req
, const char *text
)
5926 /* XXX Convert \n's to \r\n's XXX */
5927 add_header(req
, "Content-Type", "text/plain");
5928 add_header_contentLength(req
, strlen(text
));
5929 add_line(req
, text
);
5933 /*! \brief Add DTMF INFO tone to sip message */
5934 /* Always adds default duration 250 ms, regardless of what came in over the line */
5935 static int add_digit(struct sip_request
*req
, char digit
, unsigned int duration
)
5939 snprintf(tmp
, sizeof(tmp
), "Signal=%c\r\nDuration=%u\r\n", digit
, duration
);
5940 add_header(req
, "Content-Type", "application/dtmf-relay");
5941 add_header_contentLength(req
, strlen(tmp
));
5946 /*! \brief add XML encoded media control with update
5947 \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
5948 static int add_vidupdate(struct sip_request
*req
)
5950 const char *xml_is_a_huge_waste_of_space
=
5951 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
5952 " <media_control>\r\n"
5953 " <vc_primitive>\r\n"
5955 " <picture_fast_update>\r\n"
5956 " </picture_fast_update>\r\n"
5957 " </to_encoder>\r\n"
5958 " </vc_primitive>\r\n"
5959 " </media_control>\r\n";
5960 add_header(req
, "Content-Type", "application/media_control+xml");
5961 add_header_contentLength(req
, strlen(xml_is_a_huge_waste_of_space
));
5962 add_line(req
, xml_is_a_huge_waste_of_space
);
5966 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
5967 static void add_codec_to_sdp(const struct sip_pvt
*p
, int codec
, int sample_rate
,
5968 char **m_buf
, size_t *m_size
, char **a_buf
, size_t *a_size
,
5969 int debug
, int *min_packet_size
)
5972 struct ast_format_list fmt
;
5976 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec
, ast_getformatname(codec
));
5977 if ((rtp_code
= ast_rtp_lookup_code(p
->rtp
, 1, codec
)) == -1)
5981 struct ast_codec_pref
*pref
= ast_rtp_codec_getpref(p
->rtp
);
5982 fmt
= ast_codec_pref_getsize(pref
, codec
);
5983 } 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 */
5985 ast_build_string(m_buf
, m_size
, " %d", rtp_code
);
5986 ast_build_string(a_buf
, a_size
, "a=rtpmap:%d %s/%d\r\n", rtp_code
,
5987 ast_rtp_lookup_mime_subtype(1, codec
,
5988 ast_test_flag(&p
->flags
[0], SIP_G726_NONSTANDARD
) ? AST_RTP_OPT_G726_NONSTANDARD
: 0),
5990 if (codec
== AST_FORMAT_G729A
) {
5991 /* Indicate that we don't support VAD (G.729 annex B) */
5992 ast_build_string(a_buf
, a_size
, "a=fmtp:%d annexb=no\r\n", rtp_code
);
5993 } else if (codec
== AST_FORMAT_ILBC
) {
5994 /* Add information about us using only 20/30 ms packetization */
5995 ast_build_string(a_buf
, a_size
, "a=fmtp:%d mode=%d\r\n", rtp_code
, fmt
.cur_ms
);
5998 if (fmt
.cur_ms
&& (fmt
.cur_ms
< *min_packet_size
))
5999 *min_packet_size
= fmt
.cur_ms
;
6001 /* Our first codec packetization processed cannot be less than zero */
6002 if ((*min_packet_size
) == 0 && fmt
.cur_ms
)
6003 *min_packet_size
= fmt
.cur_ms
;
6006 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
6007 static int t38_get_rate(int t38cap
)
6009 int maxrate
= (t38cap
& (T38FAX_RATE_14400
| T38FAX_RATE_12000
| T38FAX_RATE_9600
| T38FAX_RATE_7200
| T38FAX_RATE_4800
| T38FAX_RATE_2400
));
6011 if (maxrate
& T38FAX_RATE_14400
) {
6012 if (option_debug
> 1)
6013 ast_log(LOG_DEBUG
, "T38MaxFaxRate 14400 found\n");
6015 } else if (maxrate
& T38FAX_RATE_12000
) {
6016 if (option_debug
> 1)
6017 ast_log(LOG_DEBUG
, "T38MaxFaxRate 12000 found\n");
6019 } else if (maxrate
& T38FAX_RATE_9600
) {
6020 if (option_debug
> 1)
6021 ast_log(LOG_DEBUG
, "T38MaxFaxRate 9600 found\n");
6023 } else if (maxrate
& T38FAX_RATE_7200
) {
6024 if (option_debug
> 1)
6025 ast_log(LOG_DEBUG
, "T38MaxFaxRate 7200 found\n");
6027 } else if (maxrate
& T38FAX_RATE_4800
) {
6028 if (option_debug
> 1)
6029 ast_log(LOG_DEBUG
, "T38MaxFaxRate 4800 found\n");
6031 } else if (maxrate
& T38FAX_RATE_2400
) {
6032 if (option_debug
> 1)
6033 ast_log(LOG_DEBUG
, "T38MaxFaxRate 2400 found\n");
6036 if (option_debug
> 1)
6037 ast_log(LOG_DEBUG
, "Strange, T38MaxFaxRate NOT found in peers T38 SDP.\n");
6042 /*! \brief Add T.38 Session Description Protocol message */
6043 static int add_t38_sdp(struct sip_request
*resp
, struct sip_pvt
*p
)
6047 struct sockaddr_in udptlsin
;
6055 char *m_modem_next
= m_modem
;
6056 size_t m_modem_left
= sizeof(m_modem
);
6057 char *a_modem_next
= a_modem
;
6058 size_t a_modem_left
= sizeof(a_modem
);
6059 struct sockaddr_in udptldest
= { 0, };
6062 debug
= sip_debug_test_pvt(p
);
6065 ast_log(LOG_WARNING
, "No way to add SDP without an UDPTL structure\n");
6069 if (!p
->sessionid
) {
6070 p
->sessionid
= getpid();
6071 p
->sessionversion
= p
->sessionid
;
6073 p
->sessionversion
++;
6075 /* Our T.38 end is */
6076 ast_udptl_get_us(p
->udptl
, &udptlsin
);
6078 /* Determine T.38 UDPTL destination */
6079 if (p
->udptlredirip
.sin_addr
.s_addr
) {
6080 udptldest
.sin_port
= p
->udptlredirip
.sin_port
;
6081 udptldest
.sin_addr
= p
->udptlredirip
.sin_addr
;
6083 udptldest
.sin_addr
= p
->ourip
;
6084 udptldest
.sin_port
= udptlsin
.sin_port
;
6088 ast_log(LOG_DEBUG
, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p
->ourip
), ntohs(udptlsin
.sin_port
));
6090 /* We break with the "recommendation" and send our IP, in order that our
6091 peer doesn't have to ast_gethostbyname() us */
6094 ast_log(LOG_DEBUG
, "Our T38 capability (%d), peer T38 capability (%d), joint capability (%d)\n",
6096 p
->t38
.peercapability
,
6097 p
->t38
.jointcapability
);
6099 snprintf(v
, sizeof(v
), "v=0\r\n");
6100 snprintf(o
, sizeof(o
), "o=root %d %d IN IP4 %s\r\n", p
->sessionid
, p
->sessionversion
, ast_inet_ntoa(udptldest
.sin_addr
));
6101 snprintf(s
, sizeof(s
), "s=session\r\n");
6102 snprintf(c
, sizeof(c
), "c=IN IP4 %s\r\n", ast_inet_ntoa(udptldest
.sin_addr
));
6103 snprintf(t
, sizeof(t
), "t=0 0\r\n");
6104 ast_build_string(&m_modem_next
, &m_modem_left
, "m=image %d udptl t38\r\n", ntohs(udptldest
.sin_port
));
6106 if ((p
->t38
.jointcapability
& T38FAX_VERSION
) == T38FAX_VERSION_0
)
6107 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38FaxVersion:0\r\n");
6108 if ((p
->t38
.jointcapability
& T38FAX_VERSION
) == T38FAX_VERSION_1
)
6109 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38FaxVersion:1\r\n");
6110 if ((x
= t38_get_rate(p
->t38
.jointcapability
)))
6111 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38MaxBitRate:%d\r\n",x
);
6112 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38FaxFillBitRemoval:%d\r\n", (p
->t38
.jointcapability
& T38FAX_FILL_BIT_REMOVAL
) ? 1 : 0);
6113 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38FaxTranscodingMMR:%d\r\n", (p
->t38
.jointcapability
& T38FAX_TRANSCODING_MMR
) ? 1 : 0);
6114 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38FaxTranscodingJBIG:%d\r\n", (p
->t38
.jointcapability
& T38FAX_TRANSCODING_JBIG
) ? 1 : 0);
6115 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38FaxRateManagement:%s\r\n", (p
->t38
.jointcapability
& T38FAX_RATE_MANAGEMENT_LOCAL_TCF
) ? "localTCF" : "transferredTCF");
6116 x
= ast_udptl_get_local_max_datagram(p
->udptl
);
6117 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38FaxMaxBuffer:%d\r\n",x
);
6118 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38FaxMaxDatagram:%d\r\n",x
);
6119 if (p
->t38
.jointcapability
!= T38FAX_UDP_EC_NONE
)
6120 ast_build_string(&a_modem_next
, &a_modem_left
, "a=T38FaxUdpEC:%s\r\n", (p
->t38
.jointcapability
& T38FAX_UDP_EC_REDUNDANCY
) ? "t38UDPRedundancy" : "t38UDPFEC");
6121 len
= strlen(v
) + strlen(s
) + strlen(o
) + strlen(c
) + strlen(t
) + strlen(m_modem
) + strlen(a_modem
);
6122 add_header(resp
, "Content-Type", "application/sdp");
6123 add_header_contentLength(resp
, len
);
6129 add_line(resp
, m_modem
);
6130 add_line(resp
, a_modem
);
6132 /* Update lastrtprx when we send our SDP */
6133 p
->lastrtprx
= p
->lastrtptx
= time(NULL
);
6139 /*! \brief Add RFC 2833 DTMF offer to SDP */
6140 static void add_noncodec_to_sdp(const struct sip_pvt
*p
, int format
, int sample_rate
,
6141 char **m_buf
, size_t *m_size
, char **a_buf
, size_t *a_size
,
6147 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format
, ast_rtp_lookup_mime_subtype(0, format
, 0));
6148 if ((rtp_code
= ast_rtp_lookup_code(p
->rtp
, 0, format
)) == -1)
6151 ast_build_string(m_buf
, m_size
, " %d", rtp_code
);
6152 ast_build_string(a_buf
, a_size
, "a=rtpmap:%d %s/%d\r\n", rtp_code
,
6153 ast_rtp_lookup_mime_subtype(0, format
, 0),
6155 if (format
== AST_RTP_DTMF
)
6156 /* Indicate we support DTMF and FLASH... */
6157 ast_build_string(a_buf
, a_size
, "a=fmtp:%d 0-16\r\n", rtp_code
);
6160 #define SDP_SAMPLE_RATE(x) (x == AST_FORMAT_G722) ? 16000 : 8000
6162 /*! \brief Add Session Description Protocol message */
6163 static enum sip_result
add_sdp(struct sip_request
*resp
, struct sip_pvt
*p
)
6166 int alreadysent
= 0;
6168 struct sockaddr_in sin
;
6169 struct sockaddr_in vsin
;
6170 struct sockaddr_in dest
;
6171 struct sockaddr_in vdest
= { 0, };
6174 char *version
= "v=0\r\n"; /* Protocol version */
6175 char *subject
= "s=session\r\n"; /* Subject of the session */
6176 char owner
[256]; /* Session owner/creator */
6177 char connection
[256]; /* Connection data */
6178 char *stime
= "t=0 0\r\n"; /* Time the session is active */
6179 char bandwidth
[256] = ""; /* Max bitrate */
6181 char m_audio
[256]; /* Media declaration line for audio */
6182 char m_video
[256]; /* Media declaration line for video */
6183 char a_audio
[1024]; /* Attributes for audio */
6184 char a_video
[1024]; /* Attributes for video */
6185 char *m_audio_next
= m_audio
;
6186 char *m_video_next
= m_video
;
6187 size_t m_audio_left
= sizeof(m_audio
);
6188 size_t m_video_left
= sizeof(m_video
);
6189 char *a_audio_next
= a_audio
;
6190 char *a_video_next
= a_video
;
6191 size_t a_audio_left
= sizeof(a_audio
);
6192 size_t a_video_left
= sizeof(a_video
);
6196 int needvideo
= FALSE
;
6197 int debug
= sip_debug_test_pvt(p
);
6198 int min_audio_packet_size
= 0;
6199 int min_video_packet_size
= 0;
6201 m_video
[0] = '\0'; /* Reset the video media string if it's not needed */
6204 ast_log(LOG_WARNING
, "No way to add SDP without an RTP structure\n");
6208 /* Set RTP Session ID and version */
6209 if (!p
->sessionid
) {
6210 p
->sessionid
= getpid();
6211 p
->sessionversion
= p
->sessionid
;
6213 p
->sessionversion
++;
6215 /* Get our addresses */
6216 ast_rtp_get_us(p
->rtp
, &sin
);
6218 ast_rtp_get_us(p
->vrtp
, &vsin
);
6220 /* Is this a re-invite to move the media out, then use the original offer from caller */
6221 if (p
->redirip
.sin_addr
.s_addr
) {
6222 dest
.sin_port
= p
->redirip
.sin_port
;
6223 dest
.sin_addr
= p
->redirip
.sin_addr
;
6225 dest
.sin_addr
= p
->ourip
;
6226 dest
.sin_port
= sin
.sin_port
;
6229 capability
= p
->jointcapability
;
6232 if (option_debug
> 1) {
6233 char codecbuf
[BUFSIZ
];
6234 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");
6235 ast_log(LOG_DEBUG
, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf
, sizeof(codecbuf
), p
->prefcodec
));
6238 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
6239 if (ast_test_flag(&p
->t38
.t38support
, SIP_PAGE2_T38SUPPORT_RTP
)) {
6240 ast_build_string(&m_audio_next
, &m_audio_left
, " %d", 191);
6241 ast_build_string(&a_audio_next
, &a_audio_left
, "a=rtpmap:%d %s/%d\r\n", 191, "t38", 8000);
6245 /* Check if we need video in this call */
6246 if ((capability
& AST_FORMAT_VIDEO_MASK
) && !ast_test_flag(&p
->flags
[0], SIP_NOVIDEO
)) {
6249 if (option_debug
> 1)
6250 ast_log(LOG_DEBUG
, "This call needs video offers!\n");
6251 } else if (option_debug
> 1)
6252 ast_log(LOG_DEBUG
, "This call needs video offers, but there's no video support enabled!\n");
6256 /* Ok, we need video. Let's add what we need for video and set codecs.
6257 Video is handled differently than audio since we can not transcode. */
6259 /* Determine video destination */
6260 if (p
->vredirip
.sin_addr
.s_addr
) {
6261 vdest
.sin_addr
= p
->vredirip
.sin_addr
;
6262 vdest
.sin_port
= p
->vredirip
.sin_port
;
6264 vdest
.sin_addr
= p
->ourip
;
6265 vdest
.sin_port
= vsin
.sin_port
;
6267 ast_build_string(&m_video_next
, &m_video_left
, "m=video %d RTP/AVP", ntohs(vdest
.sin_port
));
6269 /* Build max bitrate string */
6270 if (p
->maxcallbitrate
)
6271 snprintf(bandwidth
, sizeof(bandwidth
), "b=CT:%d\r\n", p
->maxcallbitrate
);
6273 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p
->ourip
), ntohs(vsin
.sin_port
));
6277 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p
->ourip
), ntohs(sin
.sin_port
));
6279 /* Start building generic SDP headers */
6281 /* We break with the "recommendation" and send our IP, in order that our
6282 peer doesn't have to ast_gethostbyname() us */
6284 snprintf(owner
, sizeof(owner
), "o=root %d %d IN IP4 %s\r\n", p
->sessionid
, p
->sessionversion
, ast_inet_ntoa(dest
.sin_addr
));
6285 snprintf(connection
, sizeof(connection
), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest
.sin_addr
));
6286 ast_build_string(&m_audio_next
, &m_audio_left
, "m=audio %d RTP/AVP", ntohs(dest
.sin_port
));
6288 if (ast_test_flag(&p
->flags
[1], SIP_PAGE2_CALL_ONHOLD
) == SIP_PAGE2_CALL_ONHOLD_ONEDIR
)
6289 hold
= "a=recvonly\r\n";
6290 else if (ast_test_flag(&p
->flags
[1], SIP_PAGE2_CALL_ONHOLD
) == SIP_PAGE2_CALL_ONHOLD_INACTIVE
)
6291 hold
= "a=inactive\r\n";
6293 hold
= "a=sendrecv\r\n";
6295 /* Now, start adding audio codecs. These are added in this order:
6296 - First what was requested by the calling channel
6297 - Then preferences in order from sip.conf device config for this peer/user
6298 - Then other codecs in capabilities, including video
6301 /* Prefer the audio codec we were requested to use, first, no matter what
6302 Note that p->prefcodec can include video codecs, so mask them out
6304 if (capability
& p
->prefcodec
) {
6305 int codec
= p
->prefcodec
& AST_FORMAT_AUDIO_MASK
;
6307 add_codec_to_sdp(p
, codec
, SDP_SAMPLE_RATE(codec
),
6308 &m_audio_next
, &m_audio_left
,
6309 &a_audio_next
, &a_audio_left
,
6310 debug
, &min_audio_packet_size
);
6311 alreadysent
|= codec
;
6314 /* Start by sending our preferred audio codecs */
6315 for (x
= 0; x
< 32; x
++) {
6318 if (!(codec
= ast_codec_pref_index(&p
->prefs
, x
)))
6321 if (!(capability
& codec
))
6324 if (alreadysent
& codec
)
6327 add_codec_to_sdp(p
, codec
, SDP_SAMPLE_RATE(codec
),
6328 &m_audio_next
, &m_audio_left
,
6329 &a_audio_next
, &a_audio_left
,
6330 debug
, &min_audio_packet_size
);
6331 alreadysent
|= codec
;
6334 /* Now send any other common audio and video codecs, and non-codec formats: */
6335 for (x
= 1; x
<= (needvideo
? AST_FORMAT_MAX_VIDEO
: AST_FORMAT_MAX_AUDIO
); x
<<= 1) {
6336 if (!(capability
& x
)) /* Codec not requested */
6339 if (alreadysent
& x
) /* Already added to SDP */
6342 if (x
<= AST_FORMAT_MAX_AUDIO
)
6343 add_codec_to_sdp(p
, x
, SDP_SAMPLE_RATE(x
),
6344 &m_audio_next
, &m_audio_left
,
6345 &a_audio_next
, &a_audio_left
,
6346 debug
, &min_audio_packet_size
);
6348 add_codec_to_sdp(p
, x
, 90000,
6349 &m_video_next
, &m_video_left
,
6350 &a_video_next
, &a_video_left
,
6351 debug
, &min_video_packet_size
);
6354 /* Now add DTMF RFC2833 telephony-event as a codec */
6355 for (x
= 1; x
<= AST_RTP_MAX
; x
<<= 1) {
6356 if (!(p
->jointnoncodeccapability
& x
))
6359 add_noncodec_to_sdp(p
, x
, 8000,
6360 &m_audio_next
, &m_audio_left
,
6361 &a_audio_next
, &a_audio_left
,
6365 if (option_debug
> 2)
6366 ast_log(LOG_DEBUG
, "-- Done with adding codecs to SDP\n");
6368 if (!p
->owner
|| !ast_internal_timing_enabled(p
->owner
))
6369 ast_build_string(&a_audio_next
, &a_audio_left
, "a=silenceSupp:off - - - -\r\n");
6371 if (min_audio_packet_size
)
6372 ast_build_string(&a_audio_next
, &a_audio_left
, "a=ptime:%d\r\n", min_audio_packet_size
);
6374 if (min_video_packet_size
)
6375 ast_build_string(&a_video_next
, &a_video_left
, "a=ptime:%d\r\n", min_video_packet_size
);
6377 if ((m_audio_left
< 2) || (m_video_left
< 2) || (a_audio_left
== 0) || (a_video_left
== 0))
6378 ast_log(LOG_WARNING
, "SIP SDP may be truncated due to undersized buffer!!\n");
6380 ast_build_string(&m_audio_next
, &m_audio_left
, "\r\n");
6382 ast_build_string(&m_video_next
, &m_video_left
, "\r\n");
6384 len
= strlen(version
) + strlen(subject
) + strlen(owner
) + strlen(connection
) + strlen(stime
) + strlen(m_audio
) + strlen(a_audio
) + strlen(hold
);
6385 if (needvideo
) /* only if video response is appropriate */
6386 len
+= strlen(m_video
) + strlen(a_video
) + strlen(bandwidth
) + strlen(hold
);
6388 add_header(resp
, "Content-Type", "application/sdp");
6389 add_header_contentLength(resp
, len
);
6390 add_line(resp
, version
);
6391 add_line(resp
, owner
);
6392 add_line(resp
, subject
);
6393 add_line(resp
, connection
);
6394 if (needvideo
) /* only if video response is appropriate */
6395 add_line(resp
, bandwidth
);
6396 add_line(resp
, stime
);
6397 add_line(resp
, m_audio
);
6398 add_line(resp
, a_audio
);
6399 add_line(resp
, hold
);
6400 if (needvideo
) { /* only if video response is appropriate */
6401 add_line(resp
, m_video
);
6402 add_line(resp
, a_video
);
6403 add_line(resp
, hold
); /* Repeat hold for the video stream */
6406 /* Update lastrtprx when we send our SDP */
6407 p
->lastrtprx
= p
->lastrtptx
= time(NULL
); /* XXX why both ? */
6409 if (option_debug
> 2) {
6411 ast_log(LOG_DEBUG
, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf
, BUFSIZ
, capability
));
6417 /*! \brief Used for 200 OK and 183 early media */
6418 static int transmit_response_with_t38_sdp(struct sip_pvt
*p
, char *msg
, struct sip_request
*req
, int retrans
)
6420 struct sip_request resp
;
6423 if (sscanf(get_header(req
, "CSeq"), "%d ", &seqno
) != 1) {
6424 ast_log(LOG_WARNING
, "Unable to get seqno from '%s'\n", get_header(req
, "CSeq"));
6427 respprep(&resp
, p
, msg
, req
);
6429 ast_udptl_offered_from_local(p
->udptl
, 0);
6430 add_t38_sdp(&resp
, p
);
6432 ast_log(LOG_ERROR
, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p
->callid
);
6433 if (retrans
&& !p
->pendinginvite
)
6434 p
->pendinginvite
= seqno
; /* Buggy clients sends ACK on RINGING too */
6435 return send_response(p
, &resp
, retrans
, seqno
);
6438 /*! \brief copy SIP request (mostly used to save request for responses) */
6439 static void copy_request(struct sip_request
*dst
, const struct sip_request
*src
)
6443 offset
= ((void *)dst
) - ((void *)src
);
6444 /* First copy stuff */
6445 memcpy(dst
, src
, sizeof(*dst
));
6446 /* Now fix pointer arithmetic */
6447 for (x
=0; x
< src
->headers
; x
++)
6448 dst
->header
[x
] += offset
;
6449 for (x
=0; x
< src
->lines
; x
++)
6450 dst
->line
[x
] += offset
;
6451 dst
->rlPart1
+= offset
;
6452 dst
->rlPart2
+= offset
;
6455 /*! \brief Used for 200 OK and 183 early media
6456 \return Will return XMIT_ERROR for network errors.
6458 static int transmit_response_with_sdp(struct sip_pvt
*p
, const char *msg
, const struct sip_request
*req
, enum xmittype reliable
)
6460 struct sip_request resp
;
6462 if (sscanf(get_header(req
, "CSeq"), "%d ", &seqno
) != 1) {
6463 ast_log(LOG_WARNING
, "Unable to get seqno from '%s'\n", get_header(req
, "CSeq"));
6466 respprep(&resp
, p
, msg
, req
);
6468 if (!p
->autoframing
&& !ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) {
6470 ast_log(LOG_DEBUG
, "Setting framing from config on incoming call\n");
6471 ast_rtp_codec_setpref(p
->rtp
, &p
->prefs
);
6473 try_suggested_sip_codec(p
);
6476 ast_log(LOG_ERROR
, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p
->callid
);
6477 if (reliable
&& !p
->pendinginvite
)
6478 p
->pendinginvite
= seqno
; /* Buggy clients sends ACK on RINGING too */
6479 return send_response(p
, &resp
, reliable
, seqno
);
6482 /*! \brief Parse first line of incoming SIP request */
6483 static int determine_firstline_parts(struct sip_request
*req
)
6485 char *e
= ast_skip_blanks(req
->header
[0]); /* there shouldn't be any */
6489 req
->rlPart1
= e
; /* method or protocol */
6490 e
= ast_skip_nonblanks(e
);
6493 /* Get URI or status code */
6494 e
= ast_skip_blanks(e
);
6499 if (!strcasecmp(req
->rlPart1
, "SIP/2.0") ) { /* We have a response */
6500 if (strlen(e
) < 3) /* status code is 3 digits */
6503 } else { /* We have a request */
6504 if ( *e
== '<' ) { /* XXX the spec says it must not be in <> ! */
6505 ast_log(LOG_WARNING
, "bogus uri in <> %s\n", e
);
6510 req
->rlPart2
= e
; /* URI */
6511 e
= ast_skip_nonblanks(e
);
6514 e
= ast_skip_blanks(e
);
6515 if (strcasecmp(e
, "SIP/2.0") ) {
6516 ast_log(LOG_WARNING
, "Bad request protocol %s\n", e
);
6523 /*! \brief Transmit reinvite with SDP
6524 \note A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
6525 INVITE that opened the SIP dialogue
6526 We reinvite so that the audio stream (RTP) go directly between
6527 the SIP UAs. SIP Signalling stays with * in the path.
6529 static int transmit_reinvite_with_sdp(struct sip_pvt
*p
)
6531 struct sip_request req
;
6533 reqprep(&req
, p
, ast_test_flag(&p
->flags
[0], SIP_REINVITE_UPDATE
) ? SIP_UPDATE
: SIP_INVITE
, 0, 1);
6535 add_header(&req
, "Allow", ALLOWED_METHODS
);
6536 add_header(&req
, "Supported", SUPPORTED_EXTENSIONS
);
6538 add_header(&req
, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
6539 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
))
6540 append_history(p
, "ReInv", "Re-invite sent");
6542 /* Use this as the basis */
6543 initialize_initreq(p
, &req
);
6544 p
->lastinvite
= p
->ocseq
;
6545 ast_set_flag(&p
->flags
[0], SIP_OUTGOING
); /* Change direction of this dialog */
6546 return send_request(p
, &req
, XMIT_CRITICAL
, p
->ocseq
);
6549 /*! \brief Transmit reinvite with T38 SDP
6550 We reinvite so that the T38 processing can take place.
6551 SIP Signalling stays with * in the path.
6553 static int transmit_reinvite_with_t38_sdp(struct sip_pvt
*p
)
6555 struct sip_request req
;
6557 reqprep(&req
, p
, ast_test_flag(&p
->flags
[0], SIP_REINVITE_UPDATE
) ? SIP_UPDATE
: SIP_INVITE
, 0, 1);
6559 add_header(&req
, "Allow", ALLOWED_METHODS
);
6560 add_header(&req
, "Supported", SUPPORTED_EXTENSIONS
);
6562 add_header(&req
, "X-asterisk-info", "SIP re-invite (T38 switchover)");
6563 ast_udptl_offered_from_local(p
->udptl
, 1);
6564 add_t38_sdp(&req
, p
);
6565 /* Use this as the basis */
6566 initialize_initreq(p
, &req
);
6567 ast_set_flag(&p
->flags
[0], SIP_OUTGOING
); /* Change direction of this dialog */
6568 p
->lastinvite
= p
->ocseq
;
6569 return send_request(p
, &req
, XMIT_CRITICAL
, p
->ocseq
);
6572 /*! \brief Check Contact: URI of SIP message */
6573 static void extract_uri(struct sip_pvt
*p
, struct sip_request
*req
)
6575 char stripped
[BUFSIZ
];
6578 ast_copy_string(stripped
, get_header(req
, "Contact"), sizeof(stripped
));
6579 c
= get_in_brackets(stripped
);
6580 c
= strsep(&c
, ";"); /* trim ; and beyond */
6581 if (!ast_strlen_zero(c
))
6582 ast_string_field_set(p
, uri
, c
);
6585 /*! \brief Build contact header - the contact header we send out */
6586 static void build_contact(struct sip_pvt
*p
)
6588 /* Construct Contact: header */
6589 if (ourport
!= STANDARD_SIP_PORT
)
6590 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
);
6592 ast_string_field_build(p
, our_contact
, "<sip:%s%s%s>", p
->exten
, ast_strlen_zero(p
->exten
) ? "" : "@", ast_inet_ntoa(p
->ourip
));
6595 /*! \brief Build the Remote Party-ID & From using callingpres options */
6596 static void build_rpid(struct sip_pvt
*p
)
6598 int send_pres_tags
= TRUE
;
6599 const char *privacy
=NULL
;
6600 const char *screen
=NULL
;
6602 const char *clid
= default_callerid
;
6603 const char *clin
= NULL
;
6604 const char *fromdomain
;
6606 if (!ast_strlen_zero(p
->rpid
) || !ast_strlen_zero(p
->rpid_from
))
6609 if (p
->owner
&& p
->owner
->cid
.cid_num
)
6610 clid
= p
->owner
->cid
.cid_num
;
6611 if (p
->owner
&& p
->owner
->cid
.cid_name
)
6612 clin
= p
->owner
->cid
.cid_name
;
6613 if (ast_strlen_zero(clin
))
6616 switch (p
->callingpres
) {
6617 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED
:
6621 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN
:
6625 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN
:
6629 case AST_PRES_ALLOWED_NETWORK_NUMBER
:
6633 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED
:
6637 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN
:
6641 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN
:
6645 case AST_PRES_PROHIB_NETWORK_NUMBER
:
6649 case AST_PRES_NUMBER_NOT_AVAILABLE
:
6650 send_pres_tags
= FALSE
;
6653 ast_log(LOG_WARNING
, "Unsupported callingpres (%d)\n", p
->callingpres
);
6654 if ((p
->callingpres
& AST_PRES_RESTRICTION
) != AST_PRES_ALLOWED
)
6662 fromdomain
= S_OR(p
->fromdomain
, ast_inet_ntoa(p
->ourip
));
6664 snprintf(buf
, sizeof(buf
), "\"%s\" <sip:%s@%s>", clin
, clid
, fromdomain
);
6666 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
), ";privacy=%s;screen=%s", privacy
, screen
);
6667 ast_string_field_set(p
, rpid
, buf
);
6669 ast_string_field_build(p
, rpid_from
, "\"%s\" <sip:%s@%s>;tag=%s", clin
,
6670 S_OR(p
->fromuser
, clid
),
6671 fromdomain
, p
->tag
);
6674 /*! \brief Initiate new SIP request to peer/user */
6675 static void initreqprep(struct sip_request
*req
, struct sip_pvt
*p
, int sipmethod
)
6677 char invite_buf
[256] = "";
6678 char *invite
= invite_buf
;
6679 size_t invite_max
= sizeof(invite_buf
);
6683 char tmp2
[BUFSIZ
/2];
6684 const char *l
= NULL
, *n
= NULL
;
6685 const char *urioptions
= "";
6687 if (ast_test_flag(&p
->flags
[0], SIP_USEREQPHONE
)) {
6688 const char *s
= p
->username
; /* being a string field, cannot be NULL */
6690 /* Test p->username against allowed characters in AST_DIGIT_ANY
6691 If it matches the allowed characters list, then sipuser = ";user=phone"
6692 If not, then sipuser = ""
6694 /* + is allowed in first position in a tel: uri */
6698 if (!strchr(AST_DIGIT_ANYNUM
, *s
) )
6701 /* If we have only digits, add ;user=phone to the uri */
6703 urioptions
= ";user=phone";
6707 snprintf(p
->lastmsg
, sizeof(p
->lastmsg
), "Init: %s", sip_methods
[sipmethod
].text
);
6710 l
= p
->owner
->cid
.cid_num
;
6711 n
= p
->owner
->cid
.cid_name
;
6713 /* if we are not sending RPID and user wants his callerid restricted */
6714 if (!ast_test_flag(&p
->flags
[0], SIP_SENDRPID
) &&
6715 ((p
->callingpres
& AST_PRES_RESTRICTION
) != AST_PRES_ALLOWED
)) {
6716 l
= CALLERID_UNKNOWN
;
6719 if (ast_strlen_zero(l
))
6720 l
= default_callerid
;
6721 if (ast_strlen_zero(n
))
6723 /* Allow user to be overridden */
6724 if (!ast_strlen_zero(p
->fromuser
))
6726 else /* Save for any further attempts */
6727 ast_string_field_set(p
, fromuser
, l
);
6729 /* Allow user to be overridden */
6730 if (!ast_strlen_zero(p
->fromname
))
6732 else /* Save for any further attempts */
6733 ast_string_field_set(p
, fromname
, n
);
6735 if (pedanticsipchecking
) {
6736 ast_uri_encode(n
, tmp
, sizeof(tmp
), 0);
6738 ast_uri_encode(l
, tmp2
, sizeof(tmp2
), 0);
6742 if (ourport
!= STANDARD_SIP_PORT
&& ast_strlen_zero(p
->fromdomain
))
6743 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
);
6745 snprintf(from
, sizeof(from
), "\"%s\" <sip:%s@%s>;tag=%s", n
, l
, S_OR(p
->fromdomain
, ast_inet_ntoa(p
->ourip
)), p
->tag
);
6747 /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
6748 if (!ast_strlen_zero(p
->fullcontact
)) {
6749 /* If we have full contact, trust it */
6750 ast_build_string(&invite
, &invite_max
, "%s", p
->fullcontact
);
6752 /* Otherwise, use the username while waiting for registration */
6753 ast_build_string(&invite
, &invite_max
, "sip:");
6754 if (!ast_strlen_zero(p
->username
)) {
6756 if (pedanticsipchecking
) {
6757 ast_uri_encode(n
, tmp
, sizeof(tmp
), 0);
6760 ast_build_string(&invite
, &invite_max
, "%s@", n
);
6762 ast_build_string(&invite
, &invite_max
, "%s", p
->tohost
);
6763 if (ntohs(p
->sa
.sin_port
) != STANDARD_SIP_PORT
)
6764 ast_build_string(&invite
, &invite_max
, ":%d", ntohs(p
->sa
.sin_port
));
6765 ast_build_string(&invite
, &invite_max
, "%s", urioptions
);
6768 /* If custom URI options have been provided, append them */
6769 if (p
->options
&& p
->options
->uri_options
)
6770 ast_build_string(&invite
, &invite_max
, ";%s", p
->options
->uri_options
);
6772 ast_string_field_set(p
, uri
, invite_buf
);
6774 if (sipmethod
== SIP_NOTIFY
&& !ast_strlen_zero(p
->theirtag
)) {
6775 /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
6776 snprintf(to
, sizeof(to
), "<sip:%s>;tag=%s", p
->uri
, p
->theirtag
);
6777 } else if (p
->options
&& p
->options
->vxml_url
) {
6778 /* If there is a VXML URL append it to the SIP URL */
6779 snprintf(to
, sizeof(to
), "<%s>;%s", p
->uri
, p
->options
->vxml_url
);
6781 snprintf(to
, sizeof(to
), "<%s>", p
->uri
);
6783 init_req(req
, sipmethod
, p
->uri
);
6784 snprintf(tmp
, sizeof(tmp
), "%d %s", ++p
->ocseq
, sip_methods
[sipmethod
].text
);
6786 add_header(req
, "Via", p
->via
);
6787 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
6788 * OTOH, then we won't have anything in p->route anyway */
6789 /* Build Remote Party-ID and From */
6790 if (ast_test_flag(&p
->flags
[0], SIP_SENDRPID
) && (sipmethod
== SIP_INVITE
)) {
6792 add_header(req
, "From", p
->rpid_from
);
6794 add_header(req
, "From", from
);
6795 add_header(req
, "To", to
);
6796 ast_string_field_set(p
, exten
, l
);
6798 add_header(req
, "Contact", p
->our_contact
);
6799 add_header(req
, "Call-ID", p
->callid
);
6800 add_header(req
, "CSeq", tmp
);
6801 if (!ast_strlen_zero(global_useragent
))
6802 add_header(req
, "User-Agent", global_useragent
);
6803 add_header(req
, "Max-Forwards", DEFAULT_MAX_FORWARDS
);
6804 if (!ast_strlen_zero(p
->rpid
))
6805 add_header(req
, "Remote-Party-ID", p
->rpid
);
6808 /*! \brief Build REFER/INVITE/OPTIONS message and transmit it */
6809 static int transmit_invite(struct sip_pvt
*p
, int sipmethod
, int sdp
, int init
)
6811 struct sip_request req
;
6813 req
.method
= sipmethod
;
6814 if (init
) { /* Seems like init always is 2 */
6815 /* Bump branch even on initial requests */
6816 p
->branch
^= ast_random();
6819 initreqprep(&req
, p
, sipmethod
);
6821 reqprep(&req
, p
, sipmethod
, 0, 1);
6823 reqprep(&req
, p
, sipmethod
, 0, 1);
6825 if (p
->options
&& p
->options
->auth
)
6826 add_header(&req
, p
->options
->authheader
, p
->options
->auth
);
6828 if (sipmethod
== SIP_REFER
) { /* Call transfer */
6831 if (!ast_strlen_zero(p
->refer
->refer_to
))
6832 add_header(&req
, "Refer-To", p
->refer
->refer_to
);
6833 if (!ast_strlen_zero(p
->refer
->referred_by
)) {
6834 sprintf(buf
, "%s <%s>", p
->refer
->referred_by_name
, p
->refer
->referred_by
);
6835 add_header(&req
, "Referred-By", buf
);
6839 /* This new INVITE is part of an attended transfer. Make sure that the
6840 other end knows and replace the current call with this new call */
6841 if (p
->options
&& p
->options
->replaces
&& !ast_strlen_zero(p
->options
->replaces
)) {
6842 add_header(&req
, "Replaces", p
->options
->replaces
);
6843 add_header(&req
, "Require", "replaces");
6846 add_header(&req
, "Allow", ALLOWED_METHODS
);
6847 add_header(&req
, "Supported", SUPPORTED_EXTENSIONS
);
6848 if (p
->options
&& p
->options
->addsipheaders
&& p
->owner
) {
6849 struct ast_channel
*ast
= p
->owner
; /* The owner channel */
6850 struct varshead
*headp
= &ast
->varshead
;
6853 ast_log(LOG_WARNING
,"No Headp for the channel...ooops!\n");
6855 const struct ast_var_t
*current
;
6856 AST_LIST_TRAVERSE(headp
, current
, entries
) {
6857 /* SIPADDHEADER: Add SIP header to outgoing call */
6858 if (!strncasecmp(ast_var_name(current
), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
6859 char *content
, *end
;
6860 const char *header
= ast_var_value(current
);
6861 char *headdup
= ast_strdupa(header
);
6863 /* Strip of the starting " (if it's there) */
6864 if (*headdup
== '"')
6866 if ((content
= strchr(headdup
, ':'))) {
6868 content
= ast_skip_blanks(content
); /* Skip white space */
6869 /* Strip the ending " (if it's there) */
6870 end
= content
+ strlen(content
) -1;
6874 add_header(&req
, headdup
, content
);
6876 ast_log(LOG_DEBUG
, "Adding SIP Header \"%s\" with content :%s: \n", headdup
, content
);
6883 if (p
->udptl
&& p
->t38
.state
== T38_LOCAL_DIRECT
) {
6884 ast_udptl_offered_from_local(p
->udptl
, 1);
6886 ast_log(LOG_DEBUG
, "T38 is in state %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>");
6887 add_t38_sdp(&req
, p
);
6891 add_header_contentLength(&req
, 0);
6894 if (!p
->initreq
.headers
)
6895 initialize_initreq(p
, &req
);
6896 p
->lastinvite
= p
->ocseq
;
6897 return send_request(p
, &req
, init
? XMIT_CRITICAL
: XMIT_RELIABLE
, p
->ocseq
);
6900 /*! \brief Used in the SUBSCRIBE notification subsystem */
6901 static int transmit_state_notify(struct sip_pvt
*p
, int state
, int full
, int timeout
)
6903 char tmp
[4000], from
[256], to
[256];
6904 char *t
= tmp
, *c
, *mfrom
, *mto
;
6905 size_t maxbytes
= sizeof(tmp
);
6906 struct sip_request req
;
6907 char hint
[AST_MAX_EXTENSION
];
6908 char *statestring
= "terminated";
6909 const struct cfsubscription_types
*subscriptiontype
;
6910 enum state
{ NOTIFY_OPEN
, NOTIFY_INUSE
, NOTIFY_CLOSED
} local_state
= NOTIFY_OPEN
;
6911 char *pidfstate
= "--";
6912 char *pidfnote
= "Ready";
6914 memset(from
, 0, sizeof(from
));
6915 memset(to
, 0, sizeof(to
));
6916 memset(tmp
, 0, sizeof(tmp
));
6919 case (AST_EXTENSION_RINGING
| AST_EXTENSION_INUSE
):
6920 statestring
= (global_notifyringing
) ? "early" : "confirmed";
6921 local_state
= NOTIFY_INUSE
;
6923 pidfnote
= "Ringing";
6925 case AST_EXTENSION_RINGING
:
6926 statestring
= "early";
6927 local_state
= NOTIFY_INUSE
;
6929 pidfnote
= "Ringing";
6931 case AST_EXTENSION_INUSE
:
6932 statestring
= "confirmed";
6933 local_state
= NOTIFY_INUSE
;
6935 pidfnote
= "On the phone";
6937 case AST_EXTENSION_BUSY
:
6938 statestring
= "confirmed";
6939 local_state
= NOTIFY_CLOSED
;
6941 pidfnote
= "On the phone";
6943 case AST_EXTENSION_UNAVAILABLE
:
6944 statestring
= "terminated";
6945 local_state
= NOTIFY_CLOSED
;
6947 pidfnote
= "Unavailable";
6949 case AST_EXTENSION_ONHOLD
:
6950 statestring
= "confirmed";
6951 local_state
= NOTIFY_INUSE
;
6953 pidfnote
= "On Hold";
6955 case AST_EXTENSION_NOT_INUSE
:
6957 /* Default setting */
6961 subscriptiontype
= find_subscription_type(p
->subscribed
);
6963 /* Check which device/devices we are watching and if they are registered */
6964 if (ast_get_hint(hint
, sizeof(hint
), NULL
, 0, NULL
, p
->context
, p
->exten
)) {
6965 char *hint2
= hint
, *individual_hint
= NULL
;
6966 while ((individual_hint
= strsep(&hint2
, "&"))) {
6967 /* If they are not registered, we will override notification and show no availability */
6968 if (ast_device_state(individual_hint
) == AST_DEVICE_UNAVAILABLE
) {
6969 local_state
= NOTIFY_CLOSED
;
6971 pidfnote
= "Not online";
6976 ast_copy_string(from
, get_header(&p
->initreq
, "From"), sizeof(from
));
6977 c
= get_in_brackets(from
);
6978 if (strncasecmp(c
, "sip:", 4)) {
6979 ast_log(LOG_WARNING
, "Huh? Not a SIP header (%s)?\n", c
);
6982 mfrom
= strsep(&c
, ";"); /* trim ; and beyond */
6984 ast_copy_string(to
, get_header(&p
->initreq
, "To"), sizeof(to
));
6985 c
= get_in_brackets(to
);
6986 if (strncasecmp(c
, "sip:", 4)) {
6987 ast_log(LOG_WARNING
, "Huh? Not a SIP header (%s)?\n", c
);
6990 mto
= strsep(&c
, ";"); /* trim ; and beyond */
6992 reqprep(&req
, p
, SIP_NOTIFY
, 0, 1);
6995 add_header(&req
, "Event", subscriptiontype
->event
);
6996 add_header(&req
, "Content-Type", subscriptiontype
->mediatype
);
6998 case AST_EXTENSION_DEACTIVATED
:
7000 add_header(&req
, "Subscription-State", "terminated;reason=timeout");
7002 add_header(&req
, "Subscription-State", "terminated;reason=probation");
7003 add_header(&req
, "Retry-After", "60");
7006 case AST_EXTENSION_REMOVED
:
7007 add_header(&req
, "Subscription-State", "terminated;reason=noresource");
7011 add_header(&req
, "Subscription-State", "active");
7013 add_header(&req
, "Subscription-State", "terminated;reason=timeout");
7015 switch (p
->subscribed
) {
7018 ast_build_string(&t
, &maxbytes
, "<?xml version=\"1.0\"?>\n");
7019 ast_build_string(&t
, &maxbytes
, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
7020 ast_build_string(&t
, &maxbytes
, "<presence>\n");
7021 ast_build_string(&t
, &maxbytes
, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom
);
7022 ast_build_string(&t
, &maxbytes
, "<atom id=\"%s\">\n", p
->exten
);
7023 ast_build_string(&t
, &maxbytes
, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto
);
7024 ast_build_string(&t
, &maxbytes
, "<status status=\"%s\" />\n", (local_state
== NOTIFY_OPEN
) ? "open" : (local_state
== NOTIFY_INUSE
) ? "inuse" : "closed");
7025 ast_build_string(&t
, &maxbytes
, "<msnsubstatus substatus=\"%s\" />\n", (local_state
== NOTIFY_OPEN
) ? "online" : (local_state
== NOTIFY_INUSE
) ? "onthephone" : "offline");
7026 ast_build_string(&t
, &maxbytes
, "</address>\n</atom>\n</presence>\n");
7028 case PIDF_XML
: /* Eyebeam supports this format */
7029 ast_build_string(&t
, &maxbytes
, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
7030 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
);
7031 ast_build_string(&t
, &maxbytes
, "<pp:person><status>\n");
7032 if (pidfstate
[0] != '-')
7033 ast_build_string(&t
, &maxbytes
, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate
);
7034 ast_build_string(&t
, &maxbytes
, "</status></pp:person>\n");
7035 ast_build_string(&t
, &maxbytes
, "<note>%s</note>\n", pidfnote
); /* Note */
7036 ast_build_string(&t
, &maxbytes
, "<tuple id=\"%s\">\n", p
->exten
); /* Tuple start */
7037 ast_build_string(&t
, &maxbytes
, "<contact priority=\"1\">%s</contact>\n", mto
);
7038 if (pidfstate
[0] == 'b') /* Busy? Still open ... */
7039 ast_build_string(&t
, &maxbytes
, "<status><basic>open</basic></status>\n");
7041 ast_build_string(&t
, &maxbytes
, "<status><basic>%s</basic></status>\n", (local_state
!= NOTIFY_CLOSED
) ? "open" : "closed");
7042 ast_build_string(&t
, &maxbytes
, "</tuple>\n</presence>\n");
7044 case DIALOG_INFO_XML
: /* SNOM subscribes in this format */
7045 ast_build_string(&t
, &maxbytes
, "<?xml version=\"1.0\"?>\n");
7046 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
);
7047 if ((state
& AST_EXTENSION_RINGING
) && global_notifyringing
)
7048 ast_build_string(&t
, &maxbytes
, "<dialog id=\"%s\" direction=\"recipient\">\n", p
->exten
);
7050 ast_build_string(&t
, &maxbytes
, "<dialog id=\"%s\">\n", p
->exten
);
7051 ast_build_string(&t
, &maxbytes
, "<state>%s</state>\n", statestring
);
7052 if (state
== AST_EXTENSION_ONHOLD
) {
7053 ast_build_string(&t
, &maxbytes
, "<local>\n<target uri=\"%s\">\n"
7054 "<param pname=\"+sip.rendering\" pvalue=\"no\">\n"
7055 "</target>\n</local>\n", mto
);
7057 ast_build_string(&t
, &maxbytes
, "</dialog>\n</dialog-info>\n");
7064 if (t
> tmp
+ sizeof(tmp
))
7065 ast_log(LOG_WARNING
, "Buffer overflow detected!! (Please file a bug report)\n");
7067 add_header_contentLength(&req
, strlen(tmp
));
7068 add_line(&req
, tmp
);
7070 return send_request(p
, &req
, XMIT_RELIABLE
, p
->ocseq
);
7073 /*! \brief Notify user of messages waiting in voicemail
7074 \note - Notification only works for registered peers with mailbox= definitions
7076 - We use the SIP Event package message-summary
7077 MIME type defaults to "application/simple-message-summary";
7079 static int transmit_notify_with_mwi(struct sip_pvt
*p
, int newmsgs
, int oldmsgs
, char *vmexten
)
7081 struct sip_request req
;
7084 size_t maxbytes
= sizeof(tmp
);
7086 initreqprep(&req
, p
, SIP_NOTIFY
);
7087 add_header(&req
, "Event", "message-summary");
7088 add_header(&req
, "Content-Type", default_notifymime
);
7090 ast_build_string(&t
, &maxbytes
, "Messages-Waiting: %s\r\n", newmsgs
? "yes" : "no");
7091 ast_build_string(&t
, &maxbytes
, "Message-Account: sip:%s@%s\r\n",
7092 S_OR(vmexten
, default_vmexten
), S_OR(p
->fromdomain
, ast_inet_ntoa(p
->ourip
)));
7093 /* Cisco has a bug in the SIP stack where it can't accept the
7094 (0/0) notification. This can temporarily be disabled in
7095 sip.conf with the "buggymwi" option */
7096 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)"));
7098 if (p
->subscribed
) {
7100 add_header(&req
, "Subscription-State", "active");
7102 add_header(&req
, "Subscription-State", "terminated;reason=timeout");
7105 if (t
> tmp
+ sizeof(tmp
))
7106 ast_log(LOG_WARNING
, "Buffer overflow detected!! (Please file a bug report)\n");
7108 add_header_contentLength(&req
, strlen(tmp
));
7109 add_line(&req
, tmp
);
7111 if (!p
->initreq
.headers
)
7112 initialize_initreq(p
, &req
);
7113 return send_request(p
, &req
, XMIT_RELIABLE
, p
->ocseq
);
7116 /*! \brief Transmit SIP request unreliably (only used in sip_notify subsystem) */
7117 static int transmit_sip_request(struct sip_pvt
*p
, struct sip_request
*req
)
7119 if (!p
->initreq
.headers
) /* Initialize first request before sending */
7120 initialize_initreq(p
, req
);
7121 return send_request(p
, req
, XMIT_UNRELIABLE
, p
->ocseq
);
7124 /*! \brief Notify a transferring party of the status of transfer */
7125 static int transmit_notify_with_sipfrag(struct sip_pvt
*p
, int cseq
, char *message
, int terminate
)
7127 struct sip_request req
;
7130 reqprep(&req
, p
, SIP_NOTIFY
, 0, 1);
7131 snprintf(tmp
, sizeof(tmp
), "refer;id=%d", cseq
);
7132 add_header(&req
, "Event", tmp
);
7133 add_header(&req
, "Subscription-state", terminate
? "terminated;reason=noresource" : "active");
7134 add_header(&req
, "Content-Type", "message/sipfrag;version=2.0");
7135 add_header(&req
, "Allow", ALLOWED_METHODS
);
7136 add_header(&req
, "Supported", SUPPORTED_EXTENSIONS
);
7138 snprintf(tmp
, sizeof(tmp
), "SIP/2.0 %s\r\n", message
);
7139 add_header_contentLength(&req
, strlen(tmp
));
7140 add_line(&req
, tmp
);
7142 if (!p
->initreq
.headers
)
7143 initialize_initreq(p
, &req
);
7145 return send_request(p
, &req
, XMIT_RELIABLE
, p
->ocseq
);
7148 /*! \brief Convert registration state status to string */
7149 static char *regstate2str(enum sipregistrystate regstate
)
7152 case REG_STATE_FAILED
:
7154 case REG_STATE_UNREGISTERED
:
7155 return "Unregistered";
7156 case REG_STATE_REGSENT
:
7157 return "Request Sent";
7158 case REG_STATE_AUTHSENT
:
7159 return "Auth. Sent";
7160 case REG_STATE_REGISTERED
:
7161 return "Registered";
7162 case REG_STATE_REJECTED
:
7164 case REG_STATE_TIMEOUT
:
7166 case REG_STATE_NOAUTH
:
7167 return "No Authentication";
7173 /*! \brief Update registration with SIP Proxy */
7174 static int sip_reregister(void *data
)
7176 /* if we are here, we know that we need to reregister. */
7177 struct sip_registry
*r
= ASTOBJ_REF((struct sip_registry
*) data
);
7179 /* if we couldn't get a reference to the registry object, punt */
7183 if (r
->call
&& !ast_test_flag(&r
->call
->flags
[0], SIP_NO_HISTORY
))
7184 append_history(r
->call
, "RegistryRenew", "Account: %s@%s", r
->username
, r
->hostname
);
7185 /* Since registry's are only added/removed by the the monitor thread, this
7186 may be overkill to reference/dereference at all here */
7188 ast_log(LOG_NOTICE
, " -- Re-registration for %s@%s\n", r
->username
, r
->hostname
);
7191 __sip_do_register(r
);
7192 ASTOBJ_UNREF(r
, sip_registry_destroy
);
7196 /*! \brief Register with SIP proxy */
7197 static int __sip_do_register(struct sip_registry
*r
)
7201 res
= transmit_register(r
, SIP_REGISTER
, NULL
, NULL
);
7205 /*! \brief Registration timeout, register again */
7206 static int sip_reg_timeout(void *data
)
7209 /* if we are here, our registration timed out, so we'll just do it over */
7210 struct sip_registry
*r
= ASTOBJ_REF((struct sip_registry
*) data
);
7214 /* if we couldn't get a reference to the registry object, punt */
7218 ast_log(LOG_NOTICE
, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r
->username
, r
->hostname
, r
->regattempts
);
7220 /* Unlink us, destroy old call. Locking is not relevant here because all this happens
7221 in the single SIP manager thread. */
7224 ASTOBJ_UNREF(p
->registry
, sip_registry_destroy
);
7226 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
7227 /* Pretend to ACK anything just in case */
7228 __sip_pretend_ack(p
); /* XXX we need p locked, not sure we have */
7230 /* If we have a limit, stop registration and give up */
7231 if (global_regattempts_max
&& (r
->regattempts
> global_regattempts_max
)) {
7232 /* Ok, enough is enough. Don't try any more */
7233 /* We could add an external notification here...
7234 steal it from app_voicemail :-) */
7235 ast_log(LOG_NOTICE
, " -- Giving up forever trying to register '%s@%s'\n", r
->username
, r
->hostname
);
7236 r
->regstate
= REG_STATE_FAILED
;
7238 r
->regstate
= REG_STATE_UNREGISTERED
;
7240 res
=transmit_register(r
, SIP_REGISTER
, NULL
, NULL
);
7242 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
));
7243 ASTOBJ_UNREF(r
, sip_registry_destroy
);
7247 /*! \brief Transmit register to SIP proxy or UA */
7248 static int transmit_register(struct sip_registry
*r
, int sipmethod
, const char *auth
, const char *authheader
)
7250 struct sip_request req
;
7257 /* exit if we are already in process with this registrar ?*/
7258 if ( r
== NULL
|| ((auth
==NULL
) && (r
->regstate
==REG_STATE_REGSENT
|| r
->regstate
==REG_STATE_AUTHSENT
))) {
7259 ast_log(LOG_NOTICE
, "Strange, trying to register %s@%s when registration already pending\n", r
->username
, r
->hostname
);
7263 if (r
->call
) { /* We have a registration */
7265 ast_log(LOG_WARNING
, "Already have a REGISTER going on to %s@%s?? \n", r
->username
, r
->hostname
);
7269 make_our_tag(p
->tag
, sizeof(p
->tag
)); /* create a new local tag for every register attempt */
7270 ast_string_field_free(p
, theirtag
); /* forget their old tag, so we don't match tags when getting response */
7273 /* Build callid for registration if we haven't registered before */
7274 if (!r
->callid_valid
) {
7275 build_callid_registry(r
, __ourip
, default_fromdomain
);
7276 r
->callid_valid
= TRUE
;
7278 /* Allocate SIP packet for registration */
7279 if (!(p
= sip_alloc( r
->callid
, NULL
, 0, SIP_REGISTER
))) {
7280 ast_log(LOG_WARNING
, "Unable to allocate registration transaction (memory or socket error)\n");
7283 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
))
7284 append_history(p
, "RegistryInit", "Account: %s@%s", r
->username
, r
->hostname
);
7285 /* Find address to hostname */
7286 if (create_addr(p
, r
->hostname
)) {
7287 /* we have what we hope is a temporary network error,
7288 * probably DNS. We need to reschedule a registration try */
7290 if (r
->timeout
> -1) {
7291 ast_sched_del(sched
, r
->timeout
);
7292 r
->timeout
= ast_sched_add(sched
, global_reg_timeout
*1000, sip_reg_timeout
, r
);
7293 ast_log(LOG_WARNING
, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r
->username
, r
->hostname
, r
->timeout
);
7295 r
->timeout
= ast_sched_add(sched
, global_reg_timeout
*1000, sip_reg_timeout
, r
);
7296 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
);
7301 /* Copy back Call-ID in case create_addr changed it */
7302 ast_string_field_set(r
, callid
, p
->callid
);
7304 p
->sa
.sin_port
= htons(r
->portno
);
7305 else /* Set registry port to the port set from the peer definition/srv or default */
7306 r
->portno
= ntohs(p
->sa
.sin_port
);
7307 ast_set_flag(&p
->flags
[0], SIP_OUTGOING
); /* Registration is outgoing call */
7308 r
->call
=p
; /* Save pointer to SIP packet */
7309 p
->registry
= ASTOBJ_REF(r
); /* Add pointer to registry in packet */
7310 if (!ast_strlen_zero(r
->secret
)) /* Secret (password) */
7311 ast_string_field_set(p
, peersecret
, r
->secret
);
7312 if (!ast_strlen_zero(r
->md5secret
))
7313 ast_string_field_set(p
, peermd5secret
, r
->md5secret
);
7314 /* User name in this realm
7315 - if authuser is set, use that, otherwise use username */
7316 if (!ast_strlen_zero(r
->authuser
)) {
7317 ast_string_field_set(p
, peername
, r
->authuser
);
7318 ast_string_field_set(p
, authname
, r
->authuser
);
7319 } else if (!ast_strlen_zero(r
->username
)) {
7320 ast_string_field_set(p
, peername
, r
->username
);
7321 ast_string_field_set(p
, authname
, r
->username
);
7322 ast_string_field_set(p
, fromuser
, r
->username
);
7324 if (!ast_strlen_zero(r
->username
))
7325 ast_string_field_set(p
, username
, r
->username
);
7326 /* Save extension in packet */
7327 ast_string_field_set(p
, exten
, r
->contact
);
7330 check which address we should use in our contact header
7331 based on whether the remote host is on the external or
7332 internal network so we can register through nat
7334 if (ast_sip_ouraddrfor(&p
->sa
.sin_addr
, &p
->ourip
))
7335 p
->ourip
= bindaddr
.sin_addr
;
7339 /* set up a timeout */
7341 if (r
->timeout
> -1) {
7342 ast_log(LOG_WARNING
, "Still have a registration timeout, #%d - deleting it\n", r
->timeout
);
7343 ast_sched_del(sched
, r
->timeout
);
7345 r
->timeout
= ast_sched_add(sched
, global_reg_timeout
* 1000, sip_reg_timeout
, r
);
7347 ast_log(LOG_DEBUG
, "Scheduled a registration timeout for %s id #%d \n", r
->hostname
, r
->timeout
);
7350 if (strchr(r
->username
, '@')) {
7351 snprintf(from
, sizeof(from
), "<sip:%s>;tag=%s", r
->username
, p
->tag
);
7352 if (!ast_strlen_zero(p
->theirtag
))
7353 snprintf(to
, sizeof(to
), "<sip:%s>;tag=%s", r
->username
, p
->theirtag
);
7355 snprintf(to
, sizeof(to
), "<sip:%s>", r
->username
);
7357 snprintf(from
, sizeof(from
), "<sip:%s@%s>;tag=%s", r
->username
, p
->tohost
, p
->tag
);
7358 if (!ast_strlen_zero(p
->theirtag
))
7359 snprintf(to
, sizeof(to
), "<sip:%s@%s>;tag=%s", r
->username
, p
->tohost
, p
->theirtag
);
7361 snprintf(to
, sizeof(to
), "<sip:%s@%s>", r
->username
, p
->tohost
);
7364 /* Fromdomain is what we are registering to, regardless of actual
7365 host name from SRV */
7366 if (!ast_strlen_zero(p
->fromdomain
)) {
7367 if (r
->portno
&& r
->portno
!= STANDARD_SIP_PORT
)
7368 snprintf(addr
, sizeof(addr
), "sip:%s:%d", p
->fromdomain
, r
->portno
);
7370 snprintf(addr
, sizeof(addr
), "sip:%s", p
->fromdomain
);
7372 if (r
->portno
&& r
->portno
!= STANDARD_SIP_PORT
)
7373 snprintf(addr
, sizeof(addr
), "sip:%s:%d", r
->hostname
, r
->portno
);
7375 snprintf(addr
, sizeof(addr
), "sip:%s", r
->hostname
);
7377 ast_string_field_set(p
, uri
, addr
);
7379 p
->branch
^= ast_random();
7381 init_req(&req
, sipmethod
, addr
);
7384 snprintf(tmp
, sizeof(tmp
), "%u %s", ++r
->ocseq
, sip_methods
[sipmethod
].text
);
7385 p
->ocseq
= r
->ocseq
;
7388 add_header(&req
, "Via", p
->via
);
7389 add_header(&req
, "From", from
);
7390 add_header(&req
, "To", to
);
7391 add_header(&req
, "Call-ID", p
->callid
);
7392 add_header(&req
, "CSeq", tmp
);
7393 if (!ast_strlen_zero(global_useragent
))
7394 add_header(&req
, "User-Agent", global_useragent
);
7395 add_header(&req
, "Max-Forwards", DEFAULT_MAX_FORWARDS
);
7398 if (auth
) /* Add auth header */
7399 add_header(&req
, authheader
, auth
);
7400 else if (!ast_strlen_zero(r
->nonce
)) {
7403 /* We have auth data to reuse, build a digest header! */
7405 ast_log(LOG_DEBUG
, " >>> Re-using Auth data for %s@%s\n", r
->username
, r
->hostname
);
7406 ast_string_field_set(p
, realm
, r
->realm
);
7407 ast_string_field_set(p
, nonce
, r
->nonce
);
7408 ast_string_field_set(p
, domain
, r
->domain
);
7409 ast_string_field_set(p
, opaque
, r
->opaque
);
7410 ast_string_field_set(p
, qop
, r
->qop
);
7412 p
->noncecount
= r
->noncecount
;
7414 memset(digest
,0,sizeof(digest
));
7415 if(!build_reply_digest(p
, sipmethod
, digest
, sizeof(digest
)))
7416 add_header(&req
, "Authorization", digest
);
7418 ast_log(LOG_NOTICE
, "No authorization available for authentication of registration to %s@%s\n", r
->username
, r
->hostname
);
7422 snprintf(tmp
, sizeof(tmp
), "%d", default_expiry
);
7423 add_header(&req
, "Expires", tmp
);
7424 add_header(&req
, "Contact", p
->our_contact
);
7425 add_header(&req
, "Event", "registration");
7426 add_header_contentLength(&req
, 0);
7428 initialize_initreq(p
, &req
);
7429 if (sip_debug_test_pvt(p
))
7430 ast_verbose("REGISTER %d headers, %d lines\n", p
->initreq
.headers
, p
->initreq
.lines
);
7431 r
->regstate
= auth
? REG_STATE_AUTHSENT
: REG_STATE_REGSENT
;
7432 r
->regattempts
++; /* Another attempt */
7433 if (option_debug
> 3)
7434 ast_verbose("REGISTER attempt %d to %s@%s\n", r
->regattempts
, r
->username
, r
->hostname
);
7435 return send_request(p
, &req
, XMIT_CRITICAL
, p
->ocseq
);
7438 /*! \brief Transmit text with SIP MESSAGE method */
7439 static int transmit_message_with_text(struct sip_pvt
*p
, const char *text
)
7441 struct sip_request req
;
7443 reqprep(&req
, p
, SIP_MESSAGE
, 0, 1);
7444 add_text(&req
, text
);
7445 return send_request(p
, &req
, XMIT_RELIABLE
, p
->ocseq
);
7448 /*! \brief Allocate SIP refer structure */
7449 static int sip_refer_allocate(struct sip_pvt
*p
)
7451 p
->refer
= ast_calloc(1, sizeof(struct sip_refer
));
7452 return p
->refer
? 1 : 0;
7455 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
7456 \note this is currently broken as we have no way of telling the dialplan
7457 engine whether a transfer succeeds or fails.
7458 \todo Fix the transfer() dialplan function so that a transfer may fail
7460 static int transmit_refer(struct sip_pvt
*p
, const char *dest
)
7462 struct sip_request req
= {
7470 char *theirtag
= ast_strdupa(p
->theirtag
);
7472 if (option_debug
|| sipdebug
)
7473 ast_log(LOG_DEBUG
, "SIP transfer of %s to %s\n", p
->callid
, dest
);
7475 /* Are we transfering an inbound or outbound call ? */
7476 if (ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) {
7477 of
= get_header(&p
->initreq
, "To");
7481 of
= get_header(&p
->initreq
, "From");
7486 ast_copy_string(from
, of
, sizeof(from
));
7487 of
= get_in_brackets(from
);
7488 ast_string_field_set(p
, from
, of
);
7489 if (strncasecmp(of
, "sip:", 4))
7490 ast_log(LOG_NOTICE
, "From address missing 'sip:', using it anyway\n");
7493 /* Get just the username part */
7494 if ((c
= strchr(dest
, '@')))
7496 else if ((c
= strchr(of
, '@')))
7499 snprintf(referto
, sizeof(referto
), "<sip:%s@%s>", dest
, c
);
7501 snprintf(referto
, sizeof(referto
), "<sip:%s>", dest
);
7503 /* save in case we get 407 challenge */
7504 sip_refer_allocate(p
);
7505 ast_copy_string(p
->refer
->refer_to
, referto
, sizeof(p
->refer
->refer_to
));
7506 ast_copy_string(p
->refer
->referred_by
, p
->our_contact
, sizeof(p
->refer
->referred_by
));
7507 p
->refer
->status
= REFER_SENT
; /* Set refer status */
7509 reqprep(&req
, p
, SIP_REFER
, 0, 1);
7510 add_header(&req
, "Max-Forwards", DEFAULT_MAX_FORWARDS
);
7512 add_header(&req
, "Refer-To", referto
);
7513 add_header(&req
, "Allow", ALLOWED_METHODS
);
7514 add_header(&req
, "Supported", SUPPORTED_EXTENSIONS
);
7515 if (!ast_strlen_zero(p
->our_contact
))
7516 add_header(&req
, "Referred-By", p
->our_contact
);
7518 return send_request(p
, &req
, XMIT_RELIABLE
, p
->ocseq
);
7519 /* We should propably wait for a NOTIFY here until we ack the transfer */
7520 /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
7522 /*! \todo In theory, we should hang around and wait for a reply, before
7523 returning to the dial plan here. Don't know really how that would
7524 affect the transfer() app or the pbx, but, well, to make this
7525 useful we should have a STATUS code on transfer().
7530 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
7531 static int transmit_info_with_digit(struct sip_pvt
*p
, const char digit
, unsigned int duration
)
7533 struct sip_request req
;
7535 reqprep(&req
, p
, SIP_INFO
, 0, 1);
7536 add_digit(&req
, digit
, duration
);
7537 return send_request(p
, &req
, XMIT_RELIABLE
, p
->ocseq
);
7540 /*! \brief Send SIP INFO with video update request */
7541 static int transmit_info_with_vidupdate(struct sip_pvt
*p
)
7543 struct sip_request req
;
7545 reqprep(&req
, p
, SIP_INFO
, 0, 1);
7546 add_vidupdate(&req
);
7547 return send_request(p
, &req
, XMIT_RELIABLE
, p
->ocseq
);
7550 /*! \brief Transmit generic SIP request
7551 returns XMIT_ERROR if transmit failed with a critical error (don't retry)
7553 static int transmit_request(struct sip_pvt
*p
, int sipmethod
, int seqno
, enum xmittype reliable
, int newbranch
)
7555 struct sip_request resp
;
7557 if (sipmethod
== SIP_ACK
)
7558 p
->invitestate
= INV_CONFIRMED
;
7560 reqprep(&resp
, p
, sipmethod
, seqno
, newbranch
);
7561 add_header_contentLength(&resp
, 0);
7562 return send_request(p
, &resp
, reliable
, seqno
? seqno
: p
->ocseq
);
7565 /*! \brief Transmit SIP request, auth added */
7566 static int transmit_request_with_auth(struct sip_pvt
*p
, int sipmethod
, int seqno
, enum xmittype reliable
, int newbranch
)
7568 struct sip_request resp
;
7570 reqprep(&resp
, p
, sipmethod
, seqno
, newbranch
);
7571 if (!ast_strlen_zero(p
->realm
)) {
7574 memset(digest
, 0, sizeof(digest
));
7575 if(!build_reply_digest(p
, sipmethod
, digest
, sizeof(digest
))) {
7576 if (p
->options
&& p
->options
->auth_type
== PROXY_AUTH
)
7577 add_header(&resp
, "Proxy-Authorization", digest
);
7578 else if (p
->options
&& p
->options
->auth_type
== WWW_AUTH
)
7579 add_header(&resp
, "Authorization", digest
);
7580 else /* Default, to be backwards compatible (maybe being too careful, but leaving it for now) */
7581 add_header(&resp
, "Proxy-Authorization", digest
);
7583 ast_log(LOG_WARNING
, "No authentication available for call %s\n", p
->callid
);
7585 /* If we are hanging up and know a cause for that, send it in clear text to make
7586 debugging easier. */
7587 if (sipmethod
== SIP_BYE
&& p
->owner
&& p
->owner
->hangupcause
) {
7590 add_header(&resp
, "X-Asterisk-HangupCause", ast_cause2str(p
->owner
->hangupcause
));
7591 snprintf(buf
, sizeof(buf
), "%d", p
->owner
->hangupcause
);
7592 add_header(&resp
, "X-Asterisk-HangupCauseCode", buf
);
7595 add_header_contentLength(&resp
, 0);
7596 return send_request(p
, &resp
, reliable
, seqno
? seqno
: p
->ocseq
);
7599 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
7600 static void destroy_association(struct sip_peer
*peer
)
7602 if (!ast_test_flag(&global_flags
[1], SIP_PAGE2_IGNOREREGEXPIRE
)) {
7603 if (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_RT_FROMCONTACT
))
7604 ast_update_realtime("sippeers", "name", peer
->name
, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "username", "", "regserver", "", NULL
);
7606 ast_db_del("SIP/Registry", peer
->name
);
7610 /*! \brief Expire registration of SIP peer */
7611 static int expire_register(void *data
)
7613 struct sip_peer
*peer
= data
;
7615 if (!peer
) /* Hmmm. We have no peer. Weird. */
7618 memset(&peer
->addr
, 0, sizeof(peer
->addr
));
7620 destroy_association(peer
); /* remove registration data from storage */
7622 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer
->name
);
7623 register_peer_exten(peer
, FALSE
); /* Remove regexten */
7625 ast_device_state_changed("SIP/%s", peer
->name
);
7627 /* Do we need to release this peer from memory?
7628 Only for realtime peers and autocreated peers
7630 if (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_SELFDESTRUCT
) ||
7631 ast_test_flag(&peer
->flags
[1], SIP_PAGE2_RTAUTOCLEAR
)) {
7632 peer
= ASTOBJ_CONTAINER_UNLINK(&peerl
, peer
); /* Remove from peer list */
7633 ASTOBJ_UNREF(peer
, sip_destroy_peer
); /* Remove from memory */
7639 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
7640 static int sip_poke_peer_s(void *data
)
7642 struct sip_peer
*peer
= data
;
7644 peer
->pokeexpire
= -1;
7645 sip_poke_peer(peer
);
7649 /*! \brief Get registration details from Asterisk DB */
7650 static void reg_source_db(struct sip_peer
*peer
)
7656 char *scan
, *addr
, *port_str
, *expiry_str
, *username
, *contact
;
7658 if (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_RT_FROMCONTACT
))
7660 if (ast_db_get("SIP/Registry", peer
->name
, data
, sizeof(data
)))
7664 addr
= strsep(&scan
, ":");
7665 port_str
= strsep(&scan
, ":");
7666 expiry_str
= strsep(&scan
, ":");
7667 username
= strsep(&scan
, ":");
7668 contact
= scan
; /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
7670 if (!inet_aton(addr
, &in
))
7674 port
= atoi(port_str
);
7679 expiry
= atoi(expiry_str
);
7684 ast_copy_string(peer
->username
, username
, sizeof(peer
->username
));
7686 ast_copy_string(peer
->fullcontact
, contact
, sizeof(peer
->fullcontact
));
7688 if (option_debug
> 1)
7689 ast_log(LOG_DEBUG
, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
7690 peer
->name
, peer
->username
, ast_inet_ntoa(in
), port
, expiry
);
7692 memset(&peer
->addr
, 0, sizeof(peer
->addr
));
7693 peer
->addr
.sin_family
= AF_INET
;
7694 peer
->addr
.sin_addr
= in
;
7695 peer
->addr
.sin_port
= htons(port
);
7697 /* SIP isn't up yet, so schedule a poke only, pretty soon */
7698 if (peer
->pokeexpire
> -1)
7699 ast_sched_del(sched
, peer
->pokeexpire
);
7700 peer
->pokeexpire
= ast_sched_add(sched
, ast_random() % 5000 + 1, sip_poke_peer_s
, peer
);
7702 sip_poke_peer(peer
);
7703 if (peer
->expire
> -1)
7704 ast_sched_del(sched
, peer
->expire
);
7705 peer
->expire
= ast_sched_add(sched
, (expiry
+ 10) * 1000, expire_register
, peer
);
7706 register_peer_exten(peer
, TRUE
);
7707 ast_device_state_changed("SIP/%s", peer
->name
);
7710 /*! \brief Save contact header for 200 OK on INVITE */
7711 static int parse_ok_contact(struct sip_pvt
*pvt
, struct sip_request
*req
)
7713 char contact
[BUFSIZ
];
7716 /* Look for brackets */
7717 ast_copy_string(contact
, get_header(req
, "Contact"), sizeof(contact
));
7718 c
= get_in_brackets(contact
);
7720 /* Save full contact to call pvt for later bye or re-invite */
7721 ast_string_field_set(pvt
, fullcontact
, c
);
7723 /* Save URI for later ACKs, BYE or RE-invites */
7724 ast_string_field_set(pvt
, okcontacturi
, c
);
7726 /* We should return false for URI:s we can't handle,
7727 like sips:, tel:, mailto:,ldap: etc */
7731 /*! \brief Change the other partys IP address based on given contact */
7732 static int set_address_from_contact(struct sip_pvt
*pvt
)
7735 struct ast_hostent ahp
;
7737 char *c
, *host
, *pt
;
7741 if (ast_test_flag(&pvt
->flags
[0], SIP_NAT_ROUTE
)) {
7742 /* NAT: Don't trust the contact field. Just use what they came to us
7744 pvt
->sa
= pvt
->recv
;
7749 /* Work on a copy */
7750 contact
= ast_strdupa(pvt
->fullcontact
);
7752 /* Make sure it's a SIP URL */
7753 if (strncasecmp(contact
, "sip:", 4)) {
7754 ast_log(LOG_NOTICE
, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact
);
7758 /* Ditch arguments */
7759 /* XXX this code is replicated also shortly below */
7762 host
= strchr(contact
, '@');
7763 if (!host
) { /* No username part */
7769 pt
= strchr(host
, ':');
7774 port
= STANDARD_SIP_PORT
;
7776 contact
= strsep(&contact
, ";"); /* trim ; and beyond in username part */
7777 host
= strsep(&host
, ";"); /* trim ; and beyond in host/domain part */
7779 /* XXX This could block for a long time XXX */
7780 /* We should only do this if it's a name, not an IP */
7781 hp
= ast_gethostbyname(host
, &ahp
);
7783 ast_log(LOG_WARNING
, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host
);
7786 pvt
->sa
.sin_family
= AF_INET
;
7787 memcpy(&pvt
->sa
.sin_addr
, hp
->h_addr
, sizeof(pvt
->sa
.sin_addr
));
7788 pvt
->sa
.sin_port
= htons(port
);
7794 /*! \brief Parse contact header and save registration (peer registration) */
7795 static enum parse_register_result
parse_register_contact(struct sip_pvt
*pvt
, struct sip_peer
*peer
, struct sip_request
*req
)
7797 char contact
[BUFSIZ
];
7799 const char *expires
= get_header(req
, "Expires");
7800 int expiry
= atoi(expires
);
7801 char *curi
, *n
, *pt
;
7803 const char *useragent
;
7805 struct ast_hostent ahp
;
7806 struct sockaddr_in oldsin
;
7808 ast_copy_string(contact
, get_header(req
, "Contact"), sizeof(contact
));
7810 if (ast_strlen_zero(expires
)) { /* No expires header */
7811 expires
= strcasestr(contact
, ";expires=");
7813 /* XXX bug here, we overwrite the string */
7814 expires
= strsep((char **) &expires
, ";"); /* trim ; and beyond */
7815 if (sscanf(expires
+ 9, "%d", &expiry
) != 1)
7816 expiry
= default_expiry
;
7818 /* Nothing has been specified */
7819 expiry
= default_expiry
;
7823 /* Look for brackets */
7825 if (strchr(contact
, '<') == NULL
) /* No <, check for ; and strip it */
7826 strsep(&curi
, ";"); /* This is Header options, not URI options */
7827 curi
= get_in_brackets(contact
);
7829 /* if they did not specify Contact: or Expires:, they are querying
7830 what we currently have stored as their contact address, so return
7833 if (ast_strlen_zero(curi
) && ast_strlen_zero(expires
)) {
7834 /* If we have an active registration, tell them when the registration is going to expire */
7835 if (peer
->expire
> -1 && !ast_strlen_zero(peer
->fullcontact
))
7836 pvt
->expiry
= ast_sched_when(sched
, peer
->expire
);
7837 return PARSE_REGISTER_QUERY
;
7838 } else if (!strcasecmp(curi
, "*") || !expiry
) { /* Unregister this peer */
7839 /* This means remove all registrations and return OK */
7840 memset(&peer
->addr
, 0, sizeof(peer
->addr
));
7841 if (peer
->expire
> -1)
7842 ast_sched_del(sched
, peer
->expire
);
7845 destroy_association(peer
);
7847 register_peer_exten(peer
, 0); /* Add extension from regexten= setting in sip.conf */
7848 peer
->fullcontact
[0] = '\0';
7849 peer
->useragent
[0] = '\0';
7850 peer
->sipoptions
= 0;
7853 if (option_verbose
> 2)
7854 ast_verbose(VERBOSE_PREFIX_3
"Unregistered SIP '%s'\n", peer
->name
);
7855 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer
->name
);
7856 return PARSE_REGISTER_UPDATE
;
7859 /* Store whatever we got as a contact from the client */
7860 ast_copy_string(peer
->fullcontact
, curi
, sizeof(peer
->fullcontact
));
7862 /* For the 200 OK, we should use the received contact */
7863 ast_string_field_build(pvt
, our_contact
, "<%s>", curi
);
7865 /* Make sure it's a SIP URL */
7866 if (strncasecmp(curi
, "sip:", 4)) {
7867 ast_log(LOG_NOTICE
, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", curi
);
7871 curi
= strsep(&curi
, ";");
7873 n
= strchr(curi
, '@');
7879 pt
= strchr(n
, ':');
7884 port
= STANDARD_SIP_PORT
;
7885 oldsin
= peer
->addr
;
7886 if (!ast_test_flag(&peer
->flags
[0], SIP_NAT_ROUTE
)) {
7887 /* XXX This could block for a long time XXX */
7888 hp
= ast_gethostbyname(n
, &ahp
);
7890 ast_log(LOG_WARNING
, "Invalid host '%s'\n", n
);
7891 return PARSE_REGISTER_FAILED
;
7893 peer
->addr
.sin_family
= AF_INET
;
7894 memcpy(&peer
->addr
.sin_addr
, hp
->h_addr
, sizeof(peer
->addr
.sin_addr
));
7895 peer
->addr
.sin_port
= htons(port
);
7897 /* Don't trust the contact field. Just use what they came to us
7899 peer
->addr
= pvt
->recv
;
7902 /* Save SIP options profile */
7903 peer
->sipoptions
= pvt
->sipoptions
;
7905 if (curi
) /* Overwrite the default username from config at registration */
7906 ast_copy_string(peer
->username
, curi
, sizeof(peer
->username
));
7908 peer
->username
[0] = '\0';
7910 if (peer
->expire
> -1) {
7911 ast_sched_del(sched
, peer
->expire
);
7914 if (expiry
> max_expiry
)
7915 expiry
= max_expiry
;
7916 if (expiry
< min_expiry
)
7917 expiry
= min_expiry
;
7918 peer
->expire
= ast_test_flag(&peer
->flags
[0], SIP_REALTIME
) ? -1 :
7919 ast_sched_add(sched
, (expiry
+ 10) * 1000, expire_register
, peer
);
7920 pvt
->expiry
= expiry
;
7921 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
);
7922 if (!ast_test_flag(&peer
->flags
[1], SIP_PAGE2_RT_FROMCONTACT
))
7923 ast_db_put("SIP/Registry", peer
->name
, data
);
7924 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer
->name
);
7926 /* Is this a new IP address for us? */
7927 if (inaddrcmp(&peer
->addr
, &oldsin
)) {
7928 sip_poke_peer(peer
);
7929 if (option_verbose
> 2)
7930 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
);
7931 register_peer_exten(peer
, 1);
7934 /* Save User agent */
7935 useragent
= get_header(req
, "User-Agent");
7936 if (strcasecmp(useragent
, peer
->useragent
)) { /* XXX copy if they are different ? */
7937 ast_copy_string(peer
->useragent
, useragent
, sizeof(peer
->useragent
));
7938 if (option_verbose
> 3)
7939 ast_verbose(VERBOSE_PREFIX_3
"Saved useragent \"%s\" for peer %s\n", peer
->useragent
, peer
->name
);
7941 return PARSE_REGISTER_UPDATE
;
7944 /*! \brief Remove route from route list */
7945 static void free_old_route(struct sip_route
*route
)
7947 struct sip_route
*next
;
7956 /*! \brief List all routes - mostly for debugging */
7957 static void list_route(struct sip_route
*route
)
7960 ast_verbose("list_route: no route\n");
7962 for (;route
; route
= route
->next
)
7963 ast_verbose("list_route: hop: <%s>\n", route
->hop
);
7967 /*! \brief Build route list from Record-Route header */
7968 static void build_route(struct sip_pvt
*p
, struct sip_request
*req
, int backwards
)
7970 struct sip_route
*thishop
, *head
, *tail
;
7973 const char *rr
, *contact
, *c
;
7975 /* Once a persistant route is set, don't fool with it */
7976 if (p
->route
&& p
->route_persistant
) {
7978 ast_log(LOG_DEBUG
, "build_route: Retaining previous route: <%s>\n", p
->route
->hop
);
7983 free_old_route(p
->route
);
7987 p
->route_persistant
= backwards
;
7989 /* Build a tailq, then assign it to p->route when done.
7990 * If backwards, we add entries from the head so they end up
7991 * in reverse order. However, we do need to maintain a correct
7992 * tail pointer because the contact is always at the end.
7996 /* 1st we pass through all the hops in any Record-Route headers */
7998 /* Each Record-Route header */
7999 rr
= __get_header(req
, "Record-Route", &start
);
8002 for (; (rr
= strchr(rr
, '<')) ; rr
+= len
) { /* Each route entry */
8004 len
= strcspn(rr
, ">") + 1;
8005 /* Make a struct route */
8006 if ((thishop
= ast_malloc(sizeof(*thishop
) + len
))) {
8007 /* ast_calloc is not needed because all fields are initialized in this block */
8008 ast_copy_string(thishop
->hop
, rr
, len
);
8009 if (option_debug
> 1)
8010 ast_log(LOG_DEBUG
, "build_route: Record-Route hop: <%s>\n", thishop
->hop
);
8013 /* Link in at head so they end up in reverse order */
8014 thishop
->next
= head
;
8016 /* If this was the first then it'll be the tail */
8020 thishop
->next
= NULL
;
8021 /* Link in at the end */
8023 tail
->next
= thishop
;
8032 /* Only append the contact if we are dealing with a strict router */
8033 if (!head
|| (!ast_strlen_zero(head
->hop
) && strstr(head
->hop
,";lr") == NULL
) ) {
8034 /* 2nd append the Contact: if there is one */
8035 /* Can be multiple Contact headers, comma separated values - we just take the first */
8036 contact
= get_header(req
, "Contact");
8037 if (!ast_strlen_zero(contact
)) {
8038 if (option_debug
> 1)
8039 ast_log(LOG_DEBUG
, "build_route: Contact hop: %s\n", contact
);
8040 /* Look for <: delimited address */
8041 c
= strchr(contact
, '<');
8045 len
= strcspn(c
, ">") + 1;
8047 /* No <> - just take the lot */
8049 len
= strlen(contact
) + 1;
8051 if ((thishop
= ast_malloc(sizeof(*thishop
) + len
))) {
8052 /* ast_calloc is not needed because all fields are initialized in this block */
8053 ast_copy_string(thishop
->hop
, c
, len
);
8054 thishop
->next
= NULL
;
8055 /* Goes at the end */
8057 tail
->next
= thishop
;
8064 /* Store as new route */
8067 /* For debugging dump what we ended up with */
8068 if (sip_debug_test_pvt(p
))
8069 list_route(p
->route
);
8073 /*! \brief Check user authorization from peer definition
8074 Some actions, like REGISTER and INVITEs from peers require
8075 authentication (if peer have secret set)
8076 \return 0 on success, non-zero on error
8078 static enum check_auth_result
check_auth(struct sip_pvt
*p
, struct sip_request
*req
, const char *username
,
8079 const char *secret
, const char *md5secret
, int sipmethod
,
8080 char *uri
, enum xmittype reliable
, int ignore
)
8082 const char *response
= "407 Proxy Authentication Required";
8083 const char *reqheader
= "Proxy-Authorization";
8084 const char *respheader
= "Proxy-Authenticate";
8085 const char *authtoken
;
8087 char resp_hash
[256]="";
8088 char tmp
[BUFSIZ
* 2]; /* Make a large enough buffer */
8090 int wrongnonce
= FALSE
;
8092 const char *usednonce
= p
->randdata
;
8094 /* table of recognised keywords, and their value in the digest */
8095 enum keys
{ K_RESP
, K_URI
, K_USER
, K_NONCE
, K_LAST
};
8100 [K_RESP
] = { "response=", "" },
8101 [K_URI
] = { "uri=", "" },
8102 [K_USER
] = { "username=", "" },
8103 [K_NONCE
] = { "nonce=", "" },
8104 [K_LAST
] = { NULL
, NULL
}
8107 /* Always OK if no secret */
8108 if (ast_strlen_zero(secret
) && ast_strlen_zero(md5secret
))
8109 return AUTH_SUCCESSFUL
;
8110 if (sipmethod
== SIP_REGISTER
|| sipmethod
== SIP_SUBSCRIBE
) {
8111 /* On a REGISTER, we have to use 401 and its family of headers instead of 407 and its family
8112 of headers -- GO SIP! Whoo hoo! Two things that do the same thing but are used in
8113 different circumstances! What a surprise. */
8114 response
= "401 Unauthorized";
8115 reqheader
= "Authorization";
8116 respheader
= "WWW-Authenticate";
8118 authtoken
= get_header(req
, reqheader
);
8119 if (ignore
&& !ast_strlen_zero(p
->randdata
) && ast_strlen_zero(authtoken
)) {
8120 /* This is a retransmitted invite/register/etc, don't reconstruct authentication
8123 /* Resend message if this was NOT a reliable delivery. Otherwise the
8124 retransmission should get it */
8125 transmit_response_with_auth(p
, response
, req
, p
->randdata
, reliable
, respheader
, 0);
8126 /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
8127 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
8129 return AUTH_CHALLENGE_SENT
;
8130 } else if (ast_strlen_zero(p
->randdata
) || ast_strlen_zero(authtoken
)) {
8131 /* We have no auth, so issue challenge and request authentication */
8132 ast_string_field_build(p
, randdata
, "%08lx", ast_random()); /* Create nonce for challenge */
8133 transmit_response_with_auth(p
, response
, req
, p
->randdata
, reliable
, respheader
, 0);
8134 /* Schedule auto destroy in 32 seconds */
8135 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
8136 return AUTH_CHALLENGE_SENT
;
8139 /* --- We have auth, so check it */
8141 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
8142 an example in the spec of just what it is you're doing a hash on. */
8145 /* Make a copy of the response and parse it */
8146 ast_copy_string(tmp
, authtoken
, sizeof(tmp
));
8149 while(c
&& *(c
= ast_skip_blanks(c
)) ) { /* lookup for keys */
8150 for (i
= keys
; i
->key
!= NULL
; i
++) {
8151 const char *separator
= ","; /* default */
8153 if (strncasecmp(c
, i
->key
, strlen(i
->key
)) != 0)
8155 /* Found. Skip keyword, take text in quotes or up to the separator. */
8156 c
+= strlen(i
->key
);
8157 if (*c
== '"') { /* in quotes. Skip first and look for last */
8162 strsep(&c
, separator
);
8165 if (i
->key
== NULL
) /* not found, jump after space or comma */
8169 /* Verify that digest username matches the username we auth as */
8170 if (strcmp(username
, keys
[K_USER
].s
)) {
8171 ast_log(LOG_WARNING
, "username mismatch, have <%s>, digest has <%s>\n",
8172 username
, keys
[K_USER
].s
);
8173 /* Oops, we're trying something here */
8174 return AUTH_USERNAME_MISMATCH
;
8177 /* Verify nonce from request matches our nonce. If not, send 401 with new nonce */
8178 if (strcasecmp(p
->randdata
, keys
[K_NONCE
].s
)) { /* XXX it was 'n'casecmp ? */
8180 usednonce
= keys
[K_NONCE
].s
;
8183 if (!ast_strlen_zero(md5secret
))
8184 ast_copy_string(a1_hash
, md5secret
, sizeof(a1_hash
));
8187 snprintf(a1
, sizeof(a1
), "%s:%s:%s", username
, global_realm
, secret
);
8188 ast_md5_hash(a1_hash
, a1
);
8191 /* compute the expected response to compare with what we received */
8197 snprintf(a2
, sizeof(a2
), "%s:%s", sip_methods
[sipmethod
].text
,
8198 S_OR(keys
[K_URI
].s
, uri
));
8199 ast_md5_hash(a2_hash
, a2
);
8200 snprintf(resp
, sizeof(resp
), "%s:%s:%s", a1_hash
, usednonce
, a2_hash
);
8201 ast_md5_hash(resp_hash
, resp
);
8204 good_response
= keys
[K_RESP
].s
&&
8205 !strncasecmp(keys
[K_RESP
].s
, resp_hash
, strlen(resp_hash
));
8207 ast_string_field_build(p
, randdata
, "%08lx", ast_random());
8208 if (good_response
) {
8210 ast_log(LOG_NOTICE
, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req
, "To"));
8211 /* We got working auth token, based on stale nonce . */
8212 transmit_response_with_auth(p
, response
, req
, p
->randdata
, reliable
, respheader
, TRUE
);
8214 /* Everything was wrong, so give the device one more try with a new challenge */
8216 ast_log(LOG_NOTICE
, "Bad authentication received from '%s'\n", get_header(req
, "To"));
8217 transmit_response_with_auth(p
, response
, req
, p
->randdata
, reliable
, respheader
, FALSE
);
8220 /* Schedule auto destroy in 32 seconds */
8221 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
8222 return AUTH_CHALLENGE_SENT
;
8224 if (good_response
) {
8225 append_history(p
, "AuthOK", "Auth challenge succesful for %s", username
);
8226 return AUTH_SUCCESSFUL
;
8229 /* Ok, we have a bad username/secret pair */
8230 /* Challenge again, and again, and again */
8231 transmit_response_with_auth(p
, response
, req
, p
->randdata
, reliable
, respheader
, 0);
8232 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
8234 return AUTH_CHALLENGE_SENT
;
8237 /*! \brief Change onhold state of a peer using a pvt structure */
8238 static void sip_peer_hold(struct sip_pvt
*p
, int hold
)
8240 struct sip_peer
*peer
= find_peer(p
->peername
, NULL
, 1);
8245 /* If they put someone on hold, increment the value... otherwise decrement it */
8251 /* Request device state update */
8252 ast_device_state_changed("SIP/%s", peer
->name
);
8257 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
8258 \note If you add an "hint" priority to the extension in the dial plan,
8259 you will get notifications on device state changes */
8260 static int cb_extensionstate(char *context
, char* exten
, int state
, void *data
)
8262 struct sip_pvt
*p
= data
;
8265 case AST_EXTENSION_DEACTIVATED
: /* Retry after a while */
8266 case AST_EXTENSION_REMOVED
: /* Extension is gone */
8267 if (p
->autokillid
> -1)
8268 sip_cancel_destroy(p
); /* Remove subscription expiry for renewals */
8269 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
); /* Delete subscription in 32 secs */
8270 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
);
8272 p
->subscribed
= NONE
;
8273 append_history(p
, "Subscribestatus", "%s", state
== AST_EXTENSION_REMOVED
? "HintRemoved" : "Deactivated");
8275 default: /* Tell user */
8276 p
->laststate
= state
;
8279 if (p
->subscribed
!= NONE
) /* Only send state NOTIFY if we know the format */
8280 transmit_state_notify(p
, state
, 1, FALSE
);
8282 if (option_verbose
> 1)
8283 ast_verbose(VERBOSE_PREFIX_1
"Extension Changed %s new state %s for Notify User %s\n", exten
, ast_extension_state2str(state
), p
->username
);
8287 /*! \brief Send a fake 401 Unauthorized response when the administrator
8288 wants to hide the names of local users/peers from fishers
8290 static void transmit_fake_auth_response(struct sip_pvt
*p
, struct sip_request
*req
, int reliable
)
8292 ast_string_field_build(p
, randdata
, "%08lx", ast_random()); /* Create nonce for challenge */
8293 transmit_response_with_auth(p
, "401 Unauthorized", req
, p
->randdata
, reliable
, "WWW-Authenticate", 0);
8296 /*! \brief Verify registration of user
8297 - Registration is done in several steps, first a REGISTER without auth
8298 to get a challenge (nonce) then a second one with auth
8299 - Registration requests are only matched with peers that are marked as "dynamic"
8301 static enum check_auth_result
register_verify(struct sip_pvt
*p
, struct sockaddr_in
*sin
,
8302 struct sip_request
*req
, char *uri
)
8304 enum check_auth_result res
= AUTH_NOT_FOUND
;
8305 struct sip_peer
*peer
;
8313 while(*t
&& (*t
> 32) && (*t
!= ';'))
8317 ast_copy_string(tmp
, get_header(req
, "To"), sizeof(tmp
));
8318 if (pedanticsipchecking
)
8319 ast_uri_decode(tmp
);
8321 c
= get_in_brackets(tmp
);
8322 c
= strsep(&c
, ";"); /* Ditch ;user=phone */
8324 if (!strncasecmp(c
, "sip:", 4)) {
8328 ast_log(LOG_NOTICE
, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c
, ast_inet_ntoa(sin
->sin_addr
));
8331 /* Strip off the domain name */
8332 if ((c
= strchr(name
, '@'))) {
8335 if ((c
= strchr(domain
, ':'))) /* Remove :port */
8337 if (!AST_LIST_EMPTY(&domain_list
)) {
8338 if (!check_sip_domain(domain
, NULL
, 0)) {
8339 transmit_response(p
, "404 Not found (unknown domain)", &p
->initreq
);
8340 return AUTH_UNKNOWN_DOMAIN
;
8345 ast_string_field_set(p
, exten
, name
);
8347 peer
= find_peer(name
, NULL
, 1);
8348 if (!(peer
&& ast_apply_ha(peer
->ha
, sin
))) {
8349 /* Peer fails ACL check */
8351 ASTOBJ_UNREF(peer
, sip_destroy_peer
);
8353 res
= AUTH_ACL_FAILED
;
8356 /* Set Frame packetization */
8358 ast_rtp_codec_setpref(p
->rtp
, &peer
->prefs
);
8359 p
->autoframing
= peer
->autoframing
;
8361 if (!ast_test_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
)) {
8362 ast_log(LOG_ERROR
, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer
->name
);
8363 res
= AUTH_PEER_NOT_DYNAMIC
;
8365 ast_copy_flags(&p
->flags
[0], &peer
->flags
[0], SIP_NAT
);
8366 transmit_response(p
, "100 Trying", req
);
8367 if (!(res
= check_auth(p
, req
, peer
->name
, peer
->secret
, peer
->md5secret
, SIP_REGISTER
, uri
, XMIT_UNRELIABLE
, ast_test_flag(req
, SIP_PKT_IGNORE
)))) {
8368 sip_cancel_destroy(p
);
8370 /* We have a succesful registration attemp with proper authentication,
8371 now, update the peer */
8372 switch (parse_register_contact(p
, peer
, req
)) {
8373 case PARSE_REGISTER_FAILED
:
8374 ast_log(LOG_WARNING
, "Failed to parse contact info\n");
8375 transmit_response_with_date(p
, "400 Bad Request", req
);
8376 peer
->lastmsgssent
= -1;
8379 case PARSE_REGISTER_QUERY
:
8380 transmit_response_with_date(p
, "200 OK", req
);
8381 peer
->lastmsgssent
= -1;
8384 case PARSE_REGISTER_UPDATE
:
8385 update_peer(peer
, p
->expiry
);
8386 /* Say OK and ask subsystem to retransmit msg counter */
8387 transmit_response_with_date(p
, "200 OK", req
);
8388 if (!ast_test_flag((&peer
->flags
[1]), SIP_PAGE2_SUBSCRIBEMWIONLY
))
8389 peer
->lastmsgssent
= -1;
8396 if (!peer
&& autocreatepeer
) {
8397 /* Create peer if we have autocreate mode enabled */
8398 peer
= temp_peer(name
);
8400 ASTOBJ_CONTAINER_LINK(&peerl
, peer
);
8401 sip_cancel_destroy(p
);
8402 switch (parse_register_contact(p
, peer
, req
)) {
8403 case PARSE_REGISTER_FAILED
:
8404 ast_log(LOG_WARNING
, "Failed to parse contact info\n");
8405 transmit_response_with_date(p
, "400 Bad Request", req
);
8406 peer
->lastmsgssent
= -1;
8409 case PARSE_REGISTER_QUERY
:
8410 transmit_response_with_date(p
, "200 OK", req
);
8411 peer
->lastmsgssent
= -1;
8414 case PARSE_REGISTER_UPDATE
:
8415 /* Say OK and ask subsystem to retransmit msg counter */
8416 transmit_response_with_date(p
, "200 OK", req
);
8417 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer
->name
);
8418 peer
->lastmsgssent
= -1;
8425 ast_device_state_changed("SIP/%s", peer
->name
);
8429 case AUTH_SECRET_FAILED
:
8430 /* Wrong password in authentication. Go away, don't try again until you fixed it */
8431 transmit_response(p
, "403 Forbidden (Bad auth)", &p
->initreq
);
8433 case AUTH_USERNAME_MISMATCH
:
8434 /* Username and digest username does not match.
8435 Asterisk uses the From: username for authentication. We need the
8436 users to use the same authentication user name until we support
8437 proper authentication by digest auth name */
8438 transmit_response(p
, "403 Authentication user name does not match account name", &p
->initreq
);
8440 case AUTH_NOT_FOUND
:
8441 case AUTH_PEER_NOT_DYNAMIC
:
8442 case AUTH_ACL_FAILED
:
8443 if (global_alwaysauthreject
) {
8444 transmit_fake_auth_response(p
, &p
->initreq
, 1);
8447 if (res
== AUTH_UNKNOWN_DOMAIN
|| res
== AUTH_PEER_NOT_DYNAMIC
)
8448 transmit_response(p
, "403 Forbidden", &p
->initreq
);
8450 transmit_response(p
, "404 Not found", &p
->initreq
);
8458 ASTOBJ_UNREF(peer
, sip_destroy_peer
);
8463 /*! \brief Get referring dnis */
8464 static int get_rdnis(struct sip_pvt
*p
, struct sip_request
*oreq
)
8466 char tmp
[256], *c
, *a
;
8467 struct sip_request
*req
;
8472 ast_copy_string(tmp
, get_header(req
, "Diversion"), sizeof(tmp
));
8473 if (ast_strlen_zero(tmp
))
8475 c
= get_in_brackets(tmp
);
8476 if (strncasecmp(c
, "sip:", 4)) {
8477 ast_log(LOG_WARNING
, "Huh? Not an RDNIS SIP header (%s)?\n", c
);
8482 strsep(&a
, "@;"); /* trim anything after @ or ; */
8483 if (sip_debug_test_pvt(p
))
8484 ast_verbose("RDNIS is %s\n", c
);
8485 ast_string_field_set(p
, rdnis
, c
);
8490 /*! \brief Find out who the call is for
8491 We use the INVITE uri to find out
8493 static int get_destination(struct sip_pvt
*p
, struct sip_request
*oreq
)
8495 char tmp
[256] = "", *uri
, *a
;
8496 char tmpf
[256] = "", *from
;
8497 struct sip_request
*req
;
8504 /* Find the request URI */
8506 ast_copy_string(tmp
, req
->rlPart2
, sizeof(tmp
));
8508 if (pedanticsipchecking
)
8509 ast_uri_decode(tmp
);
8511 uri
= get_in_brackets(tmp
);
8513 if (strncasecmp(uri
, "sip:", 4)) {
8514 ast_log(LOG_WARNING
, "Huh? Not a SIP header (%s)?\n", uri
);
8519 /* Now find the From: caller ID and name */
8520 ast_copy_string(tmpf
, get_header(req
, "From"), sizeof(tmpf
));
8521 if (!ast_strlen_zero(tmpf
)) {
8522 if (pedanticsipchecking
)
8523 ast_uri_decode(tmpf
);
8524 from
= get_in_brackets(tmpf
);
8529 if (!ast_strlen_zero(from
)) {
8530 if (strncasecmp(from
, "sip:", 4)) {
8531 ast_log(LOG_WARNING
, "Huh? Not a SIP header (%s)?\n", from
);
8535 if ((a
= strchr(from
, '@')))
8538 a
= from
; /* just a domain */
8539 from
= strsep(&from
, ";"); /* Remove userinfo options */
8540 a
= strsep(&a
, ";"); /* Remove URI options */
8541 ast_string_field_set(p
, fromdomain
, a
);
8544 /* Skip any options and find the domain */
8546 /* Get the target domain */
8547 if ((a
= strchr(uri
, '@'))) {
8549 } else { /* No username part */
8551 uri
= "s"; /* Set extension to "s" */
8553 colon
= strchr(a
, ':'); /* Remove :port */
8557 uri
= strsep(&uri
, ";"); /* Remove userinfo options */
8558 a
= strsep(&a
, ";"); /* Remove URI options */
8560 ast_string_field_set(p
, domain
, a
);
8562 if (!AST_LIST_EMPTY(&domain_list
)) {
8563 char domain_context
[AST_MAX_EXTENSION
];
8565 domain_context
[0] = '\0';
8566 if (!check_sip_domain(p
->domain
, domain_context
, sizeof(domain_context
))) {
8567 if (!allow_external_domains
&& (req
->method
== SIP_INVITE
|| req
->method
== SIP_REFER
)) {
8569 ast_log(LOG_DEBUG
, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods
[req
->method
].text
, p
->domain
);
8573 /* If we have a context defined, overwrite the original context */
8574 if (!ast_strlen_zero(domain_context
))
8575 ast_string_field_set(p
, context
, domain_context
);
8578 if (sip_debug_test_pvt(p
))
8579 ast_verbose("Looking for %s in %s (domain %s)\n", uri
, p
->context
, p
->domain
);
8581 /* Check the dialplan for the username part of the request URI,
8582 the domain will be stored in the SIPDOMAIN variable
8583 Return 0 if we have a matching extension */
8584 if (ast_exists_extension(NULL
, p
->context
, uri
, 1, from
) ||
8585 !strcmp(uri
, ast_pickup_ext())) {
8587 ast_string_field_set(p
, exten
, uri
);
8591 /* Return 1 for pickup extension or overlap dialling support (if we support it) */
8592 if((ast_test_flag(&global_flags
[1], SIP_PAGE2_ALLOWOVERLAP
) &&
8593 ast_canmatch_extension(NULL
, p
->context
, uri
, 1, from
)) ||
8594 !strncmp(uri
, ast_pickup_ext(), strlen(uri
))) {
8601 /*! \brief Lock interface lock and find matching pvt lock
8602 - Their tag is fromtag, our tag is to-tag
8603 - This means that in some transactions, totag needs to be their tag :-)
8604 depending upon the direction
8606 static struct sip_pvt
*get_sip_pvt_byid_locked(const char *callid
, const char *totag
, const char *fromtag
)
8608 struct sip_pvt
*sip_pvt_ptr
;
8610 ast_mutex_lock(&iflock
);
8612 if (option_debug
> 3 && totag
)
8613 ast_log(LOG_DEBUG
, "Looking for callid %s (fromtag %s totag %s)\n", callid
, fromtag
? fromtag
: "<no fromtag>", totag
? totag
: "<no totag>");
8615 /* Search interfaces and find the match */
8616 for (sip_pvt_ptr
= iflist
; sip_pvt_ptr
; sip_pvt_ptr
= sip_pvt_ptr
->next
) {
8617 if (!strcmp(sip_pvt_ptr
->callid
, callid
)) {
8619 char *ourtag
= sip_pvt_ptr
->tag
;
8621 /* Go ahead and lock it (and its owner) before returning */
8622 ast_mutex_lock(&sip_pvt_ptr
->lock
);
8624 /* Check if tags match. If not, this is not the call we want
8625 (With a forking SIP proxy, several call legs share the
8626 call id, but have different tags)
8628 if (pedanticsipchecking
&& (strcmp(fromtag
, sip_pvt_ptr
->theirtag
) || strcmp(totag
, ourtag
)))
8632 ast_mutex_unlock(&sip_pvt_ptr
->lock
);
8636 if (option_debug
> 3 && totag
)
8637 ast_log(LOG_DEBUG
, "Matched %s call - their tag is %s Our tag is %s\n",
8638 ast_test_flag(&sip_pvt_ptr
->flags
[0], SIP_OUTGOING
) ? "OUTGOING": "INCOMING",
8639 sip_pvt_ptr
->theirtag
, sip_pvt_ptr
->tag
);
8641 /* deadlock avoidance... */
8642 while (sip_pvt_ptr
->owner
&& ast_channel_trylock(sip_pvt_ptr
->owner
)) {
8643 ast_mutex_unlock(&sip_pvt_ptr
->lock
);
8645 ast_mutex_lock(&sip_pvt_ptr
->lock
);
8650 ast_mutex_unlock(&iflock
);
8651 if (option_debug
> 3 && !sip_pvt_ptr
)
8652 ast_log(LOG_DEBUG
, "Found no match for callid %s to-tag %s from-tag %s\n", callid
, totag
, fromtag
);
8656 /*! \brief Call transfer support (the REFER method)
8657 * Extracts Refer headers into pvt dialog structure */
8658 static int get_refer_info(struct sip_pvt
*transferer
, struct sip_request
*outgoing_req
)
8661 const char *p_referred_by
= NULL
;
8662 char *h_refer_to
= NULL
;
8663 char *h_referred_by
= NULL
;
8665 const char *p_refer_to
;
8666 char *referred_by_uri
= NULL
;
8668 struct sip_request
*req
= NULL
;
8669 const char *transfer_context
= NULL
;
8670 struct sip_refer
*referdata
;
8674 referdata
= transferer
->refer
;
8677 req
= &transferer
->initreq
;
8679 p_refer_to
= get_header(req
, "Refer-To");
8680 if (ast_strlen_zero(p_refer_to
)) {
8681 ast_log(LOG_WARNING
, "Refer-To Header missing. Skipping transfer.\n");
8682 return -2; /* Syntax error */
8684 h_refer_to
= ast_strdupa(p_refer_to
);
8685 refer_to
= get_in_brackets(h_refer_to
);
8686 if (pedanticsipchecking
)
8687 ast_uri_decode(refer_to
);
8689 if (strncasecmp(refer_to
, "sip:", 4)) {
8690 ast_log(LOG_WARNING
, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to
);
8693 refer_to
+= 4; /* Skip sip: */
8695 /* Get referred by header if it exists */
8696 p_referred_by
= get_header(req
, "Referred-By");
8697 if (!ast_strlen_zero(p_referred_by
)) {
8699 h_referred_by
= ast_strdupa(p_referred_by
);
8700 if (pedanticsipchecking
)
8701 ast_uri_decode(h_referred_by
);
8703 /* Store referrer's caller ID name */
8704 ast_copy_string(referdata
->referred_by_name
, h_referred_by
, sizeof(referdata
->referred_by_name
));
8705 if ((lessthan
= strchr(referdata
->referred_by_name
, '<'))) {
8706 *(lessthan
- 1) = '\0'; /* Space */
8709 referred_by_uri
= get_in_brackets(h_referred_by
);
8710 if(strncasecmp(referred_by_uri
, "sip:", 4)) {
8711 ast_log(LOG_WARNING
, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri
);
8712 referred_by_uri
= (char *) NULL
;
8714 referred_by_uri
+= 4; /* Skip sip: */
8718 /* Check for arguments in the refer_to header */
8719 if ((ptr
= strchr(refer_to
, '?'))) { /* Search for arguments */
8721 if (!strncasecmp(ptr
, "REPLACES=", 9)) {
8722 char *to
= NULL
, *from
= NULL
;
8724 /* This is an attended transfer */
8725 referdata
->attendedtransfer
= 1;
8726 ast_copy_string(referdata
->replaces_callid
, ptr
+9, sizeof(referdata
->replaces_callid
));
8727 ast_uri_decode(referdata
->replaces_callid
);
8728 if ((ptr
= strchr(referdata
->replaces_callid
, ';'))) /* Find options */ {
8733 /* Find the different tags before we destroy the string */
8734 to
= strcasestr(ptr
, "to-tag=");
8735 from
= strcasestr(ptr
, "from-tag=");
8738 /* Grab the to header */
8741 if ((to
= strchr(ptr
, '&')))
8743 if ((to
= strchr(ptr
, ';')))
8745 ast_copy_string(referdata
->replaces_callid_totag
, ptr
, sizeof(referdata
->replaces_callid_totag
));
8750 if ((to
= strchr(ptr
, '&')))
8752 if ((to
= strchr(ptr
, ';')))
8754 ast_copy_string(referdata
->replaces_callid_fromtag
, ptr
, sizeof(referdata
->replaces_callid_fromtag
));
8757 if (option_debug
> 1) {
8758 if (!pedanticsipchecking
)
8759 ast_log(LOG_DEBUG
,"Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata
->replaces_callid
);
8761 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>" );
8766 if ((ptr
= strchr(refer_to
, '@'))) { /* Separate domain */
8770 if ((urioption
= strchr(ptr
, ';')))
8771 *urioption
++ = '\0';
8772 /* Save the domain for the dial plan */
8773 ast_copy_string(referdata
->refer_to_domain
, ptr
, sizeof(referdata
->refer_to_domain
));
8775 ast_copy_string(referdata
->refer_to_urioption
, urioption
, sizeof(referdata
->refer_to_urioption
));
8778 if ((ptr
= strchr(refer_to
, ';'))) /* Remove options */
8780 ast_copy_string(referdata
->refer_to
, refer_to
, sizeof(referdata
->refer_to
));
8782 if (referred_by_uri
) {
8783 if ((ptr
= strchr(referred_by_uri
, ';'))) /* Remove options */
8785 ast_copy_string(referdata
->referred_by
, referred_by_uri
, sizeof(referdata
->referred_by
));
8787 referdata
->referred_by
[0] = '\0';
8790 /* Determine transfer context */
8791 if (transferer
->owner
) /* Mimic behaviour in res_features.c */
8792 transfer_context
= pbx_builtin_getvar_helper(transferer
->owner
, "TRANSFER_CONTEXT");
8794 /* By default, use the context in the channel sending the REFER */
8795 if (ast_strlen_zero(transfer_context
)) {
8796 transfer_context
= S_OR(transferer
->owner
->macrocontext
,
8797 S_OR(transferer
->context
, default_context
));
8800 ast_copy_string(referdata
->refer_to_context
, transfer_context
, sizeof(referdata
->refer_to_context
));
8802 /* Either an existing extension or the parking extension */
8803 if (ast_exists_extension(NULL
, transfer_context
, refer_to
, 1, NULL
) ) {
8804 if (sip_debug_test_pvt(transferer
)) {
8805 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to
, transfer_context
, referred_by_uri
);
8807 /* We are ready to transfer to the extension */
8810 if (sip_debug_test_pvt(transferer
))
8811 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to
, transfer_context
);
8813 /* Failure, we can't find this extension */
8818 /*! \brief Call transfer support (old way, deprecated by the IETF)--*/
8819 static int get_also_info(struct sip_pvt
*p
, struct sip_request
*oreq
)
8821 char tmp
[256] = "", *c
, *a
;
8822 struct sip_request
*req
= oreq
? oreq
: &p
->initreq
;
8823 struct sip_refer
*referdata
= p
->refer
;
8824 const char *transfer_context
= NULL
;
8826 ast_copy_string(tmp
, get_header(req
, "Also"), sizeof(tmp
));
8827 c
= get_in_brackets(tmp
);
8829 if (pedanticsipchecking
)
8832 if (strncasecmp(c
, "sip:", 4)) {
8833 ast_log(LOG_WARNING
, "Huh? Not a SIP header in Also: transfer (%s)?\n", c
);
8837 if ((a
= strchr(c
, ';'))) /* Remove arguments */
8840 if ((a
= strchr(c
, '@'))) { /* Separate Domain */
8842 ast_copy_string(referdata
->refer_to_domain
, a
, sizeof(referdata
->refer_to_domain
));
8845 if (sip_debug_test_pvt(p
))
8846 ast_verbose("Looking for %s in %s\n", c
, p
->context
);
8848 if (p
->owner
) /* Mimic behaviour in res_features.c */
8849 transfer_context
= pbx_builtin_getvar_helper(p
->owner
, "TRANSFER_CONTEXT");
8851 /* By default, use the context in the channel sending the REFER */
8852 if (ast_strlen_zero(transfer_context
)) {
8853 transfer_context
= S_OR(p
->owner
->macrocontext
,
8854 S_OR(p
->context
, default_context
));
8856 if (ast_exists_extension(NULL
, transfer_context
, c
, 1, NULL
)) {
8857 /* This is a blind transfer */
8859 ast_log(LOG_DEBUG
,"SIP Bye-also transfer to Extension %s@%s \n", c
, transfer_context
);
8860 ast_copy_string(referdata
->refer_to
, c
, sizeof(referdata
->refer_to
));
8861 ast_copy_string(referdata
->referred_by
, "", sizeof(referdata
->referred_by
));
8862 ast_copy_string(referdata
->refer_contact
, "", sizeof(referdata
->refer_contact
));
8863 referdata
->refer_call
= NULL
;
8864 /* Set new context */
8865 ast_string_field_set(p
, context
, transfer_context
);
8867 } else if (ast_canmatch_extension(NULL
, p
->context
, c
, 1, NULL
)) {
8873 /*! \brief check Via: header for hostname, port and rport request/answer */
8874 static void check_via(struct sip_pvt
*p
, struct sip_request
*req
)
8879 struct ast_hostent ahp
;
8881 ast_copy_string(via
, get_header(req
, "Via"), sizeof(via
));
8883 /* Work on the leftmost value of the topmost Via header */
8884 c
= strchr(via
, ',');
8888 /* Check for rport */
8889 c
= strstr(via
, ";rport");
8890 if (c
&& (c
[6] != '=')) /* rport query, not answer */
8891 ast_set_flag(&p
->flags
[0], SIP_NAT_ROUTE
);
8893 c
= strchr(via
, ';');
8897 c
= strchr(via
, ' ');
8900 c
= ast_skip_blanks(c
+1);
8901 if (strcasecmp(via
, "SIP/2.0/UDP")) {
8902 ast_log(LOG_WARNING
, "Don't know how to respond via '%s'\n", via
);
8905 pt
= strchr(c
, ':');
8907 *pt
++ = '\0'; /* remember port pointer */
8908 hp
= ast_gethostbyname(c
, &ahp
);
8910 ast_log(LOG_WARNING
, "'%s' is not a valid host\n", c
);
8913 memset(&p
->sa
, 0, sizeof(p
->sa
));
8914 p
->sa
.sin_family
= AF_INET
;
8915 memcpy(&p
->sa
.sin_addr
, hp
->h_addr
, sizeof(p
->sa
.sin_addr
));
8916 p
->sa
.sin_port
= htons(pt
? atoi(pt
) : STANDARD_SIP_PORT
);
8918 if (sip_debug_test_pvt(p
)) {
8919 const struct sockaddr_in
*dst
= sip_real_dst(p
);
8920 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst
->sin_addr
), ntohs(dst
->sin_port
), sip_nat_mode(p
));
8925 /*! \brief Get caller id name from SIP headers */
8926 static char *get_calleridname(const char *input
, char *output
, size_t outputsize
)
8928 const char *end
= strchr(input
,'<'); /* first_bracket */
8929 const char *tmp
= strchr(input
,'"'); /* first quote */
8931 int maxbytes
= outputsize
- 1;
8933 if (!end
|| end
== input
) /* we require a part in brackets */
8936 end
--; /* move just before "<" */
8938 if (tmp
&& tmp
<= end
) {
8939 /* The quote (tmp) precedes the bracket (end+1).
8940 * Find the matching quote and return the content.
8942 end
= strchr(tmp
+1, '"');
8945 bytes
= (int) (end
- tmp
);
8946 /* protect the output buffer */
8947 if (bytes
> maxbytes
)
8949 ast_copy_string(output
, tmp
+ 1, bytes
);
8951 /* No quoted string, or it is inside brackets. */
8952 /* clear the empty characters in the begining*/
8953 input
= ast_skip_blanks(input
);
8954 /* clear the empty characters in the end */
8955 while(*end
&& *end
< 33 && end
> input
)
8958 bytes
= (int) (end
- input
) + 2;
8959 /* protect the output buffer */
8960 if (bytes
> maxbytes
)
8962 ast_copy_string(output
, input
, bytes
);
8969 /*! \brief Get caller id number from Remote-Party-ID header field
8970 * Returns true if number should be restricted (privacy setting found)
8971 * output is set to NULL if no number found
8973 static int get_rpid_num(const char *input
, char *output
, int maxlen
)
8978 start
= strchr(input
,':');
8985 /* we found "number" */
8986 ast_copy_string(output
,start
,maxlen
);
8987 output
[maxlen
-1] = '\0';
8989 end
= strchr(output
,'@');
8994 if (strstr(input
,"privacy=full") || strstr(input
,"privacy=uri"))
8995 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED
;
9001 /*! \brief Check if matching user or peer is defined
9002 Match user on From: user name and peer on IP/port
9003 This is used on first invite (not re-invites) and subscribe requests
9004 \return 0 on success, non-zero on failure
9006 static enum check_auth_result
check_user_full(struct sip_pvt
*p
, struct sip_request
*req
,
9007 int sipmethod
, char *uri
, enum xmittype reliable
,
9008 struct sockaddr_in
*sin
, struct sip_peer
**authpeer
)
9010 struct sip_user
*user
= NULL
;
9011 struct sip_peer
*peer
;
9016 enum check_auth_result res
= AUTH_SUCCESSFUL
;
9018 char calleridname
[50];
9019 int debug
=sip_debug_test_addr(sin
);
9020 struct ast_variable
*tmpvar
= NULL
, *v
= NULL
;
9021 char *uri2
= ast_strdupa(uri
);
9025 while (*t
&& *t
> 32 && *t
!= ';')
9028 ast_copy_string(from
, get_header(req
, "From"), sizeof(from
)); /* XXX bug in original code, overwrote string */
9029 if (pedanticsipchecking
)
9030 ast_uri_decode(from
);
9031 /* XXX here tries to map the username for invite things */
9032 memset(calleridname
, 0, sizeof(calleridname
));
9033 get_calleridname(from
, calleridname
, sizeof(calleridname
));
9034 if (calleridname
[0])
9035 ast_string_field_set(p
, cid_name
, calleridname
);
9037 rpid
= get_header(req
, "Remote-Party-ID");
9038 memset(rpid_num
, 0, sizeof(rpid_num
));
9039 if (!ast_strlen_zero(rpid
))
9040 p
->callingpres
= get_rpid_num(rpid
, rpid_num
, sizeof(rpid_num
));
9042 of
= get_in_brackets(from
);
9043 if (ast_strlen_zero(p
->exten
)) {
9045 if (!strncasecmp(t
, "sip:", 4))
9047 ast_string_field_set(p
, exten
, t
);
9048 t
= strchr(p
->exten
, '@');
9051 if (ast_strlen_zero(p
->our_contact
))
9054 /* save the URI part of the From header */
9055 ast_string_field_set(p
, from
, of
);
9056 if (strncasecmp(of
, "sip:", 4)) {
9057 ast_log(LOG_NOTICE
, "From address missing 'sip:', using it anyway\n");
9060 /* Get just the username part */
9061 if ((c
= strchr(of
, '@'))) {
9064 if ((c
= strchr(of
, ':')))
9066 tmp
= ast_strdupa(of
);
9067 /* We need to be able to handle auth-headers looking like
9068 <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
9070 tmp
= strsep(&tmp
, ";");
9071 if (ast_is_shrinkable_phonenumber(tmp
))
9072 ast_shrink_phone_number(tmp
);
9073 ast_string_field_set(p
, cid_num
, tmp
);
9075 if (ast_strlen_zero(of
))
9076 return AUTH_SUCCESSFUL
;
9078 if (!authpeer
) /* If we are looking for a peer, don't check the user objects (or realtime) */
9079 user
= find_user(of
, 1);
9081 /* Find user based on user name in the from header */
9082 if (user
&& ast_apply_ha(user
->ha
, sin
)) {
9083 ast_copy_flags(&p
->flags
[0], &user
->flags
[0], SIP_FLAGS_TO_COPY
);
9084 ast_copy_flags(&p
->flags
[1], &user
->flags
[1], SIP_PAGE2_FLAGS_TO_COPY
);
9085 /* copy channel vars */
9086 for (v
= user
->chanvars
; v
; v
= v
->next
) {
9087 if ((tmpvar
= ast_variable_new(v
->name
, v
->value
))) {
9088 tmpvar
->next
= p
->chanvars
;
9089 p
->chanvars
= tmpvar
;
9092 p
->prefs
= user
->prefs
;
9093 /* Set Frame packetization */
9095 ast_rtp_codec_setpref(p
->rtp
, &p
->prefs
);
9096 p
->autoframing
= user
->autoframing
;
9098 /* replace callerid if rpid found, and not restricted */
9099 if (!ast_strlen_zero(rpid_num
) && ast_test_flag(&p
->flags
[0], SIP_TRUSTRPID
)) {
9102 ast_string_field_set(p
, cid_name
, calleridname
);
9103 tmp
= ast_strdupa(rpid_num
);
9104 if (ast_is_shrinkable_phonenumber(tmp
))
9105 ast_shrink_phone_number(tmp
);
9106 ast_string_field_set(p
, cid_num
, tmp
);
9109 do_setnat(p
, ast_test_flag(&p
->flags
[0], SIP_NAT_ROUTE
) );
9111 if (!(res
= check_auth(p
, req
, user
->name
, user
->secret
, user
->md5secret
, sipmethod
, uri2
, reliable
, ast_test_flag(req
, SIP_PKT_IGNORE
)))) {
9112 sip_cancel_destroy(p
);
9113 ast_copy_flags(&p
->flags
[0], &user
->flags
[0], SIP_FLAGS_TO_COPY
);
9114 ast_copy_flags(&p
->flags
[1], &user
->flags
[1], SIP_PAGE2_FLAGS_TO_COPY
);
9115 /* Copy SIP extensions profile from INVITE */
9117 user
->sipoptions
= p
->sipoptions
;
9119 /* If we have a call limit, set flag */
9120 if (user
->call_limit
)
9121 ast_set_flag(&p
->flags
[0], SIP_CALL_LIMIT
);
9122 if (!ast_strlen_zero(user
->context
))
9123 ast_string_field_set(p
, context
, user
->context
);
9124 if (!ast_strlen_zero(user
->cid_num
) && !ast_strlen_zero(p
->cid_num
)) {
9125 char *tmp
= ast_strdupa(user
->cid_num
);
9126 if (ast_is_shrinkable_phonenumber(tmp
))
9127 ast_shrink_phone_number(tmp
);
9128 ast_string_field_set(p
, cid_num
, tmp
);
9130 if (!ast_strlen_zero(user
->cid_name
) && !ast_strlen_zero(p
->cid_num
))
9131 ast_string_field_set(p
, cid_name
, user
->cid_name
);
9132 ast_string_field_set(p
, username
, user
->name
);
9133 ast_string_field_set(p
, peername
, user
->name
);
9134 ast_string_field_set(p
, peersecret
, user
->secret
);
9135 ast_string_field_set(p
, peermd5secret
, user
->md5secret
);
9136 ast_string_field_set(p
, subscribecontext
, user
->subscribecontext
);
9137 ast_string_field_set(p
, accountcode
, user
->accountcode
);
9138 ast_string_field_set(p
, language
, user
->language
);
9139 ast_string_field_set(p
, mohsuggest
, user
->mohsuggest
);
9140 ast_string_field_set(p
, mohinterpret
, user
->mohinterpret
);
9141 p
->allowtransfer
= user
->allowtransfer
;
9142 p
->amaflags
= user
->amaflags
;
9143 p
->callgroup
= user
->callgroup
;
9144 p
->pickupgroup
= user
->pickupgroup
;
9145 if (user
->callingpres
) /* User callingpres setting will override RPID header */
9146 p
->callingpres
= user
->callingpres
;
9148 /* Set default codec settings for this call */
9149 p
->capability
= user
->capability
; /* User codec choice */
9150 p
->jointcapability
= user
->capability
; /* Our codecs */
9151 if (p
->peercapability
) /* AND with peer's codecs */
9152 p
->jointcapability
&= p
->peercapability
;
9153 if ((ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_RFC2833
) ||
9154 (ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_AUTO
))
9155 p
->noncodeccapability
|= AST_RTP_DTMF
;
9157 p
->noncodeccapability
&= ~AST_RTP_DTMF
;
9158 p
->jointnoncodeccapability
= p
->noncodeccapability
;
9159 if (p
->t38
.peercapability
)
9160 p
->t38
.jointcapability
&= p
->t38
.peercapability
;
9161 p
->maxcallbitrate
= user
->maxcallbitrate
;
9162 /* If we do not support video, remove video from call structure */
9163 if ((!ast_test_flag(&p
->flags
[1], SIP_PAGE2_VIDEOSUPPORT
) || !(p
->capability
& AST_FORMAT_VIDEO_MASK
)) && p
->vrtp
) {
9164 ast_rtp_destroy(p
->vrtp
);
9169 ast_verbose("Found user '%s'\n", user
->name
);
9172 if (!authpeer
&& debug
)
9173 ast_verbose("Found user '%s', but fails host access\n", user
->name
);
9174 ASTOBJ_UNREF(user
,sip_destroy_user
);
9180 /* If we didn't find a user match, check for peers */
9181 if (sipmethod
== SIP_SUBSCRIBE
)
9182 /* For subscribes, match on peer name only */
9183 peer
= find_peer(of
, NULL
, 1);
9185 /* Look for peer based on the IP address we received data from */
9186 /* If peer is registered from this IP address or have this as a default
9187 IP address, this call is from the peer
9189 peer
= find_peer(NULL
, &p
->recv
, 1);
9192 /* Set Frame packetization */
9194 ast_rtp_codec_setpref(p
->rtp
, &peer
->prefs
);
9195 p
->autoframing
= peer
->autoframing
;
9198 ast_verbose("Found peer '%s'\n", peer
->name
);
9201 ast_copy_flags(&p
->flags
[0], &peer
->flags
[0], SIP_FLAGS_TO_COPY
);
9202 ast_copy_flags(&p
->flags
[1], &peer
->flags
[1], SIP_PAGE2_FLAGS_TO_COPY
);
9204 /* Copy SIP extensions profile to peer */
9206 peer
->sipoptions
= p
->sipoptions
;
9208 /* replace callerid if rpid found, and not restricted */
9209 if (!ast_strlen_zero(rpid_num
) && ast_test_flag(&p
->flags
[0], SIP_TRUSTRPID
)) {
9210 char *tmp
= ast_strdupa(rpid_num
);
9212 ast_string_field_set(p
, cid_name
, calleridname
);
9213 if (ast_is_shrinkable_phonenumber(tmp
))
9214 ast_shrink_phone_number(tmp
);
9215 ast_string_field_set(p
, cid_num
, tmp
);
9217 do_setnat(p
, ast_test_flag(&p
->flags
[0], SIP_NAT_ROUTE
));
9219 ast_string_field_set(p
, peersecret
, peer
->secret
);
9220 ast_string_field_set(p
, peermd5secret
, peer
->md5secret
);
9221 ast_string_field_set(p
, subscribecontext
, peer
->subscribecontext
);
9222 ast_string_field_set(p
, mohinterpret
, peer
->mohinterpret
);
9223 ast_string_field_set(p
, mohsuggest
, peer
->mohsuggest
);
9224 if (peer
->callingpres
) /* Peer calling pres setting will override RPID */
9225 p
->callingpres
= peer
->callingpres
;
9226 if (peer
->maxms
&& peer
->lastms
)
9227 p
->timer_t1
= peer
->lastms
;
9228 if (ast_test_flag(&peer
->flags
[0], SIP_INSECURE_INVITE
)) {
9229 /* Pretend there is no required authentication */
9230 ast_string_field_free(p
, peersecret
);
9231 ast_string_field_free(p
, peermd5secret
);
9233 if (!(res
= check_auth(p
, req
, peer
->name
, p
->peersecret
, p
->peermd5secret
, sipmethod
, uri2
, reliable
, ast_test_flag(req
, SIP_PKT_IGNORE
)))) {
9234 ast_copy_flags(&p
->flags
[0], &peer
->flags
[0], SIP_FLAGS_TO_COPY
);
9235 ast_copy_flags(&p
->flags
[1], &peer
->flags
[1], SIP_PAGE2_FLAGS_TO_COPY
);
9236 /* If we have a call limit, set flag */
9237 if (peer
->call_limit
)
9238 ast_set_flag(&p
->flags
[0], SIP_CALL_LIMIT
);
9239 ast_string_field_set(p
, peername
, peer
->name
);
9240 ast_string_field_set(p
, authname
, peer
->name
);
9242 /* copy channel vars */
9243 for (v
= peer
->chanvars
; v
; v
= v
->next
) {
9244 if ((tmpvar
= ast_variable_new(v
->name
, v
->value
))) {
9245 tmpvar
->next
= p
->chanvars
;
9246 p
->chanvars
= tmpvar
;
9250 (*authpeer
) = ASTOBJ_REF(peer
); /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
9253 if (!ast_strlen_zero(peer
->username
)) {
9254 ast_string_field_set(p
, username
, peer
->username
);
9255 /* Use the default username for authentication on outbound calls */
9256 /* XXX this takes the name from the caller... can we override ? */
9257 ast_string_field_set(p
, authname
, peer
->username
);
9259 if (!ast_strlen_zero(peer
->cid_num
) && !ast_strlen_zero(p
->cid_num
)) {
9260 char *tmp
= ast_strdupa(peer
->cid_num
);
9261 if (ast_is_shrinkable_phonenumber(tmp
))
9262 ast_shrink_phone_number(tmp
);
9263 ast_string_field_set(p
, cid_num
, tmp
);
9265 if (!ast_strlen_zero(peer
->cid_name
) && !ast_strlen_zero(p
->cid_name
))
9266 ast_string_field_set(p
, cid_name
, peer
->cid_name
);
9267 ast_string_field_set(p
, fullcontact
, peer
->fullcontact
);
9268 if (!ast_strlen_zero(peer
->context
))
9269 ast_string_field_set(p
, context
, peer
->context
);
9270 ast_string_field_set(p
, peersecret
, peer
->secret
);
9271 ast_string_field_set(p
, peermd5secret
, peer
->md5secret
);
9272 ast_string_field_set(p
, language
, peer
->language
);
9273 ast_string_field_set(p
, accountcode
, peer
->accountcode
);
9274 p
->amaflags
= peer
->amaflags
;
9275 p
->callgroup
= peer
->callgroup
;
9276 p
->pickupgroup
= peer
->pickupgroup
;
9277 p
->capability
= peer
->capability
;
9278 p
->prefs
= peer
->prefs
;
9279 p
->jointcapability
= peer
->capability
;
9280 if (p
->peercapability
)
9281 p
->jointcapability
&= p
->peercapability
;
9282 p
->maxcallbitrate
= peer
->maxcallbitrate
;
9283 if ((!ast_test_flag(&p
->flags
[1], SIP_PAGE2_VIDEOSUPPORT
) || !(p
->capability
& AST_FORMAT_VIDEO_MASK
)) && p
->vrtp
) {
9284 ast_rtp_destroy(p
->vrtp
);
9287 if ((ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_RFC2833
) ||
9288 (ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_AUTO
))
9289 p
->noncodeccapability
|= AST_RTP_DTMF
;
9291 p
->noncodeccapability
&= ~AST_RTP_DTMF
;
9292 p
->jointnoncodeccapability
= p
->noncodeccapability
;
9293 if (p
->t38
.peercapability
)
9294 p
->t38
.jointcapability
&= p
->t38
.peercapability
;
9296 ASTOBJ_UNREF(peer
, sip_destroy_peer
);
9299 ast_verbose("Found no matching peer or user for '%s:%d'\n", ast_inet_ntoa(p
->recv
.sin_addr
), ntohs(p
->recv
.sin_port
));
9301 /* do we allow guests? */
9302 if (!global_allowguest
) {
9303 if (global_alwaysauthreject
)
9304 res
= AUTH_FAKE_AUTH
; /* reject with fake authorization request */
9306 res
= AUTH_SECRET_FAILED
; /* we don't want any guests, authentication will fail */
9313 ASTOBJ_UNREF(user
, sip_destroy_user
);
9317 /*! \brief Find user
9318 If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
9320 static int check_user(struct sip_pvt
*p
, struct sip_request
*req
, int sipmethod
, char *uri
, enum xmittype reliable
, struct sockaddr_in
*sin
)
9322 return check_user_full(p
, req
, sipmethod
, uri
, reliable
, sin
, NULL
);
9325 /*! \brief Get text out of a SIP MESSAGE packet */
9326 static int get_msg_text(char *buf
, int len
, struct sip_request
*req
)
9332 y
= len
- strlen(buf
) - 5;
9335 for (x
=0;x
<req
->lines
;x
++) {
9336 strncat(buf
, req
->line
[x
], y
); /* safe */
9337 y
-= strlen(req
->line
[x
]) + 1;
9341 strcat(buf
, "\n"); /* safe */
9347 /*! \brief Receive SIP MESSAGE method messages
9348 \note We only handle messages within current calls currently
9349 Reference: RFC 3428 */
9350 static void receive_message(struct sip_pvt
*p
, struct sip_request
*req
)
9354 const char *content_type
= get_header(req
, "Content-Type");
9356 if (strcmp(content_type
, "text/plain")) { /* No text/plain attachment */
9357 transmit_response(p
, "415 Unsupported Media Type", req
); /* Good enough, or? */
9358 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
9362 if (get_msg_text(buf
, sizeof(buf
), req
)) {
9363 ast_log(LOG_WARNING
, "Unable to retrieve text from %s\n", p
->callid
);
9364 transmit_response(p
, "202 Accepted", req
);
9365 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
9370 if (sip_debug_test_pvt(p
))
9371 ast_verbose("Message received: '%s'\n", buf
);
9372 memset(&f
, 0, sizeof(f
));
9373 f
.frametype
= AST_FRAME_TEXT
;
9377 f
.datalen
= strlen(buf
);
9378 ast_queue_frame(p
->owner
, &f
);
9379 transmit_response(p
, "202 Accepted", req
); /* We respond 202 accepted, since we relay the message */
9380 } else { /* Message outside of a call, we do not support that */
9381 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
);
9382 transmit_response(p
, "405 Method Not Allowed", req
); /* Good enough, or? */
9384 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
9388 /*! \brief CLI Command to show calls within limits set by call_limit */
9389 static int sip_show_inuse(int fd
, int argc
, char *argv
[])
9391 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
9392 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
9395 int showall
= FALSE
;
9398 return RESULT_SHOWUSAGE
;
9400 if (argc
== 4 && !strcmp(argv
[3],"all"))
9403 ast_cli(fd
, FORMAT
, "* User name", "In use", "Limit");
9404 ASTOBJ_CONTAINER_TRAVERSE(&userl
, 1, do {
9405 ASTOBJ_RDLOCK(iterator
);
9406 if (iterator
->call_limit
)
9407 snprintf(ilimits
, sizeof(ilimits
), "%d", iterator
->call_limit
);
9409 ast_copy_string(ilimits
, "N/A", sizeof(ilimits
));
9410 snprintf(iused
, sizeof(iused
), "%d", iterator
->inUse
);
9411 if (showall
|| iterator
->call_limit
)
9412 ast_cli(fd
, FORMAT2
, iterator
->name
, iused
, ilimits
);
9413 ASTOBJ_UNLOCK(iterator
);
9416 ast_cli(fd
, FORMAT
, "* Peer name", "In use", "Limit");
9418 ASTOBJ_CONTAINER_TRAVERSE(&peerl
, 1, do {
9419 ASTOBJ_RDLOCK(iterator
);
9420 if (iterator
->call_limit
)
9421 snprintf(ilimits
, sizeof(ilimits
), "%d", iterator
->call_limit
);
9423 ast_copy_string(ilimits
, "N/A", sizeof(ilimits
));
9424 snprintf(iused
, sizeof(iused
), "%d/%d", iterator
->inUse
, iterator
->inRinging
);
9425 if (showall
|| iterator
->call_limit
)
9426 ast_cli(fd
, FORMAT2
, iterator
->name
, iused
, ilimits
);
9427 ASTOBJ_UNLOCK(iterator
);
9430 return RESULT_SUCCESS
;
9435 /*! \brief Convert transfer mode to text string */
9436 static char *transfermode2str(enum transfermodes mode
)
9438 if (mode
== TRANSFER_OPENFORALL
)
9440 else if (mode
== TRANSFER_CLOSED
)
9445 /*! \brief Convert NAT setting to text string */
9446 static char *nat2str(int nat
)
9453 case SIP_NAT_ALWAYS
:
9455 case SIP_NAT_RFC3581
:
9462 /*! \brief Report Peer status in character string
9463 * \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
9465 static int peer_status(struct sip_peer
*peer
, char *status
, int statuslen
)
9469 if (peer
->lastms
< 0) {
9470 ast_copy_string(status
, "UNREACHABLE", statuslen
);
9471 } else if (peer
->lastms
> peer
->maxms
) {
9472 snprintf(status
, statuslen
, "LAGGED (%d ms)", peer
->lastms
);
9474 } else if (peer
->lastms
) {
9475 snprintf(status
, statuslen
, "OK (%d ms)", peer
->lastms
);
9478 ast_copy_string(status
, "UNKNOWN", statuslen
);
9481 ast_copy_string(status
, "Unmonitored", statuslen
);
9482 /* Checking if port is 0 */
9488 /*! \brief CLI Command 'SIP Show Users' */
9489 static int sip_show_users(int fd
, int argc
, char *argv
[])
9492 int havepattern
= FALSE
;
9494 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
9498 if (!strcasecmp(argv
[3], "like")) {
9499 if (regcomp(®exbuf
, argv
[4], REG_EXTENDED
| REG_NOSUB
))
9500 return RESULT_SHOWUSAGE
;
9503 return RESULT_SHOWUSAGE
;
9507 return RESULT_SHOWUSAGE
;
9510 ast_cli(fd
, FORMAT
, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
9511 ASTOBJ_CONTAINER_TRAVERSE(&userl
, 1, do {
9512 ASTOBJ_RDLOCK(iterator
);
9514 if (havepattern
&& regexec(®exbuf
, iterator
->name
, 0, NULL
, 0)) {
9515 ASTOBJ_UNLOCK(iterator
);
9519 ast_cli(fd
, FORMAT
, iterator
->name
,
9521 iterator
->accountcode
,
9523 iterator
->ha
? "Yes" : "No",
9524 nat2str(ast_test_flag(&iterator
->flags
[0], SIP_NAT
)));
9525 ASTOBJ_UNLOCK(iterator
);
9532 return RESULT_SUCCESS
;
9536 static char mandescr_show_peers
[] =
9537 "Description: Lists SIP peers in text format with details on current status.\n"
9539 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
9541 /*! \brief Show SIP peers in the manager API */
9542 /* Inspired from chan_iax2 */
9543 static int manager_sip_show_peers(struct mansession
*s
, const struct message
*m
)
9545 const char *id
= astman_get_header(m
,"ActionID");
9546 const char *a
[] = {"sip", "show", "peers"};
9547 char idtext
[256] = "";
9550 if (!ast_strlen_zero(id
))
9551 snprintf(idtext
, sizeof(idtext
), "ActionID: %s\r\n", id
);
9553 astman_send_ack(s
, m
, "Peer status list will follow");
9554 /* List the peers in separate manager events */
9555 _sip_show_peers(-1, &total
, s
, m
, 3, a
);
9556 /* Send final confirmation */
9558 "Event: PeerlistComplete\r\n"
9561 "\r\n", total
, idtext
);
9565 /*! \brief CLI Show Peers command */
9566 static int sip_show_peers(int fd
, int argc
, char *argv
[])
9568 return _sip_show_peers(fd
, NULL
, NULL
, NULL
, argc
, (const char **) argv
);
9571 /*! \brief _sip_show_peers: Execute sip show peers command */
9572 static int _sip_show_peers(int fd
, int *total
, struct mansession
*s
, const struct message
*m
, int argc
, const char *argv
[])
9575 int havepattern
= FALSE
;
9577 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %-10s\n"
9578 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %-10s\n"
9581 int total_peers
= 0;
9582 int peers_mon_online
= 0;
9583 int peers_mon_offline
= 0;
9584 int peers_unmon_offline
= 0;
9585 int peers_unmon_online
= 0;
9587 char idtext
[256] = "";
9590 realtimepeers
= ast_check_realtime("sippeers");
9592 if (s
) { /* Manager - get ActionID */
9593 id
= astman_get_header(m
,"ActionID");
9594 if (!ast_strlen_zero(id
))
9595 snprintf(idtext
, sizeof(idtext
), "ActionID: %s\r\n", id
);
9600 if (!strcasecmp(argv
[3], "like")) {
9601 if (regcomp(®exbuf
, argv
[4], REG_EXTENDED
| REG_NOSUB
))
9602 return RESULT_SHOWUSAGE
;
9605 return RESULT_SHOWUSAGE
;
9609 return RESULT_SHOWUSAGE
;
9612 if (!s
) /* Normal list */
9613 ast_cli(fd
, FORMAT2
, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers
? "Realtime" : ""));
9615 ASTOBJ_CONTAINER_TRAVERSE(&peerl
, 1, do {
9616 char status
[20] = "";
9620 ASTOBJ_RDLOCK(iterator
);
9622 if (havepattern
&& regexec(®exbuf
, iterator
->name
, 0, NULL
, 0)) {
9623 ASTOBJ_UNLOCK(iterator
);
9627 if (!ast_strlen_zero(iterator
->username
) && !s
)
9628 snprintf(name
, sizeof(name
), "%s/%s", iterator
->name
, iterator
->username
);
9630 ast_copy_string(name
, iterator
->name
, sizeof(name
));
9632 pstatus
= peer_status(iterator
, status
, sizeof(status
));
9635 else if (pstatus
== 0)
9636 peers_mon_offline
++;
9638 if (iterator
->addr
.sin_port
== 0)
9639 peers_unmon_offline
++;
9641 peers_unmon_online
++;
9644 snprintf(srch
, sizeof(srch
), FORMAT
, name
,
9645 iterator
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(iterator
->addr
.sin_addr
) : "(Unspecified)",
9646 ast_test_flag(&iterator
->flags
[1], SIP_PAGE2_DYNAMIC
) ? " D " : " ", /* Dynamic or not? */
9647 ast_test_flag(&iterator
->flags
[0], SIP_NAT_ROUTE
) ? " N " : " ", /* NAT=yes? */
9648 iterator
->ha
? " A " : " ", /* permit/deny */
9649 ntohs(iterator
->addr
.sin_port
), status
,
9650 realtimepeers
? (ast_test_flag(&iterator
->flags
[0], SIP_REALTIME
) ? "Cached RT":"") : "");
9652 if (!s
) {/* Normal CLI list */
9653 ast_cli(fd
, FORMAT
, name
,
9654 iterator
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(iterator
->addr
.sin_addr
) : "(Unspecified)",
9655 ast_test_flag(&iterator
->flags
[1], SIP_PAGE2_DYNAMIC
) ? " D " : " ", /* Dynamic or not? */
9656 ast_test_flag(&iterator
->flags
[0], SIP_NAT_ROUTE
) ? " N " : " ", /* NAT=yes? */
9657 iterator
->ha
? " A " : " ", /* permit/deny */
9659 ntohs(iterator
->addr
.sin_port
), status
,
9660 realtimepeers
? (ast_test_flag(&iterator
->flags
[0], SIP_REALTIME
) ? "Cached RT":"") : "");
9661 } else { /* Manager format */
9662 /* The names here need to be the same as other channels */
9664 "Event: PeerEntry\r\n%s"
9665 "Channeltype: SIP\r\n"
9666 "ObjectName: %s\r\n"
9667 "ChanObjectType: peer\r\n" /* "peer" or "user" */
9671 "Natsupport: %s\r\n"
9672 "VideoSupport: %s\r\n"
9675 "RealtimeDevice: %s\r\n\r\n",
9678 iterator
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(iterator
->addr
.sin_addr
) : "-none-",
9679 ntohs(iterator
->addr
.sin_port
),
9680 ast_test_flag(&iterator
->flags
[1], SIP_PAGE2_DYNAMIC
) ? "yes" : "no", /* Dynamic or not? */
9681 ast_test_flag(&iterator
->flags
[0], SIP_NAT_ROUTE
) ? "yes" : "no", /* NAT=yes? */
9682 ast_test_flag(&iterator
->flags
[1], SIP_PAGE2_VIDEOSUPPORT
) ? "yes" : "no", /* VIDEOSUPPORT=yes? */
9683 iterator
->ha
? "yes" : "no", /* permit/deny */
9685 realtimepeers
? (ast_test_flag(&iterator
->flags
[0], SIP_REALTIME
) ? "yes":"no") : "no");
9688 ASTOBJ_UNLOCK(iterator
);
9694 ast_cli(fd
, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
9695 total_peers
, peers_mon_online
, peers_mon_offline
, peers_unmon_online
, peers_unmon_offline
);
9701 *total
= total_peers
;
9704 return RESULT_SUCCESS
;
9709 /*! \brief List all allocated SIP Objects (realtime or static) */
9710 static int sip_show_objects(int fd
, int argc
, char *argv
[])
9714 return RESULT_SHOWUSAGE
;
9715 ast_cli(fd
, "-= User objects: %d static, %d realtime =-\n\n", suserobjs
, ruserobjs
);
9716 ASTOBJ_CONTAINER_DUMP(fd
, tmp
, sizeof(tmp
), &userl
);
9717 ast_cli(fd
, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs
, rpeerobjs
, apeerobjs
);
9718 ASTOBJ_CONTAINER_DUMP(fd
, tmp
, sizeof(tmp
), &peerl
);
9719 ast_cli(fd
, "-= Registry objects: %d =-\n\n", regobjs
);
9720 ASTOBJ_CONTAINER_DUMP(fd
, tmp
, sizeof(tmp
), ®l
);
9721 return RESULT_SUCCESS
;
9723 /*! \brief Print call group and pickup group */
9724 static void print_group(int fd
, ast_group_t group
, int crlf
)
9727 ast_cli(fd
, crlf
? "%s\r\n" : "%s\n", ast_print_group(buf
, sizeof(buf
), group
) );
9730 /*! \brief Convert DTMF mode to printable string */
9731 static const char *dtmfmode2str(int mode
)
9734 case SIP_DTMF_RFC2833
:
9738 case SIP_DTMF_INBAND
:
9746 /*! \brief Convert Insecure setting to printable string */
9747 static const char *insecure2str(int port
, int invite
)
9750 return "port,invite";
9759 /*! \brief Destroy disused contexts between reloads
9760 Only used in reload_config so the code for regcontext doesn't get ugly
9762 static void cleanup_stale_contexts(char *new, char *old
)
9764 char *oldcontext
, *newcontext
, *stalecontext
, *stringp
, newlist
[AST_MAX_CONTEXT
];
9766 while ((oldcontext
= strsep(&old
, "&"))) {
9767 stalecontext
= '\0';
9768 ast_copy_string(newlist
, new, sizeof(newlist
));
9770 while ((newcontext
= strsep(&stringp
, "&"))) {
9771 if (strcmp(newcontext
, oldcontext
) == 0) {
9772 /* This is not the context you're looking for */
9773 stalecontext
= '\0';
9775 } else if (strcmp(newcontext
, oldcontext
)) {
9776 stalecontext
= oldcontext
;
9781 ast_context_destroy(ast_context_find(stalecontext
), "SIP");
9785 /*! \brief Remove temporary realtime objects from memory (CLI) */
9786 static int sip_prune_realtime(int fd
, int argc
, char *argv
[])
9788 struct sip_peer
*peer
;
9789 struct sip_user
*user
;
9790 int pruneuser
= FALSE
;
9791 int prunepeer
= FALSE
;
9798 if (!strcasecmp(argv
[3], "user"))
9799 return RESULT_SHOWUSAGE
;
9800 if (!strcasecmp(argv
[3], "peer"))
9801 return RESULT_SHOWUSAGE
;
9802 if (!strcasecmp(argv
[3], "like"))
9803 return RESULT_SHOWUSAGE
;
9804 if (!strcasecmp(argv
[3], "all")) {
9806 pruneuser
= prunepeer
= TRUE
;
9808 pruneuser
= prunepeer
= TRUE
;
9813 if (!strcasecmp(argv
[4], "like"))
9814 return RESULT_SHOWUSAGE
;
9815 if (!strcasecmp(argv
[3], "all"))
9816 return RESULT_SHOWUSAGE
;
9817 if (!strcasecmp(argv
[3], "like")) {
9820 pruneuser
= prunepeer
= TRUE
;
9821 } else if (!strcasecmp(argv
[3], "user")) {
9823 if (!strcasecmp(argv
[4], "all"))
9827 } else if (!strcasecmp(argv
[3], "peer")) {
9829 if (!strcasecmp(argv
[4], "all"))
9834 return RESULT_SHOWUSAGE
;
9837 if (strcasecmp(argv
[4], "like"))
9838 return RESULT_SHOWUSAGE
;
9839 if (!strcasecmp(argv
[3], "user")) {
9842 } else if (!strcasecmp(argv
[3], "peer")) {
9846 return RESULT_SHOWUSAGE
;
9849 return RESULT_SHOWUSAGE
;
9852 if (multi
&& name
) {
9853 if (regcomp(®exbuf
, name
, REG_EXTENDED
| REG_NOSUB
))
9854 return RESULT_SHOWUSAGE
;
9861 ASTOBJ_CONTAINER_WRLOCK(&peerl
);
9862 ASTOBJ_CONTAINER_TRAVERSE(&peerl
, 1, do {
9863 ASTOBJ_RDLOCK(iterator
);
9864 if (name
&& regexec(®exbuf
, iterator
->name
, 0, NULL
, 0)) {
9865 ASTOBJ_UNLOCK(iterator
);
9868 if (ast_test_flag(&iterator
->flags
[1], SIP_PAGE2_RTCACHEFRIENDS
)) {
9869 ASTOBJ_MARK(iterator
);
9872 ASTOBJ_UNLOCK(iterator
);
9875 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl
, sip_destroy_peer
);
9876 ast_cli(fd
, "%d peers pruned.\n", pruned
);
9878 ast_cli(fd
, "No peers found to prune.\n");
9879 ASTOBJ_CONTAINER_UNLOCK(&peerl
);
9884 ASTOBJ_CONTAINER_WRLOCK(&userl
);
9885 ASTOBJ_CONTAINER_TRAVERSE(&userl
, 1, do {
9886 ASTOBJ_RDLOCK(iterator
);
9887 if (name
&& regexec(®exbuf
, iterator
->name
, 0, NULL
, 0)) {
9888 ASTOBJ_UNLOCK(iterator
);
9891 if (ast_test_flag(&iterator
->flags
[1], SIP_PAGE2_RTCACHEFRIENDS
)) {
9892 ASTOBJ_MARK(iterator
);
9895 ASTOBJ_UNLOCK(iterator
);
9898 ASTOBJ_CONTAINER_PRUNE_MARKED(&userl
, sip_destroy_user
);
9899 ast_cli(fd
, "%d users pruned.\n", pruned
);
9901 ast_cli(fd
, "No users found to prune.\n");
9902 ASTOBJ_CONTAINER_UNLOCK(&userl
);
9906 if ((peer
= ASTOBJ_CONTAINER_FIND_UNLINK(&peerl
, name
))) {
9907 if (!ast_test_flag(&peer
->flags
[1], SIP_PAGE2_RTCACHEFRIENDS
)) {
9908 ast_cli(fd
, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name
);
9909 ASTOBJ_CONTAINER_LINK(&peerl
, peer
);
9911 ast_cli(fd
, "Peer '%s' pruned.\n", name
);
9912 ASTOBJ_UNREF(peer
, sip_destroy_peer
);
9914 ast_cli(fd
, "Peer '%s' not found.\n", name
);
9917 if ((user
= ASTOBJ_CONTAINER_FIND_UNLINK(&userl
, name
))) {
9918 if (!ast_test_flag(&user
->flags
[1], SIP_PAGE2_RTCACHEFRIENDS
)) {
9919 ast_cli(fd
, "User '%s' is not a Realtime user, cannot be pruned.\n", name
);
9920 ASTOBJ_CONTAINER_LINK(&userl
, user
);
9922 ast_cli(fd
, "User '%s' pruned.\n", name
);
9923 ASTOBJ_UNREF(user
, sip_destroy_user
);
9925 ast_cli(fd
, "User '%s' not found.\n", name
);
9929 return RESULT_SUCCESS
;
9932 /*! \brief Print codec list from preference to CLI/manager */
9933 static void print_codec_to_cli(int fd
, struct ast_codec_pref
*pref
)
9937 for(x
= 0; x
< 32 ; x
++) {
9938 codec
= ast_codec_pref_index(pref
, x
);
9941 ast_cli(fd
, "%s", ast_getformatname(codec
));
9942 ast_cli(fd
, ":%d", pref
->framing
[x
]);
9943 if (x
< 31 && ast_codec_pref_index(pref
, x
+ 1))
9947 ast_cli(fd
, "none");
9950 /*! \brief Print domain mode to cli */
9951 static const char *domain_mode_to_text(const enum domain_mode mode
)
9954 case SIP_DOMAIN_AUTO
:
9955 return "[Automatic]";
9956 case SIP_DOMAIN_CONFIG
:
9957 return "[Configured]";
9963 /*! \brief CLI command to list local domains */
9964 static int sip_show_domains(int fd
, int argc
, char *argv
[])
9967 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
9969 if (AST_LIST_EMPTY(&domain_list
)) {
9970 ast_cli(fd
, "SIP Domain support not enabled.\n\n");
9971 return RESULT_SUCCESS
;
9973 ast_cli(fd
, FORMAT
, "Our local SIP domains:", "Context", "Set by");
9974 AST_LIST_LOCK(&domain_list
);
9975 AST_LIST_TRAVERSE(&domain_list
, d
, list
)
9976 ast_cli(fd
, FORMAT
, d
->domain
, S_OR(d
->context
, "(default)"),
9977 domain_mode_to_text(d
->mode
));
9978 AST_LIST_UNLOCK(&domain_list
);
9980 return RESULT_SUCCESS
;
9985 static char mandescr_show_peer
[] =
9986 "Description: Show one SIP peer with details on current status.\n"
9988 " Peer: <name> The peer name you want to check.\n"
9989 " ActionID: <id> Optional action ID for this AMI transaction.\n";
9991 /*! \brief Show SIP peers in the manager API */
9992 static int manager_sip_show_peer(struct mansession
*s
, const struct message
*m
)
9998 peer
= astman_get_header(m
,"Peer");
9999 if (ast_strlen_zero(peer
)) {
10000 astman_send_error(s
, m
, "Peer: <name> missing.\n");
10008 ret
= _sip_show_peer(1, -1, s
, m
, 4, a
);
10009 astman_append(s
, "\r\n\r\n" );
10015 /*! \brief Show one peer in detail */
10016 static int sip_show_peer(int fd
, int argc
, char *argv
[])
10018 return _sip_show_peer(0, fd
, NULL
, NULL
, argc
, (const char **) argv
);
10021 /*! \brief Show one peer in detail (main function) */
10022 static int _sip_show_peer(int type
, int fd
, struct mansession
*s
, const struct message
*m
, int argc
, const char *argv
[])
10024 char status
[30] = "";
10026 struct sip_peer
*peer
;
10027 char codec_buf
[512];
10028 struct ast_codec_pref
*pref
;
10029 struct ast_variable
*v
;
10030 struct sip_auth
*auth
;
10031 int x
= 0, codec
= 0, load_realtime
;
10034 realtimepeers
= ast_check_realtime("sippeers");
10037 return RESULT_SHOWUSAGE
;
10039 load_realtime
= (argc
== 5 && !strcmp(argv
[4], "load")) ? TRUE
: FALSE
;
10040 peer
= find_peer(argv
[3], NULL
, load_realtime
);
10041 if (s
) { /* Manager */
10043 const char *id
= astman_get_header(m
,"ActionID");
10045 astman_append(s
, "Response: Success\r\n");
10046 if (!ast_strlen_zero(id
))
10047 astman_append(s
, "ActionID: %s\r\n",id
);
10049 snprintf (cbuf
, sizeof(cbuf
), "Peer %s not found.\n", argv
[3]);
10050 astman_send_error(s
, m
, cbuf
);
10054 if (peer
&& type
==0 ) { /* Normal listing */
10055 ast_cli(fd
,"\n\n");
10056 ast_cli(fd
, " * Name : %s\n", peer
->name
);
10057 if (realtimepeers
) { /* Realtime is enabled */
10058 ast_cli(fd
, " Realtime peer: %s\n", ast_test_flag(&peer
->flags
[0], SIP_REALTIME
) ? "Yes, cached" : "No");
10060 ast_cli(fd
, " Secret : %s\n", ast_strlen_zero(peer
->secret
)?"<Not set>":"<Set>");
10061 ast_cli(fd
, " MD5Secret : %s\n", ast_strlen_zero(peer
->md5secret
)?"<Not set>":"<Set>");
10062 for (auth
= peer
->auth
; auth
; auth
= auth
->next
) {
10063 ast_cli(fd
, " Realm-auth : Realm %-15.15s User %-10.20s ", auth
->realm
, auth
->username
);
10064 ast_cli(fd
, "%s\n", !ast_strlen_zero(auth
->secret
)?"<Secret set>":(!ast_strlen_zero(auth
->md5secret
)?"<MD5secret set>" : "<Not set>"));
10066 ast_cli(fd
, " Context : %s\n", peer
->context
);
10067 ast_cli(fd
, " Subscr.Cont. : %s\n", S_OR(peer
->subscribecontext
, "<Not set>") );
10068 ast_cli(fd
, " Language : %s\n", peer
->language
);
10069 if (!ast_strlen_zero(peer
->accountcode
))
10070 ast_cli(fd
, " Accountcode : %s\n", peer
->accountcode
);
10071 ast_cli(fd
, " AMA flags : %s\n", ast_cdr_flags2str(peer
->amaflags
));
10072 ast_cli(fd
, " Transfer mode: %s\n", transfermode2str(peer
->allowtransfer
));
10073 ast_cli(fd
, " CallingPres : %s\n", ast_describe_caller_presentation(peer
->callingpres
));
10074 if (!ast_strlen_zero(peer
->fromuser
))
10075 ast_cli(fd
, " FromUser : %s\n", peer
->fromuser
);
10076 if (!ast_strlen_zero(peer
->fromdomain
))
10077 ast_cli(fd
, " FromDomain : %s\n", peer
->fromdomain
);
10078 ast_cli(fd
, " Callgroup : ");
10079 print_group(fd
, peer
->callgroup
, 0);
10080 ast_cli(fd
, " Pickupgroup : ");
10081 print_group(fd
, peer
->pickupgroup
, 0);
10082 ast_cli(fd
, " Mailbox : %s\n", peer
->mailbox
);
10083 ast_cli(fd
, " VM Extension : %s\n", peer
->vmexten
);
10084 ast_cli(fd
, " LastMsgsSent : %d/%d\n", (peer
->lastmsgssent
& 0x7fff0000) >> 16, peer
->lastmsgssent
& 0xffff);
10085 ast_cli(fd
, " Call limit : %d\n", peer
->call_limit
);
10086 ast_cli(fd
, " Dynamic : %s\n", (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
)?"Yes":"No"));
10087 ast_cli(fd
, " Callerid : %s\n", ast_callerid_merge(cbuf
, sizeof(cbuf
), peer
->cid_name
, peer
->cid_num
, "<unspecified>"));
10088 ast_cli(fd
, " MaxCallBR : %d kbps\n", peer
->maxcallbitrate
);
10089 ast_cli(fd
, " Expire : %ld\n", ast_sched_when(sched
, peer
->expire
));
10090 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
)));
10091 ast_cli(fd
, " Nat : %s\n", nat2str(ast_test_flag(&peer
->flags
[0], SIP_NAT
)));
10092 ast_cli(fd
, " ACL : %s\n", (peer
->ha
?"Yes":"No"));
10093 ast_cli(fd
, " T38 pt UDPTL : %s\n", ast_test_flag(&peer
->flags
[1], SIP_PAGE2_T38SUPPORT_UDPTL
)?"Yes":"No");
10094 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10095 ast_cli(fd
, " T38 pt RTP : %s\n", ast_test_flag(&peer
->flags
[1], SIP_PAGE2_T38SUPPORT_RTP
)?"Yes":"No");
10096 ast_cli(fd
, " T38 pt TCP : %s\n", ast_test_flag(&peer
->flags
[1], SIP_PAGE2_T38SUPPORT_TCP
)?"Yes":"No");
10098 ast_cli(fd
, " CanReinvite : %s\n", ast_test_flag(&peer
->flags
[0], SIP_CAN_REINVITE
)?"Yes":"No");
10099 ast_cli(fd
, " PromiscRedir : %s\n", ast_test_flag(&peer
->flags
[0], SIP_PROMISCREDIR
)?"Yes":"No");
10100 ast_cli(fd
, " User=Phone : %s\n", ast_test_flag(&peer
->flags
[0], SIP_USEREQPHONE
)?"Yes":"No");
10101 ast_cli(fd
, " Video Support: %s\n", ast_test_flag(&peer
->flags
[1], SIP_PAGE2_VIDEOSUPPORT
)?"Yes":"No");
10102 ast_cli(fd
, " Trust RPID : %s\n", ast_test_flag(&peer
->flags
[0], SIP_TRUSTRPID
) ? "Yes" : "No");
10103 ast_cli(fd
, " Send RPID : %s\n", ast_test_flag(&peer
->flags
[0], SIP_SENDRPID
) ? "Yes" : "No");
10104 ast_cli(fd
, " Subscriptions: %s\n", ast_test_flag(&peer
->flags
[1], SIP_PAGE2_ALLOWSUBSCRIBE
) ? "Yes" : "No");
10105 ast_cli(fd
, " Overlap dial : %s\n", ast_test_flag(&peer
->flags
[1], SIP_PAGE2_ALLOWOVERLAP
) ? "Yes" : "No");
10107 /* - is enumerated */
10108 ast_cli(fd
, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer
->flags
[0], SIP_DTMF
)));
10109 ast_cli(fd
, " LastMsg : %d\n", peer
->lastmsg
);
10110 ast_cli(fd
, " ToHost : %s\n", peer
->tohost
);
10111 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
));
10112 ast_cli(fd
, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer
->defaddr
.sin_addr
), ntohs(peer
->defaddr
.sin_port
));
10113 if (!ast_strlen_zero(global_regcontext
))
10114 ast_cli(fd
, " Reg. exten : %s\n", peer
->regexten
);
10115 ast_cli(fd
, " Def. Username: %s\n", peer
->username
);
10116 ast_cli(fd
, " SIP Options : ");
10117 if (peer
->sipoptions
) {
10118 int lastoption
= -1;
10119 for (x
=0 ; (x
< (sizeof(sip_options
) / sizeof(sip_options
[0]))); x
++) {
10120 if (sip_options
[x
].id
!= lastoption
) {
10121 if (peer
->sipoptions
& sip_options
[x
].id
)
10122 ast_cli(fd
, "%s ", sip_options
[x
].text
);
10127 ast_cli(fd
, "(none)");
10130 ast_cli(fd
, " Codecs : ");
10131 ast_getformatname_multiple(codec_buf
, sizeof(codec_buf
) -1, peer
->capability
);
10132 ast_cli(fd
, "%s\n", codec_buf
);
10133 ast_cli(fd
, " Codec Order : (");
10134 print_codec_to_cli(fd
, &peer
->prefs
);
10135 ast_cli(fd
, ")\n");
10137 ast_cli(fd
, " Auto-Framing: %s \n", peer
->autoframing
? "Yes" : "No");
10138 ast_cli(fd
, " Status : ");
10139 peer_status(peer
, status
, sizeof(status
));
10140 ast_cli(fd
, "%s\n",status
);
10141 ast_cli(fd
, " Useragent : %s\n", peer
->useragent
);
10142 ast_cli(fd
, " Reg. Contact : %s\n", peer
->fullcontact
);
10143 if (peer
->chanvars
) {
10144 ast_cli(fd
, " Variables :\n");
10145 for (v
= peer
->chanvars
; v
; v
= v
->next
)
10146 ast_cli(fd
, " %s = %s\n", v
->name
, v
->value
);
10149 ASTOBJ_UNREF(peer
,sip_destroy_peer
);
10150 } else if (peer
&& type
== 1) { /* manager listing */
10152 astman_append(s
, "Channeltype: SIP\r\n");
10153 astman_append(s
, "ObjectName: %s\r\n", peer
->name
);
10154 astman_append(s
, "ChanObjectType: peer\r\n");
10155 astman_append(s
, "SecretExist: %s\r\n", ast_strlen_zero(peer
->secret
)?"N":"Y");
10156 astman_append(s
, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer
->md5secret
)?"N":"Y");
10157 astman_append(s
, "Context: %s\r\n", peer
->context
);
10158 astman_append(s
, "Language: %s\r\n", peer
->language
);
10159 if (!ast_strlen_zero(peer
->accountcode
))
10160 astman_append(s
, "Accountcode: %s\r\n", peer
->accountcode
);
10161 astman_append(s
, "AMAflags: %s\r\n", ast_cdr_flags2str(peer
->amaflags
));
10162 astman_append(s
, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer
->callingpres
));
10163 if (!ast_strlen_zero(peer
->fromuser
))
10164 astman_append(s
, "SIP-FromUser: %s\r\n", peer
->fromuser
);
10165 if (!ast_strlen_zero(peer
->fromdomain
))
10166 astman_append(s
, "SIP-FromDomain: %s\r\n", peer
->fromdomain
);
10167 astman_append(s
, "Callgroup: ");
10168 astman_append(s
, "%s\r\n", ast_print_group(buf
, sizeof(buf
), peer
->callgroup
));
10169 astman_append(s
, "Pickupgroup: ");
10170 astman_append(s
, "%s\r\n", ast_print_group(buf
, sizeof(buf
), peer
->pickupgroup
));
10171 astman_append(s
, "VoiceMailbox: %s\r\n", peer
->mailbox
);
10172 astman_append(s
, "TransferMode: %s\r\n", transfermode2str(peer
->allowtransfer
));
10173 astman_append(s
, "LastMsgsSent: %d\r\n", peer
->lastmsgssent
);
10174 astman_append(s
, "Call-limit: %d\r\n", peer
->call_limit
);
10175 astman_append(s
, "MaxCallBR: %d kbps\r\n", peer
->maxcallbitrate
);
10176 astman_append(s
, "Dynamic: %s\r\n", (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
)?"Y":"N"));
10177 astman_append(s
, "Callerid: %s\r\n", ast_callerid_merge(cbuf
, sizeof(cbuf
), peer
->cid_name
, peer
->cid_num
, ""));
10178 astman_append(s
, "RegExpire: %ld seconds\r\n", ast_sched_when(sched
,peer
->expire
));
10179 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
)));
10180 astman_append(s
, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer
->flags
[0], SIP_NAT
)));
10181 astman_append(s
, "ACL: %s\r\n", (peer
->ha
?"Y":"N"));
10182 astman_append(s
, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer
->flags
[0], SIP_CAN_REINVITE
)?"Y":"N"));
10183 astman_append(s
, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer
->flags
[0], SIP_PROMISCREDIR
)?"Y":"N"));
10184 astman_append(s
, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer
->flags
[0], SIP_USEREQPHONE
)?"Y":"N"));
10185 astman_append(s
, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_VIDEOSUPPORT
)?"Y":"N"));
10187 /* - is enumerated */
10188 astman_append(s
, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer
->flags
[0], SIP_DTMF
)));
10189 astman_append(s
, "SIPLastMsg: %d\r\n", peer
->lastmsg
);
10190 astman_append(s
, "ToHost: %s\r\n", peer
->tohost
);
10191 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
));
10192 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
));
10193 astman_append(s
, "Default-Username: %s\r\n", peer
->username
);
10194 if (!ast_strlen_zero(global_regcontext
))
10195 astman_append(s
, "RegExtension: %s\r\n", peer
->regexten
);
10196 astman_append(s
, "Codecs: ");
10197 ast_getformatname_multiple(codec_buf
, sizeof(codec_buf
) -1, peer
->capability
);
10198 astman_append(s
, "%s\r\n", codec_buf
);
10199 astman_append(s
, "CodecOrder: ");
10200 pref
= &peer
->prefs
;
10201 for(x
= 0; x
< 32 ; x
++) {
10202 codec
= ast_codec_pref_index(pref
,x
);
10205 astman_append(s
, "%s", ast_getformatname(codec
));
10206 if (x
< 31 && ast_codec_pref_index(pref
,x
+1))
10207 astman_append(s
, ",");
10210 astman_append(s
, "\r\n");
10211 astman_append(s
, "Status: ");
10212 peer_status(peer
, status
, sizeof(status
));
10213 astman_append(s
, "%s\r\n", status
);
10214 astman_append(s
, "SIP-Useragent: %s\r\n", peer
->useragent
);
10215 astman_append(s
, "Reg-Contact : %s\r\n", peer
->fullcontact
);
10216 if (peer
->chanvars
) {
10217 for (v
= peer
->chanvars
; v
; v
= v
->next
) {
10218 astman_append(s
, "ChanVariable:\n");
10219 astman_append(s
, " %s,%s\r\n", v
->name
, v
->value
);
10223 ASTOBJ_UNREF(peer
,sip_destroy_peer
);
10226 ast_cli(fd
,"Peer %s not found.\n", argv
[3]);
10230 return RESULT_SUCCESS
;
10233 /*! \brief Show one user in detail */
10234 static int sip_show_user(int fd
, int argc
, char *argv
[])
10237 struct sip_user
*user
;
10238 struct ast_variable
*v
;
10242 return RESULT_SHOWUSAGE
;
10244 /* Load from realtime storage? */
10245 load_realtime
= (argc
== 5 && !strcmp(argv
[4], "load")) ? TRUE
: FALSE
;
10247 user
= find_user(argv
[3], load_realtime
);
10249 ast_cli(fd
,"\n\n");
10250 ast_cli(fd
, " * Name : %s\n", user
->name
);
10251 ast_cli(fd
, " Secret : %s\n", ast_strlen_zero(user
->secret
)?"<Not set>":"<Set>");
10252 ast_cli(fd
, " MD5Secret : %s\n", ast_strlen_zero(user
->md5secret
)?"<Not set>":"<Set>");
10253 ast_cli(fd
, " Context : %s\n", user
->context
);
10254 ast_cli(fd
, " Language : %s\n", user
->language
);
10255 if (!ast_strlen_zero(user
->accountcode
))
10256 ast_cli(fd
, " Accountcode : %s\n", user
->accountcode
);
10257 ast_cli(fd
, " AMA flags : %s\n", ast_cdr_flags2str(user
->amaflags
));
10258 ast_cli(fd
, " Transfer mode: %s\n", transfermode2str(user
->allowtransfer
));
10259 ast_cli(fd
, " MaxCallBR : %d kbps\n", user
->maxcallbitrate
);
10260 ast_cli(fd
, " CallingPres : %s\n", ast_describe_caller_presentation(user
->callingpres
));
10261 ast_cli(fd
, " Call limit : %d\n", user
->call_limit
);
10262 ast_cli(fd
, " Callgroup : ");
10263 print_group(fd
, user
->callgroup
, 0);
10264 ast_cli(fd
, " Pickupgroup : ");
10265 print_group(fd
, user
->pickupgroup
, 0);
10266 ast_cli(fd
, " Callerid : %s\n", ast_callerid_merge(cbuf
, sizeof(cbuf
), user
->cid_name
, user
->cid_num
, "<unspecified>"));
10267 ast_cli(fd
, " ACL : %s\n", (user
->ha
?"Yes":"No"));
10268 ast_cli(fd
, " Codec Order : (");
10269 print_codec_to_cli(fd
, &user
->prefs
);
10270 ast_cli(fd
, ")\n");
10272 ast_cli(fd
, " Auto-Framing: %s \n", user
->autoframing
? "Yes" : "No");
10273 if (user
->chanvars
) {
10274 ast_cli(fd
, " Variables :\n");
10275 for (v
= user
->chanvars
; v
; v
= v
->next
)
10276 ast_cli(fd
, " %s = %s\n", v
->name
, v
->value
);
10279 ASTOBJ_UNREF(user
,sip_destroy_user
);
10281 ast_cli(fd
,"User %s not found.\n", argv
[3]);
10285 return RESULT_SUCCESS
;
10288 /*! \brief Show SIP Registry (registrations with other SIP proxies */
10289 static int sip_show_registry(int fd
, int argc
, char *argv
[])
10291 #define FORMAT2 "%-30.30s %-12.12s %8.8s %-20.20s %-25.25s\n"
10292 #define FORMAT "%-30.30s %-12.12s %8d %-20.20s %-25.25s\n"
10299 return RESULT_SHOWUSAGE
;
10300 ast_cli(fd
, FORMAT2
, "Host", "Username", "Refresh", "State", "Reg.Time");
10301 ASTOBJ_CONTAINER_TRAVERSE(®l
, 1, do {
10302 ASTOBJ_RDLOCK(iterator
);
10303 snprintf(host
, sizeof(host
), "%s:%d", iterator
->hostname
, iterator
->portno
? iterator
->portno
: STANDARD_SIP_PORT
);
10304 if (iterator
->regtime
) {
10305 ast_localtime(&iterator
->regtime
, &tm
, NULL
);
10306 strftime(tmpdat
, sizeof(tmpdat
), "%a, %d %b %Y %T", &tm
);
10310 ast_cli(fd
, FORMAT
, host
, iterator
->username
, iterator
->refresh
, regstate2str(iterator
->regstate
), tmpdat
);
10311 ASTOBJ_UNLOCK(iterator
);
10313 return RESULT_SUCCESS
;
10318 /*! \brief List global settings for the SIP channel */
10319 static int sip_show_settings(int fd
, int argc
, char *argv
[])
10323 char codec_buf
[BUFSIZ
];
10325 realtimepeers
= ast_check_realtime("sippeers");
10326 realtimeusers
= ast_check_realtime("sipusers");
10329 return RESULT_SHOWUSAGE
;
10330 ast_cli(fd
, "\n\nGlobal Settings:\n");
10331 ast_cli(fd
, "----------------\n");
10332 ast_cli(fd
, " SIP Port: %d\n", ntohs(bindaddr
.sin_port
));
10333 ast_cli(fd
, " Bindaddress: %s\n", ast_inet_ntoa(bindaddr
.sin_addr
));
10334 ast_cli(fd
, " Videosupport: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_VIDEOSUPPORT
) ? "Yes" : "No");
10335 ast_cli(fd
, " AutoCreatePeer: %s\n", autocreatepeer
? "Yes" : "No");
10336 ast_cli(fd
, " Allow unknown access: %s\n", global_allowguest
? "Yes" : "No");
10337 ast_cli(fd
, " Allow subscriptions: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_ALLOWSUBSCRIBE
) ? "Yes" : "No");
10338 ast_cli(fd
, " Allow overlap dialing: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_ALLOWOVERLAP
) ? "Yes" : "No");
10339 ast_cli(fd
, " Promsic. redir: %s\n", ast_test_flag(&global_flags
[0], SIP_PROMISCREDIR
) ? "Yes" : "No");
10340 ast_cli(fd
, " SIP domain support: %s\n", AST_LIST_EMPTY(&domain_list
) ? "No" : "Yes");
10341 ast_cli(fd
, " Call to non-local dom.: %s\n", allow_external_domains
? "Yes" : "No");
10342 ast_cli(fd
, " URI user is phone no: %s\n", ast_test_flag(&global_flags
[0], SIP_USEREQPHONE
) ? "Yes" : "No");
10343 ast_cli(fd
, " Our auth realm %s\n", global_realm
);
10344 ast_cli(fd
, " Realm. auth: %s\n", authl
? "Yes": "No");
10345 ast_cli(fd
, " Always auth rejects: %s\n", global_alwaysauthreject
? "Yes" : "No");
10346 ast_cli(fd
, " Call limit peers only: %s\n", global_limitonpeers
? "Yes" : "No");
10347 ast_cli(fd
, " Direct RTP setup: %s\n", global_directrtpsetup
? "Yes" : "No");
10348 ast_cli(fd
, " User Agent: %s\n", global_useragent
);
10349 ast_cli(fd
, " MWI checking interval: %d secs\n", global_mwitime
);
10350 ast_cli(fd
, " Reg. context: %s\n", S_OR(global_regcontext
, "(not set)"));
10351 ast_cli(fd
, " Caller ID: %s\n", default_callerid
);
10352 ast_cli(fd
, " From: Domain: %s\n", default_fromdomain
);
10353 ast_cli(fd
, " Record SIP history: %s\n", recordhistory
? "On" : "Off");
10354 ast_cli(fd
, " Call Events: %s\n", global_callevents
? "On" : "Off");
10355 ast_cli(fd
, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip
));
10356 ast_cli(fd
, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio
));
10357 ast_cli(fd
, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video
));
10358 ast_cli(fd
, " T38 fax pt UDPTL: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_T38SUPPORT_UDPTL
) ? "Yes" : "No");
10359 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10360 ast_cli(fd
, " T38 fax pt RTP: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_T38SUPPORT_RTP
) ? "Yes" : "No");
10361 ast_cli(fd
, " T38 fax pt TCP: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_T38SUPPORT_TCP
) ? "Yes" : "No");
10363 ast_cli(fd
, " RFC2833 Compensation: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_RFC2833_COMPENSATE
) ? "Yes" : "No");
10364 if (!realtimepeers
&& !realtimeusers
)
10365 ast_cli(fd
, " SIP realtime: Disabled\n" );
10367 ast_cli(fd
, " SIP realtime: Enabled\n" );
10369 ast_cli(fd
, "\nGlobal Signalling Settings:\n");
10370 ast_cli(fd
, "---------------------------\n");
10371 ast_cli(fd
, " Codecs: ");
10372 ast_getformatname_multiple(codec_buf
, sizeof(codec_buf
) -1, global_capability
);
10373 ast_cli(fd
, "%s\n", codec_buf
);
10374 ast_cli(fd
, " Codec Order: ");
10375 print_codec_to_cli(fd
, &default_prefs
);
10377 ast_cli(fd
, " T1 minimum: %d\n", global_t1min
);
10378 ast_cli(fd
, " Relax DTMF: %s\n", global_relaxdtmf
? "Yes" : "No");
10379 ast_cli(fd
, " Compact SIP headers: %s\n", compactheaders
? "Yes" : "No");
10380 ast_cli(fd
, " RTP Keepalive: %d %s\n", global_rtpkeepalive
, global_rtpkeepalive
? "" : "(Disabled)" );
10381 ast_cli(fd
, " RTP Timeout: %d %s\n", global_rtptimeout
, global_rtptimeout
? "" : "(Disabled)" );
10382 ast_cli(fd
, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout
, global_rtpholdtimeout
? "" : "(Disabled)");
10383 ast_cli(fd
, " MWI NOTIFY mime type: %s\n", default_notifymime
);
10384 ast_cli(fd
, " DNS SRV lookup: %s\n", srvlookup
? "Yes" : "No");
10385 ast_cli(fd
, " Pedantic SIP support: %s\n", pedanticsipchecking
? "Yes" : "No");
10386 ast_cli(fd
, " Reg. min duration %d secs\n", min_expiry
);
10387 ast_cli(fd
, " Reg. max duration: %d secs\n", max_expiry
);
10388 ast_cli(fd
, " Reg. default duration: %d secs\n", default_expiry
);
10389 ast_cli(fd
, " Outbound reg. timeout: %d secs\n", global_reg_timeout
);
10390 ast_cli(fd
, " Outbound reg. attempts: %d\n", global_regattempts_max
);
10391 ast_cli(fd
, " Notify ringing state: %s\n", global_notifyringing
? "Yes" : "No");
10392 ast_cli(fd
, " Notify hold state: %s\n", global_notifyhold
? "Yes" : "No");
10393 ast_cli(fd
, " SIP Transfer mode: %s\n", transfermode2str(global_allowtransfer
));
10394 ast_cli(fd
, " Max Call Bitrate: %d kbps\r\n", default_maxcallbitrate
);
10395 ast_cli(fd
, " Auto-Framing: %s \r\n", global_autoframing
? "Yes" : "No");
10396 ast_cli(fd
, "\nDefault Settings:\n");
10397 ast_cli(fd
, "-----------------\n");
10398 ast_cli(fd
, " Context: %s\n", default_context
);
10399 ast_cli(fd
, " Nat: %s\n", nat2str(ast_test_flag(&global_flags
[0], SIP_NAT
)));
10400 ast_cli(fd
, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags
[0], SIP_DTMF
)));
10401 ast_cli(fd
, " Qualify: %d\n", default_qualify
);
10402 ast_cli(fd
, " Use ClientCode: %s\n", ast_test_flag(&global_flags
[0], SIP_USECLIENTCODE
) ? "Yes" : "No");
10403 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" );
10404 ast_cli(fd
, " Language: %s\n", S_OR(default_language
, "(Defaults to English)"));
10405 ast_cli(fd
, " MOH Interpret: %s\n", default_mohinterpret
);
10406 ast_cli(fd
, " MOH Suggest: %s\n", default_mohsuggest
);
10407 ast_cli(fd
, " Voice Mail Extension: %s\n", default_vmexten
);
10410 if (realtimepeers
|| realtimeusers
) {
10411 ast_cli(fd
, "\nRealtime SIP Settings:\n");
10412 ast_cli(fd
, "----------------------\n");
10413 ast_cli(fd
, " Realtime Peers: %s\n", realtimepeers
? "Yes" : "No");
10414 ast_cli(fd
, " Realtime Users: %s\n", realtimeusers
? "Yes" : "No");
10415 ast_cli(fd
, " Cache Friends: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_RTCACHEFRIENDS
) ? "Yes" : "No");
10416 ast_cli(fd
, " Update: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_RTUPDATE
) ? "Yes" : "No");
10417 ast_cli(fd
, " Ignore Reg. Expire: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_IGNOREREGEXPIRE
) ? "Yes" : "No");
10418 ast_cli(fd
, " Save sys. name: %s\n", ast_test_flag(&global_flags
[1], SIP_PAGE2_RTSAVE_SYSNAME
) ? "Yes" : "No");
10419 ast_cli(fd
, " Auto Clear: %d\n", global_rtautoclear
);
10421 ast_cli(fd
, "\n----\n");
10422 return RESULT_SUCCESS
;
10425 /*! \brief Show subscription type in string format */
10426 static const char *subscription_type2str(enum subscriptiontype subtype
)
10430 for (i
= 1; (i
< (sizeof(subscription_types
) / sizeof(subscription_types
[0]))); i
++) {
10431 if (subscription_types
[i
].type
== subtype
) {
10432 return subscription_types
[i
].text
;
10435 return subscription_types
[0].text
;
10438 /*! \brief Find subscription type in array */
10439 static const struct cfsubscription_types
*find_subscription_type(enum subscriptiontype subtype
)
10443 for (i
= 1; (i
< (sizeof(subscription_types
) / sizeof(subscription_types
[0]))); i
++) {
10444 if (subscription_types
[i
].type
== subtype
) {
10445 return &subscription_types
[i
];
10448 return &subscription_types
[0];
10451 /*! \brief Show active SIP channels */
10452 static int sip_show_channels(int fd
, int argc
, char *argv
[])
10454 return __sip_show_channels(fd
, argc
, argv
, 0);
10457 /*! \brief Show active SIP subscriptions */
10458 static int sip_show_subscriptions(int fd
, int argc
, char *argv
[])
10460 return __sip_show_channels(fd
, argc
, argv
, 1);
10463 /*! \brief SIP show channels CLI (main function) */
10464 static int __sip_show_channels(int fd
, int argc
, char *argv
[], int subscriptions
)
10466 #define FORMAT3 "%-15.15s %-10.10s %-11.11s %-15.15s %-13.13s %-15.15s %-10.10s\n"
10467 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-4.4s %-7.7s %-15.15s\n"
10468 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-4.4s %-3.3s %-3.3s %-15.15s %-10.10s\n"
10469 struct sip_pvt
*cur
;
10471 char *referstatus
= NULL
;
10474 return RESULT_SHOWUSAGE
;
10475 ast_mutex_lock(&iflock
);
10477 if (!subscriptions
)
10478 ast_cli(fd
, FORMAT2
, "Peer", "User/ANR", "Call ID", "Seq (Tx/Rx)", "Format", "Hold", "Last Message");
10480 ast_cli(fd
, FORMAT3
, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox");
10481 for (; cur
; cur
= cur
->next
) {
10483 if (cur
->refer
) { /* SIP transfer in progress */
10484 referstatus
= referstatus2str(cur
->refer
->status
);
10486 if (cur
->subscribed
== NONE
&& !subscriptions
) {
10487 ast_cli(fd
, FORMAT
, ast_inet_ntoa(cur
->sa
.sin_addr
),
10488 S_OR(cur
->username
, S_OR(cur
->cid_num
, "(None)")),
10490 cur
->ocseq
, cur
->icseq
,
10491 ast_getformatname(cur
->owner
? cur
->owner
->nativeformats
: 0),
10492 ast_test_flag(&cur
->flags
[1], SIP_PAGE2_CALL_ONHOLD
) ? "Yes" : "No",
10493 ast_test_flag(&cur
->flags
[0], SIP_NEEDDESTROY
) ? "(d)" : "",
10499 if (cur
->subscribed
!= NONE
&& subscriptions
) {
10500 ast_cli(fd
, FORMAT3
, ast_inet_ntoa(cur
->sa
.sin_addr
),
10501 S_OR(cur
->username
, S_OR(cur
->cid_num
, "(None)")),
10503 /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
10504 cur
->subscribed
== MWI_NOTIFICATION
? "--" : cur
->subscribeuri
,
10505 cur
->subscribed
== MWI_NOTIFICATION
? "<none>" : ast_extension_state2str(cur
->laststate
),
10506 subscription_type2str(cur
->subscribed
),
10507 cur
->subscribed
== MWI_NOTIFICATION
? (cur
->relatedpeer
? cur
->relatedpeer
->mailbox
: "<none>") : "<none>"
10512 ast_mutex_unlock(&iflock
);
10513 if (!subscriptions
)
10514 ast_cli(fd
, "%d active SIP channel%s\n", numchans
, (numchans
!= 1) ? "s" : "");
10516 ast_cli(fd
, "%d active SIP subscription%s\n", numchans
, (numchans
!= 1) ? "s" : "");
10517 return RESULT_SUCCESS
;
10523 /*! \brief Support routine for 'sip show channel' CLI */
10524 static char *complete_sipch(const char *line
, const char *word
, int pos
, int state
)
10527 struct sip_pvt
*cur
;
10529 int wordlen
= strlen(word
);
10531 ast_mutex_lock(&iflock
);
10532 for (cur
= iflist
; cur
; cur
= cur
->next
) {
10533 if (!strncasecmp(word
, cur
->callid
, wordlen
) && ++which
> state
) {
10534 c
= ast_strdup(cur
->callid
);
10538 ast_mutex_unlock(&iflock
);
10542 /*! \brief Do completion on peer name */
10543 static char *complete_sip_peer(const char *word
, int state
, int flags2
)
10545 char *result
= NULL
;
10546 int wordlen
= strlen(word
);
10549 ASTOBJ_CONTAINER_TRAVERSE(&peerl
, !result
, do {
10550 /* locking of the object is not required because only the name and flags are being compared */
10551 if (!strncasecmp(word
, iterator
->name
, wordlen
) &&
10552 (!flags2
|| ast_test_flag(&iterator
->flags
[1], flags2
)) &&
10554 result
= ast_strdup(iterator
->name
);
10559 /*! \brief Support routine for 'sip show peer' CLI */
10560 static char *complete_sip_show_peer(const char *line
, const char *word
, int pos
, int state
)
10563 return complete_sip_peer(word
, state
, 0);
10568 /*! \brief Support routine for 'sip debug peer' CLI */
10569 static char *complete_sip_debug_peer(const char *line
, const char *word
, int pos
, int state
)
10572 return complete_sip_peer(word
, state
, 0);
10577 /*! \brief Do completion on user name */
10578 static char *complete_sip_user(const char *word
, int state
, int flags2
)
10580 char *result
= NULL
;
10581 int wordlen
= strlen(word
);
10584 ASTOBJ_CONTAINER_TRAVERSE(&userl
, !result
, do {
10585 /* locking of the object is not required because only the name and flags are being compared */
10586 if (!strncasecmp(word
, iterator
->name
, wordlen
)) {
10587 if (flags2
&& !ast_test_flag(&iterator
->flags
[1], flags2
))
10589 if (++which
> state
) {
10590 result
= ast_strdup(iterator
->name
);
10597 /*! \brief Support routine for 'sip show user' CLI */
10598 static char *complete_sip_show_user(const char *line
, const char *word
, int pos
, int state
)
10601 return complete_sip_user(word
, state
, 0);
10606 /*! \brief Support routine for 'sip notify' CLI */
10607 static char *complete_sipnotify(const char *line
, const char *word
, int pos
, int state
)
10614 int wordlen
= strlen(word
);
10616 /* do completion for notify type */
10621 while ( (cat
= ast_category_browse(notify_types
, cat
)) ) {
10622 if (!strncasecmp(word
, cat
, wordlen
) && ++which
> state
) {
10623 c
= ast_strdup(cat
);
10631 return complete_sip_peer(word
, state
, 0);
10636 /*! \brief Support routine for 'sip prune realtime peer' CLI */
10637 static char *complete_sip_prune_realtime_peer(const char *line
, const char *word
, int pos
, int state
)
10640 return complete_sip_peer(word
, state
, SIP_PAGE2_RTCACHEFRIENDS
);
10644 /*! \brief Support routine for 'sip prune realtime user' CLI */
10645 static char *complete_sip_prune_realtime_user(const char *line
, const char *word
, int pos
, int state
)
10648 return complete_sip_user(word
, state
, SIP_PAGE2_RTCACHEFRIENDS
);
10653 /*! \brief Show details of one active dialog */
10654 static int sip_show_channel(int fd
, int argc
, char *argv
[])
10656 struct sip_pvt
*cur
;
10661 return RESULT_SHOWUSAGE
;
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 char formatbuf
[BUFSIZ
/2];
10668 if (cur
->subscribed
!= NONE
)
10669 ast_cli(fd
, " * Subscription (type: %s)\n", subscription_type2str(cur
->subscribed
));
10671 ast_cli(fd
, " * SIP Call\n");
10672 ast_cli(fd
, " Curr. trans. direction: %s\n", ast_test_flag(&cur
->flags
[0], SIP_OUTGOING
) ? "Outgoing" : "Incoming");
10673 ast_cli(fd
, " Call-ID: %s\n", cur
->callid
);
10674 ast_cli(fd
, " Owner channel ID: %s\n", cur
->owner
? cur
->owner
->name
: "<none>");
10675 ast_cli(fd
, " Our Codec Capability: %d\n", cur
->capability
);
10676 ast_cli(fd
, " Non-Codec Capability (DTMF): %d\n", cur
->noncodeccapability
);
10677 ast_cli(fd
, " Their Codec Capability: %d\n", cur
->peercapability
);
10678 ast_cli(fd
, " Joint Codec Capability: %d\n", cur
->jointcapability
);
10679 ast_cli(fd
, " Format: %s\n", ast_getformatname_multiple(formatbuf
, sizeof(formatbuf
), cur
->owner
? cur
->owner
->nativeformats
: 0) );
10680 ast_cli(fd
, " MaxCallBR: %d kbps\n", cur
->maxcallbitrate
);
10681 ast_cli(fd
, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur
->sa
.sin_addr
), ntohs(cur
->sa
.sin_port
));
10682 ast_cli(fd
, " Received Address: %s:%d\n", ast_inet_ntoa(cur
->recv
.sin_addr
), ntohs(cur
->recv
.sin_port
));
10683 ast_cli(fd
, " SIP Transfer mode: %s\n", transfermode2str(cur
->allowtransfer
));
10684 ast_cli(fd
, " NAT Support: %s\n", nat2str(ast_test_flag(&cur
->flags
[0], SIP_NAT
)));
10685 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)" );
10686 ast_cli(fd
, " Our Tag: %s\n", cur
->tag
);
10687 ast_cli(fd
, " Their Tag: %s\n", cur
->theirtag
);
10688 ast_cli(fd
, " SIP User agent: %s\n", cur
->useragent
);
10689 if (!ast_strlen_zero(cur
->username
))
10690 ast_cli(fd
, " Username: %s\n", cur
->username
);
10691 if (!ast_strlen_zero(cur
->peername
))
10692 ast_cli(fd
, " Peername: %s\n", cur
->peername
);
10693 if (!ast_strlen_zero(cur
->uri
))
10694 ast_cli(fd
, " Original uri: %s\n", cur
->uri
);
10695 if (!ast_strlen_zero(cur
->cid_num
))
10696 ast_cli(fd
, " Caller-ID: %s\n", cur
->cid_num
);
10697 ast_cli(fd
, " Need Destroy: %d\n", ast_test_flag(&cur
->flags
[0], SIP_NEEDDESTROY
));
10698 ast_cli(fd
, " Last Message: %s\n", cur
->lastmsg
);
10699 ast_cli(fd
, " Promiscuous Redir: %s\n", ast_test_flag(&cur
->flags
[0], SIP_PROMISCREDIR
) ? "Yes" : "No");
10700 ast_cli(fd
, " Route: %s\n", cur
->route
? cur
->route
->hop
: "N/A");
10701 ast_cli(fd
, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur
->flags
[0], SIP_DTMF
)));
10702 ast_cli(fd
, " SIP Options: ");
10703 if (cur
->sipoptions
) {
10705 for (x
=0 ; (x
< (sizeof(sip_options
) / sizeof(sip_options
[0]))); x
++) {
10706 if (cur
->sipoptions
& sip_options
[x
].id
)
10707 ast_cli(fd
, "%s ", sip_options
[x
].text
);
10710 ast_cli(fd
, "(none)\n");
10711 ast_cli(fd
, "\n\n");
10715 ast_mutex_unlock(&iflock
);
10717 ast_cli(fd
, "No such SIP Call ID starting with '%s'\n", argv
[3]);
10718 return RESULT_SUCCESS
;
10721 /*! \brief Show history details of one dialog */
10722 static int sip_show_history(int fd
, int argc
, char *argv
[])
10724 struct sip_pvt
*cur
;
10729 return RESULT_SHOWUSAGE
;
10730 if (!recordhistory
)
10731 ast_cli(fd
, "\n***Note: History recording is currently DISABLED. Use 'sip history' to ENABLE.\n");
10732 len
= strlen(argv
[3]);
10733 ast_mutex_lock(&iflock
);
10734 for (cur
= iflist
; cur
; cur
= cur
->next
) {
10735 if (!strncasecmp(cur
->callid
, argv
[3], len
)) {
10736 struct sip_history
*hist
;
10740 if (cur
->subscribed
!= NONE
)
10741 ast_cli(fd
, " * Subscription\n");
10743 ast_cli(fd
, " * SIP Call\n");
10745 AST_LIST_TRAVERSE(cur
->history
, hist
, list
)
10746 ast_cli(fd
, "%d. %s\n", ++x
, hist
->event
);
10748 ast_cli(fd
, "Call '%s' has no history\n", cur
->callid
);
10752 ast_mutex_unlock(&iflock
);
10754 ast_cli(fd
, "No such SIP Call ID starting with '%s'\n", argv
[3]);
10755 return RESULT_SUCCESS
;
10758 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
10759 static void sip_dump_history(struct sip_pvt
*dialog
)
10762 struct sip_history
*hist
;
10763 static int errmsg
= 0;
10768 if (!option_debug
&& !sipdebug
) {
10770 ast_log(LOG_NOTICE
, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
10776 ast_log(LOG_DEBUG
, "\n---------- SIP HISTORY for '%s' \n", dialog
->callid
);
10777 if (dialog
->subscribed
)
10778 ast_log(LOG_DEBUG
, " * Subscription\n");
10780 ast_log(LOG_DEBUG
, " * SIP Call\n");
10781 if (dialog
->history
)
10782 AST_LIST_TRAVERSE(dialog
->history
, hist
, list
)
10783 ast_log(LOG_DEBUG
, " %-3.3d. %s\n", ++x
, hist
->event
);
10785 ast_log(LOG_DEBUG
, "Call '%s' has no history\n", dialog
->callid
);
10786 ast_log(LOG_DEBUG
, "\n---------- END SIP HISTORY for '%s' \n", dialog
->callid
);
10790 /*! \brief Receive SIP INFO Message
10791 \note Doesn't read the duration of the DTMF signal */
10792 static void handle_request_info(struct sip_pvt
*p
, struct sip_request
*req
)
10795 unsigned int event
;
10796 const char *c
= get_header(req
, "Content-Type");
10798 /* Need to check the media/type */
10799 if (!strcasecmp(c
, "application/dtmf-relay") ||
10800 !strcasecmp(c
, "application/vnd.nortelnetworks.digits")) {
10801 unsigned int duration
= 0;
10803 /* Try getting the "signal=" part */
10804 if (ast_strlen_zero(c
= get_body(req
, "Signal")) && ast_strlen_zero(c
= get_body(req
, "d"))) {
10805 ast_log(LOG_WARNING
, "Unable to retrieve DTMF signal from INFO message from %s\n", p
->callid
);
10806 transmit_response(p
, "200 OK", req
); /* Should return error */
10809 ast_copy_string(buf
, c
, sizeof(buf
));
10812 if (!ast_strlen_zero((c
= get_body(req
, "Duration"))))
10813 duration
= atoi(c
);
10815 duration
= 100; /* 100 ms */
10817 if (!p
->owner
) { /* not a PBX call */
10818 transmit_response(p
, "481 Call leg/transaction does not exist", req
);
10819 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
10823 if (ast_strlen_zero(buf
)) {
10824 transmit_response(p
, "200 OK", req
);
10830 else if (buf
[0] == '#')
10832 else if ((buf
[0] >= 'A') && (buf
[0] <= 'D'))
10833 event
= 12 + buf
[0] - 'A';
10837 /* send a FLASH event */
10838 struct ast_frame f
= { AST_FRAME_CONTROL
, AST_CONTROL_FLASH
, };
10839 ast_queue_frame(p
->owner
, &f
);
10841 ast_verbose("* DTMF-relay event received: FLASH\n");
10843 /* send a DTMF event */
10844 struct ast_frame f
= { AST_FRAME_DTMF
, };
10846 f
.subclass
= '0' + event
;
10847 } else if (event
< 11) {
10849 } else if (event
< 12) {
10851 } else if (event
< 16) {
10852 f
.subclass
= 'A' + (event
- 12);
10855 ast_queue_frame(p
->owner
, &f
);
10857 ast_verbose("* DTMF-relay event received: %c\n", f
.subclass
);
10859 transmit_response(p
, "200 OK", req
);
10861 } else if (!strcasecmp(c
, "application/media_control+xml")) {
10862 /* Eh, we'll just assume it's a fast picture update for now */
10864 ast_queue_control(p
->owner
, AST_CONTROL_VIDUPDATE
);
10865 transmit_response(p
, "200 OK", req
);
10867 } else if (!ast_strlen_zero(c
= get_header(req
, "X-ClientCode"))) {
10868 /* Client code (from SNOM phone) */
10869 if (ast_test_flag(&p
->flags
[0], SIP_USECLIENTCODE
)) {
10870 if (p
->owner
&& p
->owner
->cdr
)
10871 ast_cdr_setuserfield(p
->owner
, c
);
10872 if (p
->owner
&& ast_bridged_channel(p
->owner
) && ast_bridged_channel(p
->owner
)->cdr
)
10873 ast_cdr_setuserfield(ast_bridged_channel(p
->owner
), c
);
10874 transmit_response(p
, "200 OK", req
);
10876 transmit_response(p
, "403 Unauthorized", req
);
10880 /* Other type of INFO message, not really understood by Asterisk */
10881 /* if (get_msg_text(buf, sizeof(buf), req)) { */
10883 ast_log(LOG_WARNING
, "Unable to parse INFO message from %s. Content %s\n", p
->callid
, buf
);
10884 transmit_response(p
, "415 Unsupported media type", req
);
10888 /*! \brief Enable SIP Debugging in CLI */
10889 static int sip_do_debug_ip(int fd
, int argc
, char *argv
[])
10891 struct hostent
*hp
;
10892 struct ast_hostent ahp
;
10896 /* sip set debug ip <ip> */
10898 return RESULT_SHOWUSAGE
;
10903 hp
= ast_gethostbyname(arg
, &ahp
);
10905 return RESULT_SHOWUSAGE
;
10907 debugaddr
.sin_family
= AF_INET
;
10908 memcpy(&debugaddr
.sin_addr
, hp
->h_addr
, sizeof(debugaddr
.sin_addr
));
10909 debugaddr
.sin_port
= htons(port
);
10911 ast_cli(fd
, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr
.sin_addr
));
10913 ast_cli(fd
, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr
.sin_addr
), port
);
10915 ast_set_flag(&global_flags
[1], SIP_PAGE2_DEBUG_CONSOLE
);
10917 return RESULT_SUCCESS
;
10920 /*! \brief sip_do_debug_peer: Turn on SIP debugging with peer mask */
10921 static int sip_do_debug_peer(int fd
, int argc
, char *argv
[])
10923 struct sip_peer
*peer
;
10925 return RESULT_SHOWUSAGE
;
10926 peer
= find_peer(argv
[4], NULL
, 1);
10928 if (peer
->addr
.sin_addr
.s_addr
) {
10929 debugaddr
.sin_family
= AF_INET
;
10930 debugaddr
.sin_addr
= peer
->addr
.sin_addr
;
10931 debugaddr
.sin_port
= peer
->addr
.sin_port
;
10932 ast_cli(fd
, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr
.sin_addr
), ntohs(debugaddr
.sin_port
));
10933 ast_set_flag(&global_flags
[1], SIP_PAGE2_DEBUG_CONSOLE
);
10935 ast_cli(fd
, "Unable to get IP address of peer '%s'\n", argv
[4]);
10936 ASTOBJ_UNREF(peer
,sip_destroy_peer
);
10938 ast_cli(fd
, "No such peer '%s'\n", argv
[4]);
10939 return RESULT_SUCCESS
;
10942 /*! \brief Turn on SIP debugging (CLI command) */
10943 static int sip_do_debug(int fd
, int argc
, char *argv
[])
10945 int oldsipdebug
= sipdebug_console
;
10948 return RESULT_SHOWUSAGE
;
10949 else if (strcmp(argv
[3], "ip") == 0)
10950 return sip_do_debug_ip(fd
, argc
, argv
);
10951 else if (strcmp(argv
[3], "peer") == 0)
10952 return sip_do_debug_peer(fd
, argc
, argv
);
10954 return RESULT_SHOWUSAGE
;
10956 ast_set_flag(&global_flags
[1], SIP_PAGE2_DEBUG_CONSOLE
);
10957 memset(&debugaddr
, 0, sizeof(debugaddr
));
10958 ast_cli(fd
, "SIP Debugging %senabled\n", oldsipdebug
? "re-" : "");
10959 return RESULT_SUCCESS
;
10962 static int sip_do_debug_deprecated(int fd
, int argc
, char *argv
[])
10964 int oldsipdebug
= sipdebug_console
;
10965 char *newargv
[6] = { "sip", "set", "debug", NULL
};
10968 return RESULT_SHOWUSAGE
;
10969 else if (strcmp(argv
[2], "ip") == 0) {
10970 newargv
[3] = argv
[2];
10971 newargv
[4] = argv
[3];
10972 return sip_do_debug_ip(fd
, argc
+ 1, newargv
);
10973 } else if (strcmp(argv
[2], "peer") == 0) {
10974 newargv
[3] = argv
[2];
10975 newargv
[4] = argv
[3];
10976 return sip_do_debug_peer(fd
, argc
+ 1, newargv
);
10978 return RESULT_SHOWUSAGE
;
10980 ast_set_flag(&global_flags
[1], SIP_PAGE2_DEBUG_CONSOLE
);
10981 memset(&debugaddr
, 0, sizeof(debugaddr
));
10982 ast_cli(fd
, "SIP Debugging %senabled\n", oldsipdebug
? "re-" : "");
10983 return RESULT_SUCCESS
;
10986 /*! \brief Cli command to send SIP notify to peer */
10987 static int sip_notify(int fd
, int argc
, char *argv
[])
10989 struct ast_variable
*varlist
;
10993 return RESULT_SHOWUSAGE
;
10995 if (!notify_types
) {
10996 ast_cli(fd
, "No %s file found, or no types listed there\n", notify_config
);
10997 return RESULT_FAILURE
;
11000 varlist
= ast_variable_browse(notify_types
, argv
[2]);
11003 ast_cli(fd
, "Unable to find notify type '%s'\n", argv
[2]);
11004 return RESULT_FAILURE
;
11007 for (i
= 3; i
< argc
; i
++) {
11009 struct sip_request req
;
11010 struct ast_variable
*var
;
11012 if (!(p
= sip_alloc(NULL
, NULL
, 0, SIP_NOTIFY
))) {
11013 ast_log(LOG_WARNING
, "Unable to build sip pvt data for notify (memory/socket error)\n");
11014 return RESULT_FAILURE
;
11017 if (create_addr(p
, argv
[i
])) {
11018 /* Maybe they're not registered, etc. */
11020 ast_cli(fd
, "Could not create address for '%s'\n", argv
[i
]);
11024 initreqprep(&req
, p
, SIP_NOTIFY
);
11026 for (var
= varlist
; var
; var
= var
->next
)
11027 add_header(&req
, var
->name
, var
->value
);
11029 /* Recalculate our side, and recalculate Call ID */
11030 if (ast_sip_ouraddrfor(&p
->sa
.sin_addr
, &p
->ourip
))
11031 p
->ourip
= __ourip
;
11033 build_callid_pvt(p
);
11034 ast_cli(fd
, "Sending NOTIFY of type '%s' to '%s'\n", argv
[2], argv
[i
]);
11035 transmit_sip_request(p
, &req
);
11036 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
11039 return RESULT_SUCCESS
;
11042 /*! \brief Disable SIP Debugging in CLI */
11043 static int sip_no_debug(int fd
, int argc
, char *argv
[])
11046 return RESULT_SHOWUSAGE
;
11047 ast_clear_flag(&global_flags
[1], SIP_PAGE2_DEBUG_CONSOLE
);
11048 ast_cli(fd
, "SIP Debugging Disabled\n");
11049 return RESULT_SUCCESS
;
11052 static int sip_no_debug_deprecated(int fd
, int argc
, char *argv
[])
11055 return RESULT_SHOWUSAGE
;
11056 ast_clear_flag(&global_flags
[1], SIP_PAGE2_DEBUG_CONSOLE
);
11057 ast_cli(fd
, "SIP Debugging Disabled\n");
11058 return RESULT_SUCCESS
;
11061 /*! \brief Enable SIP History logging (CLI) */
11062 static int sip_do_history(int fd
, int argc
, char *argv
[])
11065 return RESULT_SHOWUSAGE
;
11067 recordhistory
= TRUE
;
11068 ast_cli(fd
, "SIP History Recording Enabled (use 'sip show history')\n");
11069 return RESULT_SUCCESS
;
11072 /*! \brief Disable SIP History logging (CLI) */
11073 static int sip_no_history(int fd
, int argc
, char *argv
[])
11076 return RESULT_SHOWUSAGE
;
11078 recordhistory
= FALSE
;
11079 ast_cli(fd
, "SIP History Recording Disabled\n");
11080 return RESULT_SUCCESS
;
11083 /*! \brief Authenticate for outbound registration */
11084 static int do_register_auth(struct sip_pvt
*p
, struct sip_request
*req
, char *header
, char *respheader
)
11088 memset(digest
,0,sizeof(digest
));
11089 if (reply_digest(p
, req
, header
, SIP_REGISTER
, digest
, sizeof(digest
))) {
11090 /* There's nothing to use for authentication */
11091 /* No digest challenge in request */
11092 if (sip_debug_test_pvt(p
) && p
->registry
)
11093 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p
->registry
->hostname
);
11094 /* No old challenge */
11097 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
))
11098 append_history(p
, "RegistryAuth", "Try: %d", p
->authtries
);
11099 if (sip_debug_test_pvt(p
) && p
->registry
)
11100 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p
->registry
->hostname
);
11101 return transmit_register(p
->registry
, SIP_REGISTER
, digest
, respheader
);
11104 /*! \brief Add authentication on outbound SIP packet */
11105 static int do_proxy_auth(struct sip_pvt
*p
, struct sip_request
*req
, char *header
, char *respheader
, int sipmethod
, int init
)
11109 if (!p
->options
&& !(p
->options
= ast_calloc(1, sizeof(*p
->options
))))
11113 if (option_debug
> 1)
11114 ast_log(LOG_DEBUG
, "Auth attempt %d on %s\n", p
->authtries
, sip_methods
[sipmethod
].text
);
11115 memset(digest
, 0, sizeof(digest
));
11116 if (reply_digest(p
, req
, header
, sipmethod
, digest
, sizeof(digest
) )) {
11117 /* No way to authenticate */
11120 /* Now we have a reply digest */
11121 p
->options
->auth
= digest
;
11122 p
->options
->authheader
= respheader
;
11123 return transmit_invite(p
, sipmethod
, sipmethod
== SIP_INVITE
, init
);
11126 /*! \brief reply to authentication for outbound registrations
11127 \return Returns -1 if we have no auth
11128 \note This is used for register= servers in sip.conf, SIP proxies we register
11129 with for receiving calls from. */
11130 static int reply_digest(struct sip_pvt
*p
, struct sip_request
*req
, char *header
, int sipmethod
, char *digest
, int digest_len
)
11134 char oldnonce
[256];
11136 /* table of recognised keywords, and places where they should be copied */
11141 { "realm=", ast_string_field_index(p
, realm
) },
11142 { "nonce=", ast_string_field_index(p
, nonce
) },
11143 { "opaque=", ast_string_field_index(p
, opaque
) },
11144 { "qop=", ast_string_field_index(p
, qop
) },
11145 { "domain=", ast_string_field_index(p
, domain
) },
11149 ast_copy_string(tmp
, get_header(req
, header
), sizeof(tmp
));
11150 if (ast_strlen_zero(tmp
))
11152 if (strncasecmp(tmp
, "Digest ", strlen("Digest "))) {
11153 ast_log(LOG_WARNING
, "missing Digest.\n");
11156 c
= tmp
+ strlen("Digest ");
11157 ast_copy_string(oldnonce
, p
->nonce
, sizeof(oldnonce
));
11158 while (c
&& *(c
= ast_skip_blanks(c
))) { /* lookup for keys */
11159 for (i
= keys
; i
->key
!= NULL
; i
++) {
11160 char *src
, *separator
;
11161 if (strncasecmp(c
, i
->key
, strlen(i
->key
)) != 0)
11163 /* Found. Skip keyword, take text in quotes or up to the separator. */
11164 c
+= strlen(i
->key
);
11172 strsep(&c
, separator
); /* clear separator and move ptr */
11173 ast_string_field_index_set(p
, i
->field_index
, src
);
11176 if (i
->key
== NULL
) /* not found, try ',' */
11179 /* Reset nonce count */
11180 if (strcmp(p
->nonce
, oldnonce
))
11183 /* Save auth data for following registrations */
11185 struct sip_registry
*r
= p
->registry
;
11187 if (strcmp(r
->nonce
, p
->nonce
)) {
11188 ast_string_field_set(r
, realm
, p
->realm
);
11189 ast_string_field_set(r
, nonce
, p
->nonce
);
11190 ast_string_field_set(r
, domain
, p
->domain
);
11191 ast_string_field_set(r
, opaque
, p
->opaque
);
11192 ast_string_field_set(r
, qop
, p
->qop
);
11196 return build_reply_digest(p
, sipmethod
, digest
, digest_len
);
11199 /*! \brief Build reply digest
11200 \return Returns -1 if we have no auth
11201 \note Build digest challenge for authentication of peers (for registration)
11202 and users (for calls). Also used for authentication of CANCEL and BYE
11204 static int build_reply_digest(struct sip_pvt
*p
, int method
, char* digest
, int digest_len
)
11211 char resp_hash
[256];
11214 const char *username
;
11215 const char *secret
;
11216 const char *md5secret
;
11217 struct sip_auth
*auth
= NULL
; /* Realm authentication */
11219 if (!ast_strlen_zero(p
->domain
))
11220 ast_copy_string(uri
, p
->domain
, sizeof(uri
));
11221 else if (!ast_strlen_zero(p
->uri
))
11222 ast_copy_string(uri
, p
->uri
, sizeof(uri
));
11224 snprintf(uri
, sizeof(uri
), "sip:%s@%s",p
->username
, ast_inet_ntoa(p
->sa
.sin_addr
));
11226 snprintf(cnonce
, sizeof(cnonce
), "%08lx", ast_random());
11228 /* Check if we have separate auth credentials */
11229 if ((auth
= find_realm_authentication(authl
, p
->realm
))) {
11230 ast_log(LOG_WARNING
, "use realm [%s] from peer [%s][%s]\n",
11231 auth
->username
, p
->peername
, p
->username
);
11232 username
= auth
->username
;
11233 secret
= auth
->secret
;
11234 md5secret
= auth
->md5secret
;
11236 ast_log(LOG_DEBUG
,"Using realm %s authentication for call %s\n", p
->realm
, p
->callid
);
11238 /* No authentication, use peer or register= config */
11239 username
= p
->authname
;
11240 secret
= p
->peersecret
;
11241 md5secret
= p
->peermd5secret
;
11243 if (ast_strlen_zero(username
)) /* We have no authentication */
11246 /* Calculate SIP digest response */
11247 snprintf(a1
,sizeof(a1
),"%s:%s:%s", username
, p
->realm
, secret
);
11248 snprintf(a2
,sizeof(a2
),"%s:%s", sip_methods
[method
].text
, uri
);
11249 if (!ast_strlen_zero(md5secret
))
11250 ast_copy_string(a1_hash
, md5secret
, sizeof(a1_hash
));
11252 ast_md5_hash(a1_hash
,a1
);
11253 ast_md5_hash(a2_hash
,a2
);
11256 if (!ast_strlen_zero(p
->qop
))
11257 snprintf(resp
,sizeof(resp
),"%s:%s:%08x:%s:%s:%s", a1_hash
, p
->nonce
, p
->noncecount
, cnonce
, "auth", a2_hash
);
11259 snprintf(resp
,sizeof(resp
),"%s:%s:%s", a1_hash
, p
->nonce
, a2_hash
);
11260 ast_md5_hash(resp_hash
, resp
);
11261 /* XXX We hard code our qop to "auth" for now. XXX */
11262 if (!ast_strlen_zero(p
->qop
))
11263 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
);
11265 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
);
11267 append_history(p
, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username
, p
->realm
, p
->noncecount
);
11272 static char show_domains_usage
[] =
11273 "Usage: sip show domains\n"
11274 " Lists all configured SIP local domains.\n"
11275 " Asterisk only responds to SIP messages to local domains.\n";
11277 static char notify_usage
[] =
11278 "Usage: sip notify <type> <peer> [<peer>...]\n"
11279 " Send a NOTIFY message to a SIP peer or peers\n"
11280 " Message types are defined in sip_notify.conf\n";
11282 static char show_users_usage
[] =
11283 "Usage: sip show users [like <pattern>]\n"
11284 " Lists all known SIP users.\n"
11285 " Optional regular expression pattern is used to filter the user list.\n";
11287 static char show_user_usage
[] =
11288 "Usage: sip show user <name> [load]\n"
11289 " Shows all details on one SIP user and the current status.\n"
11290 " Option \"load\" forces lookup of peer in realtime storage.\n";
11292 static char show_inuse_usage
[] =
11293 "Usage: sip show inuse [all]\n"
11294 " List all SIP users and peers usage counters and limits.\n"
11295 " Add option \"all\" to show all devices, not only those with a limit.\n";
11297 static char show_channels_usage
[] =
11298 "Usage: sip show channels\n"
11299 " Lists all currently active SIP channels.\n";
11301 static char show_channel_usage
[] =
11302 "Usage: sip show channel <channel>\n"
11303 " Provides detailed status on a given SIP channel.\n";
11305 static char show_history_usage
[] =
11306 "Usage: sip show history <channel>\n"
11307 " Provides detailed dialog history on a given SIP channel.\n";
11309 static char show_peers_usage
[] =
11310 "Usage: sip show peers [like <pattern>]\n"
11311 " Lists all known SIP peers.\n"
11312 " Optional regular expression pattern is used to filter the peer list.\n";
11314 static char show_peer_usage
[] =
11315 "Usage: sip show peer <name> [load]\n"
11316 " Shows all details on one SIP peer and the current status.\n"
11317 " Option \"load\" forces lookup of peer in realtime storage.\n";
11319 static char prune_realtime_usage
[] =
11320 "Usage: sip prune realtime [peer|user] [<name>|all|like <pattern>]\n"
11321 " Prunes object(s) from the cache.\n"
11322 " Optional regular expression pattern is used to filter the objects.\n";
11324 static char show_reg_usage
[] =
11325 "Usage: sip show registry\n"
11326 " Lists all registration requests and status.\n";
11328 static char debug_usage
[] =
11329 "Usage: sip set debug\n"
11330 " Enables dumping of SIP packets for debugging purposes\n\n"
11331 " sip set debug ip <host[:PORT]>\n"
11332 " Enables dumping of SIP packets to and from host.\n\n"
11333 " sip set debug peer <peername>\n"
11334 " Enables dumping of SIP packets to and from host.\n"
11335 " Require peer to be registered.\n";
11337 static char no_debug_usage
[] =
11338 "Usage: sip set debug off\n"
11339 " Disables dumping of SIP packets for debugging purposes\n";
11341 static char no_history_usage
[] =
11342 "Usage: sip history off\n"
11343 " Disables recording of SIP dialog history for debugging purposes\n";
11345 static char history_usage
[] =
11346 "Usage: sip history\n"
11347 " Enables recording of SIP dialog history for debugging purposes.\n"
11348 "Use 'sip show history' to view the history of a call number.\n";
11350 static char sip_reload_usage
[] =
11351 "Usage: sip reload\n"
11352 " Reloads SIP configuration from sip.conf\n";
11354 static char show_subscriptions_usage
[] =
11355 "Usage: sip show subscriptions\n"
11356 " Lists active SIP subscriptions for extension states\n";
11358 static char show_objects_usage
[] =
11359 "Usage: sip show objects\n"
11360 " Lists status of known SIP objects\n";
11362 static char show_settings_usage
[] =
11363 "Usage: sip show settings\n"
11364 " Provides detailed list of the configuration of the SIP channel.\n";
11366 /*! \brief Read SIP header (dialplan function) */
11367 static int func_header_read(struct ast_channel
*chan
, char *function
, char *data
, char *buf
, size_t len
)
11370 const char *content
= NULL
;
11371 AST_DECLARE_APP_ARGS(args
,
11372 AST_APP_ARG(header
);
11373 AST_APP_ARG(number
);
11375 int i
, number
, start
= 0;
11377 if (ast_strlen_zero(data
)) {
11378 ast_log(LOG_WARNING
, "This function requires a header name.\n");
11382 ast_channel_lock(chan
);
11383 if (chan
->tech
!= &sip_tech
&& chan
->tech
!= &sip_tech_info
) {
11384 ast_log(LOG_WARNING
, "This function can only be used on SIP channels.\n");
11385 ast_channel_unlock(chan
);
11389 AST_STANDARD_APP_ARGS(args
, data
);
11390 if (!args
.number
) {
11393 sscanf(args
.number
, "%d", &number
);
11398 p
= chan
->tech_pvt
;
11400 /* If there is no private structure, this channel is no longer alive */
11402 ast_channel_unlock(chan
);
11406 for (i
= 0; i
< number
; i
++)
11407 content
= __get_header(&p
->initreq
, args
.header
, &start
);
11409 if (ast_strlen_zero(content
)) {
11410 ast_channel_unlock(chan
);
11414 ast_copy_string(buf
, content
, len
);
11415 ast_channel_unlock(chan
);
11420 static struct ast_custom_function sip_header_function
= {
11421 .name
= "SIP_HEADER",
11422 .synopsis
= "Gets the specified SIP header",
11423 .syntax
= "SIP_HEADER(<name>[,<number>])",
11424 .desc
= "Since there are several headers (such as Via) which can occur multiple\n"
11425 "times, SIP_HEADER takes an optional second argument to specify which header with\n"
11426 "that name to retrieve. Headers start at offset 1.\n",
11427 .read
= func_header_read
,
11430 /*! \brief Dial plan function to check if domain is local */
11431 static int func_check_sipdomain(struct ast_channel
*chan
, char *cmd
, char *data
, char *buf
, size_t len
)
11433 if (ast_strlen_zero(data
)) {
11434 ast_log(LOG_WARNING
, "CHECKSIPDOMAIN requires an argument - A domain name\n");
11437 if (check_sip_domain(data
, NULL
, 0))
11438 ast_copy_string(buf
, data
, len
);
11444 static struct ast_custom_function checksipdomain_function
= {
11445 .name
= "CHECKSIPDOMAIN",
11446 .synopsis
= "Checks if domain is a local domain",
11447 .syntax
= "CHECKSIPDOMAIN(<domain|IP>)",
11448 .read
= func_check_sipdomain
,
11449 .desc
= "This function checks if the domain in the argument is configured\n"
11450 "as a local SIP domain that this Asterisk server is configured to handle.\n"
11451 "Returns the domain name if it is locally handled, otherwise an empty string.\n"
11452 "Check the domain= configuration in sip.conf\n",
11455 /*! \brief ${SIPPEER()} Dialplan function - reads peer data */
11456 static int function_sippeer(struct ast_channel
*chan
, char *cmd
, char *data
, char *buf
, size_t len
)
11458 struct sip_peer
*peer
;
11461 if ((colname
= strchr(data
, ':'))) /*! \todo Will be deprecated after 1.4 */
11463 else if ((colname
= strchr(data
, '|')))
11468 if (!(peer
= find_peer(data
, NULL
, 1)))
11471 if (!strcasecmp(colname
, "ip")) {
11472 ast_copy_string(buf
, peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(peer
->addr
.sin_addr
) : "", len
);
11473 } else if (!strcasecmp(colname
, "status")) {
11474 peer_status(peer
, buf
, len
);
11475 } else if (!strcasecmp(colname
, "language")) {
11476 ast_copy_string(buf
, peer
->language
, len
);
11477 } else if (!strcasecmp(colname
, "regexten")) {
11478 ast_copy_string(buf
, peer
->regexten
, len
);
11479 } else if (!strcasecmp(colname
, "limit")) {
11480 snprintf(buf
, len
, "%d", peer
->call_limit
);
11481 } else if (!strcasecmp(colname
, "curcalls")) {
11482 snprintf(buf
, len
, "%d", peer
->inUse
);
11483 } else if (!strcasecmp(colname
, "accountcode")) {
11484 ast_copy_string(buf
, peer
->accountcode
, len
);
11485 } else if (!strcasecmp(colname
, "useragent")) {
11486 ast_copy_string(buf
, peer
->useragent
, len
);
11487 } else if (!strcasecmp(colname
, "mailbox")) {
11488 ast_copy_string(buf
, peer
->mailbox
, len
);
11489 } else if (!strcasecmp(colname
, "context")) {
11490 ast_copy_string(buf
, peer
->context
, len
);
11491 } else if (!strcasecmp(colname
, "expire")) {
11492 snprintf(buf
, len
, "%d", peer
->expire
);
11493 } else if (!strcasecmp(colname
, "dynamic")) {
11494 ast_copy_string(buf
, (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
) ? "yes" : "no"), len
);
11495 } else if (!strcasecmp(colname
, "callerid_name")) {
11496 ast_copy_string(buf
, peer
->cid_name
, len
);
11497 } else if (!strcasecmp(colname
, "callerid_num")) {
11498 ast_copy_string(buf
, peer
->cid_num
, len
);
11499 } else if (!strcasecmp(colname
, "codecs")) {
11500 ast_getformatname_multiple(buf
, len
-1, peer
->capability
);
11501 } else if (!strncasecmp(colname
, "codec[", 6)) {
11503 int index
= 0, codec
= 0;
11505 codecnum
= colname
+ 6; /* move past the '[' */
11506 codecnum
= strsep(&codecnum
, "]"); /* trim trailing ']' if any */
11507 index
= atoi(codecnum
);
11508 if((codec
= ast_codec_pref_index(&peer
->prefs
, index
))) {
11509 ast_copy_string(buf
, ast_getformatname(codec
), len
);
11513 ASTOBJ_UNREF(peer
, sip_destroy_peer
);
11518 /*! \brief Structure to declare a dialplan function: SIPPEER */
11519 struct ast_custom_function sippeer_function
= {
11521 .synopsis
= "Gets SIP peer information",
11522 .syntax
= "SIPPEER(<peername>[|item])",
11523 .read
= function_sippeer
,
11524 .desc
= "Valid items are:\n"
11525 "- ip (default) The IP address.\n"
11526 "- mailbox The configured mailbox.\n"
11527 "- context The configured context.\n"
11528 "- expire The epoch time of the next expire.\n"
11529 "- dynamic Is it dynamic? (yes/no).\n"
11530 "- callerid_name The configured Caller ID name.\n"
11531 "- callerid_num The configured Caller ID number.\n"
11532 "- codecs The configured codecs.\n"
11533 "- status Status (if qualify=yes).\n"
11534 "- regexten Registration extension\n"
11535 "- limit Call limit (call-limit)\n"
11536 "- curcalls Current amount of calls \n"
11537 " Only available if call-limit is set\n"
11538 "- language Default language for peer\n"
11539 "- accountcode Account code for this peer\n"
11540 "- useragent Current user agent id for peer\n"
11541 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
11545 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
11546 static int function_sipchaninfo_read(struct ast_channel
*chan
, char *cmd
, char *data
, char *buf
, size_t len
)
11553 ast_log(LOG_WARNING
, "This function requires a parameter name.\n");
11557 ast_channel_lock(chan
);
11558 if (chan
->tech
!= &sip_tech
&& chan
->tech
!= &sip_tech_info
) {
11559 ast_log(LOG_WARNING
, "This function can only be used on SIP channels.\n");
11560 ast_channel_unlock(chan
);
11564 p
= chan
->tech_pvt
;
11566 /* If there is no private structure, this channel is no longer alive */
11568 ast_channel_unlock(chan
);
11572 if (!strcasecmp(data
, "peerip")) {
11573 ast_copy_string(buf
, p
->sa
.sin_addr
.s_addr
? ast_inet_ntoa(p
->sa
.sin_addr
) : "", len
);
11574 } else if (!strcasecmp(data
, "recvip")) {
11575 ast_copy_string(buf
, p
->recv
.sin_addr
.s_addr
? ast_inet_ntoa(p
->recv
.sin_addr
) : "", len
);
11576 } else if (!strcasecmp(data
, "from")) {
11577 ast_copy_string(buf
, p
->from
, len
);
11578 } else if (!strcasecmp(data
, "uri")) {
11579 ast_copy_string(buf
, p
->uri
, len
);
11580 } else if (!strcasecmp(data
, "useragent")) {
11581 ast_copy_string(buf
, p
->useragent
, len
);
11582 } else if (!strcasecmp(data
, "peername")) {
11583 ast_copy_string(buf
, p
->peername
, len
);
11584 } else if (!strcasecmp(data
, "t38passthrough")) {
11585 if (p
->t38
.state
== T38_DISABLED
)
11586 ast_copy_string(buf
, "0", sizeof("0"));
11587 else /* T38 is offered or enabled in this call */
11588 ast_copy_string(buf
, "1", sizeof("1"));
11590 ast_channel_unlock(chan
);
11593 ast_channel_unlock(chan
);
11598 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
11599 static struct ast_custom_function sipchaninfo_function
= {
11600 .name
= "SIPCHANINFO",
11601 .synopsis
= "Gets the specified SIP parameter from the current channel",
11602 .syntax
= "SIPCHANINFO(item)",
11603 .read
= function_sipchaninfo_read
,
11604 .desc
= "Valid items are:\n"
11605 "- peerip The IP address of the peer.\n"
11606 "- recvip The source IP address of the peer.\n"
11607 "- from The URI from the From: header.\n"
11608 "- uri The URI from the Contact: header.\n"
11609 "- useragent The useragent.\n"
11610 "- peername The name of the peer.\n"
11611 "- t38passthrough 1 if T38 is offered or enabled in this channel, otherwise 0\n"
11614 /*! \brief Parse 302 Moved temporalily response */
11615 static void parse_moved_contact(struct sip_pvt
*p
, struct sip_request
*req
)
11621 ast_copy_string(tmp
, get_header(req
, "Contact"), sizeof(tmp
));
11622 s
= get_in_brackets(tmp
);
11623 uri
= ast_strdupa(s
);
11624 if (ast_test_flag(&p
->flags
[0], SIP_PROMISCREDIR
)) {
11625 if (!strncasecmp(s
, "sip:", 4))
11627 e
= strchr(s
, ';');
11631 ast_log(LOG_DEBUG
, "Found promiscuous redirection to 'SIP/%s'\n", s
);
11633 ast_string_field_build(p
->owner
, call_forward
, "SIP/%s", s
);
11635 e
= strchr(tmp
, '@');
11640 /* No username part */
11643 e
= strchr(s
, ';'); /* Strip of parameters in the username part */
11646 e
= strchr(domain
, ';'); /* Strip of parameters in the domain part */
11650 if (!strncasecmp(s
, "sip:", 4))
11652 if (option_debug
> 1)
11653 ast_log(LOG_DEBUG
, "Received 302 Redirect to extension '%s' (domain %s)\n", s
, domain
);
11655 pbx_builtin_setvar_helper(p
->owner
, "SIPREDIRECTURI", uri
);
11656 pbx_builtin_setvar_helper(p
->owner
, "SIPDOMAIN", domain
);
11657 ast_string_field_set(p
->owner
, call_forward
, s
);
11662 /*! \brief Check pending actions on SIP call */
11663 static void check_pendings(struct sip_pvt
*p
)
11665 if (ast_test_flag(&p
->flags
[0], SIP_PENDINGBYE
)) {
11666 /* if we can't BYE, then this is really a pending CANCEL */
11667 if (p
->invitestate
== INV_PROCEEDING
|| p
->invitestate
== INV_EARLY_MEDIA
)
11668 transmit_request(p
, SIP_CANCEL
, p
->ocseq
, XMIT_RELIABLE
, FALSE
);
11669 /* Actually don't destroy us yet, wait for the 487 on our original
11670 INVITE, but do set an autodestruct just in case we never get it. */
11672 transmit_request_with_auth(p
, SIP_BYE
, 0, XMIT_RELIABLE
, TRUE
);
11673 ast_clear_flag(&p
->flags
[0], SIP_PENDINGBYE
);
11674 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
11675 } else if (ast_test_flag(&p
->flags
[0], SIP_NEEDREINVITE
)) {
11677 ast_log(LOG_DEBUG
, "Sending pending reinvite on '%s'\n", p
->callid
);
11678 /* Didn't get to reinvite yet, so do it now */
11679 transmit_reinvite_with_sdp(p
);
11680 ast_clear_flag(&p
->flags
[0], SIP_NEEDREINVITE
);
11684 /*! \brief Handle SIP response to INVITE dialogue */
11685 static void handle_response_invite(struct sip_pvt
*p
, int resp
, char *rest
, struct sip_request
*req
, int seqno
)
11687 int outgoing
= ast_test_flag(&p
->flags
[0], SIP_OUTGOING
);
11690 int reinvite
= (p
->owner
&& p
->owner
->_state
== AST_STATE_UP
);
11691 struct ast_channel
*bridgepeer
= NULL
;
11693 if (option_debug
> 3) {
11695 ast_log(LOG_DEBUG
, "SIP response %d to RE-invite on %s call %s\n", resp
, outgoing
? "outgoing" : "incoming", p
->callid
);
11697 ast_log(LOG_DEBUG
, "SIP response %d to standard invite\n", resp
);
11700 if (ast_test_flag(&p
->flags
[0], SIP_ALREADYGONE
)) { /* This call is already gone */
11702 ast_log(LOG_DEBUG
, "Got response on call that is already terminated: %s (ignoring)\n", p
->callid
);
11706 /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
11707 if (p
->initid
> -1) {
11708 /* Don't auto congest anymore since we've gotten something useful back */
11709 ast_sched_del(sched
, p
->initid
);
11713 /* RFC3261 says we must treat every 1xx response (but not 100)
11714 that we don't recognize as if it was 183.
11716 if (resp
> 100 && resp
< 200 && resp
!=101 && resp
!= 180 && resp
!= 183)
11719 /* Any response between 100 and 199 is PROCEEDING */
11720 if (resp
>= 100 && resp
< 200 && p
->invitestate
== INV_CALLING
)
11721 p
->invitestate
= INV_PROCEEDING
;
11723 /* Final response, not 200 ? */
11724 if (resp
>= 300 && (p
->invitestate
== INV_CALLING
|| p
->invitestate
== INV_PROCEEDING
|| p
->invitestate
== INV_EARLY_MEDIA
))
11725 p
->invitestate
= INV_COMPLETED
;
11729 case 100: /* Trying */
11730 case 101: /* Dialog establishment */
11731 if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
11732 sip_cancel_destroy(p
);
11736 case 180: /* 180 Ringing */
11737 if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
11738 sip_cancel_destroy(p
);
11739 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && p
->owner
) {
11740 ast_queue_control(p
->owner
, AST_CONTROL_RINGING
);
11741 if (p
->owner
->_state
!= AST_STATE_UP
) {
11742 ast_setstate(p
->owner
, AST_STATE_RINGING
);
11745 if (find_sdp(req
)) {
11746 p
->invitestate
= INV_EARLY_MEDIA
;
11747 res
= process_sdp(p
, req
);
11748 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && p
->owner
) {
11749 /* Queue a progress frame only if we have SDP in 180 */
11750 ast_queue_control(p
->owner
, AST_CONTROL_PROGRESS
);
11756 case 183: /* Session progress */
11757 if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
11758 sip_cancel_destroy(p
);
11759 /* Ignore 183 Session progress without SDP */
11760 if (find_sdp(req
)) {
11761 p
->invitestate
= INV_EARLY_MEDIA
;
11762 res
= process_sdp(p
, req
);
11763 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && p
->owner
) {
11764 /* Queue a progress frame */
11765 ast_queue_control(p
->owner
, AST_CONTROL_PROGRESS
);
11771 case 200: /* 200 OK on invite - someone's answering our call */
11772 if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
11773 sip_cancel_destroy(p
);
11775 if (find_sdp(req
)) {
11776 if ((res
= process_sdp(p
, req
)) && !ast_test_flag(req
, SIP_PKT_IGNORE
))
11778 /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
11779 /* For re-invites, we try to recover */
11780 ast_set_flag(&p
->flags
[0], SIP_PENDINGBYE
);
11783 /* Parse contact header for continued conversation */
11784 /* When we get 200 OK, we know which device (and IP) to contact for this call */
11785 /* This is important when we have a SIP proxy between us and the phone */
11787 update_call_counter(p
, DEC_CALL_RINGING
);
11788 parse_ok_contact(p
, req
);
11789 if(set_address_from_contact(p
)) {
11790 /* Bad contact - we don't know how to reach this device */
11791 /* We need to ACK, but then send a bye */
11792 /* OEJ: Possible issue that may need a check:
11793 If we have a proxy route between us and the device,
11794 should we care about resolving the contact
11795 or should we just send it?
11797 if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
11798 ast_set_flag(&p
->flags
[0], SIP_PENDINGBYE
);
11801 /* Save Record-Route for any later requests we make on this dialogue */
11802 build_route(p
, req
, 1);
11805 if (p
->owner
&& (p
->owner
->_state
== AST_STATE_UP
) && (bridgepeer
= ast_bridged_channel(p
->owner
))) { /* if this is a re-invite */
11806 struct sip_pvt
*bridgepvt
= NULL
;
11808 if (!bridgepeer
->tech
) {
11809 ast_log(LOG_WARNING
, "Ooooh.. no tech! That's REALLY bad\n");
11812 if (bridgepeer
->tech
== &sip_tech
|| bridgepeer
->tech
== &sip_tech_info
) {
11813 bridgepvt
= (struct sip_pvt
*)(bridgepeer
->tech_pvt
);
11814 if (bridgepvt
->udptl
) {
11815 if (p
->t38
.state
== T38_PEER_REINVITE
) {
11816 sip_handle_t38_reinvite(bridgepeer
, p
, 0);
11817 ast_rtp_set_rtptimers_onhold(p
->rtp
);
11819 ast_rtp_set_rtptimers_onhold(p
->vrtp
); /* Turn off RTP timers while we send fax */
11820 } else if (p
->t38
.state
== T38_DISABLED
&& bridgepeer
&& (bridgepvt
->t38
.state
== T38_ENABLED
)) {
11821 ast_log(LOG_WARNING
, "RTP re-inivte after T38 session not handled yet !\n");
11822 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
11823 /* XXXX Should we really destroy this session here, without any response at all??? */
11824 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
11827 if (option_debug
> 1)
11828 ast_log(LOG_DEBUG
, "Strange... The other side of the bridge does not have a udptl struct\n");
11829 ast_mutex_lock(&bridgepvt
->lock
);
11830 bridgepvt
->t38
.state
= T38_DISABLED
;
11831 ast_mutex_unlock(&bridgepvt
->lock
);
11833 ast_log(LOG_DEBUG
,"T38 state changed to %d on channel %s\n", bridgepvt
->t38
.state
, bridgepeer
->tech
->type
);
11834 p
->t38
.state
= T38_DISABLED
;
11835 if (option_debug
> 1)
11836 ast_log(LOG_DEBUG
,"T38 state changed to %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>");
11839 /* Other side is not a SIP channel */
11840 if (option_debug
> 1)
11841 ast_log(LOG_DEBUG
, "Strange... The other side of the bridge is not a SIP channel\n");
11842 p
->t38
.state
= T38_DISABLED
;
11843 if (option_debug
> 1)
11844 ast_log(LOG_DEBUG
,"T38 state changed to %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>");
11847 if ((p
->t38
.state
== T38_LOCAL_REINVITE
) || (p
->t38
.state
== T38_LOCAL_DIRECT
)) {
11848 /* If there was T38 reinvite and we are supposed to answer with 200 OK than this should set us to T38 negotiated mode */
11849 p
->t38
.state
= T38_ENABLED
;
11851 ast_log(LOG_DEBUG
, "T38 changed state to %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>");
11854 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && p
->owner
) {
11856 ast_queue_control(p
->owner
, AST_CONTROL_ANSWER
);
11857 } else { /* RE-invite */
11858 ast_queue_frame(p
->owner
, &ast_null_frame
);
11861 /* It's possible we're getting an 200 OK after we've tried to disconnect
11862 by sending CANCEL */
11863 /* First send ACK, then send bye */
11864 if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
11865 ast_set_flag(&p
->flags
[0], SIP_PENDINGBYE
);
11867 /* If I understand this right, the branch is different for a non-200 ACK only */
11868 p
->invitestate
= INV_TERMINATED
;
11869 xmitres
= transmit_request(p
, SIP_ACK
, seqno
, XMIT_UNRELIABLE
, TRUE
);
11872 case 407: /* Proxy authentication */
11873 case 401: /* Www auth */
11875 xmitres
= transmit_request(p
, SIP_ACK
, seqno
, XMIT_UNRELIABLE
, FALSE
);
11877 p
->options
->auth_type
= (resp
== 401 ? WWW_AUTH
: PROXY_AUTH
);
11880 ast_string_field_free(p
, theirtag
); /* forget their old tag, so we don't match tags when getting response */
11881 if (!ast_test_flag(req
, SIP_PKT_IGNORE
)) {
11882 char *authenticate
= (resp
== 401 ? "WWW-Authenticate" : "Proxy-Authenticate");
11883 char *authorization
= (resp
== 401 ? "Authorization" : "Proxy-Authorization");
11884 if (p
->authtries
< MAX_AUTHTRIES
)
11885 p
->invitestate
= INV_CALLING
;
11886 if ((p
->authtries
== MAX_AUTHTRIES
) || do_proxy_auth(p
, req
, authenticate
, authorization
, SIP_INVITE
, 1)) {
11887 ast_log(LOG_NOTICE
, "Failed to authenticate on INVITE to '%s'\n", get_header(&p
->initreq
, "From"));
11888 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11889 sip_alreadygone(p
);
11891 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
11896 case 403: /* Forbidden */
11898 xmitres
= transmit_request(p
, SIP_ACK
, seqno
, XMIT_UNRELIABLE
, FALSE
);
11899 ast_log(LOG_WARNING
, "Received response: \"Forbidden\" from '%s'\n", get_header(&p
->initreq
, "From"));
11900 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && p
->owner
)
11901 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
11902 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11903 sip_alreadygone(p
);
11906 case 404: /* Not found */
11907 xmitres
= transmit_request(p
, SIP_ACK
, seqno
, XMIT_UNRELIABLE
, FALSE
);
11908 if (p
->owner
&& !ast_test_flag(req
, SIP_PKT_IGNORE
))
11909 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
11910 sip_alreadygone(p
);
11913 case 481: /* Call leg does not exist */
11914 /* Could be REFER caused INVITE with replaces */
11915 ast_log(LOG_WARNING
, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p
->callid
);
11916 xmitres
= transmit_request(p
, SIP_ACK
, seqno
, XMIT_UNRELIABLE
, FALSE
);
11918 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
11919 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
11921 case 487: /* Cancelled transaction */
11922 /* We have sent CANCEL on an outbound INVITE
11923 This transaction is already scheduled to be killed by sip_hangup().
11925 xmitres
= transmit_request(p
, SIP_ACK
, seqno
, XMIT_UNRELIABLE
, FALSE
);
11926 if (p
->owner
&& !ast_test_flag(req
, SIP_PKT_IGNORE
)) {
11927 ast_queue_hangup(p
->owner
);
11928 append_history(p
, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
11929 } else if (!ast_test_flag(req
, SIP_PKT_IGNORE
)) {
11930 update_call_counter(p
, DEC_CALL_LIMIT
);
11931 append_history(p
, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
11932 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11933 sip_alreadygone(p
);
11936 case 488: /* Not acceptable here */
11937 xmitres
= transmit_request(p
, SIP_ACK
, seqno
, XMIT_UNRELIABLE
, FALSE
);
11938 if (reinvite
&& p
->udptl
) {
11939 /* If this is a T.38 call, we should go back to
11940 audio. If this is an audio call - something went
11941 terribly wrong since we don't renegotiate codecs,
11944 p
->t38
.state
= T38_DISABLED
;
11945 /* Try to reset RTP timers */
11946 ast_rtp_set_rtptimers_onhold(p
->rtp
);
11947 ast_log(LOG_ERROR
, "Got error on T.38 re-invite. Bad configuration. Peer needs to have T.38 disabled.\n");
11949 /*! \bug Is there any way we can go back to the audio call on both
11952 /* While figuring that out, hangup the call */
11953 if (p
->owner
&& !ast_test_flag(req
, SIP_PKT_IGNORE
))
11954 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
11955 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11957 /* We can't set up this call, so give up */
11958 if (p
->owner
&& !ast_test_flag(req
, SIP_PKT_IGNORE
))
11959 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
11960 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11963 case 491: /* Pending */
11964 /* we really should have to wait a while, then retransmit */
11965 /* We should support the retry-after at some point */
11966 /* At this point, we treat this as a congestion */
11967 xmitres
= transmit_request(p
, SIP_ACK
, seqno
, XMIT_UNRELIABLE
, FALSE
);
11968 if (p
->owner
&& !ast_test_flag(req
, SIP_PKT_IGNORE
))
11969 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
11970 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
11973 case 501: /* Not implemented */
11974 xmitres
= transmit_request(p
, SIP_ACK
, seqno
, XMIT_UNRELIABLE
, FALSE
);
11976 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
11979 if (xmitres
== XMIT_ERROR
)
11980 ast_log(LOG_WARNING
, "Could not transmit message in dialog %s\n", p
->callid
);
11983 /* \brief Handle SIP response in REFER transaction
11984 We've sent a REFER, now handle responses to it
11986 static void handle_response_refer(struct sip_pvt
*p
, int resp
, char *rest
, struct sip_request
*req
, int seqno
)
11988 char *auth
= "Proxy-Authenticate";
11989 char *auth2
= "Proxy-Authorization";
11991 /* If no refer structure exists, then do nothing */
11996 case 202: /* Transfer accepted */
11997 /* We need to do something here */
11998 /* The transferee is now sending INVITE to target */
11999 p
->refer
->status
= REFER_ACCEPTED
;
12000 /* Now wait for next message */
12001 if (option_debug
> 2)
12002 ast_log(LOG_DEBUG
, "Got 202 accepted on transfer\n");
12003 /* We should hang along, waiting for NOTIFY's here */
12006 case 401: /* Not www-authorized on SIP method */
12007 case 407: /* Proxy auth */
12008 if (ast_strlen_zero(p
->authname
)) {
12009 ast_log(LOG_WARNING
, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
12010 ast_inet_ntoa(p
->recv
.sin_addr
), ntohs(p
->recv
.sin_port
));
12011 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12014 auth
= "WWW-Authenticate";
12015 auth2
= "Authorization";
12017 if ((p
->authtries
> 1) || do_proxy_auth(p
, req
, auth
, auth2
, SIP_REFER
, 0)) {
12018 ast_log(LOG_NOTICE
, "Failed to authenticate on REFER to '%s'\n", get_header(&p
->initreq
, "From"));
12019 p
->refer
->status
= REFER_NOAUTH
;
12020 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12023 case 481: /* Call leg does not exist */
12025 /* A transfer with Replaces did not work */
12026 /* OEJ: We should Set flag, cancel the REFER, go back
12027 to original call - but right now we can't */
12028 ast_log(LOG_WARNING
, "Remote host can't match REFER request to call '%s'. Giving up.\n", p
->callid
);
12030 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
12031 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12034 case 500: /* Server error */
12035 case 501: /* Method not implemented */
12036 /* Return to the current call onhold */
12037 /* Status flag needed to be reset */
12038 ast_log(LOG_NOTICE
, "SIP transfer to %s failed, call miserably fails. \n", p
->refer
->refer_to
);
12039 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12040 p
->refer
->status
= REFER_FAILED
;
12042 case 603: /* Transfer declined */
12043 ast_log(LOG_NOTICE
, "SIP transfer to %s declined, call miserably fails. \n", p
->refer
->refer_to
);
12044 p
->refer
->status
= REFER_FAILED
;
12045 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12050 /*! \brief Handle responses on REGISTER to services */
12051 static int handle_response_register(struct sip_pvt
*p
, int resp
, char *rest
, struct sip_request
*req
, int ignore
, int seqno
)
12053 int expires
, expires_ms
;
12054 struct sip_registry
*r
;
12058 case 401: /* Unauthorized */
12059 if ((p
->authtries
== MAX_AUTHTRIES
) || do_register_auth(p
, req
, "WWW-Authenticate", "Authorization")) {
12060 ast_log(LOG_NOTICE
, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p
->registry
->username
, p
->registry
->hostname
, p
->authtries
);
12061 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12064 case 403: /* Forbidden */
12065 ast_log(LOG_WARNING
, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p
->registry
->username
, p
->registry
->hostname
);
12066 if (global_regattempts_max
)
12067 p
->registry
->regattempts
= global_regattempts_max
+1;
12068 ast_sched_del(sched
, r
->timeout
);
12070 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12072 case 404: /* Not found */
12073 ast_log(LOG_WARNING
, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p
->registry
->username
,p
->registry
->hostname
);
12074 if (global_regattempts_max
)
12075 p
->registry
->regattempts
= global_regattempts_max
+1;
12076 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12078 ast_sched_del(sched
, r
->timeout
);
12081 case 407: /* Proxy auth */
12082 if ((p
->authtries
== MAX_AUTHTRIES
) || do_register_auth(p
, req
, "Proxy-Authenticate", "Proxy-Authorization")) {
12083 ast_log(LOG_NOTICE
, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p
->initreq
, "From"), p
->authtries
);
12084 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12087 case 479: /* SER: Not able to process the URI - address is wrong in register*/
12088 ast_log(LOG_WARNING
, "Got error 479 on register to %s@%s, giving up (check config)\n", p
->registry
->username
,p
->registry
->hostname
);
12089 if (global_regattempts_max
)
12090 p
->registry
->regattempts
= global_regattempts_max
+1;
12091 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12093 ast_sched_del(sched
, r
->timeout
);
12096 case 200: /* 200 OK */
12098 ast_log(LOG_WARNING
, "Got 200 OK on REGISTER that isn't a register\n");
12099 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12103 r
->regstate
= REG_STATE_REGISTERED
;
12104 r
->regtime
= time(NULL
); /* Reset time of last succesful registration */
12105 manager_event(EVENT_FLAG_SYSTEM
, "Registry", "ChannelDriver: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r
->hostname
, regstate2str(r
->regstate
));
12106 r
->regattempts
= 0;
12108 ast_log(LOG_DEBUG
, "Registration successful\n");
12109 if (r
->timeout
> -1) {
12111 ast_log(LOG_DEBUG
, "Cancelling timeout %d\n", r
->timeout
);
12112 ast_sched_del(sched
, r
->timeout
);
12116 p
->registry
= NULL
;
12117 /* Let this one hang around until we have all the responses */
12118 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
12119 /* ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); */
12121 /* set us up for re-registering */
12122 /* figure out how long we got registered for */
12123 if (r
->expire
> -1)
12124 ast_sched_del(sched
, r
->expire
);
12125 /* according to section 6.13 of RFC, contact headers override
12126 expires headers, so check those first */
12129 /* XXX todo: try to save the extra call */
12130 if (!ast_strlen_zero(get_header(req
, "Contact"))) {
12131 const char *contact
= NULL
;
12132 const char *tmptmp
= NULL
;
12135 contact
= __get_header(req
, "Contact", &start
);
12136 /* this loop ensures we get a contact header about our register request */
12137 if(!ast_strlen_zero(contact
)) {
12138 if( (tmptmp
=strstr(contact
, p
->our_contact
))) {
12145 tmptmp
= strcasestr(contact
, "expires=");
12147 if (sscanf(tmptmp
+ 8, "%d;", &expires
) != 1)
12153 expires
=atoi(get_header(req
, "expires"));
12155 expires
=default_expiry
;
12157 expires_ms
= expires
* 1000;
12158 if (expires
<= EXPIRY_GUARD_LIMIT
)
12159 expires_ms
-= MAX((expires_ms
* EXPIRY_GUARD_PCT
),EXPIRY_GUARD_MIN
);
12161 expires_ms
-= EXPIRY_GUARD_SECS
* 1000;
12163 ast_log(LOG_NOTICE
, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r
->hostname
, expires
, expires_ms
/1000);
12165 r
->refresh
= (int) expires_ms
/ 1000;
12167 /* Schedule re-registration before we expire */
12168 r
->expire
=ast_sched_add(sched
, expires_ms
, sip_reregister
, r
);
12169 ASTOBJ_UNREF(r
, sip_registry_destroy
);
12174 /*! \brief Handle qualification responses (OPTIONS) */
12175 static void handle_response_peerpoke(struct sip_pvt
*p
, int resp
, struct sip_request
*req
)
12177 struct sip_peer
*peer
= p
->relatedpeer
;
12178 int statechanged
, is_reachable
, was_reachable
;
12179 int pingtime
= ast_tvdiff_ms(ast_tvnow(), peer
->ps
);
12182 * Compute the response time to a ping (goes in peer->lastms.)
12183 * -1 means did not respond, 0 means unknown,
12184 * 1..maxms is a valid response, >maxms means late response.
12186 if (pingtime
< 1) /* zero = unknown, so round up to 1 */
12189 /* Now determine new state and whether it has changed.
12190 * Use some helper variables to simplify the writing
12191 * of the expressions.
12193 was_reachable
= peer
->lastms
> 0 && peer
->lastms
<= peer
->maxms
;
12194 is_reachable
= pingtime
<= peer
->maxms
;
12195 statechanged
= peer
->lastms
== 0 /* yes, unknown before */
12196 || was_reachable
!= is_reachable
;
12198 peer
->lastms
= pingtime
;
12200 if (statechanged
) {
12201 const char *s
= is_reachable
? "Reachable" : "Lagged";
12203 ast_log(LOG_NOTICE
, "Peer '%s' is now %s. (%dms / %dms)\n",
12204 peer
->name
, s
, pingtime
, peer
->maxms
);
12205 ast_device_state_changed("SIP/%s", peer
->name
);
12206 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus",
12207 "Peer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
12208 peer
->name
, s
, pingtime
);
12211 if (peer
->pokeexpire
> -1)
12212 ast_sched_del(sched
, peer
->pokeexpire
);
12213 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12215 /* Try again eventually */
12216 peer
->pokeexpire
= ast_sched_add(sched
,
12217 is_reachable
? DEFAULT_FREQ_OK
: DEFAULT_FREQ_NOTOK
,
12218 sip_poke_peer_s
, peer
);
12221 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
12222 static void stop_media_flows(struct sip_pvt
*p
)
12224 /* Immediately stop RTP, VRTP and UDPTL as applicable */
12226 ast_rtp_stop(p
->rtp
);
12228 ast_rtp_stop(p
->vrtp
);
12230 ast_udptl_stop(p
->udptl
);
12233 /*! \brief Handle SIP response in dialogue */
12234 /* XXX only called by handle_request */
12235 static void handle_response(struct sip_pvt
*p
, int resp
, char *rest
, struct sip_request
*req
, int ignore
, int seqno
)
12237 struct ast_channel
*owner
;
12240 const char *c
= get_header(req
, "Cseq");
12241 const char *msg
= strchr(c
, ' ');
12247 sipmethod
= find_sip_method(msg
);
12251 owner
->hangupcause
= hangup_sip2cause(resp
);
12253 /* Acknowledge whatever it is destined for */
12254 if ((resp
>= 100) && (resp
<= 199))
12255 __sip_semi_ack(p
, seqno
, 0, sipmethod
);
12257 __sip_ack(p
, seqno
, 0, sipmethod
);
12259 /* Get their tag if we haven't already */
12260 if (ast_strlen_zero(p
->theirtag
) || (resp
>= 200)) {
12263 gettag(req
, "To", tag
, sizeof(tag
));
12264 ast_string_field_set(p
, theirtag
, tag
);
12266 if (p
->relatedpeer
&& p
->method
== SIP_OPTIONS
) {
12267 /* We don't really care what the response is, just that it replied back.
12268 Well, as long as it's not a 100 response... since we might
12269 need to hang around for something more "definitive" */
12271 handle_response_peerpoke(p
, resp
, req
);
12272 } else if (ast_test_flag(&p
->flags
[0], SIP_OUTGOING
)) {
12274 case 100: /* 100 Trying */
12275 case 101: /* 101 Dialog establishment */
12276 if (sipmethod
== SIP_INVITE
)
12277 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12279 case 183: /* 183 Session Progress */
12280 if (sipmethod
== SIP_INVITE
)
12281 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12283 case 180: /* 180 Ringing */
12284 if (sipmethod
== SIP_INVITE
)
12285 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12287 case 200: /* 200 OK */
12288 p
->authtries
= 0; /* Reset authentication counter */
12289 if (sipmethod
== SIP_MESSAGE
|| sipmethod
== SIP_INFO
) {
12290 /* We successfully transmitted a message
12291 or a video update request in INFO */
12292 /* Nothing happens here - the message is inside a dialog */
12293 } else if (sipmethod
== SIP_INVITE
) {
12294 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12295 } else if (sipmethod
== SIP_NOTIFY
) {
12296 /* They got the notify, this is the end */
12299 ast_log(LOG_WARNING
, "Notify answer on an owned channel? - %s\n", p
->owner
->name
);
12300 ast_queue_hangup(p
->owner
);
12301 } else if (option_debug
> 3)
12302 ast_log(LOG_DEBUG
, "Got OK on REFER Notify message\n");
12304 if (p
->subscribed
== NONE
)
12305 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12307 } else if (sipmethod
== SIP_REGISTER
)
12308 res
= handle_response_register(p
, resp
, rest
, req
, ignore
, seqno
);
12309 else if (sipmethod
== SIP_BYE
) /* Ok, we're ready to go */
12310 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12312 case 202: /* Transfer accepted */
12313 if (sipmethod
== SIP_REFER
)
12314 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12316 case 401: /* Not www-authorized on SIP method */
12317 if (sipmethod
== SIP_INVITE
)
12318 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12319 else if (sipmethod
== SIP_REFER
)
12320 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12321 else if (p
->registry
&& sipmethod
== SIP_REGISTER
)
12322 res
= handle_response_register(p
, resp
, rest
, req
, ignore
, seqno
);
12323 else if (sipmethod
== SIP_BYE
) {
12324 if (ast_strlen_zero(p
->authname
)) {
12325 ast_log(LOG_WARNING
, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12326 msg
, ast_inet_ntoa(p
->recv
.sin_addr
), ntohs(p
->recv
.sin_port
));
12327 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12328 } else if ((p
->authtries
== MAX_AUTHTRIES
) || do_proxy_auth(p
, req
, "WWW-Authenticate", "Authorization", sipmethod
, 0)) {
12329 ast_log(LOG_NOTICE
, "Failed to authenticate on %s to '%s'\n", msg
, get_header(&p
->initreq
, "From"));
12330 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12331 /* We fail to auth bye on our own call, but still needs to tear down the call.
12332 Life, they call it. */
12335 ast_log(LOG_WARNING
, "Got authentication request (401) on unknown %s to '%s'\n", sip_methods
[sipmethod
].text
, get_header(req
, "To"));
12336 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12339 case 403: /* Forbidden - we failed authentication */
12340 if (sipmethod
== SIP_INVITE
)
12341 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12342 else if (p
->registry
&& sipmethod
== SIP_REGISTER
)
12343 res
= handle_response_register(p
, resp
, rest
, req
, ignore
, seqno
);
12345 ast_log(LOG_WARNING
, "Forbidden - maybe wrong password on authentication for %s\n", msg
);
12346 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12349 case 404: /* Not found */
12350 if (p
->registry
&& sipmethod
== SIP_REGISTER
)
12351 res
= handle_response_register(p
, resp
, rest
, req
, ignore
, seqno
);
12352 else if (sipmethod
== SIP_INVITE
)
12353 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12355 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
12357 case 407: /* Proxy auth required */
12358 if (sipmethod
== SIP_INVITE
)
12359 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12360 else if (sipmethod
== SIP_REFER
)
12361 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12362 else if (p
->registry
&& sipmethod
== SIP_REGISTER
)
12363 res
= handle_response_register(p
, resp
, rest
, req
, ignore
, seqno
);
12364 else if (sipmethod
== SIP_BYE
) {
12365 if (ast_strlen_zero(p
->authname
)) {
12366 ast_log(LOG_WARNING
, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12367 msg
, ast_inet_ntoa(p
->recv
.sin_addr
), ntohs(p
->recv
.sin_port
));
12368 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12369 } else if ((p
->authtries
== MAX_AUTHTRIES
) || do_proxy_auth(p
, req
, "Proxy-Authenticate", "Proxy-Authorization", sipmethod
, 0)) {
12370 ast_log(LOG_NOTICE
, "Failed to authenticate on %s to '%s'\n", msg
, get_header(&p
->initreq
, "From"));
12371 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12373 } else /* We can't handle this, giving up in a bad way */
12374 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12377 case 481: /* Call leg does not exist */
12378 if (sipmethod
== SIP_INVITE
) {
12379 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12380 } else if (sipmethod
== SIP_REFER
) {
12381 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12382 } else if (sipmethod
== SIP_BYE
) {
12383 /* The other side has no transaction to bye,
12384 just assume it's all right then */
12385 ast_log(LOG_WARNING
, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods
[sipmethod
].text
, p
->callid
);
12386 } else if (sipmethod
== SIP_CANCEL
) {
12387 /* The other side has no transaction to cancel,
12388 just assume it's all right then */
12389 ast_log(LOG_WARNING
, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods
[sipmethod
].text
, p
->callid
);
12391 ast_log(LOG_WARNING
, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods
[sipmethod
].text
, p
->callid
);
12392 /* Guessing that this is not an important request */
12396 if (sipmethod
== SIP_INVITE
)
12397 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12399 case 488: /* Not acceptable here - codec error */
12400 if (sipmethod
== SIP_INVITE
)
12401 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12403 case 491: /* Pending */
12404 if (sipmethod
== SIP_INVITE
)
12405 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12408 ast_log(LOG_DEBUG
, "Got 491 on %s, unspported. Call ID %s\n", sip_methods
[sipmethod
].text
, p
->callid
);
12409 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12412 case 501: /* Not Implemented */
12413 if (sipmethod
== SIP_INVITE
)
12414 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12415 else if (sipmethod
== SIP_REFER
)
12416 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12418 ast_log(LOG_WARNING
, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p
->sa
.sin_addr
), msg
);
12420 case 603: /* Declined transfer */
12421 if (sipmethod
== SIP_REFER
) {
12422 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12427 if ((resp
>= 300) && (resp
< 700)) {
12428 /* Fatal response */
12429 if ((option_verbose
> 2) && (resp
!= 487))
12430 ast_verbose(VERBOSE_PREFIX_3
"Got SIP response %d \"%s\" back from %s\n", resp
, rest
, ast_inet_ntoa(p
->sa
.sin_addr
));
12432 if (sipmethod
== SIP_INVITE
)
12433 stop_media_flows(p
); /* Immediately stop RTP, VRTP and UDPTL as applicable */
12435 /* XXX Locking issues?? XXX */
12437 case 300: /* Multiple Choices */
12438 case 301: /* Moved permenantly */
12439 case 302: /* Moved temporarily */
12440 case 305: /* Use Proxy */
12441 parse_moved_contact(p
, req
);
12443 case 486: /* Busy here */
12444 case 600: /* Busy everywhere */
12445 case 603: /* Decline */
12447 ast_queue_control(p
->owner
, AST_CONTROL_BUSY
);
12450 \note SIP is incapable of performing a hairpin call, which
12451 is yet another failure of not having a layer 2 (again, YAY
12452 IETF for thinking ahead). So we treat this as a call
12453 forward and hope we end up at the right place... */
12455 ast_log(LOG_DEBUG
, "Hairpin detected, setting up call forward for what it's worth\n");
12457 ast_string_field_build(p
->owner
, call_forward
,
12458 "Local/%s@%s", p
->username
, p
->context
);
12460 case 480: /* Temporarily Unavailable */
12461 case 404: /* Not Found */
12462 case 410: /* Gone */
12463 case 400: /* Bad Request */
12464 case 500: /* Server error */
12465 if (sipmethod
== SIP_REFER
) {
12466 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12470 case 503: /* Service Unavailable */
12471 case 504: /* Server Timeout */
12473 ast_queue_control(p
->owner
, AST_CONTROL_CONGESTION
);
12477 if (owner
&& sipmethod
!= SIP_MESSAGE
&& sipmethod
!= SIP_INFO
)
12478 ast_queue_hangup(p
->owner
);
12481 /* ACK on invite */
12482 if (sipmethod
== SIP_INVITE
)
12483 transmit_request(p
, SIP_ACK
, seqno
, XMIT_UNRELIABLE
, FALSE
);
12484 if (sipmethod
!= SIP_MESSAGE
&& sipmethod
!= SIP_INFO
)
12485 sip_alreadygone(p
);
12487 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12488 } else if ((resp
>= 100) && (resp
< 200)) {
12489 if (sipmethod
== SIP_INVITE
) {
12490 if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
12491 sip_cancel_destroy(p
);
12493 process_sdp(p
, req
);
12495 /* Queue a progress frame */
12496 ast_queue_control(p
->owner
, AST_CONTROL_PROGRESS
);
12500 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
));
12503 /* Responses to OUTGOING SIP requests on INCOMING calls
12504 get handled here. As well as out-of-call message responses */
12505 if (ast_test_flag(req
, SIP_PKT_DEBUG
))
12506 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg
);
12508 if (sipmethod
== SIP_INVITE
&& resp
== 200) {
12509 /* Tags in early session is replaced by the tag in 200 OK, which is
12510 the final reply to our INVITE */
12513 gettag(req
, "To", tag
, sizeof(tag
));
12514 ast_string_field_set(p
, theirtag
, tag
);
12519 if (sipmethod
== SIP_INVITE
) {
12520 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12521 } else if (sipmethod
== SIP_CANCEL
) {
12523 ast_log(LOG_DEBUG
, "Got 200 OK on CANCEL\n");
12525 /* Wait for 487, then destroy */
12526 } else if (sipmethod
== SIP_NOTIFY
) {
12527 /* They got the notify, this is the end */
12531 ast_log(LOG_DEBUG
, "Got 200 OK on NOTIFY for transfer\n");
12533 ast_log(LOG_WARNING
, "Notify answer on an owned channel?\n");
12534 /* ast_queue_hangup(p->owner); Disabled */
12536 if (!p
->subscribed
&& !p
->refer
)
12537 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12539 } else if (sipmethod
== SIP_BYE
)
12540 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12541 else if (sipmethod
== SIP_MESSAGE
|| sipmethod
== SIP_INFO
)
12542 /* We successfully transmitted a message or
12543 a video update request in INFO */
12545 else if (sipmethod
== SIP_BYE
)
12546 /* Ok, we're ready to go */
12547 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12549 case 202: /* Transfer accepted */
12550 if (sipmethod
== SIP_REFER
)
12551 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12553 case 401: /* www-auth */
12555 if (sipmethod
== SIP_REFER
)
12556 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12557 else if (sipmethod
== SIP_INVITE
)
12558 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12559 else if (sipmethod
== SIP_BYE
) {
12560 char *auth
, *auth2
;
12562 auth
= (resp
== 407 ? "Proxy-Authenticate" : "WWW-Authenticate");
12563 auth2
= (resp
== 407 ? "Proxy-Authorization" : "Authorization");
12564 if ((p
->authtries
== MAX_AUTHTRIES
) || do_proxy_auth(p
, req
, auth
, auth2
, sipmethod
, 0)) {
12565 ast_log(LOG_NOTICE
, "Failed to authenticate on %s to '%s'\n", msg
, get_header(&p
->initreq
, "From"));
12566 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12570 case 481: /* Call leg does not exist */
12571 if (sipmethod
== SIP_INVITE
) {
12572 /* Re-invite failed */
12573 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12574 } else if (sipmethod
== SIP_BYE
) {
12575 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
12576 } else if (sipdebug
) {
12577 ast_log (LOG_DEBUG
, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods
[sipmethod
].text
, p
->callid
);
12580 case 501: /* Not Implemented */
12581 if (sipmethod
== SIP_INVITE
)
12582 handle_response_invite(p
, resp
, rest
, req
, seqno
);
12583 else if (sipmethod
== SIP_REFER
)
12584 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12586 case 603: /* Declined transfer */
12587 if (sipmethod
== SIP_REFER
) {
12588 handle_response_refer(p
, resp
, rest
, req
, seqno
);
12592 default: /* Errors without handlers */
12593 if ((resp
>= 100) && (resp
< 200)) {
12594 if (sipmethod
== SIP_INVITE
) { /* re-invite */
12595 if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
12596 sip_cancel_destroy(p
);
12599 if ((resp
>= 300) && (resp
< 700)) {
12600 if ((option_verbose
> 2) && (resp
!= 487))
12601 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
));
12603 case 488: /* Not acceptable here - codec error */
12604 case 603: /* Decline */
12605 case 500: /* Server error */
12606 case 503: /* Service Unavailable */
12607 case 504: /* Server timeout */
12609 if (sipmethod
== SIP_INVITE
) { /* re-invite failed */
12610 sip_cancel_destroy(p
);
12621 /*! \brief Park SIP call support function
12622 Starts in a new thread, then parks the call
12623 XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
12624 audio can't be heard before hangup
12626 static void *sip_park_thread(void *stuff
)
12628 struct ast_channel
*transferee
, *transferer
; /* Chan1: The transferee, Chan2: The transferer */
12629 struct sip_dual
*d
;
12630 struct sip_request req
;
12635 transferee
= d
->chan1
;
12636 transferer
= d
->chan2
;
12637 copy_request(&req
, &d
->req
);
12640 if (!transferee
|| !transferer
) {
12641 ast_log(LOG_ERROR
, "Missing channels for parking! Transferer %s Transferee %s\n", transferer
? "<available>" : "<missing>", transferee
? "<available>" : "<missing>" );
12644 if (option_debug
> 3)
12645 ast_log(LOG_DEBUG
, "SIP Park: Transferer channel %s, Transferee %s\n", transferer
->name
, transferee
->name
);
12647 ast_channel_lock(transferee
);
12648 if (ast_do_masquerade(transferee
)) {
12649 ast_log(LOG_WARNING
, "Masquerade failed.\n");
12650 transmit_response(transferer
->tech_pvt
, "503 Internal error", &req
);
12651 ast_channel_unlock(transferee
);
12654 ast_channel_unlock(transferee
);
12656 res
= ast_park_call(transferee
, transferer
, 0, &ext
);
12659 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
12661 transmit_message_with_text(transferer
->tech_pvt
, "Unable to park call.\n");
12663 /* Then tell the transferer what happened */
12664 sprintf(buf
, "Call parked on extension '%d'", ext
);
12665 transmit_message_with_text(transferer
->tech_pvt
, buf
);
12669 /* Any way back to the current call??? */
12670 /* Transmit response to the REFER request */
12671 transmit_response(transferer
->tech_pvt
, "202 Accepted", &req
);
12673 /* Transfer succeeded */
12674 append_history(transferer
->tech_pvt
, "SIPpark","Parked call on %d", ext
);
12675 transmit_notify_with_sipfrag(transferer
->tech_pvt
, d
->seqno
, "200 OK", TRUE
);
12676 transferer
->hangupcause
= AST_CAUSE_NORMAL_CLEARING
;
12677 ast_hangup(transferer
); /* This will cause a BYE */
12679 ast_log(LOG_DEBUG
, "SIP Call parked on extension '%d'\n", ext
);
12681 transmit_notify_with_sipfrag(transferer
->tech_pvt
, d
->seqno
, "503 Service Unavailable", TRUE
);
12682 append_history(transferer
->tech_pvt
, "SIPpark","Parking failed\n");
12684 ast_log(LOG_DEBUG
, "SIP Call parked failed \n");
12685 /* Do not hangup call */
12690 /*! \brief Park a call using the subsystem in res_features.c
12691 This is executed in a separate thread
12693 static int sip_park(struct ast_channel
*chan1
, struct ast_channel
*chan2
, struct sip_request
*req
, int seqno
)
12695 struct sip_dual
*d
;
12696 struct ast_channel
*transferee
, *transferer
;
12697 /* Chan2m: The transferer, chan1m: The transferee */
12700 transferee
= ast_channel_alloc(0, AST_STATE_DOWN
, 0, 0, chan1
->accountcode
, chan1
->exten
, chan1
->context
, chan1
->amaflags
, "Parking/%s", chan1
->name
);
12701 transferer
= ast_channel_alloc(0, AST_STATE_DOWN
, 0, 0, chan2
->accountcode
, chan2
->exten
, chan2
->context
, chan2
->amaflags
, "SIPPeer/%s", chan2
->name
);
12702 if ((!transferer
) || (!transferee
)) {
12704 transferee
->hangupcause
= AST_CAUSE_SWITCH_CONGESTION
;
12705 ast_hangup(transferee
);
12708 transferer
->hangupcause
= AST_CAUSE_SWITCH_CONGESTION
;
12709 ast_hangup(transferer
);
12714 /* Make formats okay */
12715 transferee
->readformat
= chan1
->readformat
;
12716 transferee
->writeformat
= chan1
->writeformat
;
12718 /* Prepare for taking over the channel */
12719 ast_channel_masquerade(transferee
, chan1
);
12721 /* Setup the extensions and such */
12722 ast_copy_string(transferee
->context
, chan1
->context
, sizeof(transferee
->context
));
12723 ast_copy_string(transferee
->exten
, chan1
->exten
, sizeof(transferee
->exten
));
12724 transferee
->priority
= chan1
->priority
;
12726 /* We make a clone of the peer channel too, so we can play
12727 back the announcement */
12729 /* Make formats okay */
12730 transferer
->readformat
= chan2
->readformat
;
12731 transferer
->writeformat
= chan2
->writeformat
;
12733 /* Prepare for taking over the channel */
12734 ast_channel_masquerade(transferer
, chan2
);
12736 /* Setup the extensions and such */
12737 ast_copy_string(transferer
->context
, chan2
->context
, sizeof(transferer
->context
));
12738 ast_copy_string(transferer
->exten
, chan2
->exten
, sizeof(transferer
->exten
));
12739 transferer
->priority
= chan2
->priority
;
12741 ast_channel_lock(transferer
);
12742 if (ast_do_masquerade(transferer
)) {
12743 ast_log(LOG_WARNING
, "Masquerade failed :(\n");
12744 ast_channel_unlock(transferer
);
12745 transferer
->hangupcause
= AST_CAUSE_SWITCH_CONGESTION
;
12746 ast_hangup(transferer
);
12749 ast_channel_unlock(transferer
);
12750 if (!transferer
|| !transferee
) {
12753 ast_log(LOG_DEBUG
, "No transferer channel, giving up parking\n");
12757 ast_log(LOG_DEBUG
, "No transferee channel, giving up parking\n");
12761 if ((d
= ast_calloc(1, sizeof(*d
)))) {
12762 pthread_attr_t attr
;
12764 pthread_attr_init(&attr
);
12765 pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
);
12767 /* Save original request for followup */
12768 copy_request(&d
->req
, req
);
12769 d
->chan1
= transferee
; /* Transferee */
12770 d
->chan2
= transferer
; /* Transferer */
12772 if (ast_pthread_create_background(&th
, &attr
, sip_park_thread
, d
) < 0) {
12773 /* Could not start thread */
12774 free(d
); /* We don't need it anymore. If thread is created, d will be free'd
12775 by sip_park_thread() */
12776 pthread_attr_destroy(&attr
);
12779 pthread_attr_destroy(&attr
);
12784 /*! \brief Turn off generator data
12785 XXX Does this function belong in the SIP channel?
12787 static void ast_quiet_chan(struct ast_channel
*chan
)
12789 if (chan
&& chan
->_state
== AST_STATE_UP
) {
12790 if (chan
->generatordata
)
12791 ast_deactivate_generator(chan
);
12795 /*! \brief Attempt transfer of SIP call
12796 This fix for attended transfers on a local PBX */
12797 static int attempt_transfer(struct sip_dual
*transferer
, struct sip_dual
*target
)
12800 struct ast_channel
*peera
= NULL
,
12806 /* We will try to connect the transferee with the target and hangup
12807 all channels to the transferer */
12808 if (option_debug
> 3) {
12809 ast_log(LOG_DEBUG
, "Sip transfer:--------------------\n");
12810 if (transferer
->chan1
)
12811 ast_log(LOG_DEBUG
, "-- Transferer to PBX channel: %s State %s\n", transferer
->chan1
->name
, ast_state2str(transferer
->chan1
->_state
));
12813 ast_log(LOG_DEBUG
, "-- No transferer first channel - odd??? \n");
12815 ast_log(LOG_DEBUG
, "-- Transferer to PBX second channel (target): %s State %s\n", target
->chan1
->name
, ast_state2str(target
->chan1
->_state
));
12817 ast_log(LOG_DEBUG
, "-- No target first channel ---\n");
12818 if (transferer
->chan2
)
12819 ast_log(LOG_DEBUG
, "-- Bridged call to transferee: %s State %s\n", transferer
->chan2
->name
, ast_state2str(transferer
->chan2
->_state
));
12821 ast_log(LOG_DEBUG
, "-- No bridged call to transferee\n");
12823 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)");
12825 ast_log(LOG_DEBUG
, "-- No target second channel ---\n");
12826 ast_log(LOG_DEBUG
, "-- END Sip transfer:--------------------\n");
12828 if (transferer
->chan2
) { /* We have a bridge on the transferer's channel */
12829 peera
= transferer
->chan1
; /* Transferer - PBX -> transferee channel * the one we hangup */
12830 peerb
= target
->chan1
; /* Transferer - PBX -> target channel - This will get lost in masq */
12831 peerc
= transferer
->chan2
; /* Asterisk to Transferee */
12832 peerd
= target
->chan2
; /* Asterisk to Target */
12833 if (option_debug
> 2)
12834 ast_log(LOG_DEBUG
, "SIP transfer: Four channels to handle\n");
12835 } else if (target
->chan2
) { /* Transferer has no bridge (IVR), but transferee */
12836 peera
= target
->chan1
; /* Transferer to PBX -> target channel */
12837 peerb
= transferer
->chan1
; /* Transferer to IVR*/
12838 peerc
= target
->chan2
; /* Asterisk to Target */
12839 peerd
= transferer
->chan2
; /* Nothing */
12840 if (option_debug
> 2)
12841 ast_log(LOG_DEBUG
, "SIP transfer: Three channels to handle\n");
12844 if (peera
&& peerb
&& peerc
&& (peerb
!= peerc
)) {
12845 ast_quiet_chan(peera
); /* Stop generators */
12846 ast_quiet_chan(peerb
);
12847 ast_quiet_chan(peerc
);
12849 ast_quiet_chan(peerd
);
12851 /* Fix CDRs so they're attached to the remaining channel */
12852 if (peera
->cdr
&& peerb
->cdr
)
12853 peerb
->cdr
= ast_cdr_append(peerb
->cdr
, peera
->cdr
);
12854 else if (peera
->cdr
)
12855 peerb
->cdr
= peera
->cdr
;
12858 if (peerb
->cdr
&& peerc
->cdr
)
12859 peerb
->cdr
= ast_cdr_append(peerb
->cdr
, peerc
->cdr
);
12860 else if (peerc
->cdr
)
12861 peerb
->cdr
= peerc
->cdr
;
12864 if (option_debug
> 3)
12865 ast_log(LOG_DEBUG
, "SIP transfer: trying to masquerade %s into %s\n", peerc
->name
, peerb
->name
);
12866 if (ast_channel_masquerade(peerb
, peerc
)) {
12867 ast_log(LOG_WARNING
, "Failed to masquerade %s into %s\n", peerb
->name
, peerc
->name
);
12870 ast_log(LOG_DEBUG
, "SIP transfer: Succeeded to masquerade channels.\n");
12873 ast_log(LOG_NOTICE
, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
12874 if (transferer
->chan1
)
12875 ast_softhangup_nolock(transferer
->chan1
, AST_SOFTHANGUP_DEV
);
12877 ast_softhangup_nolock(target
->chan1
, AST_SOFTHANGUP_DEV
);
12883 /*! \brief Get tag from packet
12885 * \return Returns the pointer to the provided tag buffer,
12886 * or NULL if the tag was not found.
12888 static const char *gettag(const struct sip_request
*req
, const char *header
, char *tagbuf
, int tagbufsize
)
12890 const char *thetag
;
12894 tagbuf
[0] = '\0'; /* reset the buffer */
12895 thetag
= get_header(req
, header
);
12896 thetag
= strcasestr(thetag
, ";tag=");
12899 ast_copy_string(tagbuf
, thetag
, tagbufsize
);
12900 return strsep(&tagbuf
, ";");
12905 /*! \brief Handle incoming notifications */
12906 static int handle_request_notify(struct sip_pvt
*p
, struct sip_request
*req
, struct sockaddr_in
*sin
, int seqno
, char *e
)
12908 /* This is mostly a skeleton for future improvements */
12909 /* Mostly created to return proper answers on notifications on outbound REFER's */
12911 const char *event
= get_header(req
, "Event");
12912 char *eventid
= NULL
;
12915 if( (sep
= strchr(event
, ';')) ) { /* XXX bug here - overwriting string ? */
12920 if (option_debug
> 1 && sipdebug
)
12921 ast_log(LOG_DEBUG
, "Got NOTIFY Event: %s\n", event
);
12923 if (strcmp(event
, "refer")) {
12924 /* We don't understand this event. */
12925 /* Here's room to implement incoming voicemail notifications :-) */
12926 transmit_response(p
, "489 Bad event", req
);
12929 /* Save nesting depth for now, since there might be other events we will
12930 support in the future */
12932 /* Handle REFER notifications */
12937 int success
= TRUE
;
12939 /* EventID for each transfer... EventID is basically the REFER cseq
12941 We are getting notifications on a call that we transfered
12942 We should hangup when we are getting a 200 OK in a sipfrag
12943 Check if we have an owner of this event */
12945 /* Check the content type */
12946 if (strncasecmp(get_header(req
, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
12947 /* We need a sipfrag */
12948 transmit_response(p
, "400 Bad request", req
);
12949 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
12953 /* Get the text of the attachment */
12954 if (get_msg_text(buf
, sizeof(buf
), req
)) {
12955 ast_log(LOG_WARNING
, "Unable to retrieve attachment from NOTIFY %s\n", p
->callid
);
12956 transmit_response(p
, "400 Bad request", req
);
12957 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
12963 A minimal, but complete, implementation can respond with a single
12964 NOTIFY containing either the body:
12967 if the subscription is pending, the body:
12969 if the reference was successful, the body:
12970 SIP/2.0 503 Service Unavailable
12971 if the reference failed, or the body:
12972 SIP/2.0 603 Declined
12974 if the REFER request was accepted before approval to follow the
12975 reference could be obtained and that approval was subsequently denied
12976 (see Section 2.4.7).
12978 If there are several REFERs in the same dialog, we need to
12979 match the ID of the event header...
12981 if (option_debug
> 2)
12982 ast_log(LOG_DEBUG
, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf
);
12983 cmd
= ast_skip_blanks(buf
);
12985 /* We are at SIP/2.0 */
12986 while(*code
&& (*code
> 32)) { /* Search white space */
12990 code
= ast_skip_blanks(code
);
12993 while(*sep
&& (*sep
> 32)) { /* Search white space */
12996 *sep
++ = '\0'; /* Response string */
12997 respcode
= atoi(code
);
12998 switch (respcode
) {
12999 case 100: /* Trying: */
13000 case 101: /* dialog establishment */
13001 /* Don't do anything yet */
13003 case 183: /* Ringing: */
13004 /* Don't do anything yet */
13006 case 200: /* OK: The new call is up, hangup this call */
13007 /* Hangup the call that we are replacing */
13009 case 301: /* Moved permenantly */
13010 case 302: /* Moved temporarily */
13011 /* Do we get the header in the packet in this case? */
13014 case 503: /* Service Unavailable: The new call failed */
13015 /* Cancel transfer, continue the call */
13018 case 603: /* Declined: Not accepted */
13019 /* Cancel transfer, continue the current call */
13024 ast_log(LOG_NOTICE
, "Transfer failed. Sorry. Nothing further to do with this call\n");
13027 /* Confirm that we received this packet */
13028 transmit_response(p
, "200 OK", req
);
13031 if (!p
->lastinvite
)
13032 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13037 /*! \brief Handle incoming OPTIONS request */
13038 static int handle_request_options(struct sip_pvt
*p
, struct sip_request
*req
)
13042 res
= get_destination(p
, req
);
13044 /* XXX Should we authenticate OPTIONS? XXX */
13045 if (ast_strlen_zero(p
->context
))
13046 ast_string_field_set(p
, context
, default_context
);
13048 transmit_response_with_allow(p
, "404 Not Found", req
, 0);
13050 transmit_response_with_allow(p
, "200 OK", req
, 0);
13051 /* Destroy if this OPTIONS was the opening request, but not if
13052 it's in the middle of a normal call flow. */
13053 if (!p
->lastinvite
)
13054 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13059 /*! \brief Handle the transfer part of INVITE with a replaces: header,
13060 meaning a target pickup or an attended transfer */
13061 static int handle_invite_replaces(struct sip_pvt
*p
, struct sip_request
*req
, int debug
, int ignore
, int seqno
, struct sockaddr_in
*sin
)
13063 struct ast_frame
*f
;
13064 int earlyreplace
= 0;
13065 int oneleggedreplace
= 0; /* Call with no bridge, propably IVR or voice message */
13066 struct ast_channel
*c
= p
->owner
; /* Our incoming call */
13067 struct ast_channel
*replacecall
= p
->refer
->refer_call
->owner
; /* The channel we're about to take over */
13068 struct ast_channel
*targetcall
; /* The bridge to the take-over target */
13070 /* Check if we're in ring state */
13071 if (replacecall
->_state
== AST_STATE_RING
)
13074 /* Check if we have a bridge */
13075 if (!(targetcall
= ast_bridged_channel(replacecall
))) {
13076 /* We have no bridge */
13077 if (!earlyreplace
) {
13078 if (option_debug
> 1)
13079 ast_log(LOG_DEBUG
, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall
->name
);
13080 oneleggedreplace
= 1;
13083 if (option_debug
> 3 && targetcall
&& targetcall
->_state
== AST_STATE_RINGING
)
13084 ast_log(LOG_DEBUG
, "SIP transfer: Target channel is in ringing state\n");
13086 if (option_debug
> 3) {
13088 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
);
13090 ast_log(LOG_DEBUG
, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall
->name
);
13094 ast_log(LOG_NOTICE
, "Ignoring this INVITE with replaces in a stupid way.\n");
13095 /* We should answer something here. If we are here, the
13096 call we are replacing exists, so an accepted
13098 transmit_response_with_sdp(p
, "200 OK", req
, XMIT_RELIABLE
);
13099 /* Do something more clever here */
13100 ast_channel_unlock(c
);
13101 ast_mutex_unlock(&p
->refer
->refer_call
->lock
);
13105 /* What to do if no channel ??? */
13106 ast_log(LOG_ERROR
, "Unable to create new channel. Invite/replace failed.\n");
13107 transmit_response_reliable(p
, "503 Service Unavailable", req
);
13108 append_history(p
, "Xfer", "INVITE/Replace Failed. No new channel.");
13109 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13110 ast_mutex_unlock(&p
->refer
->refer_call
->lock
);
13113 append_history(p
, "Xfer", "INVITE/Replace received");
13114 /* We have three channels to play with
13115 channel c: New incoming call
13116 targetcall: Call from PBX to target
13117 p->refer->refer_call: SIP pvt dialog from transferer to pbx.
13118 replacecall: The owner of the previous
13119 We need to masq C into refer_call to connect to
13121 If we are talking to internal audio stream, target call is null.
13124 /* Fake call progress */
13125 transmit_response(p
, "100 Trying", req
);
13126 ast_setstate(c
, AST_STATE_RING
);
13128 /* Masquerade the new call into the referred call to connect to target call
13129 Targetcall is not touched by the masq */
13131 /* Answer the incoming call and set channel to UP state */
13132 transmit_response_with_sdp(p
, "200 OK", req
, XMIT_RELIABLE
);
13134 ast_setstate(c
, AST_STATE_UP
);
13136 /* Stop music on hold and other generators */
13137 ast_quiet_chan(replacecall
);
13138 ast_quiet_chan(targetcall
);
13139 if (option_debug
> 3)
13140 ast_log(LOG_DEBUG
, "Invite/Replaces: preparing to masquerade %s into %s\n", c
->name
, replacecall
->name
);
13141 /* Unlock clone, but not original (replacecall) */
13142 ast_channel_unlock(c
);
13145 ast_mutex_unlock(&p
->refer
->refer_call
->lock
);
13147 /* Make sure that the masq does not free our PVT for the old call */
13148 ast_set_flag(&p
->refer
->refer_call
->flags
[0], SIP_DEFER_BYE_ON_TRANSFER
); /* Delay hangup */
13150 /* Prepare the masquerade - if this does not happen, we will be gone */
13151 if(ast_channel_masquerade(replacecall
, c
))
13152 ast_log(LOG_ERROR
, "Failed to masquerade C into Replacecall\n");
13153 else if (option_debug
> 3)
13154 ast_log(LOG_DEBUG
, "Invite/Replaces: Going to masquerade %s into %s\n", c
->name
, replacecall
->name
);
13156 /* The masquerade will happen as soon as someone reads a frame from the channel */
13158 /* C should now be in place of replacecall */
13159 /* ast_read needs to lock channel */
13160 ast_channel_unlock(c
);
13162 if (earlyreplace
|| oneleggedreplace
) {
13163 /* Force the masq to happen */
13164 if ((f
= ast_read(replacecall
))) { /* Force the masq to happen */
13167 if (option_debug
> 3)
13168 ast_log(LOG_DEBUG
, "Invite/Replace: Could successfully read frame from RING channel!\n");
13170 ast_log(LOG_WARNING
, "Invite/Replace: Could not read frame from RING channel \n");
13172 c
->hangupcause
= AST_CAUSE_SWITCH_CONGESTION
;
13173 ast_channel_unlock(replacecall
);
13174 } else { /* Bridged call, UP channel */
13175 if ((f
= ast_read(replacecall
))) { /* Force the masq to happen */
13179 if (option_debug
> 2)
13180 ast_log(LOG_DEBUG
, "Invite/Replace: Could successfully read frame from channel! Masq done.\n");
13182 ast_log(LOG_WARNING
, "Invite/Replace: Could not read frame from channel. Transfer failed\n");
13184 ast_channel_unlock(replacecall
);
13186 ast_mutex_unlock(&p
->refer
->refer_call
->lock
);
13188 ast_setstate(c
, AST_STATE_DOWN
);
13189 if (option_debug
> 3) {
13190 struct ast_channel
*test
;
13191 ast_log(LOG_DEBUG
, "After transfer:----------------------------\n");
13192 ast_log(LOG_DEBUG
, " -- C: %s State %s\n", c
->name
, ast_state2str(c
->_state
));
13194 ast_log(LOG_DEBUG
, " -- replacecall: %s State %s\n", replacecall
->name
, ast_state2str(replacecall
->_state
));
13196 ast_log(LOG_DEBUG
, " -- P->owner: %s State %s\n", p
->owner
->name
, ast_state2str(p
->owner
->_state
));
13197 test
= ast_bridged_channel(p
->owner
);
13199 ast_log(LOG_DEBUG
, " -- Call bridged to P->owner: %s State %s\n", test
->name
, ast_state2str(test
->_state
));
13201 ast_log(LOG_DEBUG
, " -- No call bridged to C->owner \n");
13203 ast_log(LOG_DEBUG
, " -- No channel yet \n");
13204 ast_log(LOG_DEBUG
, "End After transfer:----------------------------\n");
13207 ast_channel_unlock(p
->owner
); /* Unlock new owner */
13208 ast_mutex_unlock(&p
->lock
); /* Unlock SIP structure */
13210 /* The call should be down with no ast_channel, so hang it up */
13211 c
->tech_pvt
= NULL
;
13217 /*! \brief Handle incoming INVITE request
13218 \note If the INVITE has a Replaces header, it is part of an
13219 * attended transfer. If so, we do not go through the dial
13220 * plan but tries to find the active call and masquerade
13223 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
)
13227 const char *p_replaces
;
13228 char *replace_id
= NULL
;
13229 const char *required
;
13230 unsigned int required_profile
= 0;
13231 struct ast_channel
*c
= NULL
; /* New channel */
13234 /* Find out what they support */
13235 if (!p
->sipoptions
) {
13236 const char *supported
= get_header(req
, "Supported");
13237 if (!ast_strlen_zero(supported
))
13238 parse_sip_options(p
, supported
);
13241 /* Find out what they require */
13242 required
= get_header(req
, "Require");
13243 if (!ast_strlen_zero(required
)) {
13244 required_profile
= parse_sip_options(NULL
, required
);
13245 if (required_profile
&& required_profile
!= SIP_OPT_REPLACES
) {
13246 /* At this point we only support REPLACES */
13247 transmit_response_with_unsupported(p
, "420 Bad extension (unsupported)", req
, required
);
13248 ast_log(LOG_WARNING
,"Received SIP INVITE with unsupported required extension: %s\n", required
);
13249 p
->invitestate
= INV_COMPLETED
;
13250 if (!p
->lastinvite
)
13251 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13256 /* Check if this is a loop */
13257 if (ast_test_flag(&p
->flags
[0], SIP_OUTGOING
) && p
->owner
&& (p
->owner
->_state
!= AST_STATE_UP
)) {
13258 /* This is a call to ourself. Send ourselves an error code and stop
13259 processing immediately, as SIP really has no good mechanism for
13260 being able to call yourself */
13261 /* If pedantic is on, we need to check the tags. If they're different, this is
13262 in fact a forked call through a SIP proxy somewhere. */
13263 transmit_response(p
, "482 Loop Detected", req
);
13264 p
->invitestate
= INV_COMPLETED
;
13265 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13269 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && p
->pendinginvite
) {
13270 /* We already have a pending invite. Sorry. You are on hold. */
13271 transmit_response(p
, "491 Request Pending", req
);
13273 ast_log(LOG_DEBUG
, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p
->callid
);
13274 /* Don't destroy dialog here */
13278 p_replaces
= get_header(req
, "Replaces");
13279 if (!ast_strlen_zero(p_replaces
)) {
13280 /* We have a replaces header */
13282 char *fromtag
= NULL
;
13283 char *totag
= NULL
;
13288 if (option_debug
> 2)
13289 ast_log(LOG_DEBUG
, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p
->callid
);
13290 transmit_response(p
, "400 Bad request", req
); /* The best way to not not accept the transfer */
13291 /* Do not destroy existing call */
13295 if (sipdebug
&& option_debug
> 2)
13296 ast_log(LOG_DEBUG
, "INVITE part of call transfer. Replaces [%s]\n", p_replaces
);
13297 /* Create a buffer we can manipulate */
13298 replace_id
= ast_strdupa(p_replaces
);
13299 ast_uri_decode(replace_id
);
13301 if (!p
->refer
&& !sip_refer_allocate(p
)) {
13302 transmit_response(p
, "500 Server Internal Error", req
);
13303 append_history(p
, "Xfer", "INVITE/Replace Failed. Out of memory.");
13304 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13305 p
->invitestate
= INV_COMPLETED
;
13309 /* Todo: (When we find phones that support this)
13310 if the replaces header contains ";early-only"
13311 we can only replace the call in early
13312 stage, not after it's up.
13314 If it's not in early mode, 486 Busy.
13317 /* Skip leading whitespace */
13318 replace_id
= ast_skip_blanks(replace_id
);
13320 start
= replace_id
;
13321 while ( (ptr
= strsep(&start
, ";")) ) {
13322 ptr
= ast_skip_blanks(ptr
); /* XXX maybe unnecessary ? */
13323 if ( (to
= strcasestr(ptr
, "to-tag=") ) )
13324 totag
= to
+ 7; /* skip the keyword */
13325 else if ( (to
= strcasestr(ptr
, "from-tag=") ) ) {
13326 fromtag
= to
+ 9; /* skip the keyword */
13327 fromtag
= strsep(&fromtag
, "&"); /* trim what ? */
13331 if (sipdebug
&& option_debug
> 3)
13332 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>");
13335 /* Try to find call that we are replacing
13336 If we have a Replaces header, we need to cancel that call if we succeed with this call
13338 if ((p
->refer
->refer_call
= get_sip_pvt_byid_locked(replace_id
, totag
, fromtag
)) == NULL
) {
13339 ast_log(LOG_NOTICE
, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id
);
13340 transmit_response(p
, "481 Call Leg Does Not Exist (Replaces)", req
);
13344 /* At this point, bot the pvt and the owner of the call to be replaced is locked */
13346 /* The matched call is the call from the transferer to Asterisk .
13347 We want to bridge the bridged part of the call to the
13348 incoming invite, thus taking over the refered call */
13350 if (p
->refer
->refer_call
== p
) {
13351 ast_log(LOG_NOTICE
, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id
, p
->callid
);
13352 p
->refer
->refer_call
= NULL
;
13353 transmit_response(p
, "400 Bad request", req
); /* The best way to not not accept the transfer */
13357 if (!error
&& !p
->refer
->refer_call
->owner
) {
13358 /* Oops, someting wrong anyway, no owner, no call */
13359 ast_log(LOG_NOTICE
, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id
);
13360 /* Check for better return code */
13361 transmit_response(p
, "481 Call Leg Does Not Exist (Replace)", req
);
13365 if (!error
&& p
->refer
->refer_call
->owner
->_state
!= AST_STATE_RING
&& p
->refer
->refer_call
->owner
->_state
!= AST_STATE_UP
) {
13366 ast_log(LOG_NOTICE
, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id
);
13367 transmit_response(p
, "603 Declined (Replaces)", req
);
13371 if (error
) { /* Give up this dialog */
13372 append_history(p
, "Xfer", "INVITE/Replace Failed.");
13373 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13374 ast_mutex_unlock(&p
->lock
);
13375 if (p
->refer
->refer_call
) {
13376 ast_mutex_unlock(&p
->refer
->refer_call
->lock
);
13377 ast_channel_unlock(p
->refer
->refer_call
->owner
);
13379 p
->invitestate
= INV_COMPLETED
;
13385 /* Check if this is an INVITE that sets up a new dialog or
13386 a re-invite in an existing dialog */
13388 if (!ast_test_flag(req
, SIP_PKT_IGNORE
)) {
13389 int newcall
= (p
->initreq
.headers
? TRUE
: FALSE
);
13391 sip_cancel_destroy(p
);
13392 /* This also counts as a pending invite */
13393 p
->pendinginvite
= seqno
;
13396 copy_request(&p
->initreq
, req
); /* Save this INVITE as the transaction basis */
13397 if (!p
->owner
) { /* Not a re-invite */
13399 ast_verbose("Using INVITE request as basis request - %s\n", p
->callid
);
13401 append_history(p
, "Invite", "New call: %s", p
->callid
);
13402 parse_ok_contact(p
, req
);
13403 } else { /* Re-invite on existing call */
13404 ast_clear_flag(&p
->flags
[0], SIP_OUTGOING
); /* This is now an inbound dialog */
13405 /* Handle SDP here if we already have an owner */
13406 if (find_sdp(req
)) {
13407 if (process_sdp(p
, req
)) {
13408 transmit_response(p
, "488 Not acceptable here", req
);
13409 if (!p
->lastinvite
)
13410 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13414 p
->jointcapability
= p
->capability
;
13415 if (option_debug
> 2)
13416 ast_log(LOG_DEBUG
, "Hm.... No sdp for the moment\n");
13417 /* Some devices signal they want to be put off hold by sending a re-invite
13418 *without* an SDP, which is supposed to mean "Go back to your state"
13419 and since they put os on remote hold, we go back to off hold */
13420 if (ast_test_flag(&p
->flags
[1], SIP_PAGE2_CALL_ONHOLD
))
13421 change_hold_state(p
, req
, FALSE
, 0);
13423 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
)) /* This is a response, note what it was for */
13424 append_history(p
, "ReInv", "Re-invite received");
13427 ast_verbose("Ignoring this INVITE request\n");
13430 if (!p
->lastinvite
&& !ast_test_flag(req
, SIP_PKT_IGNORE
) && !p
->owner
) {
13431 /* This is a new invite */
13432 /* Handle authentication if this is our first invite */
13433 res
= check_user(p
, req
, SIP_INVITE
, e
, XMIT_RELIABLE
, sin
);
13434 if (res
== AUTH_CHALLENGE_SENT
) {
13435 p
->invitestate
= INV_COMPLETED
; /* Needs to restart in another INVITE transaction */
13438 if (res
< 0) { /* Something failed in authentication */
13439 if (res
== AUTH_FAKE_AUTH
) {
13440 ast_log(LOG_NOTICE
, "Sending fake auth rejection for user %s\n", get_header(req
, "From"));
13441 transmit_fake_auth_response(p
, req
, 1);
13443 ast_log(LOG_NOTICE
, "Failed to authenticate user %s\n", get_header(req
, "From"));
13444 transmit_response_reliable(p
, "403 Forbidden", req
);
13446 p
->invitestate
= INV_COMPLETED
;
13447 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13448 ast_string_field_free(p
, theirtag
);
13452 /* We have a succesful authentication, process the SDP portion if there is one */
13453 if (find_sdp(req
)) {
13454 if (process_sdp(p
, req
)) {
13455 /* Unacceptable codecs */
13456 transmit_response_reliable(p
, "488 Not acceptable here", req
);
13457 p
->invitestate
= INV_COMPLETED
;
13458 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13460 ast_log(LOG_DEBUG
, "No compatible codecs for this SIP call.\n");
13463 } else { /* No SDP in invite, call control session */
13464 p
->jointcapability
= p
->capability
;
13465 if (option_debug
> 1)
13466 ast_log(LOG_DEBUG
, "No SDP in Invite, third party call control\n");
13469 /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
13470 /* This seems redundant ... see !p-owner above */
13472 ast_queue_frame(p
->owner
, &ast_null_frame
);
13475 /* Initialize the context if it hasn't been already */
13476 if (ast_strlen_zero(p
->context
))
13477 ast_string_field_set(p
, context
, default_context
);
13480 /* Check number of concurrent calls -vs- incoming limit HERE */
13482 ast_log(LOG_DEBUG
, "Checking SIP call limits for device %s\n", p
->username
);
13483 if ((res
= update_call_counter(p
, INC_CALL_LIMIT
))) {
13485 ast_log(LOG_NOTICE
, "Failed to place call for user %s, too many calls\n", p
->username
);
13486 transmit_response_reliable(p
, "480 Temporarily Unavailable (Call limit) ", req
);
13487 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13488 p
->invitestate
= INV_COMPLETED
;
13492 gotdest
= get_destination(p
, NULL
); /* Get destination right away */
13493 get_rdnis(p
, NULL
); /* Get redirect information */
13494 extract_uri(p
, req
); /* Get the Contact URI */
13495 build_contact(p
); /* Build our contact header */
13498 ast_rtp_setdtmf(p
->rtp
, ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_RFC2833
);
13499 ast_rtp_setdtmfcompensate(p
->rtp
, ast_test_flag(&p
->flags
[1], SIP_PAGE2_RFC2833_COMPENSATE
));
13502 if (!replace_id
&& gotdest
) { /* No matching extension found */
13503 if (gotdest
== 1 && ast_test_flag(&p
->flags
[1], SIP_PAGE2_ALLOWOVERLAP
))
13504 transmit_response_reliable(p
, "484 Address Incomplete", req
);
13506 transmit_response_reliable(p
, "404 Not Found", req
);
13507 p
->invitestate
= INV_COMPLETED
;
13508 update_call_counter(p
, DEC_CALL_LIMIT
);
13509 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13512 /* If no extension was specified, use the s one */
13513 /* Basically for calling to IP/Host name only */
13514 if (ast_strlen_zero(p
->exten
))
13515 ast_string_field_set(p
, exten
, "s");
13516 /* Initialize our tag */
13518 make_our_tag(p
->tag
, sizeof(p
->tag
));
13519 /* First invitation - create the channel */
13520 c
= sip_new(p
, AST_STATE_DOWN
, S_OR(p
->username
, NULL
));
13523 /* Save Record-Route for any later requests we make on this dialogue */
13524 build_route(p
, req
, 0);
13527 /* Pre-lock the call */
13528 ast_channel_lock(c
);
13532 if (option_debug
> 1 && sipdebug
) {
13533 if (!ast_test_flag(req
, SIP_PKT_IGNORE
))
13534 ast_log(LOG_DEBUG
, "Got a SIP re-invite for call %s\n", p
->callid
);
13536 ast_log(LOG_DEBUG
, "Got a SIP re-transmit of INVITE for call %s\n", p
->callid
);
13542 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && p
)
13543 p
->lastinvite
= seqno
;
13545 if (replace_id
) { /* Attended transfer or call pickup - we're the target */
13546 /* Go and take over the target call */
13547 if (sipdebug
&& option_debug
> 3)
13548 ast_log(LOG_DEBUG
, "Sending this call to the invite/replcaes handler %s\n", p
->callid
);
13549 return handle_invite_replaces(p
, req
, debug
, ast_test_flag(req
, SIP_PKT_IGNORE
), seqno
, sin
);
13553 if (c
) { /* We have a call -either a new call or an old one (RE-INVITE) */
13554 switch(c
->_state
) {
13555 case AST_STATE_DOWN
:
13556 if (option_debug
> 1)
13557 ast_log(LOG_DEBUG
, "%s: New call is still down.... Trying... \n", c
->name
);
13558 transmit_response(p
, "100 Trying", req
);
13559 p
->invitestate
= INV_PROCEEDING
;
13560 ast_setstate(c
, AST_STATE_RING
);
13561 if (strcmp(p
->exten
, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
13562 enum ast_pbx_result res
;
13564 res
= ast_pbx_start(c
);
13567 case AST_PBX_FAILED
:
13568 ast_log(LOG_WARNING
, "Failed to start PBX :(\n");
13569 p
->invitestate
= INV_COMPLETED
;
13570 if (ast_test_flag(req
, SIP_PKT_IGNORE
))
13571 transmit_response(p
, "503 Unavailable", req
);
13573 transmit_response_reliable(p
, "503 Unavailable", req
);
13575 case AST_PBX_CALL_LIMIT
:
13576 ast_log(LOG_WARNING
, "Failed to start PBX (call limit reached) \n");
13577 p
->invitestate
= INV_COMPLETED
;
13578 if (ast_test_flag(req
, SIP_PKT_IGNORE
))
13579 transmit_response(p
, "480 Temporarily Unavailable", req
);
13581 transmit_response_reliable(p
, "480 Temporarily Unavailable", req
);
13583 case AST_PBX_SUCCESS
:
13584 /* nothing to do */
13590 /* Unlock locks so ast_hangup can do its magic */
13591 ast_mutex_unlock(&c
->lock
);
13592 ast_mutex_unlock(&p
->lock
);
13594 ast_mutex_lock(&p
->lock
);
13597 } else { /* Pickup call in call group */
13598 ast_channel_unlock(c
);
13599 if (ast_pickup_call(c
)) {
13600 ast_log(LOG_NOTICE
, "Nothing to pick up for %s\n", p
->callid
);
13601 if (ast_test_flag(req
, SIP_PKT_IGNORE
))
13602 transmit_response(p
, "503 Unavailable", req
); /* OEJ - Right answer? */
13604 transmit_response_reliable(p
, "503 Unavailable", req
);
13605 sip_alreadygone(p
);
13606 /* Unlock locks so ast_hangup can do its magic */
13607 ast_mutex_unlock(&p
->lock
);
13608 c
->hangupcause
= AST_CAUSE_CALL_REJECTED
;
13610 ast_mutex_unlock(&p
->lock
);
13611 ast_setstate(c
, AST_STATE_DOWN
);
13612 c
->hangupcause
= AST_CAUSE_NORMAL_CLEARING
;
13614 p
->invitestate
= INV_COMPLETED
;
13616 ast_mutex_lock(&p
->lock
);
13620 case AST_STATE_RING
:
13621 transmit_response(p
, "100 Trying", req
);
13622 p
->invitestate
= INV_PROCEEDING
;
13624 case AST_STATE_RINGING
:
13625 transmit_response(p
, "180 Ringing", req
);
13626 p
->invitestate
= INV_PROCEEDING
;
13629 if (option_debug
> 1)
13630 ast_log(LOG_DEBUG
, "%s: This call is UP.... \n", c
->name
);
13632 if (p
->t38
.state
== T38_PEER_REINVITE
) {
13633 struct ast_channel
*bridgepeer
= NULL
;
13634 struct sip_pvt
*bridgepvt
= NULL
;
13636 if ((bridgepeer
= ast_bridged_channel(p
->owner
))) {
13637 /* 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*/
13638 /*! XXX: we should also check here does the other side supports t38 at all !!! XXX */
13639 if (bridgepeer
->tech
== &sip_tech
|| bridgepeer
->tech
== &sip_tech_info
) {
13640 bridgepvt
= (struct sip_pvt
*)bridgepeer
->tech_pvt
;
13641 if (bridgepvt
->t38
.state
== T38_DISABLED
) {
13642 if (bridgepvt
->udptl
) { /* If everything is OK with other side's udptl struct */
13643 /* Send re-invite to the bridged channel */
13644 sip_handle_t38_reinvite(bridgepeer
, p
, 1);
13645 } else { /* Something is wrong with peers udptl struct */
13646 ast_log(LOG_WARNING
, "Strange... The other side of the bridge don't have udptl struct\n");
13647 ast_mutex_lock(&bridgepvt
->lock
);
13648 bridgepvt
->t38
.state
= T38_DISABLED
;
13649 ast_mutex_unlock(&bridgepvt
->lock
);
13650 if (option_debug
> 1)
13651 ast_log(LOG_DEBUG
,"T38 state changed to %d on channel %s\n", bridgepvt
->t38
.state
, bridgepeer
->name
);
13652 if (ast_test_flag(req
, SIP_PKT_IGNORE
))
13653 transmit_response(p
, "488 Not acceptable here", req
);
13655 transmit_response_reliable(p
, "488 Not acceptable here", req
);
13659 /* The other side is already setup for T.38 most likely so we need to acknowledge this too */
13660 transmit_response_with_t38_sdp(p
, "200 OK", req
, XMIT_CRITICAL
);
13661 p
->t38
.state
= T38_ENABLED
;
13663 ast_log(LOG_DEBUG
, "T38 state changed to %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>");
13666 /* Other side is not a SIP channel */
13667 if (ast_test_flag(req
, SIP_PKT_IGNORE
))
13668 transmit_response(p
, "488 Not acceptable here", req
);
13670 transmit_response_reliable(p
, "488 Not acceptable here", req
);
13671 p
->t38
.state
= T38_DISABLED
;
13672 if (option_debug
> 1)
13673 ast_log(LOG_DEBUG
,"T38 state changed to %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>");
13675 if (!p
->lastinvite
) /* Only destroy if this is *not* a re-invite */
13676 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13679 /* we are not bridged in a call */
13680 transmit_response_with_t38_sdp(p
, "200 OK", req
, XMIT_CRITICAL
);
13681 p
->t38
.state
= T38_ENABLED
;
13683 ast_log(LOG_DEBUG
,"T38 state changed to %d on channel %s\n", p
->t38
.state
, p
->owner
? p
->owner
->name
: "<none>");
13685 } else if (p
->t38
.state
== T38_DISABLED
) { /* Channel doesn't have T38 offered or enabled */
13688 /* If we are bridged to a channel that has T38 enabled than this is a case of RTP re-invite after T38 session */
13689 /* so handle it here (re-invite other party to RTP) */
13690 struct ast_channel
*bridgepeer
= NULL
;
13691 struct sip_pvt
*bridgepvt
= NULL
;
13692 if ((bridgepeer
= ast_bridged_channel(p
->owner
))) {
13693 if (bridgepeer
->tech
== &sip_tech
|| bridgepeer
->tech
== &sip_tech_info
) {
13694 bridgepvt
= (struct sip_pvt
*)bridgepeer
->tech_pvt
;
13695 /* Does the bridged peer have T38 ? */
13696 if (bridgepvt
->t38
.state
== T38_ENABLED
) {
13697 ast_log(LOG_WARNING
, "RTP re-invite after T38 session not handled yet !\n");
13698 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
13699 if (ast_test_flag(req
, SIP_PKT_IGNORE
))
13700 transmit_response(p
, "488 Not Acceptable Here (unsupported)", req
);
13702 transmit_response_reliable(p
, "488 Not Acceptable Here (unsupported)", req
);
13705 /* No bridged peer with T38 enabled*/
13708 /* Respond to normal re-invite */
13710 /* If this is not a re-invite or something to ignore - it's critical */
13711 transmit_response_with_sdp(p
, "200 OK", req
, (reinvite
|| ast_test_flag(req
, SIP_PKT_IGNORE
)) ? XMIT_UNRELIABLE
: XMIT_CRITICAL
);
13713 p
->invitestate
= INV_TERMINATED
;
13716 ast_log(LOG_WARNING
, "Don't know how to handle INVITE in state %d\n", c
->_state
);
13717 transmit_response(p
, "100 Trying", req
);
13721 if (p
&& (p
->autokillid
== -1)) {
13724 if (!p
->jointcapability
)
13725 msg
= "488 Not Acceptable Here (codec error)";
13727 ast_log(LOG_NOTICE
, "Unable to create/find SIP channel for this INVITE\n");
13728 msg
= "503 Unavailable";
13730 if (ast_test_flag(req
, SIP_PKT_IGNORE
))
13731 transmit_response(p
, msg
, req
);
13733 transmit_response_reliable(p
, msg
, req
);
13734 p
->invitestate
= INV_COMPLETED
;
13735 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
13741 /*! \brief Find all call legs and bridge transferee with target
13742 * called from handle_request_refer */
13743 static int local_attended_transfer(struct sip_pvt
*transferer
, struct sip_dual
*current
, struct sip_request
*req
, int seqno
)
13745 struct sip_dual target
; /* Chan 1: Call from tranferer to Asterisk */
13746 /* Chan 2: Call from Asterisk to target */
13748 struct sip_pvt
*targetcall_pvt
;
13750 /* Check if the call ID of the replaces header does exist locally */
13751 if (!(targetcall_pvt
= get_sip_pvt_byid_locked(transferer
->refer
->replaces_callid
, transferer
->refer
->replaces_callid_totag
,
13752 transferer
->refer
->replaces_callid_fromtag
))) {
13753 if (transferer
->refer
->localtransfer
) {
13754 /* We did not find the refered call. Sorry, can't accept then */
13755 transmit_response(transferer
, "202 Accepted", req
);
13756 /* Let's fake a response from someone else in order
13757 to follow the standard */
13758 transmit_notify_with_sipfrag(transferer
, seqno
, "481 Call leg/transaction does not exist", TRUE
);
13759 append_history(transferer
, "Xfer", "Refer failed");
13760 ast_clear_flag(&transferer
->flags
[0], SIP_GOTREFER
);
13761 transferer
->refer
->status
= REFER_FAILED
;
13764 /* Fall through for remote transfers that we did not find locally */
13765 if (option_debug
> 2)
13766 ast_log(LOG_DEBUG
, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
13770 /* Ok, we can accept this transfer */
13771 transmit_response(transferer
, "202 Accepted", req
);
13772 append_history(transferer
, "Xfer", "Refer accepted");
13773 if (!targetcall_pvt
->owner
) { /* No active channel */
13774 if (option_debug
> 3)
13775 ast_log(LOG_DEBUG
, "SIP attended transfer: Error: No owner of target call\n");
13776 /* Cancel transfer */
13777 transmit_notify_with_sipfrag(transferer
, seqno
, "503 Service Unavailable", TRUE
);
13778 append_history(transferer
, "Xfer", "Refer failed");
13779 ast_clear_flag(&transferer
->flags
[0], SIP_GOTREFER
);
13780 transferer
->refer
->status
= REFER_FAILED
;
13781 ast_mutex_unlock(&targetcall_pvt
->lock
);
13782 ast_channel_unlock(current
->chan1
);
13786 /* We have a channel, find the bridge */
13787 target
.chan1
= targetcall_pvt
->owner
; /* Transferer to Asterisk */
13788 target
.chan2
= ast_bridged_channel(targetcall_pvt
->owner
); /* Asterisk to target */
13790 if (!target
.chan2
|| !(target
.chan2
->_state
== AST_STATE_UP
|| target
.chan2
->_state
== AST_STATE_RINGING
) ) {
13791 /* Wrong state of new channel */
13792 if (option_debug
> 3) {
13794 ast_log(LOG_DEBUG
, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target
.chan2
->_state
));
13795 else if (target
.chan1
->_state
!= AST_STATE_RING
)
13796 ast_log(LOG_DEBUG
, "SIP attended transfer: Error: No target channel\n");
13798 ast_log(LOG_DEBUG
, "SIP attended transfer: Attempting transfer in ringing state\n");
13803 if (option_debug
> 3 && sipdebug
) {
13804 if (current
->chan2
) /* We have two bridges */
13805 ast_log(LOG_DEBUG
, "SIP attended transfer: trying to bridge %s and %s\n", target
.chan1
->name
, current
->chan2
->name
);
13806 else /* One bridge, propably transfer of IVR/voicemail etc */
13807 ast_log(LOG_DEBUG
, "SIP attended transfer: trying to make %s take over (masq) %s\n", target
.chan1
->name
, current
->chan1
->name
);
13810 ast_set_flag(&transferer
->flags
[0], SIP_DEFER_BYE_ON_TRANSFER
); /* Delay hangup */
13812 /* Perform the transfer */
13813 res
= attempt_transfer(current
, &target
);
13814 ast_mutex_unlock(&targetcall_pvt
->lock
);
13816 /* Failed transfer */
13817 /* Could find better message, but they will get the point */
13818 transmit_notify_with_sipfrag(transferer
, seqno
, "486 Busy", TRUE
);
13819 append_history(transferer
, "Xfer", "Refer failed");
13820 if (targetcall_pvt
->owner
)
13821 ast_channel_unlock(targetcall_pvt
->owner
);
13822 /* Right now, we have to hangup, sorry. Bridge is destroyed */
13823 ast_hangup(transferer
->owner
);
13825 /* Transfer succeeded! */
13827 /* Tell transferer that we're done. */
13828 transmit_notify_with_sipfrag(transferer
, seqno
, "200 OK", TRUE
);
13829 append_history(transferer
, "Xfer", "Refer succeeded");
13830 transferer
->refer
->status
= REFER_200OK
;
13831 if (targetcall_pvt
->owner
) {
13833 ast_log(LOG_DEBUG
, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt
->owner
->name
);
13834 ast_channel_unlock(targetcall_pvt
->owner
);
13841 /*! \brief Handle incoming REFER request */
13842 /*! \page SIP_REFER SIP transfer Support (REFER)
13844 REFER is used for call transfer in SIP. We get a REFER
13845 to place a new call with an INVITE somwhere and then
13846 keep the transferor up-to-date of the transfer. If the
13847 transfer fails, get back on line with the orginal call.
13849 - REFER can be sent outside or inside of a dialog.
13850 Asterisk only accepts REFER inside of a dialog.
13852 - If we get a replaces header, it is an attended transfer
13854 \par Blind transfers
13855 The transferor provides the transferee
13856 with the transfer targets contact. The signalling between
13857 transferer or transferee should not be cancelled, so the
13858 call is recoverable if the transfer target can not be reached
13861 In this case, Asterisk receives a TRANSFER from
13862 the transferor, thus is the transferee. We should
13863 try to set up a call to the contact provided
13864 and if that fails, re-connect the current session.
13865 If the new call is set up, we issue a hangup.
13866 In this scenario, we are following section 5.2
13867 in the SIP CC Transfer draft. (Transfer without
13870 \par Transfer with consultation hold
13871 In this case, the transferor
13872 talks to the transfer target before the transfer takes place.
13873 This is implemented with SIP hold and transfer.
13874 Note: The invite From: string could indicate a transfer.
13875 (Section 6. Transfer with consultation hold)
13876 The transferor places the transferee on hold, starts a call
13877 with the transfer target to alert them to the impending
13878 transfer, terminates the connection with the target, then
13879 proceeds with the transfer (as in Blind transfer above)
13881 \par Attended transfer
13882 The transferor places the transferee
13883 on hold, calls the transfer target to alert them,
13884 places the target on hold, then proceeds with the transfer
13885 using a Replaces header field in the Refer-to header. This
13886 will force the transfee to send an Invite to the target,
13887 with a replaces header that instructs the target to
13888 hangup the call between the transferor and the target.
13889 In this case, the Refer/to: uses the AOR address. (The same
13890 URI that the transferee used to establish the session with
13891 the transfer target (To: ). The Require: replaces header should
13892 be in the INVITE to avoid the wrong UA in a forked SIP proxy
13893 scenario to answer and have no call to replace with.
13895 The referred-by header is *NOT* required, but if we get it,
13896 can be copied into the INVITE to the transfer target to
13897 inform the target about the transferor
13899 "Any REFER request has to be appropriately authenticated.".
13901 We can't destroy dialogs, since we want the call to continue.
13904 static int handle_request_refer(struct sip_pvt
*p
, struct sip_request
*req
, int debug
, int ignore
, int seqno
, int *nounlock
)
13906 struct sip_dual current
; /* Chan1: Call between asterisk and transferer */
13907 /* Chan2: Call between asterisk and transferee */
13911 if (ast_test_flag(req
, SIP_PKT_DEBUG
))
13912 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");
13915 /* This is a REFER outside of an existing SIP dialog */
13916 /* We can't handle that, so decline it */
13917 if (option_debug
> 2)
13918 ast_log(LOG_DEBUG
, "Call %s: Declined REFER, outside of dialog...\n", p
->callid
);
13919 transmit_response(p
, "603 Declined (No dialog)", req
);
13920 if (!ast_test_flag(req
, SIP_PKT_IGNORE
)) {
13921 append_history(p
, "Xfer", "Refer failed. Outside of dialog.");
13922 sip_alreadygone(p
);
13923 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
13929 /* Check if transfer is allowed from this device */
13930 if (p
->allowtransfer
== TRANSFER_CLOSED
) {
13931 /* Transfer not allowed, decline */
13932 transmit_response(p
, "603 Declined (policy)", req
);
13933 append_history(p
, "Xfer", "Refer failed. Allowtransfer == closed.");
13934 /* Do not destroy SIP session */
13938 if(!ignore
&& ast_test_flag(&p
->flags
[0], SIP_GOTREFER
)) {
13939 /* Already have a pending REFER */
13940 transmit_response(p
, "491 Request pending", req
);
13941 append_history(p
, "Xfer", "Refer failed. Request pending.");
13945 /* Allocate memory for call transfer data */
13946 if (!p
->refer
&& !sip_refer_allocate(p
)) {
13947 transmit_response(p
, "500 Internal Server Error", req
);
13948 append_history(p
, "Xfer", "Refer failed. Memory allocation error.");
13952 res
= get_refer_info(p
, req
); /* Extract headers */
13954 p
->refer
->status
= REFER_SENT
;
13958 case -2: /* Syntax error */
13959 transmit_response(p
, "400 Bad Request (Refer-to missing)", req
);
13960 append_history(p
, "Xfer", "Refer failed. Refer-to missing.");
13961 if (ast_test_flag(req
, SIP_PKT_DEBUG
) && option_debug
)
13962 ast_log(LOG_DEBUG
, "SIP transfer to black hole can't be handled (no refer-to: )\n");
13965 transmit_response(p
, "603 Declined (Non sip: uri)", req
);
13966 append_history(p
, "Xfer", "Refer failed. Non SIP uri");
13967 if (ast_test_flag(req
, SIP_PKT_DEBUG
) && option_debug
)
13968 ast_log(LOG_DEBUG
, "SIP transfer to non-SIP uri denied\n");
13971 /* Refer-to extension not found, fake a failed transfer */
13972 transmit_response(p
, "202 Accepted", req
);
13973 append_history(p
, "Xfer", "Refer failed. Bad extension.");
13974 transmit_notify_with_sipfrag(p
, seqno
, "404 Not found", TRUE
);
13975 ast_clear_flag(&p
->flags
[0], SIP_GOTREFER
);
13976 if (ast_test_flag(req
, SIP_PKT_DEBUG
) && option_debug
)
13977 ast_log(LOG_DEBUG
, "SIP transfer to bad extension: %s\n", p
->refer
->refer_to
);
13982 if (ast_strlen_zero(p
->context
))
13983 ast_string_field_set(p
, context
, default_context
);
13985 /* If we do not support SIP domains, all transfers are local */
13986 if (allow_external_domains
&& check_sip_domain(p
->refer
->refer_to_domain
, NULL
, 0)) {
13987 p
->refer
->localtransfer
= 1;
13988 if (sipdebug
&& option_debug
> 2)
13989 ast_log(LOG_DEBUG
, "This SIP transfer is local : %s\n", p
->refer
->refer_to_domain
);
13990 } else if (AST_LIST_EMPTY(&domain_list
)) {
13991 /* This PBX don't bother with SIP domains, so all transfers are local */
13992 p
->refer
->localtransfer
= 1;
13994 if (sipdebug
&& option_debug
> 2)
13995 ast_log(LOG_DEBUG
, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p
->refer
->refer_to_domain
);
13997 /* Is this a repeat of a current request? Ignore it */
13998 /* Don't know what else to do right now. */
14002 /* If this is a blind transfer, we have the following
14003 channels to work with:
14004 - chan1, chan2: The current call between transferer and transferee (2 channels)
14005 - target_channel: A new call from the transferee to the target (1 channel)
14006 We need to stay tuned to what happens in order to be able
14007 to bring back the call to the transferer */
14009 /* If this is a attended transfer, we should have all call legs within reach:
14010 - chan1, chan2: The call between the transferer and transferee (2 channels)
14011 - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
14012 We want to bridge chan2 with targetcall_pvt!
14014 The replaces call id in the refer message points
14015 to the call leg between Asterisk and the transferer.
14016 So we need to connect the target and the transferee channel
14017 and hangup the two other channels silently
14019 If the target is non-local, the call ID could be on a remote
14020 machine and we need to send an INVITE with replaces to the
14021 target. We basically handle this as a blind transfer
14022 and let the sip_call function catch that we need replaces
14023 header in the INVITE.
14027 /* Get the transferer's channel */
14028 current
.chan1
= p
->owner
;
14030 /* Find the other part of the bridge (2) - transferee */
14031 current
.chan2
= ast_bridged_channel(current
.chan1
);
14033 if (sipdebug
&& option_debug
> 2)
14034 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>");
14036 if (!current
.chan2
&& !p
->refer
->attendedtransfer
) {
14037 /* No bridged channel, propably IVR or echo or similar... */
14038 /* Guess we should masquerade or something here */
14039 /* Until we figure it out, refuse transfer of such calls */
14040 if (sipdebug
&& option_debug
> 2)
14041 ast_log(LOG_DEBUG
,"Refused SIP transfer on non-bridged channel.\n");
14042 p
->refer
->status
= REFER_FAILED
;
14043 append_history(p
, "Xfer", "Refer failed. Non-bridged channel.");
14044 transmit_response(p
, "603 Declined", req
);
14048 if (current
.chan2
) {
14049 if (sipdebug
&& option_debug
> 3)
14050 ast_log(LOG_DEBUG
, "Got SIP transfer, applying to bridged peer '%s'\n", current
.chan2
->name
);
14052 ast_queue_control(current
.chan1
, AST_CONTROL_UNHOLD
);
14055 ast_set_flag(&p
->flags
[0], SIP_GOTREFER
);
14057 /* Attended transfer: Find all call legs and bridge transferee with target*/
14058 if (p
->refer
->attendedtransfer
) {
14059 if ((res
= local_attended_transfer(p
, ¤t
, req
, seqno
)))
14060 return res
; /* We're done with the transfer */
14061 /* Fall through for remote transfers that we did not find locally */
14062 if (sipdebug
&& option_debug
> 3)
14063 ast_log(LOG_DEBUG
, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
14064 /* Fallthrough if we can't find the call leg internally */
14068 /* Parking a call */
14069 if (p
->refer
->localtransfer
&& !strcmp(p
->refer
->refer_to
, ast_parking_ext())) {
14070 /* Must release c's lock now, because it will not longer be accessible after the transfer! */
14072 ast_channel_unlock(current
.chan1
);
14073 copy_request(¤t
.req
, req
);
14074 ast_clear_flag(&p
->flags
[0], SIP_GOTREFER
);
14075 p
->refer
->status
= REFER_200OK
;
14076 append_history(p
, "Xfer", "REFER to call parking.");
14077 if (sipdebug
&& option_debug
> 3)
14078 ast_log(LOG_DEBUG
, "SIP transfer to parking: trying to park %s. Parked by %s\n", current
.chan2
->name
, current
.chan1
->name
);
14079 sip_park(current
.chan2
, current
.chan1
, req
, seqno
);
14083 /* Blind transfers and remote attended xfers */
14084 transmit_response(p
, "202 Accepted", req
);
14086 if (current
.chan1
&& current
.chan2
) {
14087 if (option_debug
> 2)
14088 ast_log(LOG_DEBUG
, "chan1->name: %s\n", current
.chan1
->name
);
14089 pbx_builtin_setvar_helper(current
.chan1
, "BLINDTRANSFER", current
.chan2
->name
);
14091 if (current
.chan2
) {
14092 pbx_builtin_setvar_helper(current
.chan2
, "BLINDTRANSFER", current
.chan1
->name
);
14093 pbx_builtin_setvar_helper(current
.chan2
, "SIPDOMAIN", p
->refer
->refer_to_domain
);
14094 pbx_builtin_setvar_helper(current
.chan2
, "SIPTRANSFER", "yes");
14095 /* One for the new channel */
14096 pbx_builtin_setvar_helper(current
.chan2
, "_SIPTRANSFER", "yes");
14097 /* Attended transfer to remote host, prepare headers for the INVITE */
14098 if (p
->refer
->referred_by
)
14099 pbx_builtin_setvar_helper(current
.chan2
, "_SIPTRANSFER_REFERER", p
->refer
->referred_by
);
14101 /* Generate a Replaces string to be used in the INVITE during attended transfer */
14102 if (p
->refer
->replaces_callid
&& !ast_strlen_zero(p
->refer
->replaces_callid
)) {
14103 char tempheader
[BUFSIZ
];
14104 snprintf(tempheader
, sizeof(tempheader
), "%s%s%s%s%s", p
->refer
->replaces_callid
,
14105 p
->refer
->replaces_callid_totag
? ";to-tag=" : "",
14106 p
->refer
->replaces_callid_totag
,
14107 p
->refer
->replaces_callid_fromtag
? ";from-tag=" : "",
14108 p
->refer
->replaces_callid_fromtag
);
14110 pbx_builtin_setvar_helper(current
.chan2
, "_SIPTRANSFER_REPLACES", tempheader
);
14112 /* Must release lock now, because it will not longer
14113 be accessible after the transfer! */
14115 ast_channel_unlock(current
.chan1
);
14116 ast_channel_unlock(current
.chan2
);
14118 /* Connect the call */
14120 /* FAKE ringing if not attended transfer */
14121 if (!p
->refer
->attendedtransfer
)
14122 transmit_notify_with_sipfrag(p
, seqno
, "183 Ringing", FALSE
);
14124 /* For blind transfer, this will lead to a new call */
14125 /* For attended transfer to remote host, this will lead to
14126 a new SIP call with a replaces header, if the dial plan allows it
14128 if (!current
.chan2
) {
14129 /* We have no bridge, so we're talking with Asterisk somehow */
14130 /* We need to masquerade this call */
14131 /* What to do to fix this situation:
14132 * Set up the new call in a new channel
14133 * Let the new channel masq into this channel
14134 Please add that code here :-)
14136 p
->refer
->status
= REFER_FAILED
;
14137 transmit_notify_with_sipfrag(p
, seqno
, "503 Service Unavailable (can't handle one-legged xfers)", TRUE
);
14138 ast_clear_flag(&p
->flags
[0], SIP_GOTREFER
);
14139 append_history(p
, "Xfer", "Refer failed (only bridged calls).");
14142 ast_set_flag(&p
->flags
[0], SIP_DEFER_BYE_ON_TRANSFER
); /* Delay hangup */
14144 /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
14145 servers - generate an INVITE with Replaces. Either way, let the dial plan decided */
14146 res
= ast_async_goto(current
.chan2
, p
->refer
->refer_to_context
, p
->refer
->refer_to
, 1);
14149 /* Success - we have a new channel */
14150 if (option_debug
> 2)
14151 ast_log(LOG_DEBUG
, "%s transfer succeeded. Telling transferer.\n", p
->refer
->attendedtransfer
? "Attended" : "Blind");
14152 transmit_notify_with_sipfrag(p
, seqno
, "200 Ok", TRUE
);
14153 if (p
->refer
->localtransfer
)
14154 p
->refer
->status
= REFER_200OK
;
14156 p
->owner
->hangupcause
= AST_CAUSE_NORMAL_CLEARING
;
14157 append_history(p
, "Xfer", "Refer succeeded.");
14158 ast_clear_flag(&p
->flags
[0], SIP_GOTREFER
);
14159 /* Do not hangup call, the other side do that when we say 200 OK */
14160 /* We could possibly implement a timer here, auto congestion */
14163 ast_clear_flag(&p
->flags
[0], SIP_DEFER_BYE_ON_TRANSFER
); /* Don't delay hangup */
14164 if (option_debug
> 2)
14165 ast_log(LOG_DEBUG
, "%s transfer failed. Resuming original call.\n", p
->refer
->attendedtransfer
? "Attended" : "Blind");
14166 append_history(p
, "Xfer", "Refer failed.");
14167 /* Failure of some kind */
14168 p
->refer
->status
= REFER_FAILED
;
14169 transmit_notify_with_sipfrag(p
, seqno
, "503 Service Unavailable", TRUE
);
14170 ast_clear_flag(&p
->flags
[0], SIP_GOTREFER
);
14176 /*! \brief Handle incoming CANCEL request */
14177 static int handle_request_cancel(struct sip_pvt
*p
, struct sip_request
*req
)
14181 sip_alreadygone(p
);
14182 p
->invitestate
= INV_CANCELLED
;
14184 if (p
->owner
&& p
->owner
->_state
== AST_STATE_UP
) {
14185 /* This call is up, cancel is ignored, we need a bye */
14186 transmit_response(p
, "200 OK", req
);
14188 ast_log(LOG_DEBUG
, "Got CANCEL on an answered call. Ignoring... \n");
14191 stop_media_flows(p
); /* Immediately stop RTP, VRTP and UDPTL as applicable */
14194 ast_queue_hangup(p
->owner
);
14196 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
14197 if (p
->initreq
.len
> 0) {
14198 transmit_response_reliable(p
, "487 Request Terminated", &p
->initreq
);
14199 transmit_response(p
, "200 OK", req
);
14202 transmit_response(p
, "481 Call Leg Does Not Exist", req
);
14207 static int acf_channel_read(struct ast_channel
*chan
, char *funcname
, char *preparse
, char *buf
, size_t buflen
)
14209 struct ast_rtp_quality qos
;
14210 struct sip_pvt
*p
= chan
->tech_pvt
;
14211 char *all
= "", *parse
= ast_strdupa(preparse
);
14212 AST_DECLARE_APP_ARGS(args
,
14213 AST_APP_ARG(param
);
14215 AST_APP_ARG(field
);
14217 AST_STANDARD_APP_ARGS(args
, parse
);
14220 if (chan
->tech
!= &sip_tech
&& chan
->tech
!= &sip_tech_info
) {
14221 ast_log(LOG_ERROR
, "Cannot call %s on a non-SIP channel\n", funcname
);
14225 if (strcasecmp(args
.param
, "rtpqos"))
14228 memset(buf
, 0, buflen
);
14229 memset(&qos
, 0, sizeof(qos
));
14231 if (strcasecmp(args
.type
, "AUDIO") == 0) {
14232 all
= ast_rtp_get_quality(p
->rtp
, &qos
);
14233 } else if (strcasecmp(args
.type
, "VIDEO") == 0) {
14234 all
= ast_rtp_get_quality(p
->vrtp
, &qos
);
14237 if (strcasecmp(args
.field
, "local_ssrc") == 0)
14238 snprintf(buf
, buflen
, "%u", qos
.local_ssrc
);
14239 else if (strcasecmp(args
.field
, "local_lostpackets") == 0)
14240 snprintf(buf
, buflen
, "%u", qos
.local_lostpackets
);
14241 else if (strcasecmp(args
.field
, "local_jitter") == 0)
14242 snprintf(buf
, buflen
, "%.0lf", qos
.local_jitter
* 1000.0);
14243 else if (strcasecmp(args
.field
, "local_count") == 0)
14244 snprintf(buf
, buflen
, "%u", qos
.local_count
);
14245 else if (strcasecmp(args
.field
, "remote_ssrc") == 0)
14246 snprintf(buf
, buflen
, "%u", qos
.remote_ssrc
);
14247 else if (strcasecmp(args
.field
, "remote_lostpackets") == 0)
14248 snprintf(buf
, buflen
, "%u", qos
.remote_lostpackets
);
14249 else if (strcasecmp(args
.field
, "remote_jitter") == 0)
14250 snprintf(buf
, buflen
, "%.0lf", qos
.remote_jitter
* 1000.0);
14251 else if (strcasecmp(args
.field
, "remote_count") == 0)
14252 snprintf(buf
, buflen
, "%u", qos
.remote_count
);
14253 else if (strcasecmp(args
.field
, "rtt") == 0)
14254 snprintf(buf
, buflen
, "%.0lf", qos
.rtt
* 1000.0);
14255 else if (strcasecmp(args
.field
, "all") == 0)
14256 ast_copy_string(buf
, all
, buflen
);
14258 ast_log(LOG_WARNING
, "Unrecognized argument '%s' to %s\n", preparse
, funcname
);
14264 /*! \brief Handle incoming BYE request */
14265 static int handle_request_bye(struct sip_pvt
*p
, struct sip_request
*req
)
14267 struct ast_channel
*c
=NULL
;
14269 struct ast_channel
*bridged_to
;
14271 /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
14272 if (p
->pendinginvite
&& !ast_test_flag(&p
->flags
[0], SIP_OUTGOING
) && !ast_test_flag(req
, SIP_PKT_IGNORE
) && !p
->owner
)
14273 transmit_response_reliable(p
, "487 Request Terminated", &p
->initreq
);
14275 p
->invitestate
= INV_TERMINATED
;
14277 copy_request(&p
->initreq
, req
);
14279 sip_alreadygone(p
);
14281 /* Get RTCP quality before end of call */
14282 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
) || p
->owner
) {
14283 char *audioqos
, *videoqos
;
14285 audioqos
= ast_rtp_get_quality(p
->rtp
, NULL
);
14286 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
))
14287 append_history(p
, "RTCPaudio", "Quality:%s", audioqos
);
14289 pbx_builtin_setvar_helper(p
->owner
, "RTPAUDIOQOS", audioqos
);
14292 videoqos
= ast_rtp_get_quality(p
->vrtp
, NULL
);
14293 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
))
14294 append_history(p
, "RTCPvideo", "Quality:%s", videoqos
);
14296 pbx_builtin_setvar_helper(p
->owner
, "RTPVIDEOQOS", videoqos
);
14300 stop_media_flows(p
); /* Immediately stop RTP, VRTP and UDPTL as applicable */
14302 if (!ast_strlen_zero(get_header(req
, "Also"))) {
14303 ast_log(LOG_NOTICE
, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
14304 ast_inet_ntoa(p
->recv
.sin_addr
));
14305 if (ast_strlen_zero(p
->context
))
14306 ast_string_field_set(p
, context
, default_context
);
14307 res
= get_also_info(p
, req
);
14311 bridged_to
= ast_bridged_channel(c
);
14313 /* Don't actually hangup here... */
14314 ast_queue_control(c
, AST_CONTROL_UNHOLD
);
14315 ast_async_goto(bridged_to
, p
->context
, p
->refer
->refer_to
,1);
14317 ast_queue_hangup(p
->owner
);
14320 ast_log(LOG_WARNING
, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p
->recv
.sin_addr
));
14322 ast_queue_hangup(p
->owner
);
14324 } else if (p
->owner
) {
14325 ast_queue_hangup(p
->owner
);
14326 if (option_debug
> 2)
14327 ast_log(LOG_DEBUG
, "Received bye, issuing owner hangup\n");
14329 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
14330 if (option_debug
> 2)
14331 ast_log(LOG_DEBUG
, "Received bye, no owner, selfdestruct soon.\n");
14333 transmit_response(p
, "200 OK", req
);
14338 /*! \brief Handle incoming MESSAGE request */
14339 static int handle_request_message(struct sip_pvt
*p
, struct sip_request
*req
)
14341 if (!ast_test_flag(req
, SIP_PKT_IGNORE
)) {
14342 if (ast_test_flag(req
, SIP_PKT_DEBUG
))
14343 ast_verbose("Receiving message!\n");
14344 receive_message(p
, req
);
14346 transmit_response(p
, "202 Accepted", req
);
14350 /*! \brief Handle incoming SUBSCRIBE request */
14351 static int handle_request_subscribe(struct sip_pvt
*p
, struct sip_request
*req
, struct sockaddr_in
*sin
, int seqno
, char *e
)
14355 int firststate
= AST_EXTENSION_REMOVED
;
14356 struct sip_peer
*authpeer
= NULL
;
14357 const char *eventheader
= get_header(req
, "Event"); /* Get Event package name */
14358 const char *accept
= get_header(req
, "Accept");
14359 int resubscribe
= (p
->subscribed
!= NONE
);
14360 char *temp
, *event
;
14362 if (p
->initreq
.headers
) {
14363 /* We already have a dialog */
14364 if (p
->initreq
.method
!= SIP_SUBSCRIBE
) {
14365 /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
14366 /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
14367 transmit_response(p
, "403 Forbidden (within dialog)", req
);
14368 /* Do not destroy session, since we will break the call if we do */
14370 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
);
14372 } else if (ast_test_flag(req
, SIP_PKT_DEBUG
)) {
14373 if (option_debug
) {
14375 ast_log(LOG_DEBUG
, "Got a re-subscribe on existing subscription %s\n", p
->callid
);
14377 ast_log(LOG_DEBUG
, "Got a new subscription %s (possibly with auth)\n", p
->callid
);
14382 /* Check if we have a global disallow setting on subscriptions.
14383 if so, we don't have to check peer/user settings after auth, which saves a lot of processing
14385 if (!global_allowsubscribe
) {
14386 transmit_response(p
, "403 Forbidden (policy)", req
);
14387 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14391 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && !resubscribe
) { /* Set up dialog, new subscription */
14392 /* Use this as the basis */
14393 if (ast_test_flag(req
, SIP_PKT_DEBUG
))
14394 ast_verbose("Creating new subscription\n");
14396 copy_request(&p
->initreq
, req
);
14398 } else if (ast_test_flag(req
, SIP_PKT_DEBUG
) && ast_test_flag(req
, SIP_PKT_IGNORE
))
14399 ast_verbose("Ignoring this SUBSCRIBE request\n");
14401 /* Find parameters to Event: header value and remove them for now */
14402 if (ast_strlen_zero(eventheader
)) {
14403 transmit_response(p
, "489 Bad Event", req
);
14404 if (option_debug
> 1)
14405 ast_log(LOG_DEBUG
, "Received SIP subscribe for unknown event package: <none>\n");
14406 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14410 if ( (strchr(eventheader
, ';'))) {
14411 event
= ast_strdupa(eventheader
); /* Since eventheader is a const, we can't change it */
14412 temp
= strchr(event
, ';');
14413 *temp
= '\0'; /* Remove any options for now */
14414 /* We might need to use them later :-) */
14416 event
= (char *) eventheader
; /* XXX is this legal ? */
14418 /* Handle authentication */
14419 res
= check_user_full(p
, req
, SIP_SUBSCRIBE
, e
, 0, sin
, &authpeer
);
14420 /* if an authentication response was sent, we are done here */
14421 if (res
== AUTH_CHALLENGE_SENT
) {
14423 ASTOBJ_UNREF(authpeer
, sip_destroy_peer
);
14427 if (res
== AUTH_FAKE_AUTH
) {
14428 ast_log(LOG_NOTICE
, "Sending fake auth rejection for user %s\n", get_header(req
, "From"));
14429 transmit_fake_auth_response(p
, req
, 1);
14431 ast_log(LOG_NOTICE
, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req
, "From"));
14432 transmit_response_reliable(p
, "403 Forbidden", req
);
14434 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14436 ASTOBJ_UNREF(authpeer
, sip_destroy_peer
);
14440 /* Check if this user/peer is allowed to subscribe at all */
14441 if (!ast_test_flag(&p
->flags
[1], SIP_PAGE2_ALLOWSUBSCRIBE
)) {
14442 transmit_response(p
, "403 Forbidden (policy)", req
);
14443 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14445 ASTOBJ_UNREF(authpeer
, sip_destroy_peer
);
14449 /* Get destination right away */
14450 gotdest
= get_destination(p
, NULL
);
14452 /* Initialize the context if it hasn't been already;
14453 note this is done _after_ handling any domain lookups,
14454 because the context specified there is for calls, not
14457 if (!ast_strlen_zero(p
->subscribecontext
))
14458 ast_string_field_set(p
, context
, p
->subscribecontext
);
14459 else if (ast_strlen_zero(p
->context
))
14460 ast_string_field_set(p
, context
, default_context
);
14462 /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
14463 parse_ok_contact(p
, req
);
14467 transmit_response(p
, "404 Not Found", req
);
14468 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14470 ASTOBJ_UNREF(authpeer
, sip_destroy_peer
);
14474 /* Initialize tag for new subscriptions */
14475 if (ast_strlen_zero(p
->tag
))
14476 make_our_tag(p
->tag
, sizeof(p
->tag
));
14478 if (!strcmp(event
, "presence") || !strcmp(event
, "dialog")) { /* Presence, RFC 3842 */
14479 if (authpeer
) /* No need for authpeer here */
14480 ASTOBJ_UNREF(authpeer
, sip_destroy_peer
);
14482 /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
14483 /* Polycom phones only handle xpidf+xml, even if they say they can
14484 handle pidf+xml as well
14486 if (strstr(p
->useragent
, "Polycom")) {
14487 p
->subscribed
= XPIDF_XML
;
14488 } else if (strstr(accept
, "application/pidf+xml")) {
14489 p
->subscribed
= PIDF_XML
; /* RFC 3863 format */
14490 } else if (strstr(accept
, "application/dialog-info+xml")) {
14491 p
->subscribed
= DIALOG_INFO_XML
;
14492 /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
14493 } else if (strstr(accept
, "application/cpim-pidf+xml")) {
14494 p
->subscribed
= CPIM_PIDF_XML
; /* RFC 3863 format */
14495 } else if (strstr(accept
, "application/xpidf+xml")) {
14496 p
->subscribed
= XPIDF_XML
; /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
14497 } else if (ast_strlen_zero(accept
)) {
14498 if (p
->subscribed
== NONE
) { /* if the subscribed field is not already set, and there is no accept header... */
14499 transmit_response(p
, "489 Bad Event", req
);
14501 ast_log(LOG_WARNING
,"SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
14502 p
->stateid
, p
->laststate
, p
->dialogver
, p
->subscribecontext
, p
->subscribeuri
);
14503 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14506 /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
14507 so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
14509 /* Can't find a format for events that we know about */
14511 snprintf(mybuf
,sizeof(mybuf
),"489 Bad Event (format %s)", accept
);
14512 transmit_response(p
, mybuf
, req
);
14514 ast_log(LOG_WARNING
,"SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
14515 accept
, (int)p
->subscribed
, p
->stateid
, p
->laststate
, p
->dialogver
, p
->subscribecontext
, p
->subscribeuri
);
14516 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14519 } else if (!strcmp(event
, "message-summary")) {
14520 if (!ast_strlen_zero(accept
) && strcmp(accept
, "application/simple-message-summary")) {
14521 /* Format requested that we do not support */
14522 transmit_response(p
, "406 Not Acceptable", req
);
14523 if (option_debug
> 1)
14524 ast_log(LOG_DEBUG
, "Received SIP mailbox subscription for unknown format: %s\n", accept
);
14525 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14526 if (authpeer
) /* No need for authpeer here */
14527 ASTOBJ_UNREF(authpeer
, sip_destroy_peer
);
14530 /* Looks like they actually want a mailbox status
14531 This version of Asterisk supports mailbox subscriptions
14532 The subscribed URI needs to exist in the dial plan
14533 In most devices, this is configurable to the voicemailmain extension you use
14535 if (!authpeer
|| ast_strlen_zero(authpeer
->mailbox
)) {
14536 transmit_response(p
, "404 Not found (no mailbox)", req
);
14537 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14538 ast_log(LOG_NOTICE
, "Received SIP subscribe for peer without mailbox: %s\n", authpeer
->name
);
14539 if (authpeer
) /* No need for authpeer here */
14540 ASTOBJ_UNREF(authpeer
, sip_destroy_peer
);
14544 p
->subscribed
= MWI_NOTIFICATION
;
14545 if (authpeer
->mwipvt
&& authpeer
->mwipvt
!= p
) /* Destroy old PVT if this is a new one */
14546 /* We only allow one subscription per peer */
14547 sip_destroy(authpeer
->mwipvt
);
14548 authpeer
->mwipvt
= p
; /* Link from peer to pvt */
14549 p
->relatedpeer
= authpeer
; /* Link from pvt to peer */
14550 } else { /* At this point, Asterisk does not understand the specified event */
14551 transmit_response(p
, "489 Bad Event", req
);
14552 if (option_debug
> 1)
14553 ast_log(LOG_DEBUG
, "Received SIP subscribe for unknown event package: %s\n", event
);
14554 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14555 if (authpeer
) /* No need for authpeer here */
14556 ASTOBJ_UNREF(authpeer
, sip_destroy_peer
);
14560 if (p
->subscribed
!= MWI_NOTIFICATION
&& !resubscribe
)
14561 p
->stateid
= ast_extension_state_add(p
->context
, p
->exten
, cb_extensionstate
, p
);
14563 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && p
)
14564 p
->lastinvite
= seqno
;
14565 if (p
&& !ast_test_flag(&p
->flags
[0], SIP_NEEDDESTROY
)) {
14566 p
->expiry
= atoi(get_header(req
, "Expires"));
14568 /* check if the requested expiry-time is within the approved limits from sip.conf */
14569 if (p
->expiry
> max_expiry
)
14570 p
->expiry
= max_expiry
;
14571 if (p
->expiry
< min_expiry
&& p
->expiry
> 0)
14572 p
->expiry
= min_expiry
;
14574 if (sipdebug
|| option_debug
> 1) {
14575 if (p
->subscribed
== MWI_NOTIFICATION
&& p
->relatedpeer
)
14576 ast_log(LOG_DEBUG
, "Adding subscription for mailbox notification - peer %s Mailbox %s\n", p
->relatedpeer
->name
, p
->relatedpeer
->mailbox
);
14578 ast_log(LOG_DEBUG
, "Adding subscription for extension %s context %s for peer %s\n", p
->exten
, p
->context
, p
->username
);
14580 if (p
->autokillid
> -1)
14581 sip_cancel_destroy(p
); /* Remove subscription expiry for renewals */
14583 sip_scheddestroy(p
, (p
->expiry
+ 10) * 1000); /* Set timer for destruction of call at expiration */
14585 if (p
->subscribed
== MWI_NOTIFICATION
) {
14586 transmit_response(p
, "200 OK", req
);
14587 if (p
->relatedpeer
) { /* Send first notification */
14588 ASTOBJ_WRLOCK(p
->relatedpeer
);
14589 sip_send_mwi_to_peer(p
->relatedpeer
);
14590 ASTOBJ_UNLOCK(p
->relatedpeer
);
14593 struct sip_pvt
*p_old
;
14595 if ((firststate
= ast_extension_state(NULL
, p
->context
, p
->exten
)) < 0) {
14597 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
));
14598 transmit_response(p
, "404 Not found", req
);
14599 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14603 transmit_response(p
, "200 OK", req
);
14604 transmit_state_notify(p
, firststate
, 1, FALSE
); /* Send first notification */
14605 append_history(p
, "Subscribestatus", "%s", ast_extension_state2str(firststate
));
14606 /* hide the 'complete' exten/context in the refer_to field for later display */
14607 ast_string_field_build(p
, subscribeuri
, "%s@%s", p
->exten
, p
->context
);
14609 /* remove any old subscription from this peer for the same exten/context,
14610 as the peer has obviously forgotten about it and it's wasteful to wait
14611 for it to expire and send NOTIFY messages to the peer only to have them
14612 ignored (or generate errors)
14614 ast_mutex_lock(&iflock
);
14615 for (p_old
= iflist
; p_old
; p_old
= p_old
->next
) {
14618 if (p_old
->initreq
.method
!= SIP_SUBSCRIBE
)
14620 if (p_old
->subscribed
== NONE
)
14622 ast_mutex_lock(&p_old
->lock
);
14623 if (!strcmp(p_old
->username
, p
->username
)) {
14624 if (!strcmp(p_old
->exten
, p
->exten
) &&
14625 !strcmp(p_old
->context
, p
->context
)) {
14626 ast_set_flag(&p_old
->flags
[0], SIP_NEEDDESTROY
);
14627 ast_mutex_unlock(&p_old
->lock
);
14631 ast_mutex_unlock(&p_old
->lock
);
14633 ast_mutex_unlock(&iflock
);
14636 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14641 /*! \brief Handle incoming REGISTER request */
14642 static int handle_request_register(struct sip_pvt
*p
, struct sip_request
*req
, struct sockaddr_in
*sin
, char *e
)
14644 enum check_auth_result res
;
14646 /* Use this as the basis */
14647 if (ast_test_flag(req
, SIP_PKT_DEBUG
))
14648 ast_verbose("Using latest REGISTER request as basis request\n");
14649 copy_request(&p
->initreq
, req
);
14651 if ((res
= register_verify(p
, sin
, req
, e
)) < 0) {
14652 const char *reason
;
14655 case AUTH_SECRET_FAILED
:
14656 reason
= "Wrong password";
14658 case AUTH_USERNAME_MISMATCH
:
14659 reason
= "Username/auth name mismatch";
14661 case AUTH_NOT_FOUND
:
14662 reason
= "No matching peer found";
14664 case AUTH_UNKNOWN_DOMAIN
:
14665 reason
= "Not a local domain";
14667 case AUTH_PEER_NOT_DYNAMIC
:
14668 reason
= "Peer is not supposed to register";
14670 case AUTH_ACL_FAILED
:
14671 reason
= "Device does not match ACL";
14674 reason
= "Unknown failure";
14677 ast_log(LOG_NOTICE
, "Registration from '%s' failed for '%s' - %s\n",
14678 get_header(req
, "To"), ast_inet_ntoa(sin
->sin_addr
),
14680 append_history(p
, "RegRequest", "Failed : Account %s : %s", get_header(req
, "To"), reason
);
14682 append_history(p
, "RegRequest", "Succeeded : Account %s", get_header(req
, "To"));
14685 /* Destroy the session, but keep us around for just a bit in case they don't
14687 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
14692 /*! \brief Handle incoming SIP requests (methods)
14693 \note This is where all incoming requests go first */
14694 /* called with p and p->owner locked */
14695 static int handle_request(struct sip_pvt
*p
, struct sip_request
*req
, struct sockaddr_in
*sin
, int *recount
, int *nounlock
)
14697 /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
14698 relatively static */
14701 const char *useragent
;
14704 int ignore
= FALSE
;
14707 int debug
= sip_debug_test_pvt(p
);
14711 /* Get Method and Cseq */
14712 cseq
= get_header(req
, "Cseq");
14713 cmd
= req
->header
[0];
14715 /* Must have Cseq */
14716 if (ast_strlen_zero(cmd
) || ast_strlen_zero(cseq
)) {
14717 ast_log(LOG_ERROR
, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
14720 if (!error
&& sscanf(cseq
, "%d%n", &seqno
, &len
) != 1) {
14721 ast_log(LOG_ERROR
, "No seqno in '%s'. Dropping incomplete message.\n", cmd
);
14725 if (!p
->initreq
.headers
) /* New call */
14726 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
); /* Make sure we destroy this dialog */
14729 /* Get the command XXX */
14731 cmd
= req
->rlPart1
;
14734 /* Save useragent of the client */
14735 useragent
= get_header(req
, "User-Agent");
14736 if (!ast_strlen_zero(useragent
))
14737 ast_string_field_set(p
, useragent
, useragent
);
14739 /* Find out SIP method for incoming request */
14740 if (req
->method
== SIP_RESPONSE
) { /* Response to our request */
14741 /* Response to our request -- Do some sanity checks */
14742 if (!p
->initreq
.headers
) {
14744 ast_log(LOG_DEBUG
, "That's odd... Got a response on a call we dont know about. Cseq %d Cmd %s\n", seqno
, cmd
);
14745 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14747 } else if (p
->ocseq
&& (p
->ocseq
< seqno
)) {
14749 ast_log(LOG_DEBUG
, "Ignoring out of order response %d (expecting %d)\n", seqno
, p
->ocseq
);
14751 } else if (p
->ocseq
&& (p
->ocseq
!= seqno
)) {
14752 /* ignore means "don't do anything with it" but still have to
14753 respond appropriately */
14755 ast_set_flag(req
, SIP_PKT_IGNORE
);
14756 ast_set_flag(req
, SIP_PKT_IGNORE_RESP
);
14757 append_history(p
, "Ignore", "Ignoring this retransmit\n");
14759 e
= ast_skip_blanks(e
);
14760 if (sscanf(e
, "%d %n", &respid
, &len
) != 1) {
14761 ast_log(LOG_WARNING
, "Invalid response: '%s'\n", e
);
14764 ast_log(LOG_WARNING
, "Invalid SIP response code: '%d'\n", respid
);
14767 /* More SIP ridiculousness, we have to ignore bogus contacts in 100 etc responses */
14768 if ((respid
== 200) || ((respid
>= 300) && (respid
<= 399)))
14769 extract_uri(p
, req
);
14770 handle_response(p
, respid
, e
+ len
, req
, ignore
, seqno
);
14776 /* New SIP request coming in
14777 (could be new request in existing SIP dialog as well...)
14780 p
->method
= req
->method
; /* Find out which SIP method they are using */
14781 if (option_debug
> 3)
14782 ast_log(LOG_DEBUG
, "**** Received %s (%d) - Command in SIP %s\n", sip_methods
[p
->method
].text
, sip_methods
[p
->method
].id
, cmd
);
14784 if (p
->icseq
&& (p
->icseq
> seqno
)) {
14786 ast_log(LOG_DEBUG
, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno
, p
->icseq
);
14787 if (req
->method
!= SIP_ACK
)
14788 transmit_response(p
, "503 Server error", req
); /* We must respond according to RFC 3261 sec 12.2 */
14790 } else if (p
->icseq
&&
14791 p
->icseq
== seqno
&&
14792 req
->method
!= SIP_ACK
&&
14793 (p
->method
!= SIP_CANCEL
|| ast_test_flag(&p
->flags
[0], SIP_ALREADYGONE
))) {
14794 /* ignore means "don't do anything with it" but still have to
14795 respond appropriately. We do this if we receive a repeat of
14796 the last sequence number */
14798 ast_set_flag(req
, SIP_PKT_IGNORE
);
14799 ast_set_flag(req
, SIP_PKT_IGNORE_REQ
);
14800 if (option_debug
> 2)
14801 ast_log(LOG_DEBUG
, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods
[p
->method
].text
, p
->icseq
, seqno
);
14804 if (seqno
>= p
->icseq
)
14805 /* Next should follow monotonically (but not necessarily
14806 incrementally -- thanks again to the genius authors of SIP --
14810 /* Find their tag if we haven't got it */
14811 if (ast_strlen_zero(p
->theirtag
)) {
14814 gettag(req
, "From", tag
, sizeof(tag
));
14815 ast_string_field_set(p
, theirtag
, tag
);
14817 snprintf(p
->lastmsg
, sizeof(p
->lastmsg
), "Rx: %s", cmd
);
14819 if (pedanticsipchecking
) {
14820 /* If this is a request packet without a from tag, it's not
14821 correct according to RFC 3261 */
14822 /* Check if this a new request in a new dialog with a totag already attached to it,
14823 RFC 3261 - section 12.2 - and we don't want to mess with recovery */
14824 if (!p
->initreq
.headers
&& ast_test_flag(req
, SIP_PKT_WITH_TOTAG
)) {
14825 /* If this is a first request and it got a to-tag, it is not for us */
14826 if (!ast_test_flag(req
, SIP_PKT_IGNORE
) && req
->method
== SIP_INVITE
) {
14827 transmit_response_reliable(p
, "481 Call/Transaction Does Not Exist", req
);
14828 /* Will cease to exist after ACK */
14829 } else if (req
->method
!= SIP_ACK
) {
14830 transmit_response(p
, "481 Call/Transaction Does Not Exist", req
);
14831 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
14837 if (!e
&& (p
->method
== SIP_INVITE
|| p
->method
== SIP_SUBSCRIBE
|| p
->method
== SIP_REGISTER
|| p
->method
== SIP_NOTIFY
)) {
14838 transmit_response(p
, "400 Bad request", req
);
14839 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
14843 /* Handle various incoming SIP methods in requests */
14844 switch (p
->method
) {
14846 res
= handle_request_options(p
, req
);
14849 res
= handle_request_invite(p
, req
, debug
, seqno
, sin
, recount
, e
);
14852 res
= handle_request_refer(p
, req
, debug
, ignore
, seqno
, nounlock
);
14855 res
= handle_request_cancel(p
, req
);
14858 res
= handle_request_bye(p
, req
);
14861 res
= handle_request_message(p
, req
);
14863 case SIP_SUBSCRIBE
:
14864 res
= handle_request_subscribe(p
, req
, sin
, seqno
, e
);
14867 res
= handle_request_register(p
, req
, sin
, e
);
14870 if (ast_test_flag(req
, SIP_PKT_DEBUG
))
14871 ast_verbose("Receiving INFO!\n");
14873 handle_request_info(p
, req
);
14874 else /* if ignoring, transmit response */
14875 transmit_response(p
, "200 OK", req
);
14878 res
= handle_request_notify(p
, req
, sin
, seqno
, e
);
14881 /* Make sure we don't ignore this */
14882 if (seqno
== p
->pendinginvite
) {
14883 p
->invitestate
= INV_TERMINATED
;
14884 p
->pendinginvite
= 0;
14885 __sip_ack(p
, seqno
, FLAG_RESPONSE
, 0);
14886 if (find_sdp(req
)) {
14887 if (process_sdp(p
, req
))
14892 /* Got an ACK that we did not match. Ignore silently */
14893 if (!p
->lastinvite
&& ast_strlen_zero(p
->randdata
))
14894 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14897 transmit_response_with_allow(p
, "501 Method Not Implemented", req
, 0);
14898 ast_log(LOG_NOTICE
, "Unknown SIP command '%s' from '%s'\n",
14899 cmd
, ast_inet_ntoa(p
->sa
.sin_addr
));
14900 /* If this is some new method, and we don't have a call, destroy it now */
14901 if (!p
->initreq
.headers
)
14902 ast_set_flag(&p
->flags
[0], SIP_NEEDDESTROY
);
14908 /*! \brief Read data from SIP socket
14909 \note sipsock_read locks the owner channel while we are processing the SIP message
14910 \return 1 on error, 0 on success
14911 \note Successful messages is connected to SIP call and forwarded to handle_request()
14913 static int sipsock_read(int *id
, int fd
, short events
, void *ignore
)
14915 struct sip_request req
;
14916 struct sockaddr_in sin
= { 0, };
14919 socklen_t len
= sizeof(sin
);
14924 memset(&req
, 0, sizeof(req
));
14925 res
= recvfrom(sipsock
, req
.data
, sizeof(req
.data
) - 1, 0, (struct sockaddr
*)&sin
, &len
);
14927 #if !defined(__FreeBSD__)
14928 if (errno
== EAGAIN
)
14929 ast_log(LOG_NOTICE
, "SIP: Received packet with bad UDP checksum\n");
14932 if (errno
!= ECONNREFUSED
)
14933 ast_log(LOG_WARNING
, "Recv error: %s\n", strerror(errno
));
14936 if (option_debug
&& res
== sizeof(req
.data
)) {
14937 ast_log(LOG_DEBUG
, "Received packet exceeds buffer. Data is possibly lost\n");
14938 req
.data
[sizeof(req
.data
) - 1] = '\0';
14940 req
.data
[res
] = '\0';
14942 if(sip_debug_test_addr(&sin
)) /* Set the debug flag early on packet level */
14943 ast_set_flag(&req
, SIP_PKT_DEBUG
);
14944 if (pedanticsipchecking
)
14945 req
.len
= lws2sws(req
.data
, req
.len
); /* Fix multiline headers */
14946 if (ast_test_flag(&req
, SIP_PKT_DEBUG
))
14947 ast_verbose("\n<--- SIP read from %s:%d --->\n%s\n<------------->\n", ast_inet_ntoa(sin
.sin_addr
), ntohs(sin
.sin_port
), req
.data
);
14949 parse_request(&req
);
14950 req
.method
= find_sip_method(req
.rlPart1
);
14952 if (ast_test_flag(&req
, SIP_PKT_DEBUG
))
14953 ast_verbose("--- (%d headers %d lines)%s ---\n", req
.headers
, req
.lines
, (req
.headers
+ req
.lines
== 0) ? " Nat keepalive" : "");
14955 if (req
.headers
< 2) /* Must have at least two headers */
14958 /* Process request, with netlock held, and with usual deadlock avoidance */
14959 for (lockretry
= 100; lockretry
> 0; lockretry
--) {
14960 ast_mutex_lock(&netlock
);
14962 /* Find the active SIP dialog or create a new one */
14963 p
= find_call(&req
, &sin
, req
.method
); /* returns p locked */
14966 ast_log(LOG_DEBUG
, "Invalid SIP message - rejected , no callid, len %d\n", req
.len
);
14967 ast_mutex_unlock(&netlock
);
14970 /* Go ahead and lock the owner if it has one -- we may need it */
14971 /* becaues this is deadlock-prone, we need to try and unlock if failed */
14972 if (!p
->owner
|| !ast_channel_trylock(p
->owner
))
14973 break; /* locking succeeded */
14975 ast_log(LOG_DEBUG
, "Failed to grab owner channel lock, trying again. (SIP call %s)\n", p
->callid
);
14976 ast_mutex_unlock(&p
->lock
);
14977 ast_mutex_unlock(&netlock
);
14978 /* Sleep for a very short amount of time */
14983 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
)) /* This is a request or response, note what it was for */
14984 append_history(p
, "Rx", "%s / %s / %s", req
.data
, get_header(&req
, "CSeq"), req
.rlPart2
);
14988 ast_log(LOG_ERROR
, "We could NOT get the channel lock for %s! \n", S_OR(p
->owner
->name
, "- no channel name ??? - "));
14989 ast_log(LOG_ERROR
, "SIP transaction failed: %s \n", p
->callid
);
14990 if (req
.method
!= SIP_ACK
)
14991 transmit_response(p
, "503 Server error", &req
); /* We must respond according to RFC 3261 sec 12.2 */
14992 /* XXX We could add retry-after to make sure they come back */
14993 append_history(p
, "LockFail", "Owner lock failed, transaction failed.");
14997 if (handle_request(p
, &req
, &sin
, &recount
, &nounlock
) == -1) {
14998 /* Request failed */
15000 ast_log(LOG_DEBUG
, "SIP message could not be handled, bad request: %-70.70s\n", p
->callid
[0] ? p
->callid
: "<no callid>");
15003 if (p
->owner
&& !nounlock
)
15004 ast_channel_unlock(p
->owner
);
15005 ast_mutex_unlock(&p
->lock
);
15006 ast_mutex_unlock(&netlock
);
15008 ast_update_use_count();
15013 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
15014 static int sip_send_mwi_to_peer(struct sip_peer
*peer
)
15016 /* Called with peerl lock, but releases it */
15018 int newmsgs
, oldmsgs
;
15020 /* Do we have an IP address? If not, skip this peer */
15021 if (!peer
->addr
.sin_addr
.s_addr
&& !peer
->defaddr
.sin_addr
.s_addr
)
15024 /* Check for messages */
15025 ast_app_inboxcount(peer
->mailbox
, &newmsgs
, &oldmsgs
);
15027 peer
->lastmsgcheck
= time(NULL
);
15029 /* Return now if it's the same thing we told them last time */
15030 if (((newmsgs
> 0x7fff ? 0x7fff0000 : (newmsgs
<< 16)) | (oldmsgs
> 0xffff ? 0xffff : oldmsgs
)) == peer
->lastmsgssent
) {
15035 peer
->lastmsgssent
= ((newmsgs
> 0x7fff ? 0x7fff0000 : (newmsgs
<< 16)) | (oldmsgs
> 0xffff ? 0xffff : oldmsgs
));
15037 if (peer
->mwipvt
) {
15038 /* Base message on subscription */
15041 /* Build temporary dialog for this message */
15042 if (!(p
= sip_alloc(NULL
, NULL
, 0, SIP_NOTIFY
)))
15044 if (create_addr_from_peer(p
, peer
)) {
15045 /* Maybe they're not registered, etc. */
15049 /* Recalculate our side, and recalculate Call ID */
15050 if (ast_sip_ouraddrfor(&p
->sa
.sin_addr
, &p
->ourip
))
15051 p
->ourip
= __ourip
;
15053 build_callid_pvt(p
);
15054 /* Destroy this session after 32 secs */
15055 sip_scheddestroy(p
, DEFAULT_TRANS_TIMEOUT
);
15058 ast_set_flag(&p
->flags
[0], SIP_OUTGOING
);
15059 transmit_notify_with_mwi(p
, newmsgs
, oldmsgs
, peer
->vmexten
);
15063 /*! \brief Check whether peer needs a new MWI notification check */
15064 static int does_peer_need_mwi(struct sip_peer
*peer
)
15066 time_t t
= time(NULL
);
15068 if (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_SUBSCRIBEMWIONLY
) &&
15069 !peer
->mwipvt
) { /* We don't have a subscription */
15070 peer
->lastmsgcheck
= t
; /* Reset timer */
15074 if (!ast_strlen_zero(peer
->mailbox
) && (t
- peer
->lastmsgcheck
) > global_mwitime
)
15081 /*! \brief The SIP monitoring thread
15082 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
15083 (and thus do not have a separate thread) indefinitely
15085 static void *do_monitor(void *data
)
15088 struct sip_pvt
*sip
;
15089 struct sip_peer
*peer
= NULL
;
15091 int fastrestart
= FALSE
;
15092 int lastpeernum
= -1;
15096 /* Add an I/O event to our SIP UDP socket */
15098 sipsock_read_id
= ast_io_add(io
, sipsock
, sipsock_read
, AST_IO_IN
, NULL
);
15100 /* From here on out, we die whenever asked */
15102 /* Check for a reload request */
15103 ast_mutex_lock(&sip_reload_lock
);
15104 reloading
= sip_reloading
;
15105 sip_reloading
= FALSE
;
15106 ast_mutex_unlock(&sip_reload_lock
);
15108 if (option_verbose
> 0)
15109 ast_verbose(VERBOSE_PREFIX_1
"Reloading SIP\n");
15110 sip_do_reload(sip_reloadreason
);
15112 /* Change the I/O fd of our UDP socket */
15114 sipsock_read_id
= ast_io_change(io
, sipsock_read_id
, sipsock
, NULL
, 0, NULL
);
15116 /* Check for interfaces needing to be killed */
15117 ast_mutex_lock(&iflock
);
15120 /* don't scan the interface list if it hasn't been a reasonable period
15121 of time since the last time we did it (when MWI is being sent, we can
15122 get back to this point every millisecond or less)
15124 for (sip
= iflist
; !fastrestart
&& sip
; sip
= sip
->next
) {
15125 ast_mutex_lock(&sip
->lock
);
15126 /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
15127 if (sip
->rtp
&& sip
->owner
&&
15128 (sip
->owner
->_state
== AST_STATE_UP
) &&
15129 !sip
->redirip
.sin_addr
.s_addr
) {
15130 if (sip
->lastrtptx
&&
15131 ast_rtp_get_rtpkeepalive(sip
->rtp
) &&
15132 (t
> sip
->lastrtptx
+ ast_rtp_get_rtpkeepalive(sip
->rtp
))) {
15133 /* Need to send an empty RTP packet */
15134 sip
->lastrtptx
= time(NULL
);
15135 ast_rtp_sendcng(sip
->rtp
, 0);
15137 if (sip
->lastrtprx
&&
15138 (ast_rtp_get_rtptimeout(sip
->rtp
) || ast_rtp_get_rtpholdtimeout(sip
->rtp
)) &&
15139 (t
> sip
->lastrtprx
+ ast_rtp_get_rtptimeout(sip
->rtp
))) {
15140 /* Might be a timeout now -- see if we're on hold */
15141 struct sockaddr_in sin
;
15142 ast_rtp_get_peer(sip
->rtp
, &sin
);
15143 if (sin
.sin_addr
.s_addr
||
15144 (ast_rtp_get_rtpholdtimeout(sip
->rtp
) &&
15145 (t
> sip
->lastrtprx
+ ast_rtp_get_rtpholdtimeout(sip
->rtp
)))) {
15146 /* Needs a hangup */
15147 if (ast_rtp_get_rtptimeout(sip
->rtp
)) {
15148 while (sip
->owner
&& ast_channel_trylock(sip
->owner
)) {
15149 ast_mutex_unlock(&sip
->lock
);
15151 ast_mutex_lock(&sip
->lock
);
15154 if (!(ast_rtp_get_bridged(sip
->rtp
))) {
15155 ast_log(LOG_NOTICE
,
15156 "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
15158 (long) (t
- sip
->lastrtprx
));
15159 /* Issue a softhangup */
15160 ast_softhangup_nolock(sip
->owner
, AST_SOFTHANGUP_DEV
);
15162 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
));
15163 ast_channel_unlock(sip
->owner
);
15164 /* forget the timeouts for this call, since a hangup
15165 has already been requested and we don't want to
15166 repeatedly request hangups
15168 ast_rtp_set_rtptimeout(sip
->rtp
, 0);
15169 ast_rtp_set_rtpholdtimeout(sip
->rtp
, 0);
15171 ast_rtp_set_rtptimeout(sip
->vrtp
, 0);
15172 ast_rtp_set_rtpholdtimeout(sip
->vrtp
, 0);
15179 /* If we have sessions that needs to be destroyed, do it now */
15180 if (ast_test_flag(&sip
->flags
[0], SIP_NEEDDESTROY
) && !sip
->packets
&&
15182 ast_mutex_unlock(&sip
->lock
);
15183 __sip_destroy(sip
, 1);
15184 goto restartsearch
;
15186 ast_mutex_unlock(&sip
->lock
);
15188 ast_mutex_unlock(&iflock
);
15190 pthread_testcancel();
15191 /* Wait for sched or io */
15192 res
= ast_sched_wait(sched
);
15193 if ((res
< 0) || (res
> 1000))
15195 /* If we might need to send more mailboxes, don't wait long at all.*/
15198 res
= ast_io_wait(io
, res
);
15199 if (option_debug
&& res
> 20)
15200 ast_log(LOG_DEBUG
, "chan_sip: ast_io_wait ran %d all at once\n", res
);
15201 ast_mutex_lock(&monlock
);
15203 res
= ast_sched_runq(sched
);
15204 if (option_debug
&& res
>= 20)
15205 ast_log(LOG_DEBUG
, "chan_sip: ast_sched_runq ran %d all at once\n", res
);
15208 /* Send MWI notifications to peers - static and cached realtime peers */
15210 fastrestart
= FALSE
;
15213 /* Find next peer that needs mwi */
15214 ASTOBJ_CONTAINER_TRAVERSE(&peerl
, !peer
, do {
15215 if ((curpeernum
> lastpeernum
) && does_peer_need_mwi(iterator
)) {
15216 fastrestart
= TRUE
;
15217 lastpeernum
= curpeernum
;
15218 peer
= ASTOBJ_REF(iterator
);
15223 /* Send MWI to the peer */
15225 ASTOBJ_WRLOCK(peer
);
15226 sip_send_mwi_to_peer(peer
);
15227 ASTOBJ_UNLOCK(peer
);
15228 ASTOBJ_UNREF(peer
,sip_destroy_peer
);
15230 /* Reset where we come from */
15233 ast_mutex_unlock(&monlock
);
15235 /* Never reached */
15240 /*! \brief Start the channel monitor thread */
15241 static int restart_monitor(void)
15243 /* If we're supposed to be stopped -- stay stopped */
15244 if (monitor_thread
== AST_PTHREADT_STOP
)
15246 ast_mutex_lock(&monlock
);
15247 if (monitor_thread
== pthread_self()) {
15248 ast_mutex_unlock(&monlock
);
15249 ast_log(LOG_WARNING
, "Cannot kill myself\n");
15252 if (monitor_thread
!= AST_PTHREADT_NULL
) {
15253 /* Wake up the thread */
15254 pthread_kill(monitor_thread
, SIGURG
);
15256 /* Start a new monitor */
15257 if (ast_pthread_create_background(&monitor_thread
, NULL
, do_monitor
, NULL
) < 0) {
15258 ast_mutex_unlock(&monlock
);
15259 ast_log(LOG_ERROR
, "Unable to start monitor thread.\n");
15263 ast_mutex_unlock(&monlock
);
15267 /*! \brief React to lack of answer to Qualify poke */
15268 static int sip_poke_noanswer(void *data
)
15270 struct sip_peer
*peer
= data
;
15272 peer
->pokeexpire
= -1;
15273 if (peer
->lastms
> -1) {
15274 ast_log(LOG_NOTICE
, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer
->name
, peer
->lastms
);
15275 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer
->name
, -1);
15278 sip_destroy(peer
->call
);
15281 ast_device_state_changed("SIP/%s", peer
->name
);
15282 /* Try again quickly */
15283 peer
->pokeexpire
= ast_sched_add(sched
, DEFAULT_FREQ_NOTOK
, sip_poke_peer_s
, peer
);
15287 /*! \brief Check availability of peer, also keep NAT open
15288 \note This is done with the interval in qualify= configuration option
15289 Default is 2 seconds */
15290 static int sip_poke_peer(struct sip_peer
*peer
)
15295 if (!peer
->maxms
|| !peer
->addr
.sin_addr
.s_addr
) {
15296 /* IF we have no IP, or this isn't to be monitored, return
15297 imeediately after clearing things out */
15298 if (peer
->pokeexpire
> -1)
15299 ast_sched_del(sched
, peer
->pokeexpire
);
15301 peer
->pokeexpire
= -1;
15307 ast_log(LOG_NOTICE
, "Still have a QUALIFY dialog active, deleting\n");
15308 sip_destroy(peer
->call
);
15310 if (!(p
= peer
->call
= sip_alloc(NULL
, NULL
, 0, SIP_OPTIONS
)))
15313 p
->sa
= peer
->addr
;
15314 p
->recv
= peer
->addr
;
15315 ast_copy_flags(&p
->flags
[0], &peer
->flags
[0], SIP_FLAGS_TO_COPY
);
15316 ast_copy_flags(&p
->flags
[1], &peer
->flags
[1], SIP_PAGE2_FLAGS_TO_COPY
);
15318 /* Send OPTIONs to peer's fullcontact */
15319 if (!ast_strlen_zero(peer
->fullcontact
))
15320 ast_string_field_set(p
, fullcontact
, peer
->fullcontact
);
15322 if (!ast_strlen_zero(peer
->tohost
))
15323 ast_string_field_set(p
, tohost
, peer
->tohost
);
15325 ast_string_field_set(p
, tohost
, ast_inet_ntoa(peer
->addr
.sin_addr
));
15327 /* Recalculate our side, and recalculate Call ID */
15328 if (ast_sip_ouraddrfor(&p
->sa
.sin_addr
, &p
->ourip
))
15329 p
->ourip
= __ourip
;
15331 build_callid_pvt(p
);
15333 if (peer
->pokeexpire
> -1)
15334 ast_sched_del(sched
, peer
->pokeexpire
);
15335 p
->relatedpeer
= peer
;
15336 ast_set_flag(&p
->flags
[0], SIP_OUTGOING
);
15337 #ifdef VOCAL_DATA_HACK
15338 ast_copy_string(p
->username
, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p
->username
));
15339 xmitres
= transmit_invite(p
, SIP_INVITE
, 0, 2);
15341 xmitres
= transmit_invite(p
, SIP_OPTIONS
, 0, 2);
15343 gettimeofday(&peer
->ps
, NULL
);
15344 if (xmitres
== XMIT_ERROR
)
15345 sip_poke_noanswer(peer
); /* Immediately unreachable, network problems */
15347 peer
->pokeexpire
= ast_sched_add(sched
, DEFAULT_MAXMS
* 2, sip_poke_noanswer
, peer
);
15352 /*! \brief Part of PBX channel interface
15354 \par Return values:---
15356 If we have qualify on and the device is not reachable, regardless of registration
15357 state we return AST_DEVICE_UNAVAILABLE
15359 For peers with call limit:
15360 - not registered AST_DEVICE_UNAVAILABLE
15361 - registered, no call AST_DEVICE_NOT_INUSE
15362 - registered, active calls AST_DEVICE_INUSE
15363 - registered, call limit reached AST_DEVICE_BUSY
15364 - registered, onhold AST_DEVICE_ONHOLD
15365 - registered, ringing AST_DEVICE_RINGING
15367 For peers without call limit:
15368 - not registered AST_DEVICE_UNAVAILABLE
15369 - registered AST_DEVICE_NOT_INUSE
15370 - fixed IP (!dynamic) AST_DEVICE_NOT_INUSE
15372 Peers that does not have a known call and can't be reached by OPTIONS
15373 - unreachable AST_DEVICE_UNAVAILABLE
15375 If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
15376 out a state by walking the channel list.
15378 The queue system (\ref app_queue.c) treats a member as "active"
15379 if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
15381 When placing a call to the queue member, queue system sets a member to busy if
15382 != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
15385 static int sip_devicestate(void *data
)
15390 struct hostent
*hp
;
15391 struct ast_hostent ahp
;
15392 struct sip_peer
*p
;
15394 int res
= AST_DEVICE_INVALID
;
15396 /* make sure data is not null. Maybe unnecessary, but better be safe */
15397 host
= ast_strdupa(data
? data
: "");
15398 if ((tmp
= strchr(host
, '@')))
15401 if (option_debug
> 2)
15402 ast_log(LOG_DEBUG
, "Checking device state for peer %s\n", host
);
15404 if ((p
= find_peer(host
, NULL
, 1))) {
15405 if (p
->addr
.sin_addr
.s_addr
|| p
->defaddr
.sin_addr
.s_addr
) {
15406 /* we have an address for the peer */
15408 /* Check status in this order
15411 - Busy (enforced only by call limit)
15412 - Inuse (we have a call)
15413 - Unreachable (qualify)
15414 If we don't find any of these state, report AST_DEVICE_NOT_INUSE
15415 for registered devices */
15418 /* First check for hold or ring states */
15419 res
= AST_DEVICE_ONHOLD
;
15420 else if (p
->inRinging
) {
15421 if (p
->inRinging
== p
->inUse
)
15422 res
= AST_DEVICE_RINGING
;
15424 res
= AST_DEVICE_RINGINUSE
;
15425 } else if (p
->call_limit
&& (p
->inUse
== p
->call_limit
))
15426 /* check call limit */
15427 res
= AST_DEVICE_BUSY
;
15428 else if (p
->call_limit
&& p
->inUse
)
15429 /* Not busy, but we do have a call */
15430 res
= AST_DEVICE_INUSE
;
15431 else if (p
->maxms
&& (p
->lastms
> p
->maxms
))
15432 /* We don't have a call. Are we reachable at all? Requires qualify= */
15433 res
= AST_DEVICE_UNAVAILABLE
;
15434 else /* Default reply if we're registered and have no other data */
15435 res
= AST_DEVICE_NOT_INUSE
;
15437 /* there is no address, it's unavailable */
15438 res
= AST_DEVICE_UNAVAILABLE
;
15440 ASTOBJ_UNREF(p
,sip_destroy_peer
);
15442 hp
= ast_gethostbyname(host
, &ahp
);
15444 res
= AST_DEVICE_UNKNOWN
;
15450 /*! \brief PBX interface function -build SIP pvt structure
15451 SIP calls initiated by the PBX arrive here */
15452 static struct ast_channel
*sip_request_call(const char *type
, int format
, void *data
, int *cause
)
15456 struct ast_channel
*tmpc
= NULL
;
15461 oldformat
= format
;
15462 if (!(format
&= ((AST_FORMAT_MAX_AUDIO
<< 1) - 1))) {
15463 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
));
15464 *cause
= AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
; /* Can't find codec to connect to host */
15468 ast_log(LOG_DEBUG
, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp
, sizeof(tmp
), oldformat
));
15470 if (!(p
= sip_alloc(NULL
, NULL
, 0, SIP_INVITE
))) {
15471 ast_log(LOG_ERROR
, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", (char *)data
);
15472 *cause
= AST_CAUSE_SWITCH_CONGESTION
;
15476 ast_set_flag(&p
->flags
[1], SIP_PAGE2_OUTGOING_CALL
);
15478 if (!(p
->options
= ast_calloc(1, sizeof(*p
->options
)))) {
15480 ast_log(LOG_ERROR
, "Unable to build option SIP data structure - Out of memory\n");
15481 *cause
= AST_CAUSE_SWITCH_CONGESTION
;
15485 ast_copy_string(tmp
, dest
, sizeof(tmp
));
15486 host
= strchr(tmp
, '@');
15491 ext
= strchr(tmp
, '/');
15497 if (create_addr(p
, host
)) {
15498 *cause
= AST_CAUSE_UNREGISTERED
;
15499 if (option_debug
> 2)
15500 ast_log(LOG_DEBUG
, "Cant create SIP call - target device not registred\n");
15504 if (ast_strlen_zero(p
->peername
) && ext
)
15505 ast_string_field_set(p
, peername
, ext
);
15506 /* Recalculate our side, and recalculate Call ID */
15507 if (ast_sip_ouraddrfor(&p
->sa
.sin_addr
, &p
->ourip
))
15508 p
->ourip
= __ourip
;
15510 build_callid_pvt(p
);
15512 /* We have an extension to call, don't use the full contact here */
15513 /* This to enable dialing registered peers with extension dialling,
15514 like SIP/peername/extension
15515 SIP/peername will still use the full contact */
15517 ast_string_field_set(p
, username
, ext
);
15518 ast_string_field_free(p
, fullcontact
);
15521 printf("Setting up to call extension '%s' at '%s'\n", ext
? ext
: "<none>", host
);
15523 p
->prefcodec
= oldformat
; /* Format for this call */
15524 ast_mutex_lock(&p
->lock
);
15525 tmpc
= sip_new(p
, AST_STATE_DOWN
, host
); /* Place the call */
15526 ast_mutex_unlock(&p
->lock
);
15529 ast_update_use_count();
15535 \brief Handle flag-type options common to configuration of devices - users and peers
15536 \param flags array of two struct ast_flags
15537 \param mask array of two struct ast_flags
15538 \param v linked list of config variables to process
15539 \returns non-zero if any config options were handled, zero otherwise
15541 static int handle_common_options(struct ast_flags
*flags
, struct ast_flags
*mask
, struct ast_variable
*v
)
15544 static int dep_insecure_very
= 0;
15545 static int dep_insecure_yes
= 0;
15547 if (!strcasecmp(v
->name
, "trustrpid")) {
15548 ast_set_flag(&mask
[0], SIP_TRUSTRPID
);
15549 ast_set2_flag(&flags
[0], ast_true(v
->value
), SIP_TRUSTRPID
);
15550 } else if (!strcasecmp(v
->name
, "sendrpid")) {
15551 ast_set_flag(&mask
[0], SIP_SENDRPID
);
15552 ast_set2_flag(&flags
[0], ast_true(v
->value
), SIP_SENDRPID
);
15553 } else if (!strcasecmp(v
->name
, "g726nonstandard")) {
15554 ast_set_flag(&mask
[0], SIP_G726_NONSTANDARD
);
15555 ast_set2_flag(&flags
[0], ast_true(v
->value
), SIP_G726_NONSTANDARD
);
15556 } else if (!strcasecmp(v
->name
, "useclientcode")) {
15557 ast_set_flag(&mask
[0], SIP_USECLIENTCODE
);
15558 ast_set2_flag(&flags
[0], ast_true(v
->value
), SIP_USECLIENTCODE
);
15559 } else if (!strcasecmp(v
->name
, "dtmfmode")) {
15560 ast_set_flag(&mask
[0], SIP_DTMF
);
15561 ast_clear_flag(&flags
[0], SIP_DTMF
);
15562 if (!strcasecmp(v
->value
, "inband"))
15563 ast_set_flag(&flags
[0], SIP_DTMF_INBAND
);
15564 else if (!strcasecmp(v
->value
, "rfc2833"))
15565 ast_set_flag(&flags
[0], SIP_DTMF_RFC2833
);
15566 else if (!strcasecmp(v
->value
, "info"))
15567 ast_set_flag(&flags
[0], SIP_DTMF_INFO
);
15568 else if (!strcasecmp(v
->value
, "auto"))
15569 ast_set_flag(&flags
[0], SIP_DTMF_AUTO
);
15571 ast_log(LOG_WARNING
, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v
->value
, v
->lineno
);
15572 ast_set_flag(&flags
[0], SIP_DTMF_RFC2833
);
15574 } else if (!strcasecmp(v
->name
, "nat")) {
15575 ast_set_flag(&mask
[0], SIP_NAT
);
15576 ast_clear_flag(&flags
[0], SIP_NAT
);
15577 if (!strcasecmp(v
->value
, "never"))
15578 ast_set_flag(&flags
[0], SIP_NAT_NEVER
);
15579 else if (!strcasecmp(v
->value
, "route"))
15580 ast_set_flag(&flags
[0], SIP_NAT_ROUTE
);
15581 else if (ast_true(v
->value
))
15582 ast_set_flag(&flags
[0], SIP_NAT_ALWAYS
);
15584 ast_set_flag(&flags
[0], SIP_NAT_RFC3581
);
15585 } else if (!strcasecmp(v
->name
, "canreinvite")) {
15586 ast_set_flag(&mask
[0], SIP_REINVITE
);
15587 ast_clear_flag(&flags
[0], SIP_REINVITE
);
15588 if (ast_true(v
->value
)) {
15589 ast_set_flag(&flags
[0], SIP_CAN_REINVITE
| SIP_CAN_REINVITE_NAT
);
15590 } else if (!ast_false(v
->value
)) {
15592 char *word
, *next
= buf
;
15594 ast_copy_string(buf
, v
->value
, sizeof(buf
));
15595 while ((word
= strsep(&next
, ","))) {
15596 if (!strcasecmp(word
, "update")) {
15597 ast_set_flag(&flags
[0], SIP_REINVITE_UPDATE
| SIP_CAN_REINVITE
);
15598 } else if (!strcasecmp(word
, "nonat")) {
15599 ast_set_flag(&flags
[0], SIP_CAN_REINVITE
);
15600 ast_clear_flag(&flags
[0], SIP_CAN_REINVITE_NAT
);
15602 ast_log(LOG_WARNING
, "Unknown canreinvite mode '%s' on line %d\n", v
->value
, v
->lineno
);
15606 } else if (!strcasecmp(v
->name
, "insecure")) {
15607 ast_set_flag(&mask
[0], SIP_INSECURE_PORT
| SIP_INSECURE_INVITE
);
15608 ast_clear_flag(&flags
[0], SIP_INSECURE_PORT
| SIP_INSECURE_INVITE
);
15609 if (!strcasecmp(v
->value
, "very")) {
15610 ast_set_flag(&flags
[0], SIP_INSECURE_PORT
| SIP_INSECURE_INVITE
);
15611 if (!dep_insecure_very
) {
15612 ast_log(LOG_WARNING
, "insecure=very at line %d is deprecated; use insecure=port,invite instead\n", v
->lineno
);
15613 dep_insecure_very
= 1;
15616 else if (ast_true(v
->value
)) {
15617 ast_set_flag(&flags
[0], SIP_INSECURE_PORT
);
15618 if (!dep_insecure_yes
) {
15619 ast_log(LOG_WARNING
, "insecure=%s at line %d is deprecated; use insecure=port instead\n", v
->value
, v
->lineno
);
15620 dep_insecure_yes
= 1;
15623 else if (!ast_false(v
->value
)) {
15627 ast_copy_string(buf
, v
->value
, sizeof(buf
));
15629 while ((word
= strsep(&next
, ","))) {
15630 if (!strcasecmp(word
, "port"))
15631 ast_set_flag(&flags
[0], SIP_INSECURE_PORT
);
15632 else if (!strcasecmp(word
, "invite"))
15633 ast_set_flag(&flags
[0], SIP_INSECURE_INVITE
);
15635 ast_log(LOG_WARNING
, "Unknown insecure mode '%s' on line %d\n", v
->value
, v
->lineno
);
15638 } else if (!strcasecmp(v
->name
, "progressinband")) {
15639 ast_set_flag(&mask
[0], SIP_PROG_INBAND
);
15640 ast_clear_flag(&flags
[0], SIP_PROG_INBAND
);
15641 if (ast_true(v
->value
))
15642 ast_set_flag(&flags
[0], SIP_PROG_INBAND_YES
);
15643 else if (strcasecmp(v
->value
, "never"))
15644 ast_set_flag(&flags
[0], SIP_PROG_INBAND_NO
);
15645 } else if (!strcasecmp(v
->name
, "promiscredir")) {
15646 ast_set_flag(&mask
[0], SIP_PROMISCREDIR
);
15647 ast_set2_flag(&flags
[0], ast_true(v
->value
), SIP_PROMISCREDIR
);
15648 } else if (!strcasecmp(v
->name
, "videosupport")) {
15649 ast_set_flag(&mask
[1], SIP_PAGE2_VIDEOSUPPORT
);
15650 ast_set2_flag(&flags
[1], ast_true(v
->value
), SIP_PAGE2_VIDEOSUPPORT
);
15651 } else if (!strcasecmp(v
->name
, "allowoverlap")) {
15652 ast_set_flag(&mask
[1], SIP_PAGE2_ALLOWOVERLAP
);
15653 ast_set2_flag(&flags
[1], ast_true(v
->value
), SIP_PAGE2_ALLOWOVERLAP
);
15654 } else if (!strcasecmp(v
->name
, "allowsubscribe")) {
15655 ast_set_flag(&mask
[1], SIP_PAGE2_ALLOWSUBSCRIBE
);
15656 ast_set2_flag(&flags
[1], ast_true(v
->value
), SIP_PAGE2_ALLOWSUBSCRIBE
);
15657 } else if (!strcasecmp(v
->name
, "t38pt_udptl")) {
15658 ast_set_flag(&mask
[1], SIP_PAGE2_T38SUPPORT_UDPTL
);
15659 ast_set2_flag(&flags
[1], ast_true(v
->value
), SIP_PAGE2_T38SUPPORT_UDPTL
);
15660 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
15661 } else if (!strcasecmp(v
->name
, "t38pt_rtp")) {
15662 ast_set_flag(&mask
[1], SIP_PAGE2_T38SUPPORT_RTP
);
15663 ast_set2_flag(&flags
[1], ast_true(v
->value
), SIP_PAGE2_T38SUPPORT_RTP
);
15664 } else if (!strcasecmp(v
->name
, "t38pt_tcp")) {
15665 ast_set_flag(&mask
[1], SIP_PAGE2_T38SUPPORT_TCP
);
15666 ast_set2_flag(&flags
[1], ast_true(v
->value
), SIP_PAGE2_T38SUPPORT_TCP
);
15668 } else if (!strcasecmp(v
->name
, "rfc2833compensate")) {
15669 ast_set_flag(&mask
[1], SIP_PAGE2_RFC2833_COMPENSATE
);
15670 ast_set2_flag(&flags
[1], ast_true(v
->value
), SIP_PAGE2_RFC2833_COMPENSATE
);
15671 } else if (!strcasecmp(v
->name
, "buggymwi")) {
15672 ast_set_flag(&mask
[1], SIP_PAGE2_BUGGY_MWI
);
15673 ast_set2_flag(&flags
[1], ast_true(v
->value
), SIP_PAGE2_BUGGY_MWI
);
15680 /*! \brief Add SIP domain to list of domains we are responsible for */
15681 static int add_sip_domain(const char *domain
, const enum domain_mode mode
, const char *context
)
15685 if (ast_strlen_zero(domain
)) {
15686 ast_log(LOG_WARNING
, "Zero length domain.\n");
15690 if (!(d
= ast_calloc(1, sizeof(*d
))))
15693 ast_copy_string(d
->domain
, domain
, sizeof(d
->domain
));
15695 if (!ast_strlen_zero(context
))
15696 ast_copy_string(d
->context
, context
, sizeof(d
->context
));
15700 AST_LIST_LOCK(&domain_list
);
15701 AST_LIST_INSERT_TAIL(&domain_list
, d
, list
);
15702 AST_LIST_UNLOCK(&domain_list
);
15705 ast_log(LOG_DEBUG
, "Added local SIP domain '%s'\n", domain
);
15710 /*! \brief check_sip_domain: Check if domain part of uri is local to our server */
15711 static int check_sip_domain(const char *domain
, char *context
, size_t len
)
15716 AST_LIST_LOCK(&domain_list
);
15717 AST_LIST_TRAVERSE(&domain_list
, d
, list
) {
15718 if (strcasecmp(d
->domain
, domain
))
15721 if (len
&& !ast_strlen_zero(d
->context
))
15722 ast_copy_string(context
, d
->context
, len
);
15727 AST_LIST_UNLOCK(&domain_list
);
15732 /*! \brief Clear our domain list (at reload) */
15733 static void clear_sip_domains(void)
15737 AST_LIST_LOCK(&domain_list
);
15738 while ((d
= AST_LIST_REMOVE_HEAD(&domain_list
, list
)))
15740 AST_LIST_UNLOCK(&domain_list
);
15744 /*! \brief Add realm authentication in list */
15745 static struct sip_auth
*add_realm_authentication(struct sip_auth
*authlist
, char *configuration
, int lineno
)
15747 char authcopy
[256];
15748 char *username
=NULL
, *realm
=NULL
, *secret
=NULL
, *md5secret
=NULL
;
15750 struct sip_auth
*a
, *b
, *auth
;
15752 if (ast_strlen_zero(configuration
))
15756 ast_log(LOG_DEBUG
, "Auth config :: %s\n", configuration
);
15758 ast_copy_string(authcopy
, configuration
, sizeof(authcopy
));
15759 stringp
= authcopy
;
15761 username
= stringp
;
15762 realm
= strrchr(stringp
, '@');
15765 if (ast_strlen_zero(username
) || ast_strlen_zero(realm
)) {
15766 ast_log(LOG_WARNING
, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno
);
15769 stringp
= username
;
15770 username
= strsep(&stringp
, ":");
15772 secret
= strsep(&stringp
, ":");
15774 stringp
= username
;
15775 md5secret
= strsep(&stringp
,"#");
15778 if (!(auth
= ast_calloc(1, sizeof(*auth
))))
15781 ast_copy_string(auth
->realm
, realm
, sizeof(auth
->realm
));
15782 ast_copy_string(auth
->username
, username
, sizeof(auth
->username
));
15784 ast_copy_string(auth
->secret
, secret
, sizeof(auth
->secret
));
15786 ast_copy_string(auth
->md5secret
, md5secret
, sizeof(auth
->md5secret
));
15788 /* find the end of the list */
15789 for (b
= NULL
, a
= authlist
; a
; b
= a
, a
= a
->next
)
15792 b
->next
= auth
; /* Add structure add end of list */
15796 if (option_verbose
> 2)
15797 ast_verbose("Added authentication for realm %s\n", realm
);
15803 /*! \brief Clear realm authentication list (at reload) */
15804 static int clear_realm_authentication(struct sip_auth
*authlist
)
15806 struct sip_auth
*a
= authlist
;
15807 struct sip_auth
*b
;
15818 /*! \brief Find authentication for a specific realm */
15819 static struct sip_auth
*find_realm_authentication(struct sip_auth
*authlist
, const char *realm
)
15821 struct sip_auth
*a
;
15823 for (a
= authlist
; a
; a
= a
->next
) {
15824 if (!strcasecmp(a
->realm
, realm
))
15831 /*! \brief Initiate a SIP user structure from configuration (configuration or realtime) */
15832 static struct sip_user
*build_user(const char *name
, struct ast_variable
*v
, int realtime
)
15834 struct sip_user
*user
;
15836 struct ast_ha
*oldha
= NULL
;
15837 char *varname
= NULL
, *varval
= NULL
;
15838 struct ast_variable
*tmpvar
= NULL
;
15839 struct ast_flags userflags
[2] = {{(0)}};
15840 struct ast_flags mask
[2] = {{(0)}};
15843 if (!(user
= ast_calloc(1, sizeof(*user
))))
15848 ast_copy_string(user
->name
, name
, sizeof(user
->name
));
15851 ast_copy_flags(&user
->flags
[0], &global_flags
[0], SIP_FLAGS_TO_COPY
);
15852 ast_copy_flags(&user
->flags
[1], &global_flags
[1], SIP_PAGE2_FLAGS_TO_COPY
);
15853 user
->capability
= global_capability
;
15854 user
->allowtransfer
= global_allowtransfer
;
15855 user
->maxcallbitrate
= default_maxcallbitrate
;
15856 user
->autoframing
= global_autoframing
;
15857 user
->prefs
= default_prefs
;
15858 /* set default context */
15859 strcpy(user
->context
, default_context
);
15860 strcpy(user
->language
, default_language
);
15861 strcpy(user
->mohinterpret
, default_mohinterpret
);
15862 strcpy(user
->mohsuggest
, default_mohsuggest
);
15863 for (; v
; v
= v
->next
) {
15864 if (handle_common_options(&userflags
[0], &mask
[0], v
))
15867 if (!strcasecmp(v
->name
, "context")) {
15868 ast_copy_string(user
->context
, v
->value
, sizeof(user
->context
));
15869 } else if (!strcasecmp(v
->name
, "subscribecontext")) {
15870 ast_copy_string(user
->subscribecontext
, v
->value
, sizeof(user
->subscribecontext
));
15871 } else if (!strcasecmp(v
->name
, "setvar")) {
15872 varname
= ast_strdupa(v
->value
);
15873 if ((varval
= strchr(varname
,'='))) {
15875 if ((tmpvar
= ast_variable_new(varname
, varval
))) {
15876 tmpvar
->next
= user
->chanvars
;
15877 user
->chanvars
= tmpvar
;
15880 } else if (!strcasecmp(v
->name
, "permit") ||
15881 !strcasecmp(v
->name
, "deny")) {
15882 user
->ha
= ast_append_ha(v
->name
, v
->value
, user
->ha
);
15883 } else if (!strcasecmp(v
->name
, "allowtransfer")) {
15884 user
->allowtransfer
= ast_true(v
->value
) ? TRANSFER_OPENFORALL
: TRANSFER_CLOSED
;
15885 } else if (!strcasecmp(v
->name
, "secret")) {
15886 ast_copy_string(user
->secret
, v
->value
, sizeof(user
->secret
));
15887 } else if (!strcasecmp(v
->name
, "md5secret")) {
15888 ast_copy_string(user
->md5secret
, v
->value
, sizeof(user
->md5secret
));
15889 } else if (!strcasecmp(v
->name
, "callerid")) {
15890 ast_callerid_split(v
->value
, user
->cid_name
, sizeof(user
->cid_name
), user
->cid_num
, sizeof(user
->cid_num
));
15891 } else if (!strcasecmp(v
->name
, "fullname")) {
15892 ast_copy_string(user
->cid_name
, v
->value
, sizeof(user
->cid_name
));
15893 } else if (!strcasecmp(v
->name
, "cid_number")) {
15894 ast_copy_string(user
->cid_num
, v
->value
, sizeof(user
->cid_num
));
15895 } else if (!strcasecmp(v
->name
, "callgroup")) {
15896 user
->callgroup
= ast_get_group(v
->value
);
15897 } else if (!strcasecmp(v
->name
, "pickupgroup")) {
15898 user
->pickupgroup
= ast_get_group(v
->value
);
15899 } else if (!strcasecmp(v
->name
, "language")) {
15900 ast_copy_string(user
->language
, v
->value
, sizeof(user
->language
));
15901 } else if (!strcasecmp(v
->name
, "mohinterpret")
15902 || !strcasecmp(v
->name
, "musicclass") || !strcasecmp(v
->name
, "musiconhold")) {
15903 ast_copy_string(user
->mohinterpret
, v
->value
, sizeof(user
->mohinterpret
));
15904 } else if (!strcasecmp(v
->name
, "mohsuggest")) {
15905 ast_copy_string(user
->mohsuggest
, v
->value
, sizeof(user
->mohsuggest
));
15906 } else if (!strcasecmp(v
->name
, "accountcode")) {
15907 ast_copy_string(user
->accountcode
, v
->value
, sizeof(user
->accountcode
));
15908 } else if (!strcasecmp(v
->name
, "call-limit")) {
15909 user
->call_limit
= atoi(v
->value
);
15910 if (user
->call_limit
< 0)
15911 user
->call_limit
= 0;
15912 } else if (!strcasecmp(v
->name
, "amaflags")) {
15913 format
= ast_cdr_amaflags2int(v
->value
);
15915 ast_log(LOG_WARNING
, "Invalid AMA Flags: %s at line %d\n", v
->value
, v
->lineno
);
15917 user
->amaflags
= format
;
15919 } else if (!strcasecmp(v
->name
, "allow")) {
15920 ast_parse_allow_disallow(&user
->prefs
, &user
->capability
, v
->value
, 1);
15921 } else if (!strcasecmp(v
->name
, "disallow")) {
15922 ast_parse_allow_disallow(&user
->prefs
, &user
->capability
, v
->value
, 0);
15923 } else if (!strcasecmp(v
->name
, "autoframing")) {
15924 user
->autoframing
= ast_true(v
->value
);
15925 } else if (!strcasecmp(v
->name
, "callingpres")) {
15926 user
->callingpres
= ast_parse_caller_presentation(v
->value
);
15927 if (user
->callingpres
== -1)
15928 user
->callingpres
= atoi(v
->value
);
15929 } else if (!strcasecmp(v
->name
, "maxcallbitrate")) {
15930 user
->maxcallbitrate
= atoi(v
->value
);
15931 if (user
->maxcallbitrate
< 0)
15932 user
->maxcallbitrate
= default_maxcallbitrate
;
15934 /* We can't just report unknown options here because this may be a
15935 * type=friend entry. All user options are valid for a peer, but not
15936 * the other way around. */
15938 ast_copy_flags(&user
->flags
[0], &userflags
[0], mask
[0].flags
);
15939 ast_copy_flags(&user
->flags
[1], &userflags
[1], mask
[1].flags
);
15940 if (ast_test_flag(&user
->flags
[1], SIP_PAGE2_ALLOWSUBSCRIBE
))
15941 global_allowsubscribe
= TRUE
; /* No global ban any more */
15942 ast_free_ha(oldha
);
15946 /*! \brief Set peer defaults before configuring specific configurations */
15947 static void set_peer_defaults(struct sip_peer
*peer
)
15949 if (peer
->expire
== 0) {
15950 /* Don't reset expire or port time during reload
15951 if we have an active registration
15954 peer
->pokeexpire
= -1;
15955 peer
->addr
.sin_port
= htons(STANDARD_SIP_PORT
);
15957 ast_copy_flags(&peer
->flags
[0], &global_flags
[0], SIP_FLAGS_TO_COPY
);
15958 ast_copy_flags(&peer
->flags
[1], &global_flags
[1], SIP_PAGE2_FLAGS_TO_COPY
);
15959 strcpy(peer
->context
, default_context
);
15960 strcpy(peer
->subscribecontext
, default_subscribecontext
);
15961 strcpy(peer
->language
, default_language
);
15962 strcpy(peer
->mohinterpret
, default_mohinterpret
);
15963 strcpy(peer
->mohsuggest
, default_mohsuggest
);
15964 peer
->addr
.sin_family
= AF_INET
;
15965 peer
->defaddr
.sin_family
= AF_INET
;
15966 peer
->capability
= global_capability
;
15967 peer
->maxcallbitrate
= default_maxcallbitrate
;
15968 peer
->rtptimeout
= global_rtptimeout
;
15969 peer
->rtpholdtimeout
= global_rtpholdtimeout
;
15970 peer
->rtpkeepalive
= global_rtpkeepalive
;
15971 peer
->allowtransfer
= global_allowtransfer
;
15972 peer
->autoframing
= global_autoframing
;
15973 strcpy(peer
->vmexten
, default_vmexten
);
15974 peer
->secret
[0] = '\0';
15975 peer
->md5secret
[0] = '\0';
15976 peer
->cid_num
[0] = '\0';
15977 peer
->cid_name
[0] = '\0';
15978 peer
->fromdomain
[0] = '\0';
15979 peer
->fromuser
[0] = '\0';
15980 peer
->regexten
[0] = '\0';
15981 peer
->mailbox
[0] = '\0';
15982 peer
->callgroup
= 0;
15983 peer
->pickupgroup
= 0;
15984 peer
->maxms
= default_qualify
;
15985 peer
->prefs
= default_prefs
;
15988 /*! \brief Create temporary peer (used in autocreatepeer mode) */
15989 static struct sip_peer
*temp_peer(const char *name
)
15991 struct sip_peer
*peer
;
15993 if (!(peer
= ast_calloc(1, sizeof(*peer
))))
15998 set_peer_defaults(peer
);
16000 ast_copy_string(peer
->name
, name
, sizeof(peer
->name
));
16002 ast_set_flag(&peer
->flags
[1], SIP_PAGE2_SELFDESTRUCT
);
16003 ast_set_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
);
16004 peer
->prefs
= default_prefs
;
16005 reg_source_db(peer
);
16010 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
16011 static struct sip_peer
*build_peer(const char *name
, struct ast_variable
*v
, struct ast_variable
*alt
, int realtime
)
16013 struct sip_peer
*peer
= NULL
;
16014 struct ast_ha
*oldha
= NULL
;
16015 int obproxyfound
=0;
16018 int format
=0; /* Ama flags */
16019 time_t regseconds
= 0;
16020 char *varname
= NULL
, *varval
= NULL
;
16021 struct ast_variable
*tmpvar
= NULL
;
16022 struct ast_flags peerflags
[2] = {{(0)}};
16023 struct ast_flags mask
[2] = {{(0)}};
16027 /* Note we do NOT use find_peer here, to avoid realtime recursion */
16028 /* We also use a case-sensitive comparison (unlike find_peer) so
16029 that case changes made to the peer name will be properly handled
16032 peer
= ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl
, name
, name
, 0, 0, strcmp
);
16035 /* Already in the list, remove it and it will be added back (or FREE'd) */
16037 if (!(peer
->objflags
& ASTOBJ_FLAG_MARKED
))
16040 if (!(peer
= ast_calloc(1, sizeof(*peer
))))
16049 /* Note that our peer HAS had its reference count incrased */
16051 peer
->lastmsgssent
= -1;
16054 set_peer_defaults(peer
); /* Set peer defaults */
16056 if (!found
&& name
)
16057 ast_copy_string(peer
->name
, name
, sizeof(peer
->name
));
16059 /* If we have channel variables, remove them (reload) */
16060 if (peer
->chanvars
) {
16061 ast_variables_destroy(peer
->chanvars
);
16062 peer
->chanvars
= NULL
;
16063 /* XXX should unregister ? */
16065 for (; v
|| ((v
= alt
) && !(alt
=NULL
)); v
= v
->next
) {
16066 if (handle_common_options(&peerflags
[0], &mask
[0], v
))
16068 if (realtime
&& !strcasecmp(v
->name
, "regseconds")) {
16069 ast_get_time_t(v
->value
, ®seconds
, 0, NULL
);
16070 } else if (realtime
&& !strcasecmp(v
->name
, "ipaddr") && !ast_strlen_zero(v
->value
) ) {
16071 inet_aton(v
->value
, &(peer
->addr
.sin_addr
));
16072 } else if (realtime
&& !strcasecmp(v
->name
, "name"))
16073 ast_copy_string(peer
->name
, v
->value
, sizeof(peer
->name
));
16074 else if (realtime
&& !strcasecmp(v
->name
, "fullcontact")) {
16075 ast_copy_string(peer
->fullcontact
, v
->value
, sizeof(peer
->fullcontact
));
16076 ast_set_flag(&peer
->flags
[1], SIP_PAGE2_RT_FROMCONTACT
);
16077 } else if (!strcasecmp(v
->name
, "secret"))
16078 ast_copy_string(peer
->secret
, v
->value
, sizeof(peer
->secret
));
16079 else if (!strcasecmp(v
->name
, "md5secret"))
16080 ast_copy_string(peer
->md5secret
, v
->value
, sizeof(peer
->md5secret
));
16081 else if (!strcasecmp(v
->name
, "auth"))
16082 peer
->auth
= add_realm_authentication(peer
->auth
, v
->value
, v
->lineno
);
16083 else if (!strcasecmp(v
->name
, "callerid")) {
16084 ast_callerid_split(v
->value
, peer
->cid_name
, sizeof(peer
->cid_name
), peer
->cid_num
, sizeof(peer
->cid_num
));
16085 } else if (!strcasecmp(v
->name
, "fullname")) {
16086 ast_copy_string(peer
->cid_name
, v
->value
, sizeof(peer
->cid_name
));
16087 } else if (!strcasecmp(v
->name
, "cid_number")) {
16088 ast_copy_string(peer
->cid_num
, v
->value
, sizeof(peer
->cid_num
));
16089 } else if (!strcasecmp(v
->name
, "context")) {
16090 ast_copy_string(peer
->context
, v
->value
, sizeof(peer
->context
));
16091 } else if (!strcasecmp(v
->name
, "subscribecontext")) {
16092 ast_copy_string(peer
->subscribecontext
, v
->value
, sizeof(peer
->subscribecontext
));
16093 } else if (!strcasecmp(v
->name
, "fromdomain")) {
16094 ast_copy_string(peer
->fromdomain
, v
->value
, sizeof(peer
->fromdomain
));
16095 } else if (!strcasecmp(v
->name
, "usereqphone")) {
16096 ast_set2_flag(&peer
->flags
[0], ast_true(v
->value
), SIP_USEREQPHONE
);
16097 } else if (!strcasecmp(v
->name
, "fromuser")) {
16098 ast_copy_string(peer
->fromuser
, v
->value
, sizeof(peer
->fromuser
));
16099 } else if (!strcasecmp(v
->name
, "host") || !strcasecmp(v
->name
, "outboundproxy")) {
16100 if (!strcasecmp(v
->value
, "dynamic")) {
16101 if (!strcasecmp(v
->name
, "outboundproxy") || obproxyfound
) {
16102 ast_log(LOG_WARNING
, "You can't have a dynamic outbound proxy, you big silly head at line %d.\n", v
->lineno
);
16104 /* They'll register with us */
16105 if (!found
|| !ast_test_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
)) {
16106 /* Initialize stuff if this is a new peer, or if it used to be
16107 * non-dynamic before the reload. */
16108 memset(&peer
->addr
.sin_addr
, 0, 4);
16109 if (peer
->addr
.sin_port
) {
16110 /* If we've already got a port, make it the default rather than absolute */
16111 peer
->defaddr
.sin_port
= peer
->addr
.sin_port
;
16112 peer
->addr
.sin_port
= 0;
16115 ast_set_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
);
16118 /* Non-dynamic. Make sure we become that way if we're not */
16119 if (peer
->expire
> -1)
16120 ast_sched_del(sched
, peer
->expire
);
16122 ast_clear_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
);
16123 if (!obproxyfound
|| !strcasecmp(v
->name
, "outboundproxy")) {
16124 if (ast_get_ip_or_srv(&peer
->addr
, v
->value
, srvlookup
? "_sip._udp" : NULL
)) {
16125 ASTOBJ_UNREF(peer
, sip_destroy_peer
);
16129 if (!strcasecmp(v
->name
, "outboundproxy"))
16132 ast_copy_string(peer
->tohost
, v
->value
, sizeof(peer
->tohost
));
16133 if (!peer
->addr
.sin_port
)
16134 peer
->addr
.sin_port
= htons(STANDARD_SIP_PORT
);
16137 } else if (!strcasecmp(v
->name
, "defaultip")) {
16138 if (ast_get_ip(&peer
->defaddr
, v
->value
)) {
16139 ASTOBJ_UNREF(peer
, sip_destroy_peer
);
16142 } else if (!strcasecmp(v
->name
, "permit") || !strcasecmp(v
->name
, "deny")) {
16143 peer
->ha
= ast_append_ha(v
->name
, v
->value
, peer
->ha
);
16144 } else if (!strcasecmp(v
->name
, "port")) {
16145 if (!realtime
&& ast_test_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
))
16146 peer
->defaddr
.sin_port
= htons(atoi(v
->value
));
16148 peer
->addr
.sin_port
= htons(atoi(v
->value
));
16149 } else if (!strcasecmp(v
->name
, "callingpres")) {
16150 peer
->callingpres
= ast_parse_caller_presentation(v
->value
);
16151 if (peer
->callingpres
== -1)
16152 peer
->callingpres
= atoi(v
->value
);
16153 } else if (!strcasecmp(v
->name
, "username")) {
16154 ast_copy_string(peer
->username
, v
->value
, sizeof(peer
->username
));
16155 } else if (!strcasecmp(v
->name
, "language")) {
16156 ast_copy_string(peer
->language
, v
->value
, sizeof(peer
->language
));
16157 } else if (!strcasecmp(v
->name
, "regexten")) {
16158 ast_copy_string(peer
->regexten
, v
->value
, sizeof(peer
->regexten
));
16159 } else if (!strcasecmp(v
->name
, "call-limit") || !strcasecmp(v
->name
, "incominglimit")) {
16160 peer
->call_limit
= atoi(v
->value
);
16161 if (peer
->call_limit
< 0)
16162 peer
->call_limit
= 0;
16163 } else if (!strcasecmp(v
->name
, "amaflags")) {
16164 format
= ast_cdr_amaflags2int(v
->value
);
16166 ast_log(LOG_WARNING
, "Invalid AMA Flags for peer: %s at line %d\n", v
->value
, v
->lineno
);
16168 peer
->amaflags
= format
;
16170 } else if (!strcasecmp(v
->name
, "accountcode")) {
16171 ast_copy_string(peer
->accountcode
, v
->value
, sizeof(peer
->accountcode
));
16172 } else if (!strcasecmp(v
->name
, "mohinterpret")
16173 || !strcasecmp(v
->name
, "musicclass") || !strcasecmp(v
->name
, "musiconhold")) {
16174 ast_copy_string(peer
->mohinterpret
, v
->value
, sizeof(peer
->mohinterpret
));
16175 } else if (!strcasecmp(v
->name
, "mohsuggest")) {
16176 ast_copy_string(peer
->mohsuggest
, v
->value
, sizeof(peer
->mohsuggest
));
16177 } else if (!strcasecmp(v
->name
, "mailbox")) {
16178 ast_copy_string(peer
->mailbox
, v
->value
, sizeof(peer
->mailbox
));
16179 } else if (!strcasecmp(v
->name
, "subscribemwi")) {
16180 ast_set2_flag(&peer
->flags
[1], ast_true(v
->value
), SIP_PAGE2_SUBSCRIBEMWIONLY
);
16181 } else if (!strcasecmp(v
->name
, "vmexten")) {
16182 ast_copy_string(peer
->vmexten
, v
->value
, sizeof(peer
->vmexten
));
16183 } else if (!strcasecmp(v
->name
, "callgroup")) {
16184 peer
->callgroup
= ast_get_group(v
->value
);
16185 } else if (!strcasecmp(v
->name
, "allowtransfer")) {
16186 peer
->allowtransfer
= ast_true(v
->value
) ? TRANSFER_OPENFORALL
: TRANSFER_CLOSED
;
16187 } else if (!strcasecmp(v
->name
, "pickupgroup")) {
16188 peer
->pickupgroup
= ast_get_group(v
->value
);
16189 } else if (!strcasecmp(v
->name
, "allow")) {
16190 ast_parse_allow_disallow(&peer
->prefs
, &peer
->capability
, v
->value
, 1);
16191 } else if (!strcasecmp(v
->name
, "disallow")) {
16192 ast_parse_allow_disallow(&peer
->prefs
, &peer
->capability
, v
->value
, 0);
16193 } else if (!strcasecmp(v
->name
, "autoframing")) {
16194 peer
->autoframing
= ast_true(v
->value
);
16195 } else if (!strcasecmp(v
->name
, "rtptimeout")) {
16196 if ((sscanf(v
->value
, "%d", &peer
->rtptimeout
) != 1) || (peer
->rtptimeout
< 0)) {
16197 ast_log(LOG_WARNING
, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v
->value
, v
->lineno
);
16198 peer
->rtptimeout
= global_rtptimeout
;
16200 } else if (!strcasecmp(v
->name
, "rtpholdtimeout")) {
16201 if ((sscanf(v
->value
, "%d", &peer
->rtpholdtimeout
) != 1) || (peer
->rtpholdtimeout
< 0)) {
16202 ast_log(LOG_WARNING
, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v
->value
, v
->lineno
);
16203 peer
->rtpholdtimeout
= global_rtpholdtimeout
;
16205 } else if (!strcasecmp(v
->name
, "rtpkeepalive")) {
16206 if ((sscanf(v
->value
, "%d", &peer
->rtpkeepalive
) != 1) || (peer
->rtpkeepalive
< 0)) {
16207 ast_log(LOG_WARNING
, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v
->value
, v
->lineno
);
16208 peer
->rtpkeepalive
= global_rtpkeepalive
;
16210 } else if (!strcasecmp(v
->name
, "setvar")) {
16211 /* Set peer channel variable */
16212 varname
= ast_strdupa(v
->value
);
16213 if ((varval
= strchr(varname
, '='))) {
16215 if ((tmpvar
= ast_variable_new(varname
, varval
))) {
16216 tmpvar
->next
= peer
->chanvars
;
16217 peer
->chanvars
= tmpvar
;
16220 } else if (!strcasecmp(v
->name
, "qualify")) {
16221 if (!strcasecmp(v
->value
, "no")) {
16223 } else if (!strcasecmp(v
->value
, "yes")) {
16224 peer
->maxms
= DEFAULT_MAXMS
;
16225 } else if (sscanf(v
->value
, "%d", &peer
->maxms
) != 1) {
16226 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
);
16229 } else if (!strcasecmp(v
->name
, "maxcallbitrate")) {
16230 peer
->maxcallbitrate
= atoi(v
->value
);
16231 if (peer
->maxcallbitrate
< 0)
16232 peer
->maxcallbitrate
= default_maxcallbitrate
;
16235 if (!ast_test_flag(&global_flags
[1], SIP_PAGE2_IGNOREREGEXPIRE
) && ast_test_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
) && realtime
) {
16236 time_t nowtime
= time(NULL
);
16238 if ((nowtime
- regseconds
) > 0) {
16239 destroy_association(peer
);
16240 memset(&peer
->addr
, 0, sizeof(peer
->addr
));
16242 ast_log(LOG_DEBUG
, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime
- regseconds
), (int)regseconds
, (int)nowtime
);
16245 ast_copy_flags(&peer
->flags
[0], &peerflags
[0], mask
[0].flags
);
16246 ast_copy_flags(&peer
->flags
[1], &peerflags
[1], mask
[1].flags
);
16247 if (ast_test_flag(&peer
->flags
[1], SIP_PAGE2_ALLOWSUBSCRIBE
))
16248 global_allowsubscribe
= TRUE
; /* No global ban any more */
16249 if (!found
&& ast_test_flag(&peer
->flags
[1], SIP_PAGE2_DYNAMIC
) && !ast_test_flag(&peer
->flags
[0], SIP_REALTIME
))
16250 reg_source_db(peer
);
16251 ASTOBJ_UNMARK(peer
);
16252 ast_free_ha(oldha
);
16256 /*! \brief Re-read SIP.conf config file
16257 \note This function reloads all config data, except for
16258 active peers (with registrations). They will only
16259 change configuration data at restart, not at reload.
16260 SIP debug and recordhistory state will not change
16262 static int reload_config(enum channelreloadreason reason
)
16264 struct ast_config
*cfg
, *ucfg
;
16265 struct ast_variable
*v
;
16266 struct sip_peer
*peer
;
16267 struct sip_user
*user
;
16268 struct ast_hostent ahp
;
16269 char *cat
, *stringp
, *context
, *oldregcontext
;
16270 char newcontexts
[AST_MAX_CONTEXT
], oldcontexts
[AST_MAX_CONTEXT
];
16271 struct hostent
*hp
;
16273 struct ast_flags dummy
[2];
16274 int auto_sip_domains
= FALSE
;
16275 struct sockaddr_in old_bindaddr
= bindaddr
;
16276 int registry_count
= 0, peer_count
= 0, user_count
= 0;
16277 unsigned int temp_tos
= 0;
16278 struct ast_flags debugflag
= {0};
16280 cfg
= ast_config_load(config
);
16282 /* We *must* have a config file otherwise stop immediately */
16284 ast_log(LOG_NOTICE
, "Unable to load config %s\n", config
);
16288 /* Initialize copy of current global_regcontext for later use in removing stale contexts */
16289 ast_copy_string(oldcontexts
, global_regcontext
, sizeof(oldcontexts
));
16290 oldregcontext
= oldcontexts
;
16292 /* Clear all flags before setting default values */
16293 /* Preserve debugging settings for console */
16294 ast_copy_flags(&debugflag
, &global_flags
[1], SIP_PAGE2_DEBUG_CONSOLE
);
16295 ast_clear_flag(&global_flags
[0], AST_FLAGS_ALL
);
16296 ast_clear_flag(&global_flags
[1], AST_FLAGS_ALL
);
16297 ast_copy_flags(&global_flags
[1], &debugflag
, SIP_PAGE2_DEBUG_CONSOLE
);
16299 /* Reset IP addresses */
16300 memset(&bindaddr
, 0, sizeof(bindaddr
));
16301 memset(&localaddr
, 0, sizeof(localaddr
));
16302 memset(&externip
, 0, sizeof(externip
));
16303 memset(&default_prefs
, 0 , sizeof(default_prefs
));
16304 outboundproxyip
.sin_port
= htons(STANDARD_SIP_PORT
);
16305 outboundproxyip
.sin_family
= AF_INET
; /* Type of address: IPv4 */
16306 ourport
= STANDARD_SIP_PORT
;
16307 srvlookup
= DEFAULT_SRVLOOKUP
;
16308 global_tos_sip
= DEFAULT_TOS_SIP
;
16309 global_tos_audio
= DEFAULT_TOS_AUDIO
;
16310 global_tos_video
= DEFAULT_TOS_VIDEO
;
16311 externhost
[0] = '\0'; /* External host name (for behind NAT DynDNS support) */
16312 externexpire
= 0; /* Expiration for DNS re-issuing */
16313 externrefresh
= 10;
16314 memset(&outboundproxyip
, 0, sizeof(outboundproxyip
));
16316 /* Reset channel settings to default before re-configuring */
16317 allow_external_domains
= DEFAULT_ALLOW_EXT_DOM
; /* Allow external invites */
16318 global_regcontext
[0] = '\0';
16319 expiry
= DEFAULT_EXPIRY
;
16320 global_notifyringing
= DEFAULT_NOTIFYRINGING
;
16321 global_limitonpeers
= FALSE
;
16322 global_directrtpsetup
= FALSE
; /* Experimental feature, disabled by default */
16323 global_notifyhold
= FALSE
;
16324 global_alwaysauthreject
= 0;
16325 global_allowsubscribe
= FALSE
;
16326 ast_copy_string(global_useragent
, DEFAULT_USERAGENT
, sizeof(global_useragent
));
16327 ast_copy_string(default_notifymime
, DEFAULT_NOTIFYMIME
, sizeof(default_notifymime
));
16328 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME
))
16329 ast_copy_string(global_realm
, DEFAULT_REALM
, sizeof(global_realm
));
16331 ast_copy_string(global_realm
, ast_config_AST_SYSTEM_NAME
, sizeof(global_realm
));
16332 ast_copy_string(default_callerid
, DEFAULT_CALLERID
, sizeof(default_callerid
));
16333 compactheaders
= DEFAULT_COMPACTHEADERS
;
16334 global_reg_timeout
= DEFAULT_REGISTRATION_TIMEOUT
;
16335 global_regattempts_max
= 0;
16336 pedanticsipchecking
= DEFAULT_PEDANTIC
;
16337 global_mwitime
= DEFAULT_MWITIME
;
16338 autocreatepeer
= DEFAULT_AUTOCREATEPEER
;
16339 global_autoframing
= 0;
16340 global_allowguest
= DEFAULT_ALLOWGUEST
;
16341 global_rtptimeout
= 0;
16342 global_rtpholdtimeout
= 0;
16343 global_rtpkeepalive
= 0;
16344 global_allowtransfer
= TRANSFER_OPENFORALL
; /* Merrily accept all transfers by default */
16345 global_rtautoclear
= 120;
16346 ast_set_flag(&global_flags
[1], SIP_PAGE2_ALLOWSUBSCRIBE
); /* Default for peers, users: TRUE */
16347 ast_set_flag(&global_flags
[1], SIP_PAGE2_ALLOWOVERLAP
); /* Default for peers, users: TRUE */
16348 ast_set_flag(&global_flags
[1], SIP_PAGE2_RTUPDATE
);
16350 /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for peers and users */
16351 ast_copy_string(default_context
, DEFAULT_CONTEXT
, sizeof(default_context
));
16352 default_subscribecontext
[0] = '\0';
16353 default_language
[0] = '\0';
16354 default_fromdomain
[0] = '\0';
16355 default_qualify
= DEFAULT_QUALIFY
;
16356 default_maxcallbitrate
= DEFAULT_MAX_CALL_BITRATE
;
16357 ast_copy_string(default_mohinterpret
, DEFAULT_MOHINTERPRET
, sizeof(default_mohinterpret
));
16358 ast_copy_string(default_mohsuggest
, DEFAULT_MOHSUGGEST
, sizeof(default_mohsuggest
));
16359 ast_copy_string(default_vmexten
, DEFAULT_VMEXTEN
, sizeof(default_vmexten
));
16360 ast_set_flag(&global_flags
[0], SIP_DTMF_RFC2833
); /*!< Default DTMF setting: RFC2833 */
16361 ast_set_flag(&global_flags
[0], SIP_NAT_RFC3581
); /*!< NAT support if requested by device with rport */
16362 ast_set_flag(&global_flags
[0], SIP_CAN_REINVITE
); /*!< Allow re-invites */
16364 /* Debugging settings, always default to off */
16365 dumphistory
= FALSE
;
16366 recordhistory
= FALSE
;
16367 ast_clear_flag(&global_flags
[1], SIP_PAGE2_DEBUG_CONFIG
);
16369 /* Misc settings for the channel */
16370 global_relaxdtmf
= FALSE
;
16371 global_callevents
= FALSE
;
16372 global_t1min
= DEFAULT_T1MIN
;
16374 global_matchexterniplocally
= FALSE
;
16376 /* Copy the default jb config over global_jbconf */
16377 memcpy(&global_jbconf
, &default_jbconf
, sizeof(struct ast_jb_conf
));
16379 ast_clear_flag(&global_flags
[1], SIP_PAGE2_VIDEOSUPPORT
);
16381 /* Read the [general] config section of sip.conf (or from realtime config) */
16382 for (v
= ast_variable_browse(cfg
, "general"); v
; v
= v
->next
) {
16383 if (handle_common_options(&global_flags
[0], &dummy
[0], v
))
16385 /* handle jb conf */
16386 if (!ast_jb_read_conf(&global_jbconf
, v
->name
, v
->value
))
16389 /* Create the interface list */
16390 if (!strcasecmp(v
->name
, "context")) {
16391 ast_copy_string(default_context
, v
->value
, sizeof(default_context
));
16392 } else if (!strcasecmp(v
->name
, "allowguest")) {
16393 global_allowguest
= ast_true(v
->value
) ? 1 : 0;
16394 } else if (!strcasecmp(v
->name
, "realm")) {
16395 ast_copy_string(global_realm
, v
->value
, sizeof(global_realm
));
16396 } else if (!strcasecmp(v
->name
, "useragent")) {
16397 ast_copy_string(global_useragent
, v
->value
, sizeof(global_useragent
));
16399 ast_log(LOG_DEBUG
, "Setting SIP channel User-Agent Name to %s\n", global_useragent
);
16400 } else if (!strcasecmp(v
->name
, "allowtransfer")) {
16401 global_allowtransfer
= ast_true(v
->value
) ? TRANSFER_OPENFORALL
: TRANSFER_CLOSED
;
16402 } else if (!strcasecmp(v
->name
, "rtcachefriends")) {
16403 ast_set2_flag(&global_flags
[1], ast_true(v
->value
), SIP_PAGE2_RTCACHEFRIENDS
);
16404 } else if (!strcasecmp(v
->name
, "rtsavesysname")) {
16405 ast_set2_flag(&global_flags
[1], ast_true(v
->value
), SIP_PAGE2_RTSAVE_SYSNAME
);
16406 } else if (!strcasecmp(v
->name
, "rtupdate")) {
16407 ast_set2_flag(&global_flags
[1], ast_true(v
->value
), SIP_PAGE2_RTUPDATE
);
16408 } else if (!strcasecmp(v
->name
, "ignoreregexpire")) {
16409 ast_set2_flag(&global_flags
[1], ast_true(v
->value
), SIP_PAGE2_IGNOREREGEXPIRE
);
16410 } else if (!strcasecmp(v
->name
, "t1min")) {
16411 global_t1min
= atoi(v
->value
);
16412 } else if (!strcasecmp(v
->name
, "rtautoclear")) {
16413 int i
= atoi(v
->value
);
16415 global_rtautoclear
= i
;
16418 ast_set2_flag(&global_flags
[1], i
|| ast_true(v
->value
), SIP_PAGE2_RTAUTOCLEAR
);
16419 } else if (!strcasecmp(v
->name
, "usereqphone")) {
16420 ast_set2_flag(&global_flags
[0], ast_true(v
->value
), SIP_USEREQPHONE
);
16421 } else if (!strcasecmp(v
->name
, "relaxdtmf")) {
16422 global_relaxdtmf
= ast_true(v
->value
);
16423 } else if (!strcasecmp(v
->name
, "checkmwi")) {
16424 if ((sscanf(v
->value
, "%d", &global_mwitime
) != 1) || (global_mwitime
< 0)) {
16425 ast_log(LOG_WARNING
, "'%s' is not a valid MWI time setting at line %d. Using default (10).\n", v
->value
, v
->lineno
);
16426 global_mwitime
= DEFAULT_MWITIME
;
16428 } else if (!strcasecmp(v
->name
, "vmexten")) {
16429 ast_copy_string(default_vmexten
, v
->value
, sizeof(default_vmexten
));
16430 } else if (!strcasecmp(v
->name
, "rtptimeout")) {
16431 if ((sscanf(v
->value
, "%d", &global_rtptimeout
) != 1) || (global_rtptimeout
< 0)) {
16432 ast_log(LOG_WARNING
, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v
->value
, v
->lineno
);
16433 global_rtptimeout
= 0;
16435 } else if (!strcasecmp(v
->name
, "rtpholdtimeout")) {
16436 if ((sscanf(v
->value
, "%d", &global_rtpholdtimeout
) != 1) || (global_rtpholdtimeout
< 0)) {
16437 ast_log(LOG_WARNING
, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v
->value
, v
->lineno
);
16438 global_rtpholdtimeout
= 0;
16440 } else if (!strcasecmp(v
->name
, "rtpkeepalive")) {
16441 if ((sscanf(v
->value
, "%d", &global_rtpkeepalive
) != 1) || (global_rtpkeepalive
< 0)) {
16442 ast_log(LOG_WARNING
, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v
->value
, v
->lineno
);
16443 global_rtpkeepalive
= 0;
16445 } else if (!strcasecmp(v
->name
, "compactheaders")) {
16446 compactheaders
= ast_true(v
->value
);
16447 } else if (!strcasecmp(v
->name
, "notifymimetype")) {
16448 ast_copy_string(default_notifymime
, v
->value
, sizeof(default_notifymime
));
16449 } else if (!strncasecmp(v
->name
, "limitonpeer", 11)) {
16450 global_limitonpeers
= ast_true(v
->value
);
16451 } else if (!strcasecmp(v
->name
, "directrtpsetup")) {
16452 global_directrtpsetup
= ast_true(v
->value
);
16453 } else if (!strcasecmp(v
->name
, "notifyringing")) {
16454 global_notifyringing
= ast_true(v
->value
);
16455 } else if (!strcasecmp(v
->name
, "notifyhold")) {
16456 global_notifyhold
= ast_true(v
->value
);
16457 } else if (!strcasecmp(v
->name
, "alwaysauthreject")) {
16458 global_alwaysauthreject
= ast_true(v
->value
);
16459 } else if (!strcasecmp(v
->name
, "mohinterpret")
16460 || !strcasecmp(v
->name
, "musicclass") || !strcasecmp(v
->name
, "musiconhold")) {
16461 ast_copy_string(default_mohinterpret
, v
->value
, sizeof(default_mohinterpret
));
16462 } else if (!strcasecmp(v
->name
, "mohsuggest")) {
16463 ast_copy_string(default_mohsuggest
, v
->value
, sizeof(default_mohsuggest
));
16464 } else if (!strcasecmp(v
->name
, "language")) {
16465 ast_copy_string(default_language
, v
->value
, sizeof(default_language
));
16466 } else if (!strcasecmp(v
->name
, "regcontext")) {
16467 ast_copy_string(newcontexts
, v
->value
, sizeof(newcontexts
));
16468 stringp
= newcontexts
;
16469 /* Let's remove any contexts that are no longer defined in regcontext */
16470 cleanup_stale_contexts(stringp
, oldregcontext
);
16471 /* Create contexts if they don't exist already */
16472 while ((context
= strsep(&stringp
, "&"))) {
16473 if (!ast_context_find(context
))
16474 ast_context_create(NULL
, context
,"SIP");
16476 ast_copy_string(global_regcontext
, v
->value
, sizeof(global_regcontext
));
16477 } else if (!strcasecmp(v
->name
, "callerid")) {
16478 ast_copy_string(default_callerid
, v
->value
, sizeof(default_callerid
));
16479 } else if (!strcasecmp(v
->name
, "fromdomain")) {
16480 ast_copy_string(default_fromdomain
, v
->value
, sizeof(default_fromdomain
));
16481 } else if (!strcasecmp(v
->name
, "outboundproxy")) {
16482 if (ast_get_ip_or_srv(&outboundproxyip
, v
->value
, srvlookup
? "_sip._udp" : NULL
) < 0)
16483 ast_log(LOG_WARNING
, "Unable to locate host '%s'\n", v
->value
);
16484 } else if (!strcasecmp(v
->name
, "outboundproxyport")) {
16485 /* Port needs to be after IP */
16486 sscanf(v
->value
, "%d", &format
);
16487 outboundproxyip
.sin_port
= htons(format
);
16488 } else if (!strcasecmp(v
->name
, "autocreatepeer")) {
16489 autocreatepeer
= ast_true(v
->value
);
16490 } else if (!strcasecmp(v
->name
, "srvlookup")) {
16491 srvlookup
= ast_true(v
->value
);
16492 } else if (!strcasecmp(v
->name
, "pedantic")) {
16493 pedanticsipchecking
= ast_true(v
->value
);
16494 } else if (!strcasecmp(v
->name
, "maxexpirey") || !strcasecmp(v
->name
, "maxexpiry")) {
16495 max_expiry
= atoi(v
->value
);
16496 if (max_expiry
< 1)
16497 max_expiry
= DEFAULT_MAX_EXPIRY
;
16498 } else if (!strcasecmp(v
->name
, "minexpirey") || !strcasecmp(v
->name
, "minexpiry")) {
16499 min_expiry
= atoi(v
->value
);
16500 if (min_expiry
< 1)
16501 min_expiry
= DEFAULT_MIN_EXPIRY
;
16502 } else if (!strcasecmp(v
->name
, "defaultexpiry") || !strcasecmp(v
->name
, "defaultexpirey")) {
16503 default_expiry
= atoi(v
->value
);
16504 if (default_expiry
< 1)
16505 default_expiry
= DEFAULT_DEFAULT_EXPIRY
;
16506 } else if (!strcasecmp(v
->name
, "sipdebug")) { /* XXX maybe ast_set2_flags ? */
16507 if (ast_true(v
->value
))
16508 ast_set_flag(&global_flags
[1], SIP_PAGE2_DEBUG_CONFIG
);
16509 } else if (!strcasecmp(v
->name
, "dumphistory")) {
16510 dumphistory
= ast_true(v
->value
);
16511 } else if (!strcasecmp(v
->name
, "recordhistory")) {
16512 recordhistory
= ast_true(v
->value
);
16513 } else if (!strcasecmp(v
->name
, "registertimeout")) {
16514 global_reg_timeout
= atoi(v
->value
);
16515 if (global_reg_timeout
< 1)
16516 global_reg_timeout
= DEFAULT_REGISTRATION_TIMEOUT
;
16517 } else if (!strcasecmp(v
->name
, "registerattempts")) {
16518 global_regattempts_max
= atoi(v
->value
);
16519 } else if (!strcasecmp(v
->name
, "bindaddr")) {
16520 if (!(hp
= ast_gethostbyname(v
->value
, &ahp
))) {
16521 ast_log(LOG_WARNING
, "Invalid address: %s\n", v
->value
);
16523 memcpy(&bindaddr
.sin_addr
, hp
->h_addr
, sizeof(bindaddr
.sin_addr
));
16525 } else if (!strcasecmp(v
->name
, "localnet")) {
16527 if (!(na
= ast_append_ha("d", v
->value
, localaddr
)))
16528 ast_log(LOG_WARNING
, "Invalid localnet value: %s\n", v
->value
);
16531 } else if (!strcasecmp(v
->name
, "localmask")) {
16532 ast_log(LOG_WARNING
, "Use of localmask is no long supported -- use localnet with mask syntax\n");
16533 } else if (!strcasecmp(v
->name
, "externip")) {
16534 if (!(hp
= ast_gethostbyname(v
->value
, &ahp
)))
16535 ast_log(LOG_WARNING
, "Invalid address for externip keyword: %s\n", v
->value
);
16537 memcpy(&externip
.sin_addr
, hp
->h_addr
, sizeof(externip
.sin_addr
));
16539 } else if (!strcasecmp(v
->name
, "externhost")) {
16540 ast_copy_string(externhost
, v
->value
, sizeof(externhost
));
16541 if (!(hp
= ast_gethostbyname(externhost
, &ahp
)))
16542 ast_log(LOG_WARNING
, "Invalid address for externhost keyword: %s\n", externhost
);
16544 memcpy(&externip
.sin_addr
, hp
->h_addr
, sizeof(externip
.sin_addr
));
16545 externexpire
= time(NULL
);
16546 } else if (!strcasecmp(v
->name
, "externrefresh")) {
16547 if (sscanf(v
->value
, "%d", &externrefresh
) != 1) {
16548 ast_log(LOG_WARNING
, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v
->value
, v
->lineno
);
16549 externrefresh
= 10;
16551 } else if (!strcasecmp(v
->name
, "allow")) {
16552 ast_parse_allow_disallow(&default_prefs
, &global_capability
, v
->value
, 1);
16553 } else if (!strcasecmp(v
->name
, "disallow")) {
16554 ast_parse_allow_disallow(&default_prefs
, &global_capability
, v
->value
, 0);
16555 } else if (!strcasecmp(v
->name
, "autoframing")) {
16556 global_autoframing
= ast_true(v
->value
);
16557 } else if (!strcasecmp(v
->name
, "allowexternaldomains")) {
16558 allow_external_domains
= ast_true(v
->value
);
16559 } else if (!strcasecmp(v
->name
, "autodomain")) {
16560 auto_sip_domains
= ast_true(v
->value
);
16561 } else if (!strcasecmp(v
->name
, "domain")) {
16562 char *domain
= ast_strdupa(v
->value
);
16563 char *context
= strchr(domain
, ',');
16568 if (option_debug
&& ast_strlen_zero(context
))
16569 ast_log(LOG_DEBUG
, "No context specified at line %d for domain '%s'\n", v
->lineno
, domain
);
16570 if (ast_strlen_zero(domain
))
16571 ast_log(LOG_WARNING
, "Empty domain specified at line %d\n", v
->lineno
);
16573 add_sip_domain(ast_strip(domain
), SIP_DOMAIN_CONFIG
, context
? ast_strip(context
) : "");
16574 } else if (!strcasecmp(v
->name
, "register")) {
16575 if (sip_register(v
->value
, v
->lineno
) == 0)
16577 } else if (!strcasecmp(v
->name
, "tos")) {
16578 if (!ast_str2tos(v
->value
, &temp_tos
)) {
16579 global_tos_sip
= temp_tos
;
16580 global_tos_audio
= temp_tos
;
16581 global_tos_video
= temp_tos
;
16582 ast_log(LOG_WARNING
, "tos value at line %d is deprecated. See doc/ip-tos.txt for more information.\n", v
->lineno
);
16584 ast_log(LOG_WARNING
, "Invalid tos value at line %d, See doc/ip-tos.txt for more information.\n", v
->lineno
);
16585 } else if (!strcasecmp(v
->name
, "tos_sip")) {
16586 if (ast_str2tos(v
->value
, &global_tos_sip
))
16587 ast_log(LOG_WARNING
, "Invalid tos_sip value at line %d, recommended value is 'cs3'. See doc/ip-tos.txt.\n", v
->lineno
);
16588 } else if (!strcasecmp(v
->name
, "tos_audio")) {
16589 if (ast_str2tos(v
->value
, &global_tos_audio
))
16590 ast_log(LOG_WARNING
, "Invalid tos_audio value at line %d, recommended value is 'ef'. See doc/ip-tos.txt.\n", v
->lineno
);
16591 } else if (!strcasecmp(v
->name
, "tos_video")) {
16592 if (ast_str2tos(v
->value
, &global_tos_video
))
16593 ast_log(LOG_WARNING
, "Invalid tos_video value at line %d, recommended value is 'af41'. See doc/ip-tos.txt.\n", v
->lineno
);
16594 } else if (!strcasecmp(v
->name
, "bindport")) {
16595 if (sscanf(v
->value
, "%d", &ourport
) == 1) {
16596 bindaddr
.sin_port
= htons(ourport
);
16598 ast_log(LOG_WARNING
, "Invalid port number '%s' at line %d of %s\n", v
->value
, v
->lineno
, config
);
16600 } else if (!strcasecmp(v
->name
, "qualify")) {
16601 if (!strcasecmp(v
->value
, "no")) {
16602 default_qualify
= 0;
16603 } else if (!strcasecmp(v
->value
, "yes")) {
16604 default_qualify
= DEFAULT_MAXMS
;
16605 } else if (sscanf(v
->value
, "%d", &default_qualify
) != 1) {
16606 ast_log(LOG_WARNING
, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v
->lineno
);
16607 default_qualify
= 0;
16609 } else if (!strcasecmp(v
->name
, "callevents")) {
16610 global_callevents
= ast_true(v
->value
);
16611 } else if (!strcasecmp(v
->name
, "maxcallbitrate")) {
16612 default_maxcallbitrate
= atoi(v
->value
);
16613 if (default_maxcallbitrate
< 0)
16614 default_maxcallbitrate
= DEFAULT_MAX_CALL_BITRATE
;
16615 } else if (!strcasecmp(v
->name
, "matchexterniplocally")) {
16616 global_matchexterniplocally
= ast_true(v
->value
);
16620 if (!allow_external_domains
&& AST_LIST_EMPTY(&domain_list
)) {
16621 ast_log(LOG_WARNING
, "To disallow external domains, you need to configure local SIP domains.\n");
16622 allow_external_domains
= 1;
16625 /* Build list of authentication to various SIP realms, i.e. service providers */
16626 for (v
= ast_variable_browse(cfg
, "authentication"); v
; v
= v
->next
) {
16627 /* Format for authentication is auth = username:password@realm */
16628 if (!strcasecmp(v
->name
, "auth"))
16629 authl
= add_realm_authentication(authl
, v
->value
, v
->lineno
);
16632 ucfg
= ast_config_load("users.conf");
16634 struct ast_variable
*gen
;
16635 int genhassip
, genregistersip
;
16636 const char *hassip
, *registersip
;
16638 genhassip
= ast_true(ast_variable_retrieve(ucfg
, "general", "hassip"));
16639 genregistersip
= ast_true(ast_variable_retrieve(ucfg
, "general", "registersip"));
16640 gen
= ast_variable_browse(ucfg
, "general");
16641 cat
= ast_category_browse(ucfg
, NULL
);
16643 if (strcasecmp(cat
, "general")) {
16644 hassip
= ast_variable_retrieve(ucfg
, cat
, "hassip");
16645 registersip
= ast_variable_retrieve(ucfg
, cat
, "registersip");
16646 if (ast_true(hassip
) || (!hassip
&& genhassip
)) {
16647 peer
= build_peer(cat
, gen
, ast_variable_browse(ucfg
, cat
), 0);
16649 ast_device_state_changed("SIP/%s", peer
->name
);
16650 ASTOBJ_CONTAINER_LINK(&peerl
,peer
);
16651 ASTOBJ_UNREF(peer
, sip_destroy_peer
);
16655 if (ast_true(registersip
) || (!registersip
&& genregistersip
)) {
16657 const char *host
= ast_variable_retrieve(ucfg
, cat
, "host");
16658 const char *username
= ast_variable_retrieve(ucfg
, cat
, "username");
16659 const char *secret
= ast_variable_retrieve(ucfg
, cat
, "secret");
16660 const char *contact
= ast_variable_retrieve(ucfg
, cat
, "contact");
16662 host
= ast_variable_retrieve(ucfg
, "general", "host");
16664 username
= ast_variable_retrieve(ucfg
, "general", "username");
16666 secret
= ast_variable_retrieve(ucfg
, "general", "secret");
16669 if (!ast_strlen_zero(username
) && !ast_strlen_zero(host
)) {
16670 if (!ast_strlen_zero(secret
))
16671 snprintf(tmp
, sizeof(tmp
), "%s:%s@%s/%s", username
, secret
, host
, contact
);
16673 snprintf(tmp
, sizeof(tmp
), "%s@%s/%s", username
, host
, contact
);
16674 if (sip_register(tmp
, 0) == 0)
16679 cat
= ast_category_browse(ucfg
, cat
);
16681 ast_config_destroy(ucfg
);
16685 /* Load peers, users and friends */
16687 while ( (cat
= ast_category_browse(cfg
, cat
)) ) {
16689 if (!strcasecmp(cat
, "general") || !strcasecmp(cat
, "authentication"))
16691 utype
= ast_variable_retrieve(cfg
, cat
, "type");
16693 ast_log(LOG_WARNING
, "Section '%s' lacks type\n", cat
);
16696 int is_user
= 0, is_peer
= 0;
16697 if (!strcasecmp(utype
, "user"))
16699 else if (!strcasecmp(utype
, "friend"))
16700 is_user
= is_peer
= 1;
16701 else if (!strcasecmp(utype
, "peer"))
16704 ast_log(LOG_WARNING
, "Unknown type '%s' for '%s' in %s\n", utype
, cat
, "sip.conf");
16708 user
= build_user(cat
, ast_variable_browse(cfg
, cat
), 0);
16710 ASTOBJ_CONTAINER_LINK(&userl
,user
);
16711 ASTOBJ_UNREF(user
, sip_destroy_user
);
16716 peer
= build_peer(cat
, ast_variable_browse(cfg
, cat
), NULL
, 0);
16718 ASTOBJ_CONTAINER_LINK(&peerl
,peer
);
16719 ASTOBJ_UNREF(peer
, sip_destroy_peer
);
16725 if (ast_find_ourip(&__ourip
, bindaddr
)) {
16726 ast_log(LOG_WARNING
, "Unable to get own IP address, SIP disabled\n");
16729 if (!ntohs(bindaddr
.sin_port
))
16730 bindaddr
.sin_port
= ntohs(STANDARD_SIP_PORT
);
16731 bindaddr
.sin_family
= AF_INET
;
16732 ast_mutex_lock(&netlock
);
16733 if ((sipsock
> -1) && (memcmp(&old_bindaddr
, &bindaddr
, sizeof(struct sockaddr_in
)))) {
16738 sipsock
= socket(AF_INET
, SOCK_DGRAM
, 0);
16740 ast_log(LOG_WARNING
, "Unable to create SIP socket: %s\n", strerror(errno
));
16743 /* Allow SIP clients on the same host to access us: */
16744 const int reuseFlag
= 1;
16746 setsockopt(sipsock
, SOL_SOCKET
, SO_REUSEADDR
,
16747 (const char*)&reuseFlag
,
16750 ast_enable_packet_fragmentation(sipsock
);
16752 if (bind(sipsock
, (struct sockaddr
*)&bindaddr
, sizeof(bindaddr
)) < 0) {
16753 ast_log(LOG_WARNING
, "Failed to bind to %s:%d: %s\n",
16754 ast_inet_ntoa(bindaddr
.sin_addr
), ntohs(bindaddr
.sin_port
),
16759 if (option_verbose
> 1) {
16760 ast_verbose(VERBOSE_PREFIX_2
"SIP Listening on %s:%d\n",
16761 ast_inet_ntoa(bindaddr
.sin_addr
), ntohs(bindaddr
.sin_port
));
16762 ast_verbose(VERBOSE_PREFIX_2
"Using SIP TOS: %s\n", ast_tos2str(global_tos_sip
));
16764 if (setsockopt(sipsock
, IPPROTO_IP
, IP_TOS
, &global_tos_sip
, sizeof(global_tos_sip
)))
16765 ast_log(LOG_WARNING
, "Unable to set SIP TOS to %s\n", ast_tos2str(global_tos_sip
));
16769 ast_mutex_unlock(&netlock
);
16771 /* Add default domains - host name, IP address and IP:port */
16772 /* Only do this if user added any sip domain with "localdomains" */
16773 /* In order to *not* break backwards compatibility */
16774 /* Some phones address us at IP only, some with additional port number */
16775 if (auto_sip_domains
) {
16776 char temp
[MAXHOSTNAMELEN
];
16778 /* First our default IP address */
16779 if (bindaddr
.sin_addr
.s_addr
)
16780 add_sip_domain(ast_inet_ntoa(bindaddr
.sin_addr
), SIP_DOMAIN_AUTO
, NULL
);
16782 ast_log(LOG_NOTICE
, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
16784 /* Our extern IP address, if configured */
16785 if (externip
.sin_addr
.s_addr
)
16786 add_sip_domain(ast_inet_ntoa(externip
.sin_addr
), SIP_DOMAIN_AUTO
, NULL
);
16788 /* Extern host name (NAT traversal support) */
16789 if (!ast_strlen_zero(externhost
))
16790 add_sip_domain(externhost
, SIP_DOMAIN_AUTO
, NULL
);
16792 /* Our host name */
16793 if (!gethostname(temp
, sizeof(temp
)))
16794 add_sip_domain(temp
, SIP_DOMAIN_AUTO
, NULL
);
16797 /* Release configuration from memory */
16798 ast_config_destroy(cfg
);
16800 /* Load the list of manual NOTIFY types to support */
16802 ast_config_destroy(notify_types
);
16803 notify_types
= ast_config_load(notify_config
);
16805 /* Done, tell the manager */
16806 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
);
16811 static struct ast_udptl
*sip_get_udptl_peer(struct ast_channel
*chan
)
16814 struct ast_udptl
*udptl
= NULL
;
16816 p
= chan
->tech_pvt
;
16820 ast_mutex_lock(&p
->lock
);
16821 if (p
->udptl
&& ast_test_flag(&p
->flags
[0], SIP_CAN_REINVITE
))
16823 ast_mutex_unlock(&p
->lock
);
16827 static int sip_set_udptl_peer(struct ast_channel
*chan
, struct ast_udptl
*udptl
)
16831 p
= chan
->tech_pvt
;
16834 ast_mutex_lock(&p
->lock
);
16836 ast_udptl_get_peer(udptl
, &p
->udptlredirip
);
16838 memset(&p
->udptlredirip
, 0, sizeof(p
->udptlredirip
));
16839 if (!ast_test_flag(&p
->flags
[0], SIP_GOTREFER
)) {
16840 if (!p
->pendinginvite
) {
16841 if (option_debug
> 2) {
16842 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);
16844 transmit_reinvite_with_t38_sdp(p
);
16845 } else if (!ast_test_flag(&p
->flags
[0], SIP_PENDINGBYE
)) {
16846 if (option_debug
> 2) {
16847 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);
16849 ast_set_flag(&p
->flags
[0], SIP_NEEDREINVITE
);
16852 /* Reset lastrtprx timer */
16853 p
->lastrtprx
= p
->lastrtptx
= time(NULL
);
16854 ast_mutex_unlock(&p
->lock
);
16858 /*! \brief Handle T38 reinvite
16859 \todo Make sure we don't destroy the call if we can't handle the re-invite.
16860 Nothing should be changed until we have processed the SDP and know that we
16863 static int sip_handle_t38_reinvite(struct ast_channel
*chan
, struct sip_pvt
*pvt
, int reinvite
)
16868 p
= chan
->tech_pvt
;
16869 if (!p
|| !pvt
->udptl
)
16872 /* Setup everything on the other side like offered/responded from first side */
16873 ast_mutex_lock(&p
->lock
);
16875 /*! \todo check if this is not set earlier when setting up the PVT. If not
16876 maybe it should move there. */
16877 p
->t38
.jointcapability
= p
->t38
.peercapability
= pvt
->t38
.jointcapability
;
16879 ast_udptl_set_far_max_datagram(p
->udptl
, ast_udptl_get_local_max_datagram(pvt
->udptl
));
16880 ast_udptl_set_local_max_datagram(p
->udptl
, ast_udptl_get_local_max_datagram(pvt
->udptl
));
16881 ast_udptl_set_error_correction_scheme(p
->udptl
, ast_udptl_get_error_correction_scheme(pvt
->udptl
));
16883 if (reinvite
) { /* If we are handling sending re-invite to the other side of the bridge */
16884 /*! \note The SIP_CAN_REINVITE flag is for RTP media redirects,
16885 not really T38 re-invites which are different. In this
16886 case it's used properly, to see if we can reinvite over
16889 if (ast_test_flag(&p
->flags
[0], SIP_CAN_REINVITE
) && ast_test_flag(&pvt
->flags
[0], SIP_CAN_REINVITE
)) {
16890 ast_udptl_get_peer(pvt
->udptl
, &p
->udptlredirip
);
16893 memset(&p
->udptlredirip
, 0, sizeof(p
->udptlredirip
));
16895 if (!ast_test_flag(&p
->flags
[0], SIP_GOTREFER
)) {
16896 if (!p
->pendinginvite
) {
16897 if (option_debug
> 2) {
16899 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
));
16901 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
));
16903 transmit_reinvite_with_t38_sdp(p
);
16904 } else if (!ast_test_flag(&p
->flags
[0], SIP_PENDINGBYE
)) {
16905 if (option_debug
> 2) {
16907 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
));
16909 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
));
16911 ast_set_flag(&p
->flags
[0], SIP_NEEDREINVITE
);
16914 /* Reset lastrtprx timer */
16915 p
->lastrtprx
= p
->lastrtptx
= time(NULL
);
16916 ast_mutex_unlock(&p
->lock
);
16918 } else { /* If we are handling sending 200 OK to the other side of the bridge */
16919 if (ast_test_flag(&p
->flags
[0], SIP_CAN_REINVITE
) && ast_test_flag(&pvt
->flags
[0], SIP_CAN_REINVITE
)) {
16920 ast_udptl_get_peer(pvt
->udptl
, &p
->udptlredirip
);
16923 memset(&p
->udptlredirip
, 0, sizeof(p
->udptlredirip
));
16925 if (option_debug
> 2) {
16927 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
));
16929 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
));
16931 pvt
->t38
.state
= T38_ENABLED
;
16932 p
->t38
.state
= T38_ENABLED
;
16933 if (option_debug
> 1) {
16934 ast_log(LOG_DEBUG
, "T38 changed state to %d on channel %s\n", pvt
->t38
.state
, pvt
->owner
? pvt
->owner
->name
: "<none>");
16935 ast_log(LOG_DEBUG
, "T38 changed state to %d on channel %s\n", p
->t38
.state
, chan
? chan
->name
: "<none>");
16937 transmit_response_with_t38_sdp(p
, "200 OK", &p
->initreq
, XMIT_CRITICAL
);
16938 p
->lastrtprx
= p
->lastrtptx
= time(NULL
);
16939 ast_mutex_unlock(&p
->lock
);
16945 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
16946 static enum ast_rtp_get_result
sip_get_rtp_peer(struct ast_channel
*chan
, struct ast_rtp
**rtp
)
16948 struct sip_pvt
*p
= NULL
;
16949 enum ast_rtp_get_result res
= AST_RTP_TRY_PARTIAL
;
16951 if (!(p
= chan
->tech_pvt
))
16952 return AST_RTP_GET_FAILED
;
16954 ast_mutex_lock(&p
->lock
);
16956 ast_mutex_unlock(&p
->lock
);
16957 return AST_RTP_GET_FAILED
;
16962 if (ast_rtp_getnat(*rtp
) && !ast_test_flag(&p
->flags
[0], SIP_CAN_REINVITE_NAT
))
16963 res
= AST_RTP_TRY_PARTIAL
;
16964 else if (ast_test_flag(&p
->flags
[0], SIP_CAN_REINVITE
))
16965 res
= AST_RTP_TRY_NATIVE
;
16966 else if (ast_test_flag(&global_jbconf
, AST_JB_FORCED
))
16967 res
= AST_RTP_GET_FAILED
;
16969 ast_mutex_unlock(&p
->lock
);
16974 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
16975 static enum ast_rtp_get_result
sip_get_vrtp_peer(struct ast_channel
*chan
, struct ast_rtp
**rtp
)
16977 struct sip_pvt
*p
= NULL
;
16978 enum ast_rtp_get_result res
= AST_RTP_TRY_PARTIAL
;
16980 if (!(p
= chan
->tech_pvt
))
16981 return AST_RTP_GET_FAILED
;
16983 ast_mutex_lock(&p
->lock
);
16985 ast_mutex_unlock(&p
->lock
);
16986 return AST_RTP_GET_FAILED
;
16991 if (ast_test_flag(&p
->flags
[0], SIP_CAN_REINVITE
))
16992 res
= AST_RTP_TRY_NATIVE
;
16994 ast_mutex_unlock(&p
->lock
);
16999 /*! \brief Set the RTP peer for this call */
17000 static int sip_set_rtp_peer(struct ast_channel
*chan
, struct ast_rtp
*rtp
, struct ast_rtp
*vrtp
, int codecs
, int nat_active
)
17005 p
= chan
->tech_pvt
;
17009 /* Disable early RTP bridge */
17010 if (chan
->_state
!= AST_STATE_UP
&& !global_directrtpsetup
) /* We are in early state */
17013 ast_mutex_lock(&p
->lock
);
17014 if (ast_test_flag(&p
->flags
[0], SIP_ALREADYGONE
)) {
17015 /* If we're destroyed, don't bother */
17016 ast_mutex_unlock(&p
->lock
);
17020 /* if this peer cannot handle reinvites of the media stream to devices
17021 that are known to be behind a NAT, then stop the process now
17023 if (nat_active
&& !ast_test_flag(&p
->flags
[0], SIP_CAN_REINVITE_NAT
)) {
17024 ast_mutex_unlock(&p
->lock
);
17029 changed
|= ast_rtp_get_peer(rtp
, &p
->redirip
);
17030 } else if (p
->redirip
.sin_addr
.s_addr
|| ntohs(p
->redirip
.sin_port
) != 0) {
17031 memset(&p
->redirip
, 0, sizeof(p
->redirip
));
17035 changed
|= ast_rtp_get_peer(vrtp
, &p
->vredirip
);
17036 } else if (p
->vredirip
.sin_addr
.s_addr
|| ntohs(p
->vredirip
.sin_port
) != 0) {
17037 memset(&p
->vredirip
, 0, sizeof(p
->vredirip
));
17040 if (codecs
&& (p
->redircodecs
!= codecs
)) {
17041 p
->redircodecs
= codecs
;
17044 if ((p
->capability
& codecs
) != p
->capability
) {
17045 p
->jointcapability
&= codecs
;
17046 p
->capability
&= codecs
;
17049 if (changed
&& !ast_test_flag(&p
->flags
[0], SIP_GOTREFER
)) {
17050 if (chan
->_state
!= AST_STATE_UP
) { /* We are in early state */
17051 if (!ast_test_flag(&p
->flags
[0], SIP_NO_HISTORY
))
17052 append_history(p
, "ExtInv", "Initial invite sent with remote bridge proposal.");
17054 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
));
17055 } else if (!p
->pendinginvite
) { /* We are up, and have no outstanding invite */
17056 if (option_debug
> 2) {
17057 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
));
17059 transmit_reinvite_with_sdp(p
);
17060 } else if (!ast_test_flag(&p
->flags
[0], SIP_PENDINGBYE
)) {
17061 if (option_debug
> 2) {
17062 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
));
17064 /* We have a pending Invite. Send re-invite when we're done with the invite */
17065 ast_set_flag(&p
->flags
[0], SIP_NEEDREINVITE
);
17068 /* Reset lastrtprx timer */
17069 p
->lastrtprx
= p
->lastrtptx
= time(NULL
);
17070 ast_mutex_unlock(&p
->lock
);
17074 static char *synopsis_dtmfmode
= "Change the dtmfmode for a SIP call";
17075 static char *descrip_dtmfmode
= "SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
17076 static char *app_dtmfmode
= "SIPDtmfMode";
17078 static char *app_sipaddheader
= "SIPAddHeader";
17079 static char *synopsis_sipaddheader
= "Add a SIP header to the outbound call";
17081 static char *descrip_sipaddheader
= ""
17082 " SIPAddHeader(Header: Content)\n"
17083 "Adds a header to a SIP call placed with DIAL.\n"
17084 "Remember to user the X-header if you are adding non-standard SIP\n"
17085 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
17086 "Adding the wrong headers may jeopardize the SIP dialog.\n"
17087 "Always returns 0\n";
17090 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
17091 static int sip_dtmfmode(struct ast_channel
*chan
, void *data
)
17096 mode
= (char *)data
;
17098 ast_log(LOG_WARNING
, "This application requires the argument: info, inband, rfc2833\n");
17101 ast_channel_lock(chan
);
17102 if (chan
->tech
!= &sip_tech
&& chan
->tech
!= &sip_tech_info
) {
17103 ast_log(LOG_WARNING
, "Call this application only on SIP incoming calls\n");
17104 ast_channel_unlock(chan
);
17107 p
= chan
->tech_pvt
;
17109 ast_channel_unlock(chan
);
17112 ast_mutex_lock(&p
->lock
);
17113 if (!strcasecmp(mode
,"info")) {
17114 ast_clear_flag(&p
->flags
[0], SIP_DTMF
);
17115 ast_set_flag(&p
->flags
[0], SIP_DTMF_INFO
);
17116 p
->jointnoncodeccapability
&= ~AST_RTP_DTMF
;
17117 } else if (!strcasecmp(mode
,"rfc2833")) {
17118 ast_clear_flag(&p
->flags
[0], SIP_DTMF
);
17119 ast_set_flag(&p
->flags
[0], SIP_DTMF_RFC2833
);
17120 p
->jointnoncodeccapability
|= AST_RTP_DTMF
;
17121 } else if (!strcasecmp(mode
,"inband")) {
17122 ast_clear_flag(&p
->flags
[0], SIP_DTMF
);
17123 ast_set_flag(&p
->flags
[0], SIP_DTMF_INBAND
);
17124 p
->jointnoncodeccapability
&= ~AST_RTP_DTMF
;
17126 ast_log(LOG_WARNING
, "I don't know about this dtmf mode: %s\n",mode
);
17128 ast_rtp_setdtmf(p
->rtp
, ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_RFC2833
);
17129 if (ast_test_flag(&p
->flags
[0], SIP_DTMF
) == SIP_DTMF_INBAND
) {
17131 p
->vad
= ast_dsp_new();
17132 ast_dsp_set_features(p
->vad
, DSP_FEATURE_DTMF_DETECT
);
17136 ast_dsp_free(p
->vad
);
17140 ast_mutex_unlock(&p
->lock
);
17141 ast_channel_unlock(chan
);
17145 /*! \brief Add a SIP header to an outbound INVITE */
17146 static int sip_addheader(struct ast_channel
*chan
, void *data
)
17151 char *inbuf
= (char *) data
;
17153 if (ast_strlen_zero(inbuf
)) {
17154 ast_log(LOG_WARNING
, "This application requires the argument: Header\n");
17157 ast_channel_lock(chan
);
17159 /* Check for headers */
17160 while (!ok
&& no
<= 50) {
17162 snprintf(varbuf
, sizeof(varbuf
), "_SIPADDHEADER%.2d", no
);
17164 /* Compare without the leading underscore */
17165 if( (pbx_builtin_getvar_helper(chan
, (const char *) varbuf
+ 1) == (const char *) NULL
) )
17169 pbx_builtin_setvar_helper (chan
, varbuf
, inbuf
);
17171 ast_log(LOG_DEBUG
,"SIP Header added \"%s\" as %s\n", inbuf
, varbuf
);
17173 ast_log(LOG_WARNING
, "Too many SIP headers added, max 50\n");
17175 ast_channel_unlock(chan
);
17179 /*! \brief Transfer call before connect with a 302 redirect
17180 \note Called by the transfer() dialplan application through the sip_transfer()
17181 pbx interface function if the call is in ringing state
17182 \todo Fix this function so that we wait for reply to the REFER and
17183 react to errors, denials or other issues the other end might have.
17185 static int sip_sipredirect(struct sip_pvt
*p
, const char *dest
)
17188 char *extension
, *host
, *port
;
17191 cdest
= ast_strdupa(dest
);
17193 extension
= strsep(&cdest
, "@");
17194 host
= strsep(&cdest
, ":");
17195 port
= strsep(&cdest
, ":");
17196 if (ast_strlen_zero(extension
)) {
17197 ast_log(LOG_ERROR
, "Missing mandatory argument: extension\n");
17201 /* we'll issue the redirect message here */
17204 ast_copy_string(tmp
, get_header(&p
->initreq
, "To"), sizeof(tmp
));
17205 if (ast_strlen_zero(tmp
)) {
17206 ast_log(LOG_ERROR
, "Cannot retrieve the 'To' header from the original SIP request!\n");
17209 if ((localtmp
= strcasestr(tmp
, "sip:")) && (localtmp
= strchr(localtmp
, '@'))) {
17210 char lhost
[80], lport
[80];
17211 memset(lhost
, 0, sizeof(lhost
));
17212 memset(lport
, 0, sizeof(lport
));
17214 /* This is okey because lhost and lport are as big as tmp */
17215 sscanf(localtmp
, "%[^<>:; ]:%[^<>:; ]", lhost
, lport
);
17216 if (ast_strlen_zero(lhost
)) {
17217 ast_log(LOG_ERROR
, "Can't find the host address\n");
17220 host
= ast_strdupa(lhost
);
17221 if (!ast_strlen_zero(lport
)) {
17222 port
= ast_strdupa(lport
);
17227 ast_string_field_build(p
, our_contact
, "Transfer <sip:%s@%s%s%s>", extension
, host
, port
? ":" : "", port
? port
: "");
17228 transmit_response_reliable(p
, "302 Moved Temporarily", &p
->initreq
);
17230 sip_scheddestroy(p
, 32000); /* Make sure we stop send this reply. */
17231 sip_alreadygone(p
);
17235 /*! \brief Return SIP UA's codec (part of the RTP interface) */
17236 static int sip_get_codec(struct ast_channel
*chan
)
17238 struct sip_pvt
*p
= chan
->tech_pvt
;
17239 return p
->peercapability
? p
->peercapability
: p
->capability
;
17242 /*! \brief Send a poke to all known peers
17243 Space them out 100 ms apart
17244 XXX We might have a cool algorithm for this or use random - any suggestions?
17246 static void sip_poke_all_peers(void)
17250 if (!speerobjs
) /* No peers, just give up */
17253 ASTOBJ_CONTAINER_TRAVERSE(&peerl
, 1, do {
17254 ASTOBJ_WRLOCK(iterator
);
17255 if (iterator
->pokeexpire
> -1)
17256 ast_sched_del(sched
, iterator
->pokeexpire
);
17258 iterator
->pokeexpire
= ast_sched_add(sched
, ms
, sip_poke_peer_s
, iterator
);
17259 ASTOBJ_UNLOCK(iterator
);
17264 /*! \brief Send all known registrations */
17265 static void sip_send_all_registers(void)
17271 regspacing
= default_expiry
* 1000/regobjs
;
17272 if (regspacing
> 100)
17275 ASTOBJ_CONTAINER_TRAVERSE(®l
, 1, do {
17276 ASTOBJ_WRLOCK(iterator
);
17277 if (iterator
->expire
> -1)
17278 ast_sched_del(sched
, iterator
->expire
);
17280 iterator
->expire
= ast_sched_add(sched
, ms
, sip_reregister
, iterator
);
17281 ASTOBJ_UNLOCK(iterator
);
17286 /*! \brief Reload module */
17287 static int sip_do_reload(enum channelreloadreason reason
)
17289 if (option_debug
> 3)
17290 ast_log(LOG_DEBUG
, "--------------- SIP reload started\n");
17292 clear_realm_authentication(authl
);
17293 clear_sip_domains();
17296 /* First, destroy all outstanding registry calls */
17297 /* This is needed, since otherwise active registry entries will not be destroyed */
17298 ASTOBJ_CONTAINER_TRAVERSE(®l
, 1, do {
17299 ASTOBJ_RDLOCK(iterator
);
17300 if (iterator
->call
) {
17301 if (option_debug
> 2)
17302 ast_log(LOG_DEBUG
, "Destroying active SIP dialog for registry %s@%s\n", iterator
->username
, iterator
->hostname
);
17303 /* This will also remove references to the registry */
17304 sip_destroy(iterator
->call
);
17306 ASTOBJ_UNLOCK(iterator
);
17310 /* Then, actually destroy users and registry */
17311 ASTOBJ_CONTAINER_DESTROYALL(&userl
, sip_destroy_user
);
17312 if (option_debug
> 3)
17313 ast_log(LOG_DEBUG
, "--------------- Done destroying user list\n");
17314 ASTOBJ_CONTAINER_DESTROYALL(®l
, sip_registry_destroy
);
17315 if (option_debug
> 3)
17316 ast_log(LOG_DEBUG
, "--------------- Done destroying registry list\n");
17317 ASTOBJ_CONTAINER_MARKALL(&peerl
);
17318 reload_config(reason
);
17320 /* Prune peers who still are supposed to be deleted */
17321 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl
, sip_destroy_peer
);
17322 if (option_debug
> 3)
17323 ast_log(LOG_DEBUG
, "--------------- Done destroying pruned peers\n");
17325 /* Send qualify (OPTIONS) to all peers */
17326 sip_poke_all_peers();
17328 /* Register with all services */
17329 sip_send_all_registers();
17331 if (option_debug
> 3)
17332 ast_log(LOG_DEBUG
, "--------------- SIP reload done\n");
17337 /*! \brief Force reload of module from cli */
17338 static int sip_reload(int fd
, int argc
, char *argv
[])
17340 ast_mutex_lock(&sip_reload_lock
);
17342 ast_verbose("Previous SIP reload not yet done\n");
17344 sip_reloading
= TRUE
;
17346 sip_reloadreason
= CHANNEL_CLI_RELOAD
;
17348 sip_reloadreason
= CHANNEL_MODULE_RELOAD
;
17350 ast_mutex_unlock(&sip_reload_lock
);
17356 /*! \brief Part of Asterisk module interface */
17357 static int reload(void)
17359 return sip_reload(0, 0, NULL
);
17362 static struct ast_cli_entry cli_sip_debug_deprecated
=
17363 { { "sip", "debug", NULL
},
17364 sip_do_debug_deprecated
, "Enable SIP debugging",
17367 static struct ast_cli_entry cli_sip_no_debug_deprecated
=
17368 { { "sip", "no", "debug", NULL
},
17369 sip_no_debug_deprecated
, "Disable SIP debugging",
17372 static struct ast_cli_entry cli_sip
[] = {
17373 { { "sip", "show", "channels", NULL
},
17374 sip_show_channels
, "List active SIP channels",
17375 show_channels_usage
},
17377 { { "sip", "show", "domains", NULL
},
17378 sip_show_domains
, "List our local SIP domains.",
17379 show_domains_usage
},
17381 { { "sip", "show", "inuse", NULL
},
17382 sip_show_inuse
, "List all inuse/limits",
17383 show_inuse_usage
},
17385 { { "sip", "show", "objects", NULL
},
17386 sip_show_objects
, "List all SIP object allocations",
17387 show_objects_usage
},
17389 { { "sip", "show", "peers", NULL
},
17390 sip_show_peers
, "List defined SIP peers",
17391 show_peers_usage
},
17393 { { "sip", "show", "registry", NULL
},
17394 sip_show_registry
, "List SIP registration status",
17397 { { "sip", "show", "settings", NULL
},
17398 sip_show_settings
, "Show SIP global settings",
17399 show_settings_usage
},
17401 { { "sip", "show", "subscriptions", NULL
},
17402 sip_show_subscriptions
, "List active SIP subscriptions",
17403 show_subscriptions_usage
},
17405 { { "sip", "show", "users", NULL
},
17406 sip_show_users
, "List defined SIP users",
17407 show_users_usage
},
17409 { { "sip", "notify", NULL
},
17410 sip_notify
, "Send a notify packet to a SIP peer",
17411 notify_usage
, complete_sipnotify
},
17413 { { "sip", "show", "channel", NULL
},
17414 sip_show_channel
, "Show detailed SIP channel info",
17415 show_channel_usage
, complete_sipch
},
17417 { { "sip", "show", "history", NULL
},
17418 sip_show_history
, "Show SIP dialog history",
17419 show_history_usage
, complete_sipch
},
17421 { { "sip", "show", "peer", NULL
},
17422 sip_show_peer
, "Show details on specific SIP peer",
17423 show_peer_usage
, complete_sip_show_peer
},
17425 { { "sip", "show", "user", NULL
},
17426 sip_show_user
, "Show details on specific SIP user",
17427 show_user_usage
, complete_sip_show_user
},
17429 { { "sip", "prune", "realtime", NULL
},
17430 sip_prune_realtime
, "Prune cached Realtime object(s)",
17431 prune_realtime_usage
},
17433 { { "sip", "prune", "realtime", "peer", NULL
},
17434 sip_prune_realtime
, "Prune cached Realtime peer(s)",
17435 prune_realtime_usage
, complete_sip_prune_realtime_peer
},
17437 { { "sip", "prune", "realtime", "user", NULL
},
17438 sip_prune_realtime
, "Prune cached Realtime user(s)",
17439 prune_realtime_usage
, complete_sip_prune_realtime_user
},
17441 { { "sip", "set", "debug", NULL
},
17442 sip_do_debug
, "Enable SIP debugging",
17443 debug_usage
, NULL
, &cli_sip_debug_deprecated
},
17445 { { "sip", "set", "debug", "ip", NULL
},
17446 sip_do_debug
, "Enable SIP debugging on IP",
17449 { { "sip", "set", "debug", "peer", NULL
},
17450 sip_do_debug
, "Enable SIP debugging on Peername",
17451 debug_usage
, complete_sip_debug_peer
},
17453 { { "sip", "set", "debug", "off", NULL
},
17454 sip_no_debug
, "Disable SIP debugging",
17455 no_debug_usage
, NULL
, &cli_sip_no_debug_deprecated
},
17457 { { "sip", "history", NULL
},
17458 sip_do_history
, "Enable SIP history",
17461 { { "sip", "history", "off", NULL
},
17462 sip_no_history
, "Disable SIP history",
17463 no_history_usage
},
17465 { { "sip", "reload", NULL
},
17466 sip_reload
, "Reload SIP configuration",
17467 sip_reload_usage
},
17470 /*! \brief PBX load module - initialization */
17471 static int load_module(void)
17473 ASTOBJ_CONTAINER_INIT(&userl
); /* User object list */
17474 ASTOBJ_CONTAINER_INIT(&peerl
); /* Peer object list */
17475 ASTOBJ_CONTAINER_INIT(®l
); /* Registry object list */
17477 if (!(sched
= sched_context_create())) {
17478 ast_log(LOG_ERROR
, "Unable to create scheduler context\n");
17479 return AST_MODULE_LOAD_FAILURE
;
17482 if (!(io
= io_context_create())) {
17483 ast_log(LOG_ERROR
, "Unable to create I/O context\n");
17484 sched_context_destroy(sched
);
17485 return AST_MODULE_LOAD_FAILURE
;
17488 sip_reloadreason
= CHANNEL_MODULE_LOAD
;
17490 if(reload_config(sip_reloadreason
)) /* Load the configuration from sip.conf */
17491 return AST_MODULE_LOAD_DECLINE
;
17493 /* Make sure we can register our sip channel type */
17494 if (ast_channel_register(&sip_tech
)) {
17495 ast_log(LOG_ERROR
, "Unable to register channel type 'SIP'\n");
17496 io_context_destroy(io
);
17497 sched_context_destroy(sched
);
17498 return AST_MODULE_LOAD_FAILURE
;
17501 /* Register all CLI functions for SIP */
17502 ast_cli_register_multiple(cli_sip
, sizeof(cli_sip
)/ sizeof(struct ast_cli_entry
));
17504 /* Tell the RTP subdriver that we're here */
17505 ast_rtp_proto_register(&sip_rtp
);
17507 /* Tell the UDPTL subdriver that we're here */
17508 ast_udptl_proto_register(&sip_udptl
);
17510 /* Register dialplan applications */
17511 ast_register_application(app_dtmfmode
, sip_dtmfmode
, synopsis_dtmfmode
, descrip_dtmfmode
);
17512 ast_register_application(app_sipaddheader
, sip_addheader
, synopsis_sipaddheader
, descrip_sipaddheader
);
17514 /* Register dialplan functions */
17515 ast_custom_function_register(&sip_header_function
);
17516 ast_custom_function_register(&sippeer_function
);
17517 ast_custom_function_register(&sipchaninfo_function
);
17518 ast_custom_function_register(&checksipdomain_function
);
17520 /* Register manager commands */
17521 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM
, manager_sip_show_peers
,
17522 "List SIP peers (text format)", mandescr_show_peers
);
17523 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM
, manager_sip_show_peer
,
17524 "Show SIP peer (text format)", mandescr_show_peer
);
17526 sip_poke_all_peers();
17527 sip_send_all_registers();
17529 /* And start the monitor for the first time */
17532 return AST_MODULE_LOAD_SUCCESS
;
17535 /*! \brief PBX unload module API */
17536 static int unload_module(void)
17538 struct sip_pvt
*p
, *pl
;
17540 /* First, take us out of the channel type list */
17541 ast_channel_unregister(&sip_tech
);
17543 /* Unregister dial plan functions */
17544 ast_custom_function_unregister(&sipchaninfo_function
);
17545 ast_custom_function_unregister(&sippeer_function
);
17546 ast_custom_function_unregister(&sip_header_function
);
17547 ast_custom_function_unregister(&checksipdomain_function
);
17549 /* Unregister dial plan applications */
17550 ast_unregister_application(app_dtmfmode
);
17551 ast_unregister_application(app_sipaddheader
);
17553 /* Unregister CLI commands */
17554 ast_cli_unregister_multiple(cli_sip
, sizeof(cli_sip
) / sizeof(struct ast_cli_entry
));
17556 /* Disconnect from the RTP subsystem */
17557 ast_rtp_proto_unregister(&sip_rtp
);
17559 /* Disconnect from UDPTL */
17560 ast_udptl_proto_unregister(&sip_udptl
);
17562 /* Unregister AMI actions */
17563 ast_manager_unregister("SIPpeers");
17564 ast_manager_unregister("SIPshowpeer");
17566 ast_mutex_lock(&iflock
);
17567 /* Hangup all interfaces if they have an owner */
17568 for (p
= iflist
; p
; p
= p
->next
) {
17570 ast_softhangup(p
->owner
, AST_SOFTHANGUP_APPUNLOAD
);
17572 ast_mutex_unlock(&iflock
);
17574 ast_mutex_lock(&monlock
);
17575 if (monitor_thread
&& (monitor_thread
!= AST_PTHREADT_STOP
)) {
17576 pthread_cancel(monitor_thread
);
17577 pthread_kill(monitor_thread
, SIGURG
);
17578 pthread_join(monitor_thread
, NULL
);
17580 monitor_thread
= AST_PTHREADT_STOP
;
17581 ast_mutex_unlock(&monlock
);
17583 ast_mutex_lock(&iflock
);
17584 /* Destroy all the interfaces and free their memory */
17589 __sip_destroy(pl
, TRUE
);
17592 ast_mutex_unlock(&iflock
);
17594 /* Free memory for local network address mask */
17595 ast_free_ha(localaddr
);
17597 ASTOBJ_CONTAINER_DESTROYALL(&userl
, sip_destroy_user
);
17598 ASTOBJ_CONTAINER_DESTROY(&userl
);
17599 ASTOBJ_CONTAINER_DESTROYALL(&peerl
, sip_destroy_peer
);
17600 ASTOBJ_CONTAINER_DESTROY(&peerl
);
17601 ASTOBJ_CONTAINER_DESTROYALL(®l
, sip_registry_destroy
);
17602 ASTOBJ_CONTAINER_DESTROY(®l
);
17604 clear_realm_authentication(authl
);
17605 clear_sip_domains();
17607 sched_context_destroy(sched
);
17612 AST_MODULE_INFO(ASTERISK_GPL_KEY
, AST_MODFLAG_DEFAULT
, "Session Initiation Protocol (SIP)",
17613 .load
= load_module
,
17614 .unload
= unload_module
,