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
Revision 369847 New Change
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 */

    
   
1170
AST_THREADSTORAGE(sip_transport_str_buf);

    
   
1171

   

    
   
1172
/*! \brief Size of the SIP transport buffer */

    
   
1173
#define SIP_TRANSPORT_STR_BUFSIZE 128

    
   
1174

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

    
   
1179

   
1174
/* --- Sockets and networking --------------*/
1180
/* --- Sockets and networking --------------*/
1175

    
   
1181

   
1176
/*! \brief Main socket for UDP SIP communication.
1182
/*! \brief Main socket for UDP SIP communication.
1177
 *
1183
 *
1178
 * sipsock is shared between the SIP manager thread (which handles reload
1184
 * sipsock is shared between the SIP manager thread (which handles reload
1179
 * 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
1180
 * issue udp writes (using __sip_xmit()).
1186
 * issue udp writes (using __sip_xmit()).
1181
 * 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),
1182
 * 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
1183
 * 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
1184
 * 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
1185
 * 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.
1186
 * Rather, we remember that when the race may occur, communication is
1192
 * Rather, we remember that when the race may occur, communication is
1187
 * 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
1188
 * the protocol handle this above us.
1194
 * the protocol handle this above us.
1189
 */
1195
 */
1190
static int sipsock  = -1;
1196
static int sipsock  = -1;
1191

    
   
1197

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

    
   
1199

   
1194
/*! \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
1195
 *  internip is initialized picking a suitable address from one of the
1201
 *  internip is initialized picking a suitable address from one of the
1196
 * 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
1197
 * default address/port in SIP messages, and as the default address
1203
 * default address/port in SIP messages, and as the default address
1198
 * (but not port) in SDP messages.
1204
 * (but not port) in SDP messages.
1199
 */
1205
 */
1200
static struct ast_sockaddr internip;
1206
static struct ast_sockaddr internip;
1201

    
   
1207

   
1202
/*! \brief our external IP address/port for SIP sessions.
1208
/*! \brief our external IP address/port for SIP sessions.
1203
 * 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
1204
 * 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)
1205
 * ways from the config file:
1211
 * ways from the config file:
1206
 *
1212
 *
1207
 * + with "externaddr = host[:port]" we specify the address/port explicitly.
1213
 * + with "externaddr = host[:port]" we specify the address/port explicitly.
1208
 *   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;
1209
 *
1215
 *
1210
 * + with "externhost = host[:port]" we do a similar thing, but the
1216
 * + with "externhost = host[:port]" we do a similar thing, but the
1211
 *   hostname is stored in externhost, and the hostname->IP mapping
1217
 *   hostname is stored in externhost, and the hostname->IP mapping
1212
 *   is refreshed every 'externrefresh' seconds;
1218
 *   is refreshed every 'externrefresh' seconds;
1213
 *
1219
 *
1214
 * Other variables (externhost, externexpire, externrefresh) are used
1220
 * Other variables (externhost, externexpire, externrefresh) are used
1215
 * to support the above functions.
1221
 * to support the above functions.
1216
 */
1222
 */
1217
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 */
1218
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 */
1219

    
   
1225

   
1220
static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1226
static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1221
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 */
1222
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) */
1223
static uint16_t externtcpport;          /*!< external tcp port */
1229
static uint16_t externtcpport;          /*!< external tcp port */
1224
static uint16_t externtlsport;          /*!< external tls port */
1230
static uint16_t externtlsport;          /*!< external tls port */
1225

    
   
1231

   
1226
/*! \brief  List of local networks
1232
/*! \brief  List of local networks
1227
 * 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,
1228
 * 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
1229
 * 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'
1230
 * (i.e. presumably public) addresses.
1236
 * (i.e. presumably public) addresses.
1231
 */
1237
 */
1232
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 */
1233

    
   
1239

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

    
   
1243

   
1238
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 */
1239

    
   
1245

   
1240
/*! some list management macros. */
1246
/*! some list management macros. */
1241

    
   
1247

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

    
   
1254

   
1249
/*---------------------------- Forward declarations of functions in chan_sip.c */
1255
/*---------------------------- Forward declarations of functions in chan_sip.c */
1250
/* 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
1251
	in coming releases. */
1257
	in coming releases. */
1252

    
   
1258

   
1253
/*--- PBX interface functions */
1259
/*--- PBX interface functions */
1254
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);
1255
static int sip_devicestate(const char *data);
1261
static int sip_devicestate(const char *data);
1256
static int sip_sendtext(struct ast_channel *ast, const char *text);
1262
static int sip_sendtext(struct ast_channel *ast, const char *text);
1257
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);
1258
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);
1259
static int sip_hangup(struct ast_channel *ast);
1265
static int sip_hangup(struct ast_channel *ast);
1260
static int sip_answer(struct ast_channel *ast);
1266
static int sip_answer(struct ast_channel *ast);
1261
static struct ast_frame *sip_read(struct ast_channel *ast);
1267
static struct ast_frame *sip_read(struct ast_channel *ast);
1262
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);
1263
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);
1264
static int sip_transfer(struct ast_channel *ast, const char *dest);
1270
static int sip_transfer(struct ast_channel *ast, const char *dest);
1265
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);
1266
static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1272
static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1267
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);
1268
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);
1269
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);
1270
static const char *sip_get_callid(struct ast_channel *chan);
1276
static const char *sip_get_callid(struct ast_channel *chan);
1271

    
   
1277

   
1272
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);
1273
static int sip_standard_port(enum sip_transport type, int port);
1279
static int sip_standard_port(enum sip_transport type, int port);
1274
static int sip_prepare_socket(struct sip_pvt *p);
1280
static int sip_prepare_socket(struct sip_pvt *p);
1275
static int get_address_family_filter(unsigned int transport);
1281
static int get_address_family_filter(unsigned int transport);
1276

    
   
1282

   
1277
/*--- Transmitting responses and requests */
1283
/*--- Transmitting responses and requests */
1278
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);
1279
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);
1280
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);
1281
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);
1282
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);
1283
static int retrans_pkt(const void *data);
1289
static int retrans_pkt(const void *data);
1284
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);
1285
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);
1286
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);
1287
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);
1288
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);
1289
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);
1290
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);
1291
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);
1292
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);
1293
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);
1294
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);
1295
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);
1296
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);
1297
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);
1298
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);
1299
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);
1300
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);
1301
static int transmit_info_with_vidupdate(struct sip_pvt *p);
1307
static int transmit_info_with_vidupdate(struct sip_pvt *p);
1302
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);
1303
static int transmit_refer(struct sip_pvt *p, const char *dest);
1309
static int transmit_refer(struct sip_pvt *p, const char *dest);
1304
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);
1305
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);
1306
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);
1307
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);
1308
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);
1309
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);
1310
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);
1311
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);
1312
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);
1313
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);
1314

    
   
1320

   
1315
/* Misc dialog routines */
1321
/* Misc dialog routines */
1316
static int __sip_autodestruct(const void *data);
1322
static int __sip_autodestruct(const void *data);
1317
static void *registry_unref(struct sip_registry *reg, char *tag);
1323
static void *registry_unref(struct sip_registry *reg, char *tag);
1318
static int update_call_counter(struct sip_pvt *fup, int event);
1324
static int update_call_counter(struct sip_pvt *fup, int event);
1319
static int auto_congest(const void *arg);
1325
static int auto_congest(const void *arg);
1320
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);
1321
static void free_old_route(struct sip_route *route);
1327
static void free_old_route(struct sip_route *route);
1322
static void list_route(struct sip_route *route);
1328
static void list_route(struct sip_route *route);
1323
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);
1324
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,
1325
					      struct sip_request *req, const char *uri);
1331
					      struct sip_request *req, const char *uri);
1326
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);
1327
static void check_pendings(struct sip_pvt *p);
1333
static void check_pendings(struct sip_pvt *p);
1328
static void *sip_park_thread(void *stuff);
1334
static void *sip_park_thread(void *stuff);
1329
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);
1330

    
   
1336

   
1331
static void *sip_pickup_thread(void *stuff);
1337
static void *sip_pickup_thread(void *stuff);
1332
static int sip_pickup(struct ast_channel *chan);
1338
static int sip_pickup(struct ast_channel *chan);
1333

    
   
1339

   
1334
static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1340
static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1335
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);
1336

    
   
1342

   
1337
/*--- Codec handling / SDP */
1343
/*--- Codec handling / SDP */
1338
static void try_suggested_sip_codec(struct sip_pvt *p);
1344
static void try_suggested_sip_codec(struct sip_pvt *p);
1339
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);
1340
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);
1341
static int find_sdp(struct sip_request *req);
1347
static int find_sdp(struct sip_request *req);
1342
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);
1343
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);
1344
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);
1345
static int process_sdp_a_sendonly(const char *a, int *sendonly);
1351
static int process_sdp_a_sendonly(const char *a, int *sendonly);
1346
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);
1347
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);
1348
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);
1349
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);
1350
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);
1351
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);
1352
static void start_ice(struct ast_rtp_instance *instance);
1358
static void start_ice(struct ast_rtp_instance *instance);
1353
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,
1354
			     struct ast_str **m_buf, struct ast_str **a_buf,
1360
			     struct ast_str **m_buf, struct ast_str **a_buf,
1355
			     int debug, int *min_packet_size);
1361
			     int debug, int *min_packet_size);
1356
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,
1357
				struct ast_str **m_buf, struct ast_str **a_buf,
1363
				struct ast_str **m_buf, struct ast_str **a_buf,
1358
				int debug);
1364
				int debug);
1359
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);
1360
static void do_setnat(struct sip_pvt *p);
1366
static void do_setnat(struct sip_pvt *p);
1361
static void stop_media_flows(struct sip_pvt *p);
1367
static void stop_media_flows(struct sip_pvt *p);
1362

    
   
1368

   
1363
/*--- Authentication stuff */
1369
/*--- Authentication stuff */
1364
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);
1365
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);
1366
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,
1367
					 const char *secret, const char *md5secret, int sipmethod,
1373
					 const char *secret, const char *md5secret, int sipmethod,
1368
					 const char *uri, enum xmittype reliable, int ignore);
1374
					 const char *uri, enum xmittype reliable, int ignore);
1369
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,
1370
					      int sipmethod, const char *uri, enum xmittype reliable,
1376
					      int sipmethod, const char *uri, enum xmittype reliable,
1371
					      struct ast_sockaddr *addr, struct sip_peer **authpeer);
1377
					      struct ast_sockaddr *addr, struct sip_peer **authpeer);
1372
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);
1373

    
   
1379

   
1374
/*--- Domain handling */
1380
/*--- Domain handling */
1375
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 */
1376
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);
1377
static void clear_sip_domains(void);
1383
static void clear_sip_domains(void);
1378

    
   
1384

   
1379
/*--- SIP realm authentication */
1385
/*--- SIP realm authentication */
1380
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);
1381
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);
1382

    
   
1388

   
1383
/*--- Misc functions */
1389
/*--- Misc functions */
1384
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);
1385
static int reload_config(enum channelreloadreason reason);
1391
static int reload_config(enum channelreloadreason reason);
1386
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);
1387
static int expire_register(const void *data);
1393
static int expire_register(const void *data);
1388
static void *do_monitor(void *data);
1394
static void *do_monitor(void *data);
1389
static int restart_monitor(void);
1395
static int restart_monitor(void);
1390
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);
1391
static struct ast_variable *copy_vars(struct ast_variable *src);
1397
static struct ast_variable *copy_vars(struct ast_variable *src);
1392
static int dialog_find_multiple(void *obj, void *arg, int flags);
1398
static int dialog_find_multiple(void *obj, void *arg, int flags);
1393
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);
1394
/* 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 */
1395
static int sip_refer_allocate(struct sip_pvt *p);
1401
static int sip_refer_allocate(struct sip_pvt *p);
1396
static int sip_notify_allocate(struct sip_pvt *p);
1402
static int sip_notify_allocate(struct sip_pvt *p);
1397
static void ast_quiet_chan(struct ast_channel *chan);
1403
static void ast_quiet_chan(struct ast_channel *chan);
1398
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);
1399
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);
1400

    
   
1406

   
1401
/*--- Device monitoring and Device/extension state/event handling */
1407
/*--- Device monitoring and Device/extension state/event handling */
1402
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);
1403
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);
1404
static int sip_poke_noanswer(const void *data);
1410
static int sip_poke_noanswer(const void *data);
1405
static int sip_poke_peer(struct sip_peer *peer, int force);
1411
static int sip_poke_peer(struct sip_peer *peer, int force);
1406
static void sip_poke_all_peers(void);
1412
static void sip_poke_all_peers(void);
1407
static void sip_peer_hold(struct sip_pvt *p, int hold);
1413
static void sip_peer_hold(struct sip_pvt *p, int hold);
1408
static void mwi_event_cb(const struct ast_event *, void *);
1414
static void mwi_event_cb(const struct ast_event *, void *);
1409
static void network_change_event_cb(const struct ast_event *, void *);
1415
static void network_change_event_cb(const struct ast_event *, void *);
1410
static void sip_keepalive_all_peers(void);
1416
static void sip_keepalive_all_peers(void);
1411

    
   
1417

   
1412
/*--- Applications, functions, CLI and manager command helpers */
1418
/*--- Applications, functions, CLI and manager command helpers */
1413
static const char *sip_nat_mode(const struct sip_pvt *p);
1419
static const char *sip_nat_mode(const struct sip_pvt *p);
1414
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);
1415
static char *transfermode2str(enum transfermodes mode) attribute_const;
1421
static char *transfermode2str(enum transfermodes mode) attribute_const;
1416
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);
1417
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);
1418
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[]);
1419
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);
1420
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);
1421
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);
1422
static const char *dtmfmode2str(int mode) attribute_const;
1428
static const char *dtmfmode2str(int mode) attribute_const;
1423
static int str2dtmfmode(const char *str) attribute_unused;
1429
static int str2dtmfmode(const char *str) attribute_unused;
1424
static const char *insecure2str(int mode) attribute_const;
1430
static const char *insecure2str(int mode) attribute_const;
1425
static const char *allowoverlap2str(int mode) attribute_const;
1431
static const char *allowoverlap2str(int mode) attribute_const;
1426
static void cleanup_stale_contexts(char *new, char *old);
1432
static void cleanup_stale_contexts(char *new, char *old);
1427
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);
1428
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);
1429
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);
1430
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[]);
1431
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);
1432
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[]);
1433
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);
1434
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);
1435
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);
1436
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);
1437
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);
1438
static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1444
static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1439
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1445
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1440
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);
1441
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);
1442
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);
1443
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);
1444
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);
1445
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);
1446
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);
1447
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);
1448
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);
1449
static char *sip_do_debug_ip(int fd, const char *arg);
1455
static char *sip_do_debug_ip(int fd, const char *arg);
1450
static char *sip_do_debug_peer(int fd, const char *arg);
1456
static char *sip_do_debug_peer(int fd, const char *arg);
1451
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);
1452
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);
1453
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);
1454
static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1460
static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1455
static int sip_addheader(struct ast_channel *chan, const char *data);
1461
static int sip_addheader(struct ast_channel *chan, const char *data);
1456
static int sip_do_reload(enum channelreloadreason reason);
1462
static int sip_do_reload(enum channelreloadreason reason);
1457
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);
1458
static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
1464
static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
1459
				      const char *name, int flag, int family);
1465
				      const char *name, int flag, int family);
1460
static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
1466
static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
1461
				      const char *name, int flag);
1467
				      const char *name, int flag);
1462
static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
1468
static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
1463
						const char *name, int flag, unsigned int transport);
1469
						const char *name, int flag, unsigned int transport);
1464

    
   
1470

   
1465
/*--- Debugging
1471
/*--- Debugging
1466
	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
1467
	a SIP dialog
1473
	a SIP dialog
1468
*/
1474
*/
1469
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 */
1470
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);
1471
static inline int sip_debug_test_pvt(struct sip_pvt *p);
1477
static inline int sip_debug_test_pvt(struct sip_pvt *p);
1472
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, ...);
1473
static void sip_dump_history(struct sip_pvt *dialog);
1479
static void sip_dump_history(struct sip_pvt *dialog);
1474

    
   
