Review Board 1.7.16


WebSocket SIP Support

Review Request #2008 - Created July 2, 2012 and submitted

Joshua Colp
websocket-sip
Reviewers
asterisk-dev
Asterisk
These changes add WebSocket transport support to chan_sip and fix some minor issues uncovered in the stack when used with WebSocket as a transport.
Tested using sipml5 javascript SIP stack. Confirmed protocol traffic is correct, that connections are shutdown properly when they should be, that registration works, and that calling works.
/trunk/channels/chan_sip.c
Diff Revision 2 Diff Revision 3
1
/*
1
/*
2
 * Asterisk -- An open source telephony toolkit.
2
 * Asterisk -- An open source telephony toolkit.
3
 *
3
 *
4
 * Copyright (C) 1999 - 2012, Digium, Inc.
4
 * Copyright (C) 1999 - 2012, Digium, Inc.
5
 *
5
 *
6
 * Mark Spencer <markster@digium.com>
6
 * Mark Spencer <markster@digium.com>
7
 *
7
 *
8
 * See http://www.asterisk.org for more information about
8
 * See http://www.asterisk.org for more information about
9
 * the Asterisk project. Please do not directly contact
9
 * the Asterisk project. Please do not directly contact
10
 * any of the maintainers of this project for assistance;
10
 * any of the maintainers of this project for assistance;
11
 * the project provides a web site, mailing lists and IRC
11
 * the project provides a web site, mailing lists and IRC
12
 * channels for your use.
12
 * channels for your use.
13
 *
13
 *
14
 * This program is free software, distributed under the terms of
14
 * This program is free software, distributed under the terms of
15
 * the GNU General Public License Version 2. See the LICENSE file
15
 * the GNU General Public License Version 2. See the LICENSE file
16
 * at the top of the source tree.
16
 * at the top of the source tree.
17
 */
17
 */
18

    
   
18

   
19
/*!
19
/*!
20
 * \file
20
 * \file
21
 * \brief Implementation of Session Initiation Protocol
21
 * \brief Implementation of Session Initiation Protocol
22
 *
22
 *
23
 * \author Mark Spencer <markster@digium.com>
23
 * \author Mark Spencer <markster@digium.com>
24
 *
24
 *
25
 * See Also:
25
 * See Also:
26
 * \arg \ref AstCREDITS
26
 * \arg \ref AstCREDITS
27
 *
27
 *
28
 * Implementation of RFC 3261 - without S/MIME, and experimental TCP and TLS support
28
 * Implementation of RFC 3261 - without S/MIME, and experimental TCP and TLS support
29
 * Configuration file \link Config_sip sip.conf \endlink
29
 * Configuration file \link Config_sip sip.conf \endlink
30
 *
30
 *
31
 * ********** IMPORTANT *
31
 * ********** IMPORTANT *
32
 * \note TCP/TLS support is EXPERIMENTAL and WILL CHANGE. This applies to configuration
32
 * \note TCP/TLS support is EXPERIMENTAL and WILL CHANGE. This applies to configuration
33
 *	settings, dialplan commands and dialplans apps/functions
33
 *	settings, dialplan commands and dialplans apps/functions
34
 * See \ref sip_tcp_tls
34
 * See \ref sip_tcp_tls
35
 *
35
 *
36
 *
36
 *
37
 * ******** General TODO:s
37
 * ******** General TODO:s
38
 * \todo Better support of forking
38
 * \todo Better support of forking
39
 * \todo VIA branch tag transaction checking
39
 * \todo VIA branch tag transaction checking
40
 * \todo Transaction support
40
 * \todo Transaction support
41
 *
41
 *
42
 * ******** Wishlist: Improvements
42
 * ******** Wishlist: Improvements
43
 * - Support of SIP domains for devices, so that we match on username@domain in the From: header
43
 * - Support of SIP domains for devices, so that we match on username@domain in the From: header
44
 * - Connect registrations with a specific device on the incoming call. It's not done
44
 * - Connect registrations with a specific device on the incoming call. It's not done
45
 *   automatically in Asterisk
45
 *   automatically in Asterisk
46
 *
46
 *
47
 * \ingroup channel_drivers
47
 * \ingroup channel_drivers
48
 *
48
 *
49
 * \par Overview of the handling of SIP sessions
49
 * \par Overview of the handling of SIP sessions
50
 * The SIP channel handles several types of SIP sessions, or dialogs,
50
 * The SIP channel handles several types of SIP sessions, or dialogs,
51
 * not all of them being "telephone calls".
51
 * not all of them being "telephone calls".
52
 * - Incoming calls that will be sent to the PBX core
52
 * - Incoming calls that will be sent to the PBX core
53
 * - Outgoing calls, generated by the PBX
53
 * - Outgoing calls, generated by the PBX
54
 * - SIP subscriptions and notifications of states and voicemail messages
54
 * - SIP subscriptions and notifications of states and voicemail messages
55
 * - SIP registrations, both inbound and outbound
55
 * - SIP registrations, both inbound and outbound
56
 * - SIP peer management (peerpoke, OPTIONS)
56
 * - SIP peer management (peerpoke, OPTIONS)
57
 * - SIP text messages
57
 * - SIP text messages
58
 *
58
 *
59
 * In the SIP channel, there's a list of active SIP dialogs, which includes
59
 * In the SIP channel, there's a list of active SIP dialogs, which includes
60
 * all of these when they are active. "sip show channels" in the CLI will
60
 * all of these when they are active. "sip show channels" in the CLI will
61
 * show most of these, excluding subscriptions which are shown by
61
 * show most of these, excluding subscriptions which are shown by
62
 * "sip show subscriptions"
62
 * "sip show subscriptions"
63
 *
63
 *
64
 * \par incoming packets
64
 * \par incoming packets
65
 * Incoming packets are received in the monitoring thread, then handled by
65
 * Incoming packets are received in the monitoring thread, then handled by
66
 * sipsock_read() for udp only. In tcp, packets are read by the tcp_helper thread.
66
 * sipsock_read() for udp only. In tcp, packets are read by the tcp_helper thread.
67
 * sipsock_read() function parses the packet and matches an existing
67
 * sipsock_read() function parses the packet and matches an existing
68
 * dialog or starts a new SIP dialog.
68
 * dialog or starts a new SIP dialog.
69
 *
69
 *
70
 * sipsock_read sends the packet to handle_incoming(), that parses a bit more.
70
 * sipsock_read sends the packet to handle_incoming(), that parses a bit more.
71
 * If it is a response to an outbound request, the packet is sent to handle_response().
71
 * If it is a response to an outbound request, the packet is sent to handle_response().
72
 * If it is a request, handle_incoming() sends it to one of a list of functions
72
 * If it is a request, handle_incoming() sends it to one of a list of functions
73
 * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
73
 * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
74
 * sipsock_read locks the ast_channel if it exists (an active call) and
74
 * sipsock_read locks the ast_channel if it exists (an active call) and
75
 * unlocks it after we have processed the SIP message.
75
 * unlocks it after we have processed the SIP message.
76
 *
76
 *
77
 * A new INVITE is sent to handle_request_invite(), that will end up
77
 * A new INVITE is sent to handle_request_invite(), that will end up
78
 * starting a new channel in the PBX, the new channel after that executing
78
 * starting a new channel in the PBX, the new channel after that executing
79
 * in a separate channel thread. This is an incoming "call".
79
 * in a separate channel thread. This is an incoming "call".
80
 * When the call is answered, either by a bridged channel or the PBX itself
80
 * When the call is answered, either by a bridged channel or the PBX itself
81
 * the sip_answer() function is called.
81
 * the sip_answer() function is called.
82
 *
82
 *
83
 * The actual media - Video or Audio - is mostly handled by the RTP subsystem
83
 * The actual media - Video or Audio - is mostly handled by the RTP subsystem
84
 * in rtp.c
84
 * in rtp.c
85
 *
85
 *
86
 * \par Outbound calls
86
 * \par Outbound calls
87
 * Outbound calls are set up by the PBX through the sip_request_call()
87
 * Outbound calls are set up by the PBX through the sip_request_call()
88
 * function. After that, they are activated by sip_call().
88
 * function. After that, they are activated by sip_call().
89
 *
89
 *
90
 * \par Hanging up
90
 * \par Hanging up
91
 * The PBX issues a hangup on both incoming and outgoing calls through
91
 * The PBX issues a hangup on both incoming and outgoing calls through
92
 * the sip_hangup() function
92
 * the sip_hangup() function
93
 */
93
 */
94

    
   
94

   
95
/*!
95
/*!
96
 * \page sip_tcp_tls SIP TCP and TLS support
96
 * \page sip_tcp_tls SIP TCP and TLS support
97
 *
97
 *
98
 * \par tcpfixes TCP implementation changes needed
98
 * \par tcpfixes TCP implementation changes needed
99
 * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
99
 * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
100
 * \todo Save TCP/TLS sessions in registry
100
 * \todo Save TCP/TLS sessions in registry
101
 *	If someone registers a SIPS uri, this forces us to set up a TLS connection back.
101
 *	If someone registers a SIPS uri, this forces us to set up a TLS connection back.
102
 * \todo Add TCP/TLS information to function SIPPEER and SIPCHANINFO
102
 * \todo Add TCP/TLS information to function SIPPEER and SIPCHANINFO
103
 * \todo If tcpenable=yes, we must open a TCP socket on the same address as the IP for UDP.
103
 * \todo If tcpenable=yes, we must open a TCP socket on the same address as the IP for UDP.
104
 * 	The tcpbindaddr config option should only be used to open ADDITIONAL ports
104
 * 	The tcpbindaddr config option should only be used to open ADDITIONAL ports
105
 * 	So we should propably go back to
105
 * 	So we should propably go back to
106
 *		bindaddr= the default address to bind to. If tcpenable=yes, then bind this to both udp and TCP
106
 *		bindaddr= the default address to bind to. If tcpenable=yes, then bind this to both udp and TCP
107
 *				if tlsenable=yes, open TLS port (provided we also have cert)
107
 *				if tlsenable=yes, open TLS port (provided we also have cert)
108
 *		tcpbindaddr = extra address for additional TCP connections
108
 *		tcpbindaddr = extra address for additional TCP connections
109
 *		tlsbindaddr = extra address for additional TCP/TLS connections
109
 *		tlsbindaddr = extra address for additional TCP/TLS connections
110
 *		udpbindaddr = extra address for additional UDP connections
110
 *		udpbindaddr = extra address for additional UDP connections
111
 *			These three options should take multiple IP/port pairs
111
 *			These three options should take multiple IP/port pairs
112
 *	Note: Since opening additional listen sockets is a *new* feature we do not have today
112
 *	Note: Since opening additional listen sockets is a *new* feature we do not have today
113
 *		the XXXbindaddr options needs to be disabled until we have support for it
113
 *		the XXXbindaddr options needs to be disabled until we have support for it
114
 *
114
 *
115
 * \todo re-evaluate the transport= setting in sip.conf. This is right now not well
115
 * \todo re-evaluate the transport= setting in sip.conf. This is right now not well
116
 * 	thought of. If a device in sip.conf contacts us via TCP, we should not switch transport,
116
 * 	thought of. If a device in sip.conf contacts us via TCP, we should not switch transport,
117
 *	even if udp is the configured first transport.
117
 *	even if udp is the configured first transport.
118
 *
118
 *
119
 * \todo Be prepared for one outbound and another incoming socket per pvt. This applies
119
 * \todo Be prepared for one outbound and another incoming socket per pvt. This applies
120
 *       specially to communication with other peers (proxies).
120
 *       specially to communication with other peers (proxies).
121
 * \todo We need to test TCP sessions with SIP proxies and in regards
121
 * \todo We need to test TCP sessions with SIP proxies and in regards
122
 *       to the SIP outbound specs.
122
 *       to the SIP outbound specs.
123
 * \todo ;transport=tls was deprecated in RFC3261 and should not be used at all. See section 26.2.2.
123
 * \todo ;transport=tls was deprecated in RFC3261 and should not be used at all. See section 26.2.2.
124
 *
124
 *
125
 * \todo If the message is smaller than the given Content-length, the request should get a 400 Bad request
125
 * \todo If the message is smaller than the given Content-length, the request should get a 400 Bad request
126
 *       message. If it's a response, it should be dropped. (RFC 3261, Section 18.3)
126
 *       message. If it's a response, it should be dropped. (RFC 3261, Section 18.3)
127
 * \todo Since we have had multidomain support in Asterisk for quite a while, we need to support
127
 * \todo Since we have had multidomain support in Asterisk for quite a while, we need to support
128
 *       multiple domains in our TLS implementation, meaning one socket and one cert per domain
128
 *       multiple domains in our TLS implementation, meaning one socket and one cert per domain
129
 * \todo Selection of transport for a request needs to be done after we've parsed all route headers,
129
 * \todo Selection of transport for a request needs to be done after we've parsed all route headers,
130
 *	 also considering outbound proxy options.
130
 *	 also considering outbound proxy options.
131
 *		First request: Outboundproxy, routes, (reg contact or URI. If URI doesn't have port:  DNS naptr, srv, AAA)
131
 *		First request: Outboundproxy, routes, (reg contact or URI. If URI doesn't have port:  DNS naptr, srv, AAA)
132
 *		Intermediate requests: Outboundproxy(only when forced), routes, contact/uri
132
 *		Intermediate requests: Outboundproxy(only when forced), routes, contact/uri
133
 *	DNS naptr support is crucial. A SIP uri might lead to a TLS connection.
133
 *	DNS naptr support is crucial. A SIP uri might lead to a TLS connection.
134
 *	Also note that due to outbound proxy settings, a SIPS uri might have to be sent on UDP (not to recommend though)
134
 *	Also note that due to outbound proxy settings, a SIPS uri might have to be sent on UDP (not to recommend though)
135
 * \todo Default transports are set to UDP, which cause the wrong behaviour when contacting remote
135
 * \todo Default transports are set to UDP, which cause the wrong behaviour when contacting remote
136
 *	devices directly from the dialplan. UDP is only a fallback if no other method works,
136
 *	devices directly from the dialplan. UDP is only a fallback if no other method works,
137
 *	in order to be compatible with RFC2543 (SIP/1.0) devices. For transactions that exceed the
137
 *	in order to be compatible with RFC2543 (SIP/1.0) devices. For transactions that exceed the
138
 *	MTU (like INIVTE with video, audio and RTT)  TCP should be preferred.
138
 *	MTU (like INIVTE with video, audio and RTT)  TCP should be preferred.
139
 *
139
 *
140
 *	When dialling unconfigured peers (with no port number)  or devices in external domains
140
 *	When dialling unconfigured peers (with no port number)  or devices in external domains
141
 *	NAPTR records MUST be consulted to find configured transport. If they are not found,
141
 *	NAPTR records MUST be consulted to find configured transport. If they are not found,
142
 *	SRV records for both TCP and UDP should be checked. If there's a record for TCP, use that.
142
 *	SRV records for both TCP and UDP should be checked. If there's a record for TCP, use that.
143
 *	If there's no record for TCP, then use UDP as a last resort. If there's no SRV records,
143
 *	If there's no record for TCP, then use UDP as a last resort. If there's no SRV records,
144
 *	\note this only applies if there's no outbound proxy configured for the session. If an outbound
144
 *	\note this only applies if there's no outbound proxy configured for the session. If an outbound
145
 *	proxy is configured, these procedures might apply for locating the proxy and determining
145
 *	proxy is configured, these procedures might apply for locating the proxy and determining
146
 *	the transport to use for communication with the proxy.
146
 *	the transport to use for communication with the proxy.
147
 * \par Other bugs to fix ----
147
 * \par Other bugs to fix ----
148
 * __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
148
 * __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
149
 *	- sets TLS port as default for all TCP connections, unless other port is given in contact.
149
 *	- sets TLS port as default for all TCP connections, unless other port is given in contact.
150
 * parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
150
 * parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
151
 *	- assumes that the contact the UA registers is using the same transport as the REGISTER request, which is
151
 *	- assumes that the contact the UA registers is using the same transport as the REGISTER request, which is
152
 *	  a bad guess.
152
 *	  a bad guess.
153
 *      - Does not save any information about TCP/TLS connected devices, which is a severe BUG, as discussed on the mailing list.
153
 *      - Does not save any information about TCP/TLS connected devices, which is a severe BUG, as discussed on the mailing list.
154
 * get_destination(struct sip_pvt *p, struct sip_request *oreq)
154
 * get_destination(struct sip_pvt *p, struct sip_request *oreq)
155
 *	- Doesn't store the information that we got an incoming SIPS request in the channel, so that
155
 *	- Doesn't store the information that we got an incoming SIPS request in the channel, so that
156
 *	  we can require a secure signalling path OUT of Asterisk (on SIP or IAX2). Possibly, the call should
156
 *	  we can require a secure signalling path OUT of Asterisk (on SIP or IAX2). Possibly, the call should
157
 *	  fail on in-secure signalling paths if there's no override in our configuration. At least, provide a
157
 *	  fail on in-secure signalling paths if there's no override in our configuration. At least, provide a
158
 *	  channel variable in the dialplan.
158
 *	  channel variable in the dialplan.
159
 * get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
159
 * get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
160
 *	- As above, if we have a SIPS: uri in the refer-to header
160
 *	- As above, if we have a SIPS: uri in the refer-to header
161
 *	- Does not check transport in refer_to uri.
161
 *	- Does not check transport in refer_to uri.
162
 */
162
 */
163

    
   
163

   
164
/*** MODULEINFO
164
/*** MODULEINFO
165
	<use type="module">res_crypto</use>
165
	<use type="module">res_crypto</use>
166
	<depend>chan_local</depend>
166
	<depend>chan_local</depend>
167
	<support_level>core</support_level>
167
	<support_level>core</support_level>
168
 ***/
168
 ***/
169

    
   
169

   
170
/*!  \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
170
/*!  \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
171

    
   
171

   
172
	The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
172
	The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
173
	refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
173
	refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
174
	request at a negotiated interval. If a session refresh fails then all the entities that support Session-
174
	request at a negotiated interval. If a session refresh fails then all the entities that support Session-
175
	Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
175
	Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
176
	the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
176
	the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
177
	that do not support Session-Timers).
177
	that do not support Session-Timers).
178

    
   
178

   
179
	The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
179
	The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
180
	per-peer settings override the global settings. The following new parameters have been
180
	per-peer settings override the global settings. The following new parameters have been
181
	added to the sip.conf file.
181
	added to the sip.conf file.
182
		session-timers=["accept", "originate", "refuse"]
182
		session-timers=["accept", "originate", "refuse"]
183
		session-expires=[integer]
183
		session-expires=[integer]
184
		session-minse=[integer]
184
		session-minse=[integer]
185
		session-refresher=["uas", "uac"]
185
		session-refresher=["uas", "uac"]
186

    
   
186

   
187
	The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
187
	The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
188
	Asterisk. The Asterisk can be configured in one of the following three modes:
188
	Asterisk. The Asterisk can be configured in one of the following three modes:
189

    
   
189

   
190
	1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
190
	1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
191
		made by remote end-points. A remote end-point can request Asterisk to engage
191
		made by remote end-points. A remote end-point can request Asterisk to engage
192
		session-timers by either sending it an INVITE request with a "Supported: timer"
192
		session-timers by either sending it an INVITE request with a "Supported: timer"
193
		header in it or by responding to Asterisk's INVITE with a 200 OK that contains
193
		header in it or by responding to Asterisk's INVITE with a 200 OK that contains
194
		Session-Expires: header in it. In this mode, the Asterisk server does not
194
		Session-Expires: header in it. In this mode, the Asterisk server does not
195
		request session-timers from remote end-points. This is the default mode.
195
		request session-timers from remote end-points. This is the default mode.
196
	2. Originate :: In the "originate" mode, the Asterisk server requests the remote
196
	2. Originate :: In the "originate" mode, the Asterisk server requests the remote
197
		end-points to activate session-timers in addition to honoring such requests
197
		end-points to activate session-timers in addition to honoring such requests
198
		made by the remote end-pints. In order to get as much protection as possible
198
		made by the remote end-pints. In order to get as much protection as possible
199
		against hanging SIP channels due to network or end-point failures, Asterisk
199
		against hanging SIP channels due to network or end-point failures, Asterisk
200
		resends periodic re-INVITEs even if a remote end-point does not support
200
		resends periodic re-INVITEs even if a remote end-point does not support
201
		the session-timers feature.
201
		the session-timers feature.
202
	3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
202
	3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
203
		timers for inbound or outbound requests. If a remote end-point requests
203
		timers for inbound or outbound requests. If a remote end-point requests
204
		session-timers in a dialog, then Asterisk ignores that request unless it's
204
		session-timers in a dialog, then Asterisk ignores that request unless it's
205
		noted as a requirement (Require: header), in which case the INVITE is
205
		noted as a requirement (Require: header), in which case the INVITE is
206
		rejected with a 420 Bad Extension response.
206
		rejected with a 420 Bad Extension response.
207

    
   
207

   
208
*/
208
*/
209

    
   
209

   
210
#include "asterisk.h"
210
#include "asterisk.h"
211

    
   
211

   
212
ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
212
ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
213

    
   
213

   
214
#include <signal.h>
214
#include <signal.h>
215
#include <sys/signal.h>
215
#include <sys/signal.h>
216
#include <regex.h>
216
#include <regex.h>
217
#include <inttypes.h>
217
#include <inttypes.h>
218

    
   
218

   
219
#include "asterisk/network.h"
219
#include "asterisk/network.h"
220
#include "asterisk/paths.h"	/* need ast_config_AST_SYSTEM_NAME */
220
#include "asterisk/paths.h"	/* need ast_config_AST_SYSTEM_NAME */
221
/*
221
/*
222
   Uncomment the define below,  if you are having refcount related memory leaks.
222
   Uncomment the define below,  if you are having refcount related memory leaks.
223
   With this uncommented, this module will generate a file, /tmp/refs, which contains
223
   With this uncommented, this module will generate a file, /tmp/refs, which contains
224
   a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
224
   a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
225
   be modified to ao2_t_* calls, and include a tag describing what is happening with
225
   be modified to ao2_t_* calls, and include a tag describing what is happening with
226
   enough detail, to make pairing up a reference count increment with its corresponding decrement.
226
   enough detail, to make pairing up a reference count increment with its corresponding decrement.
227
   The refcounter program in utils/ can be invaluable in highlighting objects that are not
227
   The refcounter program in utils/ can be invaluable in highlighting objects that are not
228
   balanced, along with the complete history for that object.
228
   balanced, along with the complete history for that object.
229
   In normal operation, the macros defined will throw away the tags, so they do not
229
   In normal operation, the macros defined will throw away the tags, so they do not
230
   affect the speed of the program at all. They can be considered to be documentation.
230
   affect the speed of the program at all. They can be considered to be documentation.
231
*/
231
*/
232
/* #define  REF_DEBUG 1 */
232
/* #define  REF_DEBUG 1 */
233

    
   
233

   
234
#include "asterisk/lock.h"
234
#include "asterisk/lock.h"
235
#include "asterisk/config.h"
235
#include "asterisk/config.h"
236
#include "asterisk/module.h"
236
#include "asterisk/module.h"
237
#include "asterisk/pbx.h"
237
#include "asterisk/pbx.h"
238
#include "asterisk/sched.h"
238
#include "asterisk/sched.h"
239
#include "asterisk/io.h"
239
#include "asterisk/io.h"
240
#include "asterisk/rtp_engine.h"
240
#include "asterisk/rtp_engine.h"
241
#include "asterisk/udptl.h"
241
#include "asterisk/udptl.h"
242
#include "asterisk/acl.h"
242
#include "asterisk/acl.h"
243
#include "asterisk/manager.h"
243
#include "asterisk/manager.h"
244
#include "asterisk/callerid.h"
244
#include "asterisk/callerid.h"
245
#include "asterisk/cli.h"
245
#include "asterisk/cli.h"
246
#include "asterisk/musiconhold.h"
246
#include "asterisk/musiconhold.h"
247
#include "asterisk/dsp.h"
247
#include "asterisk/dsp.h"
248
#include "asterisk/features.h"
248
#include "asterisk/features.h"
249
#include "asterisk/srv.h"
249
#include "asterisk/srv.h"
250
#include "asterisk/astdb.h"
250
#include "asterisk/astdb.h"
251
#include "asterisk/causes.h"
251
#include "asterisk/causes.h"
252
#include "asterisk/utils.h"
252
#include "asterisk/utils.h"
253
#include "asterisk/file.h"
253
#include "asterisk/file.h"
254
#include "asterisk/astobj2.h"
254
#include "asterisk/astobj2.h"
255
#include "asterisk/dnsmgr.h"
255
#include "asterisk/dnsmgr.h"
256
#include "asterisk/devicestate.h"
256
#include "asterisk/devicestate.h"
257
#include "asterisk/monitor.h"
257
#include "asterisk/monitor.h"
258
#include "asterisk/netsock2.h"
258
#include "asterisk/netsock2.h"
259
#include "asterisk/localtime.h"
259
#include "asterisk/localtime.h"
260
#include "asterisk/abstract_jb.h"
260
#include "asterisk/abstract_jb.h"
261
#include "asterisk/threadstorage.h"
261
#include "asterisk/threadstorage.h"
262
#include "asterisk/translate.h"
262
#include "asterisk/translate.h"
263
#include "asterisk/ast_version.h"
263
#include "asterisk/ast_version.h"
264
#include "asterisk/event.h"
264
#include "asterisk/event.h"
265
#include "asterisk/cel.h"
265
#include "asterisk/cel.h"
266
#include "asterisk/data.h"
266
#include "asterisk/data.h"
267
#include "asterisk/aoc.h"
267
#include "asterisk/aoc.h"
268
#include "asterisk/message.h"
268
#include "asterisk/message.h"
269
#include "sip/include/sip.h"
269
#include "sip/include/sip.h"
270
#include "sip/include/globals.h"
270
#include "sip/include/globals.h"
271
#include "sip/include/config_parser.h"
271
#include "sip/include/config_parser.h"
272
#include "sip/include/reqresp_parser.h"
272
#include "sip/include/reqresp_parser.h"
273
#include "sip/include/sip_utils.h"
273
#include "sip/include/sip_utils.h"
274
#include "sip/include/srtp.h"
274
#include "sip/include/srtp.h"
275
#include "sip/include/sdp_crypto.h"
275
#include "sip/include/sdp_crypto.h"
276
#include "asterisk/ccss.h"
276
#include "asterisk/ccss.h"
277
#include "asterisk/xml.h"
277
#include "asterisk/xml.h"
278
#include "sip/include/dialog.h"
278
#include "sip/include/dialog.h"
279
#include "sip/include/dialplan_functions.h"
279
#include "sip/include/dialplan_functions.h"
280
#include "sip/include/security_events.h"
280
#include "sip/include/security_events.h"
281
#include "asterisk/sip_api.h"
281
#include "asterisk/sip_api.h"
282

    
   
