Review Board 1.7.16


fix Deadlock with attended transfers of SIP calls

Review Request #1126 - Created Feb. 23, 2011 and submitted

Alec Davis
trunk
18468, 18491, 18734, 18837
Reviewers
asterisk-dev
Asterisk
in 1.8.2.3 and prior to trunk r306216, when the REFER transfer is complete then a deadlock occurs.

Reason being sip_set_rtp_peer locks pvt, then pbx_builtin_getvar_helper tries to lock chan
Violating locking order.
 
=== Thread ID: -1292625008 (do_monitor started at [24470] chan_sip.c restart_monitor())
=== ---> Lock #0 (chan_sip.c): MUTEX 23964 handle_request_do &netlock 0xb6796e80 (1)
=== ---> Lock #1 (channel.c): MUTEX 6211 ast_do_masquerade channels 0x8d4e0c8 (1)
=== ---> Lock #2 (channel.c): MUTEX 6214 ast_do_masquerade original 0xbd98f48 (1)
=== ---> Lock #3 (channel.c): MUTEX 6234 ast_do_masquerade clonechan 0xb24bf7d0 (1)
=== ---> Waiting for Lock #4 (chan_sip.c): MUTEX 6164 sip_fixup p 0xb24bab10 (1)
=== --- ---> Locked Here: chan_sip.c line 27632 (sip_set_rtp_peer)

=== -------------------------------------------------------------------
===
=== Thread ID: -1315861616 (pbx_thread started at [ 5035] pbx.c ast_pbx_start())
=== ---> Lock #0 (chan_sip.c): MUTEX 27632 sip_set_rtp_peer p 0xb24bab10 (1)
=== ---> Waiting for Lock #1 (pbx.c): MUTEX 9467 pbx_builtin_getvar_helper chan 0xb24bf7d0 (1)
=== --- ---> Locked Here: channel.c line 6234 (ast_do_masquerade)

multiple other bug reports reveal the sip_set_rtp_peer pvt locking issue.

Solution:
  inc pvt refcount to prevent the possibility of it disappearing while unlocked.
  unlock the pvt
    call transmit_reinvite_with_sdp (which finishes up invoking pbx_builtin_getvar_helper)
  lock the pvt
  dec pvt refcount

Applies to 1.8.2.3 and trunk. Both verified deadlocks.
Presumably 1.8 branch

r306216 tries to solve it, but causes more channel locking issues 
see https://issues.asterisk.org/view.php?id=18837#132337
Testing: trunk

3 SIP phones.

A calls B, and B answers on line 1.
B puts A on hold by selecting line2.
B calls C, and C answers.
B initiates transfer of line1 to line2, phone uses REFER.

Changes between revision 2 and 3

1 2 3
1 2 3

  1. trunk/channels/chan_sip.c: Loading...
trunk/channels/chan_sip.c
Diff Revision 2 Diff Revision 3
1
/*
1
/*
2
 * Asterisk -- An open source telephony toolkit.
2
 * Asterisk -- An open source telephony toolkit.
3
 *
3
 *
4
 * Copyright (C) 1999 - 2006, Digium, Inc.
4
 * Copyright (C) 1999 - 2006, 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>res_crypto</use>
165
	<use>res_crypto</use>
166
	<depend>chan_local</depend>
166
	<depend>chan_local</depend>
167
 ***/
167
 ***/
168

    
   
168

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

    
   
170

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

    
   
177

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

    
   
185

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

    
   
188

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

    
   
206

   
207
*/
207
*/
208

    
   
208

   
209
#include "asterisk.h"
209
#include "asterisk.h"
210

    
   
210

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

    
   
212

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

    
   
217

   
218
#include "asterisk/network.h"
218
#include "asterisk/network.h"
219
#include "asterisk/paths.h"	/* need ast_config_AST_SYSTEM_NAME */
219
#include "asterisk/paths.h"	/* need ast_config_AST_SYSTEM_NAME */
220
/*
220
/*
221
   Uncomment the define below,  if you are having refcount related memory leaks.
221
   Uncomment the define below,  if you are having refcount related memory leaks.
222
   With this uncommented, this module will generate a file, /tmp/refs, which contains
222
   With this uncommented, this module will generate a file, /tmp/refs, which contains
223
   a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
223
   a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
224
   be modified to ao2_t_* calls, and include a tag describing what is happening with
224
   be modified to ao2_t_* calls, and include a tag describing what is happening with
225
   enough detail, to make pairing up a reference count increment with its corresponding decrement.
225
   enough detail, to make pairing up a reference count increment with its corresponding decrement.
226
   The refcounter program in utils/ can be invaluable in highlighting objects that are not
226
   The refcounter program in utils/ can be invaluable in highlighting objects that are not
227
   balanced, along with the complete history for that object.
227
   balanced, along with the complete history for that object.
228
   In normal operation, the macros defined will throw away the tags, so they do not
228
   In normal operation, the macros defined will throw away the tags, so they do not
229
   affect the speed of the program at all. They can be considered to be documentation.
229
   affect the speed of the program at all. They can be considered to be documentation.
230
*/
230
*/
231
/* #define  REF_DEBUG 1 */
231
/* #define  REF_DEBUG 1 */
232
#include "asterisk/lock.h"
232
#include "asterisk/lock.h"
233
#include "asterisk/config.h"
233
#include "asterisk/config.h"
234
#include "asterisk/module.h"
234
#include "asterisk/module.h"
235
#include "asterisk/pbx.h"
235
#include "asterisk/pbx.h"
236
#include "asterisk/sched.h"
236
#include "asterisk/sched.h"
237
#include "asterisk/io.h"
237
#include "asterisk/io.h"
238
#include "asterisk/rtp_engine.h"
238
#include "asterisk/rtp_engine.h"
239
#include "asterisk/udptl.h"
239
#include "asterisk/udptl.h"
240
#include "asterisk/acl.h"
240
#include "asterisk/acl.h"
241
#include "asterisk/manager.h"
241
#include "asterisk/manager.h"
242
#include "asterisk/callerid.h"
242
#include "asterisk/callerid.h"
243
#include "asterisk/cli.h"
243
#include "asterisk/cli.h"
244
#include "asterisk/musiconhold.h"
244
#include "asterisk/musiconhold.h"
245
#include "asterisk/dsp.h"
245
#include "asterisk/dsp.h"
246
#include "asterisk/features.h"
246
#include "asterisk/features.h"
247
#include "asterisk/srv.h"
247
#include "asterisk/srv.h"
248
#include "asterisk/astdb.h"
248
#include "asterisk/astdb.h"
249
#include "asterisk/causes.h"
249
#include "asterisk/causes.h"
250
#include "asterisk/utils.h"
250
#include "asterisk/utils.h"
251
#include "asterisk/file.h"
251
#include "asterisk/file.h"
252
#include "asterisk/astobj2.h"
252
#include "asterisk/astobj2.h"
253
#include "asterisk/dnsmgr.h"
253
#include "asterisk/dnsmgr.h"
254
#include "asterisk/devicestate.h"
254
#include "asterisk/devicestate.h"
255
#include "asterisk/monitor.h"
255
#include "asterisk/monitor.h"
256
#include "asterisk/netsock2.h"
256
#include "asterisk/netsock2.h"
257
#include "asterisk/localtime.h"
257
#include "asterisk/localtime.h"
258
#include "asterisk/abstract_jb.h"
258
#include "asterisk/abstract_jb.h"
259
#include "asterisk/threadstorage.h"
259
#include "asterisk/threadstorage.h"
260
#include "asterisk/translate.h"
260
#include "asterisk/translate.h"
261
#include "asterisk/ast_version.h"
261
#include "asterisk/ast_version.h"
262
#include "asterisk/event.h"
262
#include "asterisk/event.h"
263
#include "asterisk/cel.h"
263
#include "asterisk/cel.h"
264
#include "asterisk/data.h"
264
#include "asterisk/data.h"
265
#include "asterisk/aoc.h"
265
#include "asterisk/aoc.h"
266
#include "sip/include/sip.h"
266
#include "sip/include/sip.h"
267
#include "sip/include/globals.h"
267
#include "sip/include/globals.h"
268
#include "sip/include/config_parser.h"
268
#include "sip/include/config_parser.h"
269
#include "sip/include/reqresp_parser.h"
269
#include "sip/include/reqresp_parser.h"
270
#include "sip/include/sip_utils.h"
270
#include "sip/include/sip_utils.h"
271
#include "sip/include/srtp.h"
271
#include "sip/include/srtp.h"
272
#include "sip/include/sdp_crypto.h"
272
#include "sip/include/sdp_crypto.h"
273
#include "asterisk/ccss.h"
273
#include "asterisk/ccss.h"
274
#include "asterisk/xml.h"
274
#include "asterisk/xml.h"
275
#include "sip/include/dialog.h"
275
#include "sip/include/dialog.h"
276
#include "sip/include/dialplan_functions.h"
276
#include "sip/include/dialplan_functions.h"
277

    
   
277

   
278

    
   
278

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

    
   
556

   
557
static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
557
static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
558
static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
558
static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
559
static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
559
static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
560
static int mwi_expiry = DEFAULT_MWI_EXPIRY;
560
static int mwi_expiry = DEFAULT_MWI_EXPIRY;
561

    
   
561

   
562
/*! \brief Global jitterbuffer configuration - by default, jb is disabled */
562
/*! \brief Global jitterbuffer configuration - by default, jb is disabled */
563
static struct ast_jb_conf default_jbconf =
563
static struct ast_jb_conf default_jbconf =
564
{
564
{
565
	.flags = 0,
565
	.flags = 0,
566
	.max_size = -1,
566
	.max_size = -1,
567
	.resync_threshold = -1,
567
	.resync_threshold = -1,
568
	.impl = "",
568
	.impl = "",
569
	.target_extra = -1,
569
	.target_extra = -1,
570
};
570
};
571
static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
571
static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
572

    
   
572

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

    
   
575

   
576
/*! \brief Readable descriptions of device states.
576
/*! \brief Readable descriptions of device states.
577
 *  \note Should be aligned to above table as index */
577
 *  \note Should be aligned to above table as index */
578
static const struct invstate2stringtable {
578
static const struct invstate2stringtable {
579
	const enum invitestates state;
579
	const enum invitestates state;
580
	const char *desc;
580
	const char *desc;
581
} invitestate2string[] = {
581
} invitestate2string[] = {
582
	{INV_NONE,              "None"  },
582
	{INV_NONE,              "None"  },
583
	{INV_CALLING,           "Calling (Trying)"},
583
	{INV_CALLING,           "Calling (Trying)"},
584
	{INV_PROCEEDING,        "Proceeding "},
584
	{INV_PROCEEDING,        "Proceeding "},
585
	{INV_EARLY_MEDIA,       "Early media"},
585
	{INV_EARLY_MEDIA,       "Early media"},
586
	{INV_COMPLETED,         "Completed (done)"},
586
	{INV_COMPLETED,         "Completed (done)"},
587
	{INV_CONFIRMED,         "Confirmed (up)"},
587
	{INV_CONFIRMED,         "Confirmed (up)"},
588
	{INV_TERMINATED,        "Done"},
588
	{INV_TERMINATED,        "Done"},
589
	{INV_CANCELLED,         "Cancelled"}
589
	{INV_CANCELLED,         "Cancelled"}
590
};
590
};
591

    
   
591

   
592
/*! \brief Subscription types that we support. We support
592
/*! \brief Subscription types that we support. We support
593
 * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
593
 * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
594
 * - SIMPLE presence used for device status
594
 * - SIMPLE presence used for device status
595
 * - Voicemail notification subscriptions
595
 * - Voicemail notification subscriptions
596
 */
596
 */