1480

   
1475
/*--- Device object handling */
1481
/*--- Device object handling */
1476
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);
1477
static int update_call_counter(struct sip_pvt *fup, int event);
1483
static int update_call_counter(struct sip_pvt *fup, int event);
1478
static void sip_destroy_peer(struct sip_peer *peer);
1484
static void sip_destroy_peer(struct sip_peer *peer);
1479
static void sip_destroy_peer_fn(void *peer);
1485
static void sip_destroy_peer_fn(void *peer);
1480
static void set_peer_defaults(struct sip_peer *peer);
1486
static void set_peer_defaults(struct sip_peer *peer);
1481
static struct sip_peer *temp_peer(const char *name);
1487
static struct sip_peer *temp_peer(const char *name);
1482
static void register_peer_exten(struct sip_peer *peer, int onoff);
1488
static void register_peer_exten(struct sip_peer *peer, int onoff);
1483
static int sip_poke_peer_s(const void *data);
1489
static int sip_poke_peer_s(const void *data);
1484
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);
1485
static void reg_source_db(struct sip_peer *peer);
1491
static void reg_source_db(struct sip_peer *peer);
1486
static void destroy_association(struct sip_peer *peer);
1492
static void destroy_association(struct sip_peer *peer);
1487
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);
1488
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);
1489
static void set_socket_transport(struct sip_socket *socket, int transport);
1495
static void set_socket_transport(struct sip_socket *socket, int transport);
1490
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);
1491

    
   
1497

   
1492
/* Realtime device support */
1498
/* Realtime device support */
1493
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);
1494
static void update_peer(struct sip_peer *p, int expire);
1500
static void update_peer(struct sip_peer *p, int expire);
1495
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);
1496
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);
1497
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);
1498
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);
1499

    
   
1505

   
1500
/*--- Internal UA client handling (outbound registrations) */
1506
/*--- Internal UA client handling (outbound registrations) */
1501
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);
1502
static void sip_registry_destroy(struct sip_registry *reg);
1508
static void sip_registry_destroy(struct sip_registry *reg);
1503
static int sip_register(const char *value, int lineno);
1509
static int sip_register(const char *value, int lineno);
1504
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1510
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1505
static int sip_reregister(const void *data);
1511
static int sip_reregister(const void *data);
1506
static int __sip_do_register(struct sip_registry *r);
1512
static int __sip_do_register(struct sip_registry *r);
1507
static int sip_reg_timeout(const void *data);
1513
static int sip_reg_timeout(const void *data);
1508
static void sip_send_all_registers(void);
1514
static void sip_send_all_registers(void);
1509
static int sip_reinvite_retry(const void *data);
1515
static int sip_reinvite_retry(const void *data);
1510

    
   
1516

   
1511
/*--- Parsing SIP requests and responses */
1517
/*--- Parsing SIP requests and responses */
1512
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 */
1513
static int determine_firstline_parts(struct sip_request *req);
1519
static int determine_firstline_parts(struct sip_request *req);
1514
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1520
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1515
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);
1516
static int find_sip_method(const char *msg);
1522
static int find_sip_method(const char *msg);
1517
static unsigned int parse_allowed_methods(struct sip_request *req);
1523
static unsigned int parse_allowed_methods(struct sip_request *req);
1518
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);
1519
static int parse_request(struct sip_request *req);
1525
static int parse_request(struct sip_request *req);
1520
static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1526
static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1521
static int method_match(enum sipmethod id, const char *name);
1527
static int method_match(enum sipmethod id, const char *name);
1522
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);
1523
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);
1524
static const char *find_alias(const char *name, const char *_default);
1530
static const char *find_alias(const char *name, const char *_default);
1525
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);
1526
static void lws2sws(struct ast_str *msgbuf);
1532
static void lws2sws(struct ast_str *msgbuf);
1527
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);
1528
static char *remove_uri_parameters(char *uri);
1534
static char *remove_uri_parameters(char *uri);
1529
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);
1530
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);
1531
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);
1532
static int set_address_from_contact(struct sip_pvt *pvt);
1538
static int set_address_from_contact(struct sip_pvt *pvt);
1533
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);
1534
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);
1535
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);
1536
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);
1537
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);
1538
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);
1539
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);
1540
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);
1541
static int get_domain(const char *str, char *domain, int len);
1547
static int get_domain(const char *str, char *domain, int len);
1542
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);
1543

    
   
1549

   
1544
/*-- TCP connection handling ---*/
1550
/*-- TCP connection handling ---*/
1545
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);
1546
static void *sip_tcp_worker_fn(void *);
1552
static void *sip_tcp_worker_fn(void *);
1547

    
   
1553

   
1548
/*--- Constructing requests and responses */
1554
/*--- Constructing requests and responses */
1549
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);
1550
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);
1551
static void deinit_req(struct sip_request *req);
1557
static void deinit_req(struct sip_request *req);
1552
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);
1553
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);
1554
static int init_resp(struct sip_request *resp, const char *msg);
1560
static int init_resp(struct sip_request *resp, const char *msg);
1555
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);
1556
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);
1557
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);
1558
static void build_via(struct sip_pvt *p);
1564
static void build_via(struct sip_pvt *p);
1559
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);
1560
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);
1561
static char *generate_random_string(char *buf, size_t size);
1567
static char *generate_random_string(char *buf, size_t size);
1562
static void build_callid_pvt(struct sip_pvt *pvt);
1568
static void build_callid_pvt(struct sip_pvt *pvt);
1563
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);
1564
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);
1565
static void make_our_tag(struct sip_pvt *pvt);
1571
static void make_our_tag(struct sip_pvt *pvt);
1566
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);
1567
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);
1568
static int add_content(struct sip_request *req, const char *line);
1574
static int add_content(struct sip_request *req, const char *line);
1569
static int finalize_content(struct sip_request *req);
1575
static int finalize_content(struct sip_request *req);
1570
static void destroy_msg_headers(struct sip_pvt *pvt);
1576
static void destroy_msg_headers(struct sip_pvt *pvt);
1571
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);
1572
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);
1573
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);
1574
static int add_vidupdate(struct sip_request *req);
1580
static int add_vidupdate(struct sip_request *req);
1575
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);
1576
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);
1577
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);
1578
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);
1579
static void set_destination(struct sip_pvt *p, char *uri);
1585
static void set_destination(struct sip_pvt *p, char *uri);
1580
static void append_date(struct sip_request *req);
1586
static void append_date(struct sip_request *req);
1581
static void build_contact(struct sip_pvt *p);
1587
static void build_contact(struct sip_pvt *p);
1582

    
   
1588

   
1583
/*------Request handling functions */
1589
/*------Request handling functions */
1584
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);
1585
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);
1586
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);
1587
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);
1588
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);
1589
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);
1590
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);
1591
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);
1592
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);
1593
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);
1594
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);
1595
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);
1596
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);
1597
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);
1598

    
   
1604

   
1599
/*------Response handling functions */
1605
/*------Response handling functions */
1600
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);
1601
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);
1602
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);
1603
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);
1604
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);
1605
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);
1606
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);
1607

    
   
1613

   
1608
/*------ SRTP Support -------- */
1614
/*------ SRTP Support -------- */
1609
static int setup_srtp(struct sip_srtp **srtp);
1615
static int setup_srtp(struct sip_srtp **srtp);
1610
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);
1611

    
   
1617

   
1612
/*------ T38 Support --------- */
1618
/*------ T38 Support --------- */
1613
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);
1614
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);
1615
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);
1616
static void change_t38_state(struct sip_pvt *p, int state);
1622
static void change_t38_state(struct sip_pvt *p, int state);
1617

    
   
1623

   
1618
/*------ Session-Timers functions --------- */
1624
/*------ Session-Timers functions --------- */
1619
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);
1620
static int  proc_session_timer(const void *vp);
1626
static int  proc_session_timer(const void *vp);
1621
static void stop_session_timer(struct sip_pvt *p);
1627
static void stop_session_timer(struct sip_pvt *p);
1622
static void start_session_timer(struct sip_pvt *p);
1628
static void start_session_timer(struct sip_pvt *p);
1623
static void restart_session_timer(struct sip_pvt *p);
1629
static void restart_session_timer(struct sip_pvt *p);
1624
static const char *strefresher2str(enum st_refresher r);
1630
static const char *strefresher2str(enum st_refresher r);
1625
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);
1626
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);
1627
static int st_get_se(struct sip_pvt *, int max);
1633
static int st_get_se(struct sip_pvt *, int max);
1628
static enum st_refresher st_get_refresher(struct sip_pvt *);
1634
static enum st_refresher st_get_refresher(struct sip_pvt *);
1629
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);
1630
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);
1631

    
   
1637

   
1632
/*------- RTP Glue functions -------- */
1638
/*------- RTP Glue functions -------- */
1633
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);
1634

    
   
1640

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

    
   
1647

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

    
   
1676

   
1671
/*! \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
1672
 * 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
1673
 * DTMF BEGIN frames.
1679
 * DTMF BEGIN frames.
1674
 * The struct is initialized just before registering the channel driver,
1680
 * The struct is initialized just before registering the channel driver,
1675
 * and is for use with channels using SIP INFO DTMF.
1681
 * and is for use with channels using SIP INFO DTMF.
1676
 */
1682
 */
1677
struct ast_channel_tech sip_tech_info;
1683
struct ast_channel_tech sip_tech_info;
1678

    
   
1684

   
1679
/*------- CC Support -------- */
1685
/*------- CC Support -------- */
1680
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);
1681
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);
1682
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);
1683
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);
1684
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);
1685
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);
1686
static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1692
static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1687
static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1693
static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1688

    
   
1694

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

    
   
1706

   
1701
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)
1702
{
1708
{
1703
	struct ast_cc_agent *agent = obj;
1709
	struct ast_cc_agent *agent = obj;
1704
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1710
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1705
	const char *uri = arg;
1711
	const char *uri = arg;
1706

    
   
1712

   
1707
	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;
1708
}
1714
}
1709

    
   
1715

   
1710
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)
1711
{
1717
{
1712
	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");
1713
	return agent;
1719
	return agent;
1714
}
1720
}
1715

    
   
1721

   
1716
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)
1717
{
1723
{
1718
	struct ast_cc_agent *agent = obj;
1724
	struct ast_cc_agent *agent = obj;
1719
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1725
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1720
	const char *uri = arg;
1726
	const char *uri = arg;
1721

    
   
1727

   
1722
	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;
1723
}
1729
}
1724

    
   
1730

   
1725
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)
1726
{
1732
{
1727
	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");
1728
	return agent;
1734
	return agent;
1729
}
1735
}
1730

    
   
1736

   
1731
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)
1732
{
1738
{
1733
	struct ast_cc_agent *agent = obj;
1739
	struct ast_cc_agent *agent = obj;
1734
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1740
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1735
	struct sip_pvt *call_pvt = arg;
1741
	struct sip_pvt *call_pvt = arg;
1736

    
   
1742

   
1737
	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;
1738
}
1744
}
1739

    
   
1745

   
1740
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)
1741
{
1747
{
1742
	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");
1743
	return agent;
1749
	return agent;
1744
}
1750
}
1745

    
   
1751

   
1746
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)
1747
{
1753
{
1748
	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));
1749
	struct sip_pvt *call_pvt = ast_channel_tech_pvt(chan);
1755
	struct sip_pvt *call_pvt = ast_channel_tech_pvt(chan);
1750

    
   
1756

   
1751
	if (!agent_pvt) {
1757
	if (!agent_pvt) {
1752
		return -1;
1758
		return -1;
1753
	}
1759
	}
1754

    
   
1760

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

    
   
1762

   
1757
	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));
1758
	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));
1759
	agent_pvt->offer_timer_id = -1;
1765
	agent_pvt->offer_timer_id = -1;
1760
	agent->private_data = agent_pvt;
1766
	agent->private_data = agent_pvt;
1761
	sip_pvt_lock(call_pvt);
1767
	sip_pvt_lock(call_pvt);
1762
	ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1768
	ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1763
	sip_pvt_unlock(call_pvt);
1769
	sip_pvt_unlock(call_pvt);
1764
	return 0;
1770
	return 0;
1765
}
1771
}
1766

    
   
1772

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

    
   
1777

   
1772
	agent_pvt->offer_timer_id = -1;
1778
	agent_pvt->offer_timer_id = -1;
1773

    
   
1779

   
1774
	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);
1775
}
1781
}
1776

    
   
1782

   
1777
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)
1778
{
1784
{
1779
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1785
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1780
	int when;
1786
	int when;
1781

    
   
1787

   
1782
	when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1788
	when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1783
	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);
1784
	return 0;
1790
	return 0;
1785
}
1791
}
1786

    
   
1792

   
1787
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)
1788
{
1794
{
1789
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1795
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1790

    
   
1796

   
1791
	AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1797
	AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1792
	return 0;
1798
	return 0;
1793
}
1799
}
1794

    
   
1800

   
1795
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)
1796
{
1802
{
1797
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1803
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1798

    
   
1804

   
1799
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1805
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1800
	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);
1801
	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)) {
1802
		/* 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,
1803
		 * so here's an explanation. When a subscription comes into
1809
		 * so here's an explanation. When a subscription comes into
1804
		 * 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
1805
		 * 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,
1806
		 * 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
1807
		 * failure condition.
1813
		 * failure condition.
1808
		 * 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
1809
		 * 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
1810
		 * 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
1811
		 * 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.
1812
		 * Thus we respond with happiness and flowers.
1818
		 * Thus we respond with happiness and flowers.
1813
		 */
1819
		 */
1814
		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);
1815
		transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1821
		transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1816
	} else {
1822
	} else {
1817
		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);
1818
	}
1824
	}
1819
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1825
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1820
	agent_pvt->is_available = TRUE;
1826
	agent_pvt->is_available = TRUE;
1821
}
1827
}
1822

    
   
1828

   
1823
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)
1824
{
1830
{
1825
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1831
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1826
	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;
1827
	return ast_cc_agent_status_response(agent->core_id, state);
1833
	return ast_cc_agent_status_response(agent->core_id, state);
1828
}
1834
}
1829

    
   
1835

   
1830
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)
1831
{
1837
{
1832
	/* To start monitoring just means to wait for an incoming PUBLISH
1838
	/* To start monitoring just means to wait for an incoming PUBLISH
1833
	 * 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
1834
	 * action is needed
1840
	 * action is needed
1835
	 */
1841
	 */
1836
	return 0;
1842
	return 0;
1837
}
1843
}
1838

    
   
1844

   
1839
static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1845
static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1840
{
1846
{
1841
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1847
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1842
	/* 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
1843
	 * 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
1844
	 * the caller as busy
1850
	 * the caller as busy
1845
	 */
1851
	 */
1846
	if (!agent_pvt->is_available) {
1852
	if (!agent_pvt->is_available) {
1847
		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",
1848
				agent->device_name);
1854
				agent->device_name);
1849
	}
1855
	}
1850
	/* Otherwise, we transmit a NOTIFY to the caller and await either
1856
	/* Otherwise, we transmit a NOTIFY to the caller and await either
1851
	 * a PUBLISH or an INVITE
1857
	 * a PUBLISH or an INVITE
1852
	 */
1858
	 */
1853
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1859
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1854
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1860
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1855
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1861
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1856
	return 0;
1862
	return 0;
1857
}
1863
}
1858

    
   
1864

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

    
   
1868

   
1863
	if (!agent_pvt) {
1869
	if (!agent_pvt) {
1864
		/* The agent constructor probably failed. */
1870
		/* The agent constructor probably failed. */
1865
		return;
1871
		return;
1866
	}
1872
	}
1867

    
   
1873

   
1868
	sip_cc_agent_stop_offer_timer(agent);
1874
	sip_cc_agent_stop_offer_timer(agent);