282

   
283
/*** DOCUMENTATION
283
/*** DOCUMENTATION
284
	<application name="SIPDtmfMode" language="en_US">
284
	<application name="SIPDtmfMode" language="en_US">
285
		<synopsis>
285
		<synopsis>
286
			Change the dtmfmode for a SIP call.
286
			Change the dtmfmode for a SIP call.
287
		</synopsis>
287
		</synopsis>
288
		<syntax>
288
		<syntax>
289
			<parameter name="mode" required="true">
289
			<parameter name="mode" required="true">
290
				<enumlist>
290
				<enumlist>
291
					<enum name="inband" />
291
					<enum name="inband" />
292
					<enum name="info" />
292
					<enum name="info" />
293
					<enum name="rfc2833" />
293
					<enum name="rfc2833" />
294
				</enumlist>
294
				</enumlist>
295
			</parameter>
295
			</parameter>
296
		</syntax>
296
		</syntax>
297
		<description>
297
		<description>
298
			<para>Changes the dtmfmode for a SIP call.</para>
298
			<para>Changes the dtmfmode for a SIP call.</para>
299
		</description>
299
		</description>
300
	</application>
300
	</application>
301
	<application name="SIPAddHeader" language="en_US">
301
	<application name="SIPAddHeader" language="en_US">
302
		<synopsis>
302
		<synopsis>
303
			Add a SIP header to the outbound call.
303
			Add a SIP header to the outbound call.
304
		</synopsis>
304
		</synopsis>
305
		<syntax argsep=":">
305
		<syntax argsep=":">
306
			<parameter name="Header" required="true" />
306
			<parameter name="Header" required="true" />
307
			<parameter name="Content" required="true" />
307
			<parameter name="Content" required="true" />
308
		</syntax>
308
		</syntax>
309
		<description>
309
		<description>
310
			<para>Adds a header to a SIP call placed with DIAL.</para>
310
			<para>Adds a header to a SIP call placed with DIAL.</para>
311
			<para>Remember to use the X-header if you are adding non-standard SIP
311
			<para>Remember to use the X-header if you are adding non-standard SIP
312
			headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
312
			headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
313
			Adding the wrong headers may jeopardize the SIP dialog.</para>
313
			Adding the wrong headers may jeopardize the SIP dialog.</para>
314
			<para>Always returns <literal>0</literal>.</para>
314
			<para>Always returns <literal>0</literal>.</para>
315
		</description>
315
		</description>
316
	</application>
316
	</application>
317
	<application name="SIPRemoveHeader" language="en_US">
317
	<application name="SIPRemoveHeader" language="en_US">
318
		<synopsis>
318
		<synopsis>
319
			Remove SIP headers previously added with SIPAddHeader
319
			Remove SIP headers previously added with SIPAddHeader
320
		</synopsis>
320
		</synopsis>
321
		<syntax>
321
		<syntax>
322
			<parameter name="Header" required="false" />
322
			<parameter name="Header" required="false" />
323
		</syntax>
323
		</syntax>
324
		<description>
324
		<description>
325
			<para>SIPRemoveHeader() allows you to remove headers which were previously
325
			<para>SIPRemoveHeader() allows you to remove headers which were previously
326
			added with SIPAddHeader(). If no parameter is supplied, all previously added
326
			added with SIPAddHeader(). If no parameter is supplied, all previously added
327
			headers will be removed. If a parameter is supplied, only the matching headers
327
			headers will be removed. If a parameter is supplied, only the matching headers
328
			will be removed.</para>
328
			will be removed.</para>
329
			<para>For example you have added these 2 headers:</para>
329
			<para>For example you have added these 2 headers:</para>
330
			<para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
330
			<para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
331
			<para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
331
			<para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
332
			<para></para>
332
			<para></para>
333
			<para>// remove all headers</para>
333
			<para>// remove all headers</para>
334
			<para>SIPRemoveHeader();</para>
334
			<para>SIPRemoveHeader();</para>
335
			<para>// remove all P- headers</para>
335
			<para>// remove all P- headers</para>
336
			<para>SIPRemoveHeader(P-);</para>
336
			<para>SIPRemoveHeader(P-);</para>
337
			<para>// remove only the PAI header (note the : at the end)</para>
337
			<para>// remove only the PAI header (note the : at the end)</para>
338
			<para>SIPRemoveHeader(P-Asserted-Identity:);</para>
338
			<para>SIPRemoveHeader(P-Asserted-Identity:);</para>
339
			<para></para>
339
			<para></para>
340
			<para>Always returns <literal>0</literal>.</para>
340
			<para>Always returns <literal>0</literal>.</para>
341
		</description>
341
		</description>
342
	</application>
342
	</application>
343
	<application name="SIPSendCustomINFO" language="en_US">
343
	<application name="SIPSendCustomINFO" language="en_US">
344
		<synopsis>
344
		<synopsis>
345
			Send a custom INFO frame on specified channels.
345
			Send a custom INFO frame on specified channels.
346
		</synopsis>
346
		</synopsis>
347
		<syntax>
347
		<syntax>
348
			<parameter name="Data" required="true" />
348
			<parameter name="Data" required="true" />
349
			<parameter name="UserAgent" required="false" />
349
			<parameter name="UserAgent" required="false" />
350
		</syntax>
350
		</syntax>
351
		<description>
351
		<description>
352
			<para>SIPSendCustomINFO() allows you to send a custom INFO message on all
352
			<para>SIPSendCustomINFO() allows you to send a custom INFO message on all
353
			active SIP channels or on channels with the specified User Agent. This
353
			active SIP channels or on channels with the specified User Agent. This
354
			application is only available if TEST_FRAMEWORK is defined.</para>
354
			application is only available if TEST_FRAMEWORK is defined.</para>
355
		</description>
355
		</description>
356
	</application>
356
	</application>
357
	<function name="SIP_HEADER" language="en_US">
357
	<function name="SIP_HEADER" language="en_US">
358
		<synopsis>
358
		<synopsis>
359
			Gets the specified SIP header from an incoming INVITE message.
359
			Gets the specified SIP header from an incoming INVITE message.
360
		</synopsis>
360
		</synopsis>
361
		<syntax>
361
		<syntax>
362
			<parameter name="name" required="true" />
362
			<parameter name="name" required="true" />
363
			<parameter name="number">
363
			<parameter name="number">
364
				<para>If not specified, defaults to <literal>1</literal>.</para>
364
				<para>If not specified, defaults to <literal>1</literal>.</para>
365
			</parameter>
365
			</parameter>
366
		</syntax>
366
		</syntax>
367
		<description>
367
		<description>
368
			<para>Since there are several headers (such as Via) which can occur multiple
368
			<para>Since there are several headers (such as Via) which can occur multiple
369
			times, SIP_HEADER takes an optional second argument to specify which header with
369
			times, SIP_HEADER takes an optional second argument to specify which header with
370
			that name to retrieve. Headers start at offset <literal>1</literal>.</para>
370
			that name to retrieve. Headers start at offset <literal>1</literal>.</para>
371
			<para>Please observe that contents of the SDP (an attachment to the 
371
			<para>Please observe that contents of the SDP (an attachment to the 
372
			SIP request) can't be accessed with this function.</para>
372
			SIP request) can't be accessed with this function.</para>
373
		</description>
373
		</description>
374
	</function>
374
	</function>
375
	<function name="SIPPEER" language="en_US">
375
	<function name="SIPPEER" language="en_US">
376
		<synopsis>
376
		<synopsis>
377
			Gets SIP peer information.
377
			Gets SIP peer information.
378
		</synopsis>
378
		</synopsis>
379
		<syntax>
379
		<syntax>
380
			<parameter name="peername" required="true" />
380
			<parameter name="peername" required="true" />
381
			<parameter name="item">
381
			<parameter name="item">
382
				<enumlist>
382
				<enumlist>
383
					<enum name="ip">
383
					<enum name="ip">
384
						<para>(default) The IP address.</para>
384
						<para>(default) The IP address.</para>
385
					</enum>
385
					</enum>
386
					<enum name="port">
386
					<enum name="port">
387
						<para>The port number.</para>
387
						<para>The port number.</para>
388
					</enum>
388
					</enum>
389
					<enum name="mailbox">
389
					<enum name="mailbox">
390
						<para>The configured mailbox.</para>
390
						<para>The configured mailbox.</para>
391
					</enum>
391
					</enum>
392
					<enum name="context">
392
					<enum name="context">
393
						<para>The configured context.</para>
393
						<para>The configured context.</para>
394
					</enum>
394
					</enum>
395
					<enum name="expire">
395
					<enum name="expire">
396
						<para>The epoch time of the next expire.</para>
396
						<para>The epoch time of the next expire.</para>
397
					</enum>
397
					</enum>
398
					<enum name="dynamic">
398
					<enum name="dynamic">
399
						<para>Is it dynamic? (yes/no).</para>
399
						<para>Is it dynamic? (yes/no).</para>
400
					</enum>
400
					</enum>
401
					<enum name="callerid_name">
401
					<enum name="callerid_name">
402
						<para>The configured Caller ID name.</para>
402
						<para>The configured Caller ID name.</para>
403
					</enum>
403
					</enum>
404
					<enum name="callerid_num">
404
					<enum name="callerid_num">
405
						<para>The configured Caller ID number.</para>
405
						<para>The configured Caller ID number.</para>
406
					</enum>
406
					</enum>
407
					<enum name="callgroup">
407
					<enum name="callgroup">
408
						<para>The configured Callgroup.</para>
408
						<para>The configured Callgroup.</para>
409
					</enum>
409
					</enum>
410
					<enum name="pickupgroup">
410
					<enum name="pickupgroup">
411
						<para>The configured Pickupgroup.</para>
411
						<para>The configured Pickupgroup.</para>
412
					</enum>
412
					</enum>
413
					<enum name="codecs">
413
					<enum name="codecs">
414
						<para>The configured codecs.</para>
414
						<para>The configured codecs.</para>
415
					</enum>
415
					</enum>
416
					<enum name="status">
416
					<enum name="status">
417
						<para>Status (if qualify=yes).</para>
417
						<para>Status (if qualify=yes).</para>
418
					</enum>
418
					</enum>
419
					<enum name="regexten">
419
					<enum name="regexten">
420
						<para>Extension activated at registration.</para>
420
						<para>Extension activated at registration.</para>
421
					</enum>
421
					</enum>
422
					<enum name="limit">
422
					<enum name="limit">
423
						<para>Call limit (call-limit).</para>
423
						<para>Call limit (call-limit).</para>
424
					</enum>
424
					</enum>
425
					<enum name="busylevel">
425
					<enum name="busylevel">
426
						<para>Configured call level for signalling busy.</para>
426
						<para>Configured call level for signalling busy.</para>
427
					</enum>
427
					</enum>
428
					<enum name="curcalls">
428
					<enum name="curcalls">
429
						<para>Current amount of calls. Only available if call-limit is set.</para>
429
						<para>Current amount of calls. Only available if call-limit is set.</para>
430
					</enum>
430
					</enum>
431
					<enum name="language">
431
					<enum name="language">
432
						<para>Default language for peer.</para>
432
						<para>Default language for peer.</para>
433
					</enum>
433
					</enum>
434
					<enum name="accountcode">
434
					<enum name="accountcode">
435
						<para>Account code for this peer.</para>
435
						<para>Account code for this peer.</para>
436
					</enum>
436
					</enum>
437
					<enum name="useragent">
437
					<enum name="useragent">
438
						<para>Current user agent header used by peer.</para>
438
						<para>Current user agent header used by peer.</para>
439
					</enum>
439
					</enum>
440
					<enum name="maxforwards">
440
					<enum name="maxforwards">
441
						<para>The value used for SIP loop prevention in outbound requests</para>
441
						<para>The value used for SIP loop prevention in outbound requests</para>
442
					</enum>
442
					</enum>
443
					<enum name="chanvar[name]">
443
					<enum name="chanvar[name]">
444
						<para>A channel variable configured with setvar for this peer.</para>
444
						<para>A channel variable configured with setvar for this peer.</para>
445
					</enum>
445
					</enum>
446
					<enum name="codec[x]">
446
					<enum name="codec[x]">
447
						<para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
447
						<para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
448
					</enum>
448
					</enum>
449
				</enumlist>
449
				</enumlist>
450
			</parameter>
450
			</parameter>
451
		</syntax>
451
		</syntax>
452
		<description></description>
452
		<description></description>
453
	</function>
453
	</function>
454
	<function name="SIPCHANINFO" language="en_US">
454
	<function name="SIPCHANINFO" language="en_US">
455
		<synopsis>
455
		<synopsis>
456
			Gets the specified SIP parameter from the current channel.
456
			Gets the specified SIP parameter from the current channel.
457
		</synopsis>
457
		</synopsis>
458
		<syntax>
458
		<syntax>
459
			<parameter name="item" required="true">
459
			<parameter name="item" required="true">
460
				<enumlist>
460
				<enumlist>
461
					<enum name="peerip">
461
					<enum name="peerip">
462
						<para>The IP address of the peer.</para>
462
						<para>The IP address of the peer.</para>
463
					</enum>
463
					</enum>
464
					<enum name="recvip">
464
					<enum name="recvip">
465
						<para>The source IP address of the peer.</para>
465
						<para>The source IP address of the peer.</para>
466
					</enum>
466
					</enum>
467
					<enum name="from">
467
					<enum name="from">
468
						<para>The SIP URI from the <literal>From:</literal> header.</para>
468
						<para>The SIP URI from the <literal>From:</literal> header.</para>
469
					</enum>
469
					</enum>
470
					<enum name="uri">
470
					<enum name="uri">
471
						<para>The SIP URI from the <literal>Contact:</literal> header.</para>
471
						<para>The SIP URI from the <literal>Contact:</literal> header.</para>
472
					</enum>
472
					</enum>
473
					<enum name="useragent">
473
					<enum name="useragent">
474
						<para>The Useragent header used by the peer.</para>
474
						<para>The Useragent header used by the peer.</para>
475
					</enum>
475
					</enum>
476
					<enum name="peername">
476
					<enum name="peername">
477
						<para>The name of the peer.</para>
477
						<para>The name of the peer.</para>
478
					</enum>
478
					</enum>
479
					<enum name="t38passthrough">
479
					<enum name="t38passthrough">
480
						<para><literal>1</literal> if T38 is offered or enabled in this channel,
480
						<para><literal>1</literal> if T38 is offered or enabled in this channel,
481
						otherwise <literal>0</literal>.</para>
481
						otherwise <literal>0</literal>.</para>
482
					</enum>
482
					</enum>
483
				</enumlist>
483
				</enumlist>
484
			</parameter>
484
			</parameter>
485
		</syntax>
485
		</syntax>
486
		<description></description>
486
		<description></description>
487
	</function>
487
	</function>
488
	<function name="CHECKSIPDOMAIN" language="en_US">
488
	<function name="CHECKSIPDOMAIN" language="en_US">
489
		<synopsis>
489
		<synopsis>
490
			Checks if domain is a local domain.
490
			Checks if domain is a local domain.
491
		</synopsis>
491
		</synopsis>
492
		<syntax>
492
		<syntax>
493
			<parameter name="domain" required="true" />
493
			<parameter name="domain" required="true" />
494
		</syntax>
494
		</syntax>
495
		<description>
495
		<description>
496
			<para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
496
			<para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
497
			as a local SIP domain that this Asterisk server is configured to handle.
497
			as a local SIP domain that this Asterisk server is configured to handle.
498
			Returns the domain name if it is locally handled, otherwise an empty string.
498
			Returns the domain name if it is locally handled, otherwise an empty string.
499
			Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
499
			Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
500
		</description>
500
		</description>
501
	</function>
501
	</function>
502
	<manager name="SIPpeers" language="en_US">
502
	<manager name="SIPpeers" language="en_US">
503
		<synopsis>
503
		<synopsis>
504
			List SIP peers (text format).
504
			List SIP peers (text format).
505
		</synopsis>
505
		</synopsis>
506
		<syntax>
506
		<syntax>
507
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
507
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
508
		</syntax>
508
		</syntax>
509
		<description>
509
		<description>
510
			<para>Lists SIP peers in text format with details on current status.
510
			<para>Lists SIP peers in text format with details on current status.
511
			<literal>Peerlist</literal> will follow as separate events, followed by a final event called
511
			<literal>Peerlist</literal> will follow as separate events, followed by a final event called
512
			<literal>PeerlistComplete</literal>.</para>
512
			<literal>PeerlistComplete</literal>.</para>
513
		</description>
513
		</description>
514
	</manager>
514
	</manager>
515
	<manager name="SIPshowpeer" language="en_US">
515
	<manager name="SIPshowpeer" language="en_US">
516
		<synopsis>
516
		<synopsis>
517
			show SIP peer (text format).
517
			show SIP peer (text format).
518
		</synopsis>
518
		</synopsis>
519
		<syntax>
519
		<syntax>
520
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
520
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
521
			<parameter name="Peer" required="true">
521
			<parameter name="Peer" required="true">
522
				<para>The peer name you want to check.</para>
522
				<para>The peer name you want to check.</para>
523
			</parameter>
523
			</parameter>
524
		</syntax>
524
		</syntax>
525
		<description>
525
		<description>
526
			<para>Show one SIP peer with details on current status.</para>
526
			<para>Show one SIP peer with details on current status.</para>
527
		</description>
527
		</description>
528
	</manager>
528
	</manager>
529
	<manager name="SIPqualifypeer" language="en_US">
529
	<manager name="SIPqualifypeer" language="en_US">
530
		<synopsis>
530
		<synopsis>
531
			Qualify SIP peers.
531
			Qualify SIP peers.
532
		</synopsis>
532
		</synopsis>
533
		<syntax>
533
		<syntax>
534
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
534
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
535
			<parameter name="Peer" required="true">
535
			<parameter name="Peer" required="true">
536
				<para>The peer name you want to qualify.</para>
536
				<para>The peer name you want to qualify.</para>
537
			</parameter>
537
			</parameter>
538
		</syntax>
538
		</syntax>
539
		<description>
539
		<description>
540
			<para>Qualify a SIP peer.</para>
540
			<para>Qualify a SIP peer.</para>
541
		</description>
541
		</description>
542
	</manager>
542
	</manager>
543
	<manager name="SIPshowregistry" language="en_US">
543
	<manager name="SIPshowregistry" language="en_US">
544
		<synopsis>
544
		<synopsis>
545
			Show SIP registrations (text format).
545
			Show SIP registrations (text format).
546
		</synopsis>
546
		</synopsis>
547
		<syntax>
547
		<syntax>
548
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
548
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
549
		</syntax>
549
		</syntax>
550
		<description>
550
		<description>
551
			<para>Lists all registration requests and status. Registrations will follow as separate
551
			<para>Lists all registration requests and status. Registrations will follow as separate
552
			events followed by a final event called <literal>RegistrationsComplete</literal>.</para>
552
			events followed by a final event called <literal>RegistrationsComplete</literal>.</para>
553
		</description>
553
		</description>
554
	</manager>
554
	</manager>
555
	<manager name="SIPnotify" language="en_US">
555
	<manager name="SIPnotify" language="en_US">
556
		<synopsis>
556
		<synopsis>
557
			Send a SIP notify.
557
			Send a SIP notify.
558
		</synopsis>
558
		</synopsis>
559
		<syntax>
559
		<syntax>
560
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
560
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
561
			<parameter name="Channel" required="true">
561
			<parameter name="Channel" required="true">
562
				<para>Peer to receive the notify.</para>
562
				<para>Peer to receive the notify.</para>
563
			</parameter>
563
			</parameter>
564
			<parameter name="Variable" required="true">
564
			<parameter name="Variable" required="true">
565
				<para>At least one variable pair must be specified.
565
				<para>At least one variable pair must be specified.
566
				<replaceable>name</replaceable>=<replaceable>value</replaceable></para>
566
				<replaceable>name</replaceable>=<replaceable>value</replaceable></para>
567
			</parameter>
567
			</parameter>
568
		</syntax>
568
		</syntax>
569
		<description>
569
		<description>
570
			<para>Sends a SIP Notify event.</para>
570
			<para>Sends a SIP Notify event.</para>
571
			<para>All parameters for this event must be specified in the body of this request
571
			<para>All parameters for this event must be specified in the body of this request
572
			via multiple <literal>Variable: name=value</literal> sequences.</para>
572
			via multiple <literal>Variable: name=value</literal> sequences.</para>
573
		</description>
573
		</description>
574
	</manager>
574
	</manager>
575
 ***/
575
 ***/
576

    
   
576

   
577
static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
577
static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
578
static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
578
static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
579
static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
579
static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
580
static int mwi_expiry = DEFAULT_MWI_EXPIRY;
580
static int mwi_expiry = DEFAULT_MWI_EXPIRY;
581

    
   
581

   
582
static int unauth_sessions = 0;
582
static int unauth_sessions = 0;
583
static int authlimit = DEFAULT_AUTHLIMIT;
583
static int authlimit = DEFAULT_AUTHLIMIT;
584
static int authtimeout = DEFAULT_AUTHTIMEOUT;
584
static int authtimeout = DEFAULT_AUTHTIMEOUT;
585

    
   
585

   
586
/*! \brief Global jitterbuffer configuration - by default, jb is disabled
586
/*! \brief Global jitterbuffer configuration - by default, jb is disabled
587
 *  \note Values shown here match the defaults shown in sip.conf.sample */
587
 *  \note Values shown here match the defaults shown in sip.conf.sample */
588
static struct ast_jb_conf default_jbconf =
588
static struct ast_jb_conf default_jbconf =
589
{
589
{
590
	.flags = 0,
590
	.flags = 0,
591
	.max_size = 200,
591
	.max_size = 200,
592
	.resync_threshold = 1000,
592
	.resync_threshold = 1000,
593
	.impl = "fixed",
593
	.impl = "fixed",
594
	.target_extra = 40,
594
	.target_extra = 40,
595
};
595
};
596
static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
596
static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
597

    
   
597

   
598
static const char config[] = "sip.conf";                /*!< Main configuration file */
598
static const char config[] = "sip.conf";                /*!< Main configuration file */
599
static const char notify_config[] = "sip_notify.conf";  /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
599
static const char notify_config[] = "sip_notify.conf";  /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
600

    
   
600

   
601
/*! \brief Readable descriptions of device states.
601
/*! \brief Readable descriptions of device states.
602
 *  \note Should be aligned to above table as index */
602
 *  \note Should be aligned to above table as index */
603
static const struct invstate2stringtable {
603
static const struct invstate2stringtable {
604
	const enum invitestates state;
604
	const enum invitestates state;
605
	const char *desc;
605
	const char *desc;
606
} invitestate2string[] = {
606
} invitestate2string[] = {
607
	{INV_NONE,              "None"  },
607
	{INV_NONE,              "None"  },
608
	{INV_CALLING,           "Calling (Trying)"},
608
	{INV_CALLING,           "Calling (Trying)"},
609
	{INV_PROCEEDING,        "Proceeding "},
609
	{INV_PROCEEDING,        "Proceeding "},
610
	{INV_EARLY_MEDIA,       "Early media"},
610
	{INV_EARLY_MEDIA,       "Early media"},
611
	{INV_COMPLETED,         "Completed (done)"},
611
	{INV_COMPLETED,         "Completed (done)"},
612
	{INV_CONFIRMED,         "Confirmed (up)"},
612
	{INV_CONFIRMED,         "Confirmed (up)"},
613
	{INV_TERMINATED,        "Done"},
613
	{INV_TERMINATED,        "Done"},
614
	{INV_CANCELLED,         "Cancelled"}
614
	{INV_CANCELLED,         "Cancelled"}
615
};
615
};
616

    
   
616

   
617
/*! \brief Subscription types that we support. We support
617
/*! \brief Subscription types that we support. We support
618
 * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
618
 * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
619
 * - SIMPLE presence used for device status
619
 * - SIMPLE presence used for device status
620
 * - Voicemail notification subscriptions
620
 * - Voicemail notification subscriptions
621
 */
621
 */