597
static const struct cfsubscription_types {
597
static const struct cfsubscription_types {
598
	enum subscriptiontype type;
598
	enum subscriptiontype type;
599
	const char * const event;
599
	const char * const event;
600
	const char * const mediatype;
600
	const char * const mediatype;
601
	const char * const text;
601
	const char * const text;
602
} subscription_types[] = {
602
} subscription_types[] = {
603
	{ NONE,		   "-",        "unknown",	             "unknown" },
603
	{ NONE,		   "-",        "unknown",	             "unknown" },
604
	/* RFC 4235: SIP Dialog event package */
604
	/* RFC 4235: SIP Dialog event package */
605
	{ DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
605
	{ DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
606
	{ CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
606
	{ CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
607
	{ PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
607
	{ PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
608
	{ XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
608
	{ XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
609
	{ MWI_NOTIFICATION,	"message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
609
	{ MWI_NOTIFICATION,	"message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
610
};
610
};
611

    
   
611

   
612
/*! \brief The core structure to setup dialogs. We parse incoming messages by using
612
/*! \brief The core structure to setup dialogs. We parse incoming messages by using
613
 *  structure and then route the messages according to the type.
613
 *  structure and then route the messages according to the type.
614
 *
614
 *
615
 *  \note Note that sip_methods[i].id == i must hold or the code breaks
615
 *  \note Note that sip_methods[i].id == i must hold or the code breaks
616
 */
616
 */
617
static const struct  cfsip_methods {
617
static const struct  cfsip_methods {
618
	enum sipmethod id;
618
	enum sipmethod id;
619
	int need_rtp;		/*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
619
	int need_rtp;		/*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
620
	char * const text;
620
	char * const text;
621
	enum can_create_dialog can_create;
621
	enum can_create_dialog can_create;
622
} sip_methods[] = {
622
} sip_methods[] = {
623
	{ SIP_UNKNOWN,   RTP,    "-UNKNOWN-",CAN_CREATE_DIALOG },
623
	{ SIP_UNKNOWN,   RTP,    "-UNKNOWN-",CAN_CREATE_DIALOG },
624
	{ SIP_RESPONSE,  NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
624
	{ SIP_RESPONSE,  NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
625
	{ SIP_REGISTER,  NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
625
	{ SIP_REGISTER,  NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
626
	{ SIP_OPTIONS,   NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
626
	{ SIP_OPTIONS,   NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
627
	{ SIP_NOTIFY,    NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
627
	{ SIP_NOTIFY,    NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
628
	{ SIP_INVITE,    RTP,    "INVITE",   CAN_CREATE_DIALOG },
628
	{ SIP_INVITE,    RTP,    "INVITE",   CAN_CREATE_DIALOG },
629
	{ SIP_ACK,       NO_RTP, "ACK",      CAN_NOT_CREATE_DIALOG },
629
	{ SIP_ACK,       NO_RTP, "ACK",      CAN_NOT_CREATE_DIALOG },
630
	{ SIP_PRACK,     NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
630
	{ SIP_PRACK,     NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
631
	{ SIP_BYE,       NO_RTP, "BYE",      CAN_NOT_CREATE_DIALOG },
631
	{ SIP_BYE,       NO_RTP, "BYE",      CAN_NOT_CREATE_DIALOG },
632
	{ SIP_REFER,     NO_RTP, "REFER",    CAN_CREATE_DIALOG },
632
	{ SIP_REFER,     NO_RTP, "REFER",    CAN_CREATE_DIALOG },
633
	{ SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
633
	{ SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
634
	{ SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
634
	{ SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
635
	{ SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
635
	{ SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
636
	{ SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
636
	{ SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
637
	{ SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
637
	{ SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
638
	{ SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
638
	{ SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
639
	{ SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
639
	{ SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
640
};
640
};
641

    
   
641

   
642
/*! \brief Diversion header reasons
642
/*! \brief Diversion header reasons
643
 *
643
 *
644
 * The core defines a bunch of constants used to define
644
 * The core defines a bunch of constants used to define
645
 * redirecting reasons. This provides a translation table
645
 * redirecting reasons. This provides a translation table
646
 * between those and the strings which may be present in
646
 * between those and the strings which may be present in
647
 * a SIP Diversion header
647
 * a SIP Diversion header
648
 */
648
 */
649
static const struct sip_reasons {
649
static const struct sip_reasons {
650
	enum AST_REDIRECTING_REASON code;
650
	enum AST_REDIRECTING_REASON code;
651
	char * const text;
651
	char * const text;
652
} sip_reason_table[] = {
652
} sip_reason_table[] = {
653
	{ AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
653
	{ AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
654
	{ AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
654
	{ AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
655
	{ AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
655
	{ AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
656
	{ AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
656
	{ AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
657
	{ AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
657
	{ AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
658
	{ AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
658
	{ AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
659
	{ AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
659
	{ AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
660
	{ AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
660
	{ AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
661
	{ AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
661
	{ AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
662
	{ AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
662
	{ AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
663
	{ AST_REDIRECTING_REASON_AWAY, "away" },
663
	{ AST_REDIRECTING_REASON_AWAY, "away" },
664
	{ AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
664
	{ AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
665
};
665
};
666

    
   
666

   
667

    
   
667

   
668
/*! \name DefaultSettings
668
/*! \name DefaultSettings
669
	Default setttings are used as a channel setting and as a default when
669
	Default setttings are used as a channel setting and as a default when
670
	configuring devices
670
	configuring devices
671
*/
671
*/
672
/*@{*/
672
/*@{*/
673
static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
673
static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
674
static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
674
static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
675
static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
675
static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
676
static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
676
static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
677
static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
677
static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
678
static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
678
static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
679
static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
679
static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
680
static int default_qualify;                        /*!< Default Qualify= setting */
680
static int default_qualify;                        /*!< Default Qualify= setting */
681
static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
681
static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
682
static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
682
static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
683
                                                    *   a bridged channel on hold */
683
                                                    *   a bridged channel on hold */
684
static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
684
static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
685
static char default_engine[256];                   /*!< Default RTP engine */
685
static char default_engine[256];                   /*!< Default RTP engine */
686
static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
686
static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
687
static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
687
static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
688
static unsigned int default_transports;            /*!< Default Transports (enum sip_transport) that are acceptable */
688
static unsigned int default_transports;            /*!< Default Transports (enum sip_transport) that are acceptable */
689
static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
689
static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
690
/*@}*/
690
/*@}*/
691

    
   
691

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

    
   
694

   
695
/*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
695
/*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
696
#define SIP_PEDANTIC_DECODE(str)	\
696
#define SIP_PEDANTIC_DECODE(str)	\
697
	if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) {	\
697
	if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) {	\
698
		ast_uri_decode(str, ast_uri_sip_user);	\
698
		ast_uri_decode(str, ast_uri_sip_user);	\
699
	}	\
699
	}	\
700

    
   
700

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

    
   
703

   
704
static int global_relaxdtmf;        /*!< Relax DTMF */
704
static int global_relaxdtmf;        /*!< Relax DTMF */
705
static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
705
static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
706
static int global_rtptimeout;       /*!< Time out call if no RTP */
706
static int global_rtptimeout;       /*!< Time out call if no RTP */
707
static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
707
static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
708
static int global_rtpkeepalive;     /*!< Send RTP keepalives */
708
static int global_rtpkeepalive;     /*!< Send RTP keepalives */
709
static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
709
static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
710
static int global_regattempts_max;  /*!< Registration attempts before giving up */
710
static int global_regattempts_max;  /*!< Registration attempts before giving up */
711
static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
711
static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
712
static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
712
static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
713
                                     *   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
713
                                     *   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
714
                                     *   with just a boolean flag in the device structure */
714
                                     *   with just a boolean flag in the device structure */
715
static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
715
static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
716
static unsigned int global_tos_audio;    /*!< IP type of service for audio RTP packets */
716
static unsigned int global_tos_audio;    /*!< IP type of service for audio RTP packets */
717
static unsigned int global_tos_video;    /*!< IP type of service for video RTP packets */
717
static unsigned int global_tos_video;    /*!< IP type of service for video RTP packets */
718
static unsigned int global_tos_text;     /*!< IP type of service for text RTP packets */
718
static unsigned int global_tos_text;     /*!< IP type of service for text RTP packets */
719
static unsigned int global_cos_sip;      /*!< 802.1p class of service for SIP packets */
719
static unsigned int global_cos_sip;      /*!< 802.1p class of service for SIP packets */
720
static unsigned int global_cos_audio;    /*!< 802.1p class of service for audio RTP packets */
720
static unsigned int global_cos_audio;    /*!< 802.1p class of service for audio RTP packets */
721
static unsigned int global_cos_video;    /*!< 802.1p class of service for video RTP packets */
721
static unsigned int global_cos_video;    /*!< 802.1p class of service for video RTP packets */
722
static unsigned int global_cos_text;     /*!< 802.1p class of service for text RTP packets */
722
static unsigned int global_cos_text;     /*!< 802.1p class of service for text RTP packets */
723
static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
723
static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
724
static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
724
static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
725
static char global_useragent[AST_MAX_EXTENSION];    /*!< Useragent for the SIP channel */
725
static char global_useragent[AST_MAX_EXTENSION];    /*!< Useragent for the SIP channel */
726
static char global_sdpsession[AST_MAX_EXTENSION];   /*!< SDP session name for the SIP channel */
726
static char global_sdpsession[AST_MAX_EXTENSION];   /*!< SDP session name for the SIP channel */
727
static char global_sdpowner[AST_MAX_EXTENSION];     /*!< SDP owner name for the SIP channel */
727
static char global_sdpowner[AST_MAX_EXTENSION];     /*!< SDP owner name for the SIP channel */
728
static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
728
static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
729
static int global_t1;           /*!< T1 time */
729
static int global_t1;           /*!< T1 time */
730
static int global_t1min;        /*!< T1 roundtrip time minimum */
730
static int global_t1min;        /*!< T1 roundtrip time minimum */
731
static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
731
static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
732
static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
732
static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
733
static int global_qualifyfreq;          /*!< Qualify frequency */
733
static int global_qualifyfreq;          /*!< Qualify frequency */
734
static int global_qualify_gap;          /*!< Time between our group of peer pokes */
734
static int global_qualify_gap;          /*!< Time between our group of peer pokes */
735
static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
735
static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
736

    
   
736

   
737
static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
737
static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
738
static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
738
static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
739
static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
739
static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
740
static int global_max_se;                     /*!< Highest threshold for session refresh interval */
740
static int global_max_se;                     /*!< Highest threshold for session refresh interval */
741

    
   
741

   
742
static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
742
static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
743
/*@}*/
743
/*@}*/
744

    
   
744

   
745
/*!
745
/*!
746
 * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
746
 * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
747
 * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
747
 * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
748
 * event package. This variable is set at module load time and may be checked at runtime to determine
748
 * event package. This variable is set at module load time and may be checked at runtime to determine
749
 * if XML parsing support was found.
749
 * if XML parsing support was found.
750
 */
750
 */
751
static int can_parse_xml;
751
static int can_parse_xml;
752

    
   
752

   
753
/*! \name Object counters @{
753
/*! \name Object counters @{
754
 *  \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
754
 *  \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
755
 *  should be used to modify these values. */
755
 *  should be used to modify these values. */
756
static int speerobjs = 0;     /*!< Static peers */
756
static int speerobjs = 0;     /*!< Static peers */
757
static int rpeerobjs = 0;     /*!< Realtime peers */
757
static int rpeerobjs = 0;     /*!< Realtime peers */
758
static int apeerobjs = 0;     /*!< Autocreated peer objects */
758
static int apeerobjs = 0;     /*!< Autocreated peer objects */
759
static int regobjs = 0;       /*!< Registry objects */
759
static int regobjs = 0;       /*!< Registry objects */
760
/* }@ */
760
/* }@ */
761

    
   
761

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

    
   
764

   
765
static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
765
static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
766
static int network_change_event_sched_id = -1;
766
static int network_change_event_sched_id = -1;
767

    
   
767

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

    
   
769

   
770
AST_MUTEX_DEFINE_STATIC(netlock);
770
AST_MUTEX_DEFINE_STATIC(netlock);
771

    
   
771

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

    
   
775

   
776
AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
776
AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
777

    
   
777

   
778
/*! \brief This is the thread for the monitor which checks for input on the channels
778
/*! \brief This is the thread for the monitor which checks for input on the channels
779
   which are not currently in use.  */
779
   which are not currently in use.  */
780
static pthread_t monitor_thread = AST_PTHREADT_NULL;
780
static pthread_t monitor_thread = AST_PTHREADT_NULL;
781

    
   
781

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

    
   
784

   
785
struct ast_sched_context *sched;     /*!< The scheduling context */
785
struct ast_sched_context *sched;     /*!< The scheduling context */
786
static struct io_context *io;           /*!< The IO context */
786
static struct io_context *io;           /*!< The IO context */
787
static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
787
static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
788
struct sip_pkt;
788
struct sip_pkt;
789
static AST_LIST_HEAD_STATIC(domain_list, domain);    /*!< The SIP domain list */
789
static AST_LIST_HEAD_STATIC(domain_list, domain);    /*!< The SIP domain list */
790

    
   
790

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

    
   
792

   
793
static enum sip_debug_e sipdebug;
793
static enum sip_debug_e sipdebug;
794

    
   
794

   
795
/*! \brief extra debugging for 'text' related events.
795
/*! \brief extra debugging for 'text' related events.
796
 *  At the moment this is set together with sip_debug_console.
796
 *  At the moment this is set together with sip_debug_console.
797
 *  \note It should either go away or be implemented properly.
797
 *  \note It should either go away or be implemented properly.
798
 */
798
 */
799
static int sipdebug_text;
799
static int sipdebug_text;
800

    
   
800

   
801
static const struct _map_x_s referstatusstrings[] = {
801
static const struct _map_x_s referstatusstrings[] = {
802
	{ REFER_IDLE,      "<none>" },
802
	{ REFER_IDLE,      "<none>" },
803
	{ REFER_SENT,      "Request sent" },
803
	{ REFER_SENT,      "Request sent" },
804
	{ REFER_RECEIVED,  "Request received" },
804
	{ REFER_RECEIVED,  "Request received" },
805
	{ REFER_CONFIRMED, "Confirmed" },
805
	{ REFER_CONFIRMED, "Confirmed" },
806
	{ REFER_ACCEPTED,  "Accepted" },
806
	{ REFER_ACCEPTED,  "Accepted" },
807
	{ REFER_RINGING,   "Target ringing" },
807
	{ REFER_RINGING,   "Target ringing" },
808
	{ REFER_200OK,     "Done" },
808
	{ REFER_200OK,     "Done" },
809
	{ REFER_FAILED,    "Failed" },
809
	{ REFER_FAILED,    "Failed" },
810
	{ REFER_NOAUTH,    "Failed - auth failure" },
810
	{ REFER_NOAUTH,    "Failed - auth failure" },
811
	{ -1,               NULL} /* terminator */
811
	{ -1,               NULL} /* terminator */
812
};
812
};
813

    
   
813

   
814
/* --- Hash tables of various objects --------*/
814
/* --- Hash tables of various objects --------*/
815
#ifdef LOW_MEMORY
815
#ifdef LOW_MEMORY
816
static const int HASH_PEER_SIZE = 17;
816
static const int HASH_PEER_SIZE = 17;
817
static const int HASH_DIALOG_SIZE = 17;
817
static const int HASH_DIALOG_SIZE = 17;
818
#else
818
#else
819
static const int HASH_PEER_SIZE = 563;	/*!< Size of peer hash table, prime number preferred! */
819
static const int HASH_PEER_SIZE = 563;	/*!< Size of peer hash table, prime number preferred! */
820
static const int HASH_DIALOG_SIZE = 563;
820
static const int HASH_DIALOG_SIZE = 563;
821
#endif
821
#endif
822

    
   
822

   
823
static const struct {
823
static const struct {
824
	enum ast_cc_service_type service;
824
	enum ast_cc_service_type service;
825
	const char *service_string;
825
	const char *service_string;
826
} sip_cc_service_map [] = {
826
} sip_cc_service_map [] = {
827
	[AST_CC_NONE] = { AST_CC_NONE, "" },
827
	[AST_CC_NONE] = { AST_CC_NONE, "" },
828
	[AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
828
	[AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
829
	[AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
829
	[AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
830
	[AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
830
	[AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
831
};
831
};
832

    
   
832

   
833
static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
833
static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
834
{
834
{
835
	enum ast_cc_service_type service;
835
	enum ast_cc_service_type service;
836
	for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
836
	for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
837
		if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
837
		if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
838
			return service;
838
			return service;
839
		}
839
		}
840
	}
840
	}
841
	return AST_CC_NONE;
841
	return AST_CC_NONE;
842
}
842
}
843

    
   
843

   
844
static const struct {
844
static const struct {
845
	enum sip_cc_notify_state state;
845
	enum sip_cc_notify_state state;
846
	const char *state_string;
846
	const char *state_string;
847
} sip_cc_notify_state_map [] = {
847
} sip_cc_notify_state_map [] = {
848
	[CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
848
	[CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
849
	[CC_READY] = {CC_READY, "cc-state: ready"},
849
	[CC_READY] = {CC_READY, "cc-state: ready"},
850
};
850
};
851

    
   
851

   
852
AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
852
AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
853

    
   
853

   
854
static int sip_epa_register(const struct epa_static_data *static_data)
854
static int sip_epa_register(const struct epa_static_data *static_data)
855
{
855
{
856
	struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
856
	struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
857

    
   
857

   
858
	if (!backend) {
858
	if (!backend) {
859
		return -1;
859
		return -1;
860
	}
860
	}
861

    
   
861

   
862
	backend->static_data = static_data;
862
	backend->static_data = static_data;
863

    
   
863

   
864
	AST_LIST_LOCK(&epa_static_data_list);
864
	AST_LIST_LOCK(&epa_static_data_list);
865
	AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
865
	AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
866
	AST_LIST_UNLOCK(&epa_static_data_list);
866
	AST_LIST_UNLOCK(&epa_static_data_list);
867
	return 0;
867
	return 0;
868
}
868
}
869

    
   
869

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

    
   
871

   
872
static void cc_epa_destructor(void *data)
872
static void cc_epa_destructor(void *data)
873
{
873
{
874
	struct sip_epa_entry *epa_entry = data;
874
	struct sip_epa_entry *epa_entry = data;
875
	struct cc_epa_entry *cc_entry = epa_entry->instance_data;
875
	struct cc_epa_entry *cc_entry = epa_entry->instance_data;
876
	ast_free(cc_entry);
876
	ast_free(cc_entry);
877
}
877
}
878

    
   
878

   
879
static const struct epa_static_data cc_epa_static_data  = {
879
static const struct epa_static_data cc_epa_static_data  = {
880
	.event = CALL_COMPLETION,
880
	.event = CALL_COMPLETION,
881
	.name = "call-completion",
881
	.name = "call-completion",
882
	.handle_error = cc_handle_publish_error,
882
	.handle_error = cc_handle_publish_error,
883
	.destructor = cc_epa_destructor,
883
	.destructor = cc_epa_destructor,
884
};
884
};
885

    
   
885

   
886
static const struct epa_static_data *find_static_data(const char * const event_package)
886
static const struct epa_static_data *find_static_data(const char * const event_package)
887
{
887
{
888
	const struct epa_backend *backend = NULL;
888
	const struct epa_backend *backend = NULL;
889

    
   
889

   
890
	AST_LIST_LOCK(&epa_static_data_list);
890
	AST_LIST_LOCK(&epa_static_data_list);
891
	AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
891
	AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
892
		if (!strcmp(backend->static_data->name, event_package)) {
892
		if (!strcmp(backend->static_data->name, event_package)) {
893
			break;
893
			break;
894
		}
894
		}
895
	}
895
	}
896
	AST_LIST_UNLOCK(&epa_static_data_list);
896
	AST_LIST_UNLOCK(&epa_static_data_list);
897
	return backend ? backend->static_data : NULL;
897
	return backend ? backend->static_data : NULL;
898
}
898
}
899

    
   
899

   
900
static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
900
static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
901
{
901
{
902
	struct sip_epa_entry *epa_entry;
902
	struct sip_epa_entry *epa_entry;
903
	const struct epa_static_data *static_data;
903
	const struct epa_static_data *static_data;
904

    
   
904

   
905
	if (!(static_data = find_static_data(event_package))) {
905
	if (!(static_data = find_static_data(event_package))) {
906
		return NULL;
906
		return NULL;
907
	}
907
	}
908

    
   
908

   
909
	if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
909
	if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
910
		return NULL;
910
		return NULL;
911
	}
911
	}
912

    
   
912

   
913
	epa_entry->static_data = static_data;
913
	epa_entry->static_data = static_data;
914
	ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
914
	ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
915
	return epa_entry;
915
	return epa_entry;
916
}
916
}
917

    
   
917

   
918
/*!
918
/*!
919
 * Used to create new entity IDs by ESCs.
919
 * Used to create new entity IDs by ESCs.
920
 */
920
 */
921
static int esc_etag_counter;
921
static int esc_etag_counter;
922
static const int DEFAULT_PUBLISH_EXPIRES = 3600;
922
static const int DEFAULT_PUBLISH_EXPIRES = 3600;
923

    
   
923

   
924
#ifdef HAVE_LIBXML2
924
#ifdef HAVE_LIBXML2
925
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);
925
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);
926

    
   
926

   
927
static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
927
static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
928
	.initial_handler = cc_esc_publish_handler,
928
	.initial_handler = cc_esc_publish_handler,
929
	.modify_handler = cc_esc_publish_handler,
929
	.modify_handler = cc_esc_publish_handler,
930
};
930
};
931
#endif
931
#endif
932

    
   
932

   
933
/*!
933
/*!
934
 * \brief The Event State Compositors
934
 * \brief The Event State Compositors
935
 *
935
 *
936
 * An Event State Compositor is an entity which
936
 * An Event State Compositor is an entity which
937
 * accepts PUBLISH requests and acts appropriately
937
 * accepts PUBLISH requests and acts appropriately
938
 * based on these requests.
938
 * based on these requests.
939
 *
939
 *
940
 * The actual event_state_compositor structure is simply
940
 * The actual event_state_compositor structure is simply
941
 * an ao2_container of sip_esc_entrys. When an incoming
941
 * an ao2_container of sip_esc_entrys. When an incoming
942
 * PUBLISH is received, we can match the appropriate sip_esc_entry
942
 * PUBLISH is received, we can match the appropriate sip_esc_entry
943
 * using the entity ID of the incoming PUBLISH.
943
 * using the entity ID of the incoming PUBLISH.
944
 */
944
 */
945
static struct event_state_compositor {
945
static struct event_state_compositor {
946
	enum subscriptiontype event;
946
	enum subscriptiontype event;
947
	const char * name;
947
	const char * name;
948
	const struct sip_esc_publish_callbacks *callbacks;
948
	const struct sip_esc_publish_callbacks *callbacks;
949
	struct ao2_container *compositor;
949
	struct ao2_container *compositor;
950
} event_state_compositors [] = {
950
} event_state_compositors [] = {
951
#ifdef HAVE_LIBXML2
951
#ifdef HAVE_LIBXML2
952
	{CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
952
	{CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
953
#endif
953
#endif
954
};
954
};
955

    
   
955

   
956
static const int ESC_MAX_BUCKETS = 37;
956
static const int ESC_MAX_BUCKETS = 37;
957

    
   
957

   
958
static void esc_entry_destructor(void *obj)
958
static void esc_entry_destructor(void *obj)
959
{
959
{
960
	struct sip_esc_entry *esc_entry = obj;
960
	struct sip_esc_entry *esc_entry = obj;
961
	if (esc_entry->sched_id > -1) {
961
	if (esc_entry->sched_id > -1) {
962
		AST_SCHED_DEL(sched, esc_entry->sched_id);
962
		AST_SCHED_DEL(sched, esc_entry->sched_id);
963
	}
963
	}
964
}
964
}
965

    
   
965

   
966
static int esc_hash_fn(const void *obj, const int flags)
966
static int esc_hash_fn(const void *obj, const int flags)
967
{
967
{
968
	const struct sip_esc_entry *entry = obj;
968
	const struct sip_esc_entry *entry = obj;
969
	return ast_str_hash(entry->entity_tag);
969
	return ast_str_hash(entry->entity_tag);
970
}
970
}
971

    
   
971

   
972
static int esc_cmp_fn(void *obj, void *arg, int flags)
972
static int esc_cmp_fn(void *obj, void *arg, int flags)
973
{
973
{
974
	struct sip_esc_entry *entry1 = obj;
974
	struct sip_esc_entry *entry1 = obj;
975
	struct sip_esc_entry *entry2 = arg;
975
	struct sip_esc_entry *entry2 = arg;
976

    
   
976

   
977
	return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
977
	return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
978
}
978
}
979

    
   
979

   
980
static struct event_state_compositor *get_esc(const char * const event_package) {
980
static struct event_state_compositor *get_esc(const char * const event_package) {
981
	int i;
981
	int i;
982
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
982
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
983
		if (!strcasecmp(event_package, event_state_compositors[i].name)) {
983
		if (!strcasecmp(event_package, event_state_compositors[i].name)) {
984
			return &event_state_compositors[i];
984
			return &event_state_compositors[i];
985
		}
985
		}
986
	}
986
	}
987
	return NULL;
987
	return NULL;
988
}
988
}
989

    
   
989

   
990
static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
990
static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
991
	struct sip_esc_entry *entry;
991
	struct sip_esc_entry *entry;
992
	struct sip_esc_entry finder;
992
	struct sip_esc_entry finder;
993

    
   
993

   
994
	ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
994
	ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
995

    
   
995

   
996
	entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
996
	entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
997

    
   
997

   
998
	return entry;
998
	return entry;
999
}
999
}
1000

    
   
1000

   
1001
static int publish_expire(const void *data)
1001
static int publish_expire(const void *data)
1002
{
1002
{
1003
	struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
1003
	struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
1004
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1004
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1005

    
   
1005

   
1006
	ast_assert(esc != NULL);
1006
	ast_assert(esc != NULL);
1007

    
   
1007

   
1008
	ao2_unlink(esc->compositor, esc_entry);
1008
	ao2_unlink(esc->compositor, esc_entry);
1009
	ao2_ref(esc_entry, -1);
1009
	ao2_ref(esc_entry, -1);
1010
	return 0;
1010
	return 0;
1011
}
1011
}
1012

    
   
1012

   
1013
static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
1013
static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
1014
{
1014
{
1015
	int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
1015
	int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
1016
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1016
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1017

    
   
1017

   
1018
	ast_assert(esc != NULL);
1018
	ast_assert(esc != NULL);
1019
	if (is_linked) {
1019
	if (is_linked) {
1020
		ao2_unlink(esc->compositor, esc_entry);
1020
		ao2_unlink(esc->compositor, esc_entry);
1021
	}
1021
	}
1022
	snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
1022
	snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
1023
	ao2_link(esc->compositor, esc_entry);
1023
	ao2_link(esc->compositor, esc_entry);
1024
}
1024
}
1025

    
   
1025

   
1026
static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
1026
static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
1027
{
1027
{
1028
	struct sip_esc_entry *esc_entry;
1028
	struct sip_esc_entry *esc_entry;
1029
	int expires_ms;
1029
	int expires_ms;
1030

    
   
1030

   
1031
	if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
1031
	if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
1032
		return NULL;
1032
		return NULL;
1033
	}
1033
	}
1034

    
   
1034

   
1035
	esc_entry->event = esc->name;
1035
	esc_entry->event = esc->name;
1036

    
   
1036

   
1037
	expires_ms = expires * 1000;
1037
	expires_ms = expires * 1000;
1038
	/* Bump refcount for scheduler */
1038
	/* Bump refcount for scheduler */
1039
	ao2_ref(esc_entry, +1);
1039
	ao2_ref(esc_entry, +1);
1040
	esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
1040
	esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
1041

    
   
1041

   
1042
	/* Note: This links the esc_entry into the ESC properly */
1042
	/* Note: This links the esc_entry into the ESC properly */
1043
	create_new_sip_etag(esc_entry, 0);
1043
	create_new_sip_etag(esc_entry, 0);
1044

    
   
1044

   
1045
	return esc_entry;
1045
	return esc_entry;
1046
}
1046
}
1047

    
   
1047

   
1048
static int initialize_escs(void)
1048
static int initialize_escs(void)
1049
{
1049
{
1050
	int i, res = 0;
1050
	int i, res = 0;
1051
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1051
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1052
		if (!((event_state_compositors[i].compositor) =
1052
		if (!((event_state_compositors[i].compositor) =
1053
					ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
1053
					ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
1054
			res = -1;
1054
			res = -1;
1055
		}
1055
		}
1056
	}
1056
	}
1057
	return res;
1057
	return res;
1058
}
1058
}
1059

    
   
1059

   
1060
static void destroy_escs(void)
1060
static void destroy_escs(void)
1061
{
1061
{
1062
	int i;
1062
	int i;
1063
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1063
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1064
		ao2_ref(event_state_compositors[i].compositor, -1);
1064
		ao2_ref(event_state_compositors[i].compositor, -1);
1065
	}
1065
	}
1066
}
1066
}
1067

    
   
1067

   
1068
/*! \brief
1068
/*! \brief
1069
 * Here we implement the container for dialogs which are in the
1069
 * Here we implement the container for dialogs which are in the
1070
 * dialog_needdestroy state to iterate only through the dialogs
1070
 * dialog_needdestroy state to iterate only through the dialogs
1071
 * unlink them instead of iterate through all dialogs
1071
 * unlink them instead of iterate through all dialogs
1072
 */
1072
 */
1073
struct ao2_container *dialogs_needdestroy;
1073
struct ao2_container *dialogs_needdestroy;
1074

    
   
1074

   
1075
/*! \brief
1075
/*! \brief
1076
 * Here we implement the container for dialogs which have rtp
1076
 * Here we implement the container for dialogs which have rtp
1077
 * traffic and rtptimeout, rtpholdtimeout or rtpkeepalive
1077
 * traffic and rtptimeout, rtpholdtimeout or rtpkeepalive
1078
 * set. We use this container instead the whole dialog list.
1078
 * set. We use this container instead the whole dialog list.
1079
 */
1079
 */
1080
struct ao2_container *dialogs_rtpcheck;
1080
struct ao2_container *dialogs_rtpcheck;
1081

    
   
1081

   
1082
/*! \brief
1082
/*! \brief
1083
 * Here we implement the container for dialogs (sip_pvt), defining
1083
 * Here we implement the container for dialogs (sip_pvt), defining
1084
 * generic wrapper functions to ease the transition from the current
1084
 * generic wrapper functions to ease the transition from the current
1085
 * implementation (a single linked list) to a different container.
1085
 * implementation (a single linked list) to a different container.
1086
 * In addition to a reference to the container, we need functions to lock/unlock
1086
 * In addition to a reference to the container, we need functions to lock/unlock
1087
 * the container and individual items, and functions to add/remove
1087
 * the container and individual items, and functions to add/remove
1088
 * references to the individual items.
1088
 * references to the individual items.
1089
 */
1089
 */
1090
static struct ao2_container *dialogs;
1090
static struct ao2_container *dialogs;
1091
#define sip_pvt_lock(x) ao2_lock(x)
1091
#define sip_pvt_lock(x) ao2_lock(x)
1092
#define sip_pvt_trylock(x) ao2_trylock(x)
1092
#define sip_pvt_trylock(x) ao2_trylock(x)
1093
#define sip_pvt_unlock(x) ao2_unlock(x)
1093
#define sip_pvt_unlock(x) ao2_unlock(x)
1094

    
   
1094

   
1095
/*! \brief  The table of TCP threads */
1095
/*! \brief  The table of TCP threads */
1096
static struct ao2_container *threadt;
1096
static struct ao2_container *threadt;
1097

    
   
1097

   
1098
/*! \brief  The peer list: Users, Peers and Friends */
1098
/*! \brief  The peer list: Users, Peers and Friends */
1099
static struct ao2_container *peers;
1099
static struct ao2_container *peers;
1100
static struct ao2_container *peers_by_ip;
1100
static struct ao2_container *peers_by_ip;
1101

    
   
1101

   
1102
/*! \brief  The register list: Other SIP proxies we register with and receive calls from */
1102
/*! \brief  The register list: Other SIP proxies we register with and receive calls from */
1103
static struct ast_register_list {
1103
static struct ast_register_list {
1104
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1104
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1105
	int recheck;
1105
	int recheck;
1106
} regl;
1106
} regl;
1107

    
   
1107

   
1108
/*! \brief  The MWI subscription list */
1108
/*! \brief  The MWI subscription list */
1109
static struct ast_subscription_mwi_list {
1109
static struct ast_subscription_mwi_list {
1110
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
1110
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
1111
} submwil;
1111
} submwil;
1112
static int temp_pvt_init(void *);
1112
static int temp_pvt_init(void *);
1113
static void temp_pvt_cleanup(void *);
1113
static void temp_pvt_cleanup(void *);
1114

    
   
1114

   
1115
/*! \brief A per-thread temporary pvt structure */
1115
/*! \brief A per-thread temporary pvt structure */
1116
AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1116
AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1117

    
   
1117

   
1118
/*! \brief Authentication list for realm authentication
1118
/*! \brief Authentication list for realm authentication
1119
 * \todo Move the sip_auth list to AST_LIST */
1119
 * \todo Move the sip_auth list to AST_LIST */
1120
static struct sip_auth *authl = NULL;
1120
static struct sip_auth *authl = NULL;
1121

    
   
1121

   
1122
/* --- Sockets and networking --------------*/
1122
/* --- Sockets and networking --------------*/
1123

    
   
1123

   
1124
/*! \brief Main socket for UDP SIP communication.
1124
/*! \brief Main socket for UDP SIP communication.
1125
 *
1125
 *
1126
 * sipsock is shared between the SIP manager thread (which handles reload
1126
 * sipsock is shared between the SIP manager thread (which handles reload
1127
 * requests), the udp io handler (sipsock_read()) and the user routines that
1127
 * requests), the udp io handler (sipsock_read()) and the user routines that
1128
 * issue udp writes (using __sip_xmit()).
1128
 * issue udp writes (using __sip_xmit()).
1129
 * The socket is -1 only when opening fails (this is a permanent condition),
1129
 * The socket is -1 only when opening fails (this is a permanent condition),
1130
 * or when we are handling a reload() that changes its address (this is
1130
 * or when we are handling a reload() that changes its address (this is
1131
 * a transient situation during which we might have a harmless race, see
1131
 * a transient situation during which we might have a harmless race, see
1132
 * below). Because the conditions for the race to be possible are extremely
1132
 * below). Because the conditions for the race to be possible are extremely
1133
 * rare, we don't want to pay the cost of locking on every I/O.
1133
 * rare, we don't want to pay the cost of locking on every I/O.
1134
 * Rather, we remember that when the race may occur, communication is
1134
 * Rather, we remember that when the race may occur, communication is
1135
 * bound to fail anyways, so we just live with this event and let
1135
 * bound to fail anyways, so we just live with this event and let
1136
 * the protocol handle this above us.
1136
 * the protocol handle this above us.
1137
 */
1137
 */
1138
static int sipsock  = -1;
1138
static int sipsock  = -1;
1139

    
   
1139

   
1140
struct ast_sockaddr bindaddr;	/*!< UDP: The address we bind to */
1140
struct ast_sockaddr bindaddr;	/*!< UDP: The address we bind to */
1141

    
   
1141

   
1142
/*! \brief our (internal) default address/port to put in SIP/SDP messages
1142
/*! \brief our (internal) default address/port to put in SIP/SDP messages
1143
 *  internip is initialized picking a suitable address from one of the
1143
 *  internip is initialized picking a suitable address from one of the
1144
 * interfaces, and the same port number we bind to. It is used as the
1144
 * interfaces, and the same port number we bind to. It is used as the
1145
 * default address/port in SIP messages, and as the default address
1145
 * default address/port in SIP messages, and as the default address
1146
 * (but not port) in SDP messages.
1146
 * (but not port) in SDP messages.
1147
 */
1147
 */
1148
static struct ast_sockaddr internip;
1148
static struct ast_sockaddr internip;
1149

    
   
1149

   
1150
/*! \brief our external IP address/port for SIP sessions.
1150
/*! \brief our external IP address/port for SIP sessions.
1151
 * externaddr.sin_addr is only set when we know we might be behind
1151
 * externaddr.sin_addr is only set when we know we might be behind
1152
 * a NAT, and this is done using a variety of (mutually exclusive)
1152
 * a NAT, and this is done using a variety of (mutually exclusive)
1153
 * ways from the config file:
1153
 * ways from the config file:
1154
 *
1154
 *
1155
 * + with "externaddr = host[:port]" we specify the address/port explicitly.
1155
 * + with "externaddr = host[:port]" we specify the address/port explicitly.
1156
 *   The address is looked up only once when (re)loading the config file;
1156
 *   The address is looked up only once when (re)loading the config file;
1157
 *
1157
 *
1158
 * + with "externhost = host[:port]" we do a similar thing, but the
1158
 * + with "externhost = host[:port]" we do a similar thing, but the
1159
 *   hostname is stored in externhost, and the hostname->IP mapping
1159
 *   hostname is stored in externhost, and the hostname->IP mapping
1160
 *   is refreshed every 'externrefresh' seconds;
1160
 *   is refreshed every 'externrefresh' seconds;
1161
 *
1161
 *
1162
 * Other variables (externhost, externexpire, externrefresh) are used
1162
 * Other variables (externhost, externexpire, externrefresh) are used
1163
 * to support the above functions.
1163
 * to support the above functions.
1164
 */
1164
 */
1165
static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
1165
static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
1166
static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
1166
static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
1167

    
   
1167

   
1168
static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1168
static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1169
static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1169
static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1170
static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
1170
static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
1171
static uint16_t externtcpport;          /*!< external tcp port */ 
1171
static uint16_t externtcpport;          /*!< external tcp port */ 
1172
static uint16_t externtlsport;          /*!< external tls port */
1172
static uint16_t externtlsport;          /*!< external tls port */
1173

    
   
1173

   
1174
/*! \brief  List of local networks
1174
/*! \brief  List of local networks
1175
 * We store "localnet" addresses from the config file into an access list,
1175
 * We store "localnet" addresses from the config file into an access list,
1176
 * marked as 'DENY', so the call to ast_apply_ha() will return
1176
 * marked as 'DENY', so the call to ast_apply_ha() will return
1177
 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1177
 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1178
 * (i.e. presumably public) addresses.
1178
 * (i.e. presumably public) addresses.
1179
 */
1179
 */
1180
static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
1180
static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
1181

    
   
1181

   
1182
static int ourport_tcp;             /*!< The port used for TCP connections */
1182
static int ourport_tcp;             /*!< The port used for TCP connections */
1183
static int ourport_tls;             /*!< The port used for TCP/TLS connections */
1183
static int ourport_tls;             /*!< The port used for TCP/TLS connections */
1184
static struct ast_sockaddr debugaddr;
1184
static struct ast_sockaddr debugaddr;
1185

    
   
1185

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

    
   
1187

   
1188
/*! some list management macros. */
1188
/*! some list management macros. */
1189

    
   
1189

   
1190
#define UNLINK(element, head, prev) do {	\
1190
#define UNLINK(element, head, prev) do {	\
1191
	if (prev)				\
1191
	if (prev)				\
1192
		(prev)->next = (element)->next;	\
1192
		(prev)->next = (element)->next;	\
1193
	else					\
1193
	else					\
1194
		(head) = (element)->next;	\
1194
		(head) = (element)->next;	\
1195
	} while (0)
1195
	} while (0)
1196

    
   
1196

   
1197
/*---------------------------- Forward declarations of functions in chan_sip.c */
1197
/*---------------------------- Forward declarations of functions in chan_sip.c */
1198
/* Note: This is added to help splitting up chan_sip.c into several files
1198
/* Note: This is added to help splitting up chan_sip.c into several files
1199
	in coming releases. */
1199
	in coming releases. */
1200

    
   
1200

   
1201
/*--- PBX interface functions */
1201
/*--- PBX interface functions */
1202
static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, void *data, int *cause);
1202
static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, void *data, int *cause);
1203
static int sip_devicestate(void *data);
1203
static int sip_devicestate(void *data);
1204
static int sip_sendtext(struct ast_channel *ast, const char *text);
1204
static int sip_sendtext(struct ast_channel *ast, const char *text);
1205
static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1205
static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1206
static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1206
static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1207
static int sip_hangup(struct ast_channel *ast);
1207
static int sip_hangup(struct ast_channel *ast);
1208
static int sip_answer(struct ast_channel *ast);
1208
static int sip_answer(struct ast_channel *ast);
1209
static struct ast_frame *sip_read(struct ast_channel *ast);
1209
static struct ast_frame *sip_read(struct ast_channel *ast);
1210
static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1210
static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1211
static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1211
static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1212
static int sip_transfer(struct ast_channel *ast, const char *dest);
1212
static int sip_transfer(struct ast_channel *ast, const char *dest);
1213
static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1213
static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1214
static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1214
static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1215
static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1215
static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1216
static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1216
static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1217
static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1217
static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1218
static const char *sip_get_callid(struct ast_channel *chan);
1218
static const char *sip_get_callid(struct ast_channel *chan);
1219

    
   
1219

   
1220
static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
1220
static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
1221
static int sip_standard_port(enum sip_transport type, int port);
1221
static int sip_standard_port(enum sip_transport type, int port);
1222
static int sip_prepare_socket(struct sip_pvt *p);
1222
static int sip_prepare_socket(struct sip_pvt *p);
1223
static int get_address_family_filter(const struct ast_sockaddr *addr);
1223
static int get_address_family_filter(const struct ast_sockaddr *addr);
1224

    
   
1224

   
1225
/*--- Transmitting responses and requests */
1225
/*--- Transmitting responses and requests */
1226
static int sipsock_read(int *id, int fd, short events, void *ignore);
1226
static int sipsock_read(int *id, int fd, short events, void *ignore);
1227
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
1227
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
1228
static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
1228
static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
1229
static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1229
static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1230
static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1230
static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1231
static int retrans_pkt(const void *data);
1231
static int retrans_pkt(const void *data);
1232
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);
1232
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);
1233
static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1233
static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1234
static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1234
static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1235
static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1235
static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1236
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);
1236
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);
1237
static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1237
static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1238
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);
1238
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);
1239
static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1239
static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1240
static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1240
static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1241
static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
1241
static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
1242
static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1242
static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1243
static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1243
static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1244
static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
1244
static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
1245
static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
1245
static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
1246
static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1246
static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1247
static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
1247
static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
1248
static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1248
static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1249
static int transmit_info_with_vidupdate(struct sip_pvt *p);
1249
static int transmit_info_with_vidupdate(struct sip_pvt *p);
1250
static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1250
static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1251
static int transmit_refer(struct sip_pvt *p, const char *dest);
1251
static int transmit_refer(struct sip_pvt *p, const char *dest);
1252
static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1252
static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1253
static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1253
static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1254
static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
1254
static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
1255
static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1255
static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1256
static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1256
static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1257
static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1257
static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1258
static void copy_request(struct sip_request *dst, const struct sip_request *src);
1258
static void copy_request(struct sip_request *dst, const struct sip_request *src);
1259
static void receive_message(struct sip_pvt *p, struct sip_request *req);
1259
static void receive_message(struct sip_pvt *p, struct sip_request *req);
1260
static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1260
static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1261
static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1261
static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1262

    
   
1262

   
1263
/* Misc dialog routines */
1263
/* Misc dialog routines */
1264
static int __sip_autodestruct(const void *data);
1264
static int __sip_autodestruct(const void *data);
1265
static void *registry_unref(struct sip_registry *reg, char *tag);
1265
static void *registry_unref(struct sip_registry *reg, char *tag);
1266
static int update_call_counter(struct sip_pvt *fup, int event);
1266
static int update_call_counter(struct sip_pvt *fup, int event);
1267
static int auto_congest(const void *arg);
1267
static int auto_congest(const void *arg);
1268
static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
1268
static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
1269
static void free_old_route(struct sip_route *route);
1269
static void free_old_route(struct sip_route *route);
1270
static void list_route(struct sip_route *route);
1270
static void list_route(struct sip_route *route);
1271
static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1271
static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1272
static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
1272
static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
1273
					      struct sip_request *req, const char *uri);
1273
					      struct sip_request *req, const char *uri);
1274
static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1274
static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1275
static void check_pendings(struct sip_pvt *p);
1275
static void check_pendings(struct sip_pvt *p);
1276
static void *sip_park_thread(void *stuff);
1276
static void *sip_park_thread(void *stuff);
1277
static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno, char *parkexten);
1277
static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno, char *parkexten);
1278
static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1278
static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1279
static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1279
static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1280

    
   
1280

   
1281
/*--- Codec handling / SDP */
1281
/*--- Codec handling / SDP */
1282
static void try_suggested_sip_codec(struct sip_pvt *p);
1282
static void try_suggested_sip_codec(struct sip_pvt *p);
1283
static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1283
static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1284
static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1284
static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1285
static int find_sdp(struct sip_request *req);
1285
static int find_sdp(struct sip_request *req);
1286
static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1286
static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1287
static int process_sdp_o(const char *o, struct sip_pvt *p);
1287
static int process_sdp_o(const char *o, struct sip_pvt *p);
1288
static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
1288
static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
1289
static int process_sdp_a_sendonly(const char *a, int *sendonly);
1289
static int process_sdp_a_sendonly(const char *a, int *sendonly);
1290
static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1290
static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1291
static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1291
static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1292
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);
1292
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);
1293
static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1293
static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1294
static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
1294
static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
1295
			     struct ast_str **m_buf, struct ast_str **a_buf,
1295
			     struct ast_str **m_buf, struct ast_str **a_buf,
1296
			     int debug, int *min_packet_size);
1296
			     int debug, int *min_packet_size);
1297
static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1297
static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1298
				struct ast_str **m_buf, struct ast_str **a_buf,
1298
				struct ast_str **m_buf, struct ast_str **a_buf,
1299
				int debug);
1299
				int debug);
1300
static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1300
static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1301
static void do_setnat(struct sip_pvt *p);
1301
static void do_setnat(struct sip_pvt *p);
1302
static void stop_media_flows(struct sip_pvt *p);
1302
static void stop_media_flows(struct sip_pvt *p);
1303

    
   
1303

   
1304
/*--- Authentication stuff */
1304
/*--- Authentication stuff */
1305
static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1305
static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1306
static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1306
static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1307
static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1307
static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1308
					 const char *secret, const char *md5secret, int sipmethod,
1308
					 const char *secret, const char *md5secret, int sipmethod,
1309
					 const char *uri, enum xmittype reliable, int ignore);
1309
					 const char *uri, enum xmittype reliable, int ignore);
1310
static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1310
static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1311
					      int sipmethod, const char *uri, enum xmittype reliable,
1311
					      int sipmethod, const char *uri, enum xmittype reliable,
1312
					      struct ast_sockaddr *addr, struct sip_peer **authpeer);
1312
					      struct ast_sockaddr *addr, struct sip_peer **authpeer);