1869
	if (agent_pvt->subscribe_pvt) {
1875
	if (agent_pvt->subscribe_pvt) {
1870
		sip_pvt_lock(agent_pvt->subscribe_pvt);
1876
		sip_pvt_lock(agent_pvt->subscribe_pvt);
1871
		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)) {
1872
			/* 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
1873
			 * the subscriber know something went wrong
1879
			 * the subscriber know something went wrong
1874
			 */
1880
			 */
1875
			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);
1876
		}
1882
		}
1877
		sip_pvt_unlock(agent_pvt->subscribe_pvt);
1883
		sip_pvt_unlock(agent_pvt->subscribe_pvt);
1878
		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");
1879
	}
1885
	}
1880
	ast_free(agent_pvt);
1886
	ast_free(agent_pvt);
1881
}
1887
}
1882

    
   
1888

   
1883
struct ao2_container *sip_monitor_instances;
1889
struct ao2_container *sip_monitor_instances;
1884

    
   
1890

   
1885
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)
1886
{
1892
{
1887
	const struct sip_monitor_instance *monitor_instance = obj;
1893
	const struct sip_monitor_instance *monitor_instance = obj;
1888
	return monitor_instance->core_id;
1894
	return monitor_instance->core_id;
1889
}
1895
}
1890

    
   
1896

   
1891
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)
1892
{
1898
{
1893
	struct sip_monitor_instance *monitor_instance1 = obj;
1899
	struct sip_monitor_instance *monitor_instance1 = obj;
1894
	struct sip_monitor_instance *monitor_instance2 = arg;
1900
	struct sip_monitor_instance *monitor_instance2 = arg;
1895

    
   
1901

   
1896
	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;
1897
}
1903
}
1898

    
   
1904

   
1899
static void sip_monitor_instance_destructor(void *data)
1905
static void sip_monitor_instance_destructor(void *data)
1900
{
1906
{
1901
	struct sip_monitor_instance *monitor_instance = data;
1907
	struct sip_monitor_instance *monitor_instance = data;
1902
	if (monitor_instance->subscription_pvt) {
1908
	if (monitor_instance->subscription_pvt) {
1903
		sip_pvt_lock(monitor_instance->subscription_pvt);
1909
		sip_pvt_lock(monitor_instance->subscription_pvt);
1904
		monitor_instance->subscription_pvt->expiry = 0;
1910
		monitor_instance->subscription_pvt->expiry = 0;
1905
		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);
1906
		sip_pvt_unlock(monitor_instance->subscription_pvt);
1912
		sip_pvt_unlock(monitor_instance->subscription_pvt);
1907
		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");
1908
	}
1914
	}
1909
	if (monitor_instance->suspension_entry) {
1915
	if (monitor_instance->suspension_entry) {
1910
		monitor_instance->suspension_entry->body[0] = '\0';
1916
		monitor_instance->suspension_entry->body[0] = '\0';
1911
		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);
1912
		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");
1913
	}
1919
	}
1914
	ast_string_field_free_memory(monitor_instance);
1920
	ast_string_field_free_memory(monitor_instance);
1915
}
1921
}
1916

    
   
1922

   
1917
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)
1918
{
1924
{
1919
	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);
1920

    
   
1926

   
1921
	if (!monitor_instance) {
1927
	if (!monitor_instance) {
1922
		return NULL;
1928
		return NULL;
1923
	}
1929
	}
1924

    
   
1930

   
1925
	if (ast_string_field_init(monitor_instance, 256)) {
1931
	if (ast_string_field_init(monitor_instance, 256)) {
1926
		ao2_ref(monitor_instance, -1);
1932
		ao2_ref(monitor_instance, -1);
1927
		return NULL;
1933
		return NULL;
1928
	}
1934
	}
1929

    
   
1935

   
1930
	ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
1936
	ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
1931
	ast_string_field_set(monitor_instance, peername, peername);
1937
	ast_string_field_set(monitor_instance, peername, peername);
1932
	ast_string_field_set(monitor_instance, device_name, device_name);
1938
	ast_string_field_set(monitor_instance, device_name, device_name);
1933
	monitor_instance->core_id = core_id;
1939
	monitor_instance->core_id = core_id;
1934
	ao2_link(sip_monitor_instances, monitor_instance);
1940
	ao2_link(sip_monitor_instances, monitor_instance);
1935
	return monitor_instance;
1941
	return monitor_instance;
1936
}
1942
}
1937

    
   
1943

   
1938
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)
1939
{
1945
{
1940
	struct sip_monitor_instance *monitor_instance = obj;
1946
	struct sip_monitor_instance *monitor_instance = obj;
1941
	return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
1947
	return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
1942
}
1948
}
1943

    
   
1949

   
1944
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)
1945
{
1951
{
1946
	struct sip_monitor_instance *monitor_instance = obj;
1952
	struct sip_monitor_instance *monitor_instance = obj;
1947
	return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
1953
	return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
1948
}
1954
}
1949

    
   
1955

   
1950
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);
1951
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
1957
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
1952
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
1958
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
1953
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);
1954
static void sip_cc_monitor_destructor(void *private_data);
1960
static void sip_cc_monitor_destructor(void *private_data);
1955

    
   
1961

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

    
   
1970

   
1965
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)
1966
{
1972
{
1967
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1973
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1968
	enum ast_cc_service_type service = monitor->service_offered;
1974
	enum ast_cc_service_type service = monitor->service_offered;
1969
	int when;
1975
	int when;
1970

    
   
1976

   
1971
	if (!monitor_instance) {
1977
	if (!monitor_instance) {
1972
		return -1;
1978
		return -1;
1973
	}
1979
	}
1974

    
   
1980

   
1975
	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))) {
1976
		return -1;
1982
		return -1;
1977
	}
1983
	}
1978

    
   
1984

   
1979
	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) :
1980
		ast_get_ccnr_available_timer(monitor->interface->config_params);
1986
		ast_get_ccnr_available_timer(monitor->interface->config_params);
1981

    
   
1987

   
1982
	sip_pvt_lock(monitor_instance->subscription_pvt);
1988
	sip_pvt_lock(monitor_instance->subscription_pvt);
1983
	ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
1989
	ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
1984
	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);
1985
	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);
1986
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1992
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1987
	monitor_instance->subscription_pvt->expiry = when;
1993
	monitor_instance->subscription_pvt->expiry = when;
1988

    
   
1994

   
1989
	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);
1990
	sip_pvt_unlock(monitor_instance->subscription_pvt);
1996
	sip_pvt_unlock(monitor_instance->subscription_pvt);
1991

    
   
1997

   
1992
	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");
1993
	*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);
1994
	return 0;
2000
	return 0;
1995
}
2001
}
1996

    
   
2002

   
1997
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)
1998
{
2004
{
1999
	struct ast_str *body = ast_str_alloca(size);
2005
	struct ast_str *body = ast_str_alloca(size);
2000
	char tuple_id[32];
2006
	char tuple_id[32];
2001

    
   
2007

   
2002
	generate_random_string(tuple_id, sizeof(tuple_id));
2008
	generate_random_string(tuple_id, sizeof(tuple_id));
2003

    
   
2009

   
2004
	/* 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
2005
	 * 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.
2006
	 */
2012
	 */
2007
	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");
2008
	/* 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
2009
	 * 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
2010
	 * 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
2011
	 * 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
2012
	 * should be revisited as support is expanded.
2018
	 * should be revisited as support is expanded.
2013
	 */
2019
	 */
2014
	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);
2015
	ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
2021
	ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
2016
	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");
2017
	ast_str_append(&body, 0, "</tuple>\n");
2023
	ast_str_append(&body, 0, "</tuple>\n");
2018
	ast_str_append(&body, 0, "</presence>\n");
2024
	ast_str_append(&body, 0, "</presence>\n");
2019
	ast_copy_string(pidf_body, ast_str_buffer(body), size);
2025
	ast_copy_string(pidf_body, ast_str_buffer(body), size);
2020
	return 0;
2026
	return 0;
2021
}
2027
}
2022

    
   
2028

   
2023
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
2029
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
2024
{
2030
{
2025
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
2031
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
2026
	enum sip_publish_type publish_type;
2032
	enum sip_publish_type publish_type;
2027
	struct cc_epa_entry *cc_entry;
2033
	struct cc_epa_entry *cc_entry;
2028

    
   
2034

   
2029
	if (!monitor_instance) {
2035
	if (!monitor_instance) {
2030
		return -1;
2036
		return -1;
2031
	}
2037
	}
2032

    
   
2038

   
2033
	if (!monitor_instance->suspension_entry) {
2039
	if (!monitor_instance->suspension_entry) {
2034
		/* 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 */
2035
		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))) {
2036
			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");
2037
			ao2_ref(monitor_instance, -1);
2043
			ao2_ref(monitor_instance, -1);
2038
			return -1;
2044
			return -1;
2039
		}
2045
		}
2040
		if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
2046
		if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
2041
			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");
2042
			ao2_ref(monitor_instance, -1);
2048
			ao2_ref(monitor_instance, -1);
2043
			return -1;
2049
			return -1;
2044
		}
2050
		}
2045
		cc_entry->core_id = monitor->core_id;
2051
		cc_entry->core_id = monitor->core_id;
2046
		monitor_instance->suspension_entry->instance_data = cc_entry;
2052
		monitor_instance->suspension_entry->instance_data = cc_entry;
2047
		publish_type = SIP_PUBLISH_INITIAL;
2053
		publish_type = SIP_PUBLISH_INITIAL;
2048
	} else {
2054
	} else {
2049
		publish_type = SIP_PUBLISH_MODIFY;
2055
		publish_type = SIP_PUBLISH_MODIFY;
2050
		cc_entry = monitor_instance->suspension_entry->instance_data;
2056
		cc_entry = monitor_instance->suspension_entry->instance_data;
2051
	}
2057
	}
2052

    
   
2058

   
2053
	cc_entry->current_state = CC_CLOSED;
2059
	cc_entry->current_state = CC_CLOSED;
2054

    
   
2060

   
2055
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
2061
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
2056
		/* 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
2057
		 * not received a NOTIFY from this destination stating that he is
2063
		 * not received a NOTIFY from this destination stating that he is
2058
		 * currently available.
2064
		 * currently available.
2059
		 *
2065
		 *
2060
		 * This situation can arise when the core calls the suspend callbacks
2066
		 * This situation can arise when the core calls the suspend callbacks
2061
		 * of multiple destinations. If one of the other destinations aside
2067
		 * of multiple destinations. If one of the other destinations aside
2062
		 * from this one notified Asterisk that he is available, then there
2068
		 * from this one notified Asterisk that he is available, then there
2063
		 * 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,
2064
		 * 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
2065
		 * is still "suspended" then we can immediately respond with the
2071
		 * is still "suspended" then we can immediately respond with the
2066
		 * proper PUBLISH to let this endpoint know what is going on.
2072
		 * proper PUBLISH to let this endpoint know what is going on.
2067
		 */
2073
		 */
2068
		return 0;
2074
		return 0;
2069
	}
2075
	}
2070
	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);
2071
	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);
2072
}
2078
}
2073

    
   
2079

   
2074
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
2080
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
2075
{
2081
{
2076
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
2082
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
2077
	struct cc_epa_entry *cc_entry;
2083
	struct cc_epa_entry *cc_entry;
2078

    
   
2084

   
2079
	if (!monitor_instance) {
2085
	if (!monitor_instance) {
2080
		return -1;
2086
		return -1;
2081
	}
2087
	}
2082

    
   
2088

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

    
   
2090

   
2085
	cc_entry = monitor_instance->suspension_entry->instance_data;
2091
	cc_entry = monitor_instance->suspension_entry->instance_data;
2086
	cc_entry->current_state = CC_OPEN;
2092
	cc_entry->current_state = CC_OPEN;
2087
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
2093
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
2088
		/* 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
2089
		 * 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
2090
		 * PUBLISH at this point either. We can just return instead.
2096
		 * PUBLISH at this point either. We can just return instead.
2091
		 */
2097
		 */
2092
		return 0;
2098
		return 0;
2093
	}
2099
	}
2094
	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);
2095
	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);
2096
}
2102
}
2097

    
   
2103

   
2098
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)
2099
{
2105
{
2100
	if (*sched_id != -1) {
2106
	if (*sched_id != -1) {
2101
		AST_SCHED_DEL(sched, *sched_id);
2107
		AST_SCHED_DEL(sched, *sched_id);
2102
		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");
2103
	}
2109
	}
2104
	return 0;
2110
	return 0;
2105
}
2111
}
2106

    
   
2112

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

    
   
2119

   
2114
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)
2115
{
2121
{
2116
	char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
2122
	char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
2117
	char *uri;
2123
	char *uri;
2118
	char *purpose;
2124
	char *purpose;
2119
	char *service_str;
2125
	char *service_str;
2120
	static const char cc_purpose[] = "purpose=call-completion";
2126
	static const char cc_purpose[] = "purpose=call-completion";
2121
	static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2127
	static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2122

    
   
2128

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

    
   
2133

   
2128
	uri = strsep(&call_info, ";");
2134
	uri = strsep(&call_info, ";");
2129

    
   
2135

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

    
   
2145

   
2140
	/* 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 */
2141
	while ((service_str = strsep(&call_info, ";"))) {
2147
	while ((service_str = strsep(&call_info, ";"))) {
2142
		if (!strncmp(service_str, "m=", 2)) {
2148
		if (!strncmp(service_str, "m=", 2)) {
2143
			break;
2149
			break;
2144
		}
2150
		}
2145
	}
2151
	}
2146
	if (!service_str) {
2152
	if (!service_str) {
2147
		/* 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
2148
		 * doesn't matter anyway
2154
		 * doesn't matter anyway
2149
		 */
2155
		 */
2150
		service_str = "BS";
2156
		service_str = "BS";
2151
	} else {
2157
	} else {
2152
		/* 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
2153
		 * the result of this strsep
2159
		 * the result of this strsep
2154
		 */
2160
		 */
2155
		strsep(&service_str, "=");
2161
		strsep(&service_str, "=");
2156
	}
2162
	}
2157

    
   
2163

   
2158
	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) {
2159
		/* Invalid service offered */
2165
		/* Invalid service offered */
2160
		return -1;
2166
		return -1;
2161
	}
2167
	}
2162

    
   
2168

   
2163
	ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2169
	ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2164

    
   
2170

   
2165
	return 0;
2171
	return 0;
2166
}
2172
}
2167

    
   
2173

   
2168
/*
2174
/*
2169
 * \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
2170
 *
2176
 *
2171
 * 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,
2172
 * 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
2173
 * 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
2174
 * use native CC monitoring for the call, then so be it.
2180
 * use native CC monitoring for the call, then so be it.
2175
 *
2181
 *
2176
 * 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
2177
 * 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
2178
 * 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"
2179
 *
2185
 *
2180
 * \param pvt The current dialog. Contains CC parameters for the endpoint
2186
 * \param pvt The current dialog. Contains CC parameters for the endpoint
2181
 * \param req The response to the INVITE we want to inspect
2187
 * \param req The response to the INVITE we want to inspect
2182
 * \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
2183
 * monitoring, we get the service from the SIP response itself
2189
 * monitoring, we get the service from the SIP response itself
2184
 */
2190
 */
2185
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)
2186
{
2192
{
2187
	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);
2188
	int core_id;
2194
	int core_id;
2189
	char interface_name[AST_CHANNEL_NAME];
2195
	char interface_name[AST_CHANNEL_NAME];
2190

    
   
2196

   
2191
	if (monitor_policy == AST_CC_MONITOR_NEVER) {
2197
	if (monitor_policy == AST_CC_MONITOR_NEVER) {
2192
		/* Don't bother, just return */
2198
		/* Don't bother, just return */
2193
		return;
2199
		return;
2194
	}
2200
	}
2195

    
   
2201

   
2196
	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) {
2197
		/* For some reason, CC is invalid, so don't try it! */
2203
		/* For some reason, CC is invalid, so don't try it! */
2198
		return;
2204
		return;
2199
	}