622
static const struct cfsubscription_types {
622
static const struct cfsubscription_types {
623
	enum subscriptiontype type;
623
	enum subscriptiontype type;
624
	const char * const event;
624
	const char * const event;
625
	const char * const mediatype;
625
	const char * const mediatype;
626
	const char * const text;
626
	const char * const text;
627
} subscription_types[] = {
627
} subscription_types[] = {
628
	{ NONE,		   "-",        "unknown",	             "unknown" },
628
	{ NONE,		   "-",        "unknown",	             "unknown" },
629
	/* RFC 4235: SIP Dialog event package */
629
	/* RFC 4235: SIP Dialog event package */
630
	{ DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
630
	{ DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
631
	{ CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
631
	{ CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
632
	{ PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
632
	{ PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
633
	{ XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
633
	{ XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
634
	{ MWI_NOTIFICATION,	"message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
634
	{ MWI_NOTIFICATION,	"message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
635
};
635
};
636

    
   
636

   
637
/*! \brief The core structure to setup dialogs. We parse incoming messages by using
637
/*! \brief The core structure to setup dialogs. We parse incoming messages by using
638
 *  structure and then route the messages according to the type.
638
 *  structure and then route the messages according to the type.
639
 *
639
 *
640
 *  \note Note that sip_methods[i].id == i must hold or the code breaks
640
 *  \note Note that sip_methods[i].id == i must hold or the code breaks
641
 */
641
 */
642
static const struct  cfsip_methods {
642
static const struct  cfsip_methods {
643
	enum sipmethod id;
643
	enum sipmethod id;
644
	int need_rtp;		/*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
644
	int need_rtp;		/*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
645
	char * const text;
645
	char * const text;
646
	enum can_create_dialog can_create;
646
	enum can_create_dialog can_create;
647
} sip_methods[] = {
647
} sip_methods[] = {
648
	{ SIP_UNKNOWN,   RTP,    "-UNKNOWN-",CAN_CREATE_DIALOG },
648
	{ SIP_UNKNOWN,   RTP,    "-UNKNOWN-",CAN_CREATE_DIALOG },
649
	{ SIP_RESPONSE,  NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
649
	{ SIP_RESPONSE,  NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
650
	{ SIP_REGISTER,  NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
650
	{ SIP_REGISTER,  NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
651
	{ SIP_OPTIONS,   NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
651
	{ SIP_OPTIONS,   NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
652
	{ SIP_NOTIFY,    NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
652
	{ SIP_NOTIFY,    NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
653
	{ SIP_INVITE,    RTP,    "INVITE",   CAN_CREATE_DIALOG },
653
	{ SIP_INVITE,    RTP,    "INVITE",   CAN_CREATE_DIALOG },
654
	{ SIP_ACK,       NO_RTP, "ACK",      CAN_NOT_CREATE_DIALOG },
654
	{ SIP_ACK,       NO_RTP, "ACK",      CAN_NOT_CREATE_DIALOG },
655
	{ SIP_PRACK,     NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
655
	{ SIP_PRACK,     NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
656
	{ SIP_BYE,       NO_RTP, "BYE",      CAN_NOT_CREATE_DIALOG },
656
	{ SIP_BYE,       NO_RTP, "BYE",      CAN_NOT_CREATE_DIALOG },
657
	{ SIP_REFER,     NO_RTP, "REFER",    CAN_CREATE_DIALOG },
657
	{ SIP_REFER,     NO_RTP, "REFER",    CAN_CREATE_DIALOG },
658
	{ SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
658
	{ SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
659
	{ SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
659
	{ SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
660
	{ SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
660
	{ SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
661
	{ SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
661
	{ SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
662
	{ SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
662
	{ SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
663
	{ SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
663
	{ SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
664
	{ SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
664
	{ SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
665
};
665
};
666

    
   
666

   
667
/*! \brief Diversion header reasons
667
/*! \brief Diversion header reasons
668
 *
668
 *
669
 * The core defines a bunch of constants used to define
669
 * The core defines a bunch of constants used to define
670
 * redirecting reasons. This provides a translation table
670
 * redirecting reasons. This provides a translation table
671
 * between those and the strings which may be present in
671
 * between those and the strings which may be present in
672
 * a SIP Diversion header
672
 * a SIP Diversion header
673
 */
673
 */
674
static const struct sip_reasons {
674
static const struct sip_reasons {
675
	enum AST_REDIRECTING_REASON code;
675
	enum AST_REDIRECTING_REASON code;
676
	char * const text;
676
	char * const text;
677
} sip_reason_table[] = {
677
} sip_reason_table[] = {
678
	{ AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
678
	{ AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
679
	{ AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
679
	{ AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
680
	{ AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
680
	{ AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
681
	{ AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
681
	{ AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
682
	{ AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
682
	{ AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
683
	{ AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
683
	{ AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
684
	{ AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
684
	{ AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
685
	{ AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
685
	{ AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
686
	{ AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
686
	{ AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
687
	{ AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
687
	{ AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
688
	{ AST_REDIRECTING_REASON_AWAY, "away" },
688
	{ AST_REDIRECTING_REASON_AWAY, "away" },
689
	{ AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"},
689
	{ AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"},
690
	{ AST_REDIRECTING_REASON_SEND_TO_VM, "send_to_vm"},
690
	{ AST_REDIRECTING_REASON_SEND_TO_VM, "send_to_vm"},
691
};
691
};
692

    
   
692

   
693

    
   
693

   
694
/*! \name DefaultSettings
694
/*! \name DefaultSettings
695
	Default setttings are used as a channel setting and as a default when
695
	Default setttings are used as a channel setting and as a default when
696
	configuring devices
696
	configuring devices
697
*/
697
*/
698
/*@{*/
698
/*@{*/
699
static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
699
static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
700
static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
700
static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
701
static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
701
static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
702
static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
702
static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
703
static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
703
static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
704
static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
704
static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
705
static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
705
static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
706
static int default_qualify;                        /*!< Default Qualify= setting */
706
static int default_qualify;                        /*!< Default Qualify= setting */
707
static int default_keepalive;                      /*!< Default keepalive= setting */
707
static int default_keepalive;                      /*!< Default keepalive= setting */
708
static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
708
static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
709
static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
709
static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
710
                                                    *   a bridged channel on hold */
710
                                                    *   a bridged channel on hold */
711
static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
711
static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
712
static char default_engine[256];                   /*!< Default RTP engine */
712
static char default_engine[256];                   /*!< Default RTP engine */
713
static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
713
static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
714
static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
714
static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
715
static char default_zone[MAX_TONEZONE_COUNTRY];        /*!< Default tone zone for channels created from the SIP driver */
715
static char default_zone[MAX_TONEZONE_COUNTRY];        /*!< Default tone zone for channels created from the SIP driver */
716
static unsigned int default_transports;            /*!< Default Transports (enum sip_transport) that are acceptable */
716
static unsigned int default_transports;            /*!< Default Transports (enum sip_transport) that are acceptable */
717
static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
717
static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
718
/*@}*/
718
/*@}*/
719

    
   
719

   
720
static struct sip_settings sip_cfg;		/*!< SIP configuration data.
720
static struct sip_settings sip_cfg;		/*!< SIP configuration data.
721
					\note in the future we could have multiple of these (per domain, per device group etc) */
721
					\note in the future we could have multiple of these (per domain, per device group etc) */
722

    
   
722

   
723
/*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
723
/*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
724
#define SIP_PEDANTIC_DECODE(str)	\
724
#define SIP_PEDANTIC_DECODE(str)	\
725
	if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) {	\
725
	if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) {	\
726
		ast_uri_decode(str, ast_uri_sip_user);	\
726
		ast_uri_decode(str, ast_uri_sip_user);	\
727
	}	\
727
	}	\
728

    
   
728

   
729
static unsigned int chan_idx;       /*!< used in naming sip channel */
729
static unsigned int chan_idx;       /*!< used in naming sip channel */
730
static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
730
static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
731

    
   
731

   
732
static int global_relaxdtmf;        /*!< Relax DTMF */
732
static int global_relaxdtmf;        /*!< Relax DTMF */
733
static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
733
static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
734
static int global_rtptimeout;       /*!< Time out call if no RTP */
734
static int global_rtptimeout;       /*!< Time out call if no RTP */
735
static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
735
static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
736
static int global_rtpkeepalive;     /*!< Send RTP keepalives */
736
static int global_rtpkeepalive;     /*!< Send RTP keepalives */
737
static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
737
static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
738
static int global_regattempts_max;  /*!< Registration attempts before giving up */
738
static int global_regattempts_max;  /*!< Registration attempts before giving up */
739
static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
739
static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
740
static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
740
static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
741
                                     *   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
741
                                     *   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
742
                                     *   with just a boolean flag in the device structure */
742
                                     *   with just a boolean flag in the device structure */
743
static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
743
static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
744
static unsigned int global_tos_audio;    /*!< IP type of service for audio RTP packets */
744
static unsigned int global_tos_audio;    /*!< IP type of service for audio RTP packets */
745
static unsigned int global_tos_video;    /*!< IP type of service for video RTP packets */
745
static unsigned int global_tos_video;    /*!< IP type of service for video RTP packets */
746
static unsigned int global_tos_text;     /*!< IP type of service for text RTP packets */
746
static unsigned int global_tos_text;     /*!< IP type of service for text RTP packets */
747
static unsigned int global_cos_sip;      /*!< 802.1p class of service for SIP packets */
747
static unsigned int global_cos_sip;      /*!< 802.1p class of service for SIP packets */
748
static unsigned int global_cos_audio;    /*!< 802.1p class of service for audio RTP packets */
748
static unsigned int global_cos_audio;    /*!< 802.1p class of service for audio RTP packets */
749
static unsigned int global_cos_video;    /*!< 802.1p class of service for video RTP packets */
749
static unsigned int global_cos_video;    /*!< 802.1p class of service for video RTP packets */
750
static unsigned int global_cos_text;     /*!< 802.1p class of service for text RTP packets */
750
static unsigned int global_cos_text;     /*!< 802.1p class of service for text RTP packets */
751
static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
751
static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
752
static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
752
static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
753
static char global_useragent[AST_MAX_EXTENSION];    /*!< Useragent for the SIP channel */
753
static char global_useragent[AST_MAX_EXTENSION];    /*!< Useragent for the SIP channel */
754
static char global_sdpsession[AST_MAX_EXTENSION];   /*!< SDP session name for the SIP channel */
754
static char global_sdpsession[AST_MAX_EXTENSION];   /*!< SDP session name for the SIP channel */
755
static char global_sdpowner[AST_MAX_EXTENSION];     /*!< SDP owner name for the SIP channel */
755
static char global_sdpowner[AST_MAX_EXTENSION];     /*!< SDP owner name for the SIP channel */
756
static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
756
static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
757
static int global_t1;           /*!< T1 time */
757
static int global_t1;           /*!< T1 time */
758
static int global_t1min;        /*!< T1 roundtrip time minimum */
758
static int global_t1min;        /*!< T1 roundtrip time minimum */
759
static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
759
static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
760
static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
760
static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
761
static int global_qualifyfreq;          /*!< Qualify frequency */
761
static int global_qualifyfreq;          /*!< Qualify frequency */
762
static int global_qualify_gap;          /*!< Time between our group of peer pokes */
762
static int global_qualify_gap;          /*!< Time between our group of peer pokes */
763
static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
763
static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
764

    
   
764

   
765
static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
765
static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
766
static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
766
static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
767
static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
767
static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
768
static int global_max_se;                     /*!< Highest threshold for session refresh interval */
768
static int global_max_se;                     /*!< Highest threshold for session refresh interval */
769

    
   
769

   
770
static int global_store_sip_cause;    /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
770
static int global_store_sip_cause;    /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
771

    
   
771

   
772
static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
772
static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
773
/*@}*/
773
/*@}*/
774

    
   
774

   
775
/*!
775
/*!
776
 * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
776
 * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
777
 * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
777
 * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
778
 * event package. This variable is set at module load time and may be checked at runtime to determine
778
 * event package. This variable is set at module load time and may be checked at runtime to determine
779
 * if XML parsing support was found.
779
 * if XML parsing support was found.
780
 */
780
 */
781
static int can_parse_xml;
781
static int can_parse_xml;
782

    
   
782

   
783
/*! \name Object counters @{
783
/*! \name Object counters @{
784
 *  \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
784
 *  \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
785
 *  should be used to modify these values. */
785
 *  should be used to modify these values. */
786
static int speerobjs = 0;     /*!< Static peers */
786
static int speerobjs = 0;     /*!< Static peers */
787
static int rpeerobjs = 0;     /*!< Realtime peers */
787
static int rpeerobjs = 0;     /*!< Realtime peers */
788
static int apeerobjs = 0;     /*!< Autocreated peer objects */
788
static int apeerobjs = 0;     /*!< Autocreated peer objects */
789
static int regobjs = 0;       /*!< Registry objects */
789
static int regobjs = 0;       /*!< Registry objects */
790
/* }@ */
790
/* }@ */
791

    
   
791

   
792
static struct ast_flags global_flags[3] = {{0}};  /*!< global SIP_ flags */
792
static struct ast_flags global_flags[3] = {{0}};  /*!< global SIP_ flags */
793
static int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
793
static int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
794

    
   
794

   
795
static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
795
static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
796
static int network_change_event_sched_id = -1;
796
static int network_change_event_sched_id = -1;
797

    
   
797

   
798
static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
798
static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
799

    
   
799

   
800
AST_MUTEX_DEFINE_STATIC(netlock);
800
AST_MUTEX_DEFINE_STATIC(netlock);
801

    
   
801

   
802
/*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
802
/*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
803
   when it's doing something critical. */
803
   when it's doing something critical. */
804
AST_MUTEX_DEFINE_STATIC(monlock);
804
AST_MUTEX_DEFINE_STATIC(monlock);
805

    
   
805

   
806
AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
806
AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
807

    
   
807

   
808
/*! \brief This is the thread for the monitor which checks for input on the channels
808
/*! \brief This is the thread for the monitor which checks for input on the channels
809
   which are not currently in use.  */
809
   which are not currently in use.  */
810
static pthread_t monitor_thread = AST_PTHREADT_NULL;
810
static pthread_t monitor_thread = AST_PTHREADT_NULL;
811

    
   
811

   
812
static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
812
static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
813
static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
813
static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
814

    
   
814

   
815
struct ast_sched_context *sched;     /*!< The scheduling context */
815
struct ast_sched_context *sched;     /*!< The scheduling context */
816
static struct io_context *io;           /*!< The IO context */
816
static struct io_context *io;           /*!< The IO context */
817
static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
817
static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
818
struct sip_pkt;
818
struct sip_pkt;
819
static AST_LIST_HEAD_STATIC(domain_list, domain);    /*!< The SIP domain list */
819
static AST_LIST_HEAD_STATIC(domain_list, domain);    /*!< The SIP domain list */
820

    
   
820

   
821
AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
821
AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
822

    
   
822

   
823
static enum sip_debug_e sipdebug;
823
static enum sip_debug_e sipdebug;
824

    
   
824

   
825
/*! \brief extra debugging for 'text' related events.
825
/*! \brief extra debugging for 'text' related events.
826
 *  At the moment this is set together with sip_debug_console.
826
 *  At the moment this is set together with sip_debug_console.
827
 *  \note It should either go away or be implemented properly.
827
 *  \note It should either go away or be implemented properly.
828
 */
828
 */
829
static int sipdebug_text;
829
static int sipdebug_text;
830

    
   
830

   
831
static const struct _map_x_s referstatusstrings[] = {
831
static const struct _map_x_s referstatusstrings[] = {
832
	{ REFER_IDLE,      "<none>" },
832
	{ REFER_IDLE,      "<none>" },
833
	{ REFER_SENT,      "Request sent" },
833
	{ REFER_SENT,      "Request sent" },
834
	{ REFER_RECEIVED,  "Request received" },
834
	{ REFER_RECEIVED,  "Request received" },
835
	{ REFER_CONFIRMED, "Confirmed" },
835
	{ REFER_CONFIRMED, "Confirmed" },
836
	{ REFER_ACCEPTED,  "Accepted" },
836
	{ REFER_ACCEPTED,  "Accepted" },
837
	{ REFER_RINGING,   "Target ringing" },
837
	{ REFER_RINGING,   "Target ringing" },
838
	{ REFER_200OK,     "Done" },
838
	{ REFER_200OK,     "Done" },
839
	{ REFER_FAILED,    "Failed" },
839
	{ REFER_FAILED,    "Failed" },
840
	{ REFER_NOAUTH,    "Failed - auth failure" },
840
	{ REFER_NOAUTH,    "Failed - auth failure" },
841
	{ -1,               NULL} /* terminator */
841
	{ -1,               NULL} /* terminator */
842
};
842
};
843

    
   
843

   
844
/* --- Hash tables of various objects --------*/
844
/* --- Hash tables of various objects --------*/
845
#ifdef LOW_MEMORY
845
#ifdef LOW_MEMORY
846
static const int HASH_PEER_SIZE = 17;
846
static const int HASH_PEER_SIZE = 17;
847
static const int HASH_DIALOG_SIZE = 17;
847
static const int HASH_DIALOG_SIZE = 17;
848
#else
848
#else
849
static const int HASH_PEER_SIZE = 563;	/*!< Size of peer hash table, prime number preferred! */
849
static const int HASH_PEER_SIZE = 563;	/*!< Size of peer hash table, prime number preferred! */
850
static const int HASH_DIALOG_SIZE = 563;
850
static const int HASH_DIALOG_SIZE = 563;
851
#endif
851
#endif
852

    
   
852

   
853
static const struct {
853
static const struct {
854
	enum ast_cc_service_type service;
854
	enum ast_cc_service_type service;
855
	const char *service_string;
855
	const char *service_string;
856
} sip_cc_service_map [] = {
856
} sip_cc_service_map [] = {
857
	[AST_CC_NONE] = { AST_CC_NONE, "" },
857
	[AST_CC_NONE] = { AST_CC_NONE, "" },
858
	[AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
858
	[AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
859
	[AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
859
	[AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
860
	[AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
860
	[AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
861
};
861
};
862

    
   
862

   
863
static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
863
static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
864
{
864
{
865
	enum ast_cc_service_type service;
865
	enum ast_cc_service_type service;
866
	for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
866
	for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
867
		if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
867
		if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
868
			return service;
868
			return service;
869
		}
869
		}
870
	}
870
	}
871
	return AST_CC_NONE;
871
	return AST_CC_NONE;
872
}
872
}
873

    
   
873

   
874
static const struct {
874
static const struct {
875
	enum sip_cc_notify_state state;
875
	enum sip_cc_notify_state state;
876
	const char *state_string;
876
	const char *state_string;
877
} sip_cc_notify_state_map [] = {
877
} sip_cc_notify_state_map [] = {
878
	[CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
878
	[CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
879
	[CC_READY] = {CC_READY, "cc-state: ready"},
879
	[CC_READY] = {CC_READY, "cc-state: ready"},
880
};
880
};
881

    
   
881

   
882
AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
882
AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
883

    
   
883

   
884
static int sip_epa_register(const struct epa_static_data *static_data)
884
static int sip_epa_register(const struct epa_static_data *static_data)
885
{
885
{
886
	struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
886
	struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
887

    
   
887

   
888
	if (!backend) {
888
	if (!backend) {
889
		return -1;
889
		return -1;
890
	}
890
	}
891

    
   
891

   
892
	backend->static_data = static_data;
892
	backend->static_data = static_data;
893

    
   
893

   
894
	AST_LIST_LOCK(&epa_static_data_list);
894
	AST_LIST_LOCK(&epa_static_data_list);
895
	AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
895
	AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
896
	AST_LIST_UNLOCK(&epa_static_data_list);
896
	AST_LIST_UNLOCK(&epa_static_data_list);
897
	return 0;
897
	return 0;
898
}
898
}
899

    
   
899

   
900
static void sip_epa_unregister_all(void)
900
static void sip_epa_unregister_all(void)
901
{
901
{
902
	struct epa_backend *backend;
902
	struct epa_backend *backend;
903

    
   
903

   
904
	AST_LIST_LOCK(&epa_static_data_list);
904
	AST_LIST_LOCK(&epa_static_data_list);
905
	while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
905
	while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
906
		ast_free(backend);
906
		ast_free(backend);
907
	}
907
	}
908
	AST_LIST_UNLOCK(&epa_static_data_list);
908
	AST_LIST_UNLOCK(&epa_static_data_list);
909
}
909
}
910

    
   
910

   
911
static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
911
static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
912

    
   
912

   
913
static void cc_epa_destructor(void *data)
913
static void cc_epa_destructor(void *data)
914
{
914
{
915
	struct sip_epa_entry *epa_entry = data;
915
	struct sip_epa_entry *epa_entry = data;
916
	struct cc_epa_entry *cc_entry = epa_entry->instance_data;
916
	struct cc_epa_entry *cc_entry = epa_entry->instance_data;
917
	ast_free(cc_entry);
917
	ast_free(cc_entry);
918
}
918
}
919

    
   
919

   
920
static const struct epa_static_data cc_epa_static_data  = {
920
static const struct epa_static_data cc_epa_static_data  = {
921
	.event = CALL_COMPLETION,
921
	.event = CALL_COMPLETION,
922
	.name = "call-completion",
922
	.name = "call-completion",
923
	.handle_error = cc_handle_publish_error,
923
	.handle_error = cc_handle_publish_error,
924
	.destructor = cc_epa_destructor,
924
	.destructor = cc_epa_destructor,
925
};
925
};
926

    
   
926

   
927
static const struct epa_static_data *find_static_data(const char * const event_package)
927
static const struct epa_static_data *find_static_data(const char * const event_package)
928
{
928
{
929
	const struct epa_backend *backend = NULL;
929
	const struct epa_backend *backend = NULL;
930

    
   
930

   
931
	AST_LIST_LOCK(&epa_static_data_list);
931
	AST_LIST_LOCK(&epa_static_data_list);
932
	AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
932
	AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
933
		if (!strcmp(backend->static_data->name, event_package)) {
933
		if (!strcmp(backend->static_data->name, event_package)) {
934
			break;
934
			break;
935
		}
935
		}
936
	}
936
	}
937
	AST_LIST_UNLOCK(&epa_static_data_list);
937
	AST_LIST_UNLOCK(&epa_static_data_list);
938
	return backend ? backend->static_data : NULL;
938
	return backend ? backend->static_data : NULL;
939
}
939
}
940

    
   
940

   
941
static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
941
static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
942
{
942
{
943
	struct sip_epa_entry *epa_entry;
943
	struct sip_epa_entry *epa_entry;
944
	const struct epa_static_data *static_data;
944
	const struct epa_static_data *static_data;
945

    
   
945

   
946
	if (!(static_data = find_static_data(event_package))) {
946
	if (!(static_data = find_static_data(event_package))) {
947
		return NULL;
947
		return NULL;
948
	}
948
	}
949

    
   
949

   
950
	if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
950
	if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
951
		return NULL;
951
		return NULL;
952
	}
952
	}
953

    
   
953

   
954
	epa_entry->static_data = static_data;
954
	epa_entry->static_data = static_data;
955
	ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
955
	ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
956
	return epa_entry;
956
	return epa_entry;
957
}
957
}
958

    
   
958

   
959
/*!
959
/*!
960
 * Used to create new entity IDs by ESCs.
960
 * Used to create new entity IDs by ESCs.
961
 */
961
 */
962
static int esc_etag_counter;
962
static int esc_etag_counter;
963
static const int DEFAULT_PUBLISH_EXPIRES = 3600;
963
static const int DEFAULT_PUBLISH_EXPIRES = 3600;
964

    
   
964

   
965
#ifdef HAVE_LIBXML2
965
#ifdef HAVE_LIBXML2
966
static int cc_esc_publish_handler(struct sip_pvt *pvt, struct sip_request *req, struct event_state_compositor *esc, struct sip_esc_entry *esc_entry);
966
static int cc_esc_publish_handler(struct sip_pvt *pvt, struct sip_request *req, struct event_state_compositor *esc, struct sip_esc_entry *esc_entry);
967

    
   
967

   
968
static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
968
static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
969
	.initial_handler = cc_esc_publish_handler,
969
	.initial_handler = cc_esc_publish_handler,
970
	.modify_handler = cc_esc_publish_handler,
970
	.modify_handler = cc_esc_publish_handler,
971
};
971
};
972
#endif
972
#endif
973

    
   
973

   
974
/*!
974
/*!
975
 * \brief The Event State Compositors
975
 * \brief The Event State Compositors
976
 *
976
 *
977
 * An Event State Compositor is an entity which
977
 * An Event State Compositor is an entity which
978
 * accepts PUBLISH requests and acts appropriately
978
 * accepts PUBLISH requests and acts appropriately
979
 * based on these requests.
979
 * based on these requests.
980
 *
980
 *
981
 * The actual event_state_compositor structure is simply
981
 * The actual event_state_compositor structure is simply
982
 * an ao2_container of sip_esc_entrys. When an incoming
982
 * an ao2_container of sip_esc_entrys. When an incoming
983
 * PUBLISH is received, we can match the appropriate sip_esc_entry
983
 * PUBLISH is received, we can match the appropriate sip_esc_entry
984
 * using the entity ID of the incoming PUBLISH.
984
 * using the entity ID of the incoming PUBLISH.
985
 */
985
 */
986
static struct event_state_compositor {
986
static struct event_state_compositor {
987
	enum subscriptiontype event;
987
	enum subscriptiontype event;
988
	const char * name;
988
	const char * name;
989
	const struct sip_esc_publish_callbacks *callbacks;
989
	const struct sip_esc_publish_callbacks *callbacks;
990
	struct ao2_container *compositor;
990
	struct ao2_container *compositor;
991
} event_state_compositors [] = {
991
} event_state_compositors [] = {
992
#ifdef HAVE_LIBXML2
992
#ifdef HAVE_LIBXML2
993
	{CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
993
	{CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
994
#endif
994
#endif
995
};
995
};
996

    
   
996

   
997
static const int ESC_MAX_BUCKETS = 37;
997
static const int ESC_MAX_BUCKETS = 37;
998

    
   
998

   
999
static void esc_entry_destructor(void *obj)
999
static void esc_entry_destructor(void *obj)
1000
{
1000
{
1001
	struct sip_esc_entry *esc_entry = obj;
1001
	struct sip_esc_entry *esc_entry = obj;
1002
	if (esc_entry->sched_id > -1) {
1002
	if (esc_entry->sched_id > -1) {
1003
		AST_SCHED_DEL(sched, esc_entry->sched_id);
1003
		AST_SCHED_DEL(sched, esc_entry->sched_id);
1004
	}
1004
	}
1005
}
1005
}
1006

    
   
1006

   
1007
static int esc_hash_fn(const void *obj, const int flags)
1007
static int esc_hash_fn(const void *obj, const int flags)
1008
{
1008
{
1009
	const struct sip_esc_entry *entry = obj;
1009
	const struct sip_esc_entry *entry = obj;
1010
	return ast_str_hash(entry->entity_tag);
1010
	return ast_str_hash(entry->entity_tag);
1011
}
1011
}
1012

    
   
1012

   
1013
static int esc_cmp_fn(void *obj, void *arg, int flags)
1013
static int esc_cmp_fn(void *obj, void *arg, int flags)
1014
{
1014
{
1015
	struct sip_esc_entry *entry1 = obj;
1015
	struct sip_esc_entry *entry1 = obj;
1016
	struct sip_esc_entry *entry2 = arg;
1016
	struct sip_esc_entry *entry2 = arg;
1017

    
   
1017

   
1018
	return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
1018
	return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
1019
}
1019
}
1020

    
   
1020

   
1021
static struct event_state_compositor *get_esc(const char * const event_package) {
1021
static struct event_state_compositor *get_esc(const char * const event_package) {
1022
	int i;
1022
	int i;
1023
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1023
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1024
		if (!strcasecmp(event_package, event_state_compositors[i].name)) {
1024
		if (!strcasecmp(event_package, event_state_compositors[i].name)) {
1025
			return &event_state_compositors[i];
1025
			return &event_state_compositors[i];
1026
		}
1026
		}
1027
	}
1027
	}
1028
	return NULL;
1028
	return NULL;
1029
}
1029
}
1030

    
   
1030

   
1031
static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
1031
static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
1032
	struct sip_esc_entry *entry;
1032
	struct sip_esc_entry *entry;
1033
	struct sip_esc_entry finder;
1033
	struct sip_esc_entry finder;
1034

    
   
1034

   
1035
	ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
1035
	ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
1036

    
   
1036

   
1037
	entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
1037
	entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
1038

    
   
1038

   
1039
	return entry;
1039
	return entry;
1040
}
1040
}
1041

    
   
1041

   
1042
static int publish_expire(const void *data)
1042
static int publish_expire(const void *data)
1043
{
1043
{
1044
	struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
1044
	struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
1045
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1045
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1046

    
   
1046

   
1047
	ast_assert(esc != NULL);
1047
	ast_assert(esc != NULL);
1048

    
   
1048

   
1049
	ao2_unlink(esc->compositor, esc_entry);
1049
	ao2_unlink(esc->compositor, esc_entry);
1050
	ao2_ref(esc_entry, -1);
1050
	ao2_ref(esc_entry, -1);
1051
	return 0;
1051
	return 0;
1052
}
1052
}
1053

    
   
1053

   
1054
static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
1054
static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
1055
{
1055
{
1056
	int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
1056
	int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
1057
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1057
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1058

    
   
1058

   
1059
	ast_assert(esc != NULL);
1059
	ast_assert(esc != NULL);
1060
	if (is_linked) {
1060
	if (is_linked) {
1061
		ao2_unlink(esc->compositor, esc_entry);
1061
		ao2_unlink(esc->compositor, esc_entry);
1062
	}
1062
	}
1063
	snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
1063
	snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
1064
	ao2_link(esc->compositor, esc_entry);
1064
	ao2_link(esc->compositor, esc_entry);
1065
}
1065
}
1066

    
   
1066

   
1067
static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
1067
static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
1068
{
1068
{
1069
	struct sip_esc_entry *esc_entry;
1069
	struct sip_esc_entry *esc_entry;
1070
	int expires_ms;
1070
	int expires_ms;
1071

    
   
1071

   
1072
	if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
1072
	if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
1073
		return NULL;
1073
		return NULL;
1074
	}
1074
	}
1075

    
   
1075

   
1076
	esc_entry->event = esc->name;
1076
	esc_entry->event = esc->name;
1077

    
   
1077

   
1078
	expires_ms = expires * 1000;
1078
	expires_ms = expires * 1000;
1079
	/* Bump refcount for scheduler */
1079
	/* Bump refcount for scheduler */
1080
	ao2_ref(esc_entry, +1);
1080
	ao2_ref(esc_entry, +1);
1081
	esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
1081
	esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
1082

    
   
1082

   
1083
	/* Note: This links the esc_entry into the ESC properly */
1083
	/* Note: This links the esc_entry into the ESC properly */
1084
	create_new_sip_etag(esc_entry, 0);
1084
	create_new_sip_etag(esc_entry, 0);
1085

    
   
1085

   
1086
	return esc_entry;
1086
	return esc_entry;
1087
}
1087
}
1088

    
   
1088

   
1089
static int initialize_escs(void)
1089
static int initialize_escs(void)
1090
{
1090
{
1091
	int i, res = 0;
1091
	int i, res = 0;
1092
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1092
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1093
		if (!((event_state_compositors[i].compositor) =
1093
		if (!((event_state_compositors[i].compositor) =
1094
					ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
1094
					ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
1095
			res = -1;
1095
			res = -1;
1096
		}
1096
		}
1097
	}
1097
	}
1098
	return res;
1098
	return res;
1099
}
1099
}
1100

    
   
1100

   
1101
static void destroy_escs(void)
1101
static void destroy_escs(void)
1102
{
1102
{
1103
	int i;
1103
	int i;
1104
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1104
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1105
		ao2_ref(event_state_compositors[i].compositor, -1);
1105
		ao2_ref(event_state_compositors[i].compositor, -1);
1106
	}
1106
	}
1107
}
1107
}
1108

    
   
1108

   
1109
struct state_notify_data {
1109
struct state_notify_data {
1110
	int state;
1110
	int state;
1111
	int presence_state;
1111
	int presence_state;
1112
	const char *presence_subtype;
1112
	const char *presence_subtype;
1113
	const char *presence_message;
1113
	const char *presence_message;
1114
};
1114
};
1115

    
   
1115

   
1116
/*!
1116
/*!
1117
 * \details
1117
 * \details
1118
 * Here we implement the container for dialogs which are in the
1118
 * Here we implement the container for dialogs which are in the
1119
 * dialog_needdestroy state to iterate only through the dialogs
1119
 * dialog_needdestroy state to iterate only through the dialogs
1120
 * unlink them instead of iterate through all dialogs
1120
 * unlink them instead of iterate through all dialogs
1121
 */
1121
 */
1122
struct ao2_container *dialogs_needdestroy;
1122
struct ao2_container *dialogs_needdestroy;
1123

    
   
1123

   
1124
/*!
1124
/*!
1125
 * \details
1125
 * \details
1126
 * Here we implement the container for dialogs which have rtp
1126
 * Here we implement the container for dialogs which have rtp
1127
 * traffic and rtptimeout, rtpholdtimeout or rtpkeepalive
1127
 * traffic and rtptimeout, rtpholdtimeout or rtpkeepalive
1128
 * set. We use this container instead the whole dialog list.
1128
 * set. We use this container instead the whole dialog list.
1129
 */
1129
 */
1130
struct ao2_container *dialogs_rtpcheck;
1130
struct ao2_container *dialogs_rtpcheck;
1131

    
   
1131

   
1132
/*!
1132
/*!
1133
 * \details
1133
 * \details
1134
 * Here we implement the container for dialogs (sip_pvt), defining
1134
 * Here we implement the container for dialogs (sip_pvt), defining
1135
 * generic wrapper functions to ease the transition from the current
1135
 * generic wrapper functions to ease the transition from the current
1136
 * implementation (a single linked list) to a different container.
1136
 * implementation (a single linked list) to a different container.
1137
 * In addition to a reference to the container, we need functions to lock/unlock
1137
 * In addition to a reference to the container, we need functions to lock/unlock
1138
 * the container and individual items, and functions to add/remove
1138
 * the container and individual items, and functions to add/remove
1139
 * references to the individual items.
1139
 * references to the individual items.
1140
 */
1140
 */
1141
static struct ao2_container *dialogs;
1141
static struct ao2_container *dialogs;
1142
#define sip_pvt_lock(x) ao2_lock(x)
1142
#define sip_pvt_lock(x) ao2_lock(x)
1143
#define sip_pvt_trylock(x) ao2_trylock(x)
1143
#define sip_pvt_trylock(x) ao2_trylock(x)
1144
#define sip_pvt_unlock(x) ao2_unlock(x)
1144
#define sip_pvt_unlock(x) ao2_unlock(x)
1145

    
   
1145

   
1146
/*! \brief  The table of TCP threads */
1146
/*! \brief  The table of TCP threads */
1147
static struct ao2_container *threadt;
1147
static struct ao2_container *threadt;
1148

    
   
1148

   
1149
/*! \brief  The peer list: Users, Peers and Friends */
1149
/*! \brief  The peer list: Users, Peers and Friends */
1150
static struct ao2_container *peers;
1150
static struct ao2_container *peers;
1151
static struct ao2_container *peers_by_ip;
1151
static struct ao2_container *peers_by_ip;
1152

    
   
1152

   
1153
/*! \brief  The register list: Other SIP proxies we register with and receive calls from */
1153
/*! \brief  The register list: Other SIP proxies we register with and receive calls from */
1154
static struct ast_register_list {
1154
static struct ast_register_list {
1155
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1155
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1156
	int recheck;
1156
	int recheck;
1157
} regl;
1157
} regl;
1158

    
   
1158

   
1159
/*! \brief  The MWI subscription list */
1159
/*! \brief  The MWI subscription list */
1160
static struct ast_subscription_mwi_list {
1160
static struct ast_subscription_mwi_list {
1161
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
1161
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
1162
} submwil;
1162
} submwil;
1163
static int temp_pvt_init(void *);
1163
static int temp_pvt_init(void *);
1164
static void temp_pvt_cleanup(void *);
1164
static void temp_pvt_cleanup(void *);
1165

    
   
1165

   
1166
/*! \brief A per-thread temporary pvt structure */
1166
/*! \brief A per-thread temporary pvt structure */
1167
AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1167
AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1168

    
   
1168

   
1169
/*! \brief A per-thread buffer for transport to string conversion */
1169
/*! \brief A per-thread buffer for transport to string conversion */
1170
AST_THREADSTORAGE(sip_transport_str_buf);
1170
AST_THREADSTORAGE(sip_transport_str_buf);
1171

    
   
1171

   
1172
/*! \brief Size of the SIP transport buffer */
1172
/*! \brief Size of the SIP transport buffer */
1173
#define SIP_TRANSPORT_STR_BUFSIZE 128
1173
#define SIP_TRANSPORT_STR_BUFSIZE 128
1174

    
   
1174

   
1175
/*! \brief Authentication container for realm authentication */
1175
/*! \brief Authentication container for realm authentication */
1176
static struct sip_auth_container *authl = NULL;
1176
static struct sip_auth_container *authl = NULL;
1177
/*! \brief Global authentication container protection while adjusting the references. */
1177
/*! \brief Global authentication container protection while adjusting the references. */
1178
AST_MUTEX_DEFINE_STATIC(authl_lock);
1178
AST_MUTEX_DEFINE_STATIC(authl_lock);
1179

    
   
1179

   
1180
/* --- Sockets and networking --------------*/
1180
/* --- Sockets and networking --------------*/
1181

    
   
1181

   
1182
/*! \brief Main socket for UDP SIP communication.
1182
/*! \brief Main socket for UDP SIP communication.
1183
 *
1183
 *
1184
 * sipsock is shared between the SIP manager thread (which handles reload
1184
 * sipsock is shared between the SIP manager thread (which handles reload
1185
 * requests), the udp io handler (sipsock_read()) and the user routines that
1185
 * requests), the udp io handler (sipsock_read()) and the user routines that
1186
 * issue udp writes (using __sip_xmit()).
1186
 * issue udp writes (using __sip_xmit()).
1187
 * The socket is -1 only when opening fails (this is a permanent condition),
1187
 * The socket is -1 only when opening fails (this is a permanent condition),
1188
 * or when we are handling a reload() that changes its address (this is
1188
 * or when we are handling a reload() that changes its address (this is
1189
 * a transient situation during which we might have a harmless race, see
1189
 * a transient situation during which we might have a harmless race, see
1190
 * below). Because the conditions for the race to be possible are extremely
1190
 * below). Because the conditions for the race to be possible are extremely
1191
 * rare, we don't want to pay the cost of locking on every I/O.
1191
 * rare, we don't want to pay the cost of locking on every I/O.
1192
 * Rather, we remember that when the race may occur, communication is
1192
 * Rather, we remember that when the race may occur, communication is
1193
 * bound to fail anyways, so we just live with this event and let
1193
 * bound to fail anyways, so we just live with this event and let
1194
 * the protocol handle this above us.
1194
 * the protocol handle this above us.
1195
 */
1195
 */
1196
static int sipsock  = -1;
1196
static int sipsock  = -1;
1197

    
   
1197

   
1198
struct ast_sockaddr bindaddr;	/*!< UDP: The address we bind to */
1198
struct ast_sockaddr bindaddr;	/*!< UDP: The address we bind to */
1199

    
   
1199

   
1200
/*! \brief our (internal) default address/port to put in SIP/SDP messages
1200
/*! \brief our (internal) default address/port to put in SIP/SDP messages
1201
 *  internip is initialized picking a suitable address from one of the
1201
 *  internip is initialized picking a suitable address from one of the
1202
 * interfaces, and the same port number we bind to. It is used as the
1202
 * interfaces, and the same port number we bind to. It is used as the
1203
 * default address/port in SIP messages, and as the default address
1203
 * default address/port in SIP messages, and as the default address
1204
 * (but not port) in SDP messages.
1204
 * (but not port) in SDP messages.
1205
 */
1205
 */
1206
static struct ast_sockaddr internip;
1206
static struct ast_sockaddr internip;
1207

    
   
1207

   
1208
/*! \brief our external IP address/port for SIP sessions.
1208
/*! \brief our external IP address/port for SIP sessions.
1209
 * externaddr.sin_addr is only set when we know we might be behind
1209
 * externaddr.sin_addr is only set when we know we might be behind
1210
 * a NAT, and this is done using a variety of (mutually exclusive)
1210
 * a NAT, and this is done using a variety of (mutually exclusive)
1211
 * ways from the config file:
1211
 * ways from the config file:
1212
 *
1212
 *
1213
 * + with "externaddr = host[:port]" we specify the address/port explicitly.
1213
 * + with "externaddr = host[:port]" we specify the address/port explicitly.
1214
 *   The address is looked up only once when (re)loading the config file;
1214
 *   The address is looked up only once when (re)loading the config file;
1215
 *
1215
 *
1216
 * + with "externhost = host[:port]" we do a similar thing, but the
1216
 * + with "externhost = host[:port]" we do a similar thing, but the
1217
 *   hostname is stored in externhost, and the hostname->IP mapping
1217
 *   hostname is stored in externhost, and the hostname->IP mapping
1218
 *   is refreshed every 'externrefresh' seconds;
1218
 *   is refreshed every 'externrefresh' seconds;
1219
 *
1219
 *
1220
 * Other variables (externhost, externexpire, externrefresh) are used
1220
 * Other variables (externhost, externexpire, externrefresh) are used
1221
 * to support the above functions.
1221
 * to support the above functions.
1222
 */
1222
 */
1223
static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
1223
static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
1224
static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
1224
static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
1225

    
   
1225

   
1226
static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1226
static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1227
static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1227
static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1228
static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
1228
static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
1229
static uint16_t externtcpport;          /*!< external tcp port */
1229
static uint16_t externtcpport;          /*!< external tcp port */
1230
static uint16_t externtlsport;          /*!< external tls port */
1230
static uint16_t externtlsport;          /*!< external tls port */
1231

    
   
1231

   
1232
/*! \brief  List of local networks
1232
/*! \brief  List of local networks
1233
 * We store "localnet" addresses from the config file into an access list,
1233
 * We store "localnet" addresses from the config file into an access list,
1234
 * marked as 'DENY', so the call to ast_apply_ha() will return
1234
 * marked as 'DENY', so the call to ast_apply_ha() will return
1235
 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1235
 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1236
 * (i.e. presumably public) addresses.
1236
 * (i.e. presumably public) addresses.
1237
 */
1237
 */
1238
static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
1238
static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
1239

    
   
1239

   
1240
static int ourport_tcp;             /*!< The port used for TCP connections */
1240
static int ourport_tcp;             /*!< The port used for TCP connections */
1241
static int ourport_tls;             /*!< The port used for TCP/TLS connections */
1241
static int ourport_tls;             /*!< The port used for TCP/TLS connections */
1242
static struct ast_sockaddr debugaddr;
1242
static struct ast_sockaddr debugaddr;
1243

    
   
1243

   
1244
static struct ast_config *notify_types = NULL;    /*!< The list of manual NOTIFY types we know how to send */
1244
static struct ast_config *notify_types = NULL;    /*!< The list of manual NOTIFY types we know how to send */
1245

    
   
1245

   
1246
/*! some list management macros. */
1246
/*! some list management macros. */
1247

    
   
1247

   
1248
#define UNLINK(element, head, prev) do {	\
1248
#define UNLINK(element, head, prev) do {	\
1249
	if (prev)				\
1249
	if (prev)				\
1250
		(prev)->next = (element)->next;	\
1250
		(prev)->next = (element)->next;	\
1251
	else					\
1251
	else					\
1252
		(head) = (element)->next;	\
1252
		(head) = (element)->next;	\
1253
	} while (0)
1253
	} while (0)
1254

    
   
1254

   
1255
/*---------------------------- Forward declarations of functions in chan_sip.c */
1255
/*---------------------------- Forward declarations of functions in chan_sip.c */
1256
/* Note: This is added to help splitting up chan_sip.c into several files
1256
/* Note: This is added to help splitting up chan_sip.c into several files
1257
	in coming releases. */
1257
	in coming releases. */
1258

    
   
1258

   
1259
/*--- PBX interface functions */
1259
/*--- PBX interface functions */
1260
static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *dest, int *cause);
1260
static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *dest, int *cause);
1261
static int sip_devicestate(const char *data);
1261
static int sip_devicestate(const char *data);
1262
static int sip_sendtext(struct ast_channel *ast, const char *text);
1262
static int sip_sendtext(struct ast_channel *ast, const char *text);
1263
static int sip_call(struct ast_channel *ast, const char *dest, int timeout);
1263
static int sip_call(struct ast_channel *ast, const char *dest, int timeout);
1264
static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1264
static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1265
static int sip_hangup(struct ast_channel *ast);
1265
static int sip_hangup(struct ast_channel *ast);
1266
static int sip_answer(struct ast_channel *ast);
1266
static int sip_answer(struct ast_channel *ast);
1267
static struct ast_frame *sip_read(struct ast_channel *ast);
1267
static struct ast_frame *sip_read(struct ast_channel *ast);
1268
static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1268
static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1269
static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1269
static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1270
static int sip_transfer(struct ast_channel *ast, const char *dest);
1270
static int sip_transfer(struct ast_channel *ast, const char *dest);
1271
static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1271
static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1272
static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1272
static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1273
static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1273
static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1274
static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1274
static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1275
static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1275
static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1276
static const char *sip_get_callid(struct ast_channel *chan);
1276
static const char *sip_get_callid(struct ast_channel *chan);
1277

    
   
1277

   
1278
static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
1278
static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
1279
static int sip_standard_port(enum sip_transport type, int port);
1279
static int sip_standard_port(enum sip_transport type, int port);
1280
static int sip_prepare_socket(struct sip_pvt *p);
1280
static int sip_prepare_socket(struct sip_pvt *p);
1281
static int get_address_family_filter(unsigned int transport);
1281
static int get_address_family_filter(unsigned int transport);
1282

    
   
1282

   
1283
/*--- Transmitting responses and requests */
1283
/*--- Transmitting responses and requests */
1284
static int sipsock_read(int *id, int fd, short events, void *ignore);
1284
static int sipsock_read(int *id, int fd, short events, void *ignore);
1285
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
1285
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
1286
static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
1286
static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
1287
static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1287
static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1288
static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1288
static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1289
static int retrans_pkt(const void *data);
1289
static int retrans_pkt(const void *data);
1290
static int transmit_response_using_temp(ast_string_field callid, struct ast_sockaddr *addr, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
1290
static int transmit_response_using_temp(ast_string_field callid, struct ast_sockaddr *addr, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
1291
static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1291
static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1292
static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1292
static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1293
static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1293
static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1294
static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp, int rpid);
1294
static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp, int rpid);
1295
static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1295
static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1296
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);
1296
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);
1297
static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1297
static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1298
static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1298
static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1299
static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
1299
static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
1300
static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
1300
static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
1301
static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
1301
static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
1302
static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
1302
static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
1303
static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
1303
static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
1304
static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1304
static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1305
static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
1305
static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
1306
static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1306
static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1307
static int transmit_info_with_vidupdate(struct sip_pvt *p);
1307
static int transmit_info_with_vidupdate(struct sip_pvt *p);
1308
static int transmit_message(struct sip_pvt *p, int init, int auth);
1308
static int transmit_message(struct sip_pvt *p, int init, int auth);
1309
static int transmit_refer(struct sip_pvt *p, const char *dest);
1309
static int transmit_refer(struct sip_pvt *p, const char *dest);
1310
static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1310
static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1311
static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1311
static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1312
static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
1312
static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
1313
static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1313
static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1314
static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
1314
static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
1315
static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
1315
static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
1316
static void copy_request(struct sip_request *dst, const struct sip_request *src);
1316
static void copy_request(struct sip_request *dst, const struct sip_request *src);
1317
static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1317
static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1318
static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1318
static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1319
static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
1319
static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
1320

    
   
1320

   
1321
/* Misc dialog routines */
1321
/* Misc dialog routines */
1322
static int __sip_autodestruct(const void *data);
1322
static int __sip_autodestruct(const void *data);
1323
static void *registry_unref(struct sip_registry *reg, char *tag);
1323
static void *registry_unref(struct sip_registry *reg, char *tag);
1324
static int update_call_counter(struct sip_pvt *fup, int event);
1324
static int update_call_counter(struct sip_pvt *fup, int event);
1325
static int auto_congest(const void *arg);
1325
static int auto_congest(const void *arg);
1326
static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
1326
static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
1327
static void free_old_route(struct sip_route *route);
1327
static void free_old_route(struct sip_route *route);
1328
static void list_route(struct sip_route *route);
1328
static void list_route(struct sip_route *route);
1329
static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
1329
static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
1330
static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
1330
static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
1331
					      struct sip_request *req, const char *uri);
1331
					      struct sip_request *req, const char *uri);
1332
static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1332
static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1333
static void check_pendings(struct sip_pvt *p);
1333
static void check_pendings(struct sip_pvt *p);
1334
static void *sip_park_thread(void *stuff);
1334
static void *sip_park_thread(void *stuff);
1335
static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, uint32_t seqno, const char *park_exten, const char *park_context);
1335
static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, uint32_t seqno, const char *park_exten, const char *park_context);
1336

    
   
1336

   
1337
static void *sip_pickup_thread(void *stuff);
1337
static void *sip_pickup_thread(void *stuff);
1338
static int sip_pickup(struct ast_channel *chan);
1338
static int sip_pickup(struct ast_channel *chan);
1339

    
   
1339

   
1340
static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1340
static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1341
static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1341
static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1342

    
   
1342

   
1343
/*--- Codec handling / SDP */
1343
/*--- Codec handling / SDP */
1344
static void try_suggested_sip_codec(struct sip_pvt *p);
1344
static void try_suggested_sip_codec(struct sip_pvt *p);
1345
static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1345
static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1346
static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1346
static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1347
static int find_sdp(struct sip_request *req);
1347
static int find_sdp(struct sip_request *req);
1348
static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1348
static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1349
static int process_sdp_o(const char *o, struct sip_pvt *p);
1349
static int process_sdp_o(const char *o, struct sip_pvt *p);
1350
static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
1350
static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
1351
static int process_sdp_a_sendonly(const char *a, int *sendonly);
1351
static int process_sdp_a_sendonly(const char *a, int *sendonly);
1352
static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
1352
static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
1353
static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1353
static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1354
static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1354
static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1355
static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec);
1355
static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec);
1356
static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1356
static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1357
static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
1357
static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
1358
static void start_ice(struct ast_rtp_instance *instance);
1358
static void start_ice(struct ast_rtp_instance *instance);
1359
static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
1359
static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
1360
			     struct ast_str **m_buf, struct ast_str **a_buf,
1360
			     struct ast_str **m_buf, struct ast_str **a_buf,
1361
			     int debug, int *min_packet_size);
1361
			     int debug, int *min_packet_size);
1362
static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1362
static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1363
				struct ast_str **m_buf, struct ast_str **a_buf,
1363
				struct ast_str **m_buf, struct ast_str **a_buf,
1364
				int debug);
1364
				int debug);
1365
static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1365
static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1366
static void do_setnat(struct sip_pvt *p);
1366
static void do_setnat(struct sip_pvt *p);
1367
static void stop_media_flows(struct sip_pvt *p);
1367
static void stop_media_flows(struct sip_pvt *p);
1368

    
   
1368

   
1369
/*--- Authentication stuff */
1369
/*--- Authentication stuff */
1370
static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1370
static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1371
static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1371
static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1372
static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1372
static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1373
					 const char *secret, const char *md5secret, int sipmethod,
1373
					 const char *secret, const char *md5secret, int sipmethod,
1374
					 const char *uri, enum xmittype reliable, int ignore);
1374
					 const char *uri, enum xmittype reliable, int ignore);
1375
static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1375
static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1376
					      int sipmethod, const char *uri, enum xmittype reliable,
1376
					      int sipmethod, const char *uri, enum xmittype reliable,
1377
					      struct ast_sockaddr *addr, struct sip_peer **authpeer);
1377
					      struct ast_sockaddr *addr, struct sip_peer **authpeer);
1378
static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
1378
static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
1379

    
   
1379

   
1380
/*--- Domain handling */
1380
/*--- Domain handling */
1381
static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1381
static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1382
static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1382
static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1383
static void clear_sip_domains(void);
1383
static void clear_sip_domains(void);
1384

    
   
1384

   
1385
/*--- SIP realm authentication */
1385
/*--- SIP realm authentication */
1386
static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
1386
static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
1387
static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
1387
static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
1388

    
   
1388

   
1389
/*--- Misc functions */
1389
/*--- Misc functions */
1390
static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1390
static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1391
static int reload_config(enum channelreloadreason reason);
1391
static int reload_config(enum channelreloadreason reason);
1392
static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt);
1392
static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt);
1393
static int expire_register(const void *data);
1393
static int expire_register(const void *data);
1394
static void *do_monitor(void *data);
1394
static void *do_monitor(void *data);
1395
static int restart_monitor(void);
1395
static int restart_monitor(void);
1396
static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1396
static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1397
static struct ast_variable *copy_vars(struct ast_variable *src);
1397
static struct ast_variable *copy_vars(struct ast_variable *src);
1398
static int dialog_find_multiple(void *obj, void *arg, int flags);
1398
static int dialog_find_multiple(void *obj, void *arg, int flags);
1399
static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
1399
static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
1400
/* static int sip_addrcmp(char *name, struct sockaddr_in *sin);	Support for peer matching */
1400
/* static int sip_addrcmp(char *name, struct sockaddr_in *sin);	Support for peer matching */
1401
static int sip_refer_allocate(struct sip_pvt *p);
1401
static int sip_refer_allocate(struct sip_pvt *p);
1402
static int sip_notify_allocate(struct sip_pvt *p);
1402
static int sip_notify_allocate(struct sip_pvt *p);
1403
static void ast_quiet_chan(struct ast_channel *chan);
1403
static void ast_quiet_chan(struct ast_channel *chan);
1404
static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1404
static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1405
static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1405
static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1406

    
   
1406

   
1407
/*--- Device monitoring and Device/extension state/event handling */
1407
/*--- Device monitoring and Device/extension state/event handling */
1408
static int extensionstate_update(char *context, char *exten, struct state_notify_data *data, struct sip_pvt *p);
1408
static int extensionstate_update(char *context, char *exten, struct state_notify_data *data, struct sip_pvt *p);
1409
static int cb_extensionstate(char *context, char *exten, struct ast_state_cb_info *info, void *data);
1409
static int cb_extensionstate(char *context, char *exten, struct ast_state_cb_info *info, void *data);
1410
static int sip_poke_noanswer(const void *data);
1410
static int sip_poke_noanswer(const void *data);
1411
static int sip_poke_peer(struct sip_peer *peer, int force);
1411
static int sip_poke_peer(struct sip_peer *peer, int force);
1412
static void sip_poke_all_peers(void);
1412
static void sip_poke_all_peers(void);
1413
static void sip_peer_hold(struct sip_pvt *p, int hold);
1413
static void sip_peer_hold(struct sip_pvt *p, int hold);
1414
static void mwi_event_cb(const struct ast_event *, void *);
1414
static void mwi_event_cb(const struct ast_event *, void *);
1415
static void network_change_event_cb(const struct ast_event *, void *);
1415
static void network_change_event_cb(const struct ast_event *, void *);
1416
static void sip_keepalive_all_peers(void);
1416
static void sip_keepalive_all_peers(void);
1417

    
   
1417

   
1418
/*--- Applications, functions, CLI and manager command helpers */
1418
/*--- Applications, functions, CLI and manager command helpers */
1419
static const char *sip_nat_mode(const struct sip_pvt *p);
1419
static const char *sip_nat_mode(const struct sip_pvt *p);
1420
static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1420
static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1421
static char *transfermode2str(enum transfermodes mode) attribute_const;
1421
static char *transfermode2str(enum transfermodes mode) attribute_const;
1422
static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1422
static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1423
static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1423
static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1424
static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1424
static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1425
static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1425
static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1426
static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1426
static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1427
static void  print_group(int fd, ast_group_t group, int crlf);
1427
static void  print_group(int fd, ast_group_t group, int crlf);
1428
static const char *dtmfmode2str(int mode) attribute_const;
1428
static const char *dtmfmode2str(int mode) attribute_const;
1429
static int str2dtmfmode(const char *str) attribute_unused;
1429
static int str2dtmfmode(const char *str) attribute_unused;
1430
static const char *insecure2str(int mode) attribute_const;
1430
static const char *insecure2str(int mode) attribute_const;
1431
static const char *allowoverlap2str(int mode) attribute_const;
1431
static const char *allowoverlap2str(int mode) attribute_const;
1432
static void cleanup_stale_contexts(char *new, char *old);
1432
static void cleanup_stale_contexts(char *new, char *old);
1433
static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1433
static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1434
static const char *domain_mode_to_text(const enum domain_mode mode);
1434
static const char *domain_mode_to_text(const enum domain_mode mode);
1435
static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1435
static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1436
static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1436
static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1437
static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1437
static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1438
static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1438
static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1439
static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1439
static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1440
static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1440
static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1441
static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1441
static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1442
static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1442
static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1443
static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1443
static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1444
static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1444
static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1445
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1445
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1446
static char *complete_sip_peer(const char *word, int state, int flags2);
1446
static char *complete_sip_peer(const char *word, int state, int flags2);
1447
static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1447
static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1448
static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1448
static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1449
static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1449
static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1450
static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1450
static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1451
static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1451
static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1452
static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1452
static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1453
static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1453
static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1454
static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1454
static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1455
static char *sip_do_debug_ip(int fd, const char *arg);
1455
static char *sip_do_debug_ip(int fd, const char *arg);
1456
static char *sip_do_debug_peer(int fd, const char *arg);
1456
static char *sip_do_debug_peer(int fd, const char *arg);
1457
static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1457
static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1458
static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1458
static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1459
static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1459
static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1460
static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1460
static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1461
static int sip_addheader(struct ast_channel *chan, const char *data);
1461
static int sip_addheader(struct ast_channel *chan, const char *data);
1462
static int sip_do_reload(enum channelreloadreason reason);
1462
static int sip_do_reload(enum channelreloadreason reason);
1463
static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1463
static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1464
static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
1464
static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
1465
				      const char *name, int flag, int family);
1465
				      const char *name, int flag, int family);