1313
static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
1313
static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
1314

    
   
1314

   
1315
/*--- Domain handling */
1315
/*--- Domain handling */
1316
static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1316
static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1317
static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1317
static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1318
static void clear_sip_domains(void);
1318
static void clear_sip_domains(void);
1319

    
   
1319

   
1320
/*--- SIP realm authentication */
1320
/*--- SIP realm authentication */
1321
static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
1321
static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
1322
static int clear_realm_authentication(struct sip_auth *authlist);	/* Clear realm authentication list (at reload) */
1322
static int clear_realm_authentication(struct sip_auth *authlist);	/* Clear realm authentication list (at reload) */
1323
static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1323
static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1324

    
   
1324

   
1325
/*--- Misc functions */
1325
/*--- Misc functions */
1326
static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1326
static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1327
static int sip_do_reload(enum channelreloadreason reason);
1327
static int sip_do_reload(enum channelreloadreason reason);
1328
static int reload_config(enum channelreloadreason reason);
1328
static int reload_config(enum channelreloadreason reason);
1329
static int expire_register(const void *data);
1329
static int expire_register(const void *data);
1330
static void *do_monitor(void *data);
1330
static void *do_monitor(void *data);
1331
static int restart_monitor(void);
1331
static int restart_monitor(void);
1332
static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1332
static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1333
static struct ast_variable *copy_vars(struct ast_variable *src);
1333
static struct ast_variable *copy_vars(struct ast_variable *src);
1334
static int dialog_find_multiple(void *obj, void *arg, int flags);
1334
static int dialog_find_multiple(void *obj, void *arg, int flags);
1335
/* static int sip_addrcmp(char *name, struct sockaddr_in *sin);	Support for peer matching */
1335
/* static int sip_addrcmp(char *name, struct sockaddr_in *sin);	Support for peer matching */
1336
static int sip_refer_allocate(struct sip_pvt *p);
1336
static int sip_refer_allocate(struct sip_pvt *p);
1337
static int sip_notify_allocate(struct sip_pvt *p);
1337
static int sip_notify_allocate(struct sip_pvt *p);
1338
static void ast_quiet_chan(struct ast_channel *chan);
1338
static void ast_quiet_chan(struct ast_channel *chan);
1339
static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1339
static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1340
static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1340
static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1341

    
   
1341

   
1342
/*--- Device monitoring and Device/extension state/event handling */
1342
/*--- Device monitoring and Device/extension state/event handling */
1343
static int cb_extensionstate(char *context, char* exten, int state, void *data);
1343
static int cb_extensionstate(char *context, char* exten, int state, void *data);
1344
static int sip_devicestate(void *data);
1344
static int sip_devicestate(void *data);
1345
static int sip_poke_noanswer(const void *data);
1345
static int sip_poke_noanswer(const void *data);
1346
static int sip_poke_peer(struct sip_peer *peer, int force);
1346
static int sip_poke_peer(struct sip_peer *peer, int force);
1347
static void sip_poke_all_peers(void);
1347
static void sip_poke_all_peers(void);
1348
static void sip_peer_hold(struct sip_pvt *p, int hold);
1348
static void sip_peer_hold(struct sip_pvt *p, int hold);
1349
static void mwi_event_cb(const struct ast_event *, void *);
1349
static void mwi_event_cb(const struct ast_event *, void *);
1350
static void network_change_event_cb(const struct ast_event *, void *);
1350
static void network_change_event_cb(const struct ast_event *, void *);
1351

    
   
1351

   
1352
/*--- Applications, functions, CLI and manager command helpers */
1352
/*--- Applications, functions, CLI and manager command helpers */
1353
static const char *sip_nat_mode(const struct sip_pvt *p);
1353
static const char *sip_nat_mode(const struct sip_pvt *p);
1354
static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1354
static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1355
static char *transfermode2str(enum transfermodes mode) attribute_const;
1355
static char *transfermode2str(enum transfermodes mode) attribute_const;
1356
static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1356
static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1357
static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1357
static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1358
static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1358
static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1359
static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1359
static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1360
static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1360
static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1361
static void  print_group(int fd, ast_group_t group, int crlf);
1361
static void  print_group(int fd, ast_group_t group, int crlf);
1362
static const char *dtmfmode2str(int mode) attribute_const;
1362
static const char *dtmfmode2str(int mode) attribute_const;
1363
static int str2dtmfmode(const char *str) attribute_unused;
1363
static int str2dtmfmode(const char *str) attribute_unused;
1364
static const char *insecure2str(int mode) attribute_const;
1364
static const char *insecure2str(int mode) attribute_const;
1365
static void cleanup_stale_contexts(char *new, char *old);
1365
static void cleanup_stale_contexts(char *new, char *old);
1366
static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1366
static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1367
static const char *domain_mode_to_text(const enum domain_mode mode);
1367
static const char *domain_mode_to_text(const enum domain_mode mode);
1368
static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1368
static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1369
static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1369
static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1370
static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1370
static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1371
static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1371
static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1372
static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1372
static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1373
static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1373
static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1374
static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1374
static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1375
static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1375
static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1376
static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1376
static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1377
static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1377
static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1378
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1378
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1379
static char *complete_sip_peer(const char *word, int state, int flags2);
1379
static char *complete_sip_peer(const char *word, int state, int flags2);
1380
static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1380
static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1381
static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1381
static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1382
static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1382
static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1383
static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1383
static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1384
static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1384
static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1385
static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1385
static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1386
static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1386
static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1387
static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1387
static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1388
static char *sip_do_debug_ip(int fd, const char *arg);
1388
static char *sip_do_debug_ip(int fd, const char *arg);
1389
static char *sip_do_debug_peer(int fd, const char *arg);
1389
static char *sip_do_debug_peer(int fd, const char *arg);
1390
static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1390
static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1391
static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1391
static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1392
static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1392
static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1393
static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1393
static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1394
static int sip_addheader(struct ast_channel *chan, const char *data);
1394
static int sip_addheader(struct ast_channel *chan, const char *data);
1395
static int sip_do_reload(enum channelreloadreason reason);
1395
static int sip_do_reload(enum channelreloadreason reason);
1396
static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1396
static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1397
static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
1397
static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
1398
				      const char *name, int flag, int family);
1398
				      const char *name, int flag, int family);
1399
static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
1399
static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
1400
				      const char *name, int flag);
1400
				      const char *name, int flag);
1401

    
   
1401

   
1402
/*--- Debugging
1402
/*--- Debugging
1403
	Functions for enabling debug per IP or fully, or enabling history logging for
1403
	Functions for enabling debug per IP or fully, or enabling history logging for
1404
	a SIP dialog
1404
	a SIP dialog
1405
*/
1405
*/
1406
static void sip_dump_history(struct sip_pvt *dialog);	/* Dump history to debuglog at end of dialog, before destroying data */
1406
static void sip_dump_history(struct sip_pvt *dialog);	/* Dump history to debuglog at end of dialog, before destroying data */
1407
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
1407
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
1408
static inline int sip_debug_test_pvt(struct sip_pvt *p);
1408
static inline int sip_debug_test_pvt(struct sip_pvt *p);
1409
static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1409
static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1410
static void sip_dump_history(struct sip_pvt *dialog);
1410
static void sip_dump_history(struct sip_pvt *dialog);
1411

    
   
1411

   
1412
/*--- Device object handling */
1412
/*--- Device object handling */
1413
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1413
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1414
static int update_call_counter(struct sip_pvt *fup, int event);
1414
static int update_call_counter(struct sip_pvt *fup, int event);
1415
static void sip_destroy_peer(struct sip_peer *peer);
1415
static void sip_destroy_peer(struct sip_peer *peer);
1416
static void sip_destroy_peer_fn(void *peer);
1416
static void sip_destroy_peer_fn(void *peer);
1417
static void set_peer_defaults(struct sip_peer *peer);
1417
static void set_peer_defaults(struct sip_peer *peer);
1418
static struct sip_peer *temp_peer(const char *name);
1418
static struct sip_peer *temp_peer(const char *name);
1419
static void register_peer_exten(struct sip_peer *peer, int onoff);
1419
static void register_peer_exten(struct sip_peer *peer, int onoff);
1420
static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int forcenamematch, int devstate_only, int transport);
1420
static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int forcenamematch, int devstate_only, int transport);
1421
static int sip_poke_peer_s(const void *data);
1421
static int sip_poke_peer_s(const void *data);
1422
static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1422
static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1423
static void reg_source_db(struct sip_peer *peer);
1423
static void reg_source_db(struct sip_peer *peer);
1424
static void destroy_association(struct sip_peer *peer);
1424
static void destroy_association(struct sip_peer *peer);
1425
static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1425
static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1426
static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1426
static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1427
static void set_socket_transport(struct sip_socket *socket, int transport);
1427
static void set_socket_transport(struct sip_socket *socket, int transport);
1428

    
   
1428

   
1429
/* Realtime device support */
1429
/* Realtime device support */
1430
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);
1430
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);
1431
static void update_peer(struct sip_peer *p, int expire);
1431
static void update_peer(struct sip_peer *p, int expire);
1432
static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1432
static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1433
static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
1433
static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
1434
static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, int devstate_only, int which_objects);
1434
static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, int devstate_only, int which_objects);
1435
static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1435
static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1436

    
   
1436

   
1437
/*--- Internal UA client handling (outbound registrations) */
1437
/*--- Internal UA client handling (outbound registrations) */
1438
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
1438
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
1439
static void sip_registry_destroy(struct sip_registry *reg);
1439
static void sip_registry_destroy(struct sip_registry *reg);
1440
static int sip_register(const char *value, int lineno);
1440
static int sip_register(const char *value, int lineno);
1441
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1441
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1442
static int sip_reregister(const void *data);
1442
static int sip_reregister(const void *data);
1443
static int __sip_do_register(struct sip_registry *r);
1443
static int __sip_do_register(struct sip_registry *r);
1444
static int sip_reg_timeout(const void *data);
1444
static int sip_reg_timeout(const void *data);
1445
static void sip_send_all_registers(void);
1445
static void sip_send_all_registers(void);
1446
static int sip_reinvite_retry(const void *data);
1446
static int sip_reinvite_retry(const void *data);
1447

    
   
1447

   
1448
/*--- Parsing SIP requests and responses */
1448
/*--- Parsing SIP requests and responses */
1449
static void append_date(struct sip_request *req);	/* Append date to SIP packet */
1449
static void append_date(struct sip_request *req);	/* Append date to SIP packet */
1450
static int determine_firstline_parts(struct sip_request *req);
1450
static int determine_firstline_parts(struct sip_request *req);
1451
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1451
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1452
static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1452
static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1453
static int find_sip_method(const char *msg);
1453
static int find_sip_method(const char *msg);
1454
static unsigned int parse_allowed_methods(struct sip_request *req);
1454
static unsigned int parse_allowed_methods(struct sip_request *req);
1455
static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1455
static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1456
static int parse_request(struct sip_request *req);
1456
static int parse_request(struct sip_request *req);
1457
static const char *get_header(const struct sip_request *req, const char *name);
1457
static const char *get_header(const struct sip_request *req, const char *name);
1458
static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1458
static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1459
static int method_match(enum sipmethod id, const char *name);
1459
static int method_match(enum sipmethod id, const char *name);
1460
static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1460
static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1461
static const char *find_alias(const char *name, const char *_default);
1461
static const char *find_alias(const char *name, const char *_default);
1462
static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1462
static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1463
static int lws2sws(char *msgbuf, int len);
1463
static int lws2sws(char *msgbuf, int len);
1464
static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1464
static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1465
static char *remove_uri_parameters(char *uri);
1465
static char *remove_uri_parameters(char *uri);
1466
static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1466
static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1467
static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1467
static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1468
static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1468
static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1469
static int set_address_from_contact(struct sip_pvt *pvt);
1469
static int set_address_from_contact(struct sip_pvt *pvt);
1470
static void check_via(struct sip_pvt *p, struct sip_request *req);
1470
static void check_via(struct sip_pvt *p, struct sip_request *req);
1471
static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1471
static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1472
static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
1472
static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
1473
static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1473
static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1474
static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
1474
static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
1475
static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1475
static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1476
static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1476
static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1477
static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1477
static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1478
static int get_domain(const char *str, char *domain, int len);
1478
static int get_domain(const char *str, char *domain, int len);
1479
static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1479
static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1480

    
   
1480

   
1481
/*-- TCP connection handling ---*/
1481
/*-- TCP connection handling ---*/
1482
static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
1482
static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
1483
static void *sip_tcp_worker_fn(void *);
1483
static void *sip_tcp_worker_fn(void *);
1484

    
   
1484

   
1485
/*--- Constructing requests and responses */
1485
/*--- Constructing requests and responses */
1486
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1486
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1487
static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1487
static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1488
static void deinit_req(struct sip_request *req);
1488
static void deinit_req(struct sip_request *req);
1489
static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1489
static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1490
static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1490
static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1491
static int init_resp(struct sip_request *resp, const char *msg);
1491
static int init_resp(struct sip_request *resp, const char *msg);
1492
static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1492
static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1493
static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1493
static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1494
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
1494
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
1495
static void build_via(struct sip_pvt *p);
1495
static void build_via(struct sip_pvt *p);
1496
static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1496
static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1497
static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address);
1497
static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address);
1498
static char *generate_random_string(char *buf, size_t size);
1498
static char *generate_random_string(char *buf, size_t size);
1499
static void build_callid_pvt(struct sip_pvt *pvt);
1499
static void build_callid_pvt(struct sip_pvt *pvt);
1500
static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
1500
static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
1501
static void make_our_tag(char *tagbuf, size_t len);
1501
static void make_our_tag(char *tagbuf, size_t len);
1502
static int add_header(struct sip_request *req, const char *var, const char *value);
1502
static int add_header(struct sip_request *req, const char *var, const char *value);
1503
static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
1503
static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
1504
static int add_content(struct sip_request *req, const char *line);
1504
static int add_content(struct sip_request *req, const char *line);
1505
static int finalize_content(struct sip_request *req);
1505
static int finalize_content(struct sip_request *req);
1506
static int add_text(struct sip_request *req, const char *text);
1506
static int add_text(struct sip_request *req, const char *text);
1507
static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1507
static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1508
static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1508
static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1509
static int add_vidupdate(struct sip_request *req);
1509
static int add_vidupdate(struct sip_request *req);
1510
static void add_route(struct sip_request *req, struct sip_route *route);
1510
static void add_route(struct sip_request *req, struct sip_route *route);
1511
static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1511
static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1512
static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1512
static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1513
static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1513
static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1514
static void set_destination(struct sip_pvt *p, char *uri);
1514
static void set_destination(struct sip_pvt *p, char *uri);
1515
static void append_date(struct sip_request *req);
1515
static void append_date(struct sip_request *req);
1516
static void build_contact(struct sip_pvt *p);
1516
static void build_contact(struct sip_pvt *p);
1517

    
   
1517

   
1518
/*------Request handling functions */
1518
/*------Request handling functions */
1519
static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
1519
static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
1520
static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1520
static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1521
static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *recount, const char *e, int *nounlock);
1521
static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *recount, const char *e, int *nounlock);
1522
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1522
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1523
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1523
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1524
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
1524
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
1525
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1525
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1526
static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1526
static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1527
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
1527
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
1528
static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1528
static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1529
static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1529
static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1530
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *nounlock);
1530
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *nounlock);
1531
static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
1531
static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
1532
static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno, int *nounlock);
1532
static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno, int *nounlock);
1533

    
   
1533

   
1534
/*------Response handling functions */
1534
/*------Response handling functions */
1535
static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1535
static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1536
static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1536
static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1537
static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1537
static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1538
static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1538
static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1539
static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1539
static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1540
static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1540
static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1541
static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1541
static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1542

    
   
1542

   
1543
/*------ SRTP Support -------- */
1543
/*------ SRTP Support -------- */
1544
static int setup_srtp(struct sip_srtp **srtp);
1544
static int setup_srtp(struct sip_srtp **srtp);
1545
static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
1545
static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
1546

    
   
1546

   
1547
/*------ T38 Support --------- */
1547
/*------ T38 Support --------- */
1548
static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1548
static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1549
static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1549
static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1550
static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1550
static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1551
static void change_t38_state(struct sip_pvt *p, int state);
1551
static void change_t38_state(struct sip_pvt *p, int state);
1552

    
   
1552

   
1553
/*------ Session-Timers functions --------- */
1553
/*------ Session-Timers functions --------- */
1554
static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1554
static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1555
static int  proc_session_timer(const void *vp);
1555
static int  proc_session_timer(const void *vp);
1556
static void stop_session_timer(struct sip_pvt *p);
1556
static void stop_session_timer(struct sip_pvt *p);
1557
static void start_session_timer(struct sip_pvt *p);
1557
static void start_session_timer(struct sip_pvt *p);
1558
static void restart_session_timer(struct sip_pvt *p);
1558
static void restart_session_timer(struct sip_pvt *p);
1559
static const char *strefresher2str(enum st_refresher r);
1559
static const char *strefresher2str(enum st_refresher r);
1560
static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
1560
static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
1561
static int parse_minse(const char *p_hdrval, int *const p_interval);
1561
static int parse_minse(const char *p_hdrval, int *const p_interval);
1562
static int st_get_se(struct sip_pvt *, int max);
1562
static int st_get_se(struct sip_pvt *, int max);
1563
static enum st_refresher st_get_refresher(struct sip_pvt *);
1563
static enum st_refresher st_get_refresher(struct sip_pvt *);
1564
static enum st_mode st_get_mode(struct sip_pvt *);
1564
static enum st_mode st_get_mode(struct sip_pvt *);
1565
static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1565
static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1566

    
   
1566

   
1567
/*------- RTP Glue functions -------- */
1567
/*------- RTP Glue functions -------- */
1568
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);
1568
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);
1569

    
   
1569

   
1570
/*!--- SIP MWI Subscription support */
1570
/*!--- SIP MWI Subscription support */
1571
static int sip_subscribe_mwi(const char *value, int lineno);
1571
static int sip_subscribe_mwi(const char *value, int lineno);
1572
static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
1572
static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
1573
static void sip_send_all_mwi_subscriptions(void);
1573
static void sip_send_all_mwi_subscriptions(void);
1574
static int sip_subscribe_mwi_do(const void *data);
1574
static int sip_subscribe_mwi_do(const void *data);
1575
static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1575
static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1576

    
   
1576

   
1577
/*! \brief Definition of this channel for PBX channel registration */
1577
/*! \brief Definition of this channel for PBX channel registration */
1578
struct ast_channel_tech sip_tech = {
1578
struct ast_channel_tech sip_tech = {
1579
	.type = "SIP",
1579
	.type = "SIP",
1580
	.description = "Session Initiation Protocol (SIP)",
1580
	.description = "Session Initiation Protocol (SIP)",
1581
	.properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1581
	.properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1582
	.requester = sip_request_call,			/* called with chan unlocked */
1582
	.requester = sip_request_call,			/* called with chan unlocked */
1583
	.devicestate = sip_devicestate,			/* called with chan unlocked (not chan-specific) */
1583
	.devicestate = sip_devicestate,			/* called with chan unlocked (not chan-specific) */
1584
	.call = sip_call,			/* called with chan locked */
1584
	.call = sip_call,			/* called with chan locked */
1585
	.send_html = sip_sendhtml,
1585
	.send_html = sip_sendhtml,
1586
	.hangup = sip_hangup,			/* called with chan locked */
1586
	.hangup = sip_hangup,			/* called with chan locked */
1587
	.answer = sip_answer,			/* called with chan locked */
1587
	.answer = sip_answer,			/* called with chan locked */
1588
	.read = sip_read,			/* called with chan locked */
1588
	.read = sip_read,			/* called with chan locked */
1589
	.write = sip_write,			/* called with chan locked */
1589
	.write = sip_write,			/* called with chan locked */
1590
	.write_video = sip_write,		/* called with chan locked */
1590
	.write_video = sip_write,		/* called with chan locked */
1591
	.write_text = sip_write,
1591
	.write_text = sip_write,
1592
	.indicate = sip_indicate,		/* called with chan locked */
1592
	.indicate = sip_indicate,		/* called with chan locked */
1593
	.transfer = sip_transfer,		/* called with chan locked */
1593
	.transfer = sip_transfer,		/* called with chan locked */
1594
	.fixup = sip_fixup,			/* called with chan locked */
1594
	.fixup = sip_fixup,			/* called with chan locked */
1595
	.send_digit_begin = sip_senddigit_begin,	/* called with chan unlocked */
1595
	.send_digit_begin = sip_senddigit_begin,	/* called with chan unlocked */
1596
	.send_digit_end = sip_senddigit_end,
1596
	.send_digit_end = sip_senddigit_end,
1597
	.bridge = ast_rtp_instance_bridge,			/* XXX chan unlocked ? */
1597
	.bridge = ast_rtp_instance_bridge,			/* XXX chan unlocked ? */
1598
	.early_bridge = ast_rtp_instance_early_bridge,
1598
	.early_bridge = ast_rtp_instance_early_bridge,
1599
	.send_text = sip_sendtext,		/* called with chan locked */
1599
	.send_text = sip_sendtext,		/* called with chan locked */
1600
	.func_channel_read = sip_acf_channel_read,
1600
	.func_channel_read = sip_acf_channel_read,
1601
	.setoption = sip_setoption,
1601
	.setoption = sip_setoption,
1602
	.queryoption = sip_queryoption,
1602
	.queryoption = sip_queryoption,
1603
	.get_pvt_uniqueid = sip_get_callid,
1603
	.get_pvt_uniqueid = sip_get_callid,
1604
};
1604
};
1605

    
   
1605

   
1606
/*! \brief This version of the sip channel tech has no send_digit_begin
1606
/*! \brief This version of the sip channel tech has no send_digit_begin
1607
 * callback so that the core knows that the channel does not want
1607
 * callback so that the core knows that the channel does not want
1608
 * DTMF BEGIN frames.
1608
 * DTMF BEGIN frames.
1609
 * The struct is initialized just before registering the channel driver,
1609
 * The struct is initialized just before registering the channel driver,
1610
 * and is for use with channels using SIP INFO DTMF.
1610
 * and is for use with channels using SIP INFO DTMF.
1611
 */
1611
 */
1612
struct ast_channel_tech sip_tech_info;
1612
struct ast_channel_tech sip_tech_info;
1613

    
   
1613

   
1614
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1614
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1615
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1615
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1616
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1616
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1617
static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
1617
static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
1618
static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
1618
static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
1619
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1619
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1620
static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1620
static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1621
static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1621
static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1622

    
   
1622

   
1623
static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
1623
static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
1624
	.type = "SIP",
1624
	.type = "SIP",
1625
	.init = sip_cc_agent_init,
1625
	.init = sip_cc_agent_init,
1626
	.start_offer_timer = sip_cc_agent_start_offer_timer,
1626
	.start_offer_timer = sip_cc_agent_start_offer_timer,
1627
	.stop_offer_timer = sip_cc_agent_stop_offer_timer,
1627
	.stop_offer_timer = sip_cc_agent_stop_offer_timer,
1628
	.respond = sip_cc_agent_respond,
1628
	.respond = sip_cc_agent_respond,
1629
	.status_request = sip_cc_agent_status_request,
1629
	.status_request = sip_cc_agent_status_request,
1630
	.start_monitoring = sip_cc_agent_start_monitoring,
1630
	.start_monitoring = sip_cc_agent_start_monitoring,
1631
	.callee_available = sip_cc_agent_recall,