2205
	}
2200

    
   
2206

   
2201
	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));
2202

    
   
2208

   
2203
	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) {
2204
		char subscribe_uri[SIPBUFSIZE];
2210
		char subscribe_uri[SIPBUFSIZE];
2205
		char device_name[AST_CHANNEL_NAME];
2211
		char device_name[AST_CHANNEL_NAME];
2206
		enum ast_cc_service_type offered_service;
2212
		enum ast_cc_service_type offered_service;
2207
		struct sip_monitor_instance *monitor_instance;
2213
		struct sip_monitor_instance *monitor_instance;
2208
		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)) {
2209
			/* 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
2210
			 * 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
2211
			 * call completion since the monitor policy may be "always"
2217
			 * call completion since the monitor policy may be "always"
2212
			 */
2218
			 */
2213
			goto generic;
2219
			goto generic;
2214
		}
2220
		}
2215
		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));
2216
		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))) {
2217
			/* Same deal. We can try using generic still */
2223
			/* Same deal. We can try using generic still */
2218
			goto generic;
2224
			goto generic;
2219
		}
2225
		}
2220
		/* 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
2221
		 * 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
2222
		 * refcount once the monitor destructor is called
2228
		 * refcount once the monitor destructor is called
2223
		 */
2229
		 */
2224
		ast_module_ref(ast_module_info->self);
2230
		ast_module_ref(ast_module_info->self);
2225
		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);
2226
		ao2_ref(monitor_instance, -1);
2232
		ao2_ref(monitor_instance, -1);
2227
		return;
2233
		return;
2228
	}
2234
	}
2229

    
   
2235

   
2230
generic:
2236
generic:
2231
	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) {
2232
		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);
2233
	}
2239
	}
2234
}
2240
}
2235

    
   
2241

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

    
   
2244

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

    
   
2247

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

    
   
2258

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

    
   
2269

   
2264
/*! \brief Append to SIP dialog history
2270
/*! \brief Append to SIP dialog history
2265
	\return Always returns 0 */
2271
	\return Always returns 0 */
2266
#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)
2267

    
   
2273

   
2268
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)
2269
{
2275
{
2270
	if (p)
2276
	if (p)
2271
#ifdef REF_DEBUG
2277
#ifdef REF_DEBUG
2272
		__ao2_ref_debug(p, 1, tag, file, line, func);
2278
		__ao2_ref_debug(p, 1, tag, file, line, func);
2273
#else
2279
#else
2274
		ao2_ref(p, 1);
2280
		ao2_ref(p, 1);
2275
#endif
2281
#endif
2276
	else
2282
	else
2277
		ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2283
		ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2278
	return p;
2284
	return p;
2279
}
2285
}
2280

    
   
2286

   
2281
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)
2282
{
2288
{
2283
	if (p)
2289
	if (p)
2284
#ifdef REF_DEBUG
2290
#ifdef REF_DEBUG
2285
		__ao2_ref_debug(p, -1, tag, file, line, func);
2291
		__ao2_ref_debug(p, -1, tag, file, line, func);
2286
#else
2292
#else
2287
		ao2_ref(p, -1);
2293
		ao2_ref(p, -1);
2288
#endif
2294
#endif
2289
	return NULL;
2295
	return NULL;
2290
}
2296
}
2291

    
   
2297

   
2292
/*! \brief map from an integer value to a string.
2298
/*! \brief map from an integer value to a string.
2293
 * If no match is found, return errorstring
2299
 * If no match is found, return errorstring
2294
 */
2300
 */
2295
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)
2296
{
2302
{
2297
	const struct _map_x_s *cur;
2303
	const struct _map_x_s *cur;
2298

    
   
2304

   
2299
	for (cur = table; cur->s; cur++) {
2305
	for (cur = table; cur->s; cur++) {
2300
		if (cur->x == x) {
2306
		if (cur->x == x) {
2301
			return cur->s;
2307
			return cur->s;
2302
		}
2308
		}
2303
	}
2309
	}
2304
	return errorstring;
2310
	return errorstring;
2305
}
2311
}
2306

    
   
2312

   
2307
/*! \brief map from a string to an integer value, case insensitive.
2313
/*! \brief map from a string to an integer value, case insensitive.
2308
 * If no match is found, return errorvalue.
2314
 * If no match is found, return errorvalue.
2309
 */
2315
 */
2310
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)
2311
{
2317
{
2312
	const struct _map_x_s *cur;
2318
	const struct _map_x_s *cur;
2313

    
   
2319

   
2314
	for (cur = table; cur->s; cur++) {
2320
	for (cur = table; cur->s; cur++) {
2315
		if (!strcasecmp(cur->s, s)) {
2321
		if (!strcasecmp(cur->s, s)) {
2316
			return cur->x;
2322
			return cur->x;
2317
		}
2323
		}
2318
	}
2324
	}
2319
	return errorvalue;
2325
	return errorvalue;
2320
}
2326
}
2321

    
   
2327

   
2322
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)
2323
{
2329
{
2324
	enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2330
	enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2325
	int i;
2331
	int i;
2326

    
   
2332

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

    
   
2339

   
2334
	return ast;
2340
	return ast;
2335
}
2341
}
2336

    
   
2342

   
2337
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)
2338
{
2344
{
2339
	if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2345
	if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2340
		return sip_reason_table[code].text;
2346
		return sip_reason_table[code].text;
2341
	}
2347
	}
2342

    
   
2348

   
2343
	return "unknown";
2349
	return "unknown";
2344
}
2350
}
2345

    
   
2351

   
2346
/*!
2352
/*!
2347
 * \brief generic function for determining if a correct transport is being
2353
 * \brief generic function for determining if a correct transport is being
2348
 * used to contact a peer
2354
 * used to contact a peer
2349
 *
2355
 *
2350
 * 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
2351
 * sip_request or a sip_peer
2357
 * sip_request or a sip_peer
2352
 */
2358
 */
2353
#define check_request_transport(peer, tmpl) ({ \
2359
#define check_request_transport(peer, tmpl) ({ \
2354
	int ret = 0; \
2360
	int ret = 0; \
2355
	if (peer->socket.type == tmpl->socket.type) \
2361
	if (peer->socket.type == tmpl->socket.type) \
2356
		; \
2362
		; \
2357
	else if (!(peer->transports & tmpl->socket.type)) {\
2363
	else if (!(peer->transports & tmpl->socket.type)) {\
2358
		ast_log(LOG_ERROR, \
2364
		ast_log(LOG_ERROR, \
2359
			"'%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", \
2360
			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) \
2361
			); \
2367
			); \
2362
		ret = 1; \
2368
		ret = 1; \
2363
	} else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
2369
	} else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
2364
		ast_log(LOG_WARNING, \
2370
		ast_log(LOG_WARNING, \
2365
			"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", \
2366
			peer->name, sip_get_transport(tmpl->socket.type) \
2372
			peer->name, sip_get_transport(tmpl->socket.type) \
2367
		); \
2373
		); \
2368
	} else { \
2374
	} else { \
2369
		ast_debug(1, \
2375
		ast_debug(1, \
2370
			"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", \
2371
			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) \
2372
		); \
2378
		); \
2373
	}\
2379
	}\
2374
	(ret); \
2380
	(ret); \
2375
})
2381
})
2376

    
   
2382

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

    
   
2389

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

    
   
2398

   
2393
static void tcptls_packet_destructor(void *obj)
2399
static void tcptls_packet_destructor(void *obj)
2394
{
2400
{
2395
	struct tcptls_packet *packet = obj;
2401
	struct tcptls_packet *packet = obj;
2396

    
   
2402

   
2397
	ast_free(packet->data);
2403
	ast_free(packet->data);
2398
}
2404
}
2399

    
   
2405

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

    
   
2419

   
2414
static void sip_threadinfo_destructor(void *obj)
2420
static void sip_threadinfo_destructor(void *obj)
2415
{
2421
{
2416
	struct sip_threadinfo *th = obj;
2422
	struct sip_threadinfo *th = obj;
2417
	struct tcptls_packet *packet;
2423
	struct tcptls_packet *packet;
2418

    
   
2424

   
2419
	if (th->alert_pipe[1] > -1) {
2425
	if (th->alert_pipe[1] > -1) {
2420
		close(th->alert_pipe[0]);
2426
		close(th->alert_pipe[0]);
2421
	}
2427
	}
2422
	if (th->alert_pipe[1] > -1) {
2428
	if (th->alert_pipe[1] > -1) {
2423
		close(th->alert_pipe[1]);
2429
		close(th->alert_pipe[1]);
2424
	}
2430
	}
2425
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2431
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2426

    
   
2432

   
2427
	while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2433
	while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2428
		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");
2429
	}
2435
	}
2430

    
   
2436

   
2431
	if (th->tcptls_session) {
2437
	if (th->tcptls_session) {
2432
		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");
2433
	}
2439
	}
2434
}
2440
}
2435

    
   
2441

   
2436
/*! \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. */
2437
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)
2438
{
2444
{
2439
	struct sip_threadinfo *th;
2445
	struct sip_threadinfo *th;
2440

    
   
2446

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

    
   
2450

   
2445
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2451
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2446

    
   
2452

   
2447
	if (pipe(th->alert_pipe) == -1) {
2453
	if (pipe(th->alert_pipe) == -1) {
2448
		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");
2449
		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));
2450
		return NULL;
2456
		return NULL;
2451
	}
2457
	}
2452
	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");
2453
	th->tcptls_session = tcptls_session;
2459
	th->tcptls_session = tcptls_session;
2454
	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);
2455
	ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2461
	ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2456
	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");
2457
	return th;
2463
	return th;
2458
}
2464
}
2459

    
   
2465

   
2460
/*! \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 */
2461
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)
2462
{
2468
{
2463
	int res = len;
2469
	int res = len;
2464
	struct sip_threadinfo *th = NULL;
2470
	struct sip_threadinfo *th = NULL;
2465
	struct tcptls_packet *packet = NULL;
2471
	struct tcptls_packet *packet = NULL;
2466
	struct sip_threadinfo tmp = {
2472
	struct sip_threadinfo tmp = {
2467
		.tcptls_session = tcptls_session,
2473
		.tcptls_session = tcptls_session,
2468
	};
2474
	};
2469
	enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2475
	enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2470

    
   
2476

   
2471
	if (!tcptls_session) {
2477
	if (!tcptls_session) {
2472
		return XMIT_ERROR;
2478
		return XMIT_ERROR;
2473
	}
2479
	}
2474

    
   
2480

   
2475
	ao2_lock(tcptls_session);
2481
	ao2_lock(tcptls_session);
2476

    
   
2482

   
2477
	if ((tcptls_session->fd == -1) ||
2483
	if ((tcptls_session->fd == -1) ||
2478
		!(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")) ||
2479
		!(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2485
		!(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2480
		!(packet->data = ast_str_create(len))) {
2486
		!(packet->data = ast_str_create(len))) {
2481
		goto tcptls_write_setup_error;
2487
		goto tcptls_write_setup_error;
2482
	}
2488
	}
2483

    
   
2489

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

    
   
2493

   
2488
	/* 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.
2489
	 * must lock the thread info object to guarantee control of the
2495
	 * must lock the thread info object to guarantee control of the
2490
	 * packet queue */
2496
	 * packet queue */
2491
	ao2_lock(th);
2497
	ao2_lock(th);
2492
	if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2498
	if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2493
		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));
2494
		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");
2495
		packet = NULL;
2501
		packet = NULL;
2496
		res = XMIT_ERROR;
2502
		res = XMIT_ERROR;
2497
	} 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 */
2498
		AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2504
		AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2499
	}
2505
	}
2500
	ao2_unlock(th);
2506
	ao2_unlock(th);
2501

    
   
2507

   
2502
	ao2_unlock(tcptls_session);
2508
	ao2_unlock(tcptls_session);
2503
	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");
2504
	return res;
2510
	return res;
2505

    
   
2511

   
2506
tcptls_write_setup_error:
2512
tcptls_write_setup_error:
2507
	if (th) {
2513
	if (th) {
2508
		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");
2509
	}
2515
	}
2510
	if (packet) {
2516
	if (packet) {
2511
		ao2_t_ref(packet, -1, "could not allocate packet's data");
2517
		ao2_t_ref(packet, -1, "could not allocate packet's data");
2512
	}
2518
	}
2513
	ao2_unlock(tcptls_session);
2519
	ao2_unlock(tcptls_session);
2514

    
   
2520

   
2515
	return XMIT_ERROR;
2521
	return XMIT_ERROR;
2516
}
2522
}
2517

    
   
2523

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

    
   
2528

   
2523
	return _sip_tcp_helper_thread(tcptls_session);
2529
	return _sip_tcp_helper_thread(tcptls_session);
2524
}
2530
}
2525

    
   
2531

   

    
   
2532
/*! \brief SIP WebSocket connection handler */

    
   
2533
static void sip_websocket_callback(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)

    
   
2534
{

    
   
2535
	int res;

    
   
2536

   

    
   
2537
	if (ast_websocket_set_nonblock(session)) {

    
   
2538
		goto end;

    
   
2539
	}

    
   
2540

   

    
   
2541
	while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {

    
   
2542
		char *payload;

    
   
2543
		uint64_t payload_len;

    
   
2544
		enum ast_websocket_opcode opcode;

    
   
2545
		int fragmented;

    
   
2546

   

    
   
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 */

    
   
2549
			break;

    
   
2550
		}

    
   
2551

   

    
   
2552
		if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {

    
   
2553
			struct sip_request req = { 0, };

    
   
2554

   

    
   
2555
			if (!(req.data = ast_str_create(payload_len))) {

    
   
2556
				goto end;

    
   
2557
			}

    
   
2558

   

    
   
2559
			if (ast_str_set(&req.data, -1, "%s", payload) == AST_DYNSTR_BUILD_FAILED) {

    
   
2560
				deinit_req(&req);

    
   
2561
				goto end;

    
   
2562
			}

    
   
2563

   

    
   
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);

    
   
2566
			req.socket.ws_session = session;

    
   
2567

   

    
   
2568
			handle_request_do(&req, ast_websocket_remote_address(session));

    
   
2569
			deinit_req(&req);

    
   
2570

   

    
   
2571
		} else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {

    
   
2572
			break;

    
   
2573
		}

    
   
2574
	}

    
   
2575

   

    
   
2576
end:

    
   
2577
	ast_websocket_unref(session);

    
   
2578
}

    
   
2579

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

    
   
2595

   
2542
	timeout = (authtimeout - (now - start)) * 1000;
2596
	timeout = (authtimeout - (now - start)) * 1000;
2543
	if (timeout < 0) {
2597
	if (timeout < 0) {
2544
		/* we have timed out */
2598
		/* we have timed out */
2545
		return 0;
2599
		return 0;
2546
	}
2600
	}
2547

    
   
2601

   
2548
	return timeout;
2602
	return timeout;
2549
}
2603
}
2550

    
   
2604

   
2551
/*! \brief SIP TCP thread management function
2605
/*! \brief SIP TCP thread management function
2552
	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
2553
*/
2607
*/
2554
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)
2555
{
2609
{
2556
	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;
2557
	time_t start;
2611
	time_t start;
2558
	struct sip_request req = { 0, } , reqcpy = { 0, };
2612
	struct sip_request req = { 0, } , reqcpy = { 0, };
2559
	struct sip_threadinfo *me = NULL;
2613
	struct sip_threadinfo *me = NULL;
2560
	char buf[1024] = "";
2614
	char buf[1024] = "";
2561
	struct pollfd fds[2] = { { 0 }, { 0 }, };
2615
	struct pollfd fds[2] = { { 0 }, { 0 }, };
2562
	struct ast_tcptls_session_args *ca = NULL;
2616
	struct ast_tcptls_session_args *ca = NULL;
2563

    
   
2617

   
2564
	/* 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
2565
	 * 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
2566
	 * threadinfo object so we can access this thread for writing.
2620
	 * threadinfo object so we can access this thread for writing.
2567
	 *
2621
	 *
2568
	 * if this is a client connection more work must be done.
2622
	 * if this is a client connection more work must be done.
2569
	 * 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
2570
	 *    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.
2571
	 * 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
2572
	 *    it must be found within the threadt table.
2626
	 *    it must be found within the threadt table.
2573
	 * 3. Last, the tcptls_session must be started.
2627
	 * 3. Last, the tcptls_session must be started.
2574
	 */
2628
	 */
2575
	if (!tcptls_session->client) {
2629
	if (!tcptls_session->client) {
2576
		if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
2630
		if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
2577
			/* unauth_sessions is decremented in the cleanup code */
2631
			/* unauth_sessions is decremented in the cleanup code */
2578
			goto cleanup;
2632
			goto cleanup;
2579
		}
2633
		}
2580

    
   
2634

   
2581
		if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
2635
		if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
2582
			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));