1466
static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
1466
static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
1467
				      const char *name, int flag);
1467
				      const char *name, int flag);
1468
static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
1468
static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
1469
						const char *name, int flag, unsigned int transport);
1469
						const char *name, int flag, unsigned int transport);
1470

    
   
1470

   
1471
/*--- Debugging
1471
/*--- Debugging
1472
	Functions for enabling debug per IP or fully, or enabling history logging for
1472
	Functions for enabling debug per IP or fully, or enabling history logging for
1473
	a SIP dialog
1473
	a SIP dialog
1474
*/
1474
*/
1475
static void sip_dump_history(struct sip_pvt *dialog);	/* Dump history to debuglog at end of dialog, before destroying data */
1475
static void sip_dump_history(struct sip_pvt *dialog);	/* Dump history to debuglog at end of dialog, before destroying data */
1476
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
1476
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
1477
static inline int sip_debug_test_pvt(struct sip_pvt *p);
1477
static inline int sip_debug_test_pvt(struct sip_pvt *p);
1478
static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1478
static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1479
static void sip_dump_history(struct sip_pvt *dialog);
1479
static void sip_dump_history(struct sip_pvt *dialog);
1480

    
   
1480

   
1481
/*--- Device object handling */
1481
/*--- Device object handling */
1482
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1482
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1483
static int update_call_counter(struct sip_pvt *fup, int event);
1483
static int update_call_counter(struct sip_pvt *fup, int event);
1484
static void sip_destroy_peer(struct sip_peer *peer);
1484
static void sip_destroy_peer(struct sip_peer *peer);
1485
static void sip_destroy_peer_fn(void *peer);
1485
static void sip_destroy_peer_fn(void *peer);
1486
static void set_peer_defaults(struct sip_peer *peer);
1486
static void set_peer_defaults(struct sip_peer *peer);
1487
static struct sip_peer *temp_peer(const char *name);
1487
static struct sip_peer *temp_peer(const char *name);
1488
static void register_peer_exten(struct sip_peer *peer, int onoff);
1488
static void register_peer_exten(struct sip_peer *peer, int onoff);
1489
static int sip_poke_peer_s(const void *data);
1489
static int sip_poke_peer_s(const void *data);
1490
static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1490
static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1491
static void reg_source_db(struct sip_peer *peer);
1491
static void reg_source_db(struct sip_peer *peer);
1492
static void destroy_association(struct sip_peer *peer);
1492
static void destroy_association(struct sip_peer *peer);
1493
static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1493
static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1494
static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1494
static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1495
static void set_socket_transport(struct sip_socket *socket, int transport);
1495
static void set_socket_transport(struct sip_socket *socket, int transport);
1496
static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags);
1496
static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags);
1497

    
   
1497

   
1498
/* Realtime device support */
1498
/* Realtime device support */
1499
static void realtime_update_peer(const char *peername, struct ast_sockaddr *addr, const char *username, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms);
1499
static void realtime_update_peer(const char *peername, struct ast_sockaddr *addr, const char *username, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms);
1500
static void update_peer(struct sip_peer *p, int expire);
1500
static void update_peer(struct sip_peer *p, int expire);
1501
static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1501
static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1502
static const char *get_name_from_variable(const struct ast_variable *var);
1502
static const char *get_name_from_variable(const struct ast_variable *var);
1503
static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, char *callbackexten, int devstate_only, int which_objects);
1503
static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, char *callbackexten, int devstate_only, int which_objects);
1504
static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1504
static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1505

    
   
1505

   
1506
/*--- Internal UA client handling (outbound registrations) */
1506
/*--- Internal UA client handling (outbound registrations) */
1507
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
1507
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
1508
static void sip_registry_destroy(struct sip_registry *reg);
1508
static void sip_registry_destroy(struct sip_registry *reg);
1509
static int sip_register(const char *value, int lineno);
1509
static int sip_register(const char *value, int lineno);
1510
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1510
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1511
static int sip_reregister(const void *data);
1511
static int sip_reregister(const void *data);
1512
static int __sip_do_register(struct sip_registry *r);
1512
static int __sip_do_register(struct sip_registry *r);
1513
static int sip_reg_timeout(const void *data);
1513
static int sip_reg_timeout(const void *data);
1514
static void sip_send_all_registers(void);
1514
static void sip_send_all_registers(void);
1515
static int sip_reinvite_retry(const void *data);
1515
static int sip_reinvite_retry(const void *data);
1516

    
   
1516

   
1517
/*--- Parsing SIP requests and responses */
1517
/*--- Parsing SIP requests and responses */
1518
static void append_date(struct sip_request *req);	/* Append date to SIP packet */
1518
static void append_date(struct sip_request *req);	/* Append date to SIP packet */
1519
static int determine_firstline_parts(struct sip_request *req);
1519
static int determine_firstline_parts(struct sip_request *req);
1520
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1520
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1521
static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1521
static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1522
static int find_sip_method(const char *msg);
1522
static int find_sip_method(const char *msg);
1523
static unsigned int parse_allowed_methods(struct sip_request *req);
1523
static unsigned int parse_allowed_methods(struct sip_request *req);
1524
static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1524
static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1525
static int parse_request(struct sip_request *req);
1525
static int parse_request(struct sip_request *req);
1526
static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1526
static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1527
static int method_match(enum sipmethod id, const char *name);
1527
static int method_match(enum sipmethod id, const char *name);
1528
static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1528
static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1529
static void parse_oli(struct sip_request *req, struct ast_channel *chan);
1529
static void parse_oli(struct sip_request *req, struct ast_channel *chan);
1530
static const char *find_alias(const char *name, const char *_default);
1530
static const char *find_alias(const char *name, const char *_default);
1531
static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1531
static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1532
static void lws2sws(struct ast_str *msgbuf);
1532
static void lws2sws(struct ast_str *msgbuf);
1533
static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1533
static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1534
static char *remove_uri_parameters(char *uri);
1534
static char *remove_uri_parameters(char *uri);
1535
static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1535
static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1536
static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1536
static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1537
static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1537
static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1538
static int set_address_from_contact(struct sip_pvt *pvt);
1538
static int set_address_from_contact(struct sip_pvt *pvt);
1539
static void check_via(struct sip_pvt *p, struct sip_request *req);
1539
static void check_via(struct sip_pvt *p, struct sip_request *req);
1540
static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1540
static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1541
static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
1541
static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
1542
static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1542
static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1543
static int get_msg_text(char *buf, int len, struct sip_request *req);
1543
static int get_msg_text(char *buf, int len, struct sip_request *req);
1544
static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout);
1544
static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout);
1545
static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1545
static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1546
static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1546
static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1547
static int get_domain(const char *str, char *domain, int len);
1547
static int get_domain(const char *str, char *domain, int len);
1548
static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1548
static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1549

    
   
1549

   
1550
/*-- TCP connection handling ---*/
1550
/*-- TCP connection handling ---*/
1551
static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
1551
static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
1552
static void *sip_tcp_worker_fn(void *);
1552
static void *sip_tcp_worker_fn(void *);
1553

    
   
1553

   
1554
/*--- Constructing requests and responses */
1554
/*--- Constructing requests and responses */
1555
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1555
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1556
static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1556
static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1557
static void deinit_req(struct sip_request *req);
1557
static void deinit_req(struct sip_request *req);
1558
static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
1558
static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
1559
static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1559
static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1560
static int init_resp(struct sip_request *resp, const char *msg);
1560
static int init_resp(struct sip_request *resp, const char *msg);
1561
static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1561
static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1562
static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1562
static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1563
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
1563
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
1564
static void build_via(struct sip_pvt *p);
1564
static void build_via(struct sip_pvt *p);
1565
static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1565
static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1566
static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address);
1566
static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address);
1567
static char *generate_random_string(char *buf, size_t size);
1567
static char *generate_random_string(char *buf, size_t size);
1568
static void build_callid_pvt(struct sip_pvt *pvt);
1568
static void build_callid_pvt(struct sip_pvt *pvt);
1569
static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
1569
static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
1570
static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
1570
static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
1571
static void make_our_tag(struct sip_pvt *pvt);
1571
static void make_our_tag(struct sip_pvt *pvt);
1572
static int add_header(struct sip_request *req, const char *var, const char *value);
1572
static int add_header(struct sip_request *req, const char *var, const char *value);
1573
static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
1573
static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
1574
static int add_content(struct sip_request *req, const char *line);
1574
static int add_content(struct sip_request *req, const char *line);
1575
static int finalize_content(struct sip_request *req);
1575
static int finalize_content(struct sip_request *req);
1576
static void destroy_msg_headers(struct sip_pvt *pvt);
1576
static void destroy_msg_headers(struct sip_pvt *pvt);
1577
static int add_text(struct sip_request *req, struct sip_pvt *p);
1577
static int add_text(struct sip_request *req, struct sip_pvt *p);
1578
static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1578
static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1579
static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1579
static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1580
static int add_vidupdate(struct sip_request *req);
1580
static int add_vidupdate(struct sip_request *req);
1581
static void add_route(struct sip_request *req, struct sip_route *route);
1581
static void add_route(struct sip_request *req, struct sip_route *route);
1582
static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1582
static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1583
static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1583
static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1584
static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1584
static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1585
static void set_destination(struct sip_pvt *p, char *uri);
1585
static void set_destination(struct sip_pvt *p, char *uri);
1586
static void append_date(struct sip_request *req);
1586
static void append_date(struct sip_request *req);
1587
static void build_contact(struct sip_pvt *p);
1587
static void build_contact(struct sip_pvt *p);
1588

    
   
1588

   
1589
/*------Request handling functions */
1589
/*------Request handling functions */
1590
static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
1590
static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
1591
static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1591
static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1592
static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *recount, const char *e, int *nounlock);
1592
static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *recount, const char *e, int *nounlock);
1593
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock);
1593
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock);
1594
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1594
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1595
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
1595
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
1596
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1596
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1597
static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1597
static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1598
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1598
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1599
static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1599
static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1600
static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1600
static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1601
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock);
1601
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock);
1602
static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1602
static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1603
static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock);
1603
static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock);
1604

    
   
1604

   
1605
/*------Response handling functions */
1605
/*------Response handling functions */
1606
static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1606
static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1607
static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1607
static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1608
static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1608
static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1609
static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1609
static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1610
static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1610
static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1611
static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1611
static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1612
static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1612
static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1613

    
   
1613

   
1614
/*------ SRTP Support -------- */
1614
/*------ SRTP Support -------- */
1615
static int setup_srtp(struct sip_srtp **srtp);
1615
static int setup_srtp(struct sip_srtp **srtp);
1616
static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
1616
static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
1617

    
   
1617

   
1618
/*------ T38 Support --------- */
1618
/*------ T38 Support --------- */
1619
static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1619
static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1620
static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1620
static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1621
static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1621
static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1622
static void change_t38_state(struct sip_pvt *p, int state);
1622
static void change_t38_state(struct sip_pvt *p, int state);
1623

    
   
1623

   
1624
/*------ Session-Timers functions --------- */
1624
/*------ Session-Timers functions --------- */
1625
static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1625
static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1626
static int  proc_session_timer(const void *vp);
1626
static int  proc_session_timer(const void *vp);
1627
static void stop_session_timer(struct sip_pvt *p);
1627
static void stop_session_timer(struct sip_pvt *p);
1628
static void start_session_timer(struct sip_pvt *p);
1628
static void start_session_timer(struct sip_pvt *p);
1629
static void restart_session_timer(struct sip_pvt *p);
1629
static void restart_session_timer(struct sip_pvt *p);
1630
static const char *strefresher2str(enum st_refresher r);
1630
static const char *strefresher2str(enum st_refresher r);
1631
static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
1631
static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
1632
static int parse_minse(const char *p_hdrval, int *const p_interval);
1632
static int parse_minse(const char *p_hdrval, int *const p_interval);
1633
static int st_get_se(struct sip_pvt *, int max);
1633
static int st_get_se(struct sip_pvt *, int max);
1634
static enum st_refresher st_get_refresher(struct sip_pvt *);
1634
static enum st_refresher st_get_refresher(struct sip_pvt *);
1635
static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
1635
static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
1636
static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1636
static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1637

    
   
1637

   
1638
/*------- RTP Glue functions -------- */
1638
/*------- RTP Glue functions -------- */
1639
static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_rtp_instance *vinstance, struct ast_rtp_instance *tinstance, const struct ast_format_cap *cap, int nat_active);
1639
static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_rtp_instance *vinstance, struct ast_rtp_instance *tinstance, const struct ast_format_cap *cap, int nat_active);
1640

    
   
1640

   
1641
/*!--- SIP MWI Subscription support */
1641
/*!--- SIP MWI Subscription support */
1642
static int sip_subscribe_mwi(const char *value, int lineno);
1642
static int sip_subscribe_mwi(const char *value, int lineno);
1643
static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
1643
static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
1644
static void sip_send_all_mwi_subscriptions(void);
1644
static void sip_send_all_mwi_subscriptions(void);
1645
static int sip_subscribe_mwi_do(const void *data);
1645
static int sip_subscribe_mwi_do(const void *data);
1646
static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1646
static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1647

    
   
1647

   
1648
/*! \brief Definition of this channel for PBX channel registration */
1648
/*! \brief Definition of this channel for PBX channel registration */
1649
struct ast_channel_tech sip_tech = {
1649
struct ast_channel_tech sip_tech = {
1650
	.type = "SIP",
1650
	.type = "SIP",
1651
	.description = "Session Initiation Protocol (SIP)",
1651
	.description = "Session Initiation Protocol (SIP)",
1652
	.properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1652
	.properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1653
	.requester = sip_request_call,			/* called with chan unlocked */
1653
	.requester = sip_request_call,			/* called with chan unlocked */
1654
	.devicestate = sip_devicestate,			/* called with chan unlocked (not chan-specific) */
1654
	.devicestate = sip_devicestate,			/* called with chan unlocked (not chan-specific) */
1655
	.call = sip_call,			/* called with chan locked */
1655
	.call = sip_call,			/* called with chan locked */
1656
	.send_html = sip_sendhtml,
1656
	.send_html = sip_sendhtml,
1657
	.hangup = sip_hangup,			/* called with chan locked */
1657
	.hangup = sip_hangup,			/* called with chan locked */
1658
	.answer = sip_answer,			/* called with chan locked */
1658
	.answer = sip_answer,			/* called with chan locked */
1659
	.read = sip_read,			/* called with chan locked */
1659
	.read = sip_read,			/* called with chan locked */
1660
	.write = sip_write,			/* called with chan locked */
1660
	.write = sip_write,			/* called with chan locked */
1661
	.write_video = sip_write,		/* called with chan locked */
1661
	.write_video = sip_write,		/* called with chan locked */
1662
	.write_text = sip_write,
1662
	.write_text = sip_write,
1663
	.indicate = sip_indicate,		/* called with chan locked */
1663
	.indicate = sip_indicate,		/* called with chan locked */
1664
	.transfer = sip_transfer,		/* called with chan locked */
1664
	.transfer = sip_transfer,		/* called with chan locked */
1665
	.fixup = sip_fixup,			/* called with chan locked */
1665
	.fixup = sip_fixup,			/* called with chan locked */
1666
	.send_digit_begin = sip_senddigit_begin,	/* called with chan unlocked */
1666
	.send_digit_begin = sip_senddigit_begin,	/* called with chan unlocked */
1667
	.send_digit_end = sip_senddigit_end,
1667
	.send_digit_end = sip_senddigit_end,
1668
	.bridge = ast_rtp_instance_bridge,			/* XXX chan unlocked ? */
1668
	.bridge = ast_rtp_instance_bridge,			/* XXX chan unlocked ? */
1669
	.early_bridge = ast_rtp_instance_early_bridge,
1669
	.early_bridge = ast_rtp_instance_early_bridge,
1670
	.send_text = sip_sendtext,		/* called with chan locked */
1670
	.send_text = sip_sendtext,		/* called with chan locked */
1671
	.func_channel_read = sip_acf_channel_read,
1671
	.func_channel_read = sip_acf_channel_read,
1672
	.setoption = sip_setoption,
1672
	.setoption = sip_setoption,
1673
	.queryoption = sip_queryoption,
1673
	.queryoption = sip_queryoption,
1674
	.get_pvt_uniqueid = sip_get_callid,
1674
	.get_pvt_uniqueid = sip_get_callid,
1675
};
1675
};
1676

    
   
1676

   
1677
/*! \brief This version of the sip channel tech has no send_digit_begin
1677
/*! \brief This version of the sip channel tech has no send_digit_begin
1678
 * callback so that the core knows that the channel does not want
1678
 * callback so that the core knows that the channel does not want
1679
 * DTMF BEGIN frames.
1679
 * DTMF BEGIN frames.
1680
 * The struct is initialized just before registering the channel driver,
1680
 * The struct is initialized just before registering the channel driver,
1681
 * and is for use with channels using SIP INFO DTMF.
1681
 * and is for use with channels using SIP INFO DTMF.
1682
 */
1682
 */
1683
struct ast_channel_tech sip_tech_info;
1683
struct ast_channel_tech sip_tech_info;
1684

    
   
1684

   
1685
/*------- CC Support -------- */
1685
/*------- CC Support -------- */
1686
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1686
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1687
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1687
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1688
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1688
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1689
static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
1689
static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
1690
static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
1690
static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
1691
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1691
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1692
static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1692
static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1693
static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1693
static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1694

    
   
1694

   
1695
static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
1695
static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
1696
	.type = "SIP",
1696
	.type = "SIP",
1697
	.init = sip_cc_agent_init,
1697
	.init = sip_cc_agent_init,
1698
	.start_offer_timer = sip_cc_agent_start_offer_timer,
1698
	.start_offer_timer = sip_cc_agent_start_offer_timer,
1699
	.stop_offer_timer = sip_cc_agent_stop_offer_timer,
1699
	.stop_offer_timer = sip_cc_agent_stop_offer_timer,
1700
	.respond = sip_cc_agent_respond,
1700
	.respond = sip_cc_agent_respond,
1701
	.status_request = sip_cc_agent_status_request,
1701
	.status_request = sip_cc_agent_status_request,
1702
	.start_monitoring = sip_cc_agent_start_monitoring,
1702
	.start_monitoring = sip_cc_agent_start_monitoring,
1703
	.callee_available = sip_cc_agent_recall,
1703
	.callee_available = sip_cc_agent_recall,
1704
	.destructor = sip_cc_agent_destructor,
1704
	.destructor = sip_cc_agent_destructor,
1705
};
1705
};
1706

    
   
1706

   
1707
static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
1707
static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
1708
{
1708
{
1709
	struct ast_cc_agent *agent = obj;
1709
	struct ast_cc_agent *agent = obj;
1710
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1710
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1711
	const char *uri = arg;
1711
	const char *uri = arg;
1712

    
   
1712

   
1713
	return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1713
	return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1714
}
1714
}
1715

    
   
1715

   
1716
static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
1716
static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
1717
{
1717
{
1718
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
1718
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
1719
	return agent;
1719
	return agent;
1720
}
1720
}
1721

    
   
1721

   
1722
static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
1722
static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
1723
{
1723
{
1724
	struct ast_cc_agent *agent = obj;
1724
	struct ast_cc_agent *agent = obj;
1725
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1725
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1726
	const char *uri = arg;
1726
	const char *uri = arg;
1727

    
   
1727

   
1728
	return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1728
	return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1729
}
1729
}
1730

    
   
1730

   
1731
static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
1731
static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
1732
{
1732
{
1733
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
1733
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
1734
	return agent;
1734
	return agent;
1735
}
1735
}
1736

    
   
1736

   
1737
static int find_by_callid_helper(void *obj, void *arg, int flags)
1737
static int find_by_callid_helper(void *obj, void *arg, int flags)
1738
{
1738
{
1739
	struct ast_cc_agent *agent = obj;
1739
	struct ast_cc_agent *agent = obj;
1740
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1740
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1741
	struct sip_pvt *call_pvt = arg;
1741
	struct sip_pvt *call_pvt = arg;
1742

    
   
1742

   
1743
	return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
1743
	return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
1744
}
1744
}
1745

    
   
1745

   
1746
static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
1746
static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
1747
{
1747
{
1748
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
1748
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
1749
	return agent;
1749
	return agent;
1750
}
1750
}
1751

    
   
1751

   
1752
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
1752
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
1753
{
1753
{
1754
	struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
1754
	struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
1755
	struct sip_pvt *call_pvt = ast_channel_tech_pvt(chan);
1755
	struct sip_pvt *call_pvt = ast_channel_tech_pvt(chan);
1756

    
   
1756

   
1757
	if (!agent_pvt) {
1757
	if (!agent_pvt) {
1758
		return -1;
1758
		return -1;
1759
	}
1759
	}
1760

    
   
1760

   
1761
	ast_assert(!strcmp(ast_channel_tech(chan)->type, "SIP"));
1761
	ast_assert(!strcmp(ast_channel_tech(chan)->type, "SIP"));
1762

    
   
1762

   
1763
	ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
1763
	ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
1764
	ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
1764
	ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
1765
	agent_pvt->offer_timer_id = -1;
1765
	agent_pvt->offer_timer_id = -1;
1766
	agent->private_data = agent_pvt;
1766
	agent->private_data = agent_pvt;
1767
	sip_pvt_lock(call_pvt);
1767
	sip_pvt_lock(call_pvt);
1768
	ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1768
	ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1769
	sip_pvt_unlock(call_pvt);
1769
	sip_pvt_unlock(call_pvt);
1770
	return 0;
1770
	return 0;
1771
}
1771
}
1772

    
   
1772

   
1773
static int sip_offer_timer_expire(const void *data)
1773
static int sip_offer_timer_expire(const void *data)
1774
{
1774
{
1775
	struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
1775
	struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
1776
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1776
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1777

    
   
1777

   
1778
	agent_pvt->offer_timer_id = -1;
1778
	agent_pvt->offer_timer_id = -1;
1779

    
   
1779

   
1780
	return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
1780
	return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
1781
}
1781
}
1782

    
   
1782

   
1783
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
1783
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
1784
{
1784
{
1785
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1785
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1786
	int when;
1786
	int when;
1787

    
   
1787

   
1788
	when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1788
	when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1789
	agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
1789
	agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
1790
	return 0;
1790
	return 0;
1791
}
1791
}
1792

    
   
1792

   
1793
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
1793
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
1794
{
1794
{
1795
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1795
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1796

    
   
1796

   
1797
	AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1797
	AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1798
	return 0;
1798
	return 0;
1799
}
1799
}
1800

    
   
