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, and experimental TCP and TLS support
29 * Configuration file \link Config_sip sip.conf \endlink
31 * ********** IMPORTANT *
32 * \note TCP/TLS support is EXPERIMENTAL and WILL CHANGE. This applies to configuration
33 * settings, dialplan commands and dialplans apps/functions
34 * See \ref sip_tcp_tls
37 * ******** General TODO:s
38 * \todo Better support of forking
39 * \todo VIA branch tag transaction checking
40 * \todo Transaction support
42 * \ingroup channel_drivers
44 * \par Overview of the handling of SIP sessions
45 * The SIP channel handles several types of SIP sessions, or dialogs,
46 * not all of them being "telephone calls".
47 * - Incoming calls that will be sent to the PBX core
48 * - Outgoing calls, generated by the PBX
49 * - SIP subscriptions and notifications of states and voicemail messages
50 * - SIP registrations, both inbound and outbound
51 * - SIP peer management (peerpoke, OPTIONS)
54 * In the SIP channel, there's a list of active SIP dialogs, which includes
55 * all of these when they are active. "sip show channels" in the CLI will
56 * show most of these, excluding subscriptions which are shown by
57 * "sip show subscriptions"
59 * \par incoming packets
60 * Incoming packets are received in the monitoring thread, then handled by
61 * sipsock_read() for udp only. In tcp, packets are read by the tcp_helper thread.
62 * sipsock_read() function parses the packet and matches an existing
63 * dialog or starts a new SIP dialog.
65 * sipsock_read sends the packet to handle_incoming(), that parses a bit more.
66 * If it is a response to an outbound request, the packet is sent to handle_response().
67 * If it is a request, handle_incoming() sends it to one of a list of functions
68 * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
69 * sipsock_read locks the ast_channel if it exists (an active call) and
70 * unlocks it after we have processed the SIP message.
72 * A new INVITE is sent to handle_request_invite(), that will end up
73 * starting a new channel in the PBX, the new channel after that executing
74 * in a separate channel thread. This is an incoming "call".
75 * When the call is answered, either by a bridged channel or the PBX itself
76 * the sip_answer() function is called.
78 * The actual media - Video or Audio - is mostly handled by the RTP subsystem
82 * Outbound calls are set up by the PBX through the sip_request_call()
83 * function. After that, they are activated by sip_call().
86 * The PBX issues a hangup on both incoming and outgoing calls through
87 * the sip_hangup() function
90 /*! \page sip_tcp_tls SIP TCP and TLS support
91 * The TCP and TLS support is unfortunately implemented in a way that is not
92 * SIP compliant and tested in a SIP infrastructure. We hope to fix this for
93 * at least release 1.6.2. This code was new in 1.6.0 and won't be fixed for
94 * that release, due to the current release policy. Only bugs compared with
95 * the working functionality in 1.4 will be fixed. Bugs in new features will
96 * be fixed in the next release. As 1.6.1 is already in release
97 * candidate mode, there will be a buggy SIP channel in that release too.
99 * If you have opinions about this release policy, send mail to the asterisk-dev
102 * \par tcpfixes TCP implementation changes needed
103 * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
104 * \todo Save TCP/TLS sessions in registry
105 * If someone registers a SIPS uri, this forces us to set up a TLS connection back.
106 * \todo Add TCP/TLS information to function SIPPEER and SIPCHANINFO
107 * \todo If tcpenable=yes, we must open a TCP socket on the same address as the IP for UDP.
108 * The tcpbindaddr config option should only be used to open ADDITIONAL ports
109 * So we should propably go back to
110 * bindaddr= the default address to bind to. If tcpenable=yes, then bind this to both udp and TCP
111 * if tlsenable=yes, open TLS port (provided we also have cert)
112 * tcpbindaddr = extra address for additional TCP connections
113 * tlsbindaddr = extra address for additional TCP/TLS connections
114 * udpbindaddr = extra address for additional UDP connections
115 * These three options should take multiple IP/port pairs
116 * Note: Since opening additional listen sockets is a *new* feature we do not have today
117 * the XXXbindaddr options needs to be disabled until we have support for it
119 * \todo re-evaluate the transport= setting in sip.conf. This is right now not well
120 * thought of. If a device in sip.conf contacts us via TCP, we should not switch transport,
121 * even if udp is the configured first transport.
123 * \todo Be prepared for one outbound and another incoming socket per pvt. This applies
124 * specially to communication with other peers (proxies).
125 * \todo We need to test TCP sessions with SIP proxies and in regards
126 * to the SIP outbound specs.
127 * \todo transport=tls was deprecated in RFC3261 and should not be used at all. See section 22.2.2.
129 * \todo If the message is smaller than the given Content-length, the request should get a 400 Bad request
130 * message. If it's a response, it should be dropped. (RFC 3261, Section 18.3)
131 * \todo Since we have had multidomain support in Asterisk for quite a while, we need to support
132 * multiple domains in our TLS implementation, meaning one socket and one cert per domain
133 * \todo Selection of transport for a request needs to be done after we've parsed all route headers,
134 * also considering outbound proxy options.
135 * First request: Outboundproxy, routes, (reg contact or URI. If URI doesn't have port: DNS naptr, srv, AAA)
136 * Intermediate requests: Outboundproxy(only when forced), routes, contact/uri
137 * DNS naptr support is crucial. A SIP uri might lead to a TLS connection.
138 * Also note that due to outbound proxy settings, a SIPS uri might have to be sent on UDP (not to recommend though)
139 * \todo Default transports are set to UDP, which cause the wrong behaviour when contacting remote
140 * devices directly from the dialplan. UDP is only a fallback if no other method works,
141 * in order to be compatible with RFC2543 (SIP/1.0) devices. For transactions that exceed the
142 * MTU (like INIVTE with video, audio and RTT) TCP should be preferred.
144 * When dialling unconfigured peers (with no port number) or devices in external domains
145 * NAPTR records MUST be consulted to find configured transport. If they are not found,
146 * SRV records for both TCP and UDP should be checked. If there's a record for TCP, use that.
147 * If there's no record for TCP, then use UDP as a last resort. If there's no SRV records,
148 * \note this only applies if there's no outbound proxy configured for the session. If an outbound
149 * proxy is configured, these procedures might apply for locating the proxy and determining
150 * the transport to use for communication with the proxy.
151 * \par Other bugs to fix ----
152 * __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
153 * - sets TLS port as default for all TCP connections, unless other port is given in contact.
154 * parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
155 * - assumes that the contact the UA registers is using the same transport as the REGISTER request, which is
157 * - Does not save any information about TCP/TLS connected devices, which is a severe BUG, as discussed on the mailing list.
158 * get_destination(struct sip_pvt *p, struct sip_request *oreq)
159 * - Doesn't store the information that we got an incoming SIPS request in the channel, so that
160 * we can require a secure signalling path OUT of Asterisk (on SIP or IAX2). Possibly, the call should
161 * fail on in-secure signalling paths if there's no override in our configuration. At least, provide a
162 * channel variable in the dialplan.
163 * get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
164 * - As above, if we have a SIPS: uri in the refer-to header
165 * - Does not check transport in refer_to uri.
169 <depend>chan_local</depend>
172 /*! \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
174 The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
175 refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
176 request at a negotiated interval. If a session refresh fails then all the entities that support Session-
177 Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
178 the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
179 that do not support Session-Timers).
181 The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
182 per-peer settings override the global settings. The following new parameters have been
183 added to the sip.conf file.
184 session-timers=["accept", "originate", "refuse"]
185 session-expires=[integer]
186 session-minse=[integer]
187 session-refresher=["uas", "uac"]
189 The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
190 Asterisk. The Asterisk can be configured in one of the following three modes:
192 1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
193 made by remote end-points. A remote end-point can request Asterisk to engage
194 session-timers by either sending it an INVITE request with a "Supported: timer"
195 header in it or by responding to Asterisk's INVITE with a 200 OK that contains
196 Session-Expires: header in it. In this mode, the Asterisk server does not
197 request session-timers from remote end-points. This is the default mode.
198 2. Originate :: In the "originate" mode, the Asterisk server requests the remote
199 end-points to activate session-timers in addition to honoring such requests
200 made by the remote end-pints. In order to get as much protection as possible
201 against hanging SIP channels due to network or end-point failures, Asterisk
202 resends periodic re-INVITEs even if a remote end-point does not support
203 the session-timers feature.
204 3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
205 timers for inbound or outbound requests. If a remote end-point requests
206 session-timers in a dialog, then Asterisk ignores that request unless it's
207 noted as a requirement (Require: header), in which case the INVITE is
208 rejected with a 420 Bad Extension response.
212 #include "asterisk.h"
214 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
217 #include <sys/ioctl.h>
220 #include <sys/signal.h>
224 #include "asterisk/network.h"
225 #include "asterisk/paths.h" /* need ast_config_AST_SYSTEM_NAME */
227 #include "asterisk/lock.h"
228 #include "asterisk/channel.h"
229 #include "asterisk/config.h"
230 #include "asterisk/module.h"
231 #include "asterisk/pbx.h"
232 #include "asterisk/sched.h"
233 #include "asterisk/io.h"
234 #include "asterisk/rtp.h"
235 #include "asterisk/udptl.h"
236 #include "asterisk/acl.h"
237 #include "asterisk/manager.h"
238 #include "asterisk/callerid.h"
239 #include "asterisk/cli.h"
240 #include "asterisk/app.h"
241 #include "asterisk/musiconhold.h"
242 #include "asterisk/dsp.h"
243 #include "asterisk/features.h"
244 #include "asterisk/srv.h"
245 #include "asterisk/astdb.h"
246 #include "asterisk/causes.h"
247 #include "asterisk/utils.h"
248 #include "asterisk/file.h"
249 #include "asterisk/astobj.h"
251 Uncomment the define below, if you are having refcount related memory leaks.
252 With this uncommented, this module will generate a file, /tmp/refs, which contains
253 a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
254 be modified to ao2_t_* calls, and include a tag describing what is happening with
255 enough detail, to make pairing up a reference count increment with its corresponding decrement.
256 The refcounter program in utils/ can be invaluable in highlighting objects that are not
257 balanced, along with the complete history for that object.
258 In normal operation, the macros defined will throw away the tags, so they do not
259 affect the speed of the program at all. They can be considered to be documentation.
261 /* #define REF_DEBUG 1 */
262 #include "asterisk/astobj2.h"
263 #include "asterisk/dnsmgr.h"
264 #include "asterisk/devicestate.h"
265 #include "asterisk/linkedlists.h"
266 #include "asterisk/stringfields.h"
267 #include "asterisk/monitor.h"
268 #include "asterisk/netsock.h"
269 #include "asterisk/localtime.h"
270 #include "asterisk/abstract_jb.h"
271 #include "asterisk/threadstorage.h"
272 #include "asterisk/translate.h"
273 #include "asterisk/ast_version.h"
274 #include "asterisk/event.h"
275 #include "asterisk/tcptls.h"
286 #define MAX(a,b) ((a) > (b) ? (a) : (b))
290 #define SIPBUFSIZE 512 /*!< Buffer size for many operations */
292 #define XMIT_ERROR -2
294 #define SIP_RESERVED ";/?:@&=+$,# " /*!< Reserved characters in the username part of the URI */
296 /* #define VOCAL_DATA_HACK */
298 #define DEFAULT_DEFAULT_EXPIRY 120
299 #define DEFAULT_MIN_EXPIRY 60
300 #define DEFAULT_MAX_EXPIRY 3600
301 #define DEFAULT_MWI_EXPIRY 3600
302 #define DEFAULT_REGISTRATION_TIMEOUT 20
303 #define DEFAULT_MAX_FORWARDS "70"
305 /* guard limit must be larger than guard secs */
306 /* guard min must be < 1000, and should be >= 250 */
307 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
308 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
310 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
311 GUARD_PCT turns out to be lower than this, it
312 will use this time instead.
313 This is in milliseconds. */
314 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
315 below EXPIRY_GUARD_LIMIT */
316 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
318 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
319 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
320 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
321 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
323 #define CALLERID_UNKNOWN "Unknown"
325 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
326 #define DEFAULT_QUALIFYFREQ 60 * 1000 /*!< Qualification: How often to check for the host to be up */
327 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
329 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
330 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
331 #define SIP_TIMER_T1 500 /*!< SIP timer T1 (according to RFC 3261) */
332 #define SIP_TRANS_TIMEOUT 64 * SIP_TIMER_T1/*!< SIP request timeout (rfc 3261) 64*T1
333 \todo Use known T1 for timeout (peerpoke)
335 #define DEFAULT_TRANS_TIMEOUT -1 /*!< Use default SIP transaction timeout */
336 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
338 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
339 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
340 #define SIP_MIN_PACKET 1024 /*!< Initialize size of memory to allocate for packets */
342 #define INITIAL_CSEQ 101 /*!< Our initial sip sequence number */
344 #define DEFAULT_MAX_SE 1800 /*!< Session-Timer Default Session-Expires period (RFC 4028) */
345 #define DEFAULT_MIN_SE 90 /*!< Session-Timer Default Min-SE period (RFC 4028) */
347 #define SDP_MAX_RTPMAP_CODECS 32 /*!< Maximum number of codecs allowed in received SDP */
349 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
350 static struct ast_jb_conf default_jbconf =
354 .resync_threshold = -1,
357 static struct ast_jb_conf global_jbconf; /*!< Global jitterbuffer configuration */
359 static const char config[] = "sip.conf"; /*!< Main configuration file */
360 static const char notify_config[] = "sip_notify.conf"; /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
365 /*! \brief Authorization scheme for call transfers
367 \note Not a bitfield flag, since there are plans for other modes,
368 like "only allow transfers for authenticated devices" */
370 TRANSFER_OPENFORALL, /*!< Allow all SIP transfers */
371 TRANSFER_CLOSED, /*!< Allow no SIP transfers */
375 /*! \brief The result of a lot of functions */
377 AST_SUCCESS = 0, /*!< FALSE means success, funny enough */
378 AST_FAILURE = -1, /*!< Failure code */
381 /*! \brief States for the INVITE transaction, not the dialog
382 \note this is for the INVITE that sets up the dialog
385 INV_NONE = 0, /*!< No state at all, maybe not an INVITE dialog */
386 INV_CALLING = 1, /*!< Invite sent, no answer */
387 INV_PROCEEDING = 2, /*!< We got/sent 1xx message */
388 INV_EARLY_MEDIA = 3, /*!< We got 18x message with to-tag back */
389 INV_COMPLETED = 4, /*!< Got final response with error. Wait for ACK, then CONFIRMED */
390 INV_CONFIRMED = 5, /*!< Confirmed response - we've got an ack (Incoming calls only) */
391 INV_TERMINATED = 6, /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done
392 The only way out of this is a BYE from one side */
393 INV_CANCELLED = 7, /*!< Transaction cancelled by client or server in non-terminated state */
396 /*! \brief Readable descriptions of device states.
397 \note Should be aligned to above table as index */
398 static const struct invstate2stringtable {
399 const enum invitestates state;
401 } invitestate2string[] = {
403 {INV_CALLING, "Calling (Trying)"},
404 {INV_PROCEEDING, "Proceeding "},
405 {INV_EARLY_MEDIA, "Early media"},
406 {INV_COMPLETED, "Completed (done)"},
407 {INV_CONFIRMED, "Confirmed (up)"},
408 {INV_TERMINATED, "Done"},
409 {INV_CANCELLED, "Cancelled"}
412 /*! \brief When sending a SIP message, we can send with a few options, depending on
413 type of SIP request. UNRELIABLE is moslty used for responses to repeated requests,
414 where the original response would be sent RELIABLE in an INVITE transaction */
416 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
417 If it fails, it's critical and will cause a teardown of the session */
418 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
419 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
422 /*! \brief Results from the parse_register() function */
423 enum parse_register_result {
424 PARSE_REGISTER_FAILED,
425 PARSE_REGISTER_UPDATE,
426 PARSE_REGISTER_QUERY,
429 /*! \brief Type of subscription, based on the packages we do support, see \ref subscription_types */
430 enum subscriptiontype {
439 /*! \brief Subscription types that we support. We support
440 - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
441 - SIMPLE presence used for device status
442 - Voicemail notification subscriptions
444 static const struct cfsubscription_types {
445 enum subscriptiontype type;
446 const char * const event;
447 const char * const mediatype;
448 const char * const text;
449 } subscription_types[] = {
450 { NONE, "-", "unknown", "unknown" },
451 /* RFC 4235: SIP Dialog event package */
452 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
453 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
454 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
455 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
456 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
460 /*! \brief Authentication types - proxy or www authentication
461 \note Endpoints, like Asterisk, should always use WWW authentication to
462 allow multiple authentications in the same call - to the proxy and
470 /*! \brief Authentication result from check_auth* functions */
471 enum check_auth_result {
472 AUTH_DONT_KNOW = -100, /*!< no result, need to check further */
473 /* XXX maybe this is the same as AUTH_NOT_FOUND */
476 AUTH_CHALLENGE_SENT = 1,
477 AUTH_SECRET_FAILED = -1,
478 AUTH_USERNAME_MISMATCH = -2,
479 AUTH_NOT_FOUND = -3, /*!< returned by register_verify */
481 AUTH_UNKNOWN_DOMAIN = -5,
482 AUTH_PEER_NOT_DYNAMIC = -6,
483 AUTH_ACL_FAILED = -7,
484 AUTH_BAD_TRANSPORT = -8,
487 /*! \brief States for outbound registrations (with register= lines in sip.conf */
488 enum sipregistrystate {
489 REG_STATE_UNREGISTERED = 0, /*!< We are not registred
490 * \note Initial state. We should have a timeout scheduled for the initial
491 * (or next) registration transmission, calling sip_reregister
494 REG_STATE_REGSENT, /*!< Registration request sent
495 * \note sent initial request, waiting for an ack or a timeout to
496 * retransmit the initial request.
499 REG_STATE_AUTHSENT, /*!< We have tried to authenticate
500 * \note entered after transmit_register with auth info,
501 * waiting for an ack.
504 REG_STATE_REGISTERED, /*!< Registered and done */
506 REG_STATE_REJECTED, /*!< Registration rejected *
507 * \note only used when the remote party has an expire larger than
508 * our max-expire. This is a final state from which we do not
509 * recover (not sure how correctly).
512 REG_STATE_TIMEOUT, /*!< Registration timed out *
513 * \note XXX unused */
515 REG_STATE_NOAUTH, /*!< We have no accepted credentials
516 * \note fatal - no chance to proceed */
518 REG_STATE_FAILED, /*!< Registration failed after several tries
519 * \note fatal - no chance to proceed */
522 /*! \brief Modes in which Asterisk can be configured to run SIP Session-Timers */
524 SESSION_TIMER_MODE_INVALID = 0, /*!< Invalid value */
525 SESSION_TIMER_MODE_ACCEPT, /*!< Honor inbound Session-Timer requests */
526 SESSION_TIMER_MODE_ORIGINATE, /*!< Originate outbound and honor inbound requests */
527 SESSION_TIMER_MODE_REFUSE /*!< Ignore inbound Session-Timers requests */
530 /*! \brief The entity playing the refresher role for Session-Timers */
532 SESSION_TIMER_REFRESHER_AUTO, /*!< Negotiated */
533 SESSION_TIMER_REFRESHER_UAC, /*!< Session is refreshed by the UAC */
534 SESSION_TIMER_REFRESHER_UAS /*!< Session is refreshed by the UAS */
537 /*! \brief Define some implemented SIP transports
538 \note Asterisk does not support SCTP or UDP/DTLS
541 SIP_TRANSPORT_UDP = 1, /*!< Unreliable transport for SIP, needs retransmissions */
542 SIP_TRANSPORT_TCP = 1 << 1, /*!< Reliable, but unsecure */
543 SIP_TRANSPORT_TLS = 1 << 2, /*!< TCP/TLS - reliable and secure transport for signalling */
546 /*! \brief definition of a sip proxy server
548 * For outbound proxies, a sip_peer will contain a reference to a
549 * dynamically allocated instance of a sip_proxy. A sip_pvt may also
550 * contain a reference to a peer's outboundproxy, or it may contain
551 * a reference to the global_outboundproxy.
554 char name[MAXHOSTNAMELEN]; /*!< DNS name of domain/host or IP */
555 struct sockaddr_in ip; /*!< Currently used IP address and port */
556 time_t last_dnsupdate; /*!< When this was resolved */
557 enum sip_transport transport;
558 int force; /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
559 /* Room for a SRV record chain based on the name */
562 /*! \brief argument for the 'show channels|subscriptions' callback. */
563 struct __show_chan_arg {
566 int numchans; /* return value */
570 /*! \brief States whether a SIP message can create a dialog in Asterisk. */
571 enum can_create_dialog {
572 CAN_NOT_CREATE_DIALOG,
574 CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
577 /*! \brief SIP Request methods known by Asterisk
579 \note Do _NOT_ make any changes to this enum, or the array following it;
580 if you think you are doing the right thing, you are probably
581 not doing the right thing. If you think there are changes
582 needed, get someone else to review them first _before_
583 submitting a patch. If these two lists do not match properly
584 bad things will happen.
588 SIP_UNKNOWN, /*!< Unknown response */
589 SIP_RESPONSE, /*!< Not request, response to outbound request */
590 SIP_REGISTER, /*!< Registration to the mothership, tell us where you are located */
591 SIP_OPTIONS, /*!< Check capabilities of a device, used for "ping" too */
592 SIP_NOTIFY, /*!< Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER */
593 SIP_INVITE, /*!< Set up a session */
594 SIP_ACK, /*!< End of a three-way handshake started with INVITE. */
595 SIP_PRACK, /*!< Reliable pre-call signalling. Not supported in Asterisk. */
596 SIP_BYE, /*!< End of a session */
597 SIP_REFER, /*!< Refer to another URI (transfer) */
598 SIP_SUBSCRIBE, /*!< Subscribe for updates (voicemail, session status, device status, presence) */
599 SIP_MESSAGE, /*!< Text messaging */
600 SIP_UPDATE, /*!< Update a dialog. We can send UPDATE; but not accept it */
601 SIP_INFO, /*!< Information updates during a session */
602 SIP_CANCEL, /*!< Cancel an INVITE */
603 SIP_PUBLISH, /*!< Not supported in Asterisk */
604 SIP_PING, /*!< Not supported at all, no standard but still implemented out there */
607 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
608 structure and then route the messages according to the type.
610 \note Note that sip_methods[i].id == i must hold or the code breaks */
611 static const struct cfsip_methods {
613 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
615 enum can_create_dialog can_create;
617 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
618 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
619 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
620 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
621 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
622 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
623 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
624 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
625 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
626 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
627 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
628 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
629 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
630 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
631 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
632 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
633 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
636 /*! Define SIP option tags, used in Require: and Supported: headers
637 We need to be aware of these properties in the phones to use
638 the replace: header. We should not do that without knowing
639 that the other end supports it...
640 This is nothing we can configure, we learn by the dialog
641 Supported: header on the REGISTER (peer) or the INVITE
643 We are not using many of these today, but will in the future.
644 This is documented in RFC 3261
647 #define NOT_SUPPORTED 0
650 #define SIP_OPT_REPLACES (1 << 0)
651 #define SIP_OPT_100REL (1 << 1)
652 #define SIP_OPT_TIMER (1 << 2)
653 #define SIP_OPT_EARLY_SESSION (1 << 3)
654 #define SIP_OPT_JOIN (1 << 4)
655 #define SIP_OPT_PATH (1 << 5)
656 #define SIP_OPT_PREF (1 << 6)
657 #define SIP_OPT_PRECONDITION (1 << 7)
658 #define SIP_OPT_PRIVACY (1 << 8)
659 #define SIP_OPT_SDP_ANAT (1 << 9)
660 #define SIP_OPT_SEC_AGREE (1 << 10)
661 #define SIP_OPT_EVENTLIST (1 << 11)
662 #define SIP_OPT_GRUU (1 << 12)
663 #define SIP_OPT_TARGET_DIALOG (1 << 13)
664 #define SIP_OPT_NOREFERSUB (1 << 14)
665 #define SIP_OPT_HISTINFO (1 << 15)
666 #define SIP_OPT_RESPRIORITY (1 << 16)
667 #define SIP_OPT_FROMCHANGE (1 << 17)
668 #define SIP_OPT_RECLISTINV (1 << 18)
669 #define SIP_OPT_RECLISTSUB (1 << 19)
670 #define SIP_OPT_OUTBOUND (1 << 20)
671 #define SIP_OPT_UNKNOWN (1 << 21)
674 /*! \brief List of well-known SIP options. If we get this in a require,
675 we should check the list and answer accordingly. */
676 static const struct cfsip_options {
677 int id; /*!< Bitmap ID */
678 int supported; /*!< Supported by Asterisk ? */
679 char * const text; /*!< Text id, as in standard */
680 } sip_options[] = { /* XXX used in 3 places */
681 /* RFC3262: PRACK 100% reliability */
682 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
683 /* RFC3959: SIP Early session support */
684 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
685 /* SIMPLE events: RFC4662 */
686 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
687 /* RFC 4916- Connected line ID updates */
688 { SIP_OPT_FROMCHANGE, NOT_SUPPORTED, "from-change" },
689 /* GRUU: Globally Routable User Agent URI's */
690 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
691 /* RFC4244 History info */
692 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
693 /* RFC3911: SIP Join header support */
694 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
695 /* Disable the REFER subscription, RFC 4488 */
696 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
697 /* SIP outbound - the final NAT battle - draft-sip-outbound */
698 { SIP_OPT_OUTBOUND, NOT_SUPPORTED, "outbound" },
699 /* RFC3327: Path support */
700 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
701 /* RFC3840: Callee preferences */
702 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
703 /* RFC3312: Precondition support */
704 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
705 /* RFC3323: Privacy with proxies*/
706 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
707 /* RFC-ietf-sip-uri-list-conferencing-02.txt conference invite lists */
708 { SIP_OPT_RECLISTINV, NOT_SUPPORTED, "recipient-list-invite" },
709 /* RFC-ietf-sip-uri-list-subscribe-02.txt - subscription lists */
710 { SIP_OPT_RECLISTSUB, NOT_SUPPORTED, "recipient-list-subscribe" },
711 /* RFC3891: Replaces: header for transfer */
712 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
713 /* One version of Polycom firmware has the wrong label */
714 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
715 /* RFC4412 Resource priorities */
716 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
717 /* RFC3329: Security agreement mechanism */
718 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
719 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
720 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
721 /* RFC4028: SIP Session-Timers */
722 { SIP_OPT_TIMER, SUPPORTED, "timer" },
723 /* RFC4538: Target-dialog */
724 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
728 /*! \brief SIP Methods we support
729 \todo This string should be set dynamically. We only support REFER and SUBSCRIBE if we have
730 allowsubscribe and allowrefer on in sip.conf.
732 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
734 /*! \brief SIP Extensions we support
735 \note This should be generated based on the previous array
736 in combination with settings.
737 \todo We should not have "timer" if it's disabled in the configuration file.
739 #define SUPPORTED_EXTENSIONS "replaces, timer"
741 /*! \brief Standard SIP unsecure port for UDP and TCP from RFC 3261. DO NOT CHANGE THIS */
742 #define STANDARD_SIP_PORT 5060
743 /*! \brief Standard SIP TLS port from RFC 3261. DO NOT CHANGE THIS */
744 #define STANDARD_TLS_PORT 5061
746 /*! \note in many SIP headers, absence of a port number implies port 5060,
747 * and this is why we cannot change the above constant.
748 * There is a limited number of places in asterisk where we could,
749 * in principle, use a different "default" port number, but
750 * we do not support this feature at the moment.
751 * You can run Asterisk with SIP on a different port with a configuration
752 * option. If you change this value, the signalling will be incorrect.
755 /*! \name DefaultValues Default values, set and reset in reload_config before reading configuration
757 These are default values in the source. There are other recommended values in the
758 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
759 yet encouraging new behaviour on new installations
762 #define DEFAULT_CONTEXT "default" /*!< The default context for [general] section as well as devices */
763 #define DEFAULT_MOHINTERPRET "default" /*!< The default music class */
764 #define DEFAULT_MOHSUGGEST ""
765 #define DEFAULT_VMEXTEN "asterisk" /*!< Default voicemail extension */
766 #define DEFAULT_CALLERID "asterisk" /*!< Default caller ID */
767 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
768 #define DEFAULT_ALLOWGUEST TRUE
769 #define DEFAULT_RTPKEEPALIVE 0 /*!< Default RTPkeepalive setting */
770 #define DEFAULT_CALLCOUNTER FALSE
771 #define DEFAULT_SRVLOOKUP TRUE /*!< Recommended setting is ON */
772 #define DEFAULT_COMPACTHEADERS FALSE /*!< Send compact (one-character) SIP headers. Default off */
773 #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. */
774 #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. */
775 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
776 #define DEFAULT_TOS_TEXT 0 /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
777 #define DEFAULT_COS_SIP 4 /*!< Level 2 class of service for SIP signalling */
778 #define DEFAULT_COS_AUDIO 5 /*!< Level 2 class of service for audio media */
779 #define DEFAULT_COS_VIDEO 6 /*!< Level 2 class of service for video media */
780 #define DEFAULT_COS_TEXT 5 /*!< Level 2 class of service for text media (T.140) */
781 #define DEFAULT_ALLOW_EXT_DOM TRUE /*!< Allow external domains */
782 #define DEFAULT_REALM "asterisk" /*!< Realm for HTTP digest authentication */
783 #define DEFAULT_NOTIFYRINGING TRUE /*!< Notify devicestate system on ringing state */
784 #define DEFAULT_PEDANTIC FALSE /*!< Avoid following SIP standards for dialog matching */
785 #define DEFAULT_AUTOCREATEPEER FALSE /*!< Don't create peers automagically */
786 #define DEFAULT_MATCHEXTERNIPLOCALLY FALSE /*!< Match extern IP locally default setting */
787 #define DEFAULT_QUALIFY FALSE /*!< Don't monitor devices */
788 #define DEFAULT_CALLEVENTS FALSE /*!< Extra manager SIP call events */
789 #define DEFAULT_ALWAYSAUTHREJECT FALSE /*!< Don't reject authentication requests always */
790 #define DEFAULT_REGEXTENONQUALIFY FALSE
791 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
792 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
793 #ifndef DEFAULT_USERAGENT
794 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
795 #define DEFAULT_SDPSESSION "Asterisk PBX" /*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
796 #define DEFAULT_SDPOWNER "root" /*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
800 /*! \name DefaultSettings
801 Default setttings are used as a channel setting and as a default when
805 static char default_context[AST_MAX_CONTEXT];
806 static char default_subscribecontext[AST_MAX_CONTEXT];
807 static char default_language[MAX_LANGUAGE];
808 static char default_callerid[AST_MAX_EXTENSION];
809 static char default_fromdomain[AST_MAX_EXTENSION];
810 static char default_notifymime[AST_MAX_EXTENSION];
811 static int default_qualify; /*!< Default Qualify= setting */
812 static char default_vmexten[AST_MAX_EXTENSION];
813 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
814 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
815 * a bridged channel on hold */
816 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
817 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
818 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
819 static unsigned int default_transports; /*!< Default Transports (enum sip_transport) that are acceptable */
820 static unsigned int default_primary_transport; /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
824 /*! \name GlobalSettings
825 Global settings apply to the channel (often settings you can change in the general section
829 /*! \brief a place to store all global settings for the sip channel driver
831 struct sip_settings {
832 int peer_rtupdate; /*!< G: Update database with registration data for peer? */
833 int rtsave_sysname; /*!< G: Save system name at registration? */
834 int ignore_regexpire; /*!< G: Ignore expiration of peer */
835 int rtautoclear; /*!< Realtime ?? */
836 int directrtpsetup; /*!< Enable support for Direct RTP setup (no re-invites) */
837 int pedanticsipchecking; /*!< Extra checking ? Default off */
838 int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
839 int srvlookup; /*!< SRV Lookup on or off. Default is on */
840 int allowguest; /*!< allow unauthenticated peers to connect? */
841 int alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
842 int compactheaders; /*!< send compact sip headers */
843 int allow_external_domains; /*!< Accept calls to external SIP domains? */
844 int callevents; /*!< Whether we send manager events or not */
845 int regextenonqualify; /*!< Whether to add/remove regexten when qualifying peers */
846 int matchexterniplocally; /*!< Match externip/externhost setting against localnet setting */
849 static struct sip_settings sip_cfg;
851 static int global_notifyringing; /*!< Send notifications on ringing */
852 static int global_notifyhold; /*!< Send notifications on hold */
853 static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
855 static int global_relaxdtmf; /*!< Relax DTMF */
856 static int global_rtptimeout; /*!< Time out call if no RTP */
857 static int global_rtpholdtimeout; /*!< Time out call if no RTP during hold */
858 static int global_rtpkeepalive; /*!< Send RTP keepalives */
859 static int global_reg_timeout;
860 static int global_regattempts_max; /*!< Registration attempts before giving up */
861 static int global_callcounter; /*!< Enable call counters for all devices. This is currently enabled by setting the peer
862 call-limit to 999. When we remove the call-limit from the code, we can make it
863 with just a boolean flag in the device structure */
864 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
865 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
866 the global setting is in globals_flags[1] */
867 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
868 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
869 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
870 static unsigned int global_tos_text; /*!< IP type of service for text RTP packets */
871 static unsigned int global_cos_sip; /*!< 802.1p class of service for SIP packets */
872 static unsigned int global_cos_audio; /*!< 802.1p class of service for audio RTP packets */
873 static unsigned int global_cos_video; /*!< 802.1p class of service for video RTP packets */
874 static unsigned int global_cos_text; /*!< 802.1p class of service for text RTP packets */
875 static int recordhistory; /*!< Record SIP history. Off by default */
876 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
877 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
878 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
879 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
880 static char global_sdpsession[AST_MAX_EXTENSION]; /*!< SDP session name for the SIP channel */
881 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
882 static int global_authfailureevents; /*!< Whether we send authentication failure manager events or not. Default no. */
883 static int global_t1; /*!< T1 time */
884 static int global_t1min; /*!< T1 roundtrip time minimum */
885 static int global_timer_b; /*!< Timer B - RFC 3261 Section 17.1.1.2 */
886 static int global_autoframing; /*!< Turn autoframing on or off. */
887 static struct sip_proxy global_outboundproxy; /*!< Outbound proxy */
888 static int global_qualifyfreq; /*!< Qualify frequency */
891 /*! \brief Codecs that we support by default: */
892 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
894 static enum st_mode global_st_mode; /*!< Mode of operation for Session-Timers */
895 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher */
896 static int global_min_se; /*!< Lowest threshold for session refresh interval */
897 static int global_max_se; /*!< Highest threshold for session refresh interval */
901 /*! \brief Global list of addresses dynamic peers are not allowed to use */
902 static struct ast_ha *global_contact_ha = NULL;
903 static int global_dynamic_exclude_static = 0;
905 /*! \name Object counters @{
906 * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
907 * should be used to modify these values. */
908 static int speerobjs = 0; /*!< Static peers */
909 static int rpeerobjs = 0; /*!< Realtime peers */
910 static int apeerobjs = 0; /*!< Autocreated peer objects */
911 static int regobjs = 0; /*!< Registry objects */
914 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
915 static char used_context[AST_MAX_CONTEXT]; /*!< name of automatically created context for unloading */
918 AST_MUTEX_DEFINE_STATIC(netlock);
920 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
921 when it's doing something critical. */
922 AST_MUTEX_DEFINE_STATIC(monlock);
924 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
926 /*! \brief This is the thread for the monitor which checks for input on the channels
927 which are not currently in use. */
928 static pthread_t monitor_thread = AST_PTHREADT_NULL;
930 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
931 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
933 static struct sched_context *sched; /*!< The scheduling context */
934 static struct io_context *io; /*!< The IO context */
935 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
937 #define DEC_CALL_LIMIT 0
938 #define INC_CALL_LIMIT 1
939 #define DEC_CALL_RINGING 2
940 #define INC_CALL_RINGING 3
942 /*! \brief The SIP socket definition */
944 enum sip_transport type; /*!< UDP, TCP or TLS */
945 int fd; /*!< Filed descriptor, the actual socket */
947 struct ast_tcptls_session_instance *ser; /* If tcp or tls, a socket manager */
950 /*! \brief sip_request: The data grabbed from the UDP socket
953 * Incoming messages: we first store the data from the socket in data[],
954 * adding a trailing \0 to make string parsing routines happy.
955 * Then call parse_request() and req.method = find_sip_method();
956 * to initialize the other fields. The \r\n at the end of each line is
957 * replaced by \0, so that data[] is not a conforming SIP message anymore.
958 * After this processing, rlPart1 is set to non-NULL to remember
959 * that we can run get_header() on this kind of packet.
961 * parse_request() splits the first line as follows:
962 * Requests have in the first line method uri SIP/2.0
963 * rlPart1 = method; rlPart2 = uri;
964 * Responses have in the first line SIP/2.0 NNN description
965 * rlPart1 = SIP/2.0; rlPart2 = NNN + description;
967 * For outgoing packets, we initialize the fields with init_req() or init_resp()
968 * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
969 * and then fill the rest with add_header() and add_line().
970 * The \r\n at the end of the line are still there, so the get_header()
971 * and similar functions don't work on these packets.
975 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
976 char *rlPart2; /*!< The Request URI or Response Status */
977 int len; /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
978 int headers; /*!< # of SIP Headers */
979 int method; /*!< Method of this request */
980 int lines; /*!< Body Content */
981 unsigned int sdp_start; /*!< the line number where the SDP begins */
982 unsigned int sdp_end; /*!< the line number where the SDP ends */
983 char debug; /*!< print extra debugging if non zero */
984 char has_to_tag; /*!< non-zero if packet has To: tag */
985 char ignore; /*!< if non-zero This is a re-transmit, ignore it */
986 char *header[SIP_MAX_HEADERS];
987 char *line[SIP_MAX_LINES];
988 struct ast_str *data;
989 /* XXX Do we need to unref socket.ser when the request goes away? */
990 struct sip_socket socket; /*!< The socket used for this request */
993 /*! \brief structure used in transfers */
995 struct ast_channel *chan1; /*!< First channel involved */
996 struct ast_channel *chan2; /*!< Second channel involved */
997 struct sip_request req; /*!< Request that caused the transfer (REFER) */
998 int seqno; /*!< Sequence number */
1003 /*! \brief Parameters to the transmit_invite function */
1004 struct sip_invite_param {
1005 int addsipheaders; /*!< Add extra SIP headers */
1006 const char *uri_options; /*!< URI options to add to the URI */
1007 const char *vxml_url; /*!< VXML url for Cisco phones */
1008 char *auth; /*!< Authentication */
1009 char *authheader; /*!< Auth header */
1010 enum sip_auth_type auth_type; /*!< Authentication type */
1011 const char *replaces; /*!< Replaces header for call transfers */
1012 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
1015 /*! \brief Structure to save routing information for a SIP session */
1017 struct sip_route *next;
1021 /*! \brief Modes for SIP domain handling in the PBX */
1023 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
1024 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
1027 /*! \brief Domain data structure.
1028 \note In the future, we will connect this to a configuration tree specific
1032 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
1033 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
1034 enum domain_mode mode; /*!< How did we find this domain? */
1035 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
1038 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
1041 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
1042 struct sip_history {
1043 AST_LIST_ENTRY(sip_history) list;
1044 char event[0]; /* actually more, depending on needs */
1047 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
1049 /*! \brief sip_auth: Credentials for authentication to other SIP services */
1051 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
1052 char username[256]; /*!< Username */
1053 char secret[256]; /*!< Secret */
1054 char md5secret[256]; /*!< MD5Secret */
1055 struct sip_auth *next; /*!< Next auth structure in list */
1059 Various flags for the flags field in the pvt structure
1060 Trying to sort these up (one or more of the following):
1064 When flags are used by multiple structures, it is important that
1065 they have a common layout so it is easy to copy them.
1068 #define SIP_OUTGOING (1 << 0) /*!< D: Direction of the last transaction in this dialog */
1069 #define SIP_RINGING (1 << 2) /*!< D: Have sent 180 ringing */
1070 #define SIP_PROGRESS_SENT (1 << 3) /*!< D: Have sent 183 message progress */
1071 #define SIP_NEEDREINVITE (1 << 4) /*!< D: Do we need to send another reinvite? */
1072 #define SIP_PENDINGBYE (1 << 5) /*!< D: Need to send bye after we ack? */
1073 #define SIP_GOTREFER (1 << 6) /*!< D: Got a refer? */
1074 #define SIP_CALL_LIMIT (1 << 7) /*!< D: Call limit enforced for this call */
1075 #define SIP_INC_COUNT (1 << 8) /*!< D: Did this dialog increment the counter of in-use calls? */
1076 #define SIP_INC_RINGING (1 << 9) /*!< D: Did this connection increment the counter of in-use calls? */
1077 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 10) /*!< D: Do not hangup at first ast_hangup */
1079 #define SIP_PROMISCREDIR (1 << 11) /*!< DP: Promiscuous redirection */
1080 #define SIP_TRUSTRPID (1 << 12) /*!< DP: Trust RPID headers? */
1081 #define SIP_USEREQPHONE (1 << 13) /*!< DP: Add user=phone to numeric URI. Default off */
1082 #define SIP_USECLIENTCODE (1 << 14) /*!< DP: Trust X-ClientCode info message */
1084 /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
1085 #define SIP_DTMF (7 << 15) /*!< DP: DTMF Support: five settings, uses three bits */
1086 #define SIP_DTMF_RFC2833 (0 << 15) /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
1087 #define SIP_DTMF_INBAND (1 << 15) /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
1088 #define SIP_DTMF_INFO (2 << 15) /*!< DP: DTMF Support: SIP Info messages - "info" */
1089 #define SIP_DTMF_AUTO (3 << 15) /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
1090 #define SIP_DTMF_SHORTINFO (4 << 15) /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
1092 /* NAT settings - see nat2str() */
1093 #define SIP_NAT (3 << 18) /*!< DP: four settings, uses two bits */
1094 #define SIP_NAT_NEVER (0 << 18) /*!< DP: No nat support */
1095 #define SIP_NAT_RFC3581 (1 << 18) /*!< DP: NAT RFC3581 */
1096 #define SIP_NAT_ROUTE (2 << 18) /*!< DP: NAT Only ROUTE */
1097 #define SIP_NAT_ALWAYS (3 << 18) /*!< DP: NAT Both ROUTE and RFC3581 */
1099 /* re-INVITE related settings */
1100 #define SIP_REINVITE (7 << 20) /*!< DP: four settings, uses three bits */
1101 #define SIP_REINVITE_NONE (0 << 20) /*!< DP: no reinvite allowed */
1102 #define SIP_CAN_REINVITE (1 << 20) /*!< DP: allow peers to be reinvited to send media directly p2p */
1103 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< DP: allow media reinvite when new peer is behind NAT */
1104 #define SIP_REINVITE_UPDATE (4 << 20) /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
1106 /* "insecure" settings - see insecure2str() */
1107 #define SIP_INSECURE (3 << 23) /*!< DP: three settings, uses two bits */
1108 #define SIP_INSECURE_NONE (0 << 23) /*!< DP: secure mode */
1109 #define SIP_INSECURE_PORT (1 << 23) /*!< DP: don't require matching port for incoming requests */
1110 #define SIP_INSECURE_INVITE (1 << 24) /*!< DP: don't require authentication for incoming INVITEs */
1112 /* Sending PROGRESS in-band settings */
1113 #define SIP_PROG_INBAND (3 << 25) /*!< DP: three settings, uses two bits */
1114 #define SIP_PROG_INBAND_NEVER (0 << 25)
1115 #define SIP_PROG_INBAND_NO (1 << 25)
1116 #define SIP_PROG_INBAND_YES (2 << 25)
1118 #define SIP_SENDRPID (1 << 29) /*!< DP: Remote Party-ID Support */
1119 #define SIP_G726_NONSTANDARD (1 << 31) /*!< DP: Use non-standard packing for G726-32 data */
1121 /*! \brief Flags to copy from peer/user to dialog */
1122 #define SIP_FLAGS_TO_COPY \
1123 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
1124 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
1125 SIP_USEREQPHONE | SIP_INSECURE)
1129 a second page of flags (for flags[1] */
1131 /* realtime flags */
1132 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0) /*!< GP: Should we keep RT objects in memory for extended time? */
1133 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2) /*!< GP: Should we clean memory from peers after expiry? */
1134 /* Space for addition of other realtime flags in the future */
1135 #define SIP_PAGE2_STATECHANGEQUEUE (1 << 9) /*!< D: Unsent state pending change exists */
1137 #define SIP_PAGE2_VIDEOSUPPORT (1 << 14) /*!< DP: Video supported if offered? */
1138 #define SIP_PAGE2_TEXTSUPPORT (1 << 15) /*!< GDP: Global text enable */
1139 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< GP: Allow subscriptions from this peer? */
1140 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< DP: Allow overlap dialing ? */
1141 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< GP: Only issue MWI notification if subscribed to */
1143 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< GDP: T38 Fax Passthrough Support */
1144 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< GDP: T38 Fax Passthrough Support */
1145 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< GDP: T38 Fax Passthrough Support (not implemented) */
1146 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< GDP: T38 Fax Passthrough Support (not implemented) */
1148 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< D: Call hold states: */
1149 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23) /*!< D: Active hold */
1150 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23) /*!< D: One directional hold */
1151 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23) /*!< D: Inactive hold */
1153 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25) /*!< DP: Compensate for buggy RFC2833 implementations */
1154 #define SIP_PAGE2_BUGGY_MWI (1 << 26) /*!< DP: Buggy CISCO MWI fix */
1155 #define SIP_PAGE2_DIALOG_ESTABLISHED (1 << 27) /*!< 29: Has a dialog been established? */
1156 #define SIP_PAGE2_REGISTERTRYING (1 << 29) /*!< DP: Send 100 Trying on REGISTER attempts */
1157 #define SIP_PAGE2_UDPTL_DESTINATION (1 << 30) /*!< DP: Use source IP of RTP as destination if NAT is enabled */
1158 #define SIP_PAGE2_VIDEOSUPPORT_ALWAYS (1 << 31) /*!< DP: Always set up video, even if endpoints don't support it */
1160 #define SIP_PAGE2_FLAGS_TO_COPY \
1161 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
1162 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI | \
1163 SIP_PAGE2_TEXTSUPPORT | SIP_PAGE2_UDPTL_DESTINATION | \
1164 SIP_PAGE2_VIDEOSUPPORT_ALWAYS)
1168 /*! \name SIPflagsT38
1169 T.38 set of flags */
1172 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
1173 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
1174 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
1175 /* Rate management */
1176 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
1177 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
1178 /* UDP Error correction */
1179 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
1180 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
1181 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
1182 /* T38 Spec version */
1183 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
1184 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
1185 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
1186 /* Maximum Fax Rate */
1187 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
1188 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
1189 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
1190 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
1191 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
1192 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
1194 /*!< This is default: NO MMR and JBIG transcoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
1195 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
1198 /*! \brief debugging state
1199 * We store separately the debugging requests from the config file
1200 * and requests from the CLI. Debugging is enabled if either is set
1201 * (which means that if sipdebug is set in the config file, we can
1202 * only turn it off by reloading the config).
1206 sip_debug_config = 1,
1207 sip_debug_console = 2,
1210 static enum sip_debug_e sipdebug;
1212 /*! \brief extra debugging for 'text' related events.
1213 * At the moment this is set together with sip_debug_console.
1214 * \note It should either go away or be implemented properly.
1216 static int sipdebug_text;
1218 /*! \brief T38 States for a call */
1220 T38_DISABLED = 0, /*!< Not enabled */
1221 T38_LOCAL_DIRECT, /*!< Offered from local */
1222 T38_LOCAL_REINVITE, /*!< Offered from local - REINVITE */
1223 T38_PEER_DIRECT, /*!< Offered from peer */
1224 T38_PEER_REINVITE, /*!< Offered from peer - REINVITE */
1225 T38_ENABLED /*!< Negotiated (enabled) */
1228 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
1229 struct t38properties {
1230 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
1231 int capability; /*!< Our T38 capability */
1232 int peercapability; /*!< Peers T38 capability */
1233 int jointcapability; /*!< Supported T38 capability at both ends */
1234 enum t38state state; /*!< T.38 state */
1237 /*! \brief Parameters to know status of transfer */
1239 REFER_IDLE, /*!< No REFER is in progress */
1240 REFER_SENT, /*!< Sent REFER to transferee */
1241 REFER_RECEIVED, /*!< Received REFER from transferrer */
1242 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING (unused) */
1243 REFER_ACCEPTED, /*!< Accepted by transferee */
1244 REFER_RINGING, /*!< Target Ringing */
1245 REFER_200OK, /*!< Answered by transfer target */
1246 REFER_FAILED, /*!< REFER declined - go on */
1247 REFER_NOAUTH /*!< We had no auth for REFER */
1250 /*! \brief generic struct to map between strings and integers.
1251 * Fill it with x-s pairs, terminate with an entry with s = NULL;
1252 * Then you can call map_x_s(...) to map an integer to a string,
1253 * and map_s_x() for the string -> integer mapping.
1260 static const struct _map_x_s referstatusstrings[] = {
1261 { REFER_IDLE, "<none>" },
1262 { REFER_SENT, "Request sent" },
1263 { REFER_RECEIVED, "Request received" },
1264 { REFER_CONFIRMED, "Confirmed" },
1265 { REFER_ACCEPTED, "Accepted" },
1266 { REFER_RINGING, "Target ringing" },
1267 { REFER_200OK, "Done" },
1268 { REFER_FAILED, "Failed" },
1269 { REFER_NOAUTH, "Failed - auth failure" },
1270 { -1, NULL} /* terminator */
1273 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
1274 \note OEJ: Should be moved to string fields */
1276 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
1277 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
1278 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
1279 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
1280 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
1281 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
1282 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
1283 char replaces_callid[SIPBUFSIZE]; /*!< Replace info: callid */
1284 char replaces_callid_totag[SIPBUFSIZE/2]; /*!< Replace info: to-tag */
1285 char replaces_callid_fromtag[SIPBUFSIZE/2]; /*!< Replace info: from-tag */
1286 struct sip_pvt *refer_call; /*!< Call we are referring. This is just a reference to a
1287 * dialog owned by someone else, so we should not destroy
1288 * it when the sip_refer object goes.
1290 int attendedtransfer; /*!< Attended or blind transfer? */
1291 int localtransfer; /*!< Transfer to local domain? */
1292 enum referstatus status; /*!< REFER status */
1296 /*! \brief Structure that encapsulates all attributes related to running
1297 * SIP Session-Timers feature on a per dialog basis.
1300 int st_active; /*!< Session-Timers on/off */
1301 int st_interval; /*!< Session-Timers negotiated session refresh interval */
1302 int st_schedid; /*!< Session-Timers ast_sched scheduler id */
1303 enum st_refresher st_ref; /*!< Session-Timers session refresher */
1304 int st_expirys; /*!< Session-Timers number of expirys */
1305 int st_active_peer_ua; /*!< Session-Timers on/off in peer UA */
1306 int st_cached_min_se; /*!< Session-Timers cached Min-SE */
1307 int st_cached_max_se; /*!< Session-Timers cached Session-Expires */
1308 enum st_mode st_cached_mode; /*!< Session-Timers cached M.O. */
1309 enum st_refresher st_cached_ref; /*!< Session-Timers cached refresher */
1313 /*! \brief Structure that encapsulates all attributes related to configuration
1314 * of SIP Session-Timers feature on a per user/peer basis.
1317 enum st_mode st_mode_oper; /*!< Mode of operation for Session-Timers */
1318 enum st_refresher st_ref; /*!< Session-Timer refresher */
1319 int st_min_se; /*!< Lowest threshold for session refresh interval */
1320 int st_max_se; /*!< Highest threshold for session refresh interval */
1326 /*! \brief Structure used for each SIP dialog, ie. a call, a registration, a subscribe.
1327 * Created and initialized by sip_alloc(), the descriptor goes into the list of
1328 * descriptors (dialoglist).
1331 struct sip_pvt *next; /*!< Next dialog in chain */
1332 enum invitestates invitestate; /*!< Track state of SIP_INVITEs */
1333 int method; /*!< SIP method that opened this dialog */
1334 AST_DECLARE_STRING_FIELDS(
1335 AST_STRING_FIELD(callid); /*!< Global CallID */
1336 AST_STRING_FIELD(randdata); /*!< Random data */
1337 AST_STRING_FIELD(accountcode); /*!< Account code */
1338 AST_STRING_FIELD(realm); /*!< Authorization realm */
1339 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1340 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1341 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1342 AST_STRING_FIELD(domain); /*!< Authorization domain */
1343 AST_STRING_FIELD(from); /*!< The From: header */
1344 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
1345 AST_STRING_FIELD(exten); /*!< Extension where to start */
1346 AST_STRING_FIELD(context); /*!< Context for this call */
1347 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
1348 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
1349 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
1350 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
1351 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
1352 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
1353 AST_STRING_FIELD(todnid); /*!< DNID of this call (overrides host) */
1354 AST_STRING_FIELD(language); /*!< Default language for this call */
1355 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
1356 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
1357 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
1358 AST_STRING_FIELD(redircause); /*!< Referring cause */
1359 AST_STRING_FIELD(theirtag); /*!< Their tag */
1360 AST_STRING_FIELD(username); /*!< [user] name */
1361 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
1362 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
1363 AST_STRING_FIELD(uri); /*!< Original requested URI */
1364 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
1365 AST_STRING_FIELD(peersecret); /*!< Password */
1366 AST_STRING_FIELD(peermd5secret);
1367 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
1368 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
1369 AST_STRING_FIELD(via); /*!< Via: header */
1370 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
1371 /* we only store the part in <brackets> in this field. */
1372 AST_STRING_FIELD(our_contact); /*!< Our contact header */
1373 AST_STRING_FIELD(rpid); /*!< Our RPID header */
1374 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
1375 AST_STRING_FIELD(url); /*!< URL to be sent with next message to peer */
1376 AST_STRING_FIELD(parkinglot); /*!< Parkinglot */
1378 struct sip_socket socket; /*!< The socket used for this dialog */
1379 unsigned int ocseq; /*!< Current outgoing seqno */
1380 unsigned int icseq; /*!< Current incoming seqno */
1381 ast_group_t callgroup; /*!< Call group */
1382 ast_group_t pickupgroup; /*!< Pickup group */
1383 int lastinvite; /*!< Last Cseq of invite */
1384 int lastnoninvite; /*!< Last Cseq of non-invite */
1385 struct ast_flags flags[2]; /*!< SIP_ flags */
1387 /* boolean or small integers that don't belong in flags */
1388 char do_history; /*!< Set if we want to record history */
1389 char alreadygone; /*!< already destroyed by our peer */
1390 char needdestroy; /*!< need to be destroyed by the monitor thread */
1391 char outgoing_call; /*!< this is an outgoing call */
1392 char answered_elsewhere; /*!< This call is cancelled due to answer on another channel */
1393 char novideo; /*!< Didn't get video in invite, don't offer */
1394 char notext; /*!< Text not supported (?) */
1396 int timer_t1; /*!< SIP timer T1, ms rtt */
1397 int timer_b; /*!< SIP timer B, ms */
1398 unsigned int sipoptions; /*!< Supported SIP options on the other end */
1399 unsigned int reqsipoptions; /*!< Required SIP options on the other end */
1400 struct ast_codec_pref prefs; /*!< codec prefs */
1401 int capability; /*!< Special capability (codec) */
1402 int jointcapability; /*!< Supported capability at both ends (codecs) */
1403 int peercapability; /*!< Supported peer capability */
1404 int prefcodec; /*!< Preferred codec (outbound only) */
1405 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
1406 int jointnoncodeccapability; /*!< Joint Non codec capability */
1407 int redircodecs; /*!< Redirect codecs */
1408 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
1409 struct sip_proxy *outboundproxy; /*!< Outbound proxy for this dialog. Use ref_proxy to set this instead of setting it directly*/
1410 struct t38properties t38; /*!< T38 settings */
1411 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
1412 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
1413 int callingpres; /*!< Calling presentation */
1414 int authtries; /*!< Times we've tried to authenticate */
1415 int expiry; /*!< How long we take to expire */
1416 long branch; /*!< The branch identifier of this session */
1417 long invite_branch; /*!< The branch used when we sent the initial INVITE */
1418 char tag[11]; /*!< Our tag for this session */
1419 int sessionid; /*!< SDP Session ID */
1420 int sessionversion; /*!< SDP Session Version */
1421 int sessionversion_remote; /*!< Remote UA's SDP Session Version */
1422 int session_modify; /*!< Session modification request true/false */
1423 struct sockaddr_in sa; /*!< Our peer */
1424 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
1425 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
1426 struct sockaddr_in tredirip; /*!< Where our Text RTP should be going if not to us */
1427 time_t lastrtprx; /*!< Last RTP received */
1428 time_t lastrtptx; /*!< Last RTP sent */
1429 int rtptimeout; /*!< RTP timeout time */
1430 struct sockaddr_in recv; /*!< Received as */
1431 struct sockaddr_in ourip; /*!< Our IP (as seen from the outside) */
1432 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
1433 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
1434 int route_persistant; /*!< Is this the "real" route? */
1435 struct ast_variable *notify_headers; /*!< Custom notify type */
1436 struct sip_auth *peerauth; /*!< Realm authentication */
1437 int noncecount; /*!< Nonce-count */
1438 char lastmsg[256]; /*!< Last Message sent/received */
1439 int amaflags; /*!< AMA Flags */
1440 int pendinginvite; /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
1441 struct sip_request initreq; /*!< Latest request that opened a new transaction
1443 NOT the request that opened the dialog
1446 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
1447 int waitid; /*!< Wait ID for scheduler after 491 or other delays */
1448 int autokillid; /*!< Auto-kill ID (scheduler) */
1449 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
1450 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
1451 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
1452 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
1453 int laststate; /*!< SUBSCRIBE: Last known extension state */
1454 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
1456 struct ast_dsp *vad; /*!< Inband DTMF Detection dsp */
1458 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
1459 Used in peerpoke, mwi subscriptions */
1460 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
1461 struct ast_rtp *rtp; /*!< RTP Session */
1462 struct ast_rtp *vrtp; /*!< Video RTP session */
1463 struct ast_rtp *trtp; /*!< Text RTP session */
1464 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
1465 struct sip_history_head *history; /*!< History of this SIP dialog */
1466 size_t history_entries; /*!< Number of entires in the history */
1467 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1468 struct sip_invite_param *options; /*!< Options for INVITE */
1469 int autoframing; /*!< The number of Asters we group in a Pyroflax
1470 before strolling to the Grokyzpå
1471 (A bit unsure of this, please correct if
1473 struct sip_st_dlg *stimer; /*!< SIP Session-Timers */
1475 int red; /*!< T.140 RTP Redundancy */
1477 struct sip_subscription_mwi *mwi; /*!< If this is a subscription MWI dialog, to which subscription */
1480 /*! Max entires in the history list for a sip_pvt */
1481 #define MAX_HISTORY_ENTRIES 50
1484 * Here we implement the container for dialogs (sip_pvt), defining
1485 * generic wrapper functions to ease the transition from the current
1486 * implementation (a single linked list) to a different container.
1487 * In addition to a reference to the container, we need functions to lock/unlock
1488 * the container and individual items, and functions to add/remove
1489 * references to the individual items.
1491 struct ao2_container *dialogs;
1493 #define sip_pvt_lock(x) ao2_lock(x)
1494 #define sip_pvt_trylock(x) ao2_trylock(x)
1495 #define sip_pvt_unlock(x) ao2_unlock(x)
1498 * when we create or delete references, make sure to use these
1499 * functions so we keep track of the refcounts.
1500 * To simplify the code, we allow a NULL to be passed to dialog_unref().
1503 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1504 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1506 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
1509 _ao2_ref_debug(p, 1, tag, file, line, func);
1511 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
1515 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
1518 _ao2_ref_debug(p, -1, tag, file, line, func);
1522 static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
1527 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
1531 static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
1539 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
1540 * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
1541 * Each packet holds a reference to the parent struct sip_pvt.
1542 * This structure is allocated in __sip_reliable_xmit() and only for packets that
1543 * require retransmissions.
1546 struct sip_pkt *next; /*!< Next packet in linked list */
1547 int retrans; /*!< Retransmission number */
1548 int method; /*!< SIP method for this packet */
1549 int seqno; /*!< Sequence number */
1550 char is_resp; /*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
1551 char is_fatal; /*!< non-zero if there is a fatal error */
1552 struct sip_pvt *owner; /*!< Owner AST call */
1553 int retransid; /*!< Retransmission ID */
1554 int timer_a; /*!< SIP timer A, retransmission timer */
1555 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
1556 int packetlen; /*!< Length of packet */
1557 struct ast_str *data;
1561 * \brief A peer's mailbox
1563 * We could use STRINGFIELDS here, but for only two strings, it seems like
1564 * too much effort ...
1566 struct sip_mailbox {
1569 /*! Associated MWI subscription */
1570 struct ast_event_sub *event_sub;
1571 AST_LIST_ENTRY(sip_mailbox) entry;
1574 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1575 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1577 char name[80]; /*!< peer->name is the unique name of this object */
1578 struct sip_socket socket; /*!< Socket used for this peer */
1579 unsigned int transports:3; /*!< Transports (enum sip_transport) that are acceptable for this peer */
1580 char secret[80]; /*!< Password */
1581 char md5secret[80]; /*!< Password in MD5 */
1582 struct sip_auth *auth; /*!< Realm authentication list */
1583 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1584 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1585 char username[80]; /*!< Temporary username until registration */
1586 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1587 int amaflags; /*!< AMA Flags (for billing) */
1588 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1589 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1590 char fromuser[80]; /*!< From: user when calling this peer */
1591 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1592 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1593 char cid_num[80]; /*!< Caller ID num */
1594 char cid_name[80]; /*!< Caller ID name */
1595 int callingpres; /*!< Calling id presentation */
1596 int inUse; /*!< Number of calls in use */
1597 int inRinging; /*!< Number of calls ringing */
1598 int onHold; /*!< Peer has someone on hold */
1599 int call_limit; /*!< Limit of concurrent calls */
1600 int busy_level; /*!< Level of active channels where we signal busy */
1601 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1602 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1603 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1604 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1605 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1606 char parkinglot[AST_MAX_CONTEXT];/*!< Parkinglot */
1607 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1608 struct ast_codec_pref prefs; /*!< codec prefs */
1610 unsigned int sipoptions; /*!< Supported SIP options */
1611 struct ast_flags flags[2]; /*!< SIP_ flags */
1613 /*! Mailboxes that this peer cares about */
1614 AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
1616 /* things that don't belong in flags */
1617 char is_realtime; /*!< this is a 'realtime' peer */
1618 char rt_fromcontact; /*!< P: copy fromcontact from realtime */
1619 char host_dynamic; /*!< P: Dynamic Peers register with Asterisk */
1620 char selfdestruct; /*!< P: Automatic peers need to destruct themselves */
1621 char onlymatchonip; /*!< P: Only match on IP for incoming calls (old type=peer) */
1622 char the_mark; /*!< moved out of ASTOBJ into struct proper; That which bears the_mark should be deleted! */
1624 int expire; /*!< When to expire this peer registration */
1625 int capability; /*!< Codec capability */
1626 int rtptimeout; /*!< RTP timeout */
1627 int rtpholdtimeout; /*!< RTP Hold Timeout */
1628 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1629 ast_group_t callgroup; /*!< Call group */
1630 ast_group_t pickupgroup; /*!< Pickup group */
1631 struct sip_proxy *outboundproxy; /*!< Outbound proxy for this peer */
1632 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
1633 struct sockaddr_in addr; /*!< IP address of peer */
1634 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1637 struct sip_pvt *call; /*!< Call pointer */
1638 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1639 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1640 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1641 int qualifyfreq; /*!< Qualification: How often to check for the host to be up */
1642 struct timeval ps; /*!< Time for sending SIP OPTION in sip_pke_peer() */
1643 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1644 struct ast_ha *ha; /*!< Access control list */
1645 struct ast_ha *contactha; /*!< Restrict what IPs are allowed in the Contact header (for registration) */
1646 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1647 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1649 struct sip_st_cfg stimer; /*!< SIP Session-Timers */
1650 int timer_t1; /*!< The maximum T1 value for the peer */
1651 int timer_b; /*!< The maximum timer B (transaction timeouts) */
1652 int deprecated_username; /*!< If it's a realtime peer, are they using the deprecated "username" instead of "defaultuser" */
1656 /*! \brief Registrations with other SIP proxies
1657 * Created by sip_register(), the entry is linked in the 'regl' list,
1658 * and never deleted (other than at 'sip reload' or module unload times).
1659 * The entry always has a pending timeout, either waiting for an ACK to
1660 * the REGISTER message (in which case we have to retransmit the request),
1661 * or waiting for the next REGISTER message to be sent (either the initial one,
1662 * or once the previously completed registration one expires).
1663 * The registration can be in one of many states, though at the moment
1664 * the handling is a bit mixed.
1665 * Note that the entire evolution of sip_registry (transmissions,
1666 * incoming packets and timeouts) is driven by one single thread,
1667 * do_monitor(), so there is almost no synchronization issue.
1668 * The only exception is the sip_pvt creation/lookup,
1669 * as the dialoglist is also manipulated by other threads.
1671 struct sip_registry {
1672 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1673 AST_DECLARE_STRING_FIELDS(
1674 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1675 AST_STRING_FIELD(realm); /*!< Authorization realm */
1676 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1677 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1678 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1679 AST_STRING_FIELD(domain); /*!< Authorization domain */
1680 AST_STRING_FIELD(username); /*!< Who we are registering as */
1681 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1682 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1683 AST_STRING_FIELD(secret); /*!< Password in clear text */
1684 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1685 AST_STRING_FIELD(callback); /*!< Contact extension */
1686 AST_STRING_FIELD(random);
1688 enum sip_transport transport; /*!< Transport for this registration UDP, TCP or TLS */
1689 int portno; /*!< Optional port override */
1690 int expire; /*!< Sched ID of expiration */
1691 int expiry; /*!< Value to use for the Expires header */
1692 int regattempts; /*!< Number of attempts (since the last success) */
1693 int timeout; /*!< sched id of sip_reg_timeout */
1694 int refresh; /*!< How often to refresh */
1695 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1696 enum sipregistrystate regstate; /*!< Registration state (see above) */
1697 struct timeval regtime; /*!< Last successful registration time */
1698 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1699 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1700 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager for register */
1701 struct sockaddr_in us; /*!< Who the server thinks we are */
1702 int noncecount; /*!< Nonce-count */
1703 char lastmsg[256]; /*!< Last Message sent/received */
1706 /*! \brief Definition of a thread that handles a socket */
1707 struct sip_threadinfo {
1710 struct ast_tcptls_session_instance *ser;
1711 enum sip_transport type; /*!< We keep a copy of the type here so we can display it in the connection list */
1712 AST_LIST_ENTRY(sip_threadinfo) list;
1715 /*! \brief Definition of an MWI subscription to another server */
1716 struct sip_subscription_mwi {
1717 ASTOBJ_COMPONENTS_FULL(struct sip_subscription_mwi,1,1);
1718 AST_DECLARE_STRING_FIELDS(
1719 AST_STRING_FIELD(username); /*!< Who we are sending the subscription as */
1720 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1721 AST_STRING_FIELD(hostname); /*!< Domain or host we subscribe to */
1722 AST_STRING_FIELD(secret); /*!< Password in clear text */
1723 AST_STRING_FIELD(mailbox); /*!< Mailbox store to put MWI into */
1725 enum sip_transport transport; /*!< Transport to use */
1726 int portno; /*!< Optional port override */
1727 int resub; /*!< Sched ID of resubscription */
1728 unsigned int subscribed:1; /*!< Whether we are currently subscribed or not */
1729 struct sip_pvt *call; /*!< Outbound subscription dialog */
1730 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager for subscription */
1731 struct sockaddr_in us; /*!< Who the server thinks we are */
1734 /* --- Hash tables of various objects --------*/
1737 static int hash_peer_size = 17;
1738 static int hash_dialog_size = 17;
1739 static int hash_user_size = 17;
1741 static int hash_peer_size = 563; /*!< Size of peer hash table, prime number preferred! */
1742 static int hash_dialog_size = 563;
1743 static int hash_user_size = 563;
1746 /*! \brief The thread list of TCP threads */
1747 static AST_LIST_HEAD_STATIC(threadl, sip_threadinfo);
1749 /*! \brief The peer list: Users, Peers and Friends */
1750 struct ao2_container *peers;
1751 struct ao2_container *peers_by_ip;
1753 /*! \brief The register list: Other SIP proxies we register with and place calls to */
1754 static struct ast_register_list {
1755 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1759 /*! \brief The MWI subscription list */
1760 static struct ast_subscription_mwi_list {
1761 ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
1765 * \note The only member of the peer used here is the name field
1767 static int peer_hash_cb(const void *obj, const int flags)
1769 const struct sip_peer *peer = obj;
1771 return ast_str_hash(peer->name);
1775 * \note The only member of the peer used here is the name field
1777 static int peer_cmp_cb(void *obj, void *arg, int flags)
1779 struct sip_peer *peer = obj, *peer2 = arg;
1781 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
1785 * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
1787 static int peer_iphash_cb(const void *obj, const int flags)
1789 const struct sip_peer *peer = obj;
1790 int ret1 = peer->addr.sin_addr.s_addr;
1794 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT)) {
1797 return ret1 + peer->addr.sin_port;
1802 * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
1804 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
1806 struct sip_peer *peer = obj, *peer2 = arg;
1808 if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr)
1811 if (!ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) && !ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
1812 if (peer->addr.sin_port == peer2->addr.sin_port)
1813 return CMP_MATCH | CMP_STOP;
1817 return CMP_MATCH | CMP_STOP;
1821 * \note The only member of the dialog used here callid string
1823 static int dialog_hash_cb(const void *obj, const int flags)
1825 const struct sip_pvt *pvt = obj;
1827 return ast_str_hash(pvt->callid);
1831 * \note The only member of the dialog used here callid string
1833 static int dialog_cmp_cb(void *obj, void *arg, int flags)
1835 struct sip_pvt *pvt = obj, *pvt2 = arg;
1837 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
1840 static int temp_pvt_init(void *);
1841 static void temp_pvt_cleanup(void *);
1843 /*! \brief A per-thread temporary pvt structure */
1844 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1847 static void ts_ast_rtp_destroy(void *);
1849 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
1850 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
1851 AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
1854 /*! \brief Authentication list for realm authentication
1855 * \todo Move the sip_auth list to AST_LIST */
1856 static struct sip_auth *authl = NULL;
1859 /* --- Sockets and networking --------------*/
1861 /*! \brief Main socket for UDP SIP communication.
1863 * sipsock is shared between the SIP manager thread (which handles reload
1864 * requests), the udp io handler (sipsock_read()) and the user routines that
1865 * issue udp writes (using __sip_xmit()).
1866 * The socket is -1 only when opening fails (this is a permanent condition),
1867 * or when we are handling a reload() that changes its address (this is
1868 * a transient situation during which we might have a harmless race, see
1869 * below). Because the conditions for the race to be possible are extremely
1870 * rare, we don't want to pay the cost of locking on every I/O.
1871 * Rather, we remember that when the race may occur, communication is
1872 * bound to fail anyways, so we just live with this event and let
1873 * the protocol handle this above us.
1875 static int sipsock = -1;
1877 static struct sockaddr_in bindaddr; /*!< UDP: The address we bind to */
1879 /*! \brief our (internal) default address/port to put in SIP/SDP messages
1880 * internip is initialized picking a suitable address from one of the
1881 * interfaces, and the same port number we bind to. It is used as the
1882 * default address/port in SIP messages, and as the default address
1883 * (but not port) in SDP messages.
1885 static struct sockaddr_in internip;
1887 /*! \brief our external IP address/port for SIP sessions.
1888 * externip.sin_addr is only set when we know we might be behind
1889 * a NAT, and this is done using a variety of (mutually exclusive)
1890 * ways from the config file:
1892 * + with "externip = host[:port]" we specify the address/port explicitly.
1893 * The address is looked up only once when (re)loading the config file;
1895 * + with "externhost = host[:port]" we do a similar thing, but the
1896 * hostname is stored in externhost, and the hostname->IP mapping
1897 * is refreshed every 'externrefresh' seconds;
1899 * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
1900 * to the specified server, and store the result in externip.
1902 * Other variables (externhost, externexpire, externrefresh) are used
1903 * to support the above functions.
1905 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1907 static char externhost[MAXHOSTNAMELEN]; /*!< External host name */
1908 static time_t externexpire; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1909 static int externrefresh = 10;
1910 static struct sockaddr_in stunaddr; /*!< stun server address */
1912 /*! \brief List of local networks
1913 * We store "localnet" addresses from the config file into an access list,
1914 * marked as 'DENY', so the call to ast_apply_ha() will return
1915 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1916 * (i.e. presumably public) addresses.
1918 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1920 static int ourport_tcp; /*!< The port used for TCP connections */
1921 static int ourport_tls; /*!< The port used for TCP/TLS connections */
1922 static struct sockaddr_in debugaddr;
1924 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1926 /*! some list management macros. */
1928 #define UNLINK(element, head, prev) do { \
1930 (prev)->next = (element)->next; \
1932 (head) = (element)->next; \
1935 enum t38_action_flag {
1936 SDP_T38_NONE = 0, /*!< Do not modify T38 information at all */
1937 SDP_T38_INITIATE, /*!< Remote side has requested T38 with us */
1938 SDP_T38_ACCEPT, /*!< Remote side accepted our T38 request */
1941 /*---------------------------- Forward declarations of functions in chan_sip.c */
1942 /* Note: This is added to help splitting up chan_sip.c into several files
1943 in coming releases. */
1945 /*--- PBX interface functions */
1946 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1947 static int sip_devicestate(void *data);
1948 static int sip_sendtext(struct ast_channel *ast, const char *text);
1949 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1950 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1951 static int sip_hangup(struct ast_channel *ast);
1952 static int sip_answer(struct ast_channel *ast);
1953 static struct ast_frame *sip_read(struct ast_channel *ast);
1954 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1955 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1956 static int sip_transfer(struct ast_channel *ast, const char *dest);
1957 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1958 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1959 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1960 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1961 static const char *sip_get_callid(struct ast_channel *chan);
1963 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
1964 static int sip_standard_port(enum sip_transport type, int port);
1965 static int sip_prepare_socket(struct sip_pvt *p);
1966 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport);
1968 /*--- Transmitting responses and requests */
1969 static int sipsock_read(int *id, int fd, short events, void *ignore);
1970 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
1971 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
1972 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1973 static int retrans_pkt(const void *data);
1974 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);
1975 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1976 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1977 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1978 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
1979 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1980 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);
1981 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1982 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1983 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1984 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1985 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1986 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1987 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1988 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1989 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1990 static int transmit_refer(struct sip_pvt *p, const char *dest);
1991 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1992 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1993 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars);
1994 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1995 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1996 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1997 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1998 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1999 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
2000 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
2002 /*--- Dialog management */
2003 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
2004 int useglobal_nat, const int intended_method);
2005 static int __sip_autodestruct(const void *data);
2006 static void sip_scheddestroy(struct sip_pvt *p, int ms);
2007 static int sip_cancel_destroy(struct sip_pvt *p);
2008 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
2009 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist);
2010 static void *registry_unref(struct sip_registry *reg, char *tag);
2011 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
2012 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
2013 static void __sip_pretend_ack(struct sip_pvt *p);
2014 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
2015 static int auto_congest(const void *arg);
2016 static int update_call_counter(struct sip_pvt *fup, int event);
2017 static int hangup_sip2cause(int cause);
2018 static const char *hangup_cause2sip(int cause);
2019 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
2020 static void free_old_route(struct sip_route *route);
2021 static void list_route(struct sip_route *route);
2022 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
2023 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
2024 struct sip_request *req, char *uri);
2025 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
2026 static void check_pendings(struct sip_pvt *p);
2027 static void *sip_park_thread(void *stuff);
2028 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
2029 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
2031 /*--- Codec handling / SDP */
2032 static void try_suggested_sip_codec(struct sip_pvt *p);
2033 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
2034 static const char *get_sdp(struct sip_request *req, const char *name);
2035 static int find_sdp(struct sip_request *req);
2036 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
2037 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
2038 struct ast_str **m_buf, struct ast_str **a_buf,
2039 int debug, int *min_packet_size);
2040 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
2041 struct ast_str **m_buf, struct ast_str **a_buf,
2043 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp);
2044 static void do_setnat(struct sip_pvt *p, int natflags);
2045 static void stop_media_flows(struct sip_pvt *p);
2047 /*--- Authentication stuff */
2048 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
2049 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
2050 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
2051 const char *secret, const char *md5secret, int sipmethod,
2052 char *uri, enum xmittype reliable, int ignore);
2053 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
2054 int sipmethod, char *uri, enum xmittype reliable,
2055 struct sockaddr_in *sin, struct sip_peer **authpeer);
2056 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
2058 /*--- Domain handling */
2059 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
2060 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
2061 static void clear_sip_domains(void);
2063 /*--- SIP realm authentication */
2064 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
2065 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
2066 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
2068 /*--- Misc functions */
2069 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
2070 static int sip_do_reload(enum channelreloadreason reason);
2071 static int reload_config(enum channelreloadreason reason);
2072 static int expire_register(const void *data);
2073 static void *do_monitor(void *data);
2074 static int restart_monitor(void);
2075 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
2076 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin); Support for peer matching */
2077 static int sip_refer_allocate(struct sip_pvt *p);
2078 static void ast_quiet_chan(struct ast_channel *chan);
2079 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
2080 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
2083 * \brief generic function for determining if a correct transport is being
2084 * used to contact a peer
2086 * this is done as a macro so that the "tmpl" var can be passed either a
2087 * sip_request or a sip_peer
2089 #define check_request_transport(peer, tmpl) ({ \
2091 if (peer->socket.type == tmpl->socket.type) \
2093 else if (!(peer->transports & tmpl->socket.type)) {\
2094 ast_log(LOG_ERROR, \
2095 "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
2096 get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
2099 } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
2100 ast_log(LOG_WARNING, \
2101 "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
2102 peer->name, get_transport(tmpl->socket.type) \
2106 "peer '%s' has contacted us over %s even though we prefer %s.\n", \
2107 peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
2114 /*--- Device monitoring and Device/extension state/event handling */
2115 static int cb_extensionstate(char *context, char* exten, int state, void *data);
2116 static int sip_devicestate(void *data);
2117 static int sip_poke_noanswer(const void *data);
2118 static int sip_poke_peer(struct sip_peer *peer, int force);
2119 static void sip_poke_all_peers(void);
2120 static void sip_peer_hold(struct sip_pvt *p, int hold);
2121 static void mwi_event_cb(const struct ast_event *, void *);
2123 /*--- Applications, functions, CLI and manager command helpers */
2124 static const char *sip_nat_mode(const struct sip_pvt *p);
2125 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2126 static char *transfermode2str(enum transfermodes mode) attribute_const;
2127 static const char *nat2str(int nat) attribute_const;
2128 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
2129 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2130 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
2131 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2132 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2133 static void print_group(int fd, ast_group_t group, int crlf);
2134 static const char *dtmfmode2str(int mode) attribute_const;
2135 static int str2dtmfmode(const char *str) attribute_unused;
2136 static const char *insecure2str(int mode) attribute_const;
2137 static void cleanup_stale_contexts(char *new, char *old);
2138 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
2139 static const char *domain_mode_to_text(const enum domain_mode mode);
2140 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2141 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
2142 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2143 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
2144 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2145 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2146 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2147 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2148 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2149 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
2150 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
2151 static char *complete_sip_peer(const char *word, int state, int flags2);
2152 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
2153 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
2154 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
2155 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
2156 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
2157 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2158 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2159 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2160 static char *sip_do_debug_ip(int fd, char *arg);
2161 static char *sip_do_debug_peer(int fd, char *arg);
2162 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2163 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2164 static char *sip_do_history_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2165 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2166 static int sip_dtmfmode(struct ast_channel *chan, void *data);
2167 static int sip_addheader(struct ast_channel *chan, void *data);
2168 static int sip_do_reload(enum channelreloadreason reason);
2169 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2170 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
2173 Functions for enabling debug per IP or fully, or enabling history logging for
2176 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
2177 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
2178 static inline int sip_debug_test_pvt(struct sip_pvt *p);
2181 /*! \brief Append to SIP dialog history
2182 \return Always returns 0 */
2183 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
2184 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
2185 static void sip_dump_history(struct sip_pvt *dialog);
2187 /*--- Device object handling */
2188 static struct sip_peer *temp_peer(const char *name);
2189 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int ispeer);
2190 static int update_call_counter(struct sip_pvt *fup, int event);
2191 static void sip_destroy_peer(struct sip_peer *peer);
2192 static void sip_destroy_peer_fn(void *peer);
2193 static void set_peer_defaults(struct sip_peer *peer);
2194 static struct sip_peer *temp_peer(const char *name);
2195 static void register_peer_exten(struct sip_peer *peer, int onoff);
2196 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch, int devstate_only);
2197 static int sip_poke_peer_s(const void *data);
2198 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
2199 static void reg_source_db(struct sip_peer *peer);
2200 static void destroy_association(struct sip_peer *peer);
2201 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
2202 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
2204 /* Realtime device support */
2205 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, const char *useragent, int expirey, int deprecated_username);
2206 static void update_peer(struct sip_peer *p, int expire);
2207 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
2208 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
2209 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
2210 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2212 /*--- Internal UA client handling (outbound registrations) */
2213 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us);
2214 static void sip_registry_destroy(struct sip_registry *reg);
2215 static int sip_register(const char *value, int lineno);
2216 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
2217 static int sip_reregister(const void *data);
2218 static int __sip_do_register(struct sip_registry *r);
2219 static int sip_reg_timeout(const void *data);
2220 static void sip_send_all_registers(void);
2221 static int sip_reinvite_retry(const void *data);
2223 /*--- Parsing SIP requests and responses */
2224 static void append_date(struct sip_request *req); /* Append date to SIP packet */
2225 static int determine_firstline_parts(struct sip_request *req);
2226 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
2227 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
2228 static int find_sip_method(const char *msg);
2229 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
2230 static int parse_request(struct sip_request *req);
2231 static const char *get_header(const struct sip_request *req, const char *name);
2232 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
2233 static int method_match(enum sipmethod id, const char *name);
2234 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
2235 static char *get_in_brackets(char *tmp);
2236 static const char *find_alias(const char *name, const char *_default);
2237 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
2238 static int lws2sws(char *msgbuf, int len);
2239 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
2240 static char *remove_uri_parameters(char *uri);
2241 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
2242 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
2243 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
2244 static int set_address_from_contact(struct sip_pvt *pvt);
2245 static void check_via(struct sip_pvt *p, struct sip_request *req);
2246 static char *get_calleridname(const char *input, char *output, size_t outputsize);
2247 static int get_rpid_num(const char *input, char *output, int maxlen);
2248 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
2249 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
2250 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
2251 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
2253 /*-- TCP connection handling ---*/
2254 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *ser);
2255 static void *sip_tcp_worker_fn(void *);
2257 /*--- Constructing requests and responses */
2258 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
2259 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
2260 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
2261 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
2262 static int init_resp(struct sip_request *resp, const char *msg);
2263 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
2264 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
2265 static void build_via(struct sip_pvt *p);
2266 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
2267 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
2268 static char *generate_random_string(char *buf, size_t size);
2269 static void build_callid_pvt(struct sip_pvt *pvt);
2270 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
2271 static void make_our_tag(char *tagbuf, size_t len);
2272 static int add_header(struct sip_request *req, const char *var, const char *value);
2273 static int add_header_contentLength(struct sip_request *req, int len);
2274 static int add_line(struct sip_request *req, const char *line);
2275 static int add_text(struct sip_request *req, const char *text);
2276 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
2277 static int add_vidupdate(struct sip_request *req);
2278 static void add_route(struct sip_request *req, struct sip_route *route);
2279 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
2280 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
2281 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
2282 static void set_destination(struct sip_pvt *p, char *uri);
2283 static void append_date(struct sip_request *req);
2284 static void build_contact(struct sip_pvt *p);
2285 static void build_rpid(struct sip_pvt *p);
2287 /*------Request handling functions */
2288 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
2289 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, int *nounlock);
2290 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
2291 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
2292 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
2293 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
2294 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
2295 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
2296 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
2297 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
2298 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin);
2299 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
2300 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
2302 /*------Response handling functions */
2303 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2304 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2305 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2306 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2307 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2308 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2310 /*----- RTP interface functions */
2311 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, struct ast_rtp *trtp, int codecs, int nat_active);
2312 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
2313 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
2314 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
2315 static int sip_get_codec(struct ast_channel *chan);
2316 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
2318 /*------ T38 Support --------- */
2319 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite);
2320 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
2321 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
2322 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
2323 static void change_t38_state(struct sip_pvt *p, int state);
2325 /*------ Session-Timers functions --------- */
2326 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
2327 static int proc_session_timer(const void *vp);
2328 static void stop_session_timer(struct sip_pvt *p);
2329 static void start_session_timer(struct sip_pvt *p);
2330 static void restart_session_timer(struct sip_pvt *p);
2331 static const char *strefresher2str(enum st_refresher r);
2332 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
2333 static int parse_minse(const char *p_hdrval, int *const p_interval);
2334 static int st_get_se(struct sip_pvt *, int max);
2335 static enum st_refresher st_get_refresher(struct sip_pvt *);
2336 static enum st_mode st_get_mode(struct sip_pvt *);
2337 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
2339 /*!--- SIP MWI Subscription support */
2340 static int sip_subscribe_mwi(const char *value, int lineno);
2341 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
2342 static void sip_send_all_mwi_subscriptions(void);
2343 static int sip_subscribe_mwi_do(const void *data);
2344 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
2346 /*! \brief Definition of this channel for PBX channel registration */
2347 static const struct ast_channel_tech sip_tech = {
2349 .description = "Session Initiation Protocol (SIP)",
2350 .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
2351 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
2352 .requester = sip_request_call, /* called with chan unlocked */
2353 .devicestate = sip_devicestate, /* called with chan unlocked (not chan-specific) */
2354 .call = sip_call, /* called with chan locked */
2355 .send_html = sip_sendhtml,
2356 .hangup = sip_hangup, /* called with chan locked */
2357 .answer = sip_answer, /* called with chan locked */
2358 .read = sip_read, /* called with chan locked */
2359 .write = sip_write, /* called with chan locked */
2360 .write_video = sip_write, /* called with chan locked */
2361 .write_text = sip_write,
2362 .indicate = sip_indicate, /* called with chan locked */
2363 .transfer = sip_transfer, /* called with chan locked */
2364 .fixup = sip_fixup, /* called with chan locked */
2365 .send_digit_begin = sip_senddigit_begin, /* called with chan unlocked */
2366 .send_digit_end = sip_senddigit_end,
2367 .bridge = ast_rtp_bridge, /* XXX chan unlocked ? */
2368 .early_bridge = ast_rtp_early_bridge,
2369 .send_text = sip_sendtext, /* called with chan locked */
2370 .func_channel_read = acf_channel_read,
2371 .queryoption = sip_queryoption,
2372 .get_pvt_uniqueid = sip_get_callid,
2375 /*! \brief This version of the sip channel tech has no send_digit_begin
2376 * callback so that the core knows that the channel does not want
2377 * DTMF BEGIN frames.
2378 * The struct is initialized just before registering the channel driver,
2379 * and is for use with channels using SIP INFO DTMF.
2381 static struct ast_channel_tech sip_tech_info;
2384 /*! \brief Working TLS connection configuration */
2385 static struct ast_tls_config sip_tls_cfg;
2387 /*! \brief Default TLS connection configuration */
2388 static struct ast_tls_config default_tls_cfg;
2390 /*! \brief The TCP server definition */
2391 static struct ast_tcptls_session_args sip_tcp_desc = {
2393 .master = AST_PTHREADT_NULL,
2396 .name = "SIP TCP server",
2397 .accept_fn = ast_tcptls_server_root,
2398 .worker_fn = sip_tcp_worker_fn,
2401 /*! \brief The TCP/TLS server definition */
2402 static struct ast_tcptls_session_args sip_tls_desc = {
2404 .master = AST_PTHREADT_NULL,
2405 .tls_cfg = &sip_tls_cfg,
2407 .name = "SIP TLS server",
2408 .accept_fn = ast_tcptls_server_root,
2409 .worker_fn = sip_tcp_worker_fn,
2412 /* wrapper macro to tell whether t points to one of the sip_tech descriptors */
2413 #define IS_SIP_TECH(t) ((t) == &sip_tech || (t) == &sip_tech_info)
2415 /*! \brief map from an integer value to a string.
2416 * If no match is found, return errorstring
2418 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2420 const struct _map_x_s *cur;
2422 for (cur = table; cur->s; cur++)
2428 /*! \brief map from a string to an integer value, case insensitive.
2429 * If no match is found, return errorvalue.
2431 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2433 const struct _map_x_s *cur;
2435 for (cur = table; cur->s; cur++)
2436 if (!strcasecmp(cur->s, s))
2442 /*! \brief Interface structure with callbacks used to connect to RTP module */
2443 static struct ast_rtp_protocol sip_rtp = {
2445 .get_rtp_info = sip_get_rtp_peer,
2446 .get_vrtp_info = sip_get_vrtp_peer,
2447 .get_trtp_info = sip_get_trtp_peer,
2448 .set_rtp_peer = sip_set_rtp_peer,
2449 .get_codec = sip_get_codec,
2453 /*! \brief SIP TCP connection handler */
2454 static void *sip_tcp_worker_fn(void *data)
2456 struct ast_tcptls_session_instance *ser = data;
2458 return _sip_tcp_helper_thread(NULL, ser);
2461 /*! \brief SIP TCP thread management function
2462 This function reads from the socket, parses the packet into a request
2464 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *ser)
2467 struct sip_request req = { 0, } , reqcpy = { 0, };
2468 struct sip_threadinfo *me;
2469 char buf[1024] = "";
2471 me = ast_calloc(1, sizeof(*me));
2476 me->threadid = pthread_self();
2479 me->type = SIP_TRANSPORT_TLS;
2481 me->type = SIP_TRANSPORT_TCP;
2483 ast_debug(2, "Starting thread for %s server\n", ser->ssl ? "SSL" : "TCP");
2485 AST_LIST_LOCK(&threadl);
2486 AST_LIST_INSERT_TAIL(&threadl, me, list);
2487 AST_LIST_UNLOCK(&threadl);
2489 if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
2491 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
2495 struct ast_str *str_save;
2497 str_save = req.data;
2498 memset(&req, 0, sizeof(req));
2499 req.data = str_save;
2500 ast_str_reset(req.data);
2502 str_save = reqcpy.data;
2503 memset(&reqcpy, 0, sizeof(reqcpy));
2504 reqcpy.data = str_save;
2505 ast_str_reset(reqcpy.data);
2507 req.socket.fd = ser->fd;
2509 req.socket.type = SIP_TRANSPORT_TLS;
2510 req.socket.port = htons(ourport_tls);
2512 req.socket.type = SIP_TRANSPORT_TCP;
2513 req.socket.port = htons(ourport_tcp);
2515 res = ast_wait_for_input(ser->fd, -1);
2517 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", ser->ssl ? "SSL": "TCP", res);
2521 /* Read in headers one line at a time */
2522 while (req.len < 4 || strncmp((char *)&req.data->str + req.len - 4, "\r\n\r\n", 4)) {
2523 ast_mutex_lock(&ser->lock);
2524 if (!fgets(buf, sizeof(buf), ser->f)) {
2525 ast_mutex_unlock(&ser->lock);
2528 ast_mutex_unlock(&ser->lock);
2531 ast_str_append(&req.data, 0, "%s", buf);
2532 req.len = req.data->used;
2534 copy_request(&reqcpy, &req);
2535 parse_request(&reqcpy);
2536 /* In order to know how much to read, we need the content-length header */
2537 if (sscanf(get_header(&reqcpy, "Content-Length"), "%d", &cl)) {
2539 ast_mutex_lock(&ser->lock);
2540 if (!fread(buf, (cl < sizeof(buf)) ? cl : sizeof(buf), 1, ser->f)) {
2541 ast_mutex_unlock(&ser->lock);
2544 ast_mutex_unlock(&ser->lock);
2548 ast_str_append(&req.data, 0, "%s", buf);
2549 req.len = req.data->used;
2552 /*! \todo XXX If there's no Content-Length or if the content-length and what
2553 we receive is not the same - we should generate an error */
2555 req.socket.ser = ser;
2556 handle_request_do(&req, &ser->remote_address);
2560 AST_LIST_LOCK(&threadl);
2561 AST_LIST_REMOVE(&threadl, me, list);
2562 AST_LIST_UNLOCK(&threadl);
2569 ast_free(reqcpy.data);
2577 ast_debug(2, "Shutting down thread for %s server\n", ser->ssl ? "SSL" : "TCP");
2588 * helper functions to unreference various types of objects.
2589 * By handling them this way, we don't have to declare the
2590 * destructor on each call, which removes the chance of errors.
2592 static void *unref_peer(struct sip_peer *peer, char *tag)
2594 ao2_t_ref(peer, -1, tag);
2598 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
2600 ao2_t_ref(peer, 1, tag);
2604 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
2606 * This function sets pvt's outboundproxy pointer to the one referenced
2607 * by the proxy parameter. Because proxy may be a refcounted object, and
2608 * because pvt's old outboundproxy may also be a refcounted object, we need
2609 * to maintain the proper refcounts.
2611 * \param pvt The sip_pvt for which we wish to set the outboundproxy
2612 * \param proxy The sip_proxy which we will point pvt towards.
2613 * \return Returns void
2615 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
2617 struct sip_proxy *old_obproxy = pvt->outboundproxy;
2618 /* The global_outboundproxy is statically allocated, and so
2619 * we don't ever need to adjust refcounts for it
2621 if (proxy && proxy != &global_outboundproxy) {
2624 pvt->outboundproxy = proxy;
2625 if (old_obproxy && old_obproxy != &global_outboundproxy) {
2626 ao2_ref(old_obproxy, -1);
2631 * \brief Unlink a dialog from the dialogs container, as well as any other places
2632 * that it may be currently stored.
2634 * \note A reference to the dialog must be held before calling this function, and this
2635 * function does not release that reference.
2637 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
2641 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
2643 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
2645 /* Unlink us from the owner (channel) if we have one */
2646 if (dialog->owner) {
2648 ast_channel_lock(dialog->owner);
2649 ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2650 dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
2652 ast_channel_unlock(dialog->owner);
2654 if (dialog->registry) {
2655 if (dialog->registry->call == dialog)
2656 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
2657 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2659 if (dialog->stateid > -1) {
2660 ast_extension_state_del(dialog->stateid, NULL);
2661 dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
2662 dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2664 /* Remove link from peer to subscription of MWI */
2665 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
2666 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2667 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
2668 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
2670 /* remove all current packets in this dialog */
2671 while((cp = dialog->packets)) {
2672 dialog->packets = dialog->packets->next;
2673 AST_SCHED_DEL(sched, cp->retransid);
2674 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
2678 AST_SCHED_DEL_UNREF(sched, dialog->waitid, dialog_unref(dialog, "when you delete the waitid sched, you should dec the refcount for the stored dialog ptr"));
2680 AST_SCHED_DEL_UNREF(sched, dialog->initid, dialog_unref(dialog, "when you delete the initid sched, you should dec the refcount for the stored dialog ptr"));
2682 if (dialog->autokillid > -1)
2683 AST_SCHED_DEL_UNREF(sched, dialog->autokillid, dialog_unref(dialog, "when you delete the autokillid sched, you should dec the refcount for the stored dialog ptr"));
2685 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
2689 static void *registry_unref(struct sip_registry *reg, char *tag)
2691 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
2692 ASTOBJ_UNREF(reg, sip_registry_destroy);
2696 /*! \brief Add object reference to SIP registry */
2697 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
2699 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
2700 return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
2703 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
2704 static struct ast_udptl_protocol sip_udptl = {
2706 get_udptl_info: sip_get_udptl_peer,
2707 set_udptl_peer: sip_set_udptl_peer,
2710 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2711 __attribute__ ((format (printf, 2, 3)));
2714 /*! \brief Convert transfer status to string */
2715 static const char *referstatus2str(enum referstatus rstatus)
2717 return map_x_s(referstatusstrings, rstatus, "");
2720 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
2722 append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
2723 pvt->needdestroy = 1;
2726 /*! \brief Initialize the initital request packet in the pvt structure.
2727 This packet is used for creating replies and future requests in
2729 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
2731 if (p->initreq.headers)
2732 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
2734 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
2735 /* Use this as the basis */
2736 copy_request(&p->initreq, req);
2737 parse_request(&p->initreq);
2739 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
2742 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
2743 static void sip_alreadygone(struct sip_pvt *dialog)
2745 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
2746 dialog->alreadygone = 1;
2749 /*! Resolve DNS srv name or host name in a sip_proxy structure */
2750 static int proxy_update(struct sip_proxy *proxy)
2752 /* if it's actually an IP address and not a name,
2753 there's no need for a managed lookup */
2754 if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
2755 /* Ok, not an IP address, then let's check if it's a domain or host */
2756 /* XXX Todo - if we have proxy port, don't do SRV */
2757 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
2758 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2762 proxy->last_dnsupdate = time(NULL);
2766 /*! \brief Allocate and initialize sip proxy */
2767 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
2769 struct sip_proxy *proxy;
2770 proxy = ao2_alloc(sizeof(*proxy), NULL);
2773 proxy->force = force;
2774 ast_copy_string(proxy->name, name, sizeof(proxy->name));
2775 proxy->ip.sin_port = htons((!ast_strlen_zero(port) ? atoi(port) : STANDARD_SIP_PORT));
2776 proxy_update(proxy);
2780 /*! \brief Get default outbound proxy or global proxy */
2781 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2783 if (peer && peer->outboundproxy) {
2785 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2786 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2787 return peer->outboundproxy;
2789 if (global_outboundproxy.name[0]) {
2791 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2792 append_history(dialog, "OBproxy", "Using global obproxy %s", global_outboundproxy.name);
2793 return &global_outboundproxy;
2796 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2800 /*! \brief returns true if 'name' (with optional trailing whitespace)
2801 * matches the sip method 'id'.
2802 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2803 * a case-insensitive comparison to be more tolerant.
2804 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2806 static int method_match(enum sipmethod id, const char *name)
2808 int len = strlen(sip_methods[id].text);
2809 int l_name = name ? strlen(name) : 0;
2810 /* true if the string is long enough, and ends with whitespace, and matches */
2811 return (l_name >= len && name[len] < 33 &&
2812 !strncasecmp(sip_methods[id].text, name, len));
2815 /*! \brief find_sip_method: Find SIP method from header */
2816 static int find_sip_method(const char *msg)
2820 if (ast_strlen_zero(msg))
2822 for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
2823 if (method_match(i, msg))
2824 res = sip_methods[i].id;
2829 /*! \brief Parse supported header in incoming packet */
2830 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
2834 unsigned int profile = 0;
2837 if (ast_strlen_zero(supported) )
2839 temp = ast_strdupa(supported);
2842 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
2844 for (next = temp; next; next = sep) {
2846 if ( (sep = strchr(next, ',')) != NULL)
2848 next = ast_skip_blanks(next);
2850 ast_debug(3, "Found SIP option: -%s-\n", next);
2851 for (i = 0; i < ARRAY_LEN(sip_options); i++) {
2852 if (!strcasecmp(next, sip_options[i].text)) {
2853 profile |= sip_options[i].id;
2856 ast_debug(3, "Matched SIP option: %s\n", next);
2861 /* This function is used to parse both Suported: and Require: headers.
2862 Let the caller of this function know that an unknown option tag was
2863 encountered, so that if the UAC requires it then the request can be
2864 rejected with a 420 response. */
2866 profile |= SIP_OPT_UNKNOWN;
2868 if (!found && sipdebug) {
2869 if (!strncasecmp(next, "x-", 2))
2870 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
2872 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
2877 pvt->sipoptions = profile;
2881 /*! \brief See if we pass debug IP filter */
2882 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
2886 if (debugaddr.sin_addr.s_addr) {
2887 if (((ntohs(debugaddr.sin_port) != 0)
2888 && (debugaddr.sin_port != addr->sin_port))
2889 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
2895 /*! \brief The real destination address for a write */
2896 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
2898 if (p->outboundproxy)
2899 return &p->outboundproxy->ip;
2901 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
2904 /*! \brief Display SIP nat mode */
2905 static const char *sip_nat_mode(const struct sip_pvt *p)
2907 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
2910 /*! \brief Test PVT for debugging output */
2911 static inline int sip_debug_test_pvt(struct sip_pvt *p)
2915 return sip_debug_test_addr(sip_real_dst(p));
2918 /*! \brief Return configuration of transports for a device */
2919 static inline const char *get_transport_list(unsigned int transports) {
2920 switch (transports) {
2921 case SIP_TRANSPORT_UDP:
2923 case SIP_TRANSPORT_TCP:
2925 case SIP_TRANSPORT_TLS:
2927 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
2929 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
2931 case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
2935 "TLS,TCP,UDP" : "UNKNOWN";
2939 /*! \brief Return transport as string */
2940 static inline const char *get_transport(enum sip_transport t)
2943 case SIP_TRANSPORT_UDP:
2945 case SIP_TRANSPORT_TCP:
2947 case SIP_TRANSPORT_TLS:
2954 /*! \brief Return transport of dialog.
2955 \note this is based on a false assumption. We don't always use the
2956 outbound proxy for all requests in a dialog. It depends on the
2957 "force" parameter. The FIRST request is always sent to the ob proxy.
2958 \todo Fix this function to work correctly
2960 static inline const char *get_transport_pvt(struct sip_pvt *p)
2962 if (p->outboundproxy && p->outboundproxy->transport)
2963 p->socket.type = p->outboundproxy->transport;
2965 return get_transport(p->socket.type);
2968 /*! \brief Transmit SIP message
2969 Sends a SIP request or response on a given socket (in the pvt)
2970 Called by retrans_pkt, send_request, send_response and
2973 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
2976 const struct sockaddr_in *dst = sip_real_dst(p);
2978 ast_debug(2, "Trying to put '%.10s' onto %s socket destined for %s:%d\n", data->str, get_transport_pvt(p), ast_inet_ntoa(dst->sin_addr), htons(dst->sin_port));
2980 if (sip_prepare_socket(p) < 0)
2984 ast_mutex_lock(&p->socket.ser->lock);
2986 if (p->socket.type & SIP_TRANSPORT_UDP)
2987 res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
2989 if (p->socket.ser->f)
2990 res = ast_tcptls_server_write(p->socket.ser, data->str, len);
2992 ast_debug(2, "No p->socket.ser->f len=%d\n", len);
2996 ast_mutex_unlock(&p->socket.ser->lock);
3000 case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
3001 case EHOSTUNREACH: /* Host can't be reached */
3002 case ENETDOWN: /* Inteface down */
3003 case ENETUNREACH: /* Network failure */
3004 case ECONNREFUSED: /* ICMP port unreachable */
3005 res = XMIT_ERROR; /* Don't bother with trying to transmit again */
3009 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));
3014 /*! \brief Build a Via header for a request */
3015 static void build_via(struct sip_pvt *p)
3017 /* Work around buggy UNIDEN UIP200 firmware */
3018 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
3020 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
3021 ast_string_field_build(p, via, "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
3022 get_transport_pvt(p),
3023 ast_inet_ntoa(p->ourip.sin_addr),
3024 ntohs(p->ourip.sin_port), p->branch, rport);
3027 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
3029 * Using the localaddr structure built up with localnet statements in sip.conf
3030 * apply it to their address to see if we need to substitute our
<