2583
			goto cleanup;
2637
			goto cleanup;
2584
		}
2638
		}
2585

    
   
2639

   
2586
		flags |= O_NONBLOCK;
2640
		flags |= O_NONBLOCK;
2587
		if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
2641
		if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
2588
			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));
2589
			goto cleanup;
2643
			goto cleanup;
2590
		}
2644
		}
2591

    
   
2645

   
2592
		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))) {
2593
			goto cleanup;
2647
			goto cleanup;
2594
		}
2648
		}
2595
		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");
2596
	} else {
2650
	} else {
2597
		struct sip_threadinfo tmp = {
2651
		struct sip_threadinfo tmp = {
2598
			.tcptls_session = tcptls_session,
2652
			.tcptls_session = tcptls_session,
2599
		};
2653
		};
2600

    
   
2654

   
2601
		if ((!(ca = tcptls_session->parent)) ||
2655
		if ((!(ca = tcptls_session->parent)) ||
2602
			(!(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"))) ||
2603
			(!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
2657
			(!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
2604
			goto cleanup;
2658
			goto cleanup;
2605
		}
2659
		}
2606
	}
2660
	}
2607

    
   
2661

   
2608
	flags = 1;
2662
	flags = 1;
2609
	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))) {
2610
		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));
2611
		goto cleanup;
2665
		goto cleanup;
2612
	}
2666
	}
2613

    
   
2667

   
2614
	me->threadid = pthread_self();
2668
	me->threadid = pthread_self();
2615
	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");
2616

    
   
2670

   
2617
	/* 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 */
2618
	fds[0].fd = tcptls_session->fd;
2672
	fds[0].fd = tcptls_session->fd;
2619
	fds[1].fd = me->alert_pipe[0];
2673
	fds[1].fd = me->alert_pipe[0];
2620
	fds[0].events = fds[1].events = POLLIN | POLLPRI;
2674
	fds[0].events = fds[1].events = POLLIN | POLLPRI;
2621

    
   
2675

   
2622
	if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
2676
	if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
2623
		goto cleanup;
2677
		goto cleanup;
2624
	}
2678
	}
2625
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
2679
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
2626
		goto cleanup;
2680
		goto cleanup;
2627
	}
2681
	}
2628

    
   
2682

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

    
   
2687

   
2634
	for (;;) {
2688
	for (;;) {
2635
		struct ast_str *str_save;
2689
		struct ast_str *str_save;
2636

    
   
2690

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

    
   
2695

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

    
   
2701

   
2648
			if (timeout == 0) {
2702
			if (timeout == 0) {
2649
				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");
2650
				goto cleanup;
2704
				goto cleanup;
2651
			}
2705
			}
2652
		} else {
2706
		} else {
2653
			timeout = -1;
2707
			timeout = -1;
2654
		}
2708
		}
2655

    
   
2709

   
2656
		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 */
2657
		if (res < 0) {
2711
		if (res < 0) {
2658
			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);
2659
			goto cleanup;
2713
			goto cleanup;
2660
		} else if (res == 0) {
2714
		} else if (res == 0) {
2661
			/* timeout */
2715
			/* timeout */
2662
			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");
2663
			goto cleanup;
2717
			goto cleanup;
2664
		}
2718
		}
2665

    
   
2719

   
2666
		/* 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,
2667
		 * and writes from alert_pipe fd */
2721
		 * and writes from alert_pipe fd */
2668
		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 */
2669
			after_poll = 1;
2723
			after_poll = 1;
2670

    
   
2724

   
2671
			fds[0].revents = 0;
2725
			fds[0].revents = 0;
2672

    
   
2726

   
2673
			/* clear request structure */
2727
			/* clear request structure */
2674
			str_save = req.data;
2728
			str_save = req.data;
2675
			memset(&req, 0, sizeof(req));
2729
			memset(&req, 0, sizeof(req));
2676
			req.data = str_save;
2730
			req.data = str_save;
2677
			ast_str_reset(req.data);
2731
			ast_str_reset(req.data);
2678

    
   
2732

   
2679
			str_save = reqcpy.data;
2733
			str_save = reqcpy.data;
2680
			memset(&reqcpy, 0, sizeof(reqcpy));
2734
			memset(&reqcpy, 0, sizeof(reqcpy));
2681
			reqcpy.data = str_save;
2735
			reqcpy.data = str_save;
2682
			ast_str_reset(reqcpy.data);
2736
			ast_str_reset(reqcpy.data);
2683

    
   
2737

   
2684
			memset(buf, 0, sizeof(buf));
2738
			memset(buf, 0, sizeof(buf));
2685

    
   
2739

   
2686
			if (tcptls_session->ssl) {
2740
			if (tcptls_session->ssl) {
2687
				set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
2741
				set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
2688
				req.socket.port = htons(ourport_tls);
2742
				req.socket.port = htons(ourport_tls);
2689
			} else {
2743
			} else {
2690
				set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
2744
				set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
2691
				req.socket.port = htons(ourport_tcp);
2745
				req.socket.port = htons(ourport_tcp);
2692
			}
2746
			}
2693
			req.socket.fd = tcptls_session->fd;
2747
			req.socket.fd = tcptls_session->fd;
2694

    
   
2748

   
2695
			/* Read in headers one line at a time */
2749
			/* Read in headers one line at a time */
2696
			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)) {
2697
				if (!tcptls_session->client && !authenticated ) {
2751
				if (!tcptls_session->client && !authenticated ) {
2698
					if ((timeout = sip_check_authtimeout(start)) < 0) {
2752
					if ((timeout = sip_check_authtimeout(start)) < 0) {
2699
						goto cleanup;
2753
						goto cleanup;
2700
					}
2754
					}
2701

    
   
2755

   
2702
					if (timeout == 0) {
2756
					if (timeout == 0) {
2703
						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");
2704
						goto cleanup;
2758
						goto cleanup;
2705
					}
2759
					}
2706
				} else {
2760
				} else {
2707
					timeout = -1;
2761
					timeout = -1;
2708
				}
2762
				}
2709

    
   
2763

   
2710
				/* special polling behavior is required for TLS
2764
				/* special polling behavior is required for TLS
2711
				 * sockets because of the buffering done in the
2765
				 * sockets because of the buffering done in the
2712
				 * TLS layer */
2766
				 * TLS layer */
2713
				if (!tcptls_session->ssl || need_poll) {
2767
				if (!tcptls_session->ssl || need_poll) {
2714
					need_poll = 0;
2768
					need_poll = 0;
2715
					after_poll = 1;
2769
					after_poll = 1;
2716
					res = ast_wait_for_input(tcptls_session->fd, timeout);
2770
					res = ast_wait_for_input(tcptls_session->fd, timeout);
2717
					if (res < 0) {
2771
					if (res < 0) {
2718
						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);
2719
						goto cleanup;
2773
						goto cleanup;
2720
					} else if (res == 0) {
2774
					} else if (res == 0) {
2721
						/* timeout */
2775
						/* timeout */
2722
						ast_debug(2, "SIP TCP server timed out\n");
2776
						ast_debug(2, "SIP TCP server timed out\n");
2723
						goto cleanup;
2777
						goto cleanup;
2724
					}
2778
					}
2725
				}
2779
				}
2726

    
   
2780

   
2727
				ao2_lock(tcptls_session);
2781
				ao2_lock(tcptls_session);
2728
				if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2782
				if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2729
					ao2_unlock(tcptls_session);
2783
					ao2_unlock(tcptls_session);
2730
					if (after_poll) {
2784
					if (after_poll) {
2731
						goto cleanup;
2785
						goto cleanup;
2732
					} else {
2786
					} else {
2733
						need_poll = 1;
2787
						need_poll = 1;
2734
						continue;
2788
						continue;
2735
					}
2789
					}
2736
				}
2790
				}
2737
				ao2_unlock(tcptls_session);
2791
				ao2_unlock(tcptls_session);
2738
				after_poll = 0;
2792
				after_poll = 0;
2739
				if (me->stop) {
2793
				if (me->stop) {
2740
					 goto cleanup;
2794
					 goto cleanup;
2741
				}
2795
				}
2742
				ast_str_append(&req.data, 0, "%s", buf);
2796
				ast_str_append(&req.data, 0, "%s", buf);
2743
			}
2797
			}
2744
			copy_request(&reqcpy, &req);
2798
			copy_request(&reqcpy, &req);
2745
			parse_request(&reqcpy);
2799
			parse_request(&reqcpy);
2746
			/* 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 */
2747
			if (sscanf(sip_get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
2801
			if (sscanf(sip_get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
2748
				while (cl > 0) {
2802
				while (cl > 0) {
2749
					size_t bytes_read;
2803
					size_t bytes_read;
2750
					if (!tcptls_session->client && !authenticated ) {
2804
					if (!tcptls_session->client && !authenticated ) {
2751
						if ((timeout = sip_check_authtimeout(start)) < 0) {
2805
						if ((timeout = sip_check_authtimeout(start)) < 0) {
2752
							goto cleanup;
2806
							goto cleanup;
2753
						}
2807
						}
2754

    
   
2808

   
2755
						if (timeout == 0) {
2809
						if (timeout == 0) {
2756
							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");
2757
							goto cleanup;
2811
							goto cleanup;
2758
						}
2812
						}
2759
					} else {
2813
					} else {
2760
						timeout = -1;
2814
						timeout = -1;
2761
					}
2815
					}
2762

    
   
2816

   
2763
					if (!tcptls_session->ssl || need_poll) {
2817
					if (!tcptls_session->ssl || need_poll) {
2764
						need_poll = 0;
2818
						need_poll = 0;
2765
						after_poll = 1;
2819
						after_poll = 1;
2766
						res = ast_wait_for_input(tcptls_session->fd, timeout);
2820
						res = ast_wait_for_input(tcptls_session->fd, timeout);
2767
						if (res < 0) {
2821
						if (res < 0) {
2768
							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);
2769
							goto cleanup;
2823
							goto cleanup;
2770
						} else if (res == 0) {
2824
						} else if (res == 0) {
2771
							/* timeout */
2825
							/* timeout */
2772
							ast_debug(2, "SIP TCP server timed out\n");
2826
							ast_debug(2, "SIP TCP server timed out\n");
2773
							goto cleanup;
2827
							goto cleanup;
2774
						}
2828
						}
2775
					}
2829
					}
2776

    
   
2830

   
2777
					ao2_lock(tcptls_session);
2831
					ao2_lock(tcptls_session);
2778
					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))) {
2779
						ao2_unlock(tcptls_session);
2833
						ao2_unlock(tcptls_session);
2780
						if (after_poll) {
2834
						if (after_poll) {
2781
							goto cleanup;
2835
							goto cleanup;
2782
						} else {
2836
						} else {
2783
							need_poll = 1;
2837
							need_poll = 1;
2784
							continue;
2838
							continue;
2785
						}
2839
						}
2786
					}
2840
					}
2787
					buf[bytes_read] = '\0';
2841
					buf[bytes_read] = '\0';
2788
					ao2_unlock(tcptls_session);
2842
					ao2_unlock(tcptls_session);
2789
					after_poll = 0;
2843
					after_poll = 0;
2790
					if (me->stop) {
2844
					if (me->stop) {
2791
						goto cleanup;
2845
						goto cleanup;
2792
					}
2846
					}
2793
					cl -= strlen(buf);
2847
					cl -= strlen(buf);
2794
					ast_str_append(&req.data, 0, "%s", buf);
2848
					ast_str_append(&req.data, 0, "%s", buf);
2795
				}
2849
				}
2796
			}
2850
			}
2797
			/*! \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
2798
					we receive is not the same - we should generate an error */
2852
					we receive is not the same - we should generate an error */
2799

    
   
2853

   
2800
			req.socket.tcptls_session = tcptls_session;
2854
			req.socket.tcptls_session = tcptls_session;

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

    
   
2858

   
2804
		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 */
2805
			enum sip_tcptls_alert alert;
2860
			enum sip_tcptls_alert alert;
2806
			struct tcptls_packet *packet;
2861
			struct tcptls_packet *packet;
2807

    
   
2862

   
2808
			fds[1].revents = 0;
2863
			fds[1].revents = 0;
2809

    
   
2864

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

    
   
2869

   
2815
			switch (alert) {
2870
			switch (alert) {
2816
			case TCPTLS_ALERT_STOP:
2871
			case TCPTLS_ALERT_STOP:
2817
				goto cleanup;
2872
				goto cleanup;
2818
			case TCPTLS_ALERT_DATA:
2873
			case TCPTLS_ALERT_DATA:
2819
				ao2_lock(me);
2874
				ao2_lock(me);
2820
				if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
2875
				if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
2821
					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");
2822
				}
2877
				}
2823
				ao2_unlock(me);
2878
				ao2_unlock(me);
2824

    
   
2879

   
2825
				if (packet) {
2880
				if (packet) {
2826
					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) {
2827
						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");
2828
					}
2883
					}
2829
					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");
2830
				}
2885
				}
2831
				break;
2886
				break;
2832
			default:
2887
			default:
2833
				ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
2888
				ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
2834
			}
2889
			}
2835
		}
2890
		}
2836
	}
2891
	}
2837

    
   
2892

   
2838
	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");
2839

    
   
2894

   
2840
cleanup:
2895
cleanup:
2841
	if (tcptls_session && !tcptls_session->client && !authenticated) {
2896
	if (tcptls_session && !tcptls_session->client && !authenticated) {
2842
		ast_atomic_fetchadd_int(&unauth_sessions, -1);
2897
		ast_atomic_fetchadd_int(&unauth_sessions, -1);
2843
	}
2898
	}
2844

    
   
2899

   
2845
	if (me) {
2900
	if (me) {
2846
		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");
2847
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2902
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2848
	}
2903
	}
2849
	deinit_req(&reqcpy);
2904
	deinit_req(&reqcpy);
2850
	deinit_req(&req);
2905
	deinit_req(&req);
2851

    
   
2906

   
2852
	/* 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 */
2853
	if (ca) {
2908
	if (ca) {
2854
		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");
2855
	}
2910
	}
2856

    
   
2911

   
2857
	if (tcptls_session) {
2912
	if (tcptls_session) {
2858
		ao2_lock(tcptls_session);
2913
		ao2_lock(tcptls_session);
2859
		ast_tcptls_close_session_file(tcptls_session);
2914
		ast_tcptls_close_session_file(tcptls_session);
2860
		tcptls_session->parent = NULL;
2915
		tcptls_session->parent = NULL;
2861
		ao2_unlock(tcptls_session);
2916
		ao2_unlock(tcptls_session);
2862

    
   
2917

   
2863
		ao2_ref(tcptls_session, -1);
2918
		ao2_ref(tcptls_session, -1);
2864
		tcptls_session = NULL;
2919
		tcptls_session = NULL;
2865
	}
2920
	}
2866
	return NULL;
2921
	return NULL;
2867
}
2922
}
2868

    
   