1800

   
1801
static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
1801
static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
1802
{
1802
{
1803
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1803
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1804

    
   
1804

   
1805
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1805
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1806
	ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
1806
	ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
1807
	if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
1807
	if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
1808
		/* The second half of this if statement may be a bit hard to grasp,
1808
		/* The second half of this if statement may be a bit hard to grasp,
1809
		 * so here's an explanation. When a subscription comes into
1809
		 * so here's an explanation. When a subscription comes into
1810
		 * chan_sip, as long as it is not malformed, it will be passed
1810
		 * chan_sip, as long as it is not malformed, it will be passed
1811
		 * to the CC core. If the core senses an out-of-order state transition,
1811
		 * to the CC core. If the core senses an out-of-order state transition,
1812
		 * then the core will call this callback with the "reason" set to a
1812
		 * then the core will call this callback with the "reason" set to a
1813
		 * failure condition.
1813
		 * failure condition.
1814
		 * However, an out-of-order state transition will occur during a resubscription
1814
		 * However, an out-of-order state transition will occur during a resubscription
1815
		 * for CC. In such a case, we can see that we have already generated a notify_uri
1815
		 * for CC. In such a case, we can see that we have already generated a notify_uri
1816
		 * and so we can detect that this isn't a *real* failure. Rather, it is just
1816
		 * and so we can detect that this isn't a *real* failure. Rather, it is just
1817
		 * something the core doesn't recognize as a legitimate SIP state transition.
1817
		 * something the core doesn't recognize as a legitimate SIP state transition.
1818
		 * Thus we respond with happiness and flowers.
1818
		 * Thus we respond with happiness and flowers.
1819
		 */
1819
		 */
1820
		transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1820
		transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1821
		transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1821
		transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1822
	} else {
1822
	} else {
1823
		transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
1823
		transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
1824
	}
1824
	}
1825
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1825
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1826
	agent_pvt->is_available = TRUE;
1826
	agent_pvt->is_available = TRUE;
1827
}
1827
}
1828

    
   
1828

   
1829
static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
1829
static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
1830
{
1830
{
1831
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1831
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1832
	enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
1832
	enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
1833
	return ast_cc_agent_status_response(agent->core_id, state);
1833
	return ast_cc_agent_status_response(agent->core_id, state);
1834
}
1834
}
1835

    
   
1835

   
1836
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
1836
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
1837
{
1837
{
1838
	/* To start monitoring just means to wait for an incoming PUBLISH
1838
	/* To start monitoring just means to wait for an incoming PUBLISH
1839
	 * to tell us that the caller has become available again. No special
1839
	 * to tell us that the caller has become available again. No special
1840
	 * action is needed
1840
	 * action is needed
1841
	 */
1841
	 */
1842
	return 0;
1842
	return 0;
1843
}
1843
}
1844

    
   
1844

   
1845
static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1845
static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1846
{
1846
{
1847
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1847
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1848
	/* If we have received a PUBLISH beforehand stating that the caller in question
1848
	/* If we have received a PUBLISH beforehand stating that the caller in question
1849
	 * is not available, we can save ourself a bit of effort here and just report
1849
	 * is not available, we can save ourself a bit of effort here and just report
1850
	 * the caller as busy
1850
	 * the caller as busy
1851
	 */
1851
	 */
1852
	if (!agent_pvt->is_available) {
1852
	if (!agent_pvt->is_available) {
1853
		return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
1853
		return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
1854
				agent->device_name);
1854
				agent->device_name);
1855
	}
1855
	}
1856
	/* Otherwise, we transmit a NOTIFY to the caller and await either
1856
	/* Otherwise, we transmit a NOTIFY to the caller and await either
1857
	 * a PUBLISH or an INVITE
1857
	 * a PUBLISH or an INVITE
1858
	 */
1858
	 */
1859
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1859
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1860
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1860
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1861
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1861
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1862
	return 0;
1862
	return 0;
1863
}
1863
}
1864

    
   
1864

   
1865
static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
1865
static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
1866
{
1866
{
1867
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1867
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1868

    
   
1868

   
1869
	if (!agent_pvt) {
1869
	if (!agent_pvt) {
1870
		/* The agent constructor probably failed. */
1870
		/* The agent constructor probably failed. */
1871
		return;
1871
		return;
1872
	}
1872
	}
1873

    
   
1873

   
1874
	sip_cc_agent_stop_offer_timer(agent);
1874
	sip_cc_agent_stop_offer_timer(agent);
1875
	if (agent_pvt->subscribe_pvt) {
1875
	if (agent_pvt->subscribe_pvt) {
1876
		sip_pvt_lock(agent_pvt->subscribe_pvt);
1876
		sip_pvt_lock(agent_pvt->subscribe_pvt);
1877
		if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
1877
		if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
1878
			/* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
1878
			/* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
1879
			 * the subscriber know something went wrong
1879
			 * the subscriber know something went wrong
1880
			 */
1880
			 */
1881
			transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
1881
			transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
1882
		}
1882
		}
1883
		sip_pvt_unlock(agent_pvt->subscribe_pvt);
1883
		sip_pvt_unlock(agent_pvt->subscribe_pvt);
1884
		agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
1884
		agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
1885
	}
1885
	}
1886
	ast_free(agent_pvt);
1886
	ast_free(agent_pvt);
1887
}
1887
}
1888

    
   
1888

   
1889
struct ao2_container *sip_monitor_instances;
1889
struct ao2_container *sip_monitor_instances;
1890

    
   
1890

   
1891
static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
1891
static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
1892
{
1892
{
1893
	const struct sip_monitor_instance *monitor_instance = obj;
1893
	const struct sip_monitor_instance *monitor_instance = obj;
1894
	return monitor_instance->core_id;
1894
	return monitor_instance->core_id;
1895
}
1895
}
1896

    
   
1896

   
1897
static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
1897
static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
1898
{
1898
{
1899
	struct sip_monitor_instance *monitor_instance1 = obj;
1899
	struct sip_monitor_instance *monitor_instance1 = obj;
1900
	struct sip_monitor_instance *monitor_instance2 = arg;
1900
	struct sip_monitor_instance *monitor_instance2 = arg;
1901

    
   
1901

   
1902
	return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
1902
	return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
1903
}
1903
}
1904

    
   
1904

   
1905
static void sip_monitor_instance_destructor(void *data)
1905
static void sip_monitor_instance_destructor(void *data)
1906
{
1906
{
1907
	struct sip_monitor_instance *monitor_instance = data;
1907
	struct sip_monitor_instance *monitor_instance = data;
1908
	if (monitor_instance->subscription_pvt) {
1908
	if (monitor_instance->subscription_pvt) {
1909
		sip_pvt_lock(monitor_instance->subscription_pvt);
1909
		sip_pvt_lock(monitor_instance->subscription_pvt);
1910
		monitor_instance->subscription_pvt->expiry = 0;
1910
		monitor_instance->subscription_pvt->expiry = 0;
1911
		transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
1911
		transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
1912
		sip_pvt_unlock(monitor_instance->subscription_pvt);
1912
		sip_pvt_unlock(monitor_instance->subscription_pvt);
1913
		dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
1913
		dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
1914
	}
1914
	}
1915
	if (monitor_instance->suspension_entry) {
1915
	if (monitor_instance->suspension_entry) {
1916
		monitor_instance->suspension_entry->body[0] = '\0';
1916
		monitor_instance->suspension_entry->body[0] = '\0';
1917
		transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
1917
		transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
1918
		ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
1918
		ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
1919
	}
1919
	}
1920
	ast_string_field_free_memory(monitor_instance);
1920
	ast_string_field_free_memory(monitor_instance);
1921
}
1921
}
1922

    
   
1922

   
1923
static struct sip_monitor_instance *sip_monitor_instance_init(int core_id, const char * const subscribe_uri, const char * const peername, const char * const device_name)
1923
static struct sip_monitor_instance *sip_monitor_instance_init(int core_id, const char * const subscribe_uri, const char * const peername, const char * const device_name)
1924
{
1924
{
1925
	struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
1925
	struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
1926

    
   
1926

   
1927
	if (!monitor_instance) {
1927
	if (!monitor_instance) {
1928
		return NULL;
1928
		return NULL;
1929
	}
1929
	}
1930

    
   
1930

   
1931
	if (ast_string_field_init(monitor_instance, 256)) {
1931
	if (ast_string_field_init(monitor_instance, 256)) {
1932
		ao2_ref(monitor_instance, -1);
1932
		ao2_ref(monitor_instance, -1);
1933
		return NULL;
1933
		return NULL;
1934
	}
1934
	}
1935

    
   
1935

   
1936
	ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
1936
	ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
1937
	ast_string_field_set(monitor_instance, peername, peername);
1937
	ast_string_field_set(monitor_instance, peername, peername);
1938
	ast_string_field_set(monitor_instance, device_name, device_name);
1938
	ast_string_field_set(monitor_instance, device_name, device_name);
1939
	monitor_instance->core_id = core_id;
1939
	monitor_instance->core_id = core_id;
1940
	ao2_link(sip_monitor_instances, monitor_instance);
1940
	ao2_link(sip_monitor_instances, monitor_instance);
1941
	return monitor_instance;
1941
	return monitor_instance;
1942
}
1942
}
1943

    
   
1943

   
1944
static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
1944
static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
1945
{
1945
{
1946
	struct sip_monitor_instance *monitor_instance = obj;
1946
	struct sip_monitor_instance *monitor_instance = obj;
1947
	return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
1947
	return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
1948
}
1948
}
1949

    
   
1949

   
1950
static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
1950
static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
1951
{
1951
{
1952
	struct sip_monitor_instance *monitor_instance = obj;
1952
	struct sip_monitor_instance *monitor_instance = obj;
1953
	return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
1953
	return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
1954
}
1954
}
1955

    
   
1955

   
1956
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
1956
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
1957
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
1957
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
1958
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
1958
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
1959
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
1959
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
1960
static void sip_cc_monitor_destructor(void *private_data);
1960
static void sip_cc_monitor_destructor(void *private_data);
1961

    
   
1961

   
1962
static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
1962
static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
1963
	.type = "SIP",
1963
	.type = "SIP",
1964
	.request_cc = sip_cc_monitor_request_cc,
1964
	.request_cc = sip_cc_monitor_request_cc,
1965
	.suspend = sip_cc_monitor_suspend,
1965
	.suspend = sip_cc_monitor_suspend,
1966
	.unsuspend = sip_cc_monitor_unsuspend,
1966
	.unsuspend = sip_cc_monitor_unsuspend,
1967
	.cancel_available_timer = sip_cc_monitor_cancel_available_timer,
1967
	.cancel_available_timer = sip_cc_monitor_cancel_available_timer,
1968
	.destructor = sip_cc_monitor_destructor,
1968
	.destructor = sip_cc_monitor_destructor,
1969
};
1969
};
1970

    
   
1970

   
1971
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
1971
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
1972
{
1972
{
1973
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1973
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1974
	enum ast_cc_service_type service = monitor->service_offered;
1974
	enum ast_cc_service_type service = monitor->service_offered;
1975
	int when;
1975
	int when;
1976

    
   
1976

   
1977
	if (!monitor_instance) {
1977
	if (!monitor_instance) {
1978
		return -1;
1978
		return -1;
1979
	}
1979
	}
1980

    
   
1980

   
1981
	if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, NULL))) {
1981
	if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, NULL))) {
1982
		return -1;
1982
		return -1;
1983
	}
1983
	}
1984

    
   
1984

   
1985
	when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
1985
	when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
1986
		ast_get_ccnr_available_timer(monitor->interface->config_params);
1986
		ast_get_ccnr_available_timer(monitor->interface->config_params);
1987

    
   
1987

   
1988
	sip_pvt_lock(monitor_instance->subscription_pvt);
1988
	sip_pvt_lock(monitor_instance->subscription_pvt);
1989
	ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
1989
	ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
1990
	create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
1990
	create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
1991
	ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
1991
	ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
1992
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1992
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1993
	monitor_instance->subscription_pvt->expiry = when;
1993
	monitor_instance->subscription_pvt->expiry = when;
1994

    
   
1994

   
1995
	transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
1995
	transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
1996
	sip_pvt_unlock(monitor_instance->subscription_pvt);
1996
	sip_pvt_unlock(monitor_instance->subscription_pvt);
1997

    
   
1997

   
1998
	ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
1998
	ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
1999
	*available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
1999
	*available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
2000
	return 0;
2000
	return 0;
2001
}
2001
}
2002

    
   
2002

   
2003
static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
2003
static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
2004
{
2004
{
2005
	struct ast_str *body = ast_str_alloca(size);
2005
	struct ast_str *body = ast_str_alloca(size);
2006
	char tuple_id[32];
2006
	char tuple_id[32];
2007

    
   
2007

   
2008
	generate_random_string(tuple_id, sizeof(tuple_id));
2008
	generate_random_string(tuple_id, sizeof(tuple_id));
2009

    
   
2009

   
2010
	/* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
2010
	/* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
2011
	 * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
2011
	 * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
2012
	 */
2012
	 */
2013
	ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2013
	ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2014
	/* XXX The entity attribute is currently set to the peer name associated with the
2014
	/* XXX The entity attribute is currently set to the peer name associated with the
2015
	 * dialog. This is because we currently only call this function for call-completion
2015
	 * dialog. This is because we currently only call this function for call-completion
2016
	 * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
2016
	 * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
2017
	 * event packages, it may be crucial to have a proper URI as the presentity so this
2017
	 * event packages, it may be crucial to have a proper URI as the presentity so this
2018
	 * should be revisited as support is expanded.
2018
	 * should be revisited as support is expanded.
2019
	 */
2019
	 */
2020
	ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
2020
	ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
2021
	ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
2021
	ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
2022
	ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
2022
	ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
2023
	ast_str_append(&body, 0, "</tuple>\n");
2023
	ast_str_append(&body, 0, "</tuple>\n");
2024
	ast_str_append(&body, 0, "</presence>\n");
2024
	ast_str_append(&body, 0, "</presence>\n");
2025
	ast_copy_string(pidf_body, ast_str_buffer(body), size);
2025
	ast_copy_string(pidf_body, ast_str_buffer(body), size);
2026
	return 0;
2026
	return 0;
2027
}
2027
}
2028

    
   
2028

   
2029
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
2029
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
2030
{
2030
{
2031
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
2031
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
2032
	enum sip_publish_type publish_type;
2032
	enum sip_publish_type publish_type;
2033
	struct cc_epa_entry *cc_entry;
2033
	struct cc_epa_entry *cc_entry;
2034

    
   
2034

   
2035
	if (!monitor_instance) {
2035
	if (!monitor_instance) {
2036
		return -1;
2036
		return -1;
2037
	}
2037
	}
2038

    
   
2038

   
2039
	if (!monitor_instance->suspension_entry) {
2039
	if (!monitor_instance->suspension_entry) {
2040
		/* We haven't yet allocated the suspension entry, so let's give it a shot */
2040
		/* We haven't yet allocated the suspension entry, so let's give it a shot */
2041
		if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
2041
		if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
2042
			ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
2042
			ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
2043
			ao2_ref(monitor_instance, -1);
2043
			ao2_ref(monitor_instance, -1);
2044
			return -1;
2044
			return -1;
2045
		}
2045
		}
2046
		if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
2046
		if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
2047
			ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
2047
			ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
2048
			ao2_ref(monitor_instance, -1);
2048
			ao2_ref(monitor_instance, -1);
2049
			return -1;
2049
			return -1;
2050
		}
2050
		}
2051
		cc_entry->core_id = monitor->core_id;
2051
		cc_entry->core_id = monitor->core_id;
2052
		monitor_instance->suspension_entry->instance_data = cc_entry;
2052
		monitor_instance->suspension_entry->instance_data = cc_entry;
2053
		publish_type = SIP_PUBLISH_INITIAL;
2053
		publish_type = SIP_PUBLISH_INITIAL;
2054
	} else {
2054
	} else {
2055
		publish_type = SIP_PUBLISH_MODIFY;
2055
		publish_type = SIP_PUBLISH_MODIFY;
2056
		cc_entry = monitor_instance->suspension_entry->instance_data;
2056
		cc_entry = monitor_instance->suspension_entry->instance_data;
2057
	}
2057
	}
2058

    
   
2058

   
2059
	cc_entry->current_state = CC_CLOSED;
2059
	cc_entry->current_state = CC_CLOSED;
2060

    
   
2060

   
2061
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
2061
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
2062
		/* If we have no set notify_uri, then what this means is that we have
2062
		/* If we have no set notify_uri, then what this means is that we have
2063
		 * not received a NOTIFY from this destination stating that he is
2063
		 * not received a NOTIFY from this destination stating that he is
2064
		 * currently available.
2064
		 * currently available.
2065
		 *
2065
		 *
2066
		 * This situation can arise when the core calls the suspend callbacks
2066
		 * This situation can arise when the core calls the suspend callbacks
2067
		 * of multiple destinations. If one of the other destinations aside
2067
		 * of multiple destinations. If one of the other destinations aside
2068
		 * from this one notified Asterisk that he is available, then there
2068
		 * from this one notified Asterisk that he is available, then there
2069
		 * is no reason to take any suspension action on this device. Rather,
2069
		 * is no reason to take any suspension action on this device. Rather,
2070
		 * we should return now and if we receive a NOTIFY while monitoring
2070
		 * we should return now and if we receive a NOTIFY while monitoring
2071
		 * is still "suspended" then we can immediately respond with the
2071
		 * is still "suspended" then we can immediately respond with the
2072
		 * proper PUBLISH to let this endpoint know what is going on.
2072
		 * proper PUBLISH to let this endpoint know what is going on.
2073
		 */
2073
		 */
2074
		return 0;
2074
		return 0;
2075
	}
2075
	}
2076
	construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2076
	construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2077
	return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
2077
	return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
2078
}
2078
}
2079

    
   
2079

   
2080
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
2080
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
2081
{
2081
{
2082
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
2082
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
2083
	struct cc_epa_entry *cc_entry;
2083
	struct cc_epa_entry *cc_entry;
2084

    
   
2084

   
2085
	if (!monitor_instance) {
2085
	if (!monitor_instance) {
2086
		return -1;
2086
		return -1;
2087
	}
2087
	}
2088

    
   
2088

   
2089
	ast_assert(monitor_instance->suspension_entry != NULL);
2089
	ast_assert(monitor_instance->suspension_entry != NULL);
2090

    
   
2090

   
2091
	cc_entry = monitor_instance->suspension_entry->instance_data;
2091
	cc_entry = monitor_instance->suspension_entry->instance_data;
2092
	cc_entry->current_state = CC_OPEN;
2092
	cc_entry->current_state = CC_OPEN;
2093
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
2093
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
2094
		/* This means we are being asked to unsuspend a call leg we never
2094
		/* This means we are being asked to unsuspend a call leg we never
2095
		 * sent a PUBLISH on. As such, there is no reason to send another
2095
		 * sent a PUBLISH on. As such, there is no reason to send another
2096
		 * PUBLISH at this point either. We can just return instead.
2096
		 * PUBLISH at this point either. We can just return instead.
2097
		 */
2097
		 */
2098
		return 0;
2098
		return 0;
2099
	}
2099
	}
2100
	construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2100
	construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2101
	return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
2101
	return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
2102
}
2102
}
2103

    
   
2103

   
2104
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
2104
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
2105
{
2105
{
2106
	if (*sched_id != -1) {
2106
	if (*sched_id != -1) {
2107
		AST_SCHED_DEL(sched, *sched_id);
2107
		AST_SCHED_DEL(sched, *sched_id);
2108
		ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
2108
		ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
2109
	}
2109
	}
2110
	return 0;
2110
	return 0;
2111
}
2111
}
2112

    
   
2112

   
2113
static void sip_cc_monitor_destructor(void *private_data)
2113
static void sip_cc_monitor_destructor(void *private_data)
2114
{
2114
{
2115
	struct sip_monitor_instance *monitor_instance = private_data;
2115
	struct sip_monitor_instance *monitor_instance = private_data;
2116
	ao2_unlink(sip_monitor_instances, monitor_instance);
2116
	ao2_unlink(sip_monitor_instances, monitor_instance);
2117
	ast_module_unref(ast_module_info->self);
2117
	ast_module_unref(ast_module_info->self);
2118
}
2118
}
2119

    
   
2119

   
2120
static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
2120
static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
2121
{
2121
{
2122
	char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
2122
	char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
2123
	char *uri;
2123
	char *uri;
2124
	char *purpose;
2124
	char *purpose;
2125
	char *service_str;
2125
	char *service_str;
2126
	static const char cc_purpose[] = "purpose=call-completion";
2126
	static const char cc_purpose[] = "purpose=call-completion";
2127
	static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2127
	static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2128

    
   
2128

   
2129
	if (ast_strlen_zero(call_info)) {
2129
	if (ast_strlen_zero(call_info)) {
2130
		/* No Call-Info present. Definitely no CC offer */
2130
		/* No Call-Info present. Definitely no CC offer */
2131
		return -1;
2131
		return -1;
2132
	}
2132
	}
2133

    
   
2133

   
2134
	uri = strsep(&call_info, ";");
2134
	uri = strsep(&call_info, ";");
2135

    
   
2135

   
2136
	while ((purpose = strsep(&call_info, ";"))) {
2136
	while ((purpose = strsep(&call_info, ";"))) {
2137
		if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
2137
		if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
2138
			break;
2138
			break;
2139
		}
2139
		}
2140
	}
2140
	}
2141
	if (!purpose) {
2141
	if (!purpose) {
2142
		/* We didn't find the appropriate purpose= parameter. Oh well */
2142
		/* We didn't find the appropriate purpose= parameter. Oh well */
2143
		return -1;
2143
		return -1;
2144
	}
2144
	}
2145

    
   
2145

   
2146
	/* Okay, call-completion has been offered. Let's figure out what type of service this is */
2146
	/* Okay, call-completion has been offered. Let's figure out what type of service this is */
2147
	while ((service_str = strsep(&call_info, ";"))) {
2147
	while ((service_str = strsep(&call_info, ";"))) {
2148
		if (!strncmp(service_str, "m=", 2)) {
2148
		if (!strncmp(service_str, "m=", 2)) {
2149
			break;
2149
			break;
2150
		}
2150
		}
2151
	}
2151
	}
2152
	if (!service_str) {
2152
	if (!service_str) {
2153
		/* So they didn't offer a particular service, We'll just go with CCBS since it really
2153
		/* So they didn't offer a particular service, We'll just go with CCBS since it really
2154
		 * doesn't matter anyway
2154
		 * doesn't matter anyway
2155
		 */
2155
		 */
2156
		service_str = "BS";
2156
		service_str = "BS";
2157
	} else {
2157
	} else {
2158
		/* We already determined that there is an "m=" so no need to check
2158
		/* We already determined that there is an "m=" so no need to check
2159
		 * the result of this strsep
2159
		 * the result of this strsep
2160
		 */
2160
		 */
2161
		strsep(&service_str, "=");
2161
		strsep(&service_str, "=");
2162
	}
2162
	}
2163

    
   
2163

   
2164
	if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2164
	if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2165
		/* Invalid service offered */
2165
		/* Invalid service offered */
2166
		return -1;
2166
		return -1;
2167
	}
2167
	}
2168

    
   
2168

   
2169
	ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2169
	ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2170

    
   
2170

   
2171
	return 0;
2171
	return 0;
2172
}
2172
}
2173

    
   
2173

   
2174
/*
2174
/*
2175
 * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
2175
 * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
2176
 *
2176
 *
2177
 * After taking care of some formalities to be sure that this call is eligible for CC,
2177
 * After taking care of some formalities to be sure that this call is eligible for CC,
2178
 * we first try to see if we can make use of native CC. We grab the information from
2178
 * we first try to see if we can make use of native CC. We grab the information from
2179
 * the passed-in sip_request (which is always a response to an INVITE). If we can
2179
 * the passed-in sip_request (which is always a response to an INVITE). If we can
2180
 * use native CC monitoring for the call, then so be it.
2180
 * use native CC monitoring for the call, then so be it.
2181
 *
2181
 *
2182
 * If native cc monitoring is not possible or not supported, then we will instead attempt
2182
 * If native cc monitoring is not possible or not supported, then we will instead attempt
2183
 * to use generic monitoring. Falling back to generic from a failed attempt at using native
2183
 * to use generic monitoring. Falling back to generic from a failed attempt at using native
2184
 * monitoring will only work if the monitor policy of the endpoint is "always"
2184
 * monitoring will only work if the monitor policy of the endpoint is "always"
2185
 *
2185
 *
2186
 * \param pvt The current dialog. Contains CC parameters for the endpoint
2186
 * \param pvt The current dialog. Contains CC parameters for the endpoint
2187
 * \param req The response to the INVITE we want to inspect
2187
 * \param req The response to the INVITE we want to inspect
2188
 * \param service The service to use if generic monitoring is to be used. For native
2188
 * \param service The service to use if generic monitoring is to be used. For native
2189
 * monitoring, we get the service from the SIP response itself
2189
 * monitoring, we get the service from the SIP response itself
2190
 */
2190
 */
2191
static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
2191
static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
2192
{
2192
{
2193
	enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
2193
	enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
2194
	int core_id;
2194
	int core_id;
2195
	char interface_name[AST_CHANNEL_NAME];
2195
	char interface_name[AST_CHANNEL_NAME];
2196

    
   
2196

   
2197
	if (monitor_policy == AST_CC_MONITOR_NEVER) {
2197
	if (monitor_policy == AST_CC_MONITOR_NEVER) {
2198
		/* Don't bother, just return */
2198
		/* Don't bother, just return */
2199
		return;
2199
		return;
2200
	}
2200
	}
2201

    
   
2201

   
2202
	if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
2202
	if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
2203
		/* For some reason, CC is invalid, so don't try it! */
2203
		/* For some reason, CC is invalid, so don't try it! */
2204
		return;
2204
		return;
2205
	}
2205
	}
2206

    
   
2206

   
2207
	ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2207
	ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2208

    
   
2208

   
2209
	if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
2209
	if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
2210
		char subscribe_uri[SIPBUFSIZE];
2210
		char subscribe_uri[SIPBUFSIZE];
2211
		char device_name[AST_CHANNEL_NAME];
2211
		char device_name[AST_CHANNEL_NAME];
2212
		enum ast_cc_service_type offered_service;
2212
		enum ast_cc_service_type offered_service;
2213
		struct sip_monitor_instance *monitor_instance;
2213
		struct sip_monitor_instance *monitor_instance;
2214
		if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
2214
		if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
2215
			/* If CC isn't being offered to us, or for some reason the CC offer is
2215
			/* If CC isn't being offered to us, or for some reason the CC offer is
2216
			 * not formatted correctly, then it may still be possible to use generic
2216
			 * not formatted correctly, then it may still be possible to use generic
2217
			 * call completion since the monitor policy may be "always"
2217
			 * call completion since the monitor policy may be "always"
2218
			 */
2218
			 */
2219
			goto generic;
2219
			goto generic;
2220
		}
2220
		}
2221
		ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2221
		ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2222
		if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
2222
		if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
2223
			/* Same deal. We can try using generic still */
2223
			/* Same deal. We can try using generic still */
2224
			goto generic;
2224
			goto generic;
2225
		}
2225
		}
2226
		/* We bump the refcount of chan_sip because once we queue this frame, the CC core
2226
		/* We bump the refcount of chan_sip because once we queue this frame, the CC core
2227
		 * will have a reference to callbacks in this module. We decrement the module
2227
		 * will have a reference to callbacks in this module. We decrement the module
2228
		 * refcount once the monitor destructor is called
2228
		 * refcount once the monitor destructor is called
2229
		 */
2229
		 */
2230
		ast_module_ref(ast_module_info->self);
2230
		ast_module_ref(ast_module_info->self);
2231
		ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
2231
		ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
2232
		ao2_ref(monitor_instance, -1);
2232
		ao2_ref(monitor_instance, -1);
2233
		return;
2233
		return;
2234
	}
2234
	}
2235

    
   
2235

   
2236
generic:
2236
generic:
2237
	if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2237
	if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2238
		ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2238
		ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2239
	}
2239
	}
2240
}
2240
}
2241

    
   
2241

   
2242
/*! \brief Working TLS connection configuration */
2242
/*! \brief Working TLS connection configuration */
2243
static struct ast_tls_config sip_tls_cfg;
2243
static struct ast_tls_config sip_tls_cfg;
2244

    
   
2244

   
2245
/*! \brief Default TLS connection configuration */
2245
/*! \brief Default TLS connection configuration */
2246
static struct ast_tls_config default_tls_cfg;
2246
static struct ast_tls_config default_tls_cfg;
2247

    
   
2247

   
2248
/*! \brief The TCP server definition */
2248
/*! \brief The TCP server definition */
2249
static struct ast_tcptls_session_args sip_tcp_desc = {
2249
static struct ast_tcptls_session_args sip_tcp_desc = {
2250
	.accept_fd = -1,
2250
	.accept_fd = -1,
2251
	.master = AST_PTHREADT_NULL,
2251
	.master = AST_PTHREADT_NULL,
2252
	.tls_cfg = NULL,
2252
	.tls_cfg = NULL,
2253
	.poll_timeout = -1,
2253
	.poll_timeout = -1,
2254
	.name = "SIP TCP server",
2254
	.name = "SIP TCP server",
2255
	.accept_fn = ast_tcptls_server_root,
2255
	.accept_fn = ast_tcptls_server_root,
2256
	.worker_fn = sip_tcp_worker_fn,
2256
	.worker_fn = sip_tcp_worker_fn,
2257
};
2257
};
2258

    
   
2258

   
2259
/*! \brief The TCP/TLS server definition */
2259
/*! \brief The TCP/TLS server definition */
2260
static struct ast_tcptls_session_args sip_tls_desc = {
2260
static struct ast_tcptls_session_args sip_tls_desc = {
2261
	.accept_fd = -1,
2261
	.accept_fd = -1,
2262
	.master = AST_PTHREADT_NULL,
2262
	.master = AST_PTHREADT_NULL,
2263
	.tls_cfg = &sip_tls_cfg,
2263
	.tls_cfg = &sip_tls_cfg,
2264
	.poll_timeout = -1,
2264
	.poll_timeout = -1,
2265
	.name = "SIP TLS server",
2265
	.name = "SIP TLS server",
2266
	.accept_fn = ast_tcptls_server_root,
2266
	.accept_fn = ast_tcptls_server_root,
2267
	.worker_fn = sip_tcp_worker_fn,
2267
	.worker_fn = sip_tcp_worker_fn,
2268
};
2268
};
2269

    
   
2269

   
2270
/*! \brief Append to SIP dialog history
2270
/*! \brief Append to SIP dialog history
2271
	\return Always returns 0 */
2271
	\return Always returns 0 */
2272
#define append_history(p, event, fmt , args... )	append_history_full(p, "%-15s " fmt, event, ## args)
2272
#define append_history(p, event, fmt , args... )	append_history_full(p, "%-15s " fmt, event, ## args)
2273

    
   
2273

   
2274
struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
2274
struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
2275
{
2275
{
2276
	if (p)
2276
	if (p)
2277
#ifdef REF_DEBUG
2277
#ifdef REF_DEBUG
2278
		__ao2_ref_debug(p, 1, tag, file, line, func);
2278
		__ao2_ref_debug(p, 1, tag, file, line, func);
2279
#else
2279
#else
2280
		ao2_ref(p, 1);
2280
		ao2_ref(p, 1);
2281
#endif
2281
#endif
2282
	else
2282
	else
2283
		ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2283
		ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2284
	return p;
2284
	return p;
2285
}
2285
}
2286

    
   
2286

   
2287
struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
2287
struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
2288
{
2288
{
2289
	if (p)
2289
	if (p)
2290
#ifdef REF_DEBUG
2290
#ifdef REF_DEBUG
2291
		__ao2_ref_debug(p, -1, tag, file, line, func);
2291
		__ao2_ref_debug(p, -1, tag, file, line, func);
2292
#else
2292
#else
2293
		ao2_ref(p, -1);
2293
		ao2_ref(p, -1);
2294
#endif
2294
#endif
2295
	return NULL;
2295
	return NULL;
2296
}
2296
}
2297

    
   
2297

   
2298
/*! \brief map from an integer value to a string.
2298
/*! \brief map from an integer value to a string.
2299
 * If no match is found, return errorstring
2299
 * If no match is found, return errorstring
2300
 */
2300
 */
2301
static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2301
static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2302
{
2302
{
2303
	const struct _map_x_s *cur;
2303
	const struct _map_x_s *cur;
2304

    
   
2304

   
2305
	for (cur = table; cur->s; cur++) {
2305
	for (cur = table; cur->s; cur++) {
2306
		if (cur->x == x) {
2306
		if (cur->x == x) {
2307
			return cur->s;
2307
			return cur->s;
2308
		}
2308
		}
2309
	}
2309
	}
2310
	return errorstring;
2310
	return errorstring;
2311
}
2311
}
2312

    
   