1631
	.callee_available = sip_cc_agent_recall,
1632
	.destructor = sip_cc_agent_destructor,
1632
	.destructor = sip_cc_agent_destructor,
1633
};
1633
};
1634

    
   
1634

   
1635
static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
1635
static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
1636
{
1636
{
1637
	struct ast_cc_agent *agent = obj;
1637
	struct ast_cc_agent *agent = obj;
1638
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1638
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1639
	const char *uri = arg;
1639
	const char *uri = arg;
1640

    
   
1640

   
1641
	return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1641
	return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1642
}
1642
}
1643

    
   
1643

   
1644
static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
1644
static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
1645
{
1645
{
1646
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
1646
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
1647
	return agent;
1647
	return agent;
1648
}
1648
}
1649

    
   
1649

   
1650
static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
1650
static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
1651
{
1651
{
1652
	struct ast_cc_agent *agent = obj;
1652
	struct ast_cc_agent *agent = obj;
1653
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1653
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1654
	const char *uri = arg;
1654
	const char *uri = arg;
1655

    
   
1655

   
1656
	return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1656
	return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1657
}
1657
}
1658

    
   
1658

   
1659
static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
1659
static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
1660
{
1660
{
1661
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
1661
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
1662
	return agent;
1662
	return agent;
1663
}
1663
}
1664

    
   
1664

   
1665
static int find_by_callid_helper(void *obj, void *arg, int flags)
1665
static int find_by_callid_helper(void *obj, void *arg, int flags)
1666
{
1666
{
1667
	struct ast_cc_agent *agent = obj;
1667
	struct ast_cc_agent *agent = obj;
1668
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1668
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1669
	struct sip_pvt *call_pvt = arg;
1669
	struct sip_pvt *call_pvt = arg;
1670

    
   
1670

   
1671
	return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
1671
	return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
1672
}
1672
}
1673

    
   
1673

   
1674
static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
1674
static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
1675
{
1675
{
1676
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
1676
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
1677
	return agent;
1677
	return agent;
1678
}
1678
}
1679

    
   
1679

   
1680
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
1680
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
1681
{
1681
{
1682
	struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
1682
	struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
1683
	struct sip_pvt *call_pvt = chan->tech_pvt;
1683
	struct sip_pvt *call_pvt = chan->tech_pvt;
1684

    
   
1684

   
1685
	if (!agent_pvt) {
1685
	if (!agent_pvt) {
1686
		return -1;
1686
		return -1;
1687
	}
1687
	}
1688

    
   
1688

   
1689
	ast_assert(!strcmp(chan->tech->type, "SIP"));
1689
	ast_assert(!strcmp(chan->tech->type, "SIP"));
1690

    
   
1690

   
1691
	ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
1691
	ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
1692
	ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
1692
	ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
1693
	agent_pvt->offer_timer_id = -1;
1693
	agent_pvt->offer_timer_id = -1;
1694
	agent->private_data = agent_pvt;
1694
	agent->private_data = agent_pvt;
1695
	sip_pvt_lock(call_pvt);
1695
	sip_pvt_lock(call_pvt);
1696
	ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1696
	ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1697
	sip_pvt_unlock(call_pvt);
1697
	sip_pvt_unlock(call_pvt);
1698
	return 0;
1698
	return 0;
1699
}
1699
}
1700

    
   
1700

   
1701
static int sip_offer_timer_expire(const void *data)
1701
static int sip_offer_timer_expire(const void *data)
1702
{
1702
{
1703
	struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
1703
	struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
1704
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1704
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1705

    
   
1705

   
1706
	agent_pvt->offer_timer_id = -1;
1706
	agent_pvt->offer_timer_id = -1;
1707

    
   
1707

   
1708
	return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
1708
	return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
1709
}
1709
}
1710

    
   
1710

   
1711
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
1711
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
1712
{
1712
{
1713
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1713
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1714
	int when;
1714
	int when;
1715

    
   
1715

   
1716
	when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1716
	when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1717
	agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
1717
	agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
1718
	return 0;
1718
	return 0;
1719
}
1719
}
1720

    
   
1720

   
1721
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
1721
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
1722
{
1722
{
1723
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1723
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1724

    
   
1724

   
1725
	AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1725
	AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1726
	return 0;
1726
	return 0;
1727
}
1727
}
1728

    
   
1728

   
1729
static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
1729
static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
1730
{
1730
{
1731
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1731
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1732

    
   
1732

   
1733
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1733
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1734
	ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
1734
	ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
1735
	if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
1735
	if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
1736
		/* The second half of this if statement may be a bit hard to grasp,
1736
		/* The second half of this if statement may be a bit hard to grasp,
1737
		 * so here's an explanation. When a subscription comes into
1737
		 * so here's an explanation. When a subscription comes into
1738
		 * chan_sip, as long as it is not malformed, it will be passed
1738
		 * chan_sip, as long as it is not malformed, it will be passed
1739
		 * to the CC core. If the core senses an out-of-order state transition,
1739
		 * to the CC core. If the core senses an out-of-order state transition,
1740
		 * then the core will call this callback with the "reason" set to a
1740
		 * then the core will call this callback with the "reason" set to a
1741
		 * failure condition.
1741
		 * failure condition.
1742
		 * However, an out-of-order state transition will occur during a resubscription
1742
		 * However, an out-of-order state transition will occur during a resubscription
1743
		 * for CC. In such a case, we can see that we have already generated a notify_uri
1743
		 * for CC. In such a case, we can see that we have already generated a notify_uri
1744
		 * and so we can detect that this isn't a *real* failure. Rather, it is just
1744
		 * and so we can detect that this isn't a *real* failure. Rather, it is just
1745
		 * something the core doesn't recognize as a legitimate SIP state transition.
1745
		 * something the core doesn't recognize as a legitimate SIP state transition.
1746
		 * Thus we respond with happiness and flowers.
1746
		 * Thus we respond with happiness and flowers.
1747
		 */
1747
		 */
1748
		transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1748
		transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1749
		transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1749
		transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1750
	} else {
1750
	} else {
1751
		transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
1751
		transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
1752
	}
1752
	}
1753
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1753
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1754
	agent_pvt->is_available = TRUE;
1754
	agent_pvt->is_available = TRUE;
1755
}
1755
}
1756

    
   
1756

   
1757
static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
1757
static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
1758
{
1758
{
1759
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1759
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1760
	enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
1760
	enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
1761
	return ast_cc_agent_status_response(agent->core_id, state);
1761
	return ast_cc_agent_status_response(agent->core_id, state);
1762
}
1762
}
1763

    
   
1763

   
1764
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
1764
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
1765
{
1765
{
1766
	/* To start monitoring just means to wait for an incoming PUBLISH
1766
	/* To start monitoring just means to wait for an incoming PUBLISH
1767
	 * to tell us that the caller has become available again. No special
1767
	 * to tell us that the caller has become available again. No special
1768
	 * action is needed
1768
	 * action is needed
1769
	 */
1769
	 */
1770
	return 0;
1770
	return 0;
1771
}
1771
}
1772

    
   
1772

   
1773
static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1773
static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1774
{
1774
{
1775
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1775
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1776
	/* If we have received a PUBLISH beforehand stating that the caller in question
1776
	/* If we have received a PUBLISH beforehand stating that the caller in question
1777
	 * is not available, we can save ourself a bit of effort here and just report
1777
	 * is not available, we can save ourself a bit of effort here and just report
1778
	 * the caller as busy
1778
	 * the caller as busy
1779
	 */
1779
	 */
1780
	if (!agent_pvt->is_available) {
1780
	if (!agent_pvt->is_available) {
1781
		return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
1781
		return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
1782
				agent->device_name);
1782
				agent->device_name);
1783
	}
1783
	}
1784
	/* Otherwise, we transmit a NOTIFY to the caller and await either
1784
	/* Otherwise, we transmit a NOTIFY to the caller and await either
1785
	 * a PUBLISH or an INVITE
1785
	 * a PUBLISH or an INVITE
1786
	 */
1786
	 */
1787
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1787
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1788
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1788
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1789
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1789
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1790
	return 0;
1790
	return 0;
1791
}
1791
}
1792

    
   
1792

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

    
   
1796

   
1797
	if (!agent_pvt) {
1797
	if (!agent_pvt) {
1798
		/* The agent constructor probably failed. */
1798
		/* The agent constructor probably failed. */
1799
		return;
1799
		return;
1800
	}
1800
	}
1801

    
   
1801

   
1802
	sip_cc_agent_stop_offer_timer(agent);
1802
	sip_cc_agent_stop_offer_timer(agent);
1803
	if (agent_pvt->subscribe_pvt) {
1803
	if (agent_pvt->subscribe_pvt) {
1804
		sip_pvt_lock(agent_pvt->subscribe_pvt);
1804
		sip_pvt_lock(agent_pvt->subscribe_pvt);
1805
		if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
1805
		if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
1806
			/* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
1806
			/* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
1807
			 * the subscriber know something went wrong
1807
			 * the subscriber know something went wrong
1808
			 */
1808
			 */
1809
			transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
1809
			transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
1810
		}
1810
		}
1811
		sip_pvt_unlock(agent_pvt->subscribe_pvt);
1811
		sip_pvt_unlock(agent_pvt->subscribe_pvt);
1812
		agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
1812
		agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
1813
	}
1813
	}
1814
	ast_free(agent_pvt);
1814
	ast_free(agent_pvt);
1815
}
1815
}
1816

    
   
1816

   
1817
struct ao2_container *sip_monitor_instances;
1817
struct ao2_container *sip_monitor_instances;
1818

    
   
1818

   
1819
static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
1819
static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
1820
{
1820
{
1821
	const struct sip_monitor_instance *monitor_instance = obj;
1821
	const struct sip_monitor_instance *monitor_instance = obj;
1822
	return monitor_instance->core_id;
1822
	return monitor_instance->core_id;
1823
}
1823
}
1824

    
   
1824

   
1825
static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
1825
static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
1826
{
1826
{
1827
	struct sip_monitor_instance *monitor_instance1 = obj;
1827
	struct sip_monitor_instance *monitor_instance1 = obj;
1828
	struct sip_monitor_instance *monitor_instance2 = arg;
1828
	struct sip_monitor_instance *monitor_instance2 = arg;
1829

    
   
1829

   
1830
	return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
1830
	return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
1831
}
1831
}
1832

    
   
1832

   
1833
static void sip_monitor_instance_destructor(void *data)
1833
static void sip_monitor_instance_destructor(void *data)
1834
{
1834
{
1835
	struct sip_monitor_instance *monitor_instance = data;
1835
	struct sip_monitor_instance *monitor_instance = data;
1836
	if (monitor_instance->subscription_pvt) {
1836
	if (monitor_instance->subscription_pvt) {
1837
		sip_pvt_lock(monitor_instance->subscription_pvt);
1837
		sip_pvt_lock(monitor_instance->subscription_pvt);
1838
		monitor_instance->subscription_pvt->expiry = 0;
1838
		monitor_instance->subscription_pvt->expiry = 0;
1839
		transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
1839
		transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
1840
		sip_pvt_unlock(monitor_instance->subscription_pvt);
1840
		sip_pvt_unlock(monitor_instance->subscription_pvt);
1841
		dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
1841
		dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
1842
	}
1842
	}
1843
	if (monitor_instance->suspension_entry) {
1843
	if (monitor_instance->suspension_entry) {
1844
		monitor_instance->suspension_entry->body[0] = '\0';
1844
		monitor_instance->suspension_entry->body[0] = '\0';
1845
		transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
1845
		transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
1846
		ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
1846
		ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
1847
	}
1847
	}
1848
	ast_string_field_free_memory(monitor_instance);
1848
	ast_string_field_free_memory(monitor_instance);
1849
}
1849
}
1850

    
   
1850

   
1851
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)
1851
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)
1852
{
1852
{
1853
	struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
1853
	struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
1854

    
   
1854

   
1855
	if (!monitor_instance) {
1855
	if (!monitor_instance) {
1856
		return NULL;
1856
		return NULL;
1857
	}
1857
	}
1858

    
   
1858

   
1859
	if (ast_string_field_init(monitor_instance, 256)) {
1859
	if (ast_string_field_init(monitor_instance, 256)) {
1860
		ao2_ref(monitor_instance, -1);
1860
		ao2_ref(monitor_instance, -1);
1861
		return NULL;
1861
		return NULL;
1862
	}
1862
	}
1863

    
   
1863

   
1864
	ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
1864
	ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
1865
	ast_string_field_set(monitor_instance, peername, peername);
1865
	ast_string_field_set(monitor_instance, peername, peername);
1866
	ast_string_field_set(monitor_instance, device_name, device_name);
1866
	ast_string_field_set(monitor_instance, device_name, device_name);
1867
	monitor_instance->core_id = core_id;
1867
	monitor_instance->core_id = core_id;
1868
	ao2_link(sip_monitor_instances, monitor_instance);
1868
	ao2_link(sip_monitor_instances, monitor_instance);
1869
	return monitor_instance;
1869
	return monitor_instance;
1870
}
1870
}
1871

    
   
1871

   
1872
static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
1872
static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
1873
{
1873
{
1874
	struct sip_monitor_instance *monitor_instance = obj;
1874
	struct sip_monitor_instance *monitor_instance = obj;
1875
	return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
1875
	return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
1876
}
1876
}
1877

    
   
1877

   
1878
static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
1878
static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
1879
{
1879
{
1880
	struct sip_monitor_instance *monitor_instance = obj;
1880
	struct sip_monitor_instance *monitor_instance = obj;
1881
	return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
1881
	return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
1882
}
1882
}
1883

    
   
1883

   
1884
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
1884
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
1885
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
1885
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
1886
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
1886
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
1887
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
1887
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
1888
static void sip_cc_monitor_destructor(void *private_data);
1888
static void sip_cc_monitor_destructor(void *private_data);
1889

    
   
1889

   
1890
static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
1890
static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
1891
	.type = "SIP",
1891
	.type = "SIP",
1892
	.request_cc = sip_cc_monitor_request_cc,
1892
	.request_cc = sip_cc_monitor_request_cc,
1893
	.suspend = sip_cc_monitor_suspend,
1893
	.suspend = sip_cc_monitor_suspend,
1894
	.unsuspend = sip_cc_monitor_unsuspend,
1894
	.unsuspend = sip_cc_monitor_unsuspend,
1895
	.cancel_available_timer = sip_cc_monitor_cancel_available_timer,
1895
	.cancel_available_timer = sip_cc_monitor_cancel_available_timer,
1896
	.destructor = sip_cc_monitor_destructor,
1896
	.destructor = sip_cc_monitor_destructor,
1897
};
1897
};
1898

    
   
1898

   
1899
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
1899
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
1900
{
1900
{
1901
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1901
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1902
	enum ast_cc_service_type service = monitor->service_offered;
1902
	enum ast_cc_service_type service = monitor->service_offered;
1903
	int when;
1903
	int when;
1904

    
   
1904

   
1905
	if (!monitor_instance) {
1905
	if (!monitor_instance) {
1906
		return -1;
1906
		return -1;
1907
	}
1907
	}
1908

    
   
1908

   
1909
	if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
1909
	if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
1910
		return -1;
1910
		return -1;
1911
	}
1911
	}
1912

    
   
1912

   
1913
	when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
1913
	when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
1914
		ast_get_ccnr_available_timer(monitor->interface->config_params);
1914
		ast_get_ccnr_available_timer(monitor->interface->config_params);
1915

    
   
1915

   
1916
	sip_pvt_lock(monitor_instance->subscription_pvt);
1916
	sip_pvt_lock(monitor_instance->subscription_pvt);
1917
	create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
1917
	create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
1918
	ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
1918
	ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
1919
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1919
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1920
	monitor_instance->subscription_pvt->expiry = when;
1920
	monitor_instance->subscription_pvt->expiry = when;
1921

    
   
1921

   
1922
	transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
1922
	transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
1923
	sip_pvt_unlock(monitor_instance->subscription_pvt);
1923
	sip_pvt_unlock(monitor_instance->subscription_pvt);
1924

    
   
1924

   
1925
	ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
1925
	ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
1926
	*available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
1926
	*available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
1927
	return 0;
1927
	return 0;
1928
}
1928
}
1929

    
   
1929

   
1930
static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
1930
static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
1931
{
1931
{
1932
	struct ast_str *body = ast_str_alloca(size);
1932
	struct ast_str *body = ast_str_alloca(size);
1933
	char tuple_id[32];
1933
	char tuple_id[32];
1934

    
   
1934

   
1935
	generate_random_string(tuple_id, sizeof(tuple_id));
1935
	generate_random_string(tuple_id, sizeof(tuple_id));
1936

    
   
1936

   
1937
	/* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
1937
	/* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
1938
	 * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
1938
	 * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
1939
	 */
1939
	 */
1940
	ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1940
	ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1941
	/* XXX The entity attribute is currently set to the peer name associated with the
1941
	/* XXX The entity attribute is currently set to the peer name associated with the
1942
	 * dialog. This is because we currently only call this function for call-completion
1942
	 * dialog. This is because we currently only call this function for call-completion
1943
	 * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
1943
	 * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
1944
	 * event packages, it may be crucial to have a proper URI as the presentity so this
1944
	 * event packages, it may be crucial to have a proper URI as the presentity so this
1945
	 * should be revisited as support is expanded.
1945
	 * should be revisited as support is expanded.
1946
	 */
1946
	 */
1947
	ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
1947
	ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
1948
	ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
1948
	ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
1949
	ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
1949
	ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
1950
	ast_str_append(&body, 0, "</tuple>\n");
1950
	ast_str_append(&body, 0, "</tuple>\n");
1951
	ast_str_append(&body, 0, "</presence>\n");
1951
	ast_str_append(&body, 0, "</presence>\n");
1952
	ast_copy_string(pidf_body, ast_str_buffer(body), size);
1952
	ast_copy_string(pidf_body, ast_str_buffer(body), size);
1953
	return 0;
1953
	return 0;
1954
}
1954
}
1955

    
   
1955

   
1956
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
1956
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
1957
{
1957
{
1958
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1958
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1959
	enum sip_publish_type publish_type;
1959
	enum sip_publish_type publish_type;
1960
	struct cc_epa_entry *cc_entry;
1960
	struct cc_epa_entry *cc_entry;
1961

    
   
1961

   
1962
	if (!monitor_instance) {
1962
	if (!monitor_instance) {
1963
		return -1;
1963
		return -1;
1964
	}
1964
	}
1965

    
   
1965

   
1966
	if (!monitor_instance->suspension_entry) {
1966
	if (!monitor_instance->suspension_entry) {
1967
		/* We haven't yet allocated the suspension entry, so let's give it a shot */
1967
		/* We haven't yet allocated the suspension entry, so let's give it a shot */
1968
		if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
1968
		if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
1969
			ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
1969
			ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
1970
			ao2_ref(monitor_instance, -1);
1970
			ao2_ref(monitor_instance, -1);
1971
			return -1;
1971
			return -1;
1972
		}
1972
		}
1973
		if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
1973
		if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
1974
			ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
1974
			ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
1975
			ao2_ref(monitor_instance, -1);
1975
			ao2_ref(monitor_instance, -1);
1976
			return -1;
1976
			return -1;
1977
		}
1977
		}
1978
		cc_entry->core_id = monitor->core_id;
1978
		cc_entry->core_id = monitor->core_id;
1979
		monitor_instance->suspension_entry->instance_data = cc_entry;
1979
		monitor_instance->suspension_entry->instance_data = cc_entry;
1980
		publish_type = SIP_PUBLISH_INITIAL;
1980
		publish_type = SIP_PUBLISH_INITIAL;
1981
	} else {
1981
	} else {
1982
		publish_type = SIP_PUBLISH_MODIFY;
1982
		publish_type = SIP_PUBLISH_MODIFY;
1983
		cc_entry = monitor_instance->suspension_entry->instance_data;
1983
		cc_entry = monitor_instance->suspension_entry->instance_data;
1984
	}
1984
	}
1985

    
   
1985

   
1986
	cc_entry->current_state = CC_CLOSED;
1986
	cc_entry->current_state = CC_CLOSED;
1987

    
   
1987

   
1988
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
1988
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
1989
		/* If we have no set notify_uri, then what this means is that we have
1989
		/* If we have no set notify_uri, then what this means is that we have
1990
		 * not received a NOTIFY from this destination stating that he is
1990
		 * not received a NOTIFY from this destination stating that he is
1991
		 * currently available.
1991
		 * currently available.
1992
		 *
1992
		 *
1993
		 * This situation can arise when the core calls the suspend callbacks
1993
		 * This situation can arise when the core calls the suspend callbacks
1994
		 * of multiple destinations. If one of the other destinations aside
1994
		 * of multiple destinations. If one of the other destinations aside
1995
		 * from this one notified Asterisk that he is available, then there
1995
		 * from this one notified Asterisk that he is available, then there
1996
		 * is no reason to take any suspension action on this device. Rather,
1996
		 * is no reason to take any suspension action on this device. Rather,
1997
		 * we should return now and if we receive a NOTIFY while monitoring
1997
		 * we should return now and if we receive a NOTIFY while monitoring
1998
		 * is still "suspended" then we can immediately respond with the
1998
		 * is still "suspended" then we can immediately respond with the
1999
		 * proper PUBLISH to let this endpoint know what is going on.
1999
		 * proper PUBLISH to let this endpoint know what is going on.
2000
		 */
2000
		 */
2001
		return 0;
2001
		return 0;
2002
	}
2002
	}
2003
	construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2003
	construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2004
	return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
2004
	return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
2005
}
2005
}
2006

    
   
2006

   
2007
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
2007
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
2008
{
2008
{
2009
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
2009
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
2010
	struct cc_epa_entry *cc_entry;
2010
	struct cc_epa_entry *cc_entry;
2011

    
   
2011

   
2012
	if (!monitor_instance) {
2012
	if (!monitor_instance) {
2013
		return -1;
2013
		return -1;
2014
	}
2014
	}
2015

    
   
2015

   
2016
	ast_assert(monitor_instance->suspension_entry != NULL);
2016
	ast_assert(monitor_instance->suspension_entry != NULL);
2017

    
   
2017

   
2018
	cc_entry = monitor_instance->suspension_entry->instance_data;
2018
	cc_entry = monitor_instance->suspension_entry->instance_data;
2019
	cc_entry->current_state = CC_OPEN;
2019
	cc_entry->current_state = CC_OPEN;
2020
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
2020
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
2021
		/* This means we are being asked to unsuspend a call leg we never
2021
		/* This means we are being asked to unsuspend a call leg we never
2022
		 * sent a PUBLISH on. As such, there is no reason to send another
2022
		 * sent a PUBLISH on. As such, there is no reason to send another
2023
		 * PUBLISH at this point either. We can just return instead.
2023
		 * PUBLISH at this point either. We can just return instead.
2024
		 */
2024
		 */
2025
		return 0;
2025
		return 0;
2026
	}
2026
	}
2027
	construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2027
	construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2028
	return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
2028
	return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
2029
}
2029
}
2030

    
   
2030

   
2031
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
2031
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
2032
{
2032
{
2033
	if (*sched_id != -1) {
2033
	if (*sched_id != -1) {
2034
		AST_SCHED_DEL(sched, *sched_id);
2034
		AST_SCHED_DEL(sched, *sched_id);
2035
		ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
2035
		ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
2036
	}
2036
	}
2037
	return 0;
2037
	return 0;
2038
}
2038
}
2039

    
   
2039

   
2040
static void sip_cc_monitor_destructor(void *private_data)
2040
static void sip_cc_monitor_destructor(void *private_data)
2041
{
2041
{
2042
	struct sip_monitor_instance *monitor_instance = private_data;
2042
	struct sip_monitor_instance *monitor_instance = private_data;
2043
	ao2_unlink(sip_monitor_instances, monitor_instance);
2043
	ao2_unlink(sip_monitor_instances, monitor_instance);
2044
	ast_module_unref(ast_module_info->self);
2044
	ast_module_unref(ast_module_info->self);
2045
}
2045
}
2046

    
   
2046

   
2047
static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
2047
static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
2048
{
2048
{
2049
	char *call_info = ast_strdupa(get_header(req, "Call-Info"));
2049
	char *call_info = ast_strdupa(get_header(req, "Call-Info"));
2050
	char *uri;
2050
	char *uri;
2051
	char *purpose;
2051
	char *purpose;
2052
	char *service_str;
2052
	char *service_str;
2053
	static const char cc_purpose[] = "purpose=call-completion";
2053
	static const char cc_purpose[] = "purpose=call-completion";
2054
	static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2054
	static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2055

    
   
2055

   
2056
	if (ast_strlen_zero(call_info)) {
2056
	if (ast_strlen_zero(call_info)) {
2057
		/* No Call-Info present. Definitely no CC offer */
2057
		/* No Call-Info present. Definitely no CC offer */
2058
		return -1;
2058
		return -1;
2059
	}
2059
	}
2060

    
   
2060

   
2061
	uri = strsep(&call_info, ";");
2061
	uri = strsep(&call_info, ";");
2062

    
   
2062

   
2063
	while ((purpose = strsep(&call_info, ";"))) {
2063
	while ((purpose = strsep(&call_info, ";"))) {
2064
		if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
2064
		if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
2065
			break;
2065
			break;
2066
		}
2066
		}
2067
	}
2067
	}
2068
	if (!purpose) {
2068
	if (!purpose) {
2069
		/* We didn't find the appropriate purpose= parameter. Oh well */
2069
		/* We didn't find the appropriate purpose= parameter. Oh well */
2070
		return -1;
2070
		return -1;
2071
	}
2071
	}
2072

    
   
2072

   
2073
	/* Okay, call-completion has been offered. Let's figure out what type of service this is */
2073
	/* Okay, call-completion has been offered. Let's figure out what type of service this is */
2074
	while ((service_str = strsep(&call_info, ";"))) {
2074
	while ((service_str = strsep(&call_info, ";"))) {
2075
		if (!strncmp(service_str, "m=", 2)) {
2075
		if (!strncmp(service_str, "m=", 2)) {
2076
			break;
2076
			break;
2077
		}
2077
		}
2078
	}
2078
	}
2079
	if (!service_str) {
2079
	if (!service_str) {
2080
		/* So they didn't offer a particular service, We'll just go with CCBS since it really
2080
		/* So they didn't offer a particular service, We'll just go with CCBS since it really
2081
		 * doesn't matter anyway
2081
		 * doesn't matter anyway
2082
		 */
2082
		 */
2083
		service_str = "BS";
2083
		service_str = "BS";
2084
	} else {
2084
	} else {
2085
		/* We already determined that there is an "m=" so no need to check
2085
		/* We already determined that there is an "m=" so no need to check
2086
		 * the result of this strsep
2086
		 * the result of this strsep
2087
		 */
2087
		 */
2088
		strsep(&service_str, "=");
2088
		strsep(&service_str, "=");
2089
	}
2089
	}
2090

    
   
2090

   
2091
	if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2091
	if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2092
		/* Invalid service offered */
2092
		/* Invalid service offered */
2093
		return -1;
2093
		return -1;
2094
	}
2094
	}
2095

    
   
2095

   
2096
	ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2096
	ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2097

    
   
2097

   
2098
	return 0;
2098
	return 0;
2099
}
2099
}
2100

    
   