2923

   
2869
#ifdef REF_DEBUG
2924
#ifdef REF_DEBUG
2870
#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__)
2871
#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__)
2872
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)
2873
{
2928
{
2874
	if (peer)
2929
	if (peer)
2875
		__ao2_ref_debug(peer, 1, tag, file, line, func);
2930
		__ao2_ref_debug(peer, 1, tag, file, line, func);
2876
	else
2931
	else
2877
		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");
2878
	return peer;
2933
	return peer;
2879
}
2934
}
2880

    
   
2935

   
2881
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)
2882
{
2937
{
2883
	if (peer)
2938
	if (peer)
2884
		__ao2_ref_debug(peer, -1, tag, file, line, func);
2939
		__ao2_ref_debug(peer, -1, tag, file, line, func);
2885
	return NULL;
2940
	return NULL;
2886
}
2941
}
2887
#else
2942
#else
2888
/*!
2943
/*!
2889
 * helper functions to unreference various types of objects.
2944
 * helper functions to unreference various types of objects.
2890
 * 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
2891
 * destructor on each call, which removes the chance of errors.
2946
 * destructor on each call, which removes the chance of errors.
2892
 */
2947
 */
2893
void *sip_unref_peer(struct sip_peer *peer, char *tag)
2948
void *sip_unref_peer(struct sip_peer *peer, char *tag)
2894
{
2949
{
2895
	ao2_t_ref(peer, -1, tag);
2950
	ao2_t_ref(peer, -1, tag);
2896
	return NULL;
2951
	return NULL;
2897
}
2952
}
2898

    
   
2953

   
2899
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)
2900
{
2955
{
2901
	ao2_t_ref(peer, 1, tag);
2956
	ao2_t_ref(peer, 1, tag);
2902
	return peer;
2957
	return peer;
2903
}
2958
}
2904
#endif /* REF_DEBUG */
2959
#endif /* REF_DEBUG */
2905

    
   
2960

   
2906
static void peer_sched_cleanup(struct sip_peer *peer)
2961
static void peer_sched_cleanup(struct sip_peer *peer)
2907
{
2962
{
2908
	if (peer->pokeexpire != -1) {
2963
	if (peer->pokeexpire != -1) {
2909
		AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
2964
		AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
2910
				sip_unref_peer(peer, "removing poke peer ref"));
2965
				sip_unref_peer(peer, "removing poke peer ref"));
2911
	}
2966
	}
2912
	if (peer->expire != -1) {
2967
	if (peer->expire != -1) {
2913
		AST_SCHED_DEL_UNREF(sched, peer->expire,
2968
		AST_SCHED_DEL_UNREF(sched, peer->expire,
2914
				sip_unref_peer(peer, "remove register expire ref"));
2969
				sip_unref_peer(peer, "remove register expire ref"));
2915
	}
2970
	}
2916
	if (peer->keepalivesend != -1) {
2971
	if (peer->keepalivesend != -1) {
2917
		AST_SCHED_DEL_UNREF(sched, peer->keepalivesend,
2972
		AST_SCHED_DEL_UNREF(sched, peer->keepalivesend,
2918
				    sip_unref_peer(peer, "remove keepalive peer ref"));
2973
				    sip_unref_peer(peer, "remove keepalive peer ref"));
2919
	}
2974
	}
2920
}
2975
}
2921

    
   
2976

   
2922
typedef enum {
2977
typedef enum {
2923
	SIP_PEERS_MARKED,
2978
	SIP_PEERS_MARKED,
2924
	SIP_PEERS_ALL,
2979
	SIP_PEERS_ALL,
2925
} peer_unlink_flag_t;
2980
} peer_unlink_flag_t;
2926

    
   
2981

   
2927
/* 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
2928
   peers, depending on arg */
2983
   peers, depending on arg */
2929
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)
2930
{
2985
{
2931
	struct sip_peer *peer = peerobj;
2986
	struct sip_peer *peer = peerobj;
2932
	peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
2987
	peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
2933

    
   
2988

   
2934
	if (which == SIP_PEERS_ALL || peer->the_mark) {
2989
	if (which == SIP_PEERS_ALL || peer->the_mark) {
2935
		peer_sched_cleanup(peer);
2990
		peer_sched_cleanup(peer);
2936
		if (peer->dnsmgr) {
2991
		if (peer->dnsmgr) {
2937
			ast_dnsmgr_release(peer->dnsmgr);
2992
			ast_dnsmgr_release(peer->dnsmgr);
2938
			peer->dnsmgr = NULL;
2993
			peer->dnsmgr = NULL;
2939
			sip_unref_peer(peer, "Release peer from dnsmgr");
2994
			sip_unref_peer(peer, "Release peer from dnsmgr");
2940
		}
2995
		}
2941
		return CMP_MATCH;
2996
		return CMP_MATCH;
2942
	}
2997
	}
2943
	return 0;
2998
	return 0;
2944
}
2999
}
2945

    
   
3000

   
2946
static void unlink_peers_from_tables(peer_unlink_flag_t flag)
3001
static void unlink_peers_from_tables(peer_unlink_flag_t flag)
2947
{
3002
{
2948
	ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
3003
	ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
2949
		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");
2950
	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,
2951
		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");
2952
}
3007
}
2953

    
   
3008

   
2954
/* \brief Unlink all marked peers from ao2 containers */
3009
/* \brief Unlink all marked peers from ao2 containers */
2955
static void unlink_marked_peers_from_tables(void)
3010
static void unlink_marked_peers_from_tables(void)
2956
{
3011
{
2957
	unlink_peers_from_tables(SIP_PEERS_MARKED);
3012
	unlink_peers_from_tables(SIP_PEERS_MARKED);
2958
}
3013
}
2959

    
   
3014

   
2960
static void unlink_all_peers_from_tables(void)
3015
static void unlink_all_peers_from_tables(void)
2961
{
3016
{
2962
	unlink_peers_from_tables(SIP_PEERS_ALL);
3017
	unlink_peers_from_tables(SIP_PEERS_ALL);
2963
}
3018
}
2964

    
   
3019

   
2965
/* \brief Unlink single peer from all ao2 containers */
3020
/* \brief Unlink single peer from all ao2 containers */
2966
static void unlink_peer_from_tables(struct sip_peer *peer)
3021
static void unlink_peer_from_tables(struct sip_peer *peer)
2967
{
3022
{
2968
	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");
2969
	if (!ast_sockaddr_isnull(&peer->addr)) {
3024
	if (!ast_sockaddr_isnull(&peer->addr)) {
2970
		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");
2971
	}
3026
	}
2972
}
3027
}
2973

    
   
3028

   
2974
/*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
3029
/*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
2975
 *
3030
 *
2976
 * This function sets pvt's outboundproxy pointer to the one referenced
3031
 * This function sets pvt's outboundproxy pointer to the one referenced
2977
 * 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
2978
 * 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
2979
 * to maintain the proper refcounts.
3034
 * to maintain the proper refcounts.
2980
 *
3035
 *
2981
 * \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
2982
 * \param proxy The sip_proxy which we will point pvt towards.
3037
 * \param proxy The sip_proxy which we will point pvt towards.
2983
 * \return Returns void
3038
 * \return Returns void
2984
 */
3039
 */
2985
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)
2986
{
3041
{
2987
	struct sip_proxy *old_obproxy = pvt->outboundproxy;
3042
	struct sip_proxy *old_obproxy = pvt->outboundproxy;
2988
	/* The sip_cfg.outboundproxy is statically allocated, and so
3043
	/* The sip_cfg.outboundproxy is statically allocated, and so
2989
	 * we don't ever need to adjust refcounts for it
3044
	 * we don't ever need to adjust refcounts for it
2990
	 */
3045
	 */
2991
	if (proxy && proxy != &sip_cfg.outboundproxy) {
3046
	if (proxy && proxy != &sip_cfg.outboundproxy) {
2992
		ao2_ref(proxy, +1);
3047
		ao2_ref(proxy, +1);
2993
	}
3048
	}
2994
	pvt->outboundproxy = proxy;
3049
	pvt->outboundproxy = proxy;
2995
	if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
3050
	if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
2996
		ao2_ref(old_obproxy, -1);
3051
		ao2_ref(old_obproxy, -1);
2997
	}
3052
	}
2998
}
3053
}
2999

    
   
3054

   
3000
/*!
3055
/*!
3001
 * \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
3002
 * that it may be currently stored.
3057
 * that it may be currently stored.
3003
 *
3058
 *
3004
 * \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
3005
 * function does not release that reference.
3060
 * function does not release that reference.
3006
 */
3061
 */
3007
void dialog_unlink_all(struct sip_pvt *dialog)
3062
void dialog_unlink_all(struct sip_pvt *dialog)
3008
{
3063
{
3009
	struct sip_pkt *cp;
3064
	struct sip_pkt *cp;
3010
	struct ast_channel *owner;
3065
	struct ast_channel *owner;
3011

    
   
3066

   
3012
	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");
3013

    
   
3068

   
3014
	ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
3069
	ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
3015
	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");
3016
	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");
3017

    
   
3072

   
3018
	/* Unlink us from the owner (channel) if we have one */
3073
	/* Unlink us from the owner (channel) if we have one */
3019
	owner = sip_pvt_lock_full(dialog);
3074
	owner = sip_pvt_lock_full(dialog);
3020
	if (owner) {
3075
	if (owner) {
3021
		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));
3022
		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"));
3023
		ast_channel_unlock(owner);
3078
		ast_channel_unlock(owner);
3024
		ast_channel_unref(owner);
3079
		ast_channel_unref(owner);
3025
		dialog->owner = NULL;
3080
		dialog->owner = NULL;
3026
	}
3081
	}
3027
	sip_pvt_unlock(dialog);
3082
	sip_pvt_unlock(dialog);
3028

    
   
3083

   
3029
	if (dialog->registry) {
3084
	if (dialog->registry) {
3030
		if (dialog->registry->call == dialog) {
3085
		if (dialog->registry->call == dialog) {
3031
			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");
3032
		}
3087
		}
3033
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
3088
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
3034
	}
3089
	}
3035
	if (dialog->stateid != -1) {
3090
	if (dialog->stateid != -1) {
3036
		ast_extension_state_del(dialog->stateid, cb_extensionstate);
3091
		ast_extension_state_del(dialog->stateid, cb_extensionstate);
3037
		dialog->stateid = -1;
3092
		dialog->stateid = -1;
3038
	}
3093
	}
3039
	/* Remove link from peer to subscription of MWI */
3094
	/* Remove link from peer to subscription of MWI */
3040
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
3095
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
3041
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
3096
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
3042
	}
3097
	}
3043
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
3098
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
3044
		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");
3045
	}
3100
	}
3046

    
   
3101

   
3047
	/* remove all current packets in this dialog */
3102
	/* remove all current packets in this dialog */
3048
	while((cp = dialog->packets)) {
3103
	while((cp = dialog->packets)) {
3049
		dialog->packets = dialog->packets->next;
3104
		dialog->packets = dialog->packets->next;
3050
		AST_SCHED_DEL(sched, cp->retransid);
3105
		AST_SCHED_DEL(sched, cp->retransid);
3051
		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");
3052
		if (cp->data) {
3107
		if (cp->data) {
3053
			ast_free(cp->data);
3108
			ast_free(cp->data);
3054
		}
3109
		}
3055
		ast_free(cp);
3110
		ast_free(cp);
3056
	}
3111
	}
3057

    
   
3112

   
3058
	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"));
3059

    
   
3114

   
3060
	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"));
3061
	
3116
	
3062
	if (dialog->autokillid > -1) {
3117
	if (dialog->autokillid > -1) {
3063
		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"));
3064
	}
3119
	}
3065

    
   
3120

   
3066
	if (dialog->request_queue_sched_id > -1) {
3121
	if (dialog->request_queue_sched_id > -1) {
3067
		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"));
3068
	}
3123
	}
3069

    
   
3124

   
3070
	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"));
3071

    
   
3126

   
3072
	if (dialog->t38id > -1) {
3127
	if (dialog->t38id > -1) {
3073
		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"));
3074
	}
3129
	}
3075

    
   
3130

   
3076
	if (dialog->stimer) {
3131
	if (dialog->stimer) {
3077
		stop_session_timer(dialog);
3132
		stop_session_timer(dialog);
3078
	}
3133
	}
3079

    
   
3134

   
3080
	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");
3081
}
3136
}
3082

    
   
3137

   
3083
void *registry_unref(struct sip_registry *reg, char *tag)
3138
void *registry_unref(struct sip_registry *reg, char *tag)
3084
{
3139
{
3085
	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);
3086
	ASTOBJ_UNREF(reg, sip_registry_destroy);
3141
	ASTOBJ_UNREF(reg, sip_registry_destroy);
3087
	return NULL;
3142
	return NULL;
3088
}
3143
}
3089

    
   
3144

   
3090
/*! \brief Add object reference to SIP registry */
3145
/*! \brief Add object reference to SIP registry */
3091
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)
3092
{
3147
{
3093
	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);
3094
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
3149
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
3095
}
3150
}
3096

    
   
3151

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

    
   
3158

   
3104
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, ...)
3105
	__attribute__((format(printf, 2, 3)));
3160
	__attribute__((format(printf, 2, 3)));
3106

    
   
3161

   
3107

    
   
3162

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

    
   
3168

   
3114
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)
3115
{
3170
{
3116
	if (pvt->final_destruction_scheduled) {
3171
	if (pvt->final_destruction_scheduled) {
3117
		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. */
3118
	}
3173
	}
3119
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
3174
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
3120
	if (!pvt->needdestroy) {
3175
	if (!pvt->needdestroy) {
3121
		pvt->needdestroy = 1;
3176
		pvt->needdestroy = 1;
3122
		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");
3123
	}
3178
	}
3124
}
3179
}
3125

    
   
3180

   
3126
/*! \brief Initialize the initital request packet in the pvt structure.
3181
/*! \brief Initialize the initital request packet in the pvt structure.
3127
	This packet is used for creating replies and future requests in
3182
	This packet is used for creating replies and future requests in
3128
	a dialog */
3183
	a dialog */
3129
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)
3130
{
3185
{
3131
	if (p->initreq.headers) {
3186
	if (p->initreq.headers) {
3132
		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);
3133
	} else {
3188
	} else {
3134
		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);
3135
	}
3190
	}
3136
	/* Use this as the basis */
3191
	/* Use this as the basis */
3137
	copy_request(&p->initreq, req);
3192
	copy_request(&p->initreq, req);
3138
	parse_request(&p->initreq);
3193
	parse_request(&p->initreq);
3139
	if (req->debug) {
3194
	if (req->debug) {
3140
		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);
3141
	}
3196
	}
3142
}
3197
}
3143

    
   
3198

   
3144
/*! \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 */
3145
static void sip_alreadygone(struct sip_pvt *dialog)
3200
static void sip_alreadygone(struct sip_pvt *dialog)
3146
{
3201
{
3147
	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);
3148
	dialog->alreadygone = 1;
3203
	dialog->alreadygone = 1;
3149
}
3204
}
3150

    
   
3205

   
3151
/*! 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 */
3152
static int proxy_update(struct sip_proxy *proxy)
3207
static int proxy_update(struct sip_proxy *proxy)
3153
{
3208
{
3154
	/* if it's actually an IP address and not a name,
3209
	/* if it's actually an IP address and not a name,
3155
           there's no need for a managed lookup */
3210
           there's no need for a managed lookup */
3156
	if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
3211
	if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
3157
		/* 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 */
3158
		/* XXX Todo - if we have proxy port, don't do SRV */
3213
		/* XXX Todo - if we have proxy port, don't do SRV */
3159
		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 */
3160
		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) {
3161
				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);
3162
				return FALSE;
3217
				return FALSE;
3163
		}
3218
		}
3164

    
   
3219

   
3165
	}
3220
	}
3166

    
   
3221

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

    
   
3223

   
3169
	proxy->last_dnsupdate = time(NULL);
3224
	proxy->last_dnsupdate = time(NULL);
3170
	return TRUE;
3225
	return TRUE;
3171
}
3226
}
3172

    
   