2312

   
2313
/*! \brief map from a string to an integer value, case insensitive.
2313
/*! \brief map from a string to an integer value, case insensitive.
2314
 * If no match is found, return errorvalue.
2314
 * If no match is found, return errorvalue.
2315
 */
2315
 */
2316
static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2316
static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2317
{
2317
{
2318
	const struct _map_x_s *cur;
2318
	const struct _map_x_s *cur;
2319

    
   
2319

   
2320
	for (cur = table; cur->s; cur++) {
2320
	for (cur = table; cur->s; cur++) {
2321
		if (!strcasecmp(cur->s, s)) {
2321
		if (!strcasecmp(cur->s, s)) {
2322
			return cur->x;
2322
			return cur->x;
2323
		}
2323
		}
2324
	}
2324
	}
2325
	return errorvalue;
2325
	return errorvalue;
2326
}
2326
}
2327

    
   
2327

   
2328
static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
2328
static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
2329
{
2329
{
2330
	enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2330
	enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2331
	int i;
2331
	int i;
2332

    
   
2332

   
2333
	for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
2333
	for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
2334
		if (!strcasecmp(text, sip_reason_table[i].text)) {
2334
		if (!strcasecmp(text, sip_reason_table[i].text)) {
2335
			ast = sip_reason_table[i].code;
2335
			ast = sip_reason_table[i].code;
2336
			break;
2336
			break;
2337
		}
2337
		}
2338
	}
2338
	}
2339

    
   
2339

   
2340
	return ast;
2340
	return ast;
2341
}
2341
}
2342

    
   
2342

   
2343
static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
2343
static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
2344
{
2344
{
2345
	if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2345
	if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2346
		return sip_reason_table[code].text;
2346
		return sip_reason_table[code].text;
2347
	}
2347
	}
2348

    
   
2348

   
2349
	return "unknown";
2349
	return "unknown";
2350
}
2350
}
2351

    
   
2351

   
2352
/*!
2352
/*!
2353
 * \brief generic function for determining if a correct transport is being
2353
 * \brief generic function for determining if a correct transport is being
2354
 * used to contact a peer
2354
 * used to contact a peer
2355
 *
2355
 *
2356
 * this is done as a macro so that the "tmpl" var can be passed either a
2356
 * this is done as a macro so that the "tmpl" var can be passed either a
2357
 * sip_request or a sip_peer
2357
 * sip_request or a sip_peer
2358
 */
2358
 */
2359
#define check_request_transport(peer, tmpl) ({ \
2359
#define check_request_transport(peer, tmpl) ({ \
2360
	int ret = 0; \
2360
	int ret = 0; \
2361
	if (peer->socket.type == tmpl->socket.type) \
2361
	if (peer->socket.type == tmpl->socket.type) \
2362
		; \
2362
		; \
2363
	else if (!(peer->transports & tmpl->socket.type)) {\
2363
	else if (!(peer->transports & tmpl->socket.type)) {\
2364
		ast_log(LOG_ERROR, \
2364
		ast_log(LOG_ERROR, \
2365
			"'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
2365
			"'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
2366
			sip_get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
2366
			sip_get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
2367
			); \
2367
			); \
2368
		ret = 1; \
2368
		ret = 1; \
2369
	} else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
2369
	} else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
2370
		ast_log(LOG_WARNING, \
2370
		ast_log(LOG_WARNING, \
2371
			"peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
2371
			"peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
2372
			peer->name, sip_get_transport(tmpl->socket.type) \
2372
			peer->name, sip_get_transport(tmpl->socket.type) \
2373
		); \
2373
		); \
2374
	} else { \
2374
	} else { \
2375
		ast_debug(1, \
2375
		ast_debug(1, \
2376
			"peer '%s' has contacted us over %s even though we prefer %s.\n", \
2376
			"peer '%s' has contacted us over %s even though we prefer %s.\n", \
2377
			peer->name, sip_get_transport(tmpl->socket.type), sip_get_transport(peer->socket.type) \
2377
			peer->name, sip_get_transport(tmpl->socket.type), sip_get_transport(peer->socket.type) \
2378
		); \
2378
		); \
2379
	}\
2379
	}\
2380
	(ret); \
2380
	(ret); \
2381
})
2381
})
2382

    
   
2382

   
2383
/*! \brief
2383
/*! \brief
2384
 * duplicate a list of channel variables, \return the copy.
2384
 * duplicate a list of channel variables, \return the copy.
2385
 */
2385
 */
2386
static struct ast_variable *copy_vars(struct ast_variable *src)
2386
static struct ast_variable *copy_vars(struct ast_variable *src)
2387
{
2387
{
2388
	struct ast_variable *res = NULL, *tmp, *v = NULL;
2388
	struct ast_variable *res = NULL, *tmp, *v = NULL;
2389

    
   
2389

   
2390
	for (v = src ; v ; v = v->next) {
2390
	for (v = src ; v ; v = v->next) {
2391
		if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2391
		if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2392
			tmp->next = res;
2392
			tmp->next = res;
2393
			res = tmp;
2393
			res = tmp;
2394
		}
2394
		}
2395
	}
2395
	}
2396
	return res;
2396
	return res;
2397
}
2397
}
2398

    
   
2398

   
2399
static void tcptls_packet_destructor(void *obj)
2399
static void tcptls_packet_destructor(void *obj)
2400
{
2400
{
2401
	struct tcptls_packet *packet = obj;
2401
	struct tcptls_packet *packet = obj;
2402

    
   
2402

   
2403
	ast_free(packet->data);
2403
	ast_free(packet->data);
2404
}
2404
}
2405

    
   
2405

   
2406
static void sip_tcptls_client_args_destructor(void *obj)
2406
static void sip_tcptls_client_args_destructor(void *obj)
2407
{
2407
{
2408
	struct ast_tcptls_session_args *args = obj;
2408
	struct ast_tcptls_session_args *args = obj;
2409
	if (args->tls_cfg) {
2409
	if (args->tls_cfg) {
2410
		ast_free(args->tls_cfg->certfile);
2410
		ast_free(args->tls_cfg->certfile);
2411
		ast_free(args->tls_cfg->pvtfile);
2411
		ast_free(args->tls_cfg->pvtfile);
2412
		ast_free(args->tls_cfg->cipher);
2412
		ast_free(args->tls_cfg->cipher);
2413
		ast_free(args->tls_cfg->cafile);
2413
		ast_free(args->tls_cfg->cafile);
2414
		ast_free(args->tls_cfg->capath);
2414
		ast_free(args->tls_cfg->capath);
2415
	}
2415
	}
2416
	ast_free(args->tls_cfg);
2416
	ast_free(args->tls_cfg);
2417
	ast_free((char *) args->name);
2417
	ast_free((char *) args->name);
2418
}
2418
}
2419

    
   
2419

   
2420
static void sip_threadinfo_destructor(void *obj)
2420
static void sip_threadinfo_destructor(void *obj)
2421
{
2421
{
2422
	struct sip_threadinfo *th = obj;
2422
	struct sip_threadinfo *th = obj;
2423
	struct tcptls_packet *packet;
2423
	struct tcptls_packet *packet;
2424

    
   
2424

   
2425
	if (th->alert_pipe[1] > -1) {
2425
	if (th->alert_pipe[1] > -1) {
2426
		close(th->alert_pipe[0]);
2426
		close(th->alert_pipe[0]);
2427
	}
2427
	}
2428
	if (th->alert_pipe[1] > -1) {
2428
	if (th->alert_pipe[1] > -1) {
2429
		close(th->alert_pipe[1]);
2429
		close(th->alert_pipe[1]);
2430
	}
2430
	}
2431
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2431
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2432

    
   
2432

   
2433
	while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2433
	while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2434
		ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
2434
		ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
2435
	}
2435
	}
2436

    
   
2436

   
2437
	if (th->tcptls_session) {
2437
	if (th->tcptls_session) {
2438
		ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
2438
		ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
2439
	}
2439
	}
2440
}
2440
}
2441

    
   
2441

   
2442
/*! \brief creates a sip_threadinfo object and links it into the threadt table. */
2442
/*! \brief creates a sip_threadinfo object and links it into the threadt table. */
2443
static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
2443
static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
2444
{
2444
{
2445
	struct sip_threadinfo *th;
2445
	struct sip_threadinfo *th;
2446

    
   
2446

   
2447
	if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
2447
	if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
2448
		return NULL;
2448
		return NULL;
2449
	}
2449
	}
2450

    
   
2450

   
2451
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2451
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2452

    
   
2452

   
2453
	if (pipe(th->alert_pipe) == -1) {
2453
	if (pipe(th->alert_pipe) == -1) {
2454
		ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
2454
		ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
2455
		ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
2455
		ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
2456
		return NULL;
2456
		return NULL;
2457
	}
2457
	}
2458
	ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
2458
	ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
2459
	th->tcptls_session = tcptls_session;
2459
	th->tcptls_session = tcptls_session;
2460
	th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
2460
	th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
2461
	ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2461
	ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2462
	ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
2462
	ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
2463
	return th;
2463
	return th;
2464
}
2464
}
2465

    
   
2465

   
2466
/*! \brief used to indicate to a tcptls thread that data is ready to be written */
2466
/*! \brief used to indicate to a tcptls thread that data is ready to be written */
2467
static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
2467
static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
2468
{
2468
{
2469
	int res = len;
2469
	int res = len;
2470
	struct sip_threadinfo *th = NULL;
2470
	struct sip_threadinfo *th = NULL;
2471
	struct tcptls_packet *packet = NULL;
2471
	struct tcptls_packet *packet = NULL;
2472
	struct sip_threadinfo tmp = {
2472
	struct sip_threadinfo tmp = {
2473
		.tcptls_session = tcptls_session,
2473
		.tcptls_session = tcptls_session,
2474
	};
2474
	};
2475
	enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2475
	enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2476

    
   
2476

   
2477
	if (!tcptls_session) {
2477
	if (!tcptls_session) {
2478
		return XMIT_ERROR;
2478
		return XMIT_ERROR;
2479
	}
2479
	}
2480

    
   
2480

   
2481
	ao2_lock(tcptls_session);
2481
	ao2_lock(tcptls_session);
2482

    
   
2482

   
2483
	if ((tcptls_session->fd == -1) ||
2483
	if ((tcptls_session->fd == -1) ||
2484
		!(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
2484
		!(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
2485
		!(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2485
		!(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2486
		!(packet->data = ast_str_create(len))) {
2486
		!(packet->data = ast_str_create(len))) {
2487
		goto tcptls_write_setup_error;
2487
		goto tcptls_write_setup_error;
2488
	}
2488
	}
2489

    
   
2489

   
2490
	/* goto tcptls_write_error should _NOT_ be used beyond this point */
2490
	/* goto tcptls_write_error should _NOT_ be used beyond this point */
2491
	ast_str_set(&packet->data, 0, "%s", (char *) buf);
2491
	ast_str_set(&packet->data, 0, "%s", (char *) buf);
2492
	packet->len = len;
2492
	packet->len = len;
2493

    
   
2493

   
2494
	/* alert tcptls thread handler that there is a packet to be sent.
2494
	/* alert tcptls thread handler that there is a packet to be sent.
2495
	 * must lock the thread info object to guarantee control of the
2495
	 * must lock the thread info object to guarantee control of the
2496
	 * packet queue */
2496
	 * packet queue */
2497
	ao2_lock(th);
2497
	ao2_lock(th);
2498
	if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2498
	if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2499
		ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
2499
		ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
2500
		ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
2500
		ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
2501
		packet = NULL;
2501
		packet = NULL;
2502
		res = XMIT_ERROR;
2502
		res = XMIT_ERROR;
2503
	} else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
2503
	} else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
2504
		AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2504
		AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2505
	}
2505
	}
2506
	ao2_unlock(th);
2506
	ao2_unlock(th);
2507

    
   
2507

   
2508
	ao2_unlock(tcptls_session);
2508
	ao2_unlock(tcptls_session);
2509
	ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
2509
	ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
2510
	return res;
2510
	return res;
2511

    
   
2511

   
2512
tcptls_write_setup_error:
2512
tcptls_write_setup_error:
2513
	if (th) {
2513
	if (th) {
2514
		ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
2514
		ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
2515
	}
2515
	}
2516
	if (packet) {
2516
	if (packet) {
2517
		ao2_t_ref(packet, -1, "could not allocate packet's data");
2517
		ao2_t_ref(packet, -1, "could not allocate packet's data");
2518
	}
2518
	}
2519
	ao2_unlock(tcptls_session);
2519
	ao2_unlock(tcptls_session);
2520

    
   
2520

   
2521
	return XMIT_ERROR;
2521
	return XMIT_ERROR;
2522
}
2522
}
2523

    
   
2523

   
2524
/*! \brief SIP TCP connection handler */
2524
/*! \brief SIP TCP connection handler */
2525
static void *sip_tcp_worker_fn(void *data)
2525
static void *sip_tcp_worker_fn(void *data)
2526
{
2526
{
2527
	struct ast_tcptls_session_instance *tcptls_session = data;
2527
	struct ast_tcptls_session_instance *tcptls_session = data;
2528

    
   
2528

   
2529
	return _sip_tcp_helper_thread(tcptls_session);
2529
	return _sip_tcp_helper_thread(tcptls_session);
2530
}
2530
}
2531

    
   
2531

   
2532
/*! \brief SIP WebSocket connection handler */
2532
/*! \brief SIP WebSocket connection handler */
2533
static void sip_websocket_callback(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
2533
static void sip_websocket_callback(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
2534
{
2534
{
2535
	int res;
2535
	int res;
2536

    
   
2536

   
2537
	if (ast_websocket_set_nonblock(session)) {
2537
	if (ast_websocket_set_nonblock(session)) {
2538
		goto end;
2538
		goto end;
2539
	}
2539
	}
2540

    
   
2540

   
2541
	while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {
2541
	while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {
2542
		char *payload;
2542
		char *payload;
2543
		uint64_t payload_len;
2543
		uint64_t payload_len;
2544
		enum ast_websocket_opcode opcode;
2544
		enum ast_websocket_opcode opcode;
2545
		int fragmented;
2545
		int fragmented;
2546

    
   
2546

   
2547
		if (ast_websocket_read(session, &payload, &payload_len, &opcode, &fragmented)) {
2547
		if (ast_websocket_read(session, &payload, &payload_len, &opcode, &fragmented)) {
2548
			/* We err on the side of caution and terminate the session if any error occurs */
2548
			/* We err on the side of caution and terminate the session if any error occurs */
2549
			break;
2549
			break;
2550
		}
2550
		}
2551

    
   
2551

   
2552
		if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
2552
		if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
2553
			struct sip_request req = { 0, };
2553
			struct sip_request req = { 0, };
2554

    
   
2554

   
2555
			if (!(req.data = ast_str_create(payload_len))) {
2555
			if (!(req.data = ast_str_create(payload_len))) {
2556
				goto end;
2556
				goto end;
2557
			}
2557
			}
2558

    
   
2558

   
2559
			if (ast_str_set(&req.data, -1, "%s", payload) == AST_DYNSTR_BUILD_FAILED) {
2559
			if (ast_str_set(&req.data, -1, "%s", payload) == AST_DYNSTR_BUILD_FAILED) {
2560
				deinit_req(&req);
2560
				deinit_req(&req);
2561
				goto end;
2561
				goto end;
2562
			}
2562
			}
2563

    
   
2563

   
2564
			req.socket.fd = ast_websocket_fd(session);
2564
			req.socket.fd = ast_websocket_fd(session);
2565
			set_socket_transport(&req.socket, ast_websocket_is_secure(session) ? SIP_TRANSPORT_WSS : SIP_TRANSPORT_WS);
2565
			set_socket_transport(&req.socket, ast_websocket_is_secure(session) ? SIP_TRANSPORT_WSS : SIP_TRANSPORT_WS);
2566
			req.socket.ws_session = session;
2566
			req.socket.ws_session = session;
2567

    
   
2567

   
2568
			handle_request_do(&req, ast_websocket_remote_address(session));
2568
			handle_request_do(&req, ast_websocket_remote_address(session));
2569
			deinit_req(&req);
2569
			deinit_req(&req);
2570

    
   
2570

   
2571
		} else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
2571
		} else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
2572
			break;
2572
			break;
2573
		}
2573
		}
2574
	}
2574
	}
2575

    
   
2575

   
2576
end:
2576
end:
2577
	ast_websocket_unref(session);
2577
	ast_websocket_unref(session);
2578
}
2578
}
2579

    
   
2579

   
2580
/*! \brief Check if the authtimeout has expired.
2580
/*! \brief Check if the authtimeout has expired.
2581
 * \param start the time when the session started
2581
 * \param start the time when the session started
2582
 *
2582
 *
2583
 * \retval 0 the timeout has expired
2583
 * \retval 0 the timeout has expired
2584
 * \retval -1 error
2584
 * \retval -1 error
2585
 * \return the number of milliseconds until the timeout will expire
2585
 * \return the number of milliseconds until the timeout will expire
2586
 */
2586
 */
2587
static int sip_check_authtimeout(time_t start)
2587
static int sip_check_authtimeout(time_t start)
2588
{
2588
{
2589
	int timeout;
2589
	int timeout;
2590
	time_t now;
2590
	time_t now;
2591
	if(time(&now) == -1) {
2591
	if(time(&now) == -1) {
2592
		ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
2592
		ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
2593
		return -1;
2593
		return -1;
2594
	}
2594
	}
2595

    
   
2595

   
2596
	timeout = (authtimeout - (now - start)) * 1000;
2596
	timeout = (authtimeout - (now - start)) * 1000;
2597
	if (timeout < 0) {
2597
	if (timeout < 0) {
2598
		/* we have timed out */
2598
		/* we have timed out */
2599
		return 0;
2599
		return 0;
2600
	}
2600
	}
2601

    
   
2601

   
2602
	return timeout;
2602
	return timeout;
2603
}
2603
}
2604

    
   
2604

   
2605
/*! \brief SIP TCP thread management function
2605
/*! \brief SIP TCP thread management function
2606
	This function reads from the socket, parses the packet into a request
2606
	This function reads from the socket, parses the packet into a request
2607
*/
2607
*/
2608
static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
2608
static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
2609
{
2609
{
2610
	int res, cl, timeout = -1, authenticated = 0, flags, after_poll = 0, need_poll = 1;
2610
	int res, cl, timeout = -1, authenticated = 0, flags, after_poll = 0, need_poll = 1;
2611
	time_t start;
2611
	time_t start;
2612
	struct sip_request req = { 0, } , reqcpy = { 0, };
2612
	struct sip_request req = { 0, } , reqcpy = { 0, };
2613
	struct sip_threadinfo *me = NULL;
2613
	struct sip_threadinfo *me = NULL;
2614
	char buf[1024] = "";
2614
	char buf[1024] = "";
2615
	struct pollfd fds[2] = { { 0 }, { 0 }, };
2615
	struct pollfd fds[2] = { { 0 }, { 0 }, };
2616
	struct ast_tcptls_session_args *ca = NULL;
2616
	struct ast_tcptls_session_args *ca = NULL;
2617

    
   
2617

   
2618
	/* If this is a server session, then the connection has already been
2618
	/* If this is a server session, then the connection has already been
2619
	 * setup. Check if the authlimit has been reached and if not create the
2619
	 * setup. Check if the authlimit has been reached and if not create the
2620
	 * threadinfo object so we can access this thread for writing.
2620
	 * threadinfo object so we can access this thread for writing.
2621
	 *
2621
	 *
2622
	 * if this is a client connection more work must be done.
2622
	 * if this is a client connection more work must be done.
2623
	 * 1. We own the parent session args for a client connection.  This pointer needs
2623
	 * 1. We own the parent session args for a client connection.  This pointer needs
2624
	 *    to be held on to so we can decrement it's ref count on thread destruction.
2624
	 *    to be held on to so we can decrement it's ref count on thread destruction.
2625
	 * 2. The threadinfo object was created before this thread was launched, however
2625
	 * 2. The threadinfo object was created before this thread was launched, however
2626
	 *    it must be found within the threadt table.
2626
	 *    it must be found within the threadt table.
2627
	 * 3. Last, the tcptls_session must be started.
2627
	 * 3. Last, the tcptls_session must be started.
2628
	 */
2628
	 */
2629
	if (!tcptls_session->client) {
2629
	if (!tcptls_session->client) {
2630
		if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
2630
		if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
2631
			/* unauth_sessions is decremented in the cleanup code */
2631
			/* unauth_sessions is decremented in the cleanup code */
2632
			goto cleanup;
2632
			goto cleanup;
2633
		}
2633
		}
2634

    
   
2634

   
2635
		if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
2635
		if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
2636
			ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
2636
			ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
2637
			goto cleanup;
2637
			goto cleanup;
2638
		}
2638
		}
2639

    
   
2639

   
2640
		flags |= O_NONBLOCK;
2640
		flags |= O_NONBLOCK;
2641
		if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
2641
		if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
2642
			ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
2642
			ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
2643
			goto cleanup;
2643
			goto cleanup;
2644
		}
2644
		}
2645

    
   
2645

   
2646
		if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
2646
		if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
2647
			goto cleanup;
2647
			goto cleanup;
2648
		}
2648
		}
2649
		ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
2649
		ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
2650
	} else {
2650
	} else {
2651
		struct sip_threadinfo tmp = {
2651
		struct sip_threadinfo tmp = {
2652
			.tcptls_session = tcptls_session,
2652
			.tcptls_session = tcptls_session,
2653
		};
2653
		};
2654

    
   
2654

   
2655
		if ((!(ca = tcptls_session->parent)) ||
2655
		if ((!(ca = tcptls_session->parent)) ||
2656
			(!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
2656
			(!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
2657
			(!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
2657
			(!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
2658
			goto cleanup;
2658
			goto cleanup;
2659
		}
2659
		}
2660
	}
2660
	}
2661

    
   
2661

   
2662
	flags = 1;
2662
	flags = 1;
2663
	if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
2663
	if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
2664
		ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
2664
		ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
2665
		goto cleanup;
2665
		goto cleanup;
2666
	}
2666
	}
2667

    
   
2667

   
2668
	me->threadid = pthread_self();
2668
	me->threadid = pthread_self();
2669
	ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
2669
	ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
2670

    
   
2670

   
2671
	/* set up pollfd to watch for reads on both the socket and the alert_pipe */
2671
	/* set up pollfd to watch for reads on both the socket and the alert_pipe */
2672
	fds[0].fd = tcptls_session->fd;
2672
	fds[0].fd = tcptls_session->fd;
2673
	fds[1].fd = me->alert_pipe[0];
2673
	fds[1].fd = me->alert_pipe[0];
2674
	fds[0].events = fds[1].events = POLLIN | POLLPRI;
2674
	fds[0].events = fds[1].events = POLLIN | POLLPRI;
2675

    
   
2675

   
2676
	if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
2676
	if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
2677
		goto cleanup;
2677
		goto cleanup;
2678
	}
2678
	}
2679
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
2679
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
2680
		goto cleanup;
2680
		goto cleanup;
2681
	}
2681
	}
2682

    
   
2682

   
2683
	if(time(&start) == -1) {
2683
	if(time(&start) == -1) {
2684
		ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
2684
		ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
2685
		goto cleanup;
2685
		goto cleanup;
2686
	}
2686
	}
2687

    
   
2687

   
2688
	for (;;) {
2688
	for (;;) {
2689
		struct ast_str *str_save;
2689
		struct ast_str *str_save;
2690

    
   
2690

   
2691
		if (!tcptls_session->client && req.authenticated && !authenticated) {
2691
		if (!tcptls_session->client && req.authenticated && !authenticated) {
2692
			authenticated = 1;
2692
			authenticated = 1;
2693
			ast_atomic_fetchadd_int(&unauth_sessions, -1);
2693
			ast_atomic_fetchadd_int(&unauth_sessions, -1);
2694
		}
2694
		}
2695

    
   
2695

   
2696
		/* calculate the timeout for unauthenticated server sessions */
2696
		/* calculate the timeout for unauthenticated server sessions */
2697
		if (!tcptls_session->client && !authenticated ) {
2697
		if (!tcptls_session->client && !authenticated ) {
2698
			if ((timeout = sip_check_authtimeout(start)) < 0) {
2698
			if ((timeout = sip_check_authtimeout(start)) < 0) {
2699
				goto cleanup;
2699
				goto cleanup;
2700
			}
2700
			}
2701

    
   
2701

   
2702
			if (timeout == 0) {
2702
			if (timeout == 0) {
2703
				ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
2703
				ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
2704
				goto cleanup;
2704
				goto cleanup;
2705
			}
2705
			}
2706
		} else {
2706
		} else {
2707
			timeout = -1;
2707
			timeout = -1;
2708
		}
2708
		}
2709

    
   
2709

   
2710
		res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
2710
		res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
2711
		if (res < 0) {
2711
		if (res < 0) {
2712
			ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
2712
			ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
2713
			goto cleanup;
2713
			goto cleanup;
2714
		} else if (res == 0) {
2714
		} else if (res == 0) {
2715
			/* timeout */
2715
			/* timeout */
2716
			ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
2716
			ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
2717
			goto cleanup;
2717
			goto cleanup;
2718
		}
2718
		}
2719

    
   
2719

   
2720
		/* handle the socket event, check for both reads from the socket fd,
2720
		/* handle the socket event, check for both reads from the socket fd,
2721
		 * and writes from alert_pipe fd */
2721
		 * and writes from alert_pipe fd */
2722
		if (fds[0].revents) { /* there is data on the socket to be read */
2722
		if (fds[0].revents) { /* there is data on the socket to be read */
2723
			after_poll = 1;
2723
			after_poll = 1;
2724

    
   
2724

   
2725
			fds[0].revents = 0;
2725
			fds[0].revents = 0;
2726

    
   
2726

   
2727
			/* clear request structure */
2727
			/* clear request structure */
2728
			str_save = req.data;
2728
			str_save = req.data;
2729
			memset(&req, 0, sizeof(req));
2729
			memset(&req, 0, sizeof(req));
2730
			req.data = str_save;
2730
			req.data = str_save;
2731
			ast_str_reset(req.data);
2731
			ast_str_reset(req.data);
2732

    
   
2732

   
2733
			str_save = reqcpy.data;
2733
			str_save = reqcpy.data;
2734
			memset(&reqcpy, 0, sizeof(reqcpy));
2734
			memset(&reqcpy, 0, sizeof(reqcpy));
2735
			reqcpy.data = str_save;
2735
			reqcpy.data = str_save;
2736
			ast_str_reset(reqcpy.data);
2736
			ast_str_reset(reqcpy.data);
2737

    
   
2737

   
2738
			memset(buf, 0, sizeof(buf));
2738
			memset(buf, 0, sizeof(buf));
2739

    
   
2739

   
2740
			if (tcptls_session->ssl) {
2740
			if (tcptls_session->ssl) {
2741
				set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
2741
				set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
2742
				req.socket.port = htons(ourport_tls);
2742
				req.socket.port = htons(ourport_tls);
2743
			} else {
2743
			} else {
2744
				set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
2744
				set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
2745
				req.socket.port = htons(ourport_tcp);
2745
				req.socket.port = htons(ourport_tcp);
2746
			}
2746
			}
2747
			req.socket.fd = tcptls_session->fd;
2747
			req.socket.fd = tcptls_session->fd;
2748

    
   
2748

   
2749
			/* Read in headers one line at a time */
2749
			/* Read in headers one line at a time */
2750
			while (ast_str_strlen(req.data) < 4 || strncmp(REQ_OFFSET_TO_STR(&req, data->used - 4), "\r\n\r\n", 4)) {
2750
			while (ast_str_strlen(req.data) < 4 || strncmp(REQ_OFFSET_TO_STR(&req, data->used - 4), "\r\n\r\n", 4)) {
2751
				if (!tcptls_session->client && !authenticated ) {
2751
				if (!tcptls_session->client && !authenticated ) {
2752
					if ((timeout = sip_check_authtimeout(start)) < 0) {
2752
					if ((timeout = sip_check_authtimeout(start)) < 0) {
2753
						goto cleanup;
2753
						goto cleanup;
2754
					}
2754
					}
2755

    
   
2755

   
2756
					if (timeout == 0) {
2756
					if (timeout == 0) {
2757
						ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
2757
						ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
2758
						goto cleanup;
2758
						goto cleanup;
2759
					}
2759
					}
2760
				} else {
2760
				} else {
2761
					timeout = -1;
2761
					timeout = -1;
2762
				}
2762
				}
2763

    
   
2763

   
2764
				/* special polling behavior is required for TLS
2764
				/* special polling behavior is required for TLS
2765
				 * sockets because of the buffering done in the
2765
				 * sockets because of the buffering done in the
2766
				 * TLS layer */
2766
				 * TLS layer */
2767
				if (!tcptls_session->ssl || need_poll) {
2767
				if (!tcptls_session->ssl || need_poll) {
2768
					need_poll = 0;
2768
					need_poll = 0;
2769
					after_poll = 1;
2769
					after_poll = 1;
2770
					res = ast_wait_for_input(tcptls_session->fd, timeout);
2770
					res = ast_wait_for_input(tcptls_session->fd, timeout);
2771
					if (res < 0) {
2771
					if (res < 0) {
2772
						ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
2772
						ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
2773
						goto cleanup;
2773
						goto cleanup;
2774
					} else if (res == 0) {
2774
					} else if (res == 0) {
2775
						/* timeout */
2775
						/* timeout */
2776
						ast_debug(2, "SIP TCP server timed out\n");
2776
						ast_debug(2, "SIP TCP server timed out\n");
2777
						goto cleanup;
2777
						goto cleanup;
2778
					}
2778
					}
2779
				}
2779
				}
2780

    
   
2780

   
2781
				ao2_lock(tcptls_session);
2781
				ao2_lock(tcptls_session);
2782
				if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2782
				if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2783
					ao2_unlock(tcptls_session);
2783
					ao2_unlock(tcptls_session);
2784
					if (after_poll) {
2784
					if (after_poll) {
2785
						goto cleanup;
2785
						goto cleanup;
2786
					} else {
2786
					} else {
2787
						need_poll = 1;
2787
						need_poll = 1;
2788
						continue;
2788
						continue;
2789
					}
2789
					}
2790
				}
2790
				}
2791
				ao2_unlock(tcptls_session);
2791
				ao2_unlock(tcptls_session);
2792
				after_poll = 0;
2792
				after_poll = 0;
2793
				if (me->stop) {
2793
				if (me->stop) {
2794
					 goto cleanup;
2794
					 goto cleanup;
2795
				}
2795
				}
2796
				ast_str_append(&req.data, 0, "%s", buf);
2796
				ast_str_append(&req.data, 0, "%s", buf);
2797
			}
2797
			}
2798
			copy_request(&reqcpy, &req);
2798
			copy_request(&reqcpy, &req);
2799
			parse_request(&reqcpy);
2799
			parse_request(&reqcpy);
2800
			/* In order to know how much to read, we need the content-length header */
2800
			/* In order to know how much to read, we need the content-length header */
2801
			if (sscanf(sip_get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
2801
			if (sscanf(sip_get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
2802
				while (cl > 0) {
2802
				while (cl > 0) {
2803
					size_t bytes_read;
2803
					size_t bytes_read;
2804
					if (!tcptls_session->client && !authenticated ) {
2804
					if (!tcptls_session->client && !authenticated ) {
2805
						if ((timeout = sip_check_authtimeout(start)) < 0) {
2805
						if ((timeout = sip_check_authtimeout(start)) < 0) {
2806
							goto cleanup;
2806
							goto cleanup;
2807
						}
2807
						}
2808

    
   
2808

   
2809
						if (timeout == 0) {
2809
						if (timeout == 0) {
2810
							ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
2810
							ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
2811
							goto cleanup;
2811
							goto cleanup;
2812
						}
2812
						}
2813
					} else {
2813
					} else {
2814
						timeout = -1;
2814
						timeout = -1;
2815
					}
2815
					}
2816

    
   
2816

   
2817
					if (!tcptls_session->ssl || need_poll) {
2817
					if (!tcptls_session->ssl || need_poll) {
2818
						need_poll = 0;
2818
						need_poll = 0;
2819
						after_poll = 1;
2819
						after_poll = 1;
2820
						res = ast_wait_for_input(tcptls_session->fd, timeout);
2820
						res = ast_wait_for_input(tcptls_session->fd, timeout);
2821
						if (res < 0) {
2821
						if (res < 0) {
2822
							ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
2822
							ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
2823
							goto cleanup;
2823
							goto cleanup;
2824
						} else if (res == 0) {
2824
						} else if (res == 0) {
2825
							/* timeout */
2825
							/* timeout */
2826
							ast_debug(2, "SIP TCP server timed out\n");
2826
							ast_debug(2, "SIP TCP server timed out\n");
2827
							goto cleanup;
2827
							goto cleanup;
2828
						}
2828
						}
2829
					}
2829
					}
2830

    
   
2830

   
2831
					ao2_lock(tcptls_session);
2831
					ao2_lock(tcptls_session);
2832
					if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
2832
					if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
2833
						ao2_unlock(tcptls_session);
2833
						ao2_unlock(tcptls_session);
2834
						if (after_poll) {
2834
						if (after_poll) {
2835
							goto cleanup;
2835
							goto cleanup;
2836
						} else {
2836
						} else {
2837
							need_poll = 1;
2837
							need_poll = 1;
2838
							continue;
2838
							continue;
2839
						}
2839
						}
2840
					}
2840
					}
2841
					buf[bytes_read] = '\0';
2841
					buf[bytes_read] = '\0';
2842
					ao2_unlock(tcptls_session);
2842
					ao2_unlock(tcptls_session);
2843
					after_poll = 0;
2843
					after_poll = 0;
2844
					if (me->stop) {
2844
					if (me->stop) {
2845
						goto cleanup;
2845
						goto cleanup;
2846
					}
2846
					}
2847
					cl -= strlen(buf);
2847
					cl -= strlen(buf);
2848
					ast_str_append(&req.data, 0, "%s", buf);
2848
					ast_str_append(&req.data, 0, "%s", buf);
2849
				}
2849
				}
2850
			}
2850
			}
2851
			/*! \todo XXX If there's no Content-Length or if the content-length and what
2851
			/*! \todo XXX If there's no Content-Length or if the content-length and what
2852
					we receive is not the same - we should generate an error */
2852
					we receive is not the same - we should generate an error */
2853

    
   
2853

   
2854
			req.socket.tcptls_session = tcptls_session;
2854
			req.socket.tcptls_session = tcptls_session;
2855
			req.socket.ws_session = NULL;
2855
			req.socket.ws_session = NULL;
2856
			handle_request_do(&req, &tcptls_session->remote_address);
2856
			handle_request_do(&req, &tcptls_session->remote_address);
2857
		}
2857
		}