2100

   
2101
/*
2101
/*
2102
 * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
2102
 * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
2103
 *
2103
 *
2104
 * After taking care of some formalities to be sure that this call is eligible for CC,
2104
 * After taking care of some formalities to be sure that this call is eligible for CC,
2105
 * we first try to see if we can make use of native CC. We grab the information from
2105
 * we first try to see if we can make use of native CC. We grab the information from
2106
 * the passed-in sip_request (which is always a response to an INVITE). If we can
2106
 * the passed-in sip_request (which is always a response to an INVITE). If we can
2107
 * use native CC monitoring for the call, then so be it.
2107
 * use native CC monitoring for the call, then so be it.
2108
 *
2108
 *
2109
 * If native cc monitoring is not possible or not supported, then we will instead attempt
2109
 * If native cc monitoring is not possible or not supported, then we will instead attempt
2110
 * to use generic monitoring. Falling back to generic from a failed attempt at using native
2110
 * to use generic monitoring. Falling back to generic from a failed attempt at using native
2111
 * monitoring will only work if the monitor policy of the endpoint is "always"
2111
 * monitoring will only work if the monitor policy of the endpoint is "always"
2112
 *
2112
 *
2113
 * \param pvt The current dialog. Contains CC parameters for the endpoint
2113
 * \param pvt The current dialog. Contains CC parameters for the endpoint
2114
 * \param req The response to the INVITE we want to inspect
2114
 * \param req The response to the INVITE we want to inspect
2115
 * \param service The service to use if generic monitoring is to be used. For native
2115
 * \param service The service to use if generic monitoring is to be used. For native
2116
 * monitoring, we get the service from the SIP response itself
2116
 * monitoring, we get the service from the SIP response itself
2117
 */
2117
 */
2118
static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
2118
static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
2119
{
2119
{
2120
	enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
2120
	enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
2121
	int core_id;
2121
	int core_id;
2122
	char interface_name[AST_CHANNEL_NAME];
2122
	char interface_name[AST_CHANNEL_NAME];
2123

    
   
2123

   
2124
	if (monitor_policy == AST_CC_MONITOR_NEVER) {
2124
	if (monitor_policy == AST_CC_MONITOR_NEVER) {
2125
		/* Don't bother, just return */
2125
		/* Don't bother, just return */
2126
		return;
2126
		return;
2127
	}
2127
	}
2128

    
   
2128

   
2129
	if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
2129
	if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
2130
		/* For some reason, CC is invalid, so don't try it! */
2130
		/* For some reason, CC is invalid, so don't try it! */
2131
		return;
2131
		return;
2132
	}
2132
	}
2133

    
   
2133

   
2134
	ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2134
	ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2135

    
   
2135

   
2136
	if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
2136
	if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
2137
		char subscribe_uri[SIPBUFSIZE];
2137
		char subscribe_uri[SIPBUFSIZE];
2138
		char device_name[AST_CHANNEL_NAME];
2138
		char device_name[AST_CHANNEL_NAME];
2139
		enum ast_cc_service_type offered_service;
2139
		enum ast_cc_service_type offered_service;
2140
		struct sip_monitor_instance *monitor_instance;
2140
		struct sip_monitor_instance *monitor_instance;
2141
		if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
2141
		if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
2142
			/* If CC isn't being offered to us, or for some reason the CC offer is
2142
			/* If CC isn't being offered to us, or for some reason the CC offer is
2143
			 * not formatted correctly, then it may still be possible to use generic
2143
			 * not formatted correctly, then it may still be possible to use generic
2144
			 * call completion since the monitor policy may be "always"
2144
			 * call completion since the monitor policy may be "always"
2145
			 */
2145
			 */
2146
			goto generic;
2146
			goto generic;
2147
		}
2147
		}
2148
		ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2148
		ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2149
		if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
2149
		if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
2150
			/* Same deal. We can try using generic still */
2150
			/* Same deal. We can try using generic still */
2151
			goto generic;
2151
			goto generic;
2152
		}
2152
		}
2153
		/* We bump the refcount of chan_sip because once we queue this frame, the CC core
2153
		/* We bump the refcount of chan_sip because once we queue this frame, the CC core
2154
		 * will have a reference to callbacks in this module. We decrement the module
2154
		 * will have a reference to callbacks in this module. We decrement the module
2155
		 * refcount once the monitor destructor is called
2155
		 * refcount once the monitor destructor is called
2156
		 */
2156
		 */
2157
		ast_module_ref(ast_module_info->self);
2157
		ast_module_ref(ast_module_info->self);
2158
		ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
2158
		ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
2159
		ao2_ref(monitor_instance, -1);
2159
		ao2_ref(monitor_instance, -1);
2160
		return;
2160
		return;
2161
	}
2161
	}
2162

    
   
2162

   
2163
generic:
2163
generic:
2164
	if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2164
	if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2165
		ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2165
		ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2166
	}
2166
	}
2167
}
2167
}
2168

    
   
2168

   
2169
/*! \brief Working TLS connection configuration */
2169
/*! \brief Working TLS connection configuration */
2170
static struct ast_tls_config sip_tls_cfg;
2170
static struct ast_tls_config sip_tls_cfg;
2171

    
   
2171

   
2172
/*! \brief Default TLS connection configuration */
2172
/*! \brief Default TLS connection configuration */
2173
static struct ast_tls_config default_tls_cfg;
2173
static struct ast_tls_config default_tls_cfg;
2174

    
   
2174

   
2175
/*! \brief The TCP server definition */
2175
/*! \brief The TCP server definition */
2176
static struct ast_tcptls_session_args sip_tcp_desc = {
2176
static struct ast_tcptls_session_args sip_tcp_desc = {
2177
	.accept_fd = -1,
2177
	.accept_fd = -1,
2178
	.master = AST_PTHREADT_NULL,
2178
	.master = AST_PTHREADT_NULL,
2179
	.tls_cfg = NULL,
2179
	.tls_cfg = NULL,
2180
	.poll_timeout = -1,
2180
	.poll_timeout = -1,
2181
	.name = "SIP TCP server",
2181
	.name = "SIP TCP server",
2182
	.accept_fn = ast_tcptls_server_root,
2182
	.accept_fn = ast_tcptls_server_root,
2183
	.worker_fn = sip_tcp_worker_fn,
2183
	.worker_fn = sip_tcp_worker_fn,
2184
};
2184
};
2185

    
   
2185

   
2186
/*! \brief The TCP/TLS server definition */
2186
/*! \brief The TCP/TLS server definition */
2187
static struct ast_tcptls_session_args sip_tls_desc = {
2187
static struct ast_tcptls_session_args sip_tls_desc = {
2188
	.accept_fd = -1,
2188
	.accept_fd = -1,
2189
	.master = AST_PTHREADT_NULL,
2189
	.master = AST_PTHREADT_NULL,
2190
	.tls_cfg = &sip_tls_cfg,
2190
	.tls_cfg = &sip_tls_cfg,
2191
	.poll_timeout = -1,
2191
	.poll_timeout = -1,
2192
	.name = "SIP TLS server",
2192
	.name = "SIP TLS server",
2193
	.accept_fn = ast_tcptls_server_root,
2193
	.accept_fn = ast_tcptls_server_root,
2194
	.worker_fn = sip_tcp_worker_fn,
2194
	.worker_fn = sip_tcp_worker_fn,
2195
};
2195
};
2196

    
   
2196

   
2197
/*! \brief Append to SIP dialog history
2197
/*! \brief Append to SIP dialog history
2198
	\return Always returns 0 */
2198
	\return Always returns 0 */
2199
#define append_history(p, event, fmt , args... )	append_history_full(p, "%-15s " fmt, event, ## args)
2199
#define append_history(p, event, fmt , args... )	append_history_full(p, "%-15s " fmt, event, ## args)
2200

    
   
2200

   
2201
struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
2201
struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
2202
{
2202
{
2203
	if (p)
2203
	if (p)
2204
#ifdef REF_DEBUG
2204
#ifdef REF_DEBUG
2205
		__ao2_ref_debug(p, 1, tag, file, line, func);
2205
		__ao2_ref_debug(p, 1, tag, file, line, func);
2206
#else
2206
#else
2207
		ao2_ref(p, 1);
2207
		ao2_ref(p, 1);
2208
#endif
2208
#endif
2209
	else
2209
	else
2210
		ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2210
		ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2211
	return p;
2211
	return p;
2212
}
2212
}
2213

    
   
2213

   
2214
struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
2214
struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
2215
{
2215
{
2216
	if (p)
2216
	if (p)
2217
#ifdef REF_DEBUG
2217
#ifdef REF_DEBUG
2218
		__ao2_ref_debug(p, -1, tag, file, line, func);
2218
		__ao2_ref_debug(p, -1, tag, file, line, func);
2219
#else
2219
#else
2220
		ao2_ref(p, -1);
2220
		ao2_ref(p, -1);
2221
#endif
2221
#endif
2222
	return NULL;
2222
	return NULL;
2223
}
2223
}
2224

    
   
2224

   
2225
/*! \brief map from an integer value to a string.
2225
/*! \brief map from an integer value to a string.
2226
 * If no match is found, return errorstring
2226
 * If no match is found, return errorstring
2227
 */
2227
 */
2228
static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2228
static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2229
{
2229
{
2230
	const struct _map_x_s *cur;
2230
	const struct _map_x_s *cur;
2231

    
   
2231

   
2232
	for (cur = table; cur->s; cur++) {
2232
	for (cur = table; cur->s; cur++) {
2233
		if (cur->x == x) {
2233
		if (cur->x == x) {
2234
			return cur->s;
2234
			return cur->s;
2235
		}
2235
		}
2236
	}
2236
	}
2237
	return errorstring;
2237
	return errorstring;
2238
}
2238
}
2239

    
   
2239

   
2240
/*! \brief map from a string to an integer value, case insensitive.
2240
/*! \brief map from a string to an integer value, case insensitive.
2241
 * If no match is found, return errorvalue.
2241
 * If no match is found, return errorvalue.
2242
 */
2242
 */
2243
static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2243
static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2244
{
2244
{
2245
	const struct _map_x_s *cur;
2245
	const struct _map_x_s *cur;
2246

    
   
2246

   
2247
	for (cur = table; cur->s; cur++) {
2247
	for (cur = table; cur->s; cur++) {
2248
		if (!strcasecmp(cur->s, s)) {
2248
		if (!strcasecmp(cur->s, s)) {
2249
			return cur->x;
2249
			return cur->x;
2250
		}
2250
		}
2251
	}
2251
	}
2252
	return errorvalue;
2252
	return errorvalue;
2253
}
2253
}
2254

    
   
2254

   
2255
static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
2255
static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
2256
{
2256
{
2257
	enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2257
	enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2258
	int i;
2258
	int i;
2259

    
   
2259

   
2260
	for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
2260
	for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
2261
		if (!strcasecmp(text, sip_reason_table[i].text)) {
2261
		if (!strcasecmp(text, sip_reason_table[i].text)) {
2262
			ast = sip_reason_table[i].code;
2262
			ast = sip_reason_table[i].code;
2263
			break;
2263
			break;
2264
		}
2264
		}
2265
	}
2265
	}
2266

    
   
2266

   
2267
	return ast;
2267
	return ast;
2268
}
2268
}
2269

    
   
2269

   
2270
static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
2270
static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
2271
{
2271
{
2272
	if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2272
	if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2273
		return sip_reason_table[code].text;
2273
		return sip_reason_table[code].text;
2274
	}
2274
	}
2275

    
   
2275

   
2276
	return "unknown";
2276
	return "unknown";
2277
}
2277
}
2278

    
   
2278

   
2279
/*!
2279
/*!
2280
 * \brief generic function for determining if a correct transport is being
2280
 * \brief generic function for determining if a correct transport is being
2281
 * used to contact a peer
2281
 * used to contact a peer
2282
 *
2282
 *
2283
 * this is done as a macro so that the "tmpl" var can be passed either a
2283
 * this is done as a macro so that the "tmpl" var can be passed either a
2284
 * sip_request or a sip_peer
2284
 * sip_request or a sip_peer
2285
 */
2285
 */
2286
#define check_request_transport(peer, tmpl) ({ \
2286
#define check_request_transport(peer, tmpl) ({ \
2287
	int ret = 0; \
2287
	int ret = 0; \
2288
	if (peer->socket.type == tmpl->socket.type) \
2288
	if (peer->socket.type == tmpl->socket.type) \
2289
		; \
2289
		; \
2290
	else if (!(peer->transports & tmpl->socket.type)) {\
2290
	else if (!(peer->transports & tmpl->socket.type)) {\
2291
		ast_log(LOG_ERROR, \
2291
		ast_log(LOG_ERROR, \
2292
			"'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
2292
			"'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
2293
			get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
2293
			get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
2294
			); \
2294
			); \
2295
		ret = 1; \
2295
		ret = 1; \
2296
	} else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
2296
	} else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
2297
		ast_log(LOG_WARNING, \
2297
		ast_log(LOG_WARNING, \
2298
			"peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
2298
			"peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
2299
			peer->name, get_transport(tmpl->socket.type) \
2299
			peer->name, get_transport(tmpl->socket.type) \
2300
		); \
2300
		); \
2301
	} else { \
2301
	} else { \
2302
		ast_debug(1, \
2302
		ast_debug(1, \
2303
			"peer '%s' has contacted us over %s even though we prefer %s.\n", \
2303
			"peer '%s' has contacted us over %s even though we prefer %s.\n", \
2304
			peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
2304
			peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
2305
		); \
2305
		); \
2306
	}\
2306
	}\
2307
	(ret); \
2307
	(ret); \
2308
})
2308
})
2309

    
   
2309

   
2310
/*! \brief
2310
/*! \brief
2311
 * duplicate a list of channel variables, \return the copy.
2311
 * duplicate a list of channel variables, \return the copy.
2312
 */
2312
 */
2313
static struct ast_variable *copy_vars(struct ast_variable *src)
2313
static struct ast_variable *copy_vars(struct ast_variable *src)
2314
{
2314
{
2315
	struct ast_variable *res = NULL, *tmp, *v = NULL;
2315
	struct ast_variable *res = NULL, *tmp, *v = NULL;
2316

    
   
2316

   
2317
	for (v = src ; v ; v = v->next) {
2317
	for (v = src ; v ; v = v->next) {
2318
		if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2318
		if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2319
			tmp->next = res;
2319
			tmp->next = res;
2320
			res = tmp;
2320
			res = tmp;
2321
		}
2321
		}
2322
	}
2322
	}
2323
	return res;
2323
	return res;
2324
}
2324
}
2325

    
   
2325

   
2326
static void tcptls_packet_destructor(void *obj)
2326
static void tcptls_packet_destructor(void *obj)
2327
{
2327
{
2328
	struct tcptls_packet *packet = obj;
2328
	struct tcptls_packet *packet = obj;
2329

    
   
2329

   
2330
	ast_free(packet->data);
2330
	ast_free(packet->data);
2331
}
2331
}
2332

    
   
2332

   
2333
static void sip_tcptls_client_args_destructor(void *obj)
2333
static void sip_tcptls_client_args_destructor(void *obj)
2334
{
2334
{
2335
	struct ast_tcptls_session_args *args = obj;
2335
	struct ast_tcptls_session_args *args = obj;
2336
	if (args->tls_cfg) {
2336
	if (args->tls_cfg) {
2337
		ast_free(args->tls_cfg->certfile);
2337
		ast_free(args->tls_cfg->certfile);
2338
		ast_free(args->tls_cfg->pvtfile);
2338
		ast_free(args->tls_cfg->pvtfile);
2339
		ast_free(args->tls_cfg->cipher);
2339
		ast_free(args->tls_cfg->cipher);
2340
		ast_free(args->tls_cfg->cafile);
2340
		ast_free(args->tls_cfg->cafile);
2341
		ast_free(args->tls_cfg->capath);
2341
		ast_free(args->tls_cfg->capath);
2342
	}
2342
	}
2343
	ast_free(args->tls_cfg);
2343
	ast_free(args->tls_cfg);
2344
	ast_free((char *) args->name);
2344
	ast_free((char *) args->name);
2345
}
2345
}
2346

    
   
2346

   
2347
static void sip_threadinfo_destructor(void *obj)
2347
static void sip_threadinfo_destructor(void *obj)
2348
{
2348
{
2349
	struct sip_threadinfo *th = obj;
2349
	struct sip_threadinfo *th = obj;
2350
	struct tcptls_packet *packet;
2350
	struct tcptls_packet *packet;
2351

    
   
2351

   
2352
	if (th->alert_pipe[1] > -1) {
2352
	if (th->alert_pipe[1] > -1) {
2353
		close(th->alert_pipe[0]);
2353
		close(th->alert_pipe[0]);
2354
	}
2354
	}
2355
	if (th->alert_pipe[1] > -1) {
2355
	if (th->alert_pipe[1] > -1) {
2356
		close(th->alert_pipe[1]);
2356
		close(th->alert_pipe[1]);
2357
	}
2357
	}
2358
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2358
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2359

    
   
2359

   
2360
	while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2360
	while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2361
		ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
2361
		ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
2362
	}
2362
	}
2363

    
   
2363

   
2364
	if (th->tcptls_session) {
2364
	if (th->tcptls_session) {
2365
		ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
2365
		ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
2366
	}
2366
	}
2367
}
2367
}
2368

    
   
2368

   
2369
/*! \brief creates a sip_threadinfo object and links it into the threadt table. */
2369
/*! \brief creates a sip_threadinfo object and links it into the threadt table. */
2370
static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
2370
static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
2371
{
2371
{
2372
	struct sip_threadinfo *th;
2372
	struct sip_threadinfo *th;
2373

    
   
2373

   
2374
	if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
2374
	if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
2375
		return NULL;
2375
		return NULL;
2376
	}
2376
	}
2377

    
   
2377

   
2378
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2378
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2379

    
   
2379

   
2380
	if (pipe(th->alert_pipe) == -1) {
2380
	if (pipe(th->alert_pipe) == -1) {
2381
		ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
2381
		ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
2382
		ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
2382
		ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
2383
		return NULL;
2383
		return NULL;
2384
	}
2384
	}
2385
	ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
2385
	ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
2386
	th->tcptls_session = tcptls_session;
2386
	th->tcptls_session = tcptls_session;
2387
	th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
2387
	th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
2388
	ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2388
	ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2389
	ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
2389
	ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
2390
	return th;
2390
	return th;
2391
}
2391
}
2392

    
   
2392

   
2393
/*! \brief used to indicate to a tcptls thread that data is ready to be written */
2393
/*! \brief used to indicate to a tcptls thread that data is ready to be written */
2394
static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
2394
static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
2395
{
2395
{
2396
	int res = len;
2396
	int res = len;
2397
	struct sip_threadinfo *th = NULL;
2397
	struct sip_threadinfo *th = NULL;
2398
	struct tcptls_packet *packet = NULL;
2398
	struct tcptls_packet *packet = NULL;
2399
	struct sip_threadinfo tmp = {
2399
	struct sip_threadinfo tmp = {
2400
		.tcptls_session = tcptls_session,
2400
		.tcptls_session = tcptls_session,
2401
	};
2401
	};
2402
	enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2402
	enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2403

    
   
2403

   
2404
	if (!tcptls_session) {
2404
	if (!tcptls_session) {
2405
		return XMIT_ERROR;
2405
		return XMIT_ERROR;
2406
	}
2406
	}
2407

    
   
2407

   
2408
	ast_mutex_lock(&tcptls_session->lock);
2408
	ast_mutex_lock(&tcptls_session->lock);
2409

    
   
2409

   
2410
	if ((tcptls_session->fd == -1) ||
2410
	if ((tcptls_session->fd == -1) ||
2411
		!(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
2411
		!(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
2412
		!(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2412
		!(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2413
		!(packet->data = ast_str_create(len))) {
2413
		!(packet->data = ast_str_create(len))) {
2414
		goto tcptls_write_setup_error;
2414
		goto tcptls_write_setup_error;
2415
	}
2415
	}
2416

    
   
2416

   
2417
	/* goto tcptls_write_error should _NOT_ be used beyond this point */
2417
	/* goto tcptls_write_error should _NOT_ be used beyond this point */
2418
	ast_str_set(&packet->data, 0, "%s", (char *) buf);
2418
	ast_str_set(&packet->data, 0, "%s", (char *) buf);
2419
	packet->len = len;
2419
	packet->len = len;
2420

    
   
2420

   
2421
	/* alert tcptls thread handler that there is a packet to be sent.
2421
	/* alert tcptls thread handler that there is a packet to be sent.
2422
	 * must lock the thread info object to guarantee control of the
2422
	 * must lock the thread info object to guarantee control of the
2423
	 * packet queue */
2423
	 * packet queue */
2424
	ao2_lock(th);
2424
	ao2_lock(th);
2425
	if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2425
	if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2426
		ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
2426
		ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
2427
		ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
2427
		ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
2428
		packet = NULL;
2428
		packet = NULL;
2429
		res = XMIT_ERROR;
2429
		res = XMIT_ERROR;
2430
	} else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
2430
	} else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
2431
		AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2431
		AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2432
	}
2432
	}
2433
	ao2_unlock(th);
2433
	ao2_unlock(th);
2434

    
   
2434

   
2435
	ast_mutex_unlock(&tcptls_session->lock);
2435
	ast_mutex_unlock(&tcptls_session->lock);
2436
	ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
2436
	ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
2437
	return res;
2437
	return res;
2438

    
   
2438

   
2439
tcptls_write_setup_error:
2439
tcptls_write_setup_error:
2440
	if (th) {
2440
	if (th) {
2441
		ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
2441
		ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
2442
	}
2442
	}
2443
	if (packet) {
2443
	if (packet) {
2444
		ao2_t_ref(packet, -1, "could not allocate packet's data");
2444
		ao2_t_ref(packet, -1, "could not allocate packet's data");
2445
	}
2445
	}
2446
	ast_mutex_unlock(&tcptls_session->lock);
2446
	ast_mutex_unlock(&tcptls_session->lock);
2447

    
   
2447

   
2448
	return XMIT_ERROR;
2448
	return XMIT_ERROR;
2449
}
2449
}
2450

    
   
2450

   
2451
/*! \brief SIP TCP connection handler */
2451
/*! \brief SIP TCP connection handler */
2452
static void *sip_tcp_worker_fn(void *data)
2452
static void *sip_tcp_worker_fn(void *data)
2453
{
2453
{
2454
	struct ast_tcptls_session_instance *tcptls_session = data;
2454
	struct ast_tcptls_session_instance *tcptls_session = data;
2455

    
   
2455

   
2456
	return _sip_tcp_helper_thread(NULL, tcptls_session);
2456
	return _sip_tcp_helper_thread(NULL, tcptls_session);
2457
}
2457
}
2458

    
   
2458

   
2459
/*! \brief SIP TCP thread management function
2459
/*! \brief SIP TCP thread management function
2460
	This function reads from the socket, parses the packet into a request
2460
	This function reads from the socket, parses the packet into a request
2461
*/
2461
*/
2462
static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
2462
static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
2463
{
2463
{
2464
	int res, cl;
2464
	int res, cl;
2465
	struct sip_request req = { 0, } , reqcpy = { 0, };
2465
	struct sip_request req = { 0, } , reqcpy = { 0, };
2466
	struct sip_threadinfo *me = NULL;
2466
	struct sip_threadinfo *me = NULL;
2467
	char buf[1024] = "";
2467
	char buf[1024] = "";
2468
	struct pollfd fds[2] = { { 0 }, { 0 }, };
2468
	struct pollfd fds[2] = { { 0 }, { 0 }, };
2469
	struct ast_tcptls_session_args *ca = NULL;
2469
	struct ast_tcptls_session_args *ca = NULL;
2470

    
   
2470

   
2471
	/* If this is a server session, then the connection has already been setup,
2471
	/* If this is a server session, then the connection has already been setup,
2472
	 * simply create the threadinfo object so we can access this thread for writing.
2472
	 * simply create the threadinfo object so we can access this thread for writing.
2473
	 * 
2473
	 * 
2474
	 * if this is a client connection more work must be done.
2474
	 * if this is a client connection more work must be done.
2475
	 * 1. We own the parent session args for a client connection.  This pointer needs
2475
	 * 1. We own the parent session args for a client connection.  This pointer needs
2476
	 *    to be held on to so we can decrement it's ref count on thread destruction.
2476
	 *    to be held on to so we can decrement it's ref count on thread destruction.
2477
	 * 2. The threadinfo object was created before this thread was launched, however
2477
	 * 2. The threadinfo object was created before this thread was launched, however
2478
	 *    it must be found within the threadt table.
2478
	 *    it must be found within the threadt table.
2479
	 * 3. Last, the tcptls_session must be started.
2479
	 * 3. Last, the tcptls_session must be started.
2480
	 */
2480
	 */
2481
	if (!tcptls_session->client) {
2481
	if (!tcptls_session->client) {
2482
		if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
2482
		if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
2483
			goto cleanup;
2483
			goto cleanup;
2484
		}
2484
		}
2485
		ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
2485
		ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
2486
	} else {
2486
	} else {
2487
		struct sip_threadinfo tmp = {
2487
		struct sip_threadinfo tmp = {
2488
			.tcptls_session = tcptls_session,
2488
			.tcptls_session = tcptls_session,
2489
		};
2489
		};
2490

    
   
2490

   
2491
		if ((!(ca = tcptls_session->parent)) ||
2491
		if ((!(ca = tcptls_session->parent)) ||
2492
			(!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
2492
			(!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
2493
			(!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
2493
			(!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
2494
			goto cleanup;
2494
			goto cleanup;
2495
		}
2495
		}
2496
	}
2496
	}
2497

    
   
2497

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

    
   
2500

   
2501
	/* set up pollfd to watch for reads on both the socket and the alert_pipe */
2501
	/* set up pollfd to watch for reads on both the socket and the alert_pipe */
2502
	fds[0].fd = tcptls_session->fd;
2502
	fds[0].fd = tcptls_session->fd;
2503
	fds[1].fd = me->alert_pipe[0];
2503
	fds[1].fd = me->alert_pipe[0];
2504
	fds[0].events = fds[1].events = POLLIN | POLLPRI;
2504
	fds[0].events = fds[1].events = POLLIN | POLLPRI;
2505

    
   
2505

   
2506
	if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
2506
	if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
2507
		goto cleanup;
2507
		goto cleanup;
2508
	}
2508
	}
2509
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
2509
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
2510
		goto cleanup;
2510
		goto cleanup;
2511
	}
2511
	}
2512

    
   