3227

   
3173
/*! \brief converts ascii port to int representation. If no
3228
/*! \brief converts ascii port to int representation. If no
3174
 *  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
3175
 *  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.
3176
 */
3231
 */
3177
unsigned int port_str2int(const char *pt, unsigned int standard)
3232
unsigned int port_str2int(const char *pt, unsigned int standard)
3178
{
3233
{
3179
	int port = standard;
3234
	int port = standard;
3180
	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)) {
3181
		port = standard;
3236
		port = standard;
3182
	}
3237
	}
3183

    
   
3238

   
3184
	return port;
3239
	return port;
3185
}
3240
}
3186

    
   
3241

   
3187
/*! \brief Get default outbound proxy or global proxy */
3242
/*! \brief Get default outbound proxy or global proxy */
3188
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)
3189
{
3244
{
3190
	if (peer && peer->outboundproxy) {
3245
	if (peer && peer->outboundproxy) {
3191
		if (sipdebug) {
3246
		if (sipdebug) {
3192
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
3247
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
3193
		}
3248
		}
3194
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
3249
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
3195
		return peer->outboundproxy;
3250
		return peer->outboundproxy;
3196
	}
3251
	}
3197
	if (sip_cfg.outboundproxy.name[0]) {
3252
	if (sip_cfg.outboundproxy.name[0]) {
3198
		if (sipdebug) {
3253
		if (sipdebug) {
3199
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
3254
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
3200
		}
3255
		}
3201
		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);
3202
		return &sip_cfg.outboundproxy;
3257
		return &sip_cfg.outboundproxy;
3203
	}
3258
	}
3204
	if (sipdebug) {
3259
	if (sipdebug) {
3205
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
3260
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
3206
	}
3261
	}
3207
	return NULL;
3262
	return NULL;
3208
}
3263
}
3209

    
   
3264

   
3210
/*! \brief returns true if 'name' (with optional trailing whitespace)
3265
/*! \brief returns true if 'name' (with optional trailing whitespace)
3211
 * matches the sip method 'id'.
3266
 * matches the sip method 'id'.
3212
 * Strictly speaking, SIP methods are case SENSITIVE, but we do
3267
 * Strictly speaking, SIP methods are case SENSITIVE, but we do
3213
 * a case-insensitive comparison to be more tolerant.
3268
 * a case-insensitive comparison to be more tolerant.
3214
 * 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
3215
 */
3270
 */
3216
static int method_match(enum sipmethod id, const char *name)
3271
static int method_match(enum sipmethod id, const char *name)
3217
{
3272
{
3218
	int len = strlen(sip_methods[id].text);
3273
	int len = strlen(sip_methods[id].text);
3219
	int l_name = name ? strlen(name) : 0;
3274
	int l_name = name ? strlen(name) : 0;
3220
	/* 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 */
3221
	return (l_name >= len && name && name[len] < 33 &&
3276
	return (l_name >= len && name && name[len] < 33 &&
3222
		!strncasecmp(sip_methods[id].text, name, len));
3277
		!strncasecmp(sip_methods[id].text, name, len));
3223
}
3278
}
3224

    
   
3279

   
3225
/*! \brief  find_sip_method: Find SIP method from header */
3280
/*! \brief  find_sip_method: Find SIP method from header */
3226
static int find_sip_method(const char *msg)
3281
static int find_sip_method(const char *msg)
3227
{
3282
{
3228
	int i, res = 0;
3283
	int i, res = 0;
3229
	
3284
	
3230
	if (ast_strlen_zero(msg)) {
3285
	if (ast_strlen_zero(msg)) {
3231
		return 0;
3286
		return 0;
3232
	}
3287
	}
3233
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
3288
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
3234
		if (method_match(i, msg)) {
3289
		if (method_match(i, msg)) {
3235
			res = sip_methods[i].id;
3290
			res = sip_methods[i].id;
3236
		}
3291
		}
3237
	}
3292
	}
3238
	return res;
3293
	return res;
3239
}
3294
}
3240

    
   
3295

   
3241
/*! \brief See if we pass debug IP filter */
3296
/*! \brief See if we pass debug IP filter */
3242
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)
3243
{
3298
{
3244
	/* Can't debug if sipdebug is not enabled */
3299
	/* Can't debug if sipdebug is not enabled */
3245
	if (!sipdebug) {
3300
	if (!sipdebug) {
3246
		return 0;
3301
		return 0;
3247
	}
3302
	}
3248

    
   
3303

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

    
   
3308

   
3254
	/* 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
3255
	 * addresses, otherwise compare the address and port
3310
	 * addresses, otherwise compare the address and port
3256
	 */
3311
	 */
3257
	if (ast_sockaddr_port(&debugaddr)) {
3312
	if (ast_sockaddr_port(&debugaddr)) {
3258
		return !ast_sockaddr_cmp(&debugaddr, addr);
3313
		return !ast_sockaddr_cmp(&debugaddr, addr);
3259
	} else {
3314
	} else {
3260
		return !ast_sockaddr_cmp_addr(&debugaddr, addr);
3315
		return !ast_sockaddr_cmp_addr(&debugaddr, addr);
3261
	}
3316
	}
3262
}
3317
}
3263

    
   
3318

   
3264
/*! \brief The real destination address for a write */
3319
/*! \brief The real destination address for a write */
3265
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)
3266
{
3321
{
3267
	if (p->outboundproxy) {
3322
	if (p->outboundproxy) {
3268
		return &p->outboundproxy->ip;
3323
		return &p->outboundproxy->ip;
3269
	}
3324
	}
3270

    
   
3325

   
3271
	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;
3272
}
3327
}
3273

    
   
3328

   
3274
/*! \brief Display SIP nat mode */
3329
/*! \brief Display SIP nat mode */
3275
static const char *sip_nat_mode(const struct sip_pvt *p)
3330
static const char *sip_nat_mode(const struct sip_pvt *p)
3276
{
3331
{
3277
	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";
3278
}
3333
}
3279

    
   
3334

   
3280
/*! \brief Test PVT for debugging output */
3335
/*! \brief Test PVT for debugging output */
3281
static inline int sip_debug_test_pvt(struct sip_pvt *p)
3336
static inline int sip_debug_test_pvt(struct sip_pvt *p)
3282
{
3337
{
3283
	if (!sipdebug) {
3338
	if (!sipdebug) {
3284
		return 0;
3339
		return 0;
3285
	}
3340
	}
3286
	return sip_debug_test_addr(sip_real_dst(p));
3341
	return sip_debug_test_addr(sip_real_dst(p));
3287
}
3342
}
3288

    
   
3343

   
3289
/*! \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 */
3290
static int get_transport_str2enum(const char *transport)
3345
static int get_transport_str2enum(const char *transport)
3291
{
3346
{
3292
	int res = 0;
3347
	int res = 0;
3293

    
   
3348

   
3294
	if (ast_strlen_zero(transport)) {
3349
	if (ast_strlen_zero(transport)) {
3295
		return res;
3350
		return res;
3296
	}
3351
	}
3297

    
   
3352

   
3298
	if (!strcasecmp(transport, "udp")) {
3353
	if (!strcasecmp(transport, "udp")) {
3299
		res |= SIP_TRANSPORT_UDP;
3354
		res |= SIP_TRANSPORT_UDP;
3300
	}
3355
	}
3301
	if (!strcasecmp(transport, "tcp")) {
3356
	if (!strcasecmp(transport, "tcp")) {
3302
		res |= SIP_TRANSPORT_TCP;
3357
		res |= SIP_TRANSPORT_TCP;
3303
	}
3358
	}
3304
	if (!strcasecmp(transport, "tls")) {
3359
	if (!strcasecmp(transport, "tls")) {
3305
		res |= SIP_TRANSPORT_TLS;
3360
		res |= SIP_TRANSPORT_TLS;
3306
	}
3361
	}

    
   
3362
	if (!strcasecmp(transport, "ws")) {

    
   
3363
		res |= SIP_TRANSPORT_WS;

    
   
3364
	}

    
   
3365
	if (!strcasecmp(transport, "wss")) {

    
   
3366
		res |= SIP_TRANSPORT_WSS;

    
   
3367
	}
3307

    
   
3368

   
3308
	return res;
3369
	return res;
3309
}
3370
}
3310

    
   
3371

   
3311
/*! \brief Return configuration of transports for a device */
3372
/*! \brief Return configuration of transports for a device */
3312
static inline const char *get_transport_list(unsigned int transports) {
3373
static inline const char *get_transport_list(unsigned int transports)
3313
	switch (transports) {
3374
{
3314
		case SIP_TRANSPORT_UDP:
3375
	char *buf;
3315
			return "UDP";
3376

   
3316
		case SIP_TRANSPORT_TCP:
3377
	if (!transports) {
3317
			return "TCP";
3378
		return "UNKNOWN";
3318
		case SIP_TRANSPORT_TLS:
3379
	}
3319
			return "TLS";
3380

   
3320
		case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
3381
	if (!(buf = ast_threadstorage_get(&sip_transport_str_buf, SIP_TRANSPORT_STR_BUFSIZE))) {
3321
			return "TCP,UDP";
3382
		return "";
3322
		case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
3383
	}
3323
			return "TLS,UDP";
3384

   
3324
		case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
3385
	memset(buf, 0, SIP_TRANSPORT_STR_BUFSIZE);
3325
			return "TLS,TCP";
3386

   
3326
		default:
3387
	if (transports & SIP_TRANSPORT_UDP) {
3327
			return transports ?
3388
		strncat(buf, "UDP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3328
				"TLS,TCP,UDP" : "UNKNOWN";	
3389
	}

    
   
3390
	if (transports & SIP_TRANSPORT_TCP) {

    
   
3391
		strncat(buf, "TCP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3329
	}
3392
	}

    
   
3393
	if (transports & SIP_TRANSPORT_TLS) {

    
   
3394
		strncat(buf, "TLS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));

    
   
3395
	}

    
   
3396
	if (transports & SIP_TRANSPORT_WS) {

    
   
3397
		strncat(buf, "WS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));

    
   
3398
	}

    
   
3399
	if (transports & SIP_TRANSPORT_WSS) {

    
   
3400
		strncat(buf, "WSS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));

    
   
3401
	}

    
   
3402

   

    
   
3403
	/* Remove the trailing ',' if present */

    
   
3404
	if (strlen(buf)) {

    
   
3405
		buf[strlen(buf) - 1] = 0;

    
   
3406
	}

    
   
3407

   

    
   
3408
	return buf;
3330
}
3409
}
3331

    
   
3410

   
3332
/*! \brief Return transport as string */
3411
/*! \brief Return transport as string */
3333
const char *sip_get_transport(enum sip_transport t)
3412
const char *sip_get_transport(enum sip_transport t)
3334
{
3413
{
3335
	switch (t) {
3414
	switch (t) {
3336
	case SIP_TRANSPORT_UDP:
3415
	case SIP_TRANSPORT_UDP:
3337
		return "UDP";
3416
		return "UDP";
3338
	case SIP_TRANSPORT_TCP:
3417
	case SIP_TRANSPORT_TCP:
3339
		return "TCP";
3418
		return "TCP";
3340
	case SIP_TRANSPORT_TLS:
3419
	case SIP_TRANSPORT_TLS:
3341
		return "TLS";
3420
		return "TLS";

    
   
3421
	case SIP_TRANSPORT_WS:

    
   
3422
	case SIP_TRANSPORT_WSS:

    
   
3423
		return "WS";
3342
	}
3424
	}
3343

    
   
3425

   
3344
	return "UNKNOWN";
3426
	return "UNKNOWN";
3345
}
3427
}
3346

    
   
3428

   
3347
/*! \brief Return protocol string for srv dns query */
3429
/*! \brief Return protocol string for srv dns query */
3348
static inline const char *get_srv_protocol(enum sip_transport t)
3430
static inline const char *get_srv_protocol(enum sip_transport t)
3349
{
3431
{
3350
	switch (t) {
3432
	switch (t) {
3351
	case SIP_TRANSPORT_UDP:
3433
	case SIP_TRANSPORT_UDP:
3352
		return "udp";
3434
		return "udp";

    
   
3435
	case SIP_TRANSPORT_WS:

    
   
3436
		return "ws";
3353
	case SIP_TRANSPORT_TLS:
3437
	case SIP_TRANSPORT_TLS:
3354
	case SIP_TRANSPORT_TCP:
3438
	case SIP_TRANSPORT_TCP:
3355
		return "tcp";
3439
		return "tcp";

    
   
3440
	case SIP_TRANSPORT_WSS:

    
   
3441
		return "wss";
3356
	}
3442
	}
3357

    
   
3443

   
3358
	return "udp";
3444
	return "udp";
3359
}
3445
}
3360

    
   
3446

   
3361
/*! \brief Return service string for srv dns query */
3447
/*! \brief Return service string for srv dns query */
3362
static inline const char *get_srv_service(enum sip_transport t)
3448
static inline const char *get_srv_service(enum sip_transport t)
3363
{
3449
{
3364
	switch (t) {
3450
	switch (t) {
3365
	case SIP_TRANSPORT_TCP:
3451
	case SIP_TRANSPORT_TCP:
3366
	case SIP_TRANSPORT_UDP:
3452
	case SIP_TRANSPORT_UDP:

    
   
3453
	case SIP_TRANSPORT_WS:
3367
		return "sip";
3454
		return "sip";
3368
	case SIP_TRANSPORT_TLS:
3455
	case SIP_TRANSPORT_TLS:

    
   
3456
	case SIP_TRANSPORT_WSS:
3369
		return "sips";
3457
		return "sips";
3370
	}
3458
	}
3371
	return "sip";
3459
	return "sip";
3372
}
3460
}
3373

    
   
3461

   
3374
/*! \brief Return transport of dialog.
3462
/*! \brief Return transport of dialog.
3375
	\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
3376
	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
3377
	"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.
3378
	\todo Fix this function to work correctly
3466
	\todo Fix this function to work correctly
3379
*/
3467
*/
3380
static inline const char *get_transport_pvt(struct sip_pvt *p)
3468
static inline const char *get_transport_pvt(struct sip_pvt *p)
3381
{
3469
{
3382
	if (p->outboundproxy && p->outboundproxy->transport) {
3470
	if (p->outboundproxy && p->outboundproxy->transport) {
3383
		set_socket_transport(&p->socket, p->outboundproxy->transport);
3471
		set_socket_transport(&p->socket, p->outboundproxy->transport);
3384
	}
3472
	}
3385

    
   
3473

   
3386
	return sip_get_transport(p->socket.type);
3474
	return sip_get_transport(p->socket.type);
3387
}
3475
}
3388

    
   
3476

   
3389
/*!
3477
/*!
3390
 * \internal
3478
 * \internal
3391
 * \brief Transmit SIP message
3479
 * \brief Transmit SIP message
3392
 *
3480
 *
3393
 * \details
3481
 * \details
3394
 * 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)
3395
 * \note
3483
 * \note
3396
 * 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
3397
 *
3485
 *
3398
 * \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.
3399
 */
3487
 */
3400
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)
3401
{
3489
{
3402
	int res = 0;
3490
	int res = 0;
3403
	const struct ast_sockaddr *dst = sip_real_dst(p);
3491
	const struct ast_sockaddr *dst = sip_real_dst(p);
3404

    
   
3492

   
3405
	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));
3406

    
   
3494

   
3407
	if (sip_prepare_socket(p) < 0) {
3495
	if (sip_prepare_socket(p) < 0) {
3408
		return XMIT_ERROR;
3496
		return XMIT_ERROR;
3409
	}
3497
	}
3410

    
   
3498

   
3411
	if (p->socket.type == SIP_TRANSPORT_UDP) {
3499
	if (p->socket.type == SIP_TRANSPORT_UDP) {
3412
		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);
3413
	} else if (p->socket.tcptls_session) {
3501
	} else if (p->socket.tcptls_session) {
3414
		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) {

    
   
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 */

    
   
3506
			res = ast_str_strlen(data);

    
   
3507
		}
3415
	} else {
3508
	} else {
3416
		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");
3417
		return XMIT_ERROR;
3510
		return XMIT_ERROR;
3418
	}
3511
	}
3419

    
   
3512

   
3420
	if (res == -1) {
3513
	if (res == -1) {
3421
		switch (errno) {
3514
		switch (errno) {
3422
		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 */
3423
		case EHOSTUNREACH:	/* Host can't be reached */
3516
		case EHOSTUNREACH:	/* Host can't be reached */
3424
		case ENETDOWN:		/* Interface down */
3517
		case ENETDOWN:		/* Interface down */
3425
		case ENETUNREACH:	/* Network failure */
3518
		case ENETUNREACH:	/* Network failure */
3426
		case ECONNREFUSED:      /* ICMP port unreachable */
3519
		case ECONNREFUSED:      /* ICMP port unreachable */
3427
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */
3520
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */
3428
		}
3521
		}
3429
	}
3522
	}
3430
	if (res != ast_str_strlen(data)) {
3523
	if (res != ast_str_strlen(data)) {
3431
		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));
3432
	}
3525
	}