2858

    
   
2858

   
2859
		if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
2859
		if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
2860
			enum sip_tcptls_alert alert;
2860
			enum sip_tcptls_alert alert;
2861
			struct tcptls_packet *packet;
2861
			struct tcptls_packet *packet;
2862

    
   
2862

   
2863
			fds[1].revents = 0;
2863
			fds[1].revents = 0;
2864

    
   
2864

   
2865
			if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
2865
			if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
2866
				ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
2866
				ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
2867
				continue;
2867
				continue;
2868
			}
2868
			}
2869

    
   
2869

   
2870
			switch (alert) {
2870
			switch (alert) {
2871
			case TCPTLS_ALERT_STOP:
2871
			case TCPTLS_ALERT_STOP:
2872
				goto cleanup;
2872
				goto cleanup;
2873
			case TCPTLS_ALERT_DATA:
2873
			case TCPTLS_ALERT_DATA:
2874
				ao2_lock(me);
2874
				ao2_lock(me);
2875
				if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
2875
				if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
2876
					ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
2876
					ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
2877
				}
2877
				}
2878
				ao2_unlock(me);
2878
				ao2_unlock(me);
2879

    
   
2879

   
2880
				if (packet) {
2880
				if (packet) {
2881
					if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
2881
					if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
2882
						ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
2882
						ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
2883
					}
2883
					}
2884
					ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
2884
					ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
2885
				}
2885
				}
2886
				break;
2886
				break;
2887
			default:
2887
			default:
2888
				ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
2888
				ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
2889
			}
2889
			}
2890
		}
2890
		}
2891
	}
2891
	}
2892

    
   
2892

   
2893
	ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
2893
	ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
2894

    
   
2894

   
2895
cleanup:
2895
cleanup:
2896
	if (tcptls_session && !tcptls_session->client && !authenticated) {
2896
	if (tcptls_session && !tcptls_session->client && !authenticated) {
2897
		ast_atomic_fetchadd_int(&unauth_sessions, -1);
2897
		ast_atomic_fetchadd_int(&unauth_sessions, -1);
2898
	}
2898
	}
2899

    
   
2899

   
2900
	if (me) {
2900
	if (me) {
2901
		ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
2901
		ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
2902
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2902
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2903
	}
2903
	}
2904
	deinit_req(&reqcpy);
2904
	deinit_req(&reqcpy);
2905
	deinit_req(&req);
2905
	deinit_req(&req);
2906

    
   
2906

   
2907
	/* if client, we own the parent session arguments and must decrement ref */
2907
	/* if client, we own the parent session arguments and must decrement ref */
2908
	if (ca) {
2908
	if (ca) {
2909
		ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
2909
		ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
2910
	}
2910
	}
2911

    
   
2911

   
2912
	if (tcptls_session) {
2912
	if (tcptls_session) {
2913
		ao2_lock(tcptls_session);
2913
		ao2_lock(tcptls_session);
2914
		ast_tcptls_close_session_file(tcptls_session);
2914
		ast_tcptls_close_session_file(tcptls_session);
2915
		tcptls_session->parent = NULL;
2915
		tcptls_session->parent = NULL;
2916
		ao2_unlock(tcptls_session);
2916
		ao2_unlock(tcptls_session);
2917

    
   
2917

   
2918
		ao2_ref(tcptls_session, -1);
2918
		ao2_ref(tcptls_session, -1);
2919
		tcptls_session = NULL;
2919
		tcptls_session = NULL;
2920
	}
2920
	}
2921
	return NULL;
2921
	return NULL;
2922
}
2922
}
2923

    
   
2923

   
2924
#ifdef REF_DEBUG
2924
#ifdef REF_DEBUG
2925
#define sip_ref_peer(arg1,arg2) _ref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
2925
#define sip_ref_peer(arg1,arg2) _ref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
2926
#define sip_unref_peer(arg1,arg2) _unref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
2926
#define sip_unref_peer(arg1,arg2) _unref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
2927
static struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
2927
static struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
2928
{
2928
{
2929
	if (peer)
2929
	if (peer)
2930
		__ao2_ref_debug(peer, 1, tag, file, line, func);
2930
		__ao2_ref_debug(peer, 1, tag, file, line, func);
2931
	else
2931
	else
2932
		ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
2932
		ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
2933
	return peer;
2933
	return peer;
2934
}
2934
}
2935

    
   
2935

   
2936
static struct sip_peer *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
2936
static struct sip_peer *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
2937
{
2937
{
2938
	if (peer)
2938
	if (peer)
2939
		__ao2_ref_debug(peer, -1, tag, file, line, func);
2939
		__ao2_ref_debug(peer, -1, tag, file, line, func);
2940
	return NULL;
2940
	return NULL;
2941
}
2941
}
2942
#else
2942
#else
2943
/*!
2943
/*!
2944
 * helper functions to unreference various types of objects.
2944
 * helper functions to unreference various types of objects.
2945
 * By handling them this way, we don't have to declare the
2945
 * By handling them this way, we don't have to declare the
2946
 * destructor on each call, which removes the chance of errors.
2946
 * destructor on each call, which removes the chance of errors.
2947
 */
2947
 */
2948
void *sip_unref_peer(struct sip_peer *peer, char *tag)
2948
void *sip_unref_peer(struct sip_peer *peer, char *tag)
2949
{
2949
{
2950
	ao2_t_ref(peer, -1, tag);
2950
	ao2_t_ref(peer, -1, tag);
2951
	return NULL;
2951
	return NULL;
2952
}
2952
}
2953

    
   
2953

   
2954
struct sip_peer *sip_ref_peer(struct sip_peer *peer, char *tag)
2954
struct sip_peer *sip_ref_peer(struct sip_peer *peer, char *tag)
2955
{
2955
{
2956
	ao2_t_ref(peer, 1, tag);
2956
	ao2_t_ref(peer, 1, tag);
2957
	return peer;
2957
	return peer;
2958
}
2958
}
2959
#endif /* REF_DEBUG */
2959
#endif /* REF_DEBUG */
2960

    
   
2960

   
2961
static void peer_sched_cleanup(struct sip_peer *peer)
2961
static void peer_sched_cleanup(struct sip_peer *peer)
2962
{
2962
{
2963
	if (peer->pokeexpire != -1) {
2963
	if (peer->pokeexpire != -1) {
2964
		AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
2964
		AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
2965
				sip_unref_peer(peer, "removing poke peer ref"));
2965
				sip_unref_peer(peer, "removing poke peer ref"));
2966
	}
2966
	}
2967
	if (peer->expire != -1) {
2967
	if (peer->expire != -1) {
2968
		AST_SCHED_DEL_UNREF(sched, peer->expire,
2968
		AST_SCHED_DEL_UNREF(sched, peer->expire,
2969
				sip_unref_peer(peer, "remove register expire ref"));
2969
				sip_unref_peer(peer, "remove register expire ref"));
2970
	}
2970
	}
2971
	if (peer->keepalivesend != -1) {
2971
	if (peer->keepalivesend != -1) {
2972
		AST_SCHED_DEL_UNREF(sched, peer->keepalivesend,
2972
		AST_SCHED_DEL_UNREF(sched, peer->keepalivesend,
2973
				    sip_unref_peer(peer, "remove keepalive peer ref"));
2973
				    sip_unref_peer(peer, "remove keepalive peer ref"));
2974
	}
2974
	}
2975
}
2975
}
2976

    
   
2976

   
2977
typedef enum {
2977
typedef enum {
2978
	SIP_PEERS_MARKED,
2978
	SIP_PEERS_MARKED,
2979
	SIP_PEERS_ALL,
2979
	SIP_PEERS_ALL,
2980
} peer_unlink_flag_t;
2980
} peer_unlink_flag_t;
2981

    
   
2981

   
2982
/* this func is used with ao2_callback to unlink/delete all marked or linked
2982
/* this func is used with ao2_callback to unlink/delete all marked or linked
2983
   peers, depending on arg */
2983
   peers, depending on arg */
2984
static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
2984
static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
2985
{
2985
{
2986
	struct sip_peer *peer = peerobj;
2986
	struct sip_peer *peer = peerobj;
2987
	peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
2987
	peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
2988

    
   
2988

   
2989
	if (which == SIP_PEERS_ALL || peer->the_mark) {
2989
	if (which == SIP_PEERS_ALL || peer->the_mark) {
2990
		peer_sched_cleanup(peer);
2990
		peer_sched_cleanup(peer);
2991
		if (peer->dnsmgr) {
2991
		if (peer->dnsmgr) {
2992
			ast_dnsmgr_release(peer->dnsmgr);
2992
			ast_dnsmgr_release(peer->dnsmgr);
2993
			peer->dnsmgr = NULL;
2993
			peer->dnsmgr = NULL;
2994
			sip_unref_peer(peer, "Release peer from dnsmgr");
2994
			sip_unref_peer(peer, "Release peer from dnsmgr");
2995
		}
2995
		}
2996
		return CMP_MATCH;
2996
		return CMP_MATCH;
2997
	}
2997
	}
2998
	return 0;
2998
	return 0;
2999
}
2999
}
3000

    
   
3000

   
3001
static void unlink_peers_from_tables(peer_unlink_flag_t flag)
3001
static void unlink_peers_from_tables(peer_unlink_flag_t flag)
3002
{
3002
{
3003
	ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
3003
	ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
3004
		match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
3004
		match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
3005
	ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
3005
	ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
3006
		match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
3006
		match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
3007
}
3007
}
3008

    
   
3008

   
3009
/* \brief Unlink all marked peers from ao2 containers */
3009
/* \brief Unlink all marked peers from ao2 containers */
3010
static void unlink_marked_peers_from_tables(void)
3010
static void unlink_marked_peers_from_tables(void)
3011
{
3011
{
3012
	unlink_peers_from_tables(SIP_PEERS_MARKED);
3012
	unlink_peers_from_tables(SIP_PEERS_MARKED);
3013
}
3013
}
3014

    
   
3014

   
3015
static void unlink_all_peers_from_tables(void)
3015
static void unlink_all_peers_from_tables(void)
3016
{
3016
{
3017
	unlink_peers_from_tables(SIP_PEERS_ALL);
3017
	unlink_peers_from_tables(SIP_PEERS_ALL);
3018
}
3018
}
3019

    
   
3019

   
3020
/* \brief Unlink single peer from all ao2 containers */
3020
/* \brief Unlink single peer from all ao2 containers */
3021
static void unlink_peer_from_tables(struct sip_peer *peer)
3021
static void unlink_peer_from_tables(struct sip_peer *peer)
3022
{
3022
{
3023
	ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
3023
	ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
3024
	if (!ast_sockaddr_isnull(&peer->addr)) {
3024
	if (!ast_sockaddr_isnull(&peer->addr)) {
3025
		ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
3025
		ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
3026
	}
3026
	}
3027
}
3027
}
3028

    
   
3028

   
3029
/*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
3029
/*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
3030
 *
3030
 *
3031
 * This function sets pvt's outboundproxy pointer to the one referenced
3031
 * This function sets pvt's outboundproxy pointer to the one referenced
3032
 * by the proxy parameter. Because proxy may be a refcounted object, and
3032
 * by the proxy parameter. Because proxy may be a refcounted object, and
3033
 * because pvt's old outboundproxy may also be a refcounted object, we need
3033
 * because pvt's old outboundproxy may also be a refcounted object, we need
3034
 * to maintain the proper refcounts.
3034
 * to maintain the proper refcounts.
3035
 *
3035
 *
3036
 * \param pvt The sip_pvt for which we wish to set the outboundproxy
3036
 * \param pvt The sip_pvt for which we wish to set the outboundproxy
3037
 * \param proxy The sip_proxy which we will point pvt towards.
3037
 * \param proxy The sip_proxy which we will point pvt towards.
3038
 * \return Returns void
3038
 * \return Returns void
3039
 */
3039
 */
3040
static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
3040
static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
3041
{
3041
{
3042
	struct sip_proxy *old_obproxy = pvt->outboundproxy;
3042
	struct sip_proxy *old_obproxy = pvt->outboundproxy;
3043
	/* The sip_cfg.outboundproxy is statically allocated, and so
3043
	/* The sip_cfg.outboundproxy is statically allocated, and so
3044
	 * we don't ever need to adjust refcounts for it
3044
	 * we don't ever need to adjust refcounts for it
3045
	 */
3045
	 */
3046
	if (proxy && proxy != &sip_cfg.outboundproxy) {
3046
	if (proxy && proxy != &sip_cfg.outboundproxy) {
3047
		ao2_ref(proxy, +1);
3047
		ao2_ref(proxy, +1);
3048
	}
3048
	}
3049
	pvt->outboundproxy = proxy;
3049
	pvt->outboundproxy = proxy;
3050
	if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
3050
	if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
3051
		ao2_ref(old_obproxy, -1);
3051
		ao2_ref(old_obproxy, -1);
3052
	}
3052
	}
3053
}
3053
}
3054

    
   
3054

   
3055
/*!
3055
/*!
3056
 * \brief Unlink a dialog from the dialogs container, as well as any other places
3056
 * \brief Unlink a dialog from the dialogs container, as well as any other places
3057
 * that it may be currently stored.
3057
 * that it may be currently stored.
3058
 *
3058
 *
3059
 * \note A reference to the dialog must be held before calling this function, and this
3059
 * \note A reference to the dialog must be held before calling this function, and this
3060
 * function does not release that reference.
3060
 * function does not release that reference.
3061
 */
3061
 */
3062
void dialog_unlink_all(struct sip_pvt *dialog)
3062
void dialog_unlink_all(struct sip_pvt *dialog)
3063
{
3063
{
3064
	struct sip_pkt *cp;
3064
	struct sip_pkt *cp;
3065
	struct ast_channel *owner;
3065
	struct ast_channel *owner;
3066

    
   
3066

   
3067
	dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
3067
	dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
3068

    
   
3068

   
3069
	ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
3069
	ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
3070
	ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
3070
	ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
3071
	ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
3071
	ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
3072

    
   
3072

   
3073
	/* Unlink us from the owner (channel) if we have one */
3073
	/* Unlink us from the owner (channel) if we have one */
3074
	owner = sip_pvt_lock_full(dialog);
3074
	owner = sip_pvt_lock_full(dialog);
3075
	if (owner) {
3075
	if (owner) {
3076
		ast_debug(1, "Detaching from channel %s\n", ast_channel_name(owner));
3076
		ast_debug(1, "Detaching from channel %s\n", ast_channel_name(owner));
3077
		ast_channel_tech_pvt_set(owner, dialog_unref(ast_channel_tech_pvt(owner), "resetting channel dialog ptr in unlink_all"));
3077
		ast_channel_tech_pvt_set(owner, dialog_unref(ast_channel_tech_pvt(owner), "resetting channel dialog ptr in unlink_all"));
3078
		ast_channel_unlock(owner);
3078
		ast_channel_unlock(owner);
3079
		ast_channel_unref(owner);
3079
		ast_channel_unref(owner);
3080
		dialog->owner = NULL;
3080
		dialog->owner = NULL;
3081
	}
3081
	}
3082
	sip_pvt_unlock(dialog);
3082
	sip_pvt_unlock(dialog);
3083

    
   
3083

   
3084
	if (dialog->registry) {
3084
	if (dialog->registry) {
3085
		if (dialog->registry->call == dialog) {
3085
		if (dialog->registry->call == dialog) {
3086
			dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
3086
			dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
3087
		}
3087
		}
3088
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
3088
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
3089
	}
3089
	}
3090
	if (dialog->stateid != -1) {
3090
	if (dialog->stateid != -1) {
3091
		ast_extension_state_del(dialog->stateid, cb_extensionstate);
3091
		ast_extension_state_del(dialog->stateid, cb_extensionstate);
3092
		dialog->stateid = -1;
3092
		dialog->stateid = -1;
3093
	}
3093
	}
3094
	/* Remove link from peer to subscription of MWI */
3094
	/* Remove link from peer to subscription of MWI */
3095
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
3095
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
3096
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
3096
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
3097
	}
3097
	}
3098
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
3098
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
3099
		dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
3099
		dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
3100
	}
3100
	}
3101

    
   
3101

   
3102
	/* remove all current packets in this dialog */
3102
	/* remove all current packets in this dialog */
3103
	while((cp = dialog->packets)) {
3103
	while((cp = dialog->packets)) {
3104
		dialog->packets = dialog->packets->next;
3104
		dialog->packets = dialog->packets->next;
3105
		AST_SCHED_DEL(sched, cp->retransid);
3105
		AST_SCHED_DEL(sched, cp->retransid);
3106
		dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
3106
		dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
3107
		if (cp->data) {
3107
		if (cp->data) {
3108
			ast_free(cp->data);
3108
			ast_free(cp->data);
3109
		}
3109
		}
3110
		ast_free(cp);
3110
		ast_free(cp);
3111
	}
3111
	}
3112

    
   
3112

   
3113
	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"));
3113
	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"));
3114

    
   
3114

   
3115
	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"));
3115
	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"));
3116
	
3116
	
3117
	if (dialog->autokillid > -1) {
3117
	if (dialog->autokillid > -1) {
3118
		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"));
3118
		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"));
3119
	}
3119
	}
3120

    
   
3120

   
3121
	if (dialog->request_queue_sched_id > -1) {
3121
	if (dialog->request_queue_sched_id > -1) {
3122
		AST_SCHED_DEL_UNREF(sched, dialog->request_queue_sched_id, dialog_unref(dialog, "when you delete the request_queue_sched_id sched, you should dec the refcount for the stored dialog ptr"));
3122
		AST_SCHED_DEL_UNREF(sched, dialog->request_queue_sched_id, dialog_unref(dialog, "when you delete the request_queue_sched_id sched, you should dec the refcount for the stored dialog ptr"));
3123
	}
3123
	}
3124

    
   
3124

   
3125
	AST_SCHED_DEL_UNREF(sched, dialog->provisional_keepalive_sched_id, dialog_unref(dialog, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
3125
	AST_SCHED_DEL_UNREF(sched, dialog->provisional_keepalive_sched_id, dialog_unref(dialog, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
3126

    
   
3126

   
3127
	if (dialog->t38id > -1) {
3127
	if (dialog->t38id > -1) {
3128
		AST_SCHED_DEL_UNREF(sched, dialog->t38id, dialog_unref(dialog, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
3128
		AST_SCHED_DEL_UNREF(sched, dialog->t38id, dialog_unref(dialog, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
3129
	}
3129
	}
3130

    
   
3130

   
3131
	if (dialog->stimer) {
3131
	if (dialog->stimer) {
3132
		stop_session_timer(dialog);
3132
		stop_session_timer(dialog);
3133
	}
3133
	}
3134

    
   
3134

   
3135
	dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
3135
	dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
3136
}
3136
}
3137

    
   
3137

   
3138
void *registry_unref(struct sip_registry *reg, char *tag)
3138
void *registry_unref(struct sip_registry *reg, char *tag)
3139
{
3139
{
3140
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
3140
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
3141
	ASTOBJ_UNREF(reg, sip_registry_destroy);
3141
	ASTOBJ_UNREF(reg, sip_registry_destroy);
3142
	return NULL;
3142
	return NULL;
3143
}
3143
}
3144

    
   
3144

   
3145
/*! \brief Add object reference to SIP registry */
3145
/*! \brief Add object reference to SIP registry */
3146
static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
3146
static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
3147
{
3147
{
3148
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
3148
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
3149
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
3149
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
3150
}
3150
}
3151

    
   
3151

   
3152
/*! \brief Interface structure with callbacks used to connect to UDPTL module*/
3152
/*! \brief Interface structure with callbacks used to connect to UDPTL module*/
3153
static struct ast_udptl_protocol sip_udptl = {
3153
static struct ast_udptl_protocol sip_udptl = {
3154
	.type = "SIP",
3154
	.type = "SIP",
3155
	.get_udptl_info = sip_get_udptl_peer,
3155
	.get_udptl_info = sip_get_udptl_peer,
3156
	.set_udptl_peer = sip_set_udptl_peer,
3156
	.set_udptl_peer = sip_set_udptl_peer,
3157
};
3157
};
3158

    
   
3158

   
3159
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3159
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3160
	__attribute__((format(printf, 2, 3)));
3160
	__attribute__((format(printf, 2, 3)));
3161

    
   
3161

   
3162

    
   
3162

   
3163
/*! \brief Convert transfer status to string */
3163
/*! \brief Convert transfer status to string */
3164
static const char *referstatus2str(enum referstatus rstatus)
3164
static const char *referstatus2str(enum referstatus rstatus)
3165
{
3165
{
3166
	return map_x_s(referstatusstrings, rstatus, "");
3166
	return map_x_s(referstatusstrings, rstatus, "");
3167
}
3167
}
3168

    
   
3168

   
3169
static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
3169
static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
3170
{
3170
{
3171
	if (pvt->final_destruction_scheduled) {
3171
	if (pvt->final_destruction_scheduled) {
3172
		return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
3172
		return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
3173
	}
3173
	}
3174
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
3174
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
3175
	if (!pvt->needdestroy) {
3175
	if (!pvt->needdestroy) {
3176
		pvt->needdestroy = 1;
3176
		pvt->needdestroy = 1;
3177
		ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
3177
		ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
3178
	}
3178
	}
3179
}
3179
}
3180

    
   
3180

   
3181
/*! \brief Initialize the initital request packet in the pvt structure.
3181
/*! \brief Initialize the initital request packet in the pvt structure.
3182
	This packet is used for creating replies and future requests in
3182
	This packet is used for creating replies and future requests in
3183
	a dialog */
3183
	a dialog */
3184
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
3184
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
3185
{
3185
{
3186
	if (p->initreq.headers) {
3186
	if (p->initreq.headers) {
3187
		ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
3187
		ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
3188
	} else {
3188
	} else {
3189
		ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
3189
		ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
3190
	}
3190
	}
3191
	/* Use this as the basis */
3191
	/* Use this as the basis */
3192
	copy_request(&p->initreq, req);
3192
	copy_request(&p->initreq, req);
3193
	parse_request(&p->initreq);
3193
	parse_request(&p->initreq);
3194
	if (req->debug) {
3194
	if (req->debug) {
3195
		ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
3195
		ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
3196
	}
3196
	}
3197
}
3197
}
3198

    
   
3198

   
3199
/*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
3199
/*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
3200
static void sip_alreadygone(struct sip_pvt *dialog)
3200
static void sip_alreadygone(struct sip_pvt *dialog)
3201
{
3201
{
3202
	ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
3202
	ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
3203
	dialog->alreadygone = 1;
3203
	dialog->alreadygone = 1;
3204
}
3204
}
3205

    
   
3205

   
3206
/*! Resolve DNS srv name or host name in a sip_proxy structure */
3206
/*! Resolve DNS srv name or host name in a sip_proxy structure */
3207
static int proxy_update(struct sip_proxy *proxy)
3207
static int proxy_update(struct sip_proxy *proxy)
3208
{
3208
{
3209
	/* if it's actually an IP address and not a name,
3209
	/* if it's actually an IP address and not a name,
3210
           there's no need for a managed lookup */
3210
           there's no need for a managed lookup */
3211
	if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
3211
	if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
3212
		/* Ok, not an IP address, then let's check if it's a domain or host */
3212
		/* Ok, not an IP address, then let's check if it's a domain or host */
3213
		/* XXX Todo - if we have proxy port, don't do SRV */
3213
		/* XXX Todo - if we have proxy port, don't do SRV */
3214
		proxy->ip.ss.ss_family = get_address_family_filter(SIP_TRANSPORT_UDP); /* Filter address family */
3214
		proxy->ip.ss.ss_family = get_address_family_filter(SIP_TRANSPORT_UDP); /* Filter address family */
3215
		if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
3215
		if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
3216
				ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
3216
				ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
3217
				return FALSE;
3217
				return FALSE;
3218
		}
3218
		}
3219

    
   
3219

   
3220
	}
3220
	}
3221

    
   
3221

   
3222
	ast_sockaddr_set_port(&proxy->ip, proxy->port);
3222
	ast_sockaddr_set_port(&proxy->ip, proxy->port);
3223

    
   
3223

   
3224
	proxy->last_dnsupdate = time(NULL);
3224
	proxy->last_dnsupdate = time(NULL);
3225
	return TRUE;
3225
	return TRUE;
3226
}
3226
}
3227

    
   
3227

   
3228
/*! \brief converts ascii port to int representation. If no
3228
/*! \brief converts ascii port to int representation. If no
3229
 *  pt buffer is provided or the pt has errors when being converted
3229
 *  pt buffer is provided or the pt has errors when being converted
3230
 *  to an int value, the port provided as the standard is used.
3230
 *  to an int value, the port provided as the standard is used.
3231
 */
3231
 */
3232
unsigned int port_str2int(const char *pt, unsigned int standard)
3232
unsigned int port_str2int(const char *pt, unsigned int standard)
3233
{
3233
{
3234
	int port = standard;
3234
	int port = standard;
3235
	if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
3235
	if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
3236
		port = standard;
3236
		port = standard;
3237
	}
3237
	}
3238

    
   
3238

   
3239
	return port;
3239
	return port;
3240
}
3240
}
3241

    
   
3241

   
3242
/*! \brief Get default outbound proxy or global proxy */
3242
/*! \brief Get default outbound proxy or global proxy */
3243
static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
3243
static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
3244
{
3244
{
3245
	if (peer && peer->outboundproxy) {
3245
	if (peer && peer->outboundproxy) {
3246
		if (sipdebug) {
3246
		if (sipdebug) {
3247
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
3247
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
3248
		}
3248
		}
3249
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
3249
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
3250
		return peer->outboundproxy;
3250
		return peer->outboundproxy;
3251
	}
3251
	}
3252
	if (sip_cfg.outboundproxy.name[0]) {
3252
	if (sip_cfg.outboundproxy.name[0]) {
3253
		if (sipdebug) {
3253
		if (sipdebug) {
3254
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
3254
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
3255
		}
3255
		}
3256
		append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
3256
		append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
3257
		return &sip_cfg.outboundproxy;
3257
		return &sip_cfg.outboundproxy;
3258
	}
3258
	}
3259
	if (sipdebug) {
3259
	if (sipdebug) {
3260
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
3260
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
3261
	}
3261
	}
3262
	return NULL;
3262
	return NULL;
3263
}
3263
}
3264

    
   
3264

   
3265
/*! \brief returns true if 'name' (with optional trailing whitespace)
3265
/*! \brief returns true if 'name' (with optional trailing whitespace)
3266
 * matches the sip method 'id'.
3266
 * matches the sip method 'id'.
3267
 * Strictly speaking, SIP methods are case SENSITIVE, but we do
3267
 * Strictly speaking, SIP methods are case SENSITIVE, but we do
3268
 * a case-insensitive comparison to be more tolerant.
3268
 * a case-insensitive comparison to be more tolerant.
3269
 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
3269
 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
3270
 */
3270
 */
3271
static int method_match(enum sipmethod id, const char *name)
3271
static int method_match(enum sipmethod id, const char *name)
3272
{
3272
{
3273
	int len = strlen(sip_methods[id].text);
3273
	int len = strlen(sip_methods[id].text);
3274
	int l_name = name ? strlen(name) : 0;
3274
	int l_name = name ? strlen(name) : 0;
3275
	/* true if the string is long enough, and ends with whitespace, and matches */
3275
	/* true if the string is long enough, and ends with whitespace, and matches */
3276
	return (l_name >= len && name && name[len] < 33 &&
3276
	return (l_name >= len && name && name[len] < 33 &&
3277
		!strncasecmp(sip_methods[id].text, name, len));
3277
		!strncasecmp(sip_methods[id].text, name, len));
3278
}
3278
}
3279

    
   
3279

   
3280
/*! \brief  find_sip_method: Find SIP method from header */
3280
/*! \brief  find_sip_method: Find SIP method from header */
3281
static int find_sip_method(const char *msg)
3281
static int find_sip_method(const char *msg)
3282
{
3282
{
3283
	int i, res = 0;
3283
	int i, res = 0;
3284
	
3284
	
3285
	if (ast_strlen_zero(msg)) {
3285
	if (ast_strlen_zero(msg)) {
3286
		return 0;
3286
		return 0;
3287
	}
3287
	}
3288
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
3288
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
3289
		if (method_match(i, msg)) {
3289
		if (method_match(i, msg)) {
3290
			res = sip_methods[i].id;
3290
			res = sip_methods[i].id;
3291
		}
3291
		}
3292
	}
3292
	}
3293
	return res;
3293
	return res;
3294
}
3294
}
3295

    
   
3295

   
3296
/*! \brief See if we pass debug IP filter */
3296
/*! \brief See if we pass debug IP filter */
3297
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
3297
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
3298
{
3298
{
3299
	/* Can't debug if sipdebug is not enabled */
3299
	/* Can't debug if sipdebug is not enabled */
3300
	if (!sipdebug) {
3300
	if (!sipdebug) {
3301
		return 0;
3301
		return 0;
3302
	}
3302
	}
3303

    
   
3303

   
3304
	/* A null debug_addr means we'll debug any address */
3304
	/* A null debug_addr means we'll debug any address */
3305
	if (ast_sockaddr_isnull(&debugaddr)) {
3305
	if (ast_sockaddr_isnull(&debugaddr)) {
3306
		return 1;
3306
		return 1;
3307
	}
3307
	}
3308

    
   
3308

   
3309
	/* If no port was specified for a debug address, just compare the
3309
	/* If no port was specified for a debug address, just compare the
3310
	 * addresses, otherwise compare the address and port
3310
	 * addresses, otherwise compare the address and port
3311
	 */
3311
	 */
3312
	if (ast_sockaddr_port(&debugaddr)) {
3312
	if (ast_sockaddr_port(&debugaddr)) {
3313
		return !ast_sockaddr_cmp(&debugaddr, addr);
3313
		return !ast_sockaddr_cmp(&debugaddr, addr);
3314
	} else {
3314
	} else {
3315
		return !ast_sockaddr_cmp_addr(&debugaddr, addr);
3315
		return !ast_sockaddr_cmp_addr(&debugaddr, addr);
3316
	}
3316
	}
3317
}
3317
}
3318

    
   
3318

   
3319
/*! \brief The real destination address for a write */
3319
/*! \brief The real destination address for a write */
3320
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
3320
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
3321
{
3321
{
3322
	if (p->outboundproxy) {
3322
	if (p->outboundproxy) {
3323
		return &p->outboundproxy->ip;
3323
		return &p->outboundproxy->ip;
3324
	}
3324
	}
3325

    
   
3325

   
3326
	return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT) ? &p->recv : &p->sa;
3326
	return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT) ? &p->recv : &p->sa;
3327
}
3327
}
3328

    
   
3328

   
3329
/*! \brief Display SIP nat mode */
3329
/*! \brief Display SIP nat mode */
3330
static const char *sip_nat_mode(const struct sip_pvt *p)
3330
static const char *sip_nat_mode(const struct sip_pvt *p)
3331
{
3331
{
3332
	return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
3332
	return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
3333
}
3333
}
3334

    
   
3334

   
3335
/*! \brief Test PVT for debugging output */
3335
/*! \brief Test PVT for debugging output */
3336
static inline int sip_debug_test_pvt(struct sip_pvt *p)
3336
static inline int sip_debug_test_pvt(struct sip_pvt *p)
3337
{
3337
{
3338
	if (!sipdebug) {
3338
	if (!sipdebug) {
3339
		return 0;
3339
		return 0;
3340
	}
3340
	}
3341
	return sip_debug_test_addr(sip_real_dst(p));
3341
	return sip_debug_test_addr(sip_real_dst(p));
3342
}
3342
}
3343

    
   