2512

   
2513
	for (;;) {
2513
	for (;;) {
2514
		struct ast_str *str_save;
2514
		struct ast_str *str_save;
2515

    
   
2515

   
2516
		res = ast_poll(fds, 2, -1); /* polls for both socket and alert_pipe */
2516
		res = ast_poll(fds, 2, -1); /* polls for both socket and alert_pipe */
2517
		if (res < 0) {
2517
		if (res < 0) {
2518
			ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
2518
			ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
2519
			goto cleanup;
2519
			goto cleanup;
2520
		}
2520
		}
2521

    
   
2521

   
2522
		/* handle the socket event, check for both reads from the socket fd,
2522
		/* handle the socket event, check for both reads from the socket fd,
2523
		 * and writes from alert_pipe fd */
2523
		 * and writes from alert_pipe fd */
2524
		if (fds[0].revents) { /* there is data on the socket to be read */
2524
		if (fds[0].revents) { /* there is data on the socket to be read */
2525

    
   
2525

   
2526
			fds[0].revents = 0;
2526
			fds[0].revents = 0;
2527

    
   
2527

   
2528
			/* clear request structure */
2528
			/* clear request structure */
2529
			str_save = req.data;
2529
			str_save = req.data;
2530
			memset(&req, 0, sizeof(req));
2530
			memset(&req, 0, sizeof(req));
2531
			req.data = str_save;
2531
			req.data = str_save;
2532
			ast_str_reset(req.data);
2532
			ast_str_reset(req.data);
2533

    
   
2533

   
2534
			str_save = reqcpy.data;
2534
			str_save = reqcpy.data;
2535
			memset(&reqcpy, 0, sizeof(reqcpy));
2535
			memset(&reqcpy, 0, sizeof(reqcpy));
2536
			reqcpy.data = str_save;
2536
			reqcpy.data = str_save;
2537
			ast_str_reset(reqcpy.data);
2537
			ast_str_reset(reqcpy.data);
2538

    
   
2538

   
2539
			memset(buf, 0, sizeof(buf));
2539
			memset(buf, 0, sizeof(buf));
2540

    
   
2540

   
2541
			if (tcptls_session->ssl) {
2541
			if (tcptls_session->ssl) {
2542
				set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
2542
				set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
2543
				req.socket.port = htons(ourport_tls);
2543
				req.socket.port = htons(ourport_tls);
2544
			} else {
2544
			} else {
2545
				set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
2545
				set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
2546
				req.socket.port = htons(ourport_tcp);
2546
				req.socket.port = htons(ourport_tcp);
2547
			}
2547
			}
2548
			req.socket.fd = tcptls_session->fd;
2548
			req.socket.fd = tcptls_session->fd;
2549

    
   
2549

   
2550
			/* Read in headers one line at a time */
2550
			/* Read in headers one line at a time */
2551
			while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
2551
			while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
2552
				ast_mutex_lock(&tcptls_session->lock);
2552
				ast_mutex_lock(&tcptls_session->lock);
2553
				if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2553
				if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2554
					ast_mutex_unlock(&tcptls_session->lock);
2554
					ast_mutex_unlock(&tcptls_session->lock);
2555
					goto cleanup;
2555
					goto cleanup;
2556
				}
2556
				}
2557
				ast_mutex_unlock(&tcptls_session->lock);
2557
				ast_mutex_unlock(&tcptls_session->lock);
2558
				if (me->stop) {
2558
				if (me->stop) {
2559
					 goto cleanup;
2559
					 goto cleanup;
2560
				}
2560
				}
2561
				ast_str_append(&req.data, 0, "%s", buf);
2561
				ast_str_append(&req.data, 0, "%s", buf);
2562
				req.len = req.data->used;
2562
				req.len = req.data->used;
2563
			}
2563
			}
2564
			copy_request(&reqcpy, &req);
2564
			copy_request(&reqcpy, &req);
2565
			parse_request(&reqcpy);
2565
			parse_request(&reqcpy);
2566
			/* In order to know how much to read, we need the content-length header */
2566
			/* In order to know how much to read, we need the content-length header */
2567
			if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
2567
			if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
2568
				while (cl > 0) {
2568
				while (cl > 0) {
2569
					size_t bytes_read;
2569
					size_t bytes_read;
2570
					ast_mutex_lock(&tcptls_session->lock);
2570
					ast_mutex_lock(&tcptls_session->lock);
2571
					if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
2571
					if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
2572
						ast_mutex_unlock(&tcptls_session->lock);
2572
						ast_mutex_unlock(&tcptls_session->lock);
2573
						goto cleanup;
2573
						goto cleanup;
2574
					}
2574
					}
2575
					buf[bytes_read] = '\0';
2575
					buf[bytes_read] = '\0';
2576
					ast_mutex_unlock(&tcptls_session->lock);
2576
					ast_mutex_unlock(&tcptls_session->lock);
2577
					if (me->stop) {
2577
					if (me->stop) {
2578
						goto cleanup;
2578
						goto cleanup;
2579
					}
2579
					}
2580
					cl -= strlen(buf);
2580
					cl -= strlen(buf);
2581
					ast_str_append(&req.data, 0, "%s", buf);
2581
					ast_str_append(&req.data, 0, "%s", buf);
2582
					req.len = req.data->used;
2582
					req.len = req.data->used;
2583
				}
2583
				}
2584
			}
2584
			}
2585
			/*! \todo XXX If there's no Content-Length or if the content-length and what
2585
			/*! \todo XXX If there's no Content-Length or if the content-length and what
2586
					we receive is not the same - we should generate an error */
2586
					we receive is not the same - we should generate an error */
2587

    
   
2587

   
2588
			req.socket.tcptls_session = tcptls_session;
2588
			req.socket.tcptls_session = tcptls_session;
2589
			handle_request_do(&req, &tcptls_session->remote_address);
2589
			handle_request_do(&req, &tcptls_session->remote_address);
2590
		}
2590
		}
2591

    
   
2591

   
2592
		if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
2592
		if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
2593
			enum sip_tcptls_alert alert;
2593
			enum sip_tcptls_alert alert;
2594
			struct tcptls_packet *packet;
2594
			struct tcptls_packet *packet;
2595

    
   
2595

   
2596
			fds[1].revents = 0;
2596
			fds[1].revents = 0;
2597

    
   
2597

   
2598
			if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
2598
			if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
2599
				ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
2599
				ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
2600
				continue;
2600
				continue;
2601
			}
2601
			}
2602

    
   
2602

   
2603
			switch (alert) {
2603
			switch (alert) {
2604
			case TCPTLS_ALERT_STOP:
2604
			case TCPTLS_ALERT_STOP:
2605
				goto cleanup;
2605
				goto cleanup;
2606
			case TCPTLS_ALERT_DATA:
2606
			case TCPTLS_ALERT_DATA:
2607
				ao2_lock(me);
2607
				ao2_lock(me);
2608
				if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
2608
				if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
2609
					ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
2609
					ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
2610
				} else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
2610
				} else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
2611
					ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
2611
					ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
2612
				}
2612
				}
2613

    
   
2613

   
2614
				if (packet) {
2614
				if (packet) {
2615
					ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
2615
					ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
2616
				}
2616
				}
2617
				ao2_unlock(me);
2617
				ao2_unlock(me);
2618
				break;
2618
				break;
2619
			default:
2619
			default:
2620
				ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
2620
				ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
2621
			}
2621
			}
2622
		}
2622
		}
2623
	}
2623
	}
2624

    
   
2624

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

    
   
2626

   
2627
cleanup:
2627
cleanup:
2628
	if (me) {
2628
	if (me) {
2629
		ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
2629
		ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
2630
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2630
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2631
	}
2631
	}
2632
	deinit_req(&reqcpy);
2632
	deinit_req(&reqcpy);
2633
	deinit_req(&req);
2633
	deinit_req(&req);
2634

    
   
2634

   
2635
	/* if client, we own the parent session arguments and must decrement ref */
2635
	/* if client, we own the parent session arguments and must decrement ref */
2636
	if (ca) {
2636
	if (ca) {
2637
		ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
2637
		ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
2638
	}
2638
	}
2639

    
   
2639

   
2640
	if (tcptls_session) {
2640
	if (tcptls_session) {
2641
		ast_mutex_lock(&tcptls_session->lock);
2641
		ast_mutex_lock(&tcptls_session->lock);
2642
		if (tcptls_session->f) {
2642
		if (tcptls_session->f) {
2643
			fclose(tcptls_session->f);
2643
			fclose(tcptls_session->f);
2644
			tcptls_session->f = NULL;
2644
			tcptls_session->f = NULL;
2645
		}
2645
		}
2646
		if (tcptls_session->fd != -1) {
2646
		if (tcptls_session->fd != -1) {
2647
			close(tcptls_session->fd);
2647
			close(tcptls_session->fd);
2648
			tcptls_session->fd = -1;
2648
			tcptls_session->fd = -1;
2649
		}
2649
		}
2650
		tcptls_session->parent = NULL;
2650
		tcptls_session->parent = NULL;
2651
		ast_mutex_unlock(&tcptls_session->lock);
2651
		ast_mutex_unlock(&tcptls_session->lock);
2652

    
   
2652

   
2653
		ao2_ref(tcptls_session, -1);
2653
		ao2_ref(tcptls_session, -1);
2654
		tcptls_session = NULL;
2654
		tcptls_session = NULL;
2655
	}
2655
	}
2656
	return NULL;
2656
	return NULL;
2657
}
2657
}
2658

    
   
2658

   
2659
/* this func is used with ao2_callback to unlink/delete all marked
2659
/* this func is used with ao2_callback to unlink/delete all marked
2660
   peers */
2660
   peers */
2661
static int peer_is_marked(void *peerobj, void *arg, int flags)
2661
static int peer_is_marked(void *peerobj, void *arg, int flags)
2662
{
2662
{
2663
	struct sip_peer *peer = peerobj;
2663
	struct sip_peer *peer = peerobj;
2664
	if (peer->the_mark && peer->pokeexpire != -1) {
2664
	if (peer->the_mark && peer->pokeexpire != -1) {
2665
		AST_SCHED_DEL(sched, peer->pokeexpire);
2665
		AST_SCHED_DEL(sched, peer->pokeexpire);
2666
	}
2666
	}
2667
	return peer->the_mark ? CMP_MATCH : 0;
2667
	return peer->the_mark ? CMP_MATCH : 0;
2668
}
2668
}
2669

    
   
2669

   
2670

    
   
2670

   
2671
/* \brief Unlink all marked peers from ao2 containers */
2671
/* \brief Unlink all marked peers from ao2 containers */
2672
static void unlink_marked_peers_from_tables(void)
2672
static void unlink_marked_peers_from_tables(void)
2673
{
2673
{
2674
	ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
2674
	ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
2675
						"initiating callback to remove marked peers");
2675
						"initiating callback to remove marked peers");
2676
	ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
2676
	ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
2677
						"initiating callback to remove marked peers");
2677
						"initiating callback to remove marked peers");
2678
}
2678
}
2679

    
   
2679

   
2680
/* \brief Unlink single peer from all ao2 containers */
2680
/* \brief Unlink single peer from all ao2 containers */
2681
static void unlink_peer_from_tables(struct sip_peer *peer)
2681
static void unlink_peer_from_tables(struct sip_peer *peer)
2682
{
2682
{
2683
	ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
2683
	ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
2684
	if (!ast_sockaddr_isnull(&peer->addr)) {
2684
	if (!ast_sockaddr_isnull(&peer->addr)) {
2685
		ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
2685
		ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
2686
	}
2686
	}
2687
}
2687
}
2688

    
   
2688

   
2689
/*!
2689
/*!
2690
 * helper functions to unreference various types of objects.
2690
 * helper functions to unreference various types of objects.
2691
 * By handling them this way, we don't have to declare the
2691
 * By handling them this way, we don't have to declare the
2692
 * destructor on each call, which removes the chance of errors.
2692
 * destructor on each call, which removes the chance of errors.
2693
 */
2693
 */
2694
static void *unref_peer(struct sip_peer *peer, char *tag)
2694
static void *unref_peer(struct sip_peer *peer, char *tag)
2695
{
2695
{
2696
	ao2_t_ref(peer, -1, tag);
2696
	ao2_t_ref(peer, -1, tag);
2697
	return NULL;
2697
	return NULL;
2698
}
2698
}
2699

    
   
2699

   
2700
static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
2700
static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
2701
{
2701
{
2702
	ao2_t_ref(peer, 1, tag);
2702
	ao2_t_ref(peer, 1, tag);
2703
	return peer;
2703
	return peer;
2704
}
2704
}
2705

    
   
2705

   
2706
/*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
2706
/*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
2707
 *
2707
 *
2708
 * This function sets pvt's outboundproxy pointer to the one referenced
2708
 * This function sets pvt's outboundproxy pointer to the one referenced
2709
 * by the proxy parameter. Because proxy may be a refcounted object, and
2709
 * by the proxy parameter. Because proxy may be a refcounted object, and
2710
 * because pvt's old outboundproxy may also be a refcounted object, we need
2710
 * because pvt's old outboundproxy may also be a refcounted object, we need
2711
 * to maintain the proper refcounts.
2711
 * to maintain the proper refcounts.
2712
 *
2712
 *
2713
 * \param pvt The sip_pvt for which we wish to set the outboundproxy
2713
 * \param pvt The sip_pvt for which we wish to set the outboundproxy
2714
 * \param proxy The sip_proxy which we will point pvt towards.
2714
 * \param proxy The sip_proxy which we will point pvt towards.
2715
 * \return Returns void
2715
 * \return Returns void
2716
 */
2716
 */
2717
static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
2717
static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
2718
{
2718
{
2719
	struct sip_proxy *old_obproxy = pvt->outboundproxy;
2719
	struct sip_proxy *old_obproxy = pvt->outboundproxy;
2720
	/* The sip_cfg.outboundproxy is statically allocated, and so
2720
	/* The sip_cfg.outboundproxy is statically allocated, and so
2721
	 * we don't ever need to adjust refcounts for it
2721
	 * we don't ever need to adjust refcounts for it
2722
	 */
2722
	 */
2723
	if (proxy && proxy != &sip_cfg.outboundproxy) {
2723
	if (proxy && proxy != &sip_cfg.outboundproxy) {
2724
		ao2_ref(proxy, +1);
2724
		ao2_ref(proxy, +1);
2725
	}
2725
	}
2726
	pvt->outboundproxy = proxy;
2726
	pvt->outboundproxy = proxy;
2727
	if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
2727
	if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
2728
		ao2_ref(old_obproxy, -1);
2728
		ao2_ref(old_obproxy, -1);
2729
	}
2729
	}
2730
}
2730
}
2731

    
   
2731

   
2732
 /*!
2732
 /*!
2733
 * \brief Unlink a dialog from the dialogs_checkrtp container
2733
 * \brief Unlink a dialog from the dialogs_checkrtp container
2734
 */
2734
 */
2735
static void *dialog_unlink_rtpcheck(struct sip_pvt *dialog)
2735
static void *dialog_unlink_rtpcheck(struct sip_pvt *dialog)
2736
{
2736
{
2737
	ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
2737
	ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
2738
	return NULL;
2738
	return NULL;
2739
}
2739
}
2740

    
   
2740

   
2741
/*!
2741
/*!
2742
 * \brief Unlink a dialog from the dialogs container, as well as any other places
2742
 * \brief Unlink a dialog from the dialogs container, as well as any other places
2743
 * that it may be currently stored.
2743
 * that it may be currently stored.
2744
 *
2744
 *
2745
 * \note A reference to the dialog must be held before calling this function, and this
2745
 * \note A reference to the dialog must be held before calling this function, and this
2746
 * function does not release that reference.
2746
 * function does not release that reference.
2747
 */
2747
 */
2748
void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
2748
void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
2749
{
2749
{
2750
	struct sip_pkt *cp;
2750
	struct sip_pkt *cp;
2751

    
   
2751

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

    
   
2753

   
2754
	ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
2754
	ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
2755
	ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
2755
	ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
2756
	ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
2756
	ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
2757

    
   
2757

   
2758
	/* Unlink us from the owner (channel) if we have one */
2758
	/* Unlink us from the owner (channel) if we have one */
2759
	if (dialog->owner) {
2759
	if (dialog->owner) {
2760
		if (lockowner) {
2760
		if (lockowner) {
2761
			ast_channel_lock(dialog->owner);
2761
			ast_channel_lock(dialog->owner);
2762
		}
2762
		}
2763
		ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2763
		ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2764
		dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
2764
		dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
2765
		if (lockowner) {
2765
		if (lockowner) {
2766
			ast_channel_unlock(dialog->owner);
2766
			ast_channel_unlock(dialog->owner);
2767
		}
2767
		}
2768
	}
2768
	}
2769
	if (dialog->registry) {
2769
	if (dialog->registry) {
2770
		if (dialog->registry->call == dialog) {
2770
		if (dialog->registry->call == dialog) {
2771
			dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
2771
			dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
2772
		}
2772
		}
2773
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2773
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2774
	}
2774
	}
2775
	if (dialog->stateid > -1) {
2775
	if (dialog->stateid > -1) {
2776
		ast_extension_state_del(dialog->stateid, NULL);
2776
		ast_extension_state_del(dialog->stateid, NULL);
2777
		dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
2777
		dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
2778
		dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2778
		dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2779
	}
2779
	}
2780
	/* Remove link from peer to subscription of MWI */
2780
	/* Remove link from peer to subscription of MWI */
2781
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
2781
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
2782
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2782
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2783
	}
2783
	}
2784
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
2784
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
2785
		dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
2785
		dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
2786
	}
2786
	}
2787

    
   
2787

   
2788
	/* remove all current packets in this dialog */
2788
	/* remove all current packets in this dialog */
2789
	while((cp = dialog->packets)) {
2789
	while((cp = dialog->packets)) {
2790
		dialog->packets = dialog->packets->next;
2790
		dialog->packets = dialog->packets->next;
2791
		AST_SCHED_DEL(sched, cp->retransid);
2791
		AST_SCHED_DEL(sched, cp->retransid);
2792
		dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
2792
		dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
2793
		if (cp->data) {
2793
		if (cp->data) {
2794
			ast_free(cp->data);
2794
			ast_free(cp->data);
2795
		}
2795
		}
2796
		ast_free(cp);
2796
		ast_free(cp);
2797
	}
2797
	}
2798

    
   
2798

   
2799
	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"));
2799
	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"));
2800

    
   
2800

   
2801
	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"));
2801
	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"));
2802
	
2802
	
2803
	if (dialog->autokillid > -1) {
2803
	if (dialog->autokillid > -1) {
2804
		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"));
2804
		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"));
2805
	}
2805
	}
2806

    
   
2806

   
2807
	if (dialog->request_queue_sched_id > -1) {
2807
	if (dialog->request_queue_sched_id > -1) {
2808
		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"));
2808
		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"));
2809
	}
2809
	}
2810

    
   
2810

   
2811
	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"));
2811
	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"));
2812

    
   
2812

   
2813
	if (dialog->t38id > -1) {
2813
	if (dialog->t38id > -1) {
2814
		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"));
2814
		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"));
2815
	}
2815
	}
2816

    
   
2816

   
2817
	dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
2817
	dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
2818
	return NULL;
2818
	return NULL;
2819
}
2819
}
2820

    
   
2820

   
2821
void *registry_unref(struct sip_registry *reg, char *tag)
2821
void *registry_unref(struct sip_registry *reg, char *tag)
2822
{
2822
{
2823
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
2823
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
2824
	ASTOBJ_UNREF(reg, sip_registry_destroy);
2824
	ASTOBJ_UNREF(reg, sip_registry_destroy);
2825
	return NULL;
2825
	return NULL;
2826
}
2826
}
2827

    
   
2827

   
2828
/*! \brief Add object reference to SIP registry */
2828
/*! \brief Add object reference to SIP registry */
2829
static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
2829
static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
2830
{
2830
{
2831
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
2831
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
2832
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
2832
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
2833
}
2833
}
2834

    
   
2834

   
2835
/*! \brief Interface structure with callbacks used to connect to UDPTL module*/
2835
/*! \brief Interface structure with callbacks used to connect to UDPTL module*/
2836
static struct ast_udptl_protocol sip_udptl = {
2836
static struct ast_udptl_protocol sip_udptl = {
2837
	type: "SIP",
2837
	type: "SIP",
2838
	get_udptl_info: sip_get_udptl_peer,
2838
	get_udptl_info: sip_get_udptl_peer,
2839
	set_udptl_peer: sip_set_udptl_peer,
2839
	set_udptl_peer: sip_set_udptl_peer,
2840
};
2840
};
2841

    
   
2841

   
2842
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2842
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2843
	__attribute__((format(printf, 2, 3)));
2843
	__attribute__((format(printf, 2, 3)));
2844

    
   
2844

   
2845

    
   
2845

   
2846
/*! \brief Convert transfer status to string */
2846
/*! \brief Convert transfer status to string */
2847
static const char *referstatus2str(enum referstatus rstatus)
2847
static const char *referstatus2str(enum referstatus rstatus)
2848
{
2848
{
2849
	return map_x_s(referstatusstrings, rstatus, "");
2849
	return map_x_s(referstatusstrings, rstatus, "");
2850
}
2850
}
2851

    
   
2851

   
2852
static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
2852
static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
2853
{
2853
{
2854
	if (pvt->final_destruction_scheduled) {
2854
	if (pvt->final_destruction_scheduled) {
2855
		return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
2855
		return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
2856
	}
2856
	}
2857
	if(pvt->needdestroy != 1) {
2857
	if(pvt->needdestroy != 1) {
2858
		ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
2858
		ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
2859
	}
2859
	}
2860
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
2860
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
2861
	pvt->needdestroy = 1;
2861
	pvt->needdestroy = 1;
2862
}
2862
}
2863

    
   
2863

   
2864
/*! \brief Initialize the initital request packet in the pvt structure.
2864
/*! \brief Initialize the initital request packet in the pvt structure.
2865
 	This packet is used for creating replies and future requests in
2865
 	This packet is used for creating replies and future requests in
2866
	a dialog */
2866
	a dialog */
2867
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
2867
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
2868
{
2868
{
2869
	if (p->initreq.headers) {
2869
	if (p->initreq.headers) {
2870
		ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
2870
		ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
2871
	} else {
2871
	} else {
2872
		ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
2872
		ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
2873
	}
2873
	}
2874
	/* Use this as the basis */
2874
	/* Use this as the basis */
2875
	copy_request(&p->initreq, req);
2875
	copy_request(&p->initreq, req);
2876
	parse_request(&p->initreq);
2876
	parse_request(&p->initreq);
2877
	if (req->debug) {
2877
	if (req->debug) {
2878
		ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
2878
		ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
2879
	}
2879
	}
2880
}
2880
}
2881

    
   
2881

   
2882
/*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
2882
/*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
2883
static void sip_alreadygone(struct sip_pvt *dialog)
2883
static void sip_alreadygone(struct sip_pvt *dialog)
2884
{
2884
{
2885
	ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
2885
	ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
2886
	dialog->alreadygone = 1;
2886
	dialog->alreadygone = 1;
2887
}
2887
}
2888

    
   
2888

   
2889
/*! Resolve DNS srv name or host name in a sip_proxy structure */
2889
/*! Resolve DNS srv name or host name in a sip_proxy structure */
2890
static int proxy_update(struct sip_proxy *proxy)
2890
static int proxy_update(struct sip_proxy *proxy)
2891
{
2891
{
2892
	/* if it's actually an IP address and not a name,
2892
	/* if it's actually an IP address and not a name,
2893
           there's no need for a managed lookup */
2893
           there's no need for a managed lookup */
2894
	if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
2894
	if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
2895
		/* Ok, not an IP address, then let's check if it's a domain or host */
2895
		/* Ok, not an IP address, then let's check if it's a domain or host */
2896
		/* XXX Todo - if we have proxy port, don't do SRV */
2896
		/* XXX Todo - if we have proxy port, don't do SRV */
2897
		proxy->ip.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
2897
		proxy->ip.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
2898
		if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
2898
		if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
2899
				ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2899
				ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2900
				return FALSE;
2900
				return FALSE;
2901
		}
2901
		}
2902

    
   
2902

   
2903
	}
2903
	}
2904

    
   
2904

   
2905
	ast_sockaddr_set_port(&proxy->ip, proxy->port);
2905
	ast_sockaddr_set_port(&proxy->ip, proxy->port);
2906

    
   
2906

   
2907
	proxy->last_dnsupdate = time(NULL);
2907
	proxy->last_dnsupdate = time(NULL);
2908
	return TRUE;
2908
	return TRUE;
2909
}
2909
}
2910

    
   
2910

   
2911
/*! \brief converts ascii port to int representation. If no
2911
/*! \brief converts ascii port to int representation. If no
2912
 *  pt buffer is provided or the pt has errors when being converted
2912
 *  pt buffer is provided or the pt has errors when being converted
2913
 *  to an int value, the port provided as the standard is used.
2913
 *  to an int value, the port provided as the standard is used.
2914
 */
2914
 */
2915
unsigned int port_str2int(const char *pt, unsigned int standard)
2915
unsigned int port_str2int(const char *pt, unsigned int standard)
2916
{
2916
{
2917
	int port = standard;
2917
	int port = standard;
2918
	if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
2918
	if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
2919
		port = standard;
2919
		port = standard;
2920
	}
2920
	}
2921

    
   
2921

   
2922
	return port;
2922
	return port;
2923
}
2923
}
2924

    
   
2924

   
2925
/*! \brief Get default outbound proxy or global proxy */
2925
/*! \brief Get default outbound proxy or global proxy */
2926
static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2926
static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2927
{
2927
{
2928
	if (peer && peer->outboundproxy) {
2928
	if (peer && peer->outboundproxy) {
2929
		if (sipdebug) {
2929
		if (sipdebug) {
2930
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2930
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2931
		}
2931
		}
2932
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2932
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2933
		return peer->outboundproxy;
2933
		return peer->outboundproxy;
2934
	}
2934
	}
2935
	if (sip_cfg.outboundproxy.name[0]) {
2935
	if (sip_cfg.outboundproxy.name[0]) {
2936
		if (sipdebug) {
2936
		if (sipdebug) {
2937
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2937
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2938
		}
2938
		}
2939
		append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
2939
		append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
2940
		return &sip_cfg.outboundproxy;
2940
		return &sip_cfg.outboundproxy;
2941
	}
2941
	}
2942
	if (sipdebug) {
2942
	if (sipdebug) {
2943
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2943
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2944
	}
2944
	}
2945
	return NULL;
2945
	return NULL;
2946
}
2946
}
2947

    
   
2947

   
2948
/*! \brief returns true if 'name' (with optional trailing whitespace)
2948
/*! \brief returns true if 'name' (with optional trailing whitespace)
2949
 * matches the sip method 'id'.
2949
 * matches the sip method 'id'.
2950
 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2950
 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2951
 * a case-insensitive comparison to be more tolerant.
2951
 * a case-insensitive comparison to be more tolerant.
2952
 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2952
 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2953
 */
2953
 */
2954
static int method_match(enum sipmethod id, const char *name)
2954
static int method_match(enum sipmethod id, const char *name)
2955
{
2955
{
2956
	int len = strlen(sip_methods[id].text);
2956
	int len = strlen(sip_methods[id].text);
2957
	int l_name = name ? strlen(name) : 0;
2957
	int l_name = name ? strlen(name) : 0;
2958
	/* true if the string is long enough, and ends with whitespace, and matches */
2958
	/* true if the string is long enough, and ends with whitespace, and matches */
2959
	return (l_name >= len && name[len] < 33 &&
2959
	return (l_name >= len && name[len] < 33 &&
2960
		!strncasecmp(sip_methods[id].text, name, len));
2960
		!strncasecmp(sip_methods[id].text, name, len));
2961
}
2961
}
2962

    
   
2962

   
2963
/*! \brief  find_sip_method: Find SIP method from header */
2963
/*! \brief  find_sip_method: Find SIP method from header */
2964
static int find_sip_method(const char *msg)
2964
static int find_sip_method(const char *msg)
2965
{
2965
{
2966
	int i, res = 0;
2966
	int i, res = 0;
2967
	
2967
	
2968
	if (ast_strlen_zero(msg)) {
2968
	if (ast_strlen_zero(msg)) {
2969
		return 0;
2969
		return 0;
2970
	}
2970
	}
2971
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
2971
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
2972
		if (method_match(i, msg)) {
2972
		if (method_match(i, msg)) {
2973
			res = sip_methods[i].id;
2973
			res = sip_methods[i].id;
2974
		}
2974
		}
2975
	}
2975
	}
2976
	return res;
2976
	return res;
2977
}
2977
}
2978

    
   