3433

    
   
3526

   
3434
	return res;
3527
	return res;
3435
}
3528
}
3436

    
   
3529

   
3437
/*! \brief Build a Via header for a request */
3530
/*! \brief Build a Via header for a request */
3438
static void build_via(struct sip_pvt *p)
3531
static void build_via(struct sip_pvt *p)
3439
{
3532
{
3440
	/* Work around buggy UNIDEN UIP200 firmware */
3533
	/* Work around buggy UNIDEN UIP200 firmware */
3441
	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" : "";
3442

    
   
3535

   
3443
	/* 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 */
3444
	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",
3445
		 get_transport_pvt(p),
3538
		 get_transport_pvt(p),
3446
		 ast_sockaddr_stringify_remote(&p->ourip),
3539
		 ast_sockaddr_stringify_remote(&p->ourip),
3447
		 (int) p->branch, rport);
3540
		 (int) p->branch, rport);
3448
}
3541
}
3449

    
   
3542

   
3450
/*! \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?
3451
 *
3544
 *
3452
 * 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
3453
 * 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
3454
 * externaddr or can get away with our internal bindaddr
3547
 * externaddr or can get away with our internal bindaddr
3455
 * 'us' is always overwritten.
3548
 * 'us' is always overwritten.
3456
 */
3549
 */
3457
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)
3458
{
3551
{
3459
	struct ast_sockaddr theirs;
3552
	struct ast_sockaddr theirs;
3460

    
   
3553

   
3461
	/* 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
3462
	 * reachable IP address and port. This is done if:
3555
	 * reachable IP address and port. This is done if:
3463
	 * 1. we have a localaddr list (containing 'internal' addresses marked
3556
	 * 1. we have a localaddr list (containing 'internal' addresses marked
3464
	 *    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,
3465
	 *    and AST_SENSE_ALLOW on 'external' ones);
3558
	 *    and AST_SENSE_ALLOW on 'external' ones);
3466
	 * 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
3467
	 *    externally visible address;
3560
	 *    externally visible address;
3468
	 * 3. the remote address, 'them', is external;
3561
	 * 3. the remote address, 'them', is external;
3469
	 * 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
3470
	 *    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.
3471
	 *    This fourth condition is checked later.
3564
	 *    This fourth condition is checked later.
3472
	 */
3565
	 */
3473
	int want_remap = 0;
3566
	int want_remap = 0;
3474

    
   
3567

   
3475
	ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
3568
	ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
3476
	/* 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' */
3477
	ast_ouraddrfor(them, us);
3570
	ast_ouraddrfor(them, us);
3478
	ast_sockaddr_copy(&theirs, them);
3571
	ast_sockaddr_copy(&theirs, them);
3479

    
   
3572

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

    
   
3584

   
3492
	if (want_remap &&
3585
	if (want_remap &&
3493
	    (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
3586
	    (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
3494
		/* 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 */
3495
		if (externexpire && time(NULL) >= externexpire) {
3588
		if (externexpire && time(NULL) >= externexpire) {
3496
			if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
3589
			if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
3497
				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);
3498
			}
3591
			}
3499
			externexpire = time(NULL) + externrefresh;
3592
			externexpire = time(NULL) + externrefresh;
3500
		}
3593
		}
3501
		if (!ast_sockaddr_isnull(&externaddr)) {
3594
		if (!ast_sockaddr_isnull(&externaddr)) {
3502
			ast_sockaddr_copy(us, &externaddr);
3595
			ast_sockaddr_copy(us, &externaddr);
3503
			switch (p->socket.type) {
3596
			switch (p->socket.type) {
3504
			case SIP_TRANSPORT_TCP:
3597
			case SIP_TRANSPORT_TCP:
3505
				if (!externtcpport && ast_sockaddr_port(&externaddr)) {
3598
				if (!externtcpport && ast_sockaddr_port(&externaddr)) {
3506
					/* for consistency, default to the externaddr port */
3599
					/* for consistency, default to the externaddr port */
3507
					externtcpport = ast_sockaddr_port(&externaddr);
3600
					externtcpport = ast_sockaddr_port(&externaddr);
3508
				}
3601
				}
3509
				ast_sockaddr_set_port(us, externtcpport);
3602
				ast_sockaddr_set_port(us, externtcpport);
3510
				break;
3603
				break;
3511
			case SIP_TRANSPORT_TLS:
3604
			case SIP_TRANSPORT_TLS:
3512
				ast_sockaddr_set_port(us, externtlsport);
3605
				ast_sockaddr_set_port(us, externtlsport);
3513
				break;
3606
				break;
3514
			case SIP_TRANSPORT_UDP:
3607
			case SIP_TRANSPORT_UDP:
3515
				if (!ast_sockaddr_port(&externaddr)) {
3608
				if (!ast_sockaddr_port(&externaddr)) {
3516
					ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3609
					ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3517
				}
3610
				}
3518
				break;
3611
				break;
3519
			default:
3612
			default:
3520
				break;
3613
				break;
3521
			}
3614
			}
3522
		}
3615
		}
3523
		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",
3524
			  ast_sockaddr_stringify(them));
3617
			  ast_sockaddr_stringify(them));
3525
	} else {
3618
	} else {
3526
		/* 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. */
3527
		switch (p->socket.type) {
3620
		switch (p->socket.type) {
3528
		case SIP_TRANSPORT_TCP:
3621
		case SIP_TRANSPORT_TCP:
3529
			if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
3622
			if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
3530
				ast_sockaddr_copy(us,
3623
				ast_sockaddr_copy(us,
3531
						  &sip_tcp_desc.local_address);
3624
						  &sip_tcp_desc.local_address);
3532
			} else {
3625
			} else {
3533
				ast_sockaddr_set_port(us,
3626
				ast_sockaddr_set_port(us,
3534
						      ast_sockaddr_port(&sip_tcp_desc.local_address));
3627
						      ast_sockaddr_port(&sip_tcp_desc.local_address));
3535
			}
3628
			}
3536
			break;
3629
			break;
3537
		case SIP_TRANSPORT_TLS:
3630
		case SIP_TRANSPORT_TLS:
3538
			if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
3631
			if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
3539
				ast_sockaddr_copy(us,
3632
				ast_sockaddr_copy(us,
3540
						  &sip_tls_desc.local_address);
3633
						  &sip_tls_desc.local_address);
3541
			} else {
3634
			} else {
3542
				ast_sockaddr_set_port(us,
3635
				ast_sockaddr_set_port(us,
3543
						      ast_sockaddr_port(&sip_tls_desc.local_address));
3636
						      ast_sockaddr_port(&sip_tls_desc.local_address));
3544
			}
3637
			}
3545
			break;
3638
			break;
3546
		case SIP_TRANSPORT_UDP:
3639
		case SIP_TRANSPORT_UDP:
3547
			/* fall through on purpose */
3640
			/* fall through on purpose */
3548
		default:
3641
		default:
3549
			if (!ast_sockaddr_is_any(&bindaddr)) {
3642
			if (!ast_sockaddr_is_any(&bindaddr)) {
3550
				ast_sockaddr_copy(us, &bindaddr);
3643
				ast_sockaddr_copy(us, &bindaddr);
3551
			}
3644
			}
3552
			if (!ast_sockaddr_port(us)) {
3645
			if (!ast_sockaddr_port(us)) {
3553
				ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3646
				ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3554
			}
3647
			}
3555
		}
3648
		}
3556
	}
3649
	}
3557
	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));
3558
}
3651
}
3559

    
   
3652

   
3560
/*! \brief Append to SIP dialog history with arg list  */
3653
/*! \brief Append to SIP dialog history with arg list  */
3561
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)
3562
{
3655
{
3563
	char buf[80], *c = buf; /* max history length */
3656
	char buf[80], *c = buf; /* max history length */
3564
	struct sip_history *hist;
3657
	struct sip_history *hist;
3565
	int l;
3658
	int l;
3566

    
   
3659

   
3567
	vsnprintf(buf, sizeof(buf), fmt, ap);
3660
	vsnprintf(buf, sizeof(buf), fmt, ap);
3568
	strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
3661
	strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
3569
	l = strlen(buf) + 1;
3662
	l = strlen(buf) + 1;
3570
	if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
3663
	if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
3571
		return;
3664
		return;
3572
	}
3665
	}
3573
	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
3666
	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
3574
		ast_free(hist);
3667
		ast_free(hist);
3575
		return;
3668
		return;
3576
	}
3669
	}
3577
	memcpy(hist->event, buf, l);
3670
	memcpy(hist->event, buf, l);
3578
	if (p->history_entries == MAX_HISTORY_ENTRIES) {
3671
	if (p->history_entries == MAX_HISTORY_ENTRIES) {
3579
		struct sip_history *oldest;
3672
		struct sip_history *oldest;
3580
		oldest = AST_LIST_REMOVE_HEAD(p->history, list);
3673
		oldest = AST_LIST_REMOVE_HEAD(p->history, list);
3581
		p->history_entries--;
3674
		p->history_entries--;
3582
		ast_free(oldest);
3675
		ast_free(oldest);
3583
	}
3676
	}
3584
	AST_LIST_INSERT_TAIL(p->history, hist, list);
3677
	AST_LIST_INSERT_TAIL(p->history, hist, list);
3585
	p->history_entries++;
3678
	p->history_entries++;
3586
}
3679
}
3587

    
   
3680

   
3588
/*! \brief Append to SIP dialog history with arg list  */
3681
/*! \brief Append to SIP dialog history with arg list  */
3589
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, ...)
3590
{
3683
{
3591
	va_list ap;
3684
	va_list ap;
3592

    
   
3685

   
3593
	if (!p) {
3686
	if (!p) {
3594
		return;
3687
		return;
3595
	}
3688
	}
3596

    
   
3689

   
3597
	if (!p->do_history && !recordhistory && !dumphistory) {
3690
	if (!p->do_history && !recordhistory && !dumphistory) {
3598
		return;
3691
		return;
3599
	}
3692
	}
3600

    
   
3693

   
3601
	va_start(ap, fmt);
3694
	va_start(ap, fmt);
3602
	append_history_va(p, fmt, ap);
3695
	append_history_va(p, fmt, ap);
3603
	va_end(ap);
3696
	va_end(ap);
3604

    
   
3697

   
3605
	return;
3698
	return;
3606
}
3699
}
3607

    
   
3700

   
3608
/*! \brief Retransmit SIP message if no answer (Called from scheduler) */
3701
/*! \brief Retransmit SIP message if no answer (Called from scheduler) */
3609
static int retrans_pkt(const void *data)
3702
static int retrans_pkt(const void *data)
3610
{
3703
{
3611
	struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
3704
	struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
3612
	int reschedule = DEFAULT_RETRANS;
3705
	int reschedule = DEFAULT_RETRANS;
3613
	int xmitres = 0;
3706
	int xmitres = 0;
3614
	/* how many ms until retrans timeout is reached */
3707
	/* how many ms until retrans timeout is reached */
3615
	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);
3616

    
   
3709

   
3617
	/* 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
3618
	 * 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
3619
	 * 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. */
3620
	if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
3713
	if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
3621
		pkt->retrans_stop = 1;
3714
		pkt->retrans_stop = 1;
3622
	}
3715
	}
3623

    
   
3716

   
3624
	/* Lock channel PVT */
3717
	/* Lock channel PVT */
3625
	sip_pvt_lock(pkt->owner);
3718
	sip_pvt_lock(pkt->owner);
3626

    
   
3719

   
3627
	if (!pkt->retrans_stop) {
3720
	if (!pkt->retrans_stop) {
3628
		pkt->retrans++;
3721
		pkt->retrans++;
3629
		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 */
3630
			if (sipdebug) {
3723
			if (sipdebug) {
3631
				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",
3632
					pkt->retransid,
3725
					pkt->retransid,
3633
					sip_methods[pkt->method].text,
3726
					sip_methods[pkt->method].text,
3634
					pkt->method);
3727
					pkt->method);
3635
			}
3728
			}
3636
		} else {
3729
		} else {
3637
			int siptimer_a;
3730
			int siptimer_a;
3638

    
   
3731

   
3639
			if (sipdebug) {
3732
			if (sipdebug) {
3640
				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",
3641
					pkt->retransid,
3734
					pkt->retransid,
3642
					pkt->retrans,
3735
					pkt->retrans,
3643
					sip_methods[pkt->method].text,
3736
					sip_methods[pkt->method].text,
3644
					pkt->method);
3737
					pkt->method);
3645
			}
3738
			}
3646
			if (!pkt->timer_a) {
3739
			if (!pkt->timer_a) {
3647
				pkt->timer_a = 2 ;
3740
				pkt->timer_a = 2 ;
3648
			} else {
3741
			} else {
3649
				pkt->timer_a = 2 * pkt->timer_a;
3742
				pkt->timer_a = 2 * pkt->timer_a;
3650
			}
3743
			}
3651

    
   
3744

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

    
   
3750

   
3658
			/* Reschedule re-transmit */
3751
			/* Reschedule re-transmit */
3659
			reschedule = siptimer_a;
3752
			reschedule = siptimer_a;
3660
			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",
3661
				pkt->retrans + 1,
3754
				pkt->retrans + 1,
3662
				siptimer_a,
3755
				siptimer_a,
3663
				pkt->timer_t1,
3756
				pkt->timer_t1,
3664
				pkt->retransid);
3757
				pkt->retransid);
3665
		}
3758
		}
3666

    
   
3759

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

    
   
3767

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

    
   
3770

   
3678
		/* 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,
3679
		 * 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
3680
		 * 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
3681
		 * 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
3682
		 * call to this function by the scheduler. */
3775
		 * call to this function by the scheduler. */
3683
		if (xmitres != XMIT_ERROR) {
3776
		if (xmitres != XMIT_ERROR) {
3684
			if (reschedule >= diff) {
3777
			if (reschedule >= diff) {
3685
				pkt->retrans_stop = 1;
3778
				pkt->retrans_stop = 1;
3686
				reschedule = diff;
3779
				reschedule = diff;
3687
			}
3780
			}
3688
			sip_pvt_unlock(pkt->owner);
3781
			sip_pvt_unlock(pkt->owner);
3689
			return  reschedule;
3782
			return  reschedule;
3690
		}
3783
		}
3691
	}
3784
	}
3692

    
   
3785

   
3693
	/* At this point, either the packet's retransmission timed out, or there was a
3786
	/* At this point, either the packet's retransmission timed out, or there was a
3694
	 * transmission error, either way destroy the scheduler item and this packet. */
3787
	 * transmission error, either way destroy the scheduler item and this packet. */
3695

    
   
3788

   
3696
	pkt->retransid = -1; /* Kill this scheduler item */
3789
	pkt->retransid = -1; /* Kill this scheduler item */
3697

    
   
3790

   
3698
	if (pkt->method != SIP_OPTIONS && xmitres == 0) {
3791
	if (pkt->method != SIP_OPTIONS && xmitres == 0) {
3699
		if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
3792
		if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we'