3343

   
3344
/*! \brief Return int representing a bit field of transport types found in const char *transport */
3344
/*! \brief Return int representing a bit field of transport types found in const char *transport */
3345
static int get_transport_str2enum(const char *transport)
3345
static int get_transport_str2enum(const char *transport)
3346
{
3346
{
3347
	int res = 0;
3347
	int res = 0;
3348

    
   
3348

   
3349
	if (ast_strlen_zero(transport)) {
3349
	if (ast_strlen_zero(transport)) {
3350
		return res;
3350
		return res;
3351
	}
3351
	}
3352

    
   
3352

   
3353
	if (!strcasecmp(transport, "udp")) {
3353
	if (!strcasecmp(transport, "udp")) {
3354
		res |= SIP_TRANSPORT_UDP;
3354
		res |= SIP_TRANSPORT_UDP;
3355
	}
3355
	}
3356
	if (!strcasecmp(transport, "tcp")) {
3356
	if (!strcasecmp(transport, "tcp")) {
3357
		res |= SIP_TRANSPORT_TCP;
3357
		res |= SIP_TRANSPORT_TCP;
3358
	}
3358
	}
3359
	if (!strcasecmp(transport, "tls")) {
3359
	if (!strcasecmp(transport, "tls")) {
3360
		res |= SIP_TRANSPORT_TLS;
3360
		res |= SIP_TRANSPORT_TLS;
3361
	}
3361
	}
3362
	if (!strcasecmp(transport, "ws")) {
3362
	if (!strcasecmp(transport, "ws")) {
3363
		res |= SIP_TRANSPORT_WS;
3363
		res |= SIP_TRANSPORT_WS;
3364
	}
3364
	}
3365
	if (!strcasecmp(transport, "wss")) {
3365
	if (!strcasecmp(transport, "wss")) {
3366
		res |= SIP_TRANSPORT_WSS;
3366
		res |= SIP_TRANSPORT_WSS;
3367
	}
3367
	}
3368

    
   
3368

   
3369
	return res;
3369
	return res;
3370
}
3370
}
3371

    
   
3371

   
3372
/*! \brief Return configuration of transports for a device */
3372
/*! \brief Return configuration of transports for a device */
3373
static inline const char *get_transport_list(unsigned int transports)
3373
static inline const char *get_transport_list(unsigned int transports)
3374
{
3374
{
3375
	char *buf;
3375
	char *buf;
3376

    
   
3376

   
3377
	if (!transports) {
3377
	if (!transports) {
3378
		return "UNKNOWN";
3378
		return "UNKNOWN";
3379
	}
3379
	}
3380

    
   
3380

   
3381
	if (!(buf = ast_threadstorage_get(&sip_transport_str_buf, SIP_TRANSPORT_STR_BUFSIZE))) {
3381
	if (!(buf = ast_threadstorage_get(&sip_transport_str_buf, SIP_TRANSPORT_STR_BUFSIZE))) {
3382
		return "";
3382
		return "";
3383
	}
3383
	}
3384

    
   
3384

   
3385
	memset(buf, 0, SIP_TRANSPORT_STR_BUFSIZE);
3385
	memset(buf, 0, SIP_TRANSPORT_STR_BUFSIZE);
3386

    
   
3386

   
3387
	if (transports & SIP_TRANSPORT_UDP) {
3387
	if (transports & SIP_TRANSPORT_UDP) {
3388
		strncat(buf, "UDP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3388
		strncat(buf, "UDP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3389
	}
3389
	}
3390
	if (transports & SIP_TRANSPORT_TCP) {
3390
	if (transports & SIP_TRANSPORT_TCP) {
3391
		strncat(buf, "TCP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3391
		strncat(buf, "TCP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3392
	}
3392
	}
3393
	if (transports & SIP_TRANSPORT_TLS) {
3393
	if (transports & SIP_TRANSPORT_TLS) {
3394
		strncat(buf, "TLS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3394
		strncat(buf, "TLS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3395
	}
3395
	}
3396
	if (transports & SIP_TRANSPORT_WS) {
3396
	if (transports & SIP_TRANSPORT_WS) {
3397
		strncat(buf, "WS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3397
		strncat(buf, "WS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3398
	}
3398
	}
3399
	if (transports & SIP_TRANSPORT_WSS) {
3399
	if (transports & SIP_TRANSPORT_WSS) {
3400
		strncat(buf, "WSS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3400
		strncat(buf, "WSS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3401
	}
3401
	}
3402

    
   
3402

   
3403
	/* Remove the trailing ',' if present */
3403
	/* Remove the trailing ',' if present */
3404
	if (strlen(buf)) {
3404
	if (strlen(buf)) {
3405
		buf[strlen(buf) - 1] = 0;
3405
		buf[strlen(buf) - 1] = 0;
3406
	}
3406
	}
3407

    
   
3407

   
3408
	return buf;
3408
	return buf;
3409
}
3409
}
3410

    
   
3410

   
3411
/*! \brief Return transport as string */
3411
/*! \brief Return transport as string */
3412
const char *sip_get_transport(enum sip_transport t)
3412
const char *sip_get_transport(enum sip_transport t)
3413
{
3413
{
3414
	switch (t) {
3414
	switch (t) {
3415
	case SIP_TRANSPORT_UDP:
3415
	case SIP_TRANSPORT_UDP:
3416
		return "UDP";
3416
		return "UDP";
3417
	case SIP_TRANSPORT_TCP:
3417
	case SIP_TRANSPORT_TCP:
3418
		return "TCP";
3418
		return "TCP";
3419
	case SIP_TRANSPORT_TLS:
3419
	case SIP_TRANSPORT_TLS:
3420
		return "TLS";
3420
		return "TLS";
3421
	case SIP_TRANSPORT_WS:
3421
	case SIP_TRANSPORT_WS:
3422
	case SIP_TRANSPORT_WSS:
3422
	case SIP_TRANSPORT_WSS:
3423
		return "WS";
3423
		return "WS";
3424
	}
3424
	}
3425

    
   
3425

   
3426
	return "UNKNOWN";
3426
	return "UNKNOWN";
3427
}
3427
}
3428

    
   
3428

   
3429
/*! \brief Return protocol string for srv dns query */
3429
/*! \brief Return protocol string for srv dns query */
3430
static inline const char *get_srv_protocol(enum sip_transport t)
3430
static inline const char *get_srv_protocol(enum sip_transport t)
3431
{
3431
{
3432
	switch (t) {
3432
	switch (t) {
3433
	case SIP_TRANSPORT_UDP:
3433
	case SIP_TRANSPORT_UDP:
3434
		return "udp";
3434
		return "udp";
3435
	case SIP_TRANSPORT_WS:
3435
	case SIP_TRANSPORT_WS:
3436
		return "ws";
3436
		return "ws";
3437
	case SIP_TRANSPORT_TLS:
3437
	case SIP_TRANSPORT_TLS:
3438
	case SIP_TRANSPORT_TCP:
3438
	case SIP_TRANSPORT_TCP:
3439
		return "tcp";
3439
		return "tcp";
3440
	case SIP_TRANSPORT_WSS:
3440
	case SIP_TRANSPORT_WSS:
3441
		return "wss";
3441
		return "wss";
3442
	}
3442
	}
3443

    
   
3443

   
3444
	return "udp";
3444
	return "udp";
3445
}
3445
}
3446

    
   
3446

   
3447
/*! \brief Return service string for srv dns query */
3447
/*! \brief Return service string for srv dns query */
3448
static inline const char *get_srv_service(enum sip_transport t)
3448
static inline const char *get_srv_service(enum sip_transport t)
3449
{
3449
{
3450
	switch (t) {
3450
	switch (t) {
3451
	case SIP_TRANSPORT_TCP:
3451
	case SIP_TRANSPORT_TCP:
3452
	case SIP_TRANSPORT_UDP:
3452
	case SIP_TRANSPORT_UDP:
3453
	case SIP_TRANSPORT_WS:
3453
	case SIP_TRANSPORT_WS:
3454
		return "sip";
3454
		return "sip";
3455
	case SIP_TRANSPORT_TLS:
3455
	case SIP_TRANSPORT_TLS:
3456
	case SIP_TRANSPORT_WSS:
3456
	case SIP_TRANSPORT_WSS:
3457
		return "sips";
3457
		return "sips";
3458
	}
3458
	}
3459
	return "sip";
3459
	return "sip";
3460
}
3460
}
3461

    
   
3461

   
3462
/*! \brief Return transport of dialog.
3462
/*! \brief Return transport of dialog.
3463
	\note this is based on a false assumption. We don't always use the
3463
	\note this is based on a false assumption. We don't always use the
3464
	outbound proxy for all requests in a dialog. It depends on the
3464
	outbound proxy for all requests in a dialog. It depends on the
3465
	"force" parameter. The FIRST request is always sent to the ob proxy.
3465
	"force" parameter. The FIRST request is always sent to the ob proxy.
3466
	\todo Fix this function to work correctly
3466
	\todo Fix this function to work correctly
3467
*/
3467
*/
3468
static inline const char *get_transport_pvt(struct sip_pvt *p)
3468
static inline const char *get_transport_pvt(struct sip_pvt *p)
3469
{
3469
{
3470
	if (p->outboundproxy && p->outboundproxy->transport) {
3470
	if (p->outboundproxy && p->outboundproxy->transport) {
3471
		set_socket_transport(&p->socket, p->outboundproxy->transport);
3471
		set_socket_transport(&p->socket, p->outboundproxy->transport);
3472
	}
3472
	}
3473

    
   
3473

   
3474
	return sip_get_transport(p->socket.type);
3474
	return sip_get_transport(p->socket.type);
3475
}
3475
}
3476

    
   
3476

   
3477
/*!
3477
/*!
3478
 * \internal
3478
 * \internal
3479
 * \brief Transmit SIP message
3479
 * \brief Transmit SIP message
3480
 *
3480
 *
3481
 * \details
3481
 * \details
3482
 * Sends a SIP request or response on a given socket (in the pvt)
3482
 * Sends a SIP request or response on a given socket (in the pvt)
3483
 * \note
3483
 * \note
3484
 * Called by retrans_pkt, send_request, send_response and __sip_reliable_xmit
3484
 * Called by retrans_pkt, send_request, send_response and __sip_reliable_xmit
3485
 *
3485
 *
3486
 * \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
3486
 * \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
3487
 */
3487
 */
3488
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
3488
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
3489
{
3489
{
3490
	int res = 0;
3490
	int res = 0;
3491
	const struct ast_sockaddr *dst = sip_real_dst(p);
3491
	const struct ast_sockaddr *dst = sip_real_dst(p);
3492

    
   
3492

   
3493
	ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s\n", data->str, get_transport_pvt(p), ast_sockaddr_stringify(dst));
3493
	ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s\n", data->str, get_transport_pvt(p), ast_sockaddr_stringify(dst));
3494

    
   
3494

   
3495
	if (sip_prepare_socket(p) < 0) {
3495
	if (sip_prepare_socket(p) < 0) {
3496
		return XMIT_ERROR;
3496
		return XMIT_ERROR;
3497
	}
3497
	}
3498

    
   
3498

   
3499
	if (p->socket.type == SIP_TRANSPORT_UDP) {
3499
	if (p->socket.type == SIP_TRANSPORT_UDP) {
3500
		res = ast_sendto(p->socket.fd, data->str, ast_str_strlen(data), 0, dst);
3500
		res = ast_sendto(p->socket.fd, data->str, ast_str_strlen(data), 0, dst);
3501
	} else if (p->socket.tcptls_session) {
3501
	} else if (p->socket.tcptls_session) {
3502
		res = sip_tcptls_write(p->socket.tcptls_session, data->str, ast_str_strlen(data));
3502
		res = sip_tcptls_write(p->socket.tcptls_session, data->str, ast_str_strlen(data));
3503
	} else if (p->socket.ws_session) {
3503
	} else if (p->socket.ws_session) {
3504
		if (!(res = ast_websocket_write(p->socket.ws_session, AST_WEBSOCKET_OPCODE_TEXT, data->str, ast_str_strlen(data)))) {
3504
		if (!(res = ast_websocket_write(p->socket.ws_session, AST_WEBSOCKET_OPCODE_TEXT, data->str, ast_str_strlen(data)))) {
3505
			/* The WebSocket API just returns 0 on success and -1 on failure, while this code expects the payload length to be returned */
3505
			/* The WebSocket API just returns 0 on success and -1 on failure, while this code expects the payload length to be returned */
3506
			res = ast_str_strlen(data);
3506
			res = ast_str_strlen(data);
3507
		}
3507
		}
3508
	} else {
3508
	} else {
3509
		ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
3509
		ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
3510
		return XMIT_ERROR;
3510
		return XMIT_ERROR;
3511
	}
3511
	}
3512

    
   
3512

   
3513
	if (res == -1) {
3513
	if (res == -1) {
3514
		switch (errno) {
3514
		switch (errno) {
3515
		case EBADF:		/* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
3515
		case EBADF:		/* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
3516
		case EHOSTUNREACH:	/* Host can't be reached */
3516
		case EHOSTUNREACH:	/* Host can't be reached */
3517
		case ENETDOWN:		/* Interface down */
3517
		case ENETDOWN:		/* Interface down */
3518
		case ENETUNREACH:	/* Network failure */
3518
		case ENETUNREACH:	/* Network failure */
3519
		case ECONNREFUSED:      /* ICMP port unreachable */
3519
		case ECONNREFUSED:      /* ICMP port unreachable */
3520
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */
3520
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */
3521
		}
3521
		}
3522
	}
3522
	}
3523
	if (res != ast_str_strlen(data)) {
3523
	if (res != ast_str_strlen(data)) {
3524
		ast_log(LOG_WARNING, "sip_xmit of %p (len %zu) to %s returned %d: %s\n", data, ast_str_strlen(data), ast_sockaddr_stringify(dst), res, strerror(errno));
3524
		ast_log(LOG_WARNING, "sip_xmit of %p (len %zu) to %s returned %d: %s\n", data, ast_str_strlen(data), ast_sockaddr_stringify(dst), res, strerror(errno));
3525
	}
3525
	}
3526

    
   
3526

   
3527
	return res;
3527
	return res;
3528
}
3528
}
3529

    
   
3529

   
3530
/*! \brief Build a Via header for a request */
3530
/*! \brief Build a Via header for a request */
3531
static void build_via(struct sip_pvt *p)
3531
static void build_via(struct sip_pvt *p)
3532
{
3532
{
3533
	/* Work around buggy UNIDEN UIP200 firmware */
3533
	/* Work around buggy UNIDEN UIP200 firmware */
3534
	const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
3534
	const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
3535

    
   
3535

   
3536
	/* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
3536
	/* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
3537
	snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
3537
	snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
3538
		 get_transport_pvt(p),
3538
		 get_transport_pvt(p),
3539
		 ast_sockaddr_stringify_remote(&p->ourip),
3539
		 ast_sockaddr_stringify_remote(&p->ourip),
3540
		 (int) p->branch, rport);
3540
		 (int) p->branch, rport);
3541
}
3541
}
3542

    
   
3542

   
3543
/*! \brief NAT fix - decide which IP address to use for Asterisk server?
3543
/*! \brief NAT fix - decide which IP address to use for Asterisk server?
3544
 *
3544
 *
3545
 * Using the localaddr structure built up with localnet statements in sip.conf
3545
 * Using the localaddr structure built up with localnet statements in sip.conf
3546
 * apply it to their address to see if we need to substitute our
3546
 * apply it to their address to see if we need to substitute our
3547
 * externaddr or can get away with our internal bindaddr
3547
 * externaddr or can get away with our internal bindaddr
3548
 * 'us' is always overwritten.
3548
 * 'us' is always overwritten.
3549
 */
3549
 */
3550
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
3550
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
3551
{
3551
{
3552
	struct ast_sockaddr theirs;
3552
	struct ast_sockaddr theirs;
3553

    
   
3553

   
3554
	/* Set want_remap to non-zero if we want to remap 'us' to an externally
3554
	/* Set want_remap to non-zero if we want to remap 'us' to an externally
3555
	 * reachable IP address and port. This is done if:
3555
	 * reachable IP address and port. This is done if:
3556
	 * 1. we have a localaddr list (containing 'internal' addresses marked
3556
	 * 1. we have a localaddr list (containing 'internal' addresses marked
3557
	 *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
3557
	 *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
3558
	 *    and AST_SENSE_ALLOW on 'external' ones);
3558
	 *    and AST_SENSE_ALLOW on 'external' ones);
3559
	 * 2. externaddr is set, so we know what to use as the
3559
	 * 2. externaddr is set, so we know what to use as the
3560
	 *    externally visible address;
3560
	 *    externally visible address;
3561
	 * 3. the remote address, 'them', is external;
3561
	 * 3. the remote address, 'them', is external;
3562
	 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
3562
	 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
3563
	 *    when passed to ast_apply_ha() so it does need to be remapped.
3563
	 *    when passed to ast_apply_ha() so it does need to be remapped.
3564
	 *    This fourth condition is checked later.
3564
	 *    This fourth condition is checked later.
3565
	 */
3565
	 */
3566
	int want_remap = 0;
3566
	int want_remap = 0;
3567

    
   
3567

   
3568
	ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
3568
	ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
3569
	/* now ask the system what would it use to talk to 'them' */
3569
	/* now ask the system what would it use to talk to 'them' */
3570
	ast_ouraddrfor(them, us);
3570
	ast_ouraddrfor(them, us);
3571
	ast_sockaddr_copy(&theirs, them);
3571
	ast_sockaddr_copy(&theirs, them);
3572

    
   
3572

   
3573
	if (ast_sockaddr_is_ipv6(&theirs)) {
3573
	if (ast_sockaddr_is_ipv6(&theirs)) {
3574
		if (localaddr && !ast_sockaddr_isnull(&externaddr) && !ast_sockaddr_is_any(&bindaddr)) {
3574
		if (localaddr && !ast_sockaddr_isnull(&externaddr) && !ast_sockaddr_is_any(&bindaddr)) {
3575
			ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
3575
			ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
3576
				"but we're using IPv6, which doesn't need it. Please "
3576
				"but we're using IPv6, which doesn't need it. Please "
3577
				"remove \"localnet\" and/or \"externaddr\" settings.\n");
3577
				"remove \"localnet\" and/or \"externaddr\" settings.\n");
3578
		}
3578
		}
3579
	} else {
3579
	} else {
3580
		want_remap = localaddr &&
3580
		want_remap = localaddr &&
3581
			!ast_sockaddr_isnull(&externaddr) &&
3581
			!ast_sockaddr_isnull(&externaddr) &&
3582
			ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
3582
			ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
3583
	}
3583
	}
3584

    
   
3584

   
3585
	if (want_remap &&
3585
	if (want_remap &&
3586
	    (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
3586
	    (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
3587
		/* if we used externhost, see if it is time to refresh the info */
3587
		/* if we used externhost, see if it is time to refresh the info */
3588
		if (externexpire && time(NULL) >= externexpire) {
3588
		if (externexpire && time(NULL) >= externexpire) {
3589
			if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
3589
			if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
3590
				ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
3590
				ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
3591
			}
3591
			}
3592
			externexpire = time(NULL) + externrefresh;
3592
			externexpire = time(NULL) + externrefresh;
3593
		}
3593
		}
3594
		if (!ast_sockaddr_isnull(&externaddr)) {
3594
		if (!ast_sockaddr_isnull(&externaddr)) {
3595
			ast_sockaddr_copy(us, &externaddr);
3595
			ast_sockaddr_copy(us, &externaddr);
3596
			switch (p->socket.type) {
3596
			switch (p->socket.type) {
3597
			case SIP_TRANSPORT_TCP:
3597
			case SIP_TRANSPORT_TCP:
3598
				if (!externtcpport && ast_sockaddr_port(&externaddr)) {
3598
				if (!externtcpport && ast_sockaddr_port(&externaddr)) {
3599
					/* for consistency, default to the externaddr port */
3599
					/* for consistency, default to the externaddr port */
3600
					externtcpport = ast_sockaddr_port(&externaddr);
3600
					externtcpport = ast_sockaddr_port(&externaddr);
3601
				}
3601
				}
3602
				ast_sockaddr_set_port(us, externtcpport);
3602
				ast_sockaddr_set_port(us, externtcpport);
3603
				break;
3603
				break;
3604
			case SIP_TRANSPORT_TLS:
3604
			case SIP_TRANSPORT_TLS:
3605
				ast_sockaddr_set_port(us, externtlsport);
3605
				ast_sockaddr_set_port(us, externtlsport);
3606
				break;
3606
				break;
3607
			case SIP_TRANSPORT_UDP:
3607
			case SIP_TRANSPORT_UDP:
3608
				if (!ast_sockaddr_port(&externaddr)) {
3608
				if (!ast_sockaddr_port(&externaddr)) {
3609
					ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3609
					ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3610
				}
3610
				}
3611
				break;
3611
				break;
3612
			default:
3612
			default:
3613
				break;
3613
				break;
3614
			}
3614
			}
3615
		}
3615
		}
3616
		ast_debug(1, "Target address %s is not local, substituting externaddr\n",
3616
		ast_debug(1, "Target address %s is not local, substituting externaddr\n",
3617
			  ast_sockaddr_stringify(them));
3617
			  ast_sockaddr_stringify(them));
3618
	} else {
3618
	} else {
3619
		/* no remapping, but we bind to a specific address, so use it. */
3619
		/* no remapping, but we bind to a specific address, so use it. */
3620
		switch (p->socket.type) {
3620
		switch (p->socket.type) {
3621
		case SIP_TRANSPORT_TCP:
3621
		case SIP_TRANSPORT_TCP:
3622
			if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
3622
			if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
3623
				ast_sockaddr_copy(us,
3623
				ast_sockaddr_copy(us,
3624
						  &sip_tcp_desc.local_address);
3624
						  &sip_tcp_desc.local_address);
3625
			} else {
3625
			} else {
3626
				ast_sockaddr_set_port(us,
3626
				ast_sockaddr_set_port(us,
3627
						      ast_sockaddr_port(&sip_tcp_desc.local_address));
3627
						      ast_sockaddr_port(&sip_tcp_desc.local_address));
3628
			}
3628
			}
3629
			break;
3629
			break;
3630
		case SIP_TRANSPORT_TLS:
3630
		case SIP_TRANSPORT_TLS:
3631
			if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
3631
			if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
3632
				ast_sockaddr_copy(us,
3632
				ast_sockaddr_copy(us,
3633
						  &sip_tls_desc.local_address);
3633
						  &sip_tls_desc.local_address);
3634
			} else {
3634
			} else {
3635
				ast_sockaddr_set_port(us,
3635
				ast_sockaddr_set_port(us,
3636
						      ast_sockaddr_port(&sip_tls_desc.local_address));
3636
						      ast_sockaddr_port(&sip_tls_desc.local_address));
3637
			}
3637
			}
3638
			break;
3638
			break;
3639
		case SIP_TRANSPORT_UDP:
3639
		case SIP_TRANSPORT_UDP:
3640
			/* fall through on purpose */
3640
			/* fall through on purpose */
3641
		default:
3641
		default:
3642
			if (!ast_sockaddr_is_any(&bindaddr)) {
3642
			if (!ast_sockaddr_is_any(&bindaddr)) {
3643
				ast_sockaddr_copy(us, &bindaddr);
3643
				ast_sockaddr_copy(us, &bindaddr);
3644
			}
3644
			}
3645
			if (!ast_sockaddr_port(us)) {
3645
			if (!ast_sockaddr_port(us)) {
3646
				ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3646
				ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3647
			}
3647
			}
3648
		}
3648
		}
3649
	}
3649
	}
3650
	ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", sip_get_transport(p->socket.type), ast_sockaddr_stringify(us));
3650
	ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", sip_get_transport(p->socket.type), ast_sockaddr_stringify(us));
3651
}
3651
}
3652

    
   
3652

   
3653
/*! \brief Append to SIP dialog history with arg list  */
3653
/*! \brief Append to SIP dialog history with arg list  */
3654
static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
3654
static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
3655
{
3655
{
3656
	char buf[80], *c = buf; /* max history length */
3656
	char buf[80], *c = buf; /* max history length */
3657
	struct sip_history *hist;
3657
	struct sip_history *hist;
3658
	int l;
3658
	int l;
3659

    
   
3659

   
3660
	vsnprintf(buf, sizeof(buf), fmt, ap);
3660
	vsnprintf(buf, sizeof(buf), fmt, ap);
3661
	strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
3661
	strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
3662
	l = strlen(buf) + 1;
3662
	l = strlen(buf) + 1;
3663
	if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
3663
	if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
3664
		return;
3664
		return;
3665
	}
3665
	}
3666
	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
3666
	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
3667
		ast_free(hist);
3667
		ast_free(hist);
3668
		return;
3668
		return;
3669
	}
3669
	}
3670
	memcpy(hist->event, buf, l);
3670
	memcpy(hist->event, buf, l);
3671
	if (p->history_entries == MAX_HISTORY_ENTRIES) {
3671
	if (p->history_entries == MAX_HISTORY_ENTRIES) {
3672
		struct sip_history *oldest;
3672
		struct sip_history *oldest;
3673
		oldest = AST_LIST_REMOVE_HEAD(p->history, list);
3673
		oldest = AST_LIST_REMOVE_HEAD(p->history, list);
3674
		p->history_entries--;
3674
		p->history_entries--;
3675
		ast_free(oldest);
3675
		ast_free(oldest);
3676
	}
3676
	}
3677
	AST_LIST_INSERT_TAIL(p->history, hist, list);
3677
	AST_LIST_INSERT_TAIL(p->history, hist, list);
3678
	p->history_entries++;
3678
	p->history_entries++;
3679
}
3679
}
3680

    
   
3680

   
3681
/*! \brief Append to SIP dialog history with arg list  */
3681
/*! \brief Append to SIP dialog history with arg list  */
3682
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3682
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3683
{
3683
{
3684
	va_list ap;
3684
	va_list ap;
3685

    
   
3685

   
3686
	if (!p) {
3686
	if (!p) {
3687
		return;
3687
		return;
3688
	}
3688
	}
3689

    
   
3689

   
3690
	if (!p->do_history && !recordhistory && !dumphistory) {
3690
	if (!p->do_history && !recordhistory && !dumphistory) {
3691
		return;
3691
		return;
3692
	}
3692
	}
3693

    
   
3693

   
3694
	va_start(ap, fmt);
3694
	va_start(ap, fmt);
3695
	append_history_va(p, fmt, ap);
3695
	append_history_va(p, fmt, ap);
3696
	va_end(ap);
3696
	va_end(ap);
3697

    
   
3697

   
3698
	return;
3698
	return;
3699
}
3699
}
3700

    
   
3700

   
3701
/*! \brief Retransmit SIP message if no answer (Called from scheduler) */
3701
/*! \brief Retransmit SIP message if no answer (Called from scheduler) */
3702
static int retrans_pkt(const void *data)
3702
static int retrans_pkt(const void *data)
3703
{
3703
{
3704
	struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
3704
	struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
3705
	int reschedule = DEFAULT_RETRANS;
3705
	int reschedule = DEFAULT_RETRANS;
3706
	int xmitres = 0;
3706
	int xmitres = 0;
3707
	/* how many ms until retrans timeout is reached */
3707
	/* how many ms until retrans timeout is reached */
3708
	int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
3708
	int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
3709

    
   
3709

   
3710
	/* Do not retransmit if time out is reached. This will be negative if the time between
3710
	/* Do not retransmit if time out is reached. This will be negative if the time between
3711
	 * the first transmission and now is larger than our timeout period. This is a fail safe
3711
	 * the first transmission and now is larger than our timeout period. This is a fail safe
3712
	 * check in case the scheduler gets behind or the clock is changed. */
3712
	 * check in case the scheduler gets behind or the clock is changed. */
3713
	if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
3713
	if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
3714
		pkt->retrans_stop = 1;
3714
		pkt->retrans_stop = 1;
3715
	}
3715
	}
3716

    
   
3716

   
3717
	/* Lock channel PVT */
3717
	/* Lock channel PVT */
3718
	sip_pvt_lock(pkt->owner);
3718
	sip_pvt_lock(pkt->owner);
3719

    
   
3719

   
3720
	if (!pkt->retrans_stop) {
3720
	if (!pkt->retrans_stop) {
3721
		pkt->retrans++;
3721
		pkt->retrans++;
3722
		if (!pkt->timer_t1) {	/* Re-schedule using timer_a and timer_t1 */
3722
		if (!pkt->timer_t1) {	/* Re-schedule using timer_a and timer_t1 */
3723
			if (sipdebug) {
3723
			if (sipdebug) {
3724
				ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
3724
				ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
3725
					pkt->retransid,
3725
					pkt->retransid,
3726
					sip_methods[pkt->method].text,
3726
					sip_methods[pkt->method].text,
3727
					pkt->method);
3727
					pkt->method);
3728
			}
3728
			}
3729
		} else {
3729
		} else {
3730
			int siptimer_a;
3730
			int siptimer_a;
3731

    
   
3731

   
3732
			if (sipdebug) {
3732
			if (sipdebug) {
3733
				ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
3733
				ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
3734
					pkt->retransid,
3734
					pkt->retransid,
3735
					pkt->retrans,
3735
					pkt->retrans,
3736
					sip_methods[pkt->method].text,
3736
					sip_methods[pkt->method].text,
3737
					pkt->method);
3737
					pkt->method);
3738
			}
3738
			}
3739
			if (!pkt->timer_a) {
3739
			if (!pkt->timer_a) {
3740
				pkt->timer_a = 2 ;
3740
				pkt->timer_a = 2 ;
3741
			} else {
3741
			} else {
3742
				pkt->timer_a = 2 * pkt->timer_a;
3742
				pkt->timer_a = 2 * pkt->timer_a;
3743
			}
3743
			}
3744

    
   
3744

   
3745
			/* For non-invites, a maximum of 4 secs */
3745
			/* For non-invites, a maximum of 4 secs */
3746
			siptimer_a = pkt->timer_t1 * pkt->timer_a;	/* Double each time */
3746
			siptimer_a = pkt->timer_t1 * pkt->timer_a;	/* Double each time */
3747
			if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
3747
			if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
3748
				siptimer_a = 4000;
3748
				siptimer_a = 4000;
3749
			}
3749
			}
3750

    
   
3750

   
3751
			/* Reschedule re-transmit */
3751
			/* Reschedule re-transmit */
3752
			reschedule = siptimer_a;
3752
			reschedule = siptimer_a;
3753
			ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
3753
			ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
3754
				pkt->retrans + 1,
3754
				pkt->retrans + 1,
3755
				siptimer_a,
3755
				siptimer_a,
3756
				pkt->timer_t1,
3756
				pkt->timer_t1,
3757
				pkt->retransid);
3757
				pkt->retransid);
3758
		}
3758
		}
3759

    
   
3759

   
3760
		if (sip_debug_test_pvt(pkt->owner)) {
3760
		if (sip_debug_test_pvt(pkt->owner)) {
3761
			const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
3761
			const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
3762
			ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
3762
			ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
3763
				pkt->retrans, sip_nat_mode(pkt->owner),
3763
				pkt->retrans, sip_nat_mode(pkt->owner),
3764
				ast_sockaddr_stringify(dst),
3764
				ast_sockaddr_stringify(dst),
3765
				pkt->data->str);
3765
				pkt->data->str);
3766
		}
3766
		}
3767

    
   
3767

   
3768
		append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
3768
		append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
3769
		xmitres = __sip_xmit(pkt->owner, pkt->data);
3769
		xmitres = __sip_xmit(pkt->owner, pkt->data);
3770

    
   
3770

   
3771
		/* If there was no error during the network transmission, schedule the next retransmission,
3771
		/* If there was no error during the network transmission, schedule the next retransmission,
3772
		 * but if the next retransmission is going to be beyond our timeout period, mark the packet's
3772
		 * but if the next retransmission is going to be beyond our timeout period, mark the packet's
3773
		 * stop_retrans value and set the next retransmit to be the exact time of timeout.  This will
3773
		 * stop_retrans value and set the next retransmit to be the exact time of timeout.  This will
3774
		 * allow any responses to the packet to be processed before the packet is destroyed on the next
3774
		 * allow any responses to the packet to be processed before the packet is destroyed on the next
3775
		 * call to this function by the scheduler. */
3775
		 * call to this function by the scheduler. */
3776
		if (xmitres != XMIT_ERROR) {
3776
		if (xmitres != XMIT_ERROR) {
3777
			if (reschedule >= diff) {
3777
			if (reschedule >= diff) {
3778
				pkt->retrans_stop = 1;
3778
				pkt->retrans_stop = 1;
3779
				reschedule = diff;
3779
				reschedule = diff;
3780
			}
3780
			}
3781
			sip_pvt_unlock(pkt->owner);
3781
			sip_pvt_unlock(pkt->owner);