2978

   
2979
/*! \brief See if we pass debug IP filter */
2979
/*! \brief See if we pass debug IP filter */
2980
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
2980
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
2981
{
2981
{
2982
	/* Can't debug if sipdebug is not enabled */
2982
	/* Can't debug if sipdebug is not enabled */
2983
	if (!sipdebug) {
2983
	if (!sipdebug) {
2984
		return 0;
2984
		return 0;
2985
	}
2985
	}
2986

    
   
2986

   
2987
	/* A null debug_addr means we'll debug any address */
2987
	/* A null debug_addr means we'll debug any address */
2988
	if (ast_sockaddr_isnull(&debugaddr)) {
2988
	if (ast_sockaddr_isnull(&debugaddr)) {
2989
		return 1;
2989
		return 1;
2990
	}
2990
	}
2991

    
   
2991

   
2992
	/* If no port was specified for a debug address, just compare the
2992
	/* If no port was specified for a debug address, just compare the
2993
	 * addresses, otherwise compare the address and port
2993
	 * addresses, otherwise compare the address and port
2994
	 */
2994
	 */
2995
	if (ast_sockaddr_port(&debugaddr)) {
2995
	if (ast_sockaddr_port(&debugaddr)) {
2996
		return !ast_sockaddr_cmp(&debugaddr, addr);
2996
		return !ast_sockaddr_cmp(&debugaddr, addr);
2997
	} else {
2997
	} else {
2998
		return !ast_sockaddr_cmp_addr(&debugaddr, addr);
2998
		return !ast_sockaddr_cmp_addr(&debugaddr, addr);
2999
	}
2999
	}
3000
}
3000
}
3001

    
   
3001

   
3002
/*! \brief The real destination address for a write */
3002
/*! \brief The real destination address for a write */
3003
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
3003
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
3004
{
3004
{
3005
	if (p->outboundproxy) {
3005
	if (p->outboundproxy) {
3006
		return &p->outboundproxy->ip;
3006
		return &p->outboundproxy->ip;
3007
	}
3007
	}
3008

    
   
3008

   
3009
	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;
3009
	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;
3010
}
3010
}
3011

    
   
3011

   
3012
/*! \brief Display SIP nat mode */
3012
/*! \brief Display SIP nat mode */
3013
static const char *sip_nat_mode(const struct sip_pvt *p)
3013
static const char *sip_nat_mode(const struct sip_pvt *p)
3014
{
3014
{
3015
	return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
3015
	return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
3016
}
3016
}
3017

    
   
3017

   
3018
/*! \brief Test PVT for debugging output */
3018
/*! \brief Test PVT for debugging output */
3019
static inline int sip_debug_test_pvt(struct sip_pvt *p)
3019
static inline int sip_debug_test_pvt(struct sip_pvt *p)
3020
{
3020
{
3021
	if (!sipdebug) {
3021
	if (!sipdebug) {
3022
		return 0;
3022
		return 0;
3023
	}
3023
	}
3024
	return sip_debug_test_addr(sip_real_dst(p));
3024
	return sip_debug_test_addr(sip_real_dst(p));
3025
}
3025
}
3026

    
   
3026

   
3027
/*! \brief Return int representing a bit field of transport types found in const char *transport */
3027
/*! \brief Return int representing a bit field of transport types found in const char *transport */
3028
static int get_transport_str2enum(const char *transport)
3028
static int get_transport_str2enum(const char *transport)
3029
{
3029
{
3030
	int res = 0;
3030
	int res = 0;
3031

    
   
3031

   
3032
	if (ast_strlen_zero(transport)) {
3032
	if (ast_strlen_zero(transport)) {
3033
		return res;
3033
		return res;
3034
	}
3034
	}
3035

    
   
3035

   
3036
	if (!strcasecmp(transport, "udp")) {
3036
	if (!strcasecmp(transport, "udp")) {
3037
		res |= SIP_TRANSPORT_UDP;
3037
		res |= SIP_TRANSPORT_UDP;
3038
	}
3038
	}
3039
	if (!strcasecmp(transport, "tcp")) {
3039
	if (!strcasecmp(transport, "tcp")) {
3040
		res |= SIP_TRANSPORT_TCP;
3040
		res |= SIP_TRANSPORT_TCP;
3041
	}
3041
	}
3042
	if (!strcasecmp(transport, "tls")) {
3042
	if (!strcasecmp(transport, "tls")) {
3043
		res |= SIP_TRANSPORT_TLS;
3043
		res |= SIP_TRANSPORT_TLS;
3044
	}
3044
	}
3045

    
   
3045

   
3046
	return res;
3046
	return res;
3047
}
3047
}
3048

    
   
3048

   
3049
/*! \brief Return configuration of transports for a device */
3049
/*! \brief Return configuration of transports for a device */
3050
static inline const char *get_transport_list(unsigned int transports) {
3050
static inline const char *get_transport_list(unsigned int transports) {
3051
	switch (transports) {
3051
	switch (transports) {
3052
		case SIP_TRANSPORT_UDP:
3052
		case SIP_TRANSPORT_UDP:
3053
			return "UDP";
3053
			return "UDP";
3054
		case SIP_TRANSPORT_TCP:
3054
		case SIP_TRANSPORT_TCP:
3055
			return "TCP";
3055
			return "TCP";
3056
		case SIP_TRANSPORT_TLS:
3056
		case SIP_TRANSPORT_TLS:
3057
			return "TLS";
3057
			return "TLS";
3058
		case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
3058
		case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
3059
			return "TCP,UDP";
3059
			return "TCP,UDP";
3060
		case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
3060
		case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
3061
			return "TLS,UDP";
3061
			return "TLS,UDP";
3062
		case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
3062
		case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
3063
			return "TLS,TCP";
3063
			return "TLS,TCP";
3064
		default:
3064
		default:
3065
			return transports ?
3065
			return transports ?
3066
				"TLS,TCP,UDP" : "UNKNOWN";	
3066
				"TLS,TCP,UDP" : "UNKNOWN";	
3067
	}
3067
	}
3068
}
3068
}
3069

    
   
3069

   
3070
/*! \brief Return transport as string */
3070
/*! \brief Return transport as string */
3071
static inline const char *get_transport(enum sip_transport t)
3071
static inline const char *get_transport(enum sip_transport t)
3072
{
3072
{
3073
	switch (t) {
3073
	switch (t) {
3074
	case SIP_TRANSPORT_UDP:
3074
	case SIP_TRANSPORT_UDP:
3075
		return "UDP";
3075
		return "UDP";
3076
	case SIP_TRANSPORT_TCP:
3076
	case SIP_TRANSPORT_TCP:
3077
		return "TCP";
3077
		return "TCP";
3078
	case SIP_TRANSPORT_TLS:
3078
	case SIP_TRANSPORT_TLS:
3079
		return "TLS";
3079
		return "TLS";
3080
	}
3080
	}
3081

    
   
3081

   
3082
	return "UNKNOWN";
3082
	return "UNKNOWN";
3083
}
3083
}
3084

    
   
3084

   
3085
/*! \brief Return protocol string for srv dns query */
3085
/*! \brief Return protocol string for srv dns query */
3086
static inline const char *get_srv_protocol(enum sip_transport t)
3086
static inline const char *get_srv_protocol(enum sip_transport t)
3087
{
3087
{
3088
	switch (t) {
3088
	switch (t) {
3089
	case SIP_TRANSPORT_UDP:
3089
	case SIP_TRANSPORT_UDP:
3090
		return "udp";
3090
		return "udp";
3091
	case SIP_TRANSPORT_TLS:
3091
	case SIP_TRANSPORT_TLS:
3092
	case SIP_TRANSPORT_TCP:
3092
	case SIP_TRANSPORT_TCP:
3093
		return "tcp";
3093
		return "tcp";
3094
	}
3094
	}
3095

    
   
3095

   
3096
	return "udp";
3096
	return "udp";
3097
}
3097
}
3098

    
   
3098

   
3099
/*! \brief Return service string for srv dns query */
3099
/*! \brief Return service string for srv dns query */
3100
static inline const char *get_srv_service(enum sip_transport t)
3100
static inline const char *get_srv_service(enum sip_transport t)
3101
{
3101
{
3102
	switch (t) {
3102
	switch (t) {
3103
	case SIP_TRANSPORT_TCP:
3103
	case SIP_TRANSPORT_TCP:
3104
	case SIP_TRANSPORT_UDP:
3104
	case SIP_TRANSPORT_UDP:
3105
		return "sip";
3105
		return "sip";
3106
	case SIP_TRANSPORT_TLS:
3106
	case SIP_TRANSPORT_TLS:
3107
		return "sips";
3107
		return "sips";
3108
	}
3108
	}
3109
	return "sip";
3109
	return "sip";
3110
}
3110
}
3111

    
   
3111

   
3112
/*! \brief Return transport of dialog.
3112
/*! \brief Return transport of dialog.
3113
	\note this is based on a false assumption. We don't always use the
3113
	\note this is based on a false assumption. We don't always use the
3114
	outbound proxy for all requests in a dialog. It depends on the
3114
	outbound proxy for all requests in a dialog. It depends on the
3115
	"force" parameter. The FIRST request is always sent to the ob proxy.
3115
	"force" parameter. The FIRST request is always sent to the ob proxy.
3116
	\todo Fix this function to work correctly
3116
	\todo Fix this function to work correctly
3117
*/
3117
*/
3118
static inline const char *get_transport_pvt(struct sip_pvt *p)
3118
static inline const char *get_transport_pvt(struct sip_pvt *p)
3119
{
3119
{
3120
	if (p->outboundproxy && p->outboundproxy->transport) {
3120
	if (p->outboundproxy && p->outboundproxy->transport) {
3121
		set_socket_transport(&p->socket, p->outboundproxy->transport);
3121
		set_socket_transport(&p->socket, p->outboundproxy->transport);
3122
	}
3122
	}
3123

    
   
3123

   
3124
	return get_transport(p->socket.type);
3124
	return get_transport(p->socket.type);
3125
}
3125
}
3126

    
   
3126

   
3127
/*! \brief Transmit SIP message
3127
/*! \brief Transmit SIP message
3128
	Sends a SIP request or response on a given socket (in the pvt)
3128
	Sends a SIP request or response on a given socket (in the pvt)
3129
	Called by retrans_pkt, send_request, send_response and
3129
	Called by retrans_pkt, send_request, send_response and
3130
	__sip_reliable_xmit
3130
	__sip_reliable_xmit
3131
	\return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
3131
	\return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
3132
*/
3132
*/
3133
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
3133
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
3134
{
3134
{
3135
	int res = 0;
3135
	int res = 0;
3136
	const struct ast_sockaddr *dst = sip_real_dst(p);
3136
	const struct ast_sockaddr *dst = sip_real_dst(p);
3137

    
   
3137

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

    
   
3139

   
3140
	if (sip_prepare_socket(p) < 0) {
3140
	if (sip_prepare_socket(p) < 0) {
3141
		return XMIT_ERROR;
3141
		return XMIT_ERROR;
3142
	}
3142
	}
3143

    
   
3143

   
3144
	if (p->socket.type == SIP_TRANSPORT_UDP) {
3144
	if (p->socket.type == SIP_TRANSPORT_UDP) {
3145
		res = ast_sendto(p->socket.fd, data->str, len, 0, dst);
3145
		res = ast_sendto(p->socket.fd, data->str, len, 0, dst);
3146
	} else if (p->socket.tcptls_session) {
3146
	} else if (p->socket.tcptls_session) {
3147
		res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
3147
		res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
3148
	} else {
3148
	} else {
3149
		ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
3149
		ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
3150
		return XMIT_ERROR;
3150
		return XMIT_ERROR;
3151
	}
3151
	}
3152

    
   
3152

   
3153
	if (res == -1) {
3153
	if (res == -1) {
3154
		switch (errno) {
3154
		switch (errno) {
3155
		case EBADF:		/* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
3155
		case EBADF:		/* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
3156
		case EHOSTUNREACH:	/* Host can't be reached */
3156
		case EHOSTUNREACH:	/* Host can't be reached */
3157
		case ENETDOWN:		/* Interface down */
3157
		case ENETDOWN:		/* Interface down */
3158
		case ENETUNREACH:	/* Network failure */
3158
		case ENETUNREACH:	/* Network failure */
3159
		case ECONNREFUSED:      /* ICMP port unreachable */
3159
		case ECONNREFUSED:      /* ICMP port unreachable */
3160
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */
3160
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */
3161
		}
3161
		}
3162
	}
3162
	}
3163
	if (res != len) {
3163
	if (res != len) {
3164
		ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s returned %d: %s\n", data, len, ast_sockaddr_stringify(dst), res, strerror(errno));
3164
		ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s returned %d: %s\n", data, len, ast_sockaddr_stringify(dst), res, strerror(errno));
3165
	}
3165
	}
3166

    
   
3166

   
3167
	return res;
3167
	return res;
3168
}
3168
}
3169

    
   
3169

   
3170
/*! \brief Build a Via header for a request */
3170
/*! \brief Build a Via header for a request */
3171
static void build_via(struct sip_pvt *p)
3171
static void build_via(struct sip_pvt *p)
3172
{
3172
{
3173
	/* Work around buggy UNIDEN UIP200 firmware */
3173
	/* Work around buggy UNIDEN UIP200 firmware */
3174
	const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
3174
	const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
3175

    
   
3175

   
3176
	/* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
3176
	/* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
3177
	snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
3177
	snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
3178
		 get_transport_pvt(p),
3178
		 get_transport_pvt(p),
3179
		 ast_sockaddr_stringify(&p->ourip),
3179
		 ast_sockaddr_stringify(&p->ourip),
3180
		 (int) p->branch, rport);
3180
		 (int) p->branch, rport);
3181
}
3181
}
3182

    
   
3182

   
3183
/*! \brief NAT fix - decide which IP address to use for Asterisk server?
3183
/*! \brief NAT fix - decide which IP address to use for Asterisk server?
3184
 *
3184
 *
3185
 * Using the localaddr structure built up with localnet statements in sip.conf
3185
 * Using the localaddr structure built up with localnet statements in sip.conf
3186
 * apply it to their address to see if we need to substitute our
3186
 * apply it to their address to see if we need to substitute our
3187
 * externaddr or can get away with our internal bindaddr
3187
 * externaddr or can get away with our internal bindaddr
3188
 * 'us' is always overwritten.
3188
 * 'us' is always overwritten.
3189
 */
3189
 */
3190
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
3190
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
3191
{
3191
{
3192
	struct ast_sockaddr theirs;
3192
	struct ast_sockaddr theirs;
3193

    
   
3193

   
3194
	/* Set want_remap to non-zero if we want to remap 'us' to an externally
3194
	/* Set want_remap to non-zero if we want to remap 'us' to an externally
3195
	 * reachable IP address and port. This is done if:
3195
	 * reachable IP address and port. This is done if:
3196
	 * 1. we have a localaddr list (containing 'internal' addresses marked
3196
	 * 1. we have a localaddr list (containing 'internal' addresses marked
3197
	 *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
3197
	 *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
3198
	 *    and AST_SENSE_ALLOW on 'external' ones);
3198
	 *    and AST_SENSE_ALLOW on 'external' ones);
3199
	 * 2. externaddr is set, so we know what to use as the
3199
	 * 2. externaddr is set, so we know what to use as the
3200
	 *    externally visible address;
3200
	 *    externally visible address;
3201
	 * 3. the remote address, 'them', is external;
3201
	 * 3. the remote address, 'them', is external;
3202
	 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
3202
	 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
3203
	 *    when passed to ast_apply_ha() so it does need to be remapped.
3203
	 *    when passed to ast_apply_ha() so it does need to be remapped.
3204
	 *    This fourth condition is checked later.
3204
	 *    This fourth condition is checked later.
3205
	 */
3205
	 */
3206
	int want_remap = 0;
3206
	int want_remap = 0;
3207

    
   
3207

   
3208
	ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
3208
	ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
3209
	/* now ask the system what would it use to talk to 'them' */
3209
	/* now ask the system what would it use to talk to 'them' */
3210
	ast_ouraddrfor(them, us);
3210
	ast_ouraddrfor(them, us);
3211
	ast_sockaddr_copy(&theirs, them);
3211
	ast_sockaddr_copy(&theirs, them);
3212

    
   
3212

   
3213
	if (ast_sockaddr_is_ipv6(&theirs)) {
3213
	if (ast_sockaddr_is_ipv6(&theirs)) {
3214
		if (localaddr && !ast_sockaddr_isnull(&externaddr)) {
3214
		if (localaddr && !ast_sockaddr_isnull(&externaddr)) {
3215
			ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
3215
			ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
3216
				"but we're using IPv6, which doesn't need it. Please "
3216
				"but we're using IPv6, which doesn't need it. Please "
3217
				"remove \"localnet\" and/or \"externaddr\" settings.\n");
3217
				"remove \"localnet\" and/or \"externaddr\" settings.\n");
3218
		}
3218
		}
3219
	} else {
3219
	} else {
3220
		want_remap = localaddr &&
3220
		want_remap = localaddr &&
3221
			!ast_sockaddr_isnull(&externaddr) &&
3221
			!ast_sockaddr_isnull(&externaddr) &&
3222
			ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
3222
			ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
3223
	}
3223
	}
3224

    
   
3224

   
3225
	if (want_remap &&
3225
	if (want_remap &&
3226
	    (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
3226
	    (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
3227
		/* if we used externhost, see if it is time to refresh the info */
3227
		/* if we used externhost, see if it is time to refresh the info */
3228
		if (externexpire && time(NULL) >= externexpire) {
3228
		if (externexpire && time(NULL) >= externexpire) {
3229
			if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
3229
			if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
3230
				ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
3230
				ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
3231
			}
3231
			}
3232
			externexpire = time(NULL) + externrefresh;
3232
			externexpire = time(NULL) + externrefresh;
3233
		}
3233
		}
3234
		if (!ast_sockaddr_isnull(&externaddr)) {
3234
		if (!ast_sockaddr_isnull(&externaddr)) {
3235
			ast_sockaddr_copy(us, &externaddr);
3235
			ast_sockaddr_copy(us, &externaddr);
3236
			switch (p->socket.type) {
3236
			switch (p->socket.type) {
3237
			case SIP_TRANSPORT_TCP:
3237
			case SIP_TRANSPORT_TCP:
3238
				if (!externtcpport && ast_sockaddr_port(&externaddr)) {
3238
				if (!externtcpport && ast_sockaddr_port(&externaddr)) {
3239
					/* for consistency, default to the externaddr port */
3239
					/* for consistency, default to the externaddr port */
3240
					externtcpport = ast_sockaddr_port(&externaddr);
3240
					externtcpport = ast_sockaddr_port(&externaddr);
3241
				}
3241
				}
3242
				ast_sockaddr_set_port(us, externtcpport);
3242
				ast_sockaddr_set_port(us, externtcpport);
3243
				break;
3243
				break;
3244
			case SIP_TRANSPORT_TLS:
3244
			case SIP_TRANSPORT_TLS:
3245
				ast_sockaddr_set_port(us, externtlsport);
3245
				ast_sockaddr_set_port(us, externtlsport);
3246
				break;
3246
				break;
3247
			case SIP_TRANSPORT_UDP:
3247
			case SIP_TRANSPORT_UDP:
3248
				if (!ast_sockaddr_port(&externaddr)) {
3248
				if (!ast_sockaddr_port(&externaddr)) {
3249
					ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3249
					ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3250
				}
3250
				}
3251
				break;
3251
				break;
3252
			default:
3252
			default:
3253
				break;
3253
				break;
3254
			}
3254
			}
3255
		}
3255
		}
3256
		ast_debug(1, "Target address %s is not local, substituting externaddr\n",
3256
		ast_debug(1, "Target address %s is not local, substituting externaddr\n",
3257
			  ast_sockaddr_stringify(them));
3257
			  ast_sockaddr_stringify(them));
3258
	} else if (p) {
3258
	} else if (p) {
3259
		/* no remapping, but we bind to a specific address, so use it. */
3259
		/* no remapping, but we bind to a specific address, so use it. */
3260
		switch (p->socket.type) {
3260
		switch (p->socket.type) {
3261
		case SIP_TRANSPORT_TCP:
3261
		case SIP_TRANSPORT_TCP:
3262
			if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
3262
			if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
3263
				ast_sockaddr_copy(us,
3263
				ast_sockaddr_copy(us,
3264
						  &sip_tcp_desc.local_address);
3264
						  &sip_tcp_desc.local_address);
3265
			} else {
3265
			} else {
3266
				ast_sockaddr_set_port(us,
3266
				ast_sockaddr_set_port(us,
3267
						      ast_sockaddr_port(&sip_tcp_desc.local_address));
3267
						      ast_sockaddr_port(&sip_tcp_desc.local_address));
3268
			}
3268
			}
3269
			break;
3269
			break;
3270
		case SIP_TRANSPORT_TLS:
3270
		case SIP_TRANSPORT_TLS:
3271
			if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
3271
			if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
3272
				ast_sockaddr_copy(us,
3272
				ast_sockaddr_copy(us,
3273
						  &sip_tls_desc.local_address);
3273
						  &sip_tls_desc.local_address);
3274
			} else {
3274
			} else {
3275
				ast_sockaddr_set_port(us,
3275
				ast_sockaddr_set_port(us,
3276
						      ast_sockaddr_port(&sip_tls_desc.local_address));
3276
						      ast_sockaddr_port(&sip_tls_desc.local_address));
3277
			}
3277
			}
3278
			break;
3278
			break;
3279
		case SIP_TRANSPORT_UDP:
3279
		case SIP_TRANSPORT_UDP:
3280
			/* fall through on purpose */
3280
			/* fall through on purpose */
3281
		default:
3281
		default:
3282
			if (!ast_sockaddr_is_any(&bindaddr)) {
3282
			if (!ast_sockaddr_is_any(&bindaddr)) {
3283
				ast_sockaddr_copy(us, &bindaddr);
3283
				ast_sockaddr_copy(us, &bindaddr);
3284
			}
3284
			}
3285
			if (!ast_sockaddr_port(us)) {
3285
			if (!ast_sockaddr_port(us)) {
3286
				ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3286
				ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3287
			}
3287
			}
3288
		}
3288
		}
3289
	} else if (!ast_sockaddr_is_any(&bindaddr)) {
3289
	} else if (!ast_sockaddr_is_any(&bindaddr)) {
3290
		ast_sockaddr_copy(us, &bindaddr);
3290
		ast_sockaddr_copy(us, &bindaddr);
3291
	}
3291
	}
3292
	ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", get_transport(p->socket.type), ast_sockaddr_stringify(us));
3292
	ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", get_transport(p->socket.type), ast_sockaddr_stringify(us));
3293
}
3293
}
3294

    
   
3294

   
3295
/*! \brief Append to SIP dialog history with arg list  */
3295
/*! \brief Append to SIP dialog history with arg list  */
3296
static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
3296
static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
3297
{
3297
{
3298
	char buf[80], *c = buf; /* max history length */
3298
	char buf[80], *c = buf; /* max history length */
3299
	struct sip_history *hist;
3299
	struct sip_history *hist;
3300
	int l;
3300
	int l;
3301

    
   
3301

   
3302
	vsnprintf(buf, sizeof(buf), fmt, ap);
3302
	vsnprintf(buf, sizeof(buf), fmt, ap);
3303
	strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
3303
	strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
3304
	l = strlen(buf) + 1;
3304
	l = strlen(buf) + 1;
3305
	if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
3305
	if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
3306
		return;
3306
		return;
3307
	}
3307
	}
3308
	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
3308
	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
3309
		ast_free(hist);
3309
		ast_free(hist);
3310
		return;
3310
		return;
3311
	}
3311
	}
3312
	memcpy(hist->event, buf, l);
3312
	memcpy(hist->event, buf, l);
3313
	if (p->history_entries == MAX_HISTORY_ENTRIES) {
3313
	if (p->history_entries == MAX_HISTORY_ENTRIES) {
3314
		struct sip_history *oldest;
3314
		struct sip_history *oldest;
3315
		oldest = AST_LIST_REMOVE_HEAD(p->history, list);
3315
		oldest = AST_LIST_REMOVE_HEAD(p->history, list);
3316
		p->history_entries--;
3316
		p->history_entries--;
3317
		ast_free(oldest);
3317
		ast_free(oldest);
3318
	}
3318
	}
3319
	AST_LIST_INSERT_TAIL(p->history, hist, list);
3319
	AST_LIST_INSERT_TAIL(p->history, hist, list);
3320
	p->history_entries++;
3320
	p->history_entries++;
3321
}
3321
}
3322

    
   
3322

   
3323
/*! \brief Append to SIP dialog history with arg list  */
3323
/*! \brief Append to SIP dialog history with arg list  */
3324
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3324
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3325
{
3325
{
3326
	va_list ap;
3326
	va_list ap;
3327

    
   
3327

   
3328
	if (!p) {
3328
	if (!p) {
3329
		return;
3329
		return;
3330
	}
3330
	}
3331

    
   
3331

   
3332
	if (!p->do_history && !recordhistory && !dumphistory) {
3332
	if (!p->do_history && !recordhistory && !dumphistory) {
3333
		return;
3333
		return;
3334
	}
3334
	}
3335

    
   
3335

   
3336
	va_start(ap, fmt);
3336
	va_start(ap, fmt);
3337
	append_history_va(p, fmt, ap);
3337
	append_history_va(p, fmt, ap);
3338
	va_end(ap);
3338
	va_end(ap);
3339

    
   
3339

   
3340
	return;
3340
	return;
3341
}
3341
}
3342

    
   
3342

   
3343
/*! \brief Retransmit SIP message if no answer (Called from scheduler) */
3343
/*! \brief Retransmit SIP message if no answer (Called from scheduler) */
3344
static int retrans_pkt(const void *data)
3344
static int retrans_pkt(const void *data)
3345
{
3345
{
3346
	struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
3346
	struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
3347
	int reschedule = DEFAULT_RETRANS;
3347
	int reschedule = DEFAULT_RETRANS;
3348
	int xmitres = 0;
3348
	int xmitres = 0;
3349
	/* how many ms until retrans timeout is reached */
3349
	/* how many ms until retrans timeout is reached */
3350
	int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
3350
	int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
3351

    
   
3351

   
3352
	/* Do not retransmit if time out is reached. This will be negative if the time between
3352
	/* Do not retransmit if time out is reached. This will be negative if the time between
3353
	 * the first transmission and now is larger than our timeout period. This is a fail safe
3353
	 * the first transmission and now is larger than our timeout period. This is a fail safe
3354
	 * check in case the scheduler gets behind or the clock is changed. */
3354
	 * check in case the scheduler gets behind or the clock is changed. */
3355
	if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
3355
	if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
3356
		pkt->retrans_stop = 1;
3356
		pkt->retrans_stop = 1;
3357
	}
3357
	}
3358

    
   
3358

   
3359
	/* Lock channel PVT */
3359
	/* Lock channel PVT */
3360
	sip_pvt_lock(pkt->owner);
3360
	sip_pvt_lock(pkt->owner);
3361

    
   
3361

   
3362
	if (!pkt->retrans_stop) {
3362
	if (!pkt->retrans_stop) {
3363
		pkt->retrans++;
3363
		pkt->retrans++;
3364
		if (!pkt->timer_t1) {	/* Re-schedule using timer_a and timer_t1 */
3364
		if (!pkt->timer_t1) {	/* Re-schedule using timer_a and timer_t1 */
3365
			if (sipdebug) {
3365
			if (sipdebug) {
3366
				ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
3366
				ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
3367
					pkt->retransid,
3367
					pkt->retransid,
3368
					sip_methods[pkt->method].text,
3368
					sip_methods[pkt->method].text,
3369
					pkt->method);
3369
					pkt->method);
3370
			}
3370
			}
3371
		} else {
3371
		} else {
3372
			int siptimer_a;
3372
			int siptimer_a;
3373

    
   
3373

   
3374
			if (sipdebug) {
3374
			if (sipdebug) {
3375
				ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
3375
				ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
3376
					pkt->retransid,
3376
					pkt->retransid,
3377
					pkt->retrans,
3377
					pkt->retrans,
3378
					sip_methods[pkt->method].text,
3378
					sip_methods[pkt->method].text,
3379
					pkt->method);
3379
					pkt->method);
3380
			}
3380
			}
3381
			if (!pkt->timer_a) {
3381
			if (!pkt->timer_a) {
3382
				pkt->timer_a = 2 ;
3382
				pkt->timer_a = 2 ;
3383
			} else {
3383
			} else {
3384
				pkt->timer_a = 2 * pkt->timer_a;
3384
				pkt->timer_a = 2 * pkt->timer_a;
3385
			}
3385
			}
3386

    
   
3386

   
3387
			/* For non-invites, a maximum of 4 secs */
3387
			/* For non-invites, a maximum of 4 secs */
3388
			siptimer_a = pkt->timer_t1 * pkt->timer_a;	/* Double each time */
3388
			siptimer_a = pkt->timer_t1 * pkt->timer_a;	/* Double each time */
3389
			if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
3389
			if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
3390
				siptimer_a = 4000;
3390
				siptimer_a = 4000;
3391
			}
3391
			}
3392

    
   
3392

   
3393
			/* Reschedule re-transmit */
3393
			/* Reschedule re-transmit */
3394
			reschedule = siptimer_a;
3394
			reschedule = siptimer_a;
3395
			ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
3395
			ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
3396
				pkt->retrans + 1,
3396
				pkt->retrans + 1,
3397
				siptimer_a,
3397
				siptimer_a,
3398
				pkt->timer_t1,
3398
				pkt->timer_t1,
3399
				pkt->retransid);
3399
				pkt->retransid);
3400
		}
3400
		}
3401

    
   
3401

   
3402
		if (sip_debug_test_pvt(pkt->owner)) {
3402
		if (sip_debug_test_pvt(pkt->owner)) {
3403
			const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
3403
			const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
3404
			ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
3404
			ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
3405
				pkt->retrans, sip_nat_mode(pkt->owner),
3405
				pkt->retrans, sip_nat_mode(pkt->owner),
3406
				ast_sockaddr_stringify(dst),
3406
				ast_sockaddr_stringify(dst),
3407
				pkt->data->str);
3407
				pkt->data->str);
3408
		}
3408
		}
3409

    
   
3409

   
3410
		append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
3410
		append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
3411
		xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
3411
		xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
3412

    
   
3412

   
3413
		/* If there was no error during the network transmission, schedule the next retransmission,
3413
		/* If there was no error during the network transmission, schedule the next retransmission,
3414
		 * but if the next retransmission is going to be beyond our timeout period, mark the packet's
3414
		 * but if the next retransmission is going to be beyond our timeout period, mark the packet's
3415
		 * stop_retrans value and set the next retransmit to be the exact time of timeout.  This will
3415
		 * stop_retrans value and set the next retransmit to be the exact time of timeout.  This will
3416
		 * allow any responses to the packet to be processed before the packet is destroyed on the next
3416
		 * allow any responses to the packet to be processed before the packet is destroyed on the next
3417
		 * call to this function by the scheduler. */
3417
		 * call to this function by the scheduler. */
3418
		if (xmitres != XMIT_ERROR) {
3418
		if (xmitres != XMIT_ERROR) {
3419
			if (reschedule >= diff) {
3419
			if (reschedule >= diff) {
3420
				pkt->retrans_stop = 1;
3420
				pkt->retrans_stop = 1;
3421
				reschedule = diff;
3421
				reschedule = diff;
3422
			}
3422
			}
3423
			sip_pvt_unlock(pkt->owner);
3423
			sip_pvt_unlock(pkt->owner);
3424
			return  reschedule;
3424
			return  reschedule;
3425
		}
3425
		}
3426
	}
3426
	}
3427

    
   
3427

   
3428
	/* At this point, either the packet's retransmission timed out, or there was a
3428
	/* At this point, either the packet's retransmission timed out, or there was a
3429
	 * transmission error, either way destroy the scheduler item and this packet. */
3429
	 * transmission error, either way destroy the scheduler item and this packet. */
3430

    
   
3430

   
3431
	pkt->retransid = -1; /* Kill this scheduler item */
3431
	pkt->retransid = -1; /* Kill this scheduler item */
3432

    
   
3432

   
3433
	if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
3433
	if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
3434
		if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
3434
		if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
3435
			ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s for seqno %d (%s %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n"
3435
			ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s for seqno %d (%s %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n"
3436
				"Packet timed out after %dms with no response\n",
3436
				"Packet timed out after %dms with no response\n",
3437
				pkt->owner->callid,
3437
				pkt->owner->callid,
3438
				pkt->seqno,
3438
				pkt->seqno,
3439
				pkt->is_fatal ? "Critical" : "Non-critical",
3439
				pkt->is_fatal ? "Critical" : "Non-critical",
3440
				pkt->is_resp ? "Response" : "Request",
3440
				pkt->is_resp ? "Response" : "Request",
3441
				(int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
3441
				(int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
3442
		}
3442
		}
3443
	} else if (pkt->method == SIP_OPTIONS && sipdebug) {
3443
	} else if (pkt->method == SIP_OPTIONS && sipdebug) {
3444
		ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n", pkt->owner->callid);
3444
		ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n", pkt->owner->callid);
3445
	}
3445
	}
3446

    
   
3446

   
3447
	if (xmitres == XMIT_ERROR) {
3447
	if (xmitres == XMIT_ERROR) {
3448
		ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
3448
		ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
3449
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3449
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3450
	} else {
3450
	} else {
3451
		append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3451
		append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3452
	}
3452
	}
3453

    
   
3453

   
3454
	if (pkt->is_fatal) {
3454
	if (pkt->is_fatal) {
3455
		while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
3455
		while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
3456
			sip_pvt_unlock(pkt->owner);	/* SIP_PVT, not channel */
3456
			sip_pvt_unlock(pkt->owner);	/* SIP_PVT, not channel */
3457
			usleep(1);
3457
			usleep(1);
3458
			sip_pvt_lock(pkt->owner);
3458
			sip_pvt_lock(pkt->owner);
3459
		}
3459
		}
3460
		if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
3460
		if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
3461
			pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
3461
			pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
3462
		}
3462
		}
3463
		if (pkt->owner->owner) {
3463
		if (pkt->owner->owner) {
3464
			ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions).\n", pkt->owner->callid);
3464
			ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions).\n", pkt->owner->callid);
3465

    
   
3465

   
3466
			if (pkt->is_resp &&
3466
			if (pkt->is_resp &&
3467
				(pkt->response_code >= 200) &&
3467
				(pkt->response_code >= 200) &&
3468
				(pkt->response_code < 300) &&
3468
				(pkt->response_code < 300) &&
3469
				pkt->owner->pendinginvite &&
3469
				pkt->owner->pendinginvite &&
3470
				ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
3470
				ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
3471
				/* This is a timeout of the 2XX response to a pending INVITE.  In this case terminate the INVITE
3471
				/* This is a timeout of the 2XX response to a pending INVITE.  In this case terminate the INVITE
3472
				 * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup
3472
				 * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup
3473
				 * will send the BYE as long as the dialog is not set as "alreadygone")
3473
				 * will send the BYE as long as the dialog is not set as "alreadygone")
3474
				 * RFC 3261 section 13.3.1.4.
3474
				 * RFC 3261 section 13.3.1.4.
3475
				 * "If the server retransmits the 2xx response for 64*T1 seconds without receiving
3475
				 * "If the server retransmits the 2xx response for 64*T1 seconds without receiving
3476
				 * an ACK, the dialog is confirmed, but the session SHOULD be terminated.  This is
3476
				 * an ACK, the dialog is confirmed, but the session SHOULD be terminated.  This is
3477
				 * accomplished with a BYE, as described in Section 15." */
3477
				 * accomplished with a BYE, as described in Section 15." */
3478
				pkt->owner->invitestate = INV_TERMINATED;
3478
				pkt->owner->invitestate = INV_TERMINATED;
3479
				pkt->owner->pendinginvite = 0;
3479
				pkt->owner->pendinginvite = 0;
3480
			} else {
3480
			} else {
3481
				/* there is nothing left to do, mark the dialog as gone */
3481
				/* there is nothing left to do, mark the dialog as gone */
3482
				sip_alreadygone(pkt->owner);
3482
				sip_alreadygone(pkt->owner);
3483
			}
3483
			}
3484
			ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
3484
			ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
3485
			ast_channel_unlock(pkt->owner->owner);
3485
			ast_channel_unlock(pkt->owner->owner);
3486
		} else {
3486
		} else {
3487
			/* If no channel owner, destroy now */
3487
			/* If no channel owner, destroy now */
3488

    
   
3488

   
3489
			/* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
3489
			/* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
3490
			if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
3490
			if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
3491
				pvt_set_needdestroy(pkt->owner, "no response to critical packet");
3491
				pvt_set_needdestroy(pkt->owner, "no response to critical packet");
3492
				sip_alreadygone(pkt->owner);
3492
				sip_alreadygone(pkt->owner);
3493
				append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
3493
				append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
3494
			}
3494
			}
3495
		}
3495
		}
3496
	}
3496
	}
3497

    
   
3497

   
3498
	if (pkt->method == SIP_BYE) {
3498
	if (pkt->method == SIP_BYE) {
3499
		/* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
3499
		/* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
3500
		sip_alreadygone(pkt->owner);
3500
		sip_alreadygone(pkt->owner);
3501
		if (pkt->owner->owner) {
3501
		if (pkt->owner->owner) {
3502
			ast_channel_unlock(pkt->owner->owner);
3502
			ast_channel_unlock(pkt->owner->owner);
3503
		}
3503
		}
3504
		append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
3504
		append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
3505
		pvt_set_needdestroy(pkt->owner, "no response to BYE");
3505
		pvt_set_needdestroy(pkt->owner, "no response to BYE");
3506
	}
3506
	}
3507

    
   
3507

   
3508
	/* Remove the packet */
3508
	/* Remove the packet */
3509
	for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
3509
	for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
3510
		if (cur == pkt) {
3510
		if (cur == pkt) {
3511
			UNLINK(cur, pkt->owner->packets, prev);
3511
			UNLINK(cur, pkt->owner->packets, prev);
3512
			sip_pvt_unlock(pkt->owner);
3512
			sip_pvt_unlock(pkt->owner);
3513
			if (pkt->owner) {
3513
			if (pkt->owner) {
3514
				pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3514
				pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3515
			}
3515
			}
3516
			if (pkt->data) {
3516
			if (pkt->data) {
3517
				ast_free(pkt->data);
3517
				ast_free(pkt->data);
3518
			}
3518
			}
3519
			pkt->data = NULL;
3519
			pkt->data = NULL;
3520
			ast_free(pkt);
3520
			ast_free(pkt);
3521
			return 0;
3521
			return 0;
3522
		}
3522
		}
3523
	}
3523
	}
3524
	/* error case */
3524
	/* error case */
3525
	ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
3525
	ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
3526
	sip_pvt_unlock(pkt->owner);
3526
	sip_pvt_unlock(pkt->owner);
3527
	return 0;
3527
	return 0;
3528
}
3528
}
3529

    
   
3529

   
3530
/*! \brief Transmit packet with retransmits
3530
/*! \brief Transmit packet with retransmits
3531
	\return 0 on success, -1 on failure to allocate packet
3531
	\return 0 on success, -1 on failure to allocate packet
3532
*/
3532
*/
3533
static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod)
3533
static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod)
3534
{
3534
{
3535
	struct sip_pkt *pkt = NULL;
3535
	struct sip_pkt *pkt = NULL;
3536
	int siptimer_a = DEFAULT_RETRANS;
3536
	int siptimer_a = DEFAULT_RETRANS;
3537
	int xmitres = 0;
3537
	int xmitres = 0;
3538
	int respid;
3538
	int respid;
3539

    
   
3539

   
3540
	if (sipmethod == SIP_INVITE) {
3540
	if (sipmethod == SIP_INVITE) {
3541
		/* Note this is a pending invite */
3541
		/* Note this is a pending invite */
3542
		p->pendinginvite = seqno;
3542
		p->pendinginvite = seqno;
3543
	}
3543
	}
3544

    
   
3544

   
3545
	/* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
3545
	/* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
3546
	/* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
3546
	/* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
3547
	/*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
3547
	/*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
3548
	if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
3548
	if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
3549
		xmitres = __sip_xmit(p, data, len);	/* Send packet */
3549
		xmitres = __sip_xmit(p, data, len);	/* Send packet */
3550
		if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
3550
		if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
3551
			append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
3551
			append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
3552
			return AST_FAILURE;
3552
			return AST_FAILURE;
3553
		} else {
3553
		} else {
3554
			return AST_SUCCESS;
3554
			return AST_SUCCESS;
3555
		}
3555
		}
3556
	}
3556
	}
3557

    
   
3557

   
3558
	if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1))) {
3558
	if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1))) {
3559
		return AST_FAILURE;
3559
		return AST_FAILURE;
3560
	}
3560
	}
3561
	/* copy data, add a terminator and save length */
3561
	/* copy data, add a terminator and save length */
3562
	if (!(pkt->data = ast_str_create(len))) {
3562
	if (!(pkt->data = ast_str_create(len))) {
3563
		ast_free(pkt);
3563
		ast_free(pkt);
3564
		return AST_FAILURE;
3564
		return AST_FAILURE;
3565
	}
3565
	}
3566
	ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
3566
	ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
3567
	pkt->packetlen = len;
3567
	pkt->packetlen = len;
3568
	/* copy other parameters from the caller */
3568
	/* copy other parameters from the caller */
3569
	pkt->method = sipmethod;
3569
	pkt->method = sipmethod;
3570
	pkt->seqno = seqno;
3570
	pkt->seqno = seqno;
3571
	pkt->is_resp = resp;
3571
	pkt->is_resp = resp;
3572
	pkt->is_fatal = fatal;
3572
	pkt->is_fatal = fatal;
3573
	pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
3573
	pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
3574
	pkt->next = p->packets;
3574
	pkt->next = p->packets;
3575
	p->packets = pkt;	/* Add it to the queue */
3575
	p->packets = pkt;	/* Add it to the queue */
3576
	if (resp) {
3576
	if (resp) {
3577
		/* Parse out the response code */
3577
		/* Parse out the response code */
3578
		if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
3578
		if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
3579
			pkt->response_code = respid;
3579
			pkt->response_code = respid;
3580
		}
3580
		}
3581
	}
3581
	}
3582
	pkt->timer_t1 = p->timer_t1;	/* Set SIP timer T1 */
3582
	pkt->timer_t1 = p->timer_t1;	/* Set SIP timer T1 */
3583
	pkt->retransid = -1;
3583
	pkt->retransid = -1;
3584
	if (pkt->timer_t1) {
3584
	if (pkt->timer_t1) {
3585
		siptimer_a = pkt->timer_t1;
3585
		siptimer_a = pkt->timer_t1;
3586
	}
3586
	}
3587

    
   
3587

   
3588
	pkt->time_sent = ast_tvnow(); /* time packet was sent */
3588
	pkt->time_sent = ast_tvnow(); /* time packet was sent */
3589
	pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
3589
	pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
3590

    
   
3590

   
3591
	/* Schedule retransmission */
3591
	/* Schedule retransmission */
3592
	AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
3592
	AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
3593
	if (sipdebug) {
3593
	if (sipdebug) {
3594
		ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
3594
		ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
3595
	}
3595
	}
3596

    
   
3596

   
3597
	xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);	/* Send packet */
3597
	xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);	/* Send packet */
3598

    
   
3598

   
3599
	if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
3599
	if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
3600
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3600
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3601
		ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
3601
		ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
3602
		AST_SCHED_DEL(sched, pkt->retransid);
3602
		AST_SCHED_DEL(sched, pkt->retransid);
3603
		p->packets = pkt->next;
3603
		p->packets = pkt->next;
3604
		pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3604
		pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3605
		ast_free(pkt->data);
3605
		ast_free(pkt->data);
3606
		ast_free(pkt);
3606
		ast_free(pkt);
3607
		return AST_FAILURE;
3607
		return AST_FAILURE;
3608
	} else {
3608
	} else {
3609
		/* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
3609
		/* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
3610
		 * only wakes up every 1000ms by default, we have to poke the thread here to make
3610
		 * only wakes up every 1000ms by default, we have to poke the thread here to make
3611
		 * sure it successfully detects this must be retransmitted in less time than
3611
		 * sure it successfully detects this must be retransmitted in less time than
3612
		 * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
3612
		 * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
3613
		if (monitor_thread != AST_PTHREADT_NULL) {
3613
		if (monitor_thread != AST_PTHREADT_NULL) {
3614
			pthread_kill(monitor_thread, SIGURG);
3614
			pthread_kill(monitor_thread, SIGURG);
3615
		}
3615
		}
3616
		return AST_SUCCESS;
3616
		return AST_SUCCESS;
3617
	}
3617
	}
3618
}
3618
}
3619

    
   
3619

   
3620
/*! \brief Kill a SIP dialog (called only by the scheduler)
3620
/*! \brief Kill a SIP dialog (called only by the scheduler)
3621
 * The scheduler has a reference to this dialog when p->autokillid != -1,
3621
 * The scheduler has a reference to this dialog when p->autokillid != -1,
3622
 * and we are called using that reference. So if the event is not
3622
 * and we are called using that reference. So if the event is not
3623
 * rescheduled, we need to call dialog_unref().
3623
 * rescheduled, we need to call dialog_unref().
3624
 */
3624
 */
3625
static int __sip_autodestruct(const void *data)
3625
static int __sip_autodestruct(const void *data)
3626
{
3626
{
3627
	struct sip_pvt *p = (struct sip_pvt *)data;
3627
	struct sip_pvt *p = (struct sip_pvt *)data;
3628

    
   
3628

   
3629
	/* If this is a subscription, tell the phone that we got a timeout */
3629
	/* If this is a subscription, tell the phone that we got a timeout */
3630
	if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
3630
	if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
3631
		transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);	/* Send last notification */
3631
		transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);	/* Send last notification */
3632
		p->subscribed = NONE;
3632
		p->subscribed = NONE;
3633
		append_history(p, "Subscribestatus", "timeout");
3633
		append_history(p, "Subscribestatus", "timeout");
3634
		ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
3634
		ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
3635
		return 10000;	/* Reschedule this destruction so that we know that it's gone */
3635
		return 10000;	/* Reschedule this destruction so that we know that it's gone */
3636
	}
3636
	}
3637

    
   
3637

   
3638
	/* If there are packets still waiting for delivery, delay the destruction */
3638
	/* If there are packets still waiting for delivery, delay the destruction */
3639
	if (p->packets) {
3639
	if (p->packets) {
3640
		if (!p->needdestroy) {
3640
		if (!p->needdestroy) {
3641
			char method_str[31];
3641
			char method_str[31];
3642
			ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
3642
			ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
3643
			append_history(p, "ReliableXmit", "timeout");
3643
			append_history(p, "ReliableXmit", "timeout");
3644
			if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
3644
			if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
3645
				if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
3645
				if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
3646
					pvt_set_needdestroy(p, "autodestruct");
3646
					pvt_set_needdestroy(p, "autodestruct");
3647
				}
3647
				}
3648
			}
3648
			}
3649
			return 10000;
3649
			return 10000;
3650
		} else {
3650
		} else {
3651
			/* They've had their chance to respond. Time to bail */
3651
			/* They've had their chance to respond. Time to bail */
3652
			__sip_pretend_ack(p);
3652
			__sip_pretend_ack(p);
3653
		}
3653
		}
3654
	}
3654
	}
3655

    
   
3655

   
3656
	/* Reset schedule ID */
3656
	/* Reset schedule ID */
3657
	p->autokillid = -1;
3657
	p->autokillid = -1;
3658

    
   
3658

   
3659

    
   
3659

   
3660
	/*
3660
	/*
3661
	 * Lock both the pvt and the channel safely so that we can queue up a frame.
3661
	 * Lock both the pvt and the channel safely so that we can queue up a frame.
3662
	 */
3662
	 */
3663
	sip_pvt_lock(p);
3663
	sip_pvt_lock(p);
3664
	while (p->owner && ast_channel_trylock(p->owner)) {
3664
	while (p->owner && ast_channel_trylock(p->owner)) {
3665
		sip_pvt_unlock(p);
3665
		sip_pvt_unlock(p);
3666
		sched_yield();
3666
		sched_yield();
3667
		sip_pvt_lock(p);
3667
		sip_pvt_lock(p);
3668
	}
3668
	}
3669

    
   
3669

   
3670
	if (p->owner) {
3670
	if (p->owner) {
3671
		ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
3671
		ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
3672
		ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
3672
		ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
3673
		ast_channel_unlock(p->owner);
3673
		ast_channel_unlock(p->owner);
3674
	} else if (p->refer && !p->alreadygone) {
3674
	} else if (p->refer && !p->alreadygone) {
3675
		ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
3675
		ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
3676
		transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3676
		transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3677
		append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
3677
		append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
3678
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3678
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3679
	} else {
3679
	} else {
3680
		append_history(p, "AutoDestroy", "%s", p->callid);
3680
		append_history(p, "AutoDestroy", "%s", p->callid);
3681
		ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
3681
		ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
3682
		dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
3682
		dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
3683
		/* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
3683
		/* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
3684
		/* sip_destroy(p); */		/* Go ahead and destroy dialog. All attempts to recover is done */
3684
		/* sip_destroy(p); */		/* Go ahead and destroy dialog. All attempts to recover is done */
3685
		/* sip_destroy also absorbs the reference */
3685
		/* sip_destroy also absorbs the reference */
3686
	}
3686
	}
3687

    
   
3687

   
3688
	sip_pvt_unlock(p);
3688
	sip_pvt_unlock(p);
3689

    
   
3689

   
3690
	dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
3690
	dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
3691

    
   
3691

   
3692
	return 0;
3692
	return 0;
3693
}
3693
}
3694

    
   
3694

   
3695
/*! \brief Schedule final destruction of SIP dialog.  This can not be canceled.
3695
/*! \brief Schedule final destruction of SIP dialog.  This can not be canceled.
3696
 *  This function is used to keep a dialog around for a period of time in order
3696
 *  This function is used to keep a dialog around for a period of time in order
3697
 *  to properly respond to any retransmits. */
3697
 *  to properly respond to any retransmits. */
3698
void sip_scheddestroy_final(struct sip_pvt *p, int ms)
3698
void sip_scheddestroy_final(struct sip_pvt *p, int ms)
3699
{
3699
{
3700
	if (p->final_destruction_scheduled) {
3700
	if (p->final_destruction_scheduled) {
3701
		return; /* already set final destruction */
3701
		return; /* already set final destruction */
3702
	}
3702
	}
3703

    
   
3703

   
3704
	sip_scheddestroy(p, ms);
3704
	sip_scheddestroy(p, ms);
3705
	if (p->autokillid != -1) {
3705
	if (p->autokillid != -1) {
3706
		p->final_destruction_scheduled = 1;
3706
		p->final_destruction_scheduled = 1;
3707
	}
3707
	}
3708
}
3708
}
3709

    
   
3709

   
3710
/*! \brief Schedule destruction of SIP dialog */
3710
/*! \brief Schedule destruction of SIP dialog */
3711
void sip_scheddestroy(struct sip_pvt *p, int ms)
3711
void sip_scheddestroy(struct sip_pvt *p, int ms)
3712
{
3712
{
3713
	if (p->final_destruction_scheduled) {
3713
	if (p->final_destruction_scheduled) {
3714
		return; /* already set final destruction */
3714
		return; /* already set final destruction */
3715
	}
3715
	}
3716

    
   
3716

   
3717
	if (ms < 0) {
3717
	if (ms < 0) {
3718
		if (p->timer_t1 == 0) {
3718
		if (p->timer_t1 == 0) {
3719
			p->timer_t1 = global_t1;	/* Set timer T1 if not set (RFC 3261) */
3719
			p->timer_t1 = global_t1;	/* Set timer T1 if not set (RFC 3261) */
3720
		}
3720
		}
3721
		if (p->timer_b == 0) {
3721
		if (p->timer_b == 0) {
3722
			p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
3722
			p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
3723
		}
3723
		}
3724
		ms = p->timer_t1 * 64;
3724
		ms = p->timer_t1 * 64;
3725
	}
3725
	}
3726
	if (sip_debug_test_pvt(p)) {
3726
	if (sip_debug_test_pvt(p)) {
3727
		ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
3727
		ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
3728
	}
3728
	}
3729
	if (sip_cancel_destroy(p)) {
3729
	if (sip_cancel_destroy(p)) {
3730
		ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
3730
		ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
3731
	}
3731
	}
3732

    
   
3732

   
3733
	if (p->do_history) {
3733
	if (p->do_history) {
3734
		append_history(p, "SchedDestroy", "%d ms", ms);
3734
		append_history(p, "SchedDestroy", "%d ms", ms);
3735
	}
3735
	}
3736
	p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
3736
	p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
3737

    
   
3737

   
3738
	if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
3738
	if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
3739
		stop_session_timer(p);
3739
		stop_session_timer(p);
3740
	}
3740
	}
3741
}
3741
}
3742

    
   
3742

   
3743
/*! \brief Cancel destruction of SIP dialog.
3743
/*! \brief Cancel destruction of SIP dialog.
3744
 * Be careful as this also absorbs the reference - if you call it
3744
 * Be careful as this also absorbs the reference - if you call it
3745
 * from within the scheduler, this might be the last reference.
3745
 * from within the scheduler, this might be the last reference.
3746
 */
3746
 */
3747
int sip_cancel_destroy(struct sip_pvt *p)
3747
int sip_cancel_destroy(struct sip_pvt *p)
3748
{
3748
{
3749
	int res = 0;
3749
	int res = 0;
3750

    
   
3750

   
3751
	if (p->final_destruction_scheduled) {
3751
	if (p->final_destruction_scheduled) {
3752
		return res;
3752
		return res;
3753
	}
3753
	}
3754

    
   
3754

   
3755
	if (p->autokillid > -1) {
3755
	if (p->autokillid > -1) {
3756
		int res3;
3756
		int res3;
3757

    
   
3757

   
3758
		if (!(res3 = ast_sched_del(sched, p->autokillid))) {
3758
		if (!(res3 = ast_sched_del(sched, p->autokillid))) {
3759
			append_history(p, "CancelDestroy", "");
3759
			append_history(p, "CancelDestroy", "");
3760
			p->autokillid = -1;
3760
			p->autokillid = -1;
3761
			dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
3761
			dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
3762
		}
3762
		}
3763
	}
3763
	}
3764
	return res;
3764
	return res;
3765
}
3765
}
3766

    
   
3766

   
3767
/*! \brief Acknowledges receipt of a packet and stops retransmission
3767
/*! \brief Acknowledges receipt of a packet and stops retransmission
3768
 * called with p locked*/
3768
 * called with p locked*/
3769
int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
3769
int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
3770
{
3770
{
3771
	struct s