Review Board 1.7.16


Use the correct IP address in the c and o sdp lines when using an externally mapped IP address

Review Request #566 - Created March 16, 2010 and submitted

ebroad
/trunk
17044
Reviewers
asterisk-dev
Asterisk
The issue stems from a call to ast_rtp_instance_get_local_address() in chan_sip.c in get_our_media_address(). ast_rtp_instance_get_local_address() will always return the internal IP address of the Asterisk machine, which could pose a problem when using NAT.

A simple solution would be to override {v,t}sin->sin_addr in get_our_media_address() with p->ourip.sin_addr.s_addr if it is different(which is what the attached diff does), though I don't know what that might break.

Edit 1: This patch short-circuits some logic later on in get_our_media_address(). ast_rtp_instance_get_local_address() does exactly as the function name suggests, it gets the local address of the machine the Asterisk is running on, which is bad for NAT setups. Should we be calling this in get_our_media_address() or instead just use p->ourip? or should we try to stick with letting the RTP engine decide, and modifying ast_rtp_instance_get_local_address() to return our externally mapped IP when appropriate, which would break from what the function is supposed to do? Comments anyone? 
Applied to trunk, compiled, fax and voice calls made to and from Asterisk successfully.

Changes between revision 3 and 4

1 2 3 4
1 2 3 4

  1. /trunk/channels/chan_sip.c: Loading...
/trunk/channels/chan_sip.c
Diff Revision 3 Diff Revision 4
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
	<depend>chan_local</depend>
165
	<depend>chan_local</depend>
166
 ***/
166
 ***/
167

    
   
167

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

    
   
169

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

    
   
176

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

    
   
184

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

    
   
187

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

    
   
205

   
206
*/
206
*/
207

    
   
207

   
208
#include "asterisk.h"
208
#include "asterisk.h"
209

    
   
209

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

    
   
211

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

    
   
216

   
217
#include "asterisk/network.h"
217
#include "asterisk/network.h"
218
#include "asterisk/paths.h"	/* need ast_config_AST_SYSTEM_NAME */
218
#include "asterisk/paths.h"	/* need ast_config_AST_SYSTEM_NAME */
219
/*
219
/*
220
   Uncomment the define below,  if you are having refcount related memory leaks.
220
   Uncomment the define below,  if you are having refcount related memory leaks.
221
   With this uncommented, this module will generate a file, /tmp/refs, which contains
221
   With this uncommented, this module will generate a file, /tmp/refs, which contains
222
   a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
222
   a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
223
   be modified to ao2_t_* calls, and include a tag describing what is happening with
223
   be modified to ao2_t_* calls, and include a tag describing what is happening with
224
   enough detail, to make pairing up a reference count increment with its corresponding decrement.
224
   enough detail, to make pairing up a reference count increment with its corresponding decrement.
225
   The refcounter program in utils/ can be invaluable in highlighting objects that are not
225
   The refcounter program in utils/ can be invaluable in highlighting objects that are not
226
   balanced, along with the complete history for that object.
226
   balanced, along with the complete history for that object.
227
   In normal operation, the macros defined will throw away the tags, so they do not
227
   In normal operation, the macros defined will throw away the tags, so they do not
228
   affect the speed of the program at all. They can be considered to be documentation.
228
   affect the speed of the program at all. They can be considered to be documentation.
229
*/
229
*/
230
/* #define  REF_DEBUG 1 */
230
/* #define  REF_DEBUG 1 */
231
#include "asterisk/lock.h"
231
#include "asterisk/lock.h"
232
#include "asterisk/config.h"
232
#include "asterisk/config.h"
233
#include "asterisk/module.h"
233
#include "asterisk/module.h"
234
#include "asterisk/pbx.h"
234
#include "asterisk/pbx.h"
235
#include "asterisk/sched.h"
235
#include "asterisk/sched.h"
236
#include "asterisk/io.h"
236
#include "asterisk/io.h"
237
#include "asterisk/rtp_engine.h"
237
#include "asterisk/rtp_engine.h"
238
#include "asterisk/udptl.h"
238
#include "asterisk/udptl.h"
239
#include "asterisk/acl.h"
239
#include "asterisk/acl.h"
240
#include "asterisk/manager.h"
240
#include "asterisk/manager.h"
241
#include "asterisk/callerid.h"
241
#include "asterisk/callerid.h"
242
#include "asterisk/cli.h"
242
#include "asterisk/cli.h"
243
#include "asterisk/musiconhold.h"
243
#include "asterisk/musiconhold.h"
244
#include "asterisk/dsp.h"
244
#include "asterisk/dsp.h"
245
#include "asterisk/features.h"
245
#include "asterisk/features.h"
246
#include "asterisk/srv.h"
246
#include "asterisk/srv.h"
247
#include "asterisk/astdb.h"
247
#include "asterisk/astdb.h"
248
#include "asterisk/causes.h"
248
#include "asterisk/causes.h"
249
#include "asterisk/utils.h"
249
#include "asterisk/utils.h"
250
#include "asterisk/file.h"
250
#include "asterisk/file.h"
251
#include "asterisk/astobj2.h"
251
#include "asterisk/astobj2.h"
252
#include "asterisk/dnsmgr.h"
252
#include "asterisk/dnsmgr.h"
253
#include "asterisk/devicestate.h"
253
#include "asterisk/devicestate.h"
254
#include "asterisk/monitor.h"
254
#include "asterisk/monitor.h"
255
#include "asterisk/netsock2.h"
255
#include "asterisk/netsock2.h"
256
#include "asterisk/localtime.h"
256
#include "asterisk/localtime.h"
257
#include "asterisk/abstract_jb.h"
257
#include "asterisk/abstract_jb.h"
258
#include "asterisk/threadstorage.h"
258
#include "asterisk/threadstorage.h"
259
#include "asterisk/translate.h"
259
#include "asterisk/translate.h"
260
#include "asterisk/ast_version.h"
260
#include "asterisk/ast_version.h"
261
#include "asterisk/event.h"
261
#include "asterisk/event.h"
262
#include "asterisk/stun.h"
262
#include "asterisk/stun.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 />
432
		<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 />
466
		<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);	\
698
		ast_uri_decode(str);	\
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 char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
765
static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
766

    
   
766

   
767
AST_MUTEX_DEFINE_STATIC(netlock);
767
AST_MUTEX_DEFINE_STATIC(netlock);
768

    
   
768

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

    
   
772

   
773
AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
773
AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
774

    
   
774

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

    
   
778

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

    
   
781

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

    
   
787

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

    
   
789

   
790
static enum sip_debug_e sipdebug;
790
static enum sip_debug_e sipdebug;
791

    
   
791

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

    
   
797

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

    
   
810

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

    
   
819

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

    
   
829

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

    
   
840

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

    
   
848

   
849
AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
849
AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
850

    
   
850

   
851
static int sip_epa_register(const struct epa_static_data *static_data)
851
static int sip_epa_register(const struct epa_static_data *static_data)
852
{
852
{
853
	struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
853
	struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
854

    
   
854

   
855
	if (!backend) {
855
	if (!backend) {
856
		return -1;
856
		return -1;
857
	}
857
	}
858

    
   
858

   
859
	backend->static_data = static_data;
859
	backend->static_data = static_data;
860

    
   
860

   
861
	AST_LIST_LOCK(&epa_static_data_list);
861
	AST_LIST_LOCK(&epa_static_data_list);
862
	AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
862
	AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
863
	AST_LIST_UNLOCK(&epa_static_data_list);
863
	AST_LIST_UNLOCK(&epa_static_data_list);
864
	return 0;
864
	return 0;
865
}
865
}
866

    
   
866

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

    
   
868

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

    
   
875

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

    
   
882

   
883
static const struct epa_static_data *find_static_data(const char * const event_package)
883
static const struct epa_static_data *find_static_data(const char * const event_package)
884
{
884
{
885
	const struct epa_backend *backend = NULL;
885
	const struct epa_backend *backend = NULL;
886

    
   
886

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

    
   
896

   
897
static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
897
static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
898
{
898
{
899
	struct sip_epa_entry *epa_entry;
899
	struct sip_epa_entry *epa_entry;
900
	const struct epa_static_data *static_data;
900
	const struct epa_static_data *static_data;
901

    
   
901

   
902
	if (!(static_data = find_static_data(event_package))) {
902
	if (!(static_data = find_static_data(event_package))) {
903
		return NULL;
903
		return NULL;
904
	}
904
	}
905

    
   
905

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

    
   
909

   
910
	epa_entry->static_data = static_data;
910
	epa_entry->static_data = static_data;
911
	ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
911
	ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
912
	return epa_entry;
912
	return epa_entry;
913
}
913
}
914

    
   
914

   
915
/*!
915
/*!
916
 * Used to create new entity IDs by ESCs.
916
 * Used to create new entity IDs by ESCs.
917
 */
917
 */
918
static int esc_etag_counter;
918
static int esc_etag_counter;
919
static const int DEFAULT_PUBLISH_EXPIRES = 3600;
919
static const int DEFAULT_PUBLISH_EXPIRES = 3600;
920

    
   
920

   
921
#ifdef HAVE_LIBXML2
921
#ifdef HAVE_LIBXML2
922
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);
922
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);
923

    
   
923

   
924
static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
924
static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
925
	.initial_handler = cc_esc_publish_handler,
925
	.initial_handler = cc_esc_publish_handler,
926
	.modify_handler = cc_esc_publish_handler,
926
	.modify_handler = cc_esc_publish_handler,
927
};
927
};
928
#endif
928
#endif
929

    
   
929

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

    
   
952

   
953
static const int ESC_MAX_BUCKETS = 37;
953
static const int ESC_MAX_BUCKETS = 37;
954

    
   
954

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

    
   
962

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

    
   
968

   
969
static int esc_cmp_fn(void *obj, void *arg, int flags)
969
static int esc_cmp_fn(void *obj, void *arg, int flags)
970
{
970
{
971
	struct sip_esc_entry *entry1 = obj;
971
	struct sip_esc_entry *entry1 = obj;
972
	struct sip_esc_entry *entry2 = arg;
972
	struct sip_esc_entry *entry2 = arg;
973

    
   
973

   
974
	return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
974
	return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
975
}
975
}
976

    
   
976

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

    
   
986

   
987
static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
987
static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
988
	struct sip_esc_entry *entry;
988
	struct sip_esc_entry *entry;
989
	struct sip_esc_entry finder;
989
	struct sip_esc_entry finder;
990

    
   
990

   
991
	ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
991
	ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
992

    
   
992

   
993
	entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
993
	entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
994

    
   
994

   
995
	return entry;
995
	return entry;
996
}
996
}
997

    
   
997

   
998
static int publish_expire(const void *data)
998
static int publish_expire(const void *data)
999
{
999
{
1000
	struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
1000
	struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
1001
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1001
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1002

    
   
1002

   
1003
	ast_assert(esc != NULL);
1003
	ast_assert(esc != NULL);
1004

    
   
1004

   
1005
	ao2_unlink(esc->compositor, esc_entry);
1005
	ao2_unlink(esc->compositor, esc_entry);
1006
	ao2_ref(esc_entry, -1);
1006
	ao2_ref(esc_entry, -1);
1007
	return 0;
1007
	return 0;
1008
}
1008
}
1009

    
   
1009

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

    
   
1014

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

    
   
1022

   
1023
static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
1023
static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
1024
{
1024
{
1025
	struct sip_esc_entry *esc_entry;
1025
	struct sip_esc_entry *esc_entry;
1026
	int expires_ms;
1026
	int expires_ms;
1027

    
   
1027

   
1028
	if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
1028
	if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
1029
		return NULL;
1029
		return NULL;
1030
	}
1030
	}
1031

    
   
1031

   
1032
	esc_entry->event = esc->name;
1032
	esc_entry->event = esc->name;
1033

    
   
1033

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

    
   
1038

   
1039
	/* Note: This links the esc_entry into the ESC properly */
1039
	/* Note: This links the esc_entry into the ESC properly */
1040
	create_new_sip_etag(esc_entry, 0);
1040
	create_new_sip_etag(esc_entry, 0);
1041

    
   
1041

   
1042
	return esc_entry;
1042
	return esc_entry;
1043
}
1043
}
1044

    
   
1044

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

    
   
1056

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

    
   
1064

   
1065
/*! \brief
1065
/*! \brief
1066
 * Here we implement the container for dialogs (sip_pvt), defining
1066
 * Here we implement the container for dialogs (sip_pvt), defining
1067
 * generic wrapper functions to ease the transition from the current
1067
 * generic wrapper functions to ease the transition from the current
1068
 * implementation (a single linked list) to a different container.
1068
 * implementation (a single linked list) to a different container.
1069
 * In addition to a reference to the container, we need functions to lock/unlock
1069
 * In addition to a reference to the container, we need functions to lock/unlock
1070
 * the container and individual items, and functions to add/remove
1070
 * the container and individual items, and functions to add/remove
1071
 * references to the individual items.
1071
 * references to the individual items.
1072
 */
1072
 */
1073
static struct ao2_container *dialogs;
1073
static struct ao2_container *dialogs;
1074
#define sip_pvt_lock(x) ao2_lock(x)
1074
#define sip_pvt_lock(x) ao2_lock(x)
1075
#define sip_pvt_trylock(x) ao2_trylock(x)
1075
#define sip_pvt_trylock(x) ao2_trylock(x)
1076
#define sip_pvt_unlock(x) ao2_unlock(x)
1076
#define sip_pvt_unlock(x) ao2_unlock(x)
1077

    
   
1077

   
1078
/*! \brief  The table of TCP threads */
1078
/*! \brief  The table of TCP threads */
1079
static struct ao2_container *threadt;
1079
static struct ao2_container *threadt;
1080

    
   
1080

   
1081
/*! \brief  The peer list: Users, Peers and Friends */
1081
/*! \brief  The peer list: Users, Peers and Friends */
1082
static struct ao2_container *peers;
1082
static struct ao2_container *peers;
1083
static struct ao2_container *peers_by_ip;
1083
static struct ao2_container *peers_by_ip;
1084

    
   
1084

   
1085
/*! \brief  The register list: Other SIP proxies we register with and receive calls from */
1085
/*! \brief  The register list: Other SIP proxies we register with and receive calls from */
1086
static struct ast_register_list {
1086
static struct ast_register_list {
1087
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1087
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1088
	int recheck;
1088
	int recheck;
1089
} regl;
1089
} regl;
1090

    
   
1090

   
1091
/*! \brief  The MWI subscription list */
1091
/*! \brief  The MWI subscription list */
1092
static struct ast_subscription_mwi_list {
1092
static struct ast_subscription_mwi_list {
1093
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
1093
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
1094
} submwil;
1094
} submwil;
1095
static int temp_pvt_init(void *);
1095
static int temp_pvt_init(void *);
1096
static void temp_pvt_cleanup(void *);
1096
static void temp_pvt_cleanup(void *);
1097

    
   
1097

   
1098
/*! \brief A per-thread temporary pvt structure */
1098
/*! \brief A per-thread temporary pvt structure */
1099
AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1099
AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1100

    
   
1100

   
1101
/*! \brief Authentication list for realm authentication
1101
/*! \brief Authentication list for realm authentication
1102
 * \todo Move the sip_auth list to AST_LIST */
1102
 * \todo Move the sip_auth list to AST_LIST */
1103
static struct sip_auth *authl = NULL;
1103
static struct sip_auth *authl = NULL;
1104

    
   
1104

   
1105
/* --- Sockets and networking --------------*/
1105
/* --- Sockets and networking --------------*/
1106

    
   
1106

   
1107
/*! \brief Main socket for UDP SIP communication.
1107
/*! \brief Main socket for UDP SIP communication.
1108
 *
1108
 *
1109
 * sipsock is shared between the SIP manager thread (which handles reload
1109
 * sipsock is shared between the SIP manager thread (which handles reload
1110
 * requests), the udp io handler (sipsock_read()) and the user routines that
1110
 * requests), the udp io handler (sipsock_read()) and the user routines that
1111
 * issue udp writes (using __sip_xmit()).
1111
 * issue udp writes (using __sip_xmit()).
1112
 * The socket is -1 only when opening fails (this is a permanent condition),
1112
 * The socket is -1 only when opening fails (this is a permanent condition),
1113
 * or when we are handling a reload() that changes its address (this is
1113
 * or when we are handling a reload() that changes its address (this is
1114
 * a transient situation during which we might have a harmless race, see
1114
 * a transient situation during which we might have a harmless race, see
1115
 * below). Because the conditions for the race to be possible are extremely
1115
 * below). Because the conditions for the race to be possible are extremely
1116
 * rare, we don't want to pay the cost of locking on every I/O.
1116
 * rare, we don't want to pay the cost of locking on every I/O.
1117
 * Rather, we remember that when the race may occur, communication is
1117
 * Rather, we remember that when the race may occur, communication is
1118
 * bound to fail anyways, so we just live with this event and let
1118
 * bound to fail anyways, so we just live with this event and let
1119
 * the protocol handle this above us.
1119
 * the protocol handle this above us.
1120
 */
1120
 */
1121
static int sipsock  = -1;
1121
static int sipsock  = -1;
1122

    
   
1122

   
1123
struct ast_sockaddr bindaddr;	/*!< UDP: The address we bind to */
1123
struct ast_sockaddr bindaddr;	/*!< UDP: The address we bind to */
1124

    
   
1124

   
1125
/*! \brief our (internal) default address/port to put in SIP/SDP messages
1125
/*! \brief our (internal) default address/port to put in SIP/SDP messages
1126
 *  internip is initialized picking a suitable address from one of the
1126
 *  internip is initialized picking a suitable address from one of the
1127
 * interfaces, and the same port number we bind to. It is used as the
1127
 * interfaces, and the same port number we bind to. It is used as the
1128
 * default address/port in SIP messages, and as the default address
1128
 * default address/port in SIP messages, and as the default address
1129
 * (but not port) in SDP messages.
1129
 * (but not port) in SDP messages.
1130
 */
1130
 */
1131
static struct ast_sockaddr internip;
1131
static struct ast_sockaddr internip;
1132

    
   
1132

   
1133
/*! \brief our external IP address/port for SIP sessions.
1133
/*! \brief our external IP address/port for SIP sessions.
1134
 * externaddr.sin_addr is only set when we know we might be behind
1134
 * externaddr.sin_addr is only set when we know we might be behind
1135
 * a NAT, and this is done using a variety of (mutually exclusive)
1135
 * a NAT, and this is done using a variety of (mutually exclusive)
1136
 * ways from the config file:
1136
 * ways from the config file:
1137
 *
1137
 *
1138
 * + with "externaddr = host[:port]" we specify the address/port explicitly.
1138
 * + with "externaddr = host[:port]" we specify the address/port explicitly.
1139
 *   The address is looked up only once when (re)loading the config file;
1139
 *   The address is looked up only once when (re)loading the config file;
1140
 *
1140
 *
1141
 * + with "externhost = host[:port]" we do a similar thing, but the
1141
 * + with "externhost = host[:port]" we do a similar thing, but the
1142
 *   hostname is stored in externhost, and the hostname->IP mapping
1142
 *   hostname is stored in externhost, and the hostname->IP mapping
1143
 *   is refreshed every 'externrefresh' seconds;
1143
 *   is refreshed every 'externrefresh' seconds;
1144
 *
1144
 *
1145
 * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
1145
 * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
1146
 *   to the specified server, and store the result in externaddr.
1146
 *   to the specified server, and store the result in externaddr.
1147
 *
1147
 *
1148
 * Other variables (externhost, externexpire, externrefresh) are used
1148
 * Other variables (externhost, externexpire, externrefresh) are used
1149
 * to support the above functions.
1149
 * to support the above functions.
1150
 */
1150
 */
1151
static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
1151
static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
1152
static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
1152
static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
1153

    
   
1153

   
1154
static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1154
static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1155
static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1155
static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1156
static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
1156
static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
1157
static struct sockaddr_in stunaddr;     /*!< stun server address */
1157
static struct sockaddr_in stunaddr;     /*!< stun server address */
1158
static uint16_t externtcpport;          /*!< external tcp port */ 
1158
static uint16_t externtcpport;          /*!< external tcp port */ 
1159
static uint16_t externtlsport;          /*!< external tls port */
1159
static uint16_t externtlsport;          /*!< external tls port */
1160

    
   
1160

   
1161
/*! \brief  List of local networks
1161
/*! \brief  List of local networks
1162
 * We store "localnet" addresses from the config file into an access list,
1162
 * We store "localnet" addresses from the config file into an access list,
1163
 * marked as 'DENY', so the call to ast_apply_ha() will return
1163
 * marked as 'DENY', so the call to ast_apply_ha() will return
1164
 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1164
 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1165
 * (i.e. presumably public) addresses.
1165
 * (i.e. presumably public) addresses.
1166
 */
1166
 */
1167
static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
1167
static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
1168

    
   
1168

   
1169
static int ourport_tcp;             /*!< The port used for TCP connections */
1169
static int ourport_tcp;             /*!< The port used for TCP connections */
1170
static int ourport_tls;             /*!< The port used for TCP/TLS connections */
1170
static int ourport_tls;             /*!< The port used for TCP/TLS connections */
1171
static struct ast_sockaddr debugaddr;
1171
static struct ast_sockaddr debugaddr;
1172

    
   
1172

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

    
   
1174

   
1175
/*! some list management macros. */
1175
/*! some list management macros. */
1176

    
   
1176

   
1177
#define UNLINK(element, head, prev) do {	\
1177
#define UNLINK(element, head, prev) do {	\
1178
	if (prev)				\
1178
	if (prev)				\
1179
		(prev)->next = (element)->next;	\
1179
		(prev)->next = (element)->next;	\
1180
	else					\
1180
	else					\
1181
		(head) = (element)->next;	\
1181
		(head) = (element)->next;	\
1182
	} while (0)
1182
	} while (0)
1183

    
   
1183

   
1184
/*---------------------------- Forward declarations of functions in chan_sip.c */
1184
/*---------------------------- Forward declarations of functions in chan_sip.c */
1185
/* Note: This is added to help splitting up chan_sip.c into several files
1185
/* Note: This is added to help splitting up chan_sip.c into several files
1186
	in coming releases. */
1186
	in coming releases. */
1187

    
   
1187

   
1188
/*--- PBX interface functions */
1188
/*--- PBX interface functions */
1189
static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
1189
static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
1190
static int sip_devicestate(void *data);
1190
static int sip_devicestate(void *data);
1191
static int sip_sendtext(struct ast_channel *ast, const char *text);
1191
static int sip_sendtext(struct ast_channel *ast, const char *text);
1192
static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1192
static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1193
static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1193
static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1194
static int sip_hangup(struct ast_channel *ast);
1194
static int sip_hangup(struct ast_channel *ast);
1195
static int sip_answer(struct ast_channel *ast);
1195
static int sip_answer(struct ast_channel *ast);
1196
static struct ast_frame *sip_read(struct ast_channel *ast);
1196
static struct ast_frame *sip_read(struct ast_channel *ast);
1197
static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1197
static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1198
static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1198
static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1199
static int sip_transfer(struct ast_channel *ast, const char *dest);
1199
static int sip_transfer(struct ast_channel *ast, const char *dest);
1200
static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1200
static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1201
static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1201
static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1202
static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1202
static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1203
static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1203
static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1204
static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1204
static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1205
static const char *sip_get_callid(struct ast_channel *chan);
1205
static const char *sip_get_callid(struct ast_channel *chan);
1206

    
   
1206

   
1207
static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
1207
static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
1208
static int sip_standard_port(enum sip_transport type, int port);
1208
static int sip_standard_port(enum sip_transport type, int port);
1209
static int sip_prepare_socket(struct sip_pvt *p);
1209
static int sip_prepare_socket(struct sip_pvt *p);
1210
static int get_address_family_filter(const struct ast_sockaddr *addr);
1210
static int get_address_family_filter(const struct ast_sockaddr *addr);
1211

    
   
1211

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

    
   
1249

   
1250
/* Misc dialog routines */
1250
/* Misc dialog routines */
1251
static int __sip_autodestruct(const void *data);
1251
static int __sip_autodestruct(const void *data);
1252
static void *registry_unref(struct sip_registry *reg, char *tag);
1252
static void *registry_unref(struct sip_registry *reg, char *tag);
1253
static int update_call_counter(struct sip_pvt *fup, int event);
1253
static int update_call_counter(struct sip_pvt *fup, int event);
1254
static int auto_congest(const void *arg);
1254
static int auto_congest(const void *arg);
1255
static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
1255
static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
1256
static void free_old_route(struct sip_route *route);
1256
static void free_old_route(struct sip_route *route);
1257
static void list_route(struct sip_route *route);
1257
static void list_route(struct sip_route *route);
1258
static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1258
static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1259
static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
1259
static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
1260
					      struct sip_request *req, const char *uri);
1260
					      struct sip_request *req, const char *uri);
1261
static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1261
static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1262
static void check_pendings(struct sip_pvt *p);
1262
static void check_pendings(struct sip_pvt *p);
1263
static void *sip_park_thread(void *stuff);
1263
static void *sip_park_thread(void *stuff);
1264
static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1264
static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1265
static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1265
static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1266
static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1266
static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1267

    
   
1267

   
1268
/*--- Codec handling / SDP */
1268
/*--- Codec handling / SDP */
1269
static void try_suggested_sip_codec(struct sip_pvt *p);
1269
static void try_suggested_sip_codec(struct sip_pvt *p);
1270
static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1270
static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1271
static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1271
static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1272
static int find_sdp(struct sip_request *req);
1272
static int find_sdp(struct sip_request *req);
1273
static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1273
static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1274
static int process_sdp_o(const char *o, struct sip_pvt *p);
1274
static int process_sdp_o(const char *o, struct sip_pvt *p);
1275
static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
1275
static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
1276
static int process_sdp_a_sendonly(const char *a, int *sendonly);
1276
static int process_sdp_a_sendonly(const char *a, int *sendonly);
1277
static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1277
static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1278
static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1278
static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1279
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);
1279
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);
1280
static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1280
static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1281
static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
1281
static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
1282
			     struct ast_str **m_buf, struct ast_str **a_buf,
1282
			     struct ast_str **m_buf, struct ast_str **a_buf,
1283
			     int debug, int *min_packet_size);
1283
			     int debug, int *min_packet_size);
1284
static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1284
static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1285
				struct ast_str **m_buf, struct ast_str **a_buf,
1285
				struct ast_str **m_buf, struct ast_str **a_buf,
1286
				int debug);
1286
				int debug);
1287
static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1287
static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1288
static void do_setnat(struct sip_pvt *p);
1288
static void do_setnat(struct sip_pvt *p);
1289
static void stop_media_flows(struct sip_pvt *p);
1289
static void stop_media_flows(struct sip_pvt *p);
1290

    
   
1290

   
1291
/*--- Authentication stuff */
1291
/*--- Authentication stuff */
1292
static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1292
static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1293
static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1293
static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1294
static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1294
static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1295
					 const char *secret, const char *md5secret, int sipmethod,
1295
					 const char *secret, const char *md5secret, int sipmethod,
1296
					 const char *uri, enum xmittype reliable, int ignore);
1296
					 const char *uri, enum xmittype reliable, int ignore);
1297
static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1297
static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1298
					      int sipmethod, const char *uri, enum xmittype reliable,
1298
					      int sipmethod, const char *uri, enum xmittype reliable,
1299
					      struct ast_sockaddr *addr, struct sip_peer **authpeer);
1299
					      struct ast_sockaddr *addr, struct sip_peer **authpeer);
1300
static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
1300
static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
1301

    
   
1301

   
1302
/*--- Domain handling */
1302
/*--- Domain handling */
1303
static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1303
static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1304
static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1304
static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1305
static void clear_sip_domains(void);
1305
static void clear_sip_domains(void);
1306

    
   
1306

   
1307
/*--- SIP realm authentication */
1307
/*--- SIP realm authentication */
1308
static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
1308
static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
1309
static int clear_realm_authentication(struct sip_auth *authlist);	/* Clear realm authentication list (at reload) */
1309
static int clear_realm_authentication(struct sip_auth *authlist);	/* Clear realm authentication list (at reload) */
1310
static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1310
static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1311

    
   
1311

   
1312
/*--- Misc functions */
1312
/*--- Misc functions */
1313
static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1313
static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1314
static int sip_do_reload(enum channelreloadreason reason);
1314
static int sip_do_reload(enum channelreloadreason reason);
1315
static int reload_config(enum channelreloadreason reason);
1315
static int reload_config(enum channelreloadreason reason);
1316
static int expire_register(const void *data);
1316
static int expire_register(const void *data);
1317
static void *do_monitor(void *data);
1317
static void *do_monitor(void *data);
1318
static int restart_monitor(void);
1318
static int restart_monitor(void);
1319
static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1319
static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1320
static struct ast_variable *copy_vars(struct ast_variable *src);
1320
static struct ast_variable *copy_vars(struct ast_variable *src);
1321
static int dialog_find_multiple(void *obj, void *arg, int flags);
1321
static int dialog_find_multiple(void *obj, void *arg, int flags);
1322
/* static int sip_addrcmp(char *name, struct sockaddr_in *sin);	Support for peer matching */
1322
/* static int sip_addrcmp(char *name, struct sockaddr_in *sin);	Support for peer matching */
1323
static int sip_refer_allocate(struct sip_pvt *p);
1323
static int sip_refer_allocate(struct sip_pvt *p);
1324
static int sip_notify_allocate(struct sip_pvt *p);
1324
static int sip_notify_allocate(struct sip_pvt *p);
1325
static void ast_quiet_chan(struct ast_channel *chan);
1325
static void ast_quiet_chan(struct ast_channel *chan);
1326
static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1326
static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1327
static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1327
static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1328

    
   
1328

   
1329
/*--- Device monitoring and Device/extension state/event handling */
1329
/*--- Device monitoring and Device/extension state/event handling */
1330
static int cb_extensionstate(char *context, char* exten, int state, void *data);
1330
static int cb_extensionstate(char *context, char* exten, int state, void *data);
1331
static int sip_devicestate(void *data);
1331
static int sip_devicestate(void *data);
1332
static int sip_poke_noanswer(const void *data);
1332
static int sip_poke_noanswer(const void *data);
1333
static int sip_poke_peer(struct sip_peer *peer, int force);
1333
static int sip_poke_peer(struct sip_peer *peer, int force);
1334
static void sip_poke_all_peers(void);
1334
static void sip_poke_all_peers(void);
1335
static void sip_peer_hold(struct sip_pvt *p, int hold);
1335
static void sip_peer_hold(struct sip_pvt *p, int hold);
1336
static void mwi_event_cb(const struct ast_event *, void *);
1336
static void mwi_event_cb(const struct ast_event *, void *);
1337

    
   
1337

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

    
   
1387

   
1388
/*--- Debugging
1388
/*--- Debugging
1389
	Functions for enabling debug per IP or fully, or enabling history logging for
1389
	Functions for enabling debug per IP or fully, or enabling history logging for
1390
	a SIP dialog
1390
	a SIP dialog
1391
*/
1391
*/
1392
static void sip_dump_history(struct sip_pvt *dialog);	/* Dump history to debuglog at end of dialog, before destroying data */
1392
static void sip_dump_history(struct sip_pvt *dialog);	/* Dump history to debuglog at end of dialog, before destroying data */
1393
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
1393
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
1394
static inline int sip_debug_test_pvt(struct sip_pvt *p);
1394
static inline int sip_debug_test_pvt(struct sip_pvt *p);
1395
static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1395
static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1396
static void sip_dump_history(struct sip_pvt *dialog);
1396
static void sip_dump_history(struct sip_pvt *dialog);
1397

    
   
1397

   
1398
/*--- Device object handling */
1398
/*--- Device object handling */
1399
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1399
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1400
static int update_call_counter(struct sip_pvt *fup, int event);
1400
static int update_call_counter(struct sip_pvt *fup, int event);
1401
static void sip_destroy_peer(struct sip_peer *peer);
1401
static void sip_destroy_peer(struct sip_peer *peer);
1402
static void sip_destroy_peer_fn(void *peer);
1402
static void sip_destroy_peer_fn(void *peer);
1403
static void set_peer_defaults(struct sip_peer *peer);
1403
static void set_peer_defaults(struct sip_peer *peer);
1404
static struct sip_peer *temp_peer(const char *name);
1404
static struct sip_peer *temp_peer(const char *name);
1405
static void register_peer_exten(struct sip_peer *peer, int onoff);
1405
static void register_peer_exten(struct sip_peer *peer, int onoff);
1406
static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int forcenamematch, int devstate_only, int transport);
1406
static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int forcenamematch, int devstate_only, int transport);
1407
static int sip_poke_peer_s(const void *data);
1407
static int sip_poke_peer_s(const void *data);
1408
static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1408
static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1409
static void reg_source_db(struct sip_peer *peer);
1409
static void reg_source_db(struct sip_peer *peer);
1410
static void destroy_association(struct sip_peer *peer);
1410
static void destroy_association(struct sip_peer *peer);
1411
static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1411
static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1412
static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1412
static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1413
static void set_socket_transport(struct sip_socket *socket, int transport);
1413
static void set_socket_transport(struct sip_socket *socket, int transport);
1414

    
   
1414

   
1415
/* Realtime device support */
1415
/* Realtime device support */
1416
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);
1416
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);
1417
static void update_peer(struct sip_peer *p, int expire);
1417
static void update_peer(struct sip_peer *p, int expire);
1418
static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1418
static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1419
static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
1419
static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
1420
static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, int devstate_only);
1420
static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, int devstate_only);
1421
static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1421
static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1422

    
   
1422

   
1423
/*--- Internal UA client handling (outbound registrations) */
1423
/*--- Internal UA client handling (outbound registrations) */
1424
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
1424
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
1425
static void sip_registry_destroy(struct sip_registry *reg);
1425
static void sip_registry_destroy(struct sip_registry *reg);
1426
static int sip_register(const char *value, int lineno);
1426
static int sip_register(const char *value, int lineno);
1427
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1427
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1428
static int sip_reregister(const void *data);
1428
static int sip_reregister(const void *data);
1429
static int __sip_do_register(struct sip_registry *r);
1429
static int __sip_do_register(struct sip_registry *r);
1430
static int sip_reg_timeout(const void *data);
1430
static int sip_reg_timeout(const void *data);
1431
static void sip_send_all_registers(void);
1431
static void sip_send_all_registers(void);
1432
static int sip_reinvite_retry(const void *data);
1432
static int sip_reinvite_retry(const void *data);
1433

    
   
1433

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

    
   
1466

   
1467
/*-- TCP connection handling ---*/
1467
/*-- TCP connection handling ---*/
1468
static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
1468
static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
1469
static void *sip_tcp_worker_fn(void *);
1469
static void *sip_tcp_worker_fn(void *);
1470

    
   
1470

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

    
   
1503

   
1504
/*------Request handling functions */
1504
/*------Request handling functions */
1505
static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
1505
static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
1506
static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1506
static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1507
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);
1507
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);
1508
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1508
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1509
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1509
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1510
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
1510
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
1511
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1511
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1512
static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1512
static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1513
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
1513
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
1514
static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1514
static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1515
static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1515
static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1516
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *nounlock);
1516
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *nounlock);
1517
static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
1517
static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
1518
static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno, int *nounlock);
1518
static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno, int *nounlock);
1519

    
   
1519

   
1520
/*------Response handling functions */
1520
/*------Response handling functions */
1521
static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1521
static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1522
static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1522
static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1523
static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1523
static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1524
static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1524
static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1525
static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1525
static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1526
static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1526
static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1527
static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1527
static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1528

    
   
1528

   
1529
/*------ SRTP Support -------- */
1529
/*------ SRTP Support -------- */
1530
static int setup_srtp(struct sip_srtp **srtp);
1530
static int setup_srtp(struct sip_srtp **srtp);
1531
static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
1531
static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
1532

    
   
1532

   
1533
/*------ T38 Support --------- */
1533
/*------ T38 Support --------- */
1534
static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1534
static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1535
static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1535
static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1536
static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1536
static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1537
static void change_t38_state(struct sip_pvt *p, int state);
1537
static void change_t38_state(struct sip_pvt *p, int state);
1538

    
   
1538

   
1539
/*------ Session-Timers functions --------- */
1539
/*------ Session-Timers functions --------- */
1540
static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1540
static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1541
static int  proc_session_timer(const void *vp);
1541
static int  proc_session_timer(const void *vp);
1542
static void stop_session_timer(struct sip_pvt *p);
1542
static void stop_session_timer(struct sip_pvt *p);
1543
static void start_session_timer(struct sip_pvt *p);
1543
static void start_session_timer(struct sip_pvt *p);
1544
static void restart_session_timer(struct sip_pvt *p);
1544
static void restart_session_timer(struct sip_pvt *p);
1545
static const char *strefresher2str(enum st_refresher r);
1545
static const char *strefresher2str(enum st_refresher r);
1546
static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
1546
static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
1547
static int parse_minse(const char *p_hdrval, int *const p_interval);
1547
static int parse_minse(const char *p_hdrval, int *const p_interval);
1548
static int st_get_se(struct sip_pvt *, int max);
1548
static int st_get_se(struct sip_pvt *, int max);
1549
static enum st_refresher st_get_refresher(struct sip_pvt *);
1549
static enum st_refresher st_get_refresher(struct sip_pvt *);
1550
static enum st_mode st_get_mode(struct sip_pvt *);
1550
static enum st_mode st_get_mode(struct sip_pvt *);
1551
static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1551
static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1552

    
   
1552

   
1553
/*------- RTP Glue functions -------- */
1553
/*------- RTP Glue functions -------- */
1554
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, format_t codecs, int nat_active);
1554
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, format_t codecs, int nat_active);
1555

    
   
1555

   
1556
/*!--- SIP MWI Subscription support */
1556
/*!--- SIP MWI Subscription support */
1557
static int sip_subscribe_mwi(const char *value, int lineno);
1557
static int sip_subscribe_mwi(const char *value, int lineno);
1558
static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
1558
static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
1559
static void sip_send_all_mwi_subscriptions(void);
1559
static void sip_send_all_mwi_subscriptions(void);
1560
static int sip_subscribe_mwi_do(const void *data);
1560
static int sip_subscribe_mwi_do(const void *data);
1561
static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1561
static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1562

    
   
1562

   
1563
/*! \brief Definition of this channel for PBX channel registration */
1563
/*! \brief Definition of this channel for PBX channel registration */
1564
const struct ast_channel_tech sip_tech = {
1564
const struct ast_channel_tech sip_tech = {
1565
	.type = "SIP",
1565
	.type = "SIP",
1566
	.description = "Session Initiation Protocol (SIP)",
1566
	.description = "Session Initiation Protocol (SIP)",
1567
	.capabilities = AST_FORMAT_AUDIO_MASK,	/* all audio formats */
1567
	.capabilities = AST_FORMAT_AUDIO_MASK,	/* all audio formats */
1568
	.properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1568
	.properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1569
	.requester = sip_request_call,			/* called with chan unlocked */
1569
	.requester = sip_request_call,			/* called with chan unlocked */
1570
	.devicestate = sip_devicestate,			/* called with chan unlocked (not chan-specific) */
1570
	.devicestate = sip_devicestate,			/* called with chan unlocked (not chan-specific) */
1571
	.call = sip_call,			/* called with chan locked */
1571
	.call = sip_call,			/* called with chan locked */
1572
	.send_html = sip_sendhtml,
1572
	.send_html = sip_sendhtml,
1573
	.hangup = sip_hangup,			/* called with chan locked */
1573
	.hangup = sip_hangup,			/* called with chan locked */
1574
	.answer = sip_answer,			/* called with chan locked */
1574
	.answer = sip_answer,			/* called with chan locked */
1575
	.read = sip_read,			/* called with chan locked */
1575
	.read = sip_read,			/* called with chan locked */
1576
	.write = sip_write,			/* called with chan locked */
1576
	.write = sip_write,			/* called with chan locked */
1577
	.write_video = sip_write,		/* called with chan locked */
1577
	.write_video = sip_write,		/* called with chan locked */
1578
	.write_text = sip_write,
1578
	.write_text = sip_write,
1579
	.indicate = sip_indicate,		/* called with chan locked */
1579
	.indicate = sip_indicate,		/* called with chan locked */
1580
	.transfer = sip_transfer,		/* called with chan locked */
1580
	.transfer = sip_transfer,		/* called with chan locked */
1581
	.fixup = sip_fixup,			/* called with chan locked */
1581
	.fixup = sip_fixup,			/* called with chan locked */
1582
	.send_digit_begin = sip_senddigit_begin,	/* called with chan unlocked */
1582
	.send_digit_begin = sip_senddigit_begin,	/* called with chan unlocked */
1583
	.send_digit_end = sip_senddigit_end,
1583
	.send_digit_end = sip_senddigit_end,
1584
	.bridge = ast_rtp_instance_bridge,			/* XXX chan unlocked ? */
1584
	.bridge = ast_rtp_instance_bridge,			/* XXX chan unlocked ? */
1585
	.early_bridge = ast_rtp_instance_early_bridge,
1585
	.early_bridge = ast_rtp_instance_early_bridge,
1586
	.send_text = sip_sendtext,		/* called with chan locked */
1586
	.send_text = sip_sendtext,		/* called with chan locked */
1587
	.func_channel_read = sip_acf_channel_read,
1587
	.func_channel_read = sip_acf_channel_read,
1588
	.setoption = sip_setoption,
1588
	.setoption = sip_setoption,
1589
	.queryoption = sip_queryoption,
1589
	.queryoption = sip_queryoption,
1590
	.get_pvt_uniqueid = sip_get_callid,
1590
	.get_pvt_uniqueid = sip_get_callid,
1591
};
1591
};
1592

    
   
1592

   
1593
/*! \brief This version of the sip channel tech has no send_digit_begin
1593
/*! \brief This version of the sip channel tech has no send_digit_begin
1594
 * callback so that the core knows that the channel does not want
1594
 * callback so that the core knows that the channel does not want
1595
 * DTMF BEGIN frames.
1595
 * DTMF BEGIN frames.
1596
 * The struct is initialized just before registering the channel driver,
1596
 * The struct is initialized just before registering the channel driver,
1597
 * and is for use with channels using SIP INFO DTMF.
1597
 * and is for use with channels using SIP INFO DTMF.
1598
 */
1598
 */
1599
struct ast_channel_tech sip_tech_info;
1599
struct ast_channel_tech sip_tech_info;
1600

    
   
1600

   
1601
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1601
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1602
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1602
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1603
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1603
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1604
static void sip_cc_agent_ack(struct ast_cc_agent *agent);
1604
static void sip_cc_agent_ack(struct ast_cc_agent *agent);
1605
static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
1605
static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
1606
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1606
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1607
static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1607
static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1608
static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1608
static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1609

    
   
1609

   
1610
static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
1610
static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
1611
	.type = "SIP",
1611
	.type = "SIP",
1612
	.init = sip_cc_agent_init,
1612
	.init = sip_cc_agent_init,
1613
	.start_offer_timer = sip_cc_agent_start_offer_timer,
1613
	.start_offer_timer = sip_cc_agent_start_offer_timer,
1614
	.stop_offer_timer = sip_cc_agent_stop_offer_timer,
1614
	.stop_offer_timer = sip_cc_agent_stop_offer_timer,
1615
	.ack = sip_cc_agent_ack,
1615
	.ack = sip_cc_agent_ack,
1616
	.status_request = sip_cc_agent_status_request,
1616
	.status_request = sip_cc_agent_status_request,
1617
	.start_monitoring = sip_cc_agent_start_monitoring,
1617
	.start_monitoring = sip_cc_agent_start_monitoring,
1618
	.callee_available = sip_cc_agent_recall,
1618
	.callee_available = sip_cc_agent_recall,
1619
	.destructor = sip_cc_agent_destructor,
1619
	.destructor = sip_cc_agent_destructor,
1620
};
1620
};
1621

    
   
1621

   
1622
static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
1622
static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
1623
{
1623
{
1624
	struct ast_cc_agent *agent = obj;
1624
	struct ast_cc_agent *agent = obj;
1625
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1625
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1626
	const char *uri = arg;
1626
	const char *uri = arg;
1627

    
   
1627

   
1628
	return !strcmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1628
	return !strcmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1629
}
1629
}
1630

    
   
1630

   
1631
static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
1631
static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
1632
{
1632
{
1633
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
1633
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
1634
	return agent;
1634
	return agent;
1635
}
1635
}
1636

    
   
1636

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

    
   
1642

   
1643
	return !strcmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1643
	return !strcmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1644
}
1644
}
1645

    
   
1645

   
1646
static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
1646
static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
1647
{
1647
{
1648
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
1648
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
1649
	return agent;
1649
	return agent;
1650
}
1650
}
1651

    
   
1651

   
1652
static int find_by_callid_helper(void *obj, void *arg, int flags)
1652
static int find_by_callid_helper(void *obj, void *arg, int flags)
1653
{
1653
{
1654
	struct ast_cc_agent *agent = obj;
1654
	struct ast_cc_agent *agent = obj;
1655
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1655
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1656
	struct sip_pvt *call_pvt = arg;
1656
	struct sip_pvt *call_pvt = arg;
1657

    
   
1657

   
1658
	return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
1658
	return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
1659
}
1659
}
1660

    
   
1660

   
1661
static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
1661
static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
1662
{
1662
{
1663
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
1663
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
1664
	return agent;
1664
	return agent;
1665
}
1665
}
1666

    
   
1666

   
1667
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
1667
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
1668
{
1668
{
1669
	struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
1669
	struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
1670
	struct sip_pvt *call_pvt = chan->tech_pvt;
1670
	struct sip_pvt *call_pvt = chan->tech_pvt;
1671

    
   
1671

   
1672
	if (!agent_pvt) {
1672
	if (!agent_pvt) {
1673
		return -1;
1673
		return -1;
1674
	}
1674
	}
1675

    
   
1675

   
1676
	ast_assert(!strcmp(chan->tech->type, "SIP"));
1676
	ast_assert(!strcmp(chan->tech->type, "SIP"));
1677

    
   
1677

   
1678
	ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
1678
	ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
1679
	ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
1679
	ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
1680
	agent_pvt->offer_timer_id = -1;
1680
	agent_pvt->offer_timer_id = -1;
1681
	agent->private_data = agent_pvt;
1681
	agent->private_data = agent_pvt;
1682
	sip_pvt_lock(call_pvt);
1682
	sip_pvt_lock(call_pvt);
1683
	ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1683
	ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1684
	sip_pvt_unlock(call_pvt);
1684
	sip_pvt_unlock(call_pvt);
1685
	return 0;
1685
	return 0;
1686
}
1686
}
1687

    
   
1687

   
1688
static int sip_offer_timer_expire(const void *data)
1688
static int sip_offer_timer_expire(const void *data)
1689
{
1689
{
1690
	struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
1690
	struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
1691
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1691
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1692

    
   
1692

   
1693
	agent_pvt->offer_timer_id = -1;
1693
	agent_pvt->offer_timer_id = -1;
1694

    
   
1694

   
1695
	return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
1695
	return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
1696
}
1696
}
1697

    
   
1697

   
1698
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
1698
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
1699
{
1699
{
1700
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1700
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1701
	int when;
1701
	int when;
1702

    
   
1702

   
1703
	when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1703
	when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1704
	agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
1704
	agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
1705
	return 0;
1705
	return 0;
1706
}
1706
}
1707

    
   
1707

   
1708
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
1708
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
1709
{
1709
{
1710
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1710
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1711

    
   
1711

   
1712
	AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1712
	AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1713
	return 0;
1713
	return 0;
1714
}
1714
}
1715

    
   
1715

   
1716
static void sip_cc_agent_ack(struct ast_cc_agent *agent)
1716
static void sip_cc_agent_ack(struct ast_cc_agent *agent)
1717
{
1717
{
1718
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1718
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1719

    
   
1719

   
1720
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1720
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1721
	ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
1721
	ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
1722
	transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1722
	transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1723
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1723
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1724
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1724
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1725
	agent_pvt->is_available = TRUE;
1725
	agent_pvt->is_available = TRUE;
1726
}
1726
}
1727

    
   
1727

   
1728
static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
1728
static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
1729
{
1729
{
1730
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1730
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1731
	enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
1731
	enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
1732
	return ast_cc_agent_status_response(agent->core_id, state);
1732
	return ast_cc_agent_status_response(agent->core_id, state);
1733
}
1733
}
1734

    
   
1734

   
1735
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
1735
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
1736
{
1736
{
1737
	/* To start monitoring just means to wait for an incoming PUBLISH
1737
	/* To start monitoring just means to wait for an incoming PUBLISH
1738
	 * to tell us that the caller has become available again. No special
1738
	 * to tell us that the caller has become available again. No special
1739
	 * action is needed
1739
	 * action is needed
1740
	 */
1740
	 */
1741
	return 0;
1741
	return 0;
1742
}
1742
}
1743

    
   
1743

   
1744
static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1744
static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1745
{
1745
{
1746
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1746
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1747
	/* If we have received a PUBLISH beforehand stating that the caller in question
1747
	/* If we have received a PUBLISH beforehand stating that the caller in question
1748
	 * is not available, we can save ourself a bit of effort here and just report
1748
	 * is not available, we can save ourself a bit of effort here and just report
1749
	 * the caller as busy
1749
	 * the caller as busy
1750
	 */
1750
	 */
1751
	if (!agent_pvt->is_available) {
1751
	if (!agent_pvt->is_available) {
1752
		return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
1752
		return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
1753
				agent->device_name);
1753
				agent->device_name);
1754
	}
1754
	}
1755
	/* Otherwise, we transmit a NOTIFY to the caller and await either
1755
	/* Otherwise, we transmit a NOTIFY to the caller and await either
1756
	 * a PUBLISH or an INVITE
1756
	 * a PUBLISH or an INVITE
1757
	 */
1757
	 */
1758
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1758
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1759
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1759
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1760
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1760
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1761
	return 0;
1761
	return 0;
1762
}
1762
}
1763

    
   
1763

   
1764
static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
1764
static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
1765
{
1765
{
1766
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1766
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1767

    
   
1767

   
1768
	if (!agent_pvt) {
1768
	if (!agent_pvt) {
1769
		/* The agent constructor probably failed. */
1769
		/* The agent constructor probably failed. */
1770
		return;
1770
		return;
1771
	}
1771
	}
1772

    
   
1772

   
1773
	sip_cc_agent_stop_offer_timer(agent);
1773
	sip_cc_agent_stop_offer_timer(agent);
1774
	if (agent_pvt->subscribe_pvt) {
1774
	if (agent_pvt->subscribe_pvt) {
1775
		sip_pvt_lock(agent_pvt->subscribe_pvt);
1775
		sip_pvt_lock(agent_pvt->subscribe_pvt);
1776
		if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
1776
		if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
1777
			/* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
1777
			/* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
1778
			 * the subscriber know something went wrong
1778
			 * the subscriber know something went wrong
1779
			 */
1779
			 */
1780
			transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
1780
			transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
1781
		}
1781
		}
1782
		sip_pvt_unlock(agent_pvt->subscribe_pvt);
1782
		sip_pvt_unlock(agent_pvt->subscribe_pvt);
1783
		agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
1783
		agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
1784
	}
1784
	}
1785
	ast_free(agent_pvt);
1785
	ast_free(agent_pvt);
1786
}
1786
}
1787

    
   
1787

   
1788
struct ao2_container *sip_monitor_instances;
1788
struct ao2_container *sip_monitor_instances;
1789

    
   
1789

   
1790
static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
1790
static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
1791
{
1791
{
1792
	const struct sip_monitor_instance *monitor_instance = obj;
1792
	const struct sip_monitor_instance *monitor_instance = obj;
1793
	return monitor_instance->core_id;
1793
	return monitor_instance->core_id;
1794
}
1794
}
1795

    
   
1795

   
1796
static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
1796
static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
1797
{
1797
{
1798
	struct sip_monitor_instance *monitor_instance1 = obj;
1798
	struct sip_monitor_instance *monitor_instance1 = obj;
1799
	struct sip_monitor_instance *monitor_instance2 = arg;
1799
	struct sip_monitor_instance *monitor_instance2 = arg;
1800

    
   
1800

   
1801
	return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
1801
	return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
1802
}
1802
}
1803

    
   
1803

   
1804
static void sip_monitor_instance_destructor(void *data)
1804
static void sip_monitor_instance_destructor(void *data)
1805
{
1805
{
1806
	struct sip_monitor_instance *monitor_instance = data;
1806
	struct sip_monitor_instance *monitor_instance = data;
1807
	if (monitor_instance->subscription_pvt) {
1807
	if (monitor_instance->subscription_pvt) {
1808
		sip_pvt_lock(monitor_instance->subscription_pvt);
1808
		sip_pvt_lock(monitor_instance->subscription_pvt);
1809
		monitor_instance->subscription_pvt->expiry = 0;
1809
		monitor_instance->subscription_pvt->expiry = 0;
1810
		transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
1810
		transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
1811
		sip_pvt_unlock(monitor_instance->subscription_pvt);
1811
		sip_pvt_unlock(monitor_instance->subscription_pvt);
1812
		dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
1812
		dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
1813
	}
1813
	}
1814
	if (monitor_instance->suspension_entry) {
1814
	if (monitor_instance->suspension_entry) {
1815
		monitor_instance->suspension_entry->body[0] = '\0';
1815
		monitor_instance->suspension_entry->body[0] = '\0';
1816
		transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
1816
		transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
1817
		ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
1817
		ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
1818
	}
1818
	}
1819
	ast_string_field_free_memory(monitor_instance);
1819
	ast_string_field_free_memory(monitor_instance);
1820
}
1820
}
1821

    
   
1821

   
1822
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)
1822
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)
1823
{
1823
{
1824
	struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
1824
	struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
1825

    
   
1825

   
1826
	if (!monitor_instance) {
1826
	if (!monitor_instance) {
1827
		return NULL;
1827
		return NULL;
1828
	}
1828
	}
1829

    
   
1829

   
1830
	if (ast_string_field_init(monitor_instance, 256)) {
1830
	if (ast_string_field_init(monitor_instance, 256)) {
1831
		ao2_ref(monitor_instance, -1);
1831
		ao2_ref(monitor_instance, -1);
1832
		return NULL;
1832
		return NULL;
1833
	}
1833
	}
1834

    
   
1834

   
1835
	ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
1835
	ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
1836
	ast_string_field_set(monitor_instance, peername, peername);
1836
	ast_string_field_set(monitor_instance, peername, peername);
1837
	ast_string_field_set(monitor_instance, device_name, device_name);
1837
	ast_string_field_set(monitor_instance, device_name, device_name);
1838
	monitor_instance->core_id = core_id;
1838
	monitor_instance->core_id = core_id;
1839
	ao2_link(sip_monitor_instances, monitor_instance);
1839
	ao2_link(sip_monitor_instances, monitor_instance);
1840
	return monitor_instance;
1840
	return monitor_instance;
1841
}
1841
}
1842

    
   
1842

   
1843
static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
1843
static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
1844
{
1844
{
1845
	struct sip_monitor_instance *monitor_instance = obj;
1845
	struct sip_monitor_instance *monitor_instance = obj;
1846
	return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
1846
	return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
1847
}
1847
}
1848

    
   
1848

   
1849
static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
1849
static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
1850
{
1850
{
1851
	struct sip_monitor_instance *monitor_instance = obj;
1851
	struct sip_monitor_instance *monitor_instance = obj;
1852
	return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
1852
	return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
1853
}
1853
}
1854

    
   
1854

   
1855
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
1855
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
1856
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
1856
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
1857
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
1857
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
1858
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
1858
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
1859
static void sip_cc_monitor_destructor(void *private_data);
1859
static void sip_cc_monitor_destructor(void *private_data);
1860

    
   
1860

   
1861
static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
1861
static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
1862
	.type = "SIP",
1862
	.type = "SIP",
1863
	.request_cc = sip_cc_monitor_request_cc,
1863
	.request_cc = sip_cc_monitor_request_cc,
1864
	.suspend = sip_cc_monitor_suspend,
1864
	.suspend = sip_cc_monitor_suspend,
1865
	.unsuspend = sip_cc_monitor_unsuspend,
1865
	.unsuspend = sip_cc_monitor_unsuspend,
1866
	.cancel_available_timer = sip_cc_monitor_cancel_available_timer,
1866
	.cancel_available_timer = sip_cc_monitor_cancel_available_timer,
1867
	.destructor = sip_cc_monitor_destructor,
1867
	.destructor = sip_cc_monitor_destructor,
1868
};
1868
};
1869

    
   
1869

   
1870
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
1870
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
1871
{
1871
{
1872
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1872
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1873
	enum ast_cc_service_type service = monitor->service_offered;
1873
	enum ast_cc_service_type service = monitor->service_offered;
1874
	int when;
1874
	int when;
1875

    
   
1875

   
1876
	if (!monitor_instance) {
1876
	if (!monitor_instance) {
1877
		return -1;
1877
		return -1;
1878
	}
1878
	}
1879

    
   
1879

   
1880
	if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
1880
	if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
1881
		return -1;
1881
		return -1;
1882
	}
1882
	}
1883

    
   
1883

   
1884
	when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
1884
	when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
1885
		ast_get_ccnr_available_timer(monitor->interface->config_params);
1885
		ast_get_ccnr_available_timer(monitor->interface->config_params);
1886

    
   
1886

   
1887
	sip_pvt_lock(monitor_instance->subscription_pvt);
1887
	sip_pvt_lock(monitor_instance->subscription_pvt);
1888
	create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
1888
	create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
1889
	ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
1889
	ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
1890
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1890
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1891
	monitor_instance->subscription_pvt->expiry = when;
1891
	monitor_instance->subscription_pvt->expiry = when;
1892

    
   
1892

   
1893
	transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
1893
	transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
1894
	sip_pvt_unlock(monitor_instance->subscription_pvt);
1894
	sip_pvt_unlock(monitor_instance->subscription_pvt);
1895

    
   
1895

   
1896
	ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
1896
	ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
1897
	*available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
1897
	*available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
1898
	return 0;
1898
	return 0;
1899
}
1899
}
1900

    
   
1900

   
1901
static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
1901
static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
1902
{
1902
{
1903
	struct ast_str *body = ast_str_alloca(size);
1903
	struct ast_str *body = ast_str_alloca(size);
1904
	char tuple_id[32];
1904
	char tuple_id[32];
1905

    
   
1905

   
1906
	generate_random_string(tuple_id, sizeof(tuple_id));
1906
	generate_random_string(tuple_id, sizeof(tuple_id));
1907

    
   
1907

   
1908
	/* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
1908
	/* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
1909
	 * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
1909
	 * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
1910
	 */
1910
	 */
1911
	ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1911
	ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1912
	/* XXX The entity attribute is currently set to the peer name associated with the
1912
	/* XXX The entity attribute is currently set to the peer name associated with the
1913
	 * dialog. This is because we currently only call this function for call-completion
1913
	 * dialog. This is because we currently only call this function for call-completion
1914
	 * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
1914
	 * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
1915
	 * event packages, it may be crucial to have a proper URI as the presentity so this
1915
	 * event packages, it may be crucial to have a proper URI as the presentity so this
1916
	 * should be revisited as support is expanded.
1916
	 * should be revisited as support is expanded.
1917
	 */
1917
	 */
1918
	ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
1918
	ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
1919
	ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
1919
	ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
1920
	ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
1920
	ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
1921
	ast_str_append(&body, 0, "</tuple>\n");
1921
	ast_str_append(&body, 0, "</tuple>\n");
1922
	ast_str_append(&body, 0, "</presence>\n");
1922
	ast_str_append(&body, 0, "</presence>\n");
1923
	ast_copy_string(pidf_body, ast_str_buffer(body), size);
1923
	ast_copy_string(pidf_body, ast_str_buffer(body), size);
1924
	return 0;
1924
	return 0;
1925
}
1925
}
1926

    
   
1926

   
1927
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
1927
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
1928
{
1928
{
1929
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1929
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1930
	enum sip_publish_type publish_type;
1930
	enum sip_publish_type publish_type;
1931
	struct cc_epa_entry *cc_entry;
1931
	struct cc_epa_entry *cc_entry;
1932

    
   
1932

   
1933
	if (!monitor_instance) {
1933
	if (!monitor_instance) {
1934
		return -1;
1934
		return -1;
1935
	}
1935
	}
1936

    
   
1936

   
1937
	if (!monitor_instance->suspension_entry) {
1937
	if (!monitor_instance->suspension_entry) {
1938
		/* We haven't yet allocated the suspension entry, so let's give it a shot */
1938
		/* We haven't yet allocated the suspension entry, so let's give it a shot */
1939
		if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
1939
		if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
1940
			ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
1940
			ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
1941
			ao2_ref(monitor_instance, -1);
1941
			ao2_ref(monitor_instance, -1);
1942
			return -1;
1942
			return -1;
1943
		}
1943
		}
1944
		if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
1944
		if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
1945
			ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
1945
			ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
1946
			ao2_ref(monitor_instance, -1);
1946
			ao2_ref(monitor_instance, -1);
1947
			return -1;
1947
			return -1;
1948
		}
1948
		}
1949
		cc_entry->core_id = monitor->core_id;
1949
		cc_entry->core_id = monitor->core_id;
1950
		monitor_instance->suspension_entry->instance_data = cc_entry;
1950
		monitor_instance->suspension_entry->instance_data = cc_entry;
1951
		publish_type = SIP_PUBLISH_INITIAL;
1951
		publish_type = SIP_PUBLISH_INITIAL;
1952
	} else {
1952
	} else {
1953
		publish_type = SIP_PUBLISH_MODIFY;
1953
		publish_type = SIP_PUBLISH_MODIFY;
1954
		cc_entry = monitor_instance->suspension_entry->instance_data;
1954
		cc_entry = monitor_instance->suspension_entry->instance_data;
1955
	}
1955
	}
1956

    
   
1956

   
1957
	cc_entry->current_state = CC_CLOSED;
1957
	cc_entry->current_state = CC_CLOSED;
1958

    
   
1958

   
1959
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
1959
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
1960
		/* If we have no set notify_uri, then what this means is that we have
1960
		/* If we have no set notify_uri, then what this means is that we have
1961
		 * not received a NOTIFY from this destination stating that he is
1961
		 * not received a NOTIFY from this destination stating that he is
1962
		 * currently available.
1962
		 * currently available.
1963
		 *
1963
		 *
1964
		 * This situation can arise when the core calls the suspend callbacks
1964
		 * This situation can arise when the core calls the suspend callbacks
1965
		 * of multiple destinations. If one of the other destinations aside
1965
		 * of multiple destinations. If one of the other destinations aside
1966
		 * from this one notified Asterisk that he is available, then there
1966
		 * from this one notified Asterisk that he is available, then there
1967
		 * is no reason to take any suspension action on this device. Rather,
1967
		 * is no reason to take any suspension action on this device. Rather,
1968
		 * we should return now and if we receive a NOTIFY while monitoring
1968
		 * we should return now and if we receive a NOTIFY while monitoring
1969
		 * is still "suspended" then we can immediately respond with the
1969
		 * is still "suspended" then we can immediately respond with the
1970
		 * proper PUBLISH to let this endpoint know what is going on.
1970
		 * proper PUBLISH to let this endpoint know what is going on.
1971
		 */
1971
		 */
1972
		return 0;
1972
		return 0;
1973
	}
1973
	}
1974
	construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
1974
	construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
1975
	return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
1975
	return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
1976
}
1976
}
1977

    
   
1977

   
1978
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
1978
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
1979
{
1979
{
1980
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1980
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1981
	struct cc_epa_entry *cc_entry;
1981
	struct cc_epa_entry *cc_entry;
1982

    
   
1982

   
1983
	if (!monitor_instance) {
1983
	if (!monitor_instance) {
1984
		return -1;
1984
		return -1;
1985
	}
1985
	}
1986

    
   
1986

   
1987
	ast_assert(monitor_instance->suspension_entry != NULL);
1987
	ast_assert(monitor_instance->suspension_entry != NULL);
1988

    
   
1988

   
1989
	cc_entry = monitor_instance->suspension_entry->instance_data;
1989
	cc_entry = monitor_instance->suspension_entry->instance_data;
1990
	cc_entry->current_state = CC_OPEN;
1990
	cc_entry->current_state = CC_OPEN;
1991
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
1991
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
1992
		/* This means we are being asked to unsuspend a call leg we never
1992
		/* This means we are being asked to unsuspend a call leg we never
1993
		 * sent a PUBLISH on. As such, there is no reason to send another
1993
		 * sent a PUBLISH on. As such, there is no reason to send another
1994
		 * PUBLISH at this point either. We can just return instead.
1994
		 * PUBLISH at this point either. We can just return instead.
1995
		 */
1995
		 */
1996
		return 0;
1996
		return 0;
1997
	}
1997
	}
1998
	construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
1998
	construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
1999
	return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
1999
	return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
2000
}
2000
}
2001

    
   
2001

   
2002
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
2002
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
2003
{
2003
{
2004
	if (*sched_id != -1) {
2004
	if (*sched_id != -1) {
2005
		AST_SCHED_DEL(sched, *sched_id);
2005
		AST_SCHED_DEL(sched, *sched_id);
2006
		ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
2006
		ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
2007
	}
2007
	}
2008
	return 0;
2008
	return 0;
2009
}
2009
}
2010

    
   
2010

   
2011
static void sip_cc_monitor_destructor(void *private_data)
2011
static void sip_cc_monitor_destructor(void *private_data)
2012
{
2012
{
2013
	struct sip_monitor_instance *monitor_instance = private_data;
2013
	struct sip_monitor_instance *monitor_instance = private_data;
2014
	ao2_unlink(sip_monitor_instances, monitor_instance);
2014
	ao2_unlink(sip_monitor_instances, monitor_instance);
2015
	ast_module_unref(ast_module_info->self);
2015
	ast_module_unref(ast_module_info->self);
2016
}
2016
}
2017

    
   
2017

   
2018
static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
2018
static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
2019
{
2019
{
2020
	char *call_info = ast_strdupa(get_header(req, "Call-Info"));
2020
	char *call_info = ast_strdupa(get_header(req, "Call-Info"));
2021
	char *uri;
2021
	char *uri;
2022
	char *purpose;
2022
	char *purpose;
2023
	char *service_str;
2023
	char *service_str;
2024
	static const char cc_purpose[] = "purpose=call-completion";
2024
	static const char cc_purpose[] = "purpose=call-completion";
2025
	static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2025
	static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2026

    
   
2026

   
2027
	if (ast_strlen_zero(call_info)) {
2027
	if (ast_strlen_zero(call_info)) {
2028
		/* No Call-Info present. Definitely no CC offer */
2028
		/* No Call-Info present. Definitely no CC offer */
2029
		return -1;
2029
		return -1;
2030
	}
2030
	}
2031

    
   
2031

   
2032
	uri = strsep(&call_info, ";");
2032
	uri = strsep(&call_info, ";");
2033

    
   
2033

   
2034
	while ((purpose = strsep(&call_info, ";"))) {
2034
	while ((purpose = strsep(&call_info, ";"))) {
2035
		if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
2035
		if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
2036
			break;
2036
			break;
2037
		}
2037
		}
2038
	}
2038
	}
2039
	if (!purpose) {
2039
	if (!purpose) {
2040
		/* We didn't find the appropriate purpose= parameter. Oh well */
2040
		/* We didn't find the appropriate purpose= parameter. Oh well */
2041
		return -1;
2041
		return -1;
2042
	}
2042
	}
2043

    
   
2043

   
2044
	/* Okay, call-completion has been offered. Let's figure out what type of service this is */
2044
	/* Okay, call-completion has been offered. Let's figure out what type of service this is */
2045
	while ((service_str = strsep(&call_info, ";"))) {
2045
	while ((service_str = strsep(&call_info, ";"))) {
2046
		if (!strncmp(service_str, "m=", 2)) {
2046
		if (!strncmp(service_str, "m=", 2)) {
2047
			break;
2047
			break;
2048
		}
2048
		}
2049
	}
2049
	}
2050
	if (!service_str) {
2050
	if (!service_str) {
2051
		/* So they didn't offer a particular service, We'll just go with CCBS since it really
2051
		/* So they didn't offer a particular service, We'll just go with CCBS since it really
2052
		 * doesn't matter anyway
2052
		 * doesn't matter anyway
2053
		 */
2053
		 */
2054
		service_str = "BS";
2054
		service_str = "BS";
2055
	} else {
2055
	} else {
2056
		/* We already determined that there is an "m=" so no need to check
2056
		/* We already determined that there is an "m=" so no need to check
2057
		 * the result of this strsep
2057
		 * the result of this strsep
2058
		 */
2058
		 */
2059
		strsep(&service_str, "=");
2059
		strsep(&service_str, "=");
2060
	}
2060
	}
2061

    
   
2061

   
2062
	if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2062
	if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2063
		/* Invalid service offered */
2063
		/* Invalid service offered */
2064
		return -1;
2064
		return -1;
2065
	}
2065
	}
2066

    
   
2066

   
2067
	ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2067
	ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2068

    
   
2068

   
2069
	return 0;
2069
	return 0;
2070
}
2070
}
2071

    
   
2071

   
2072
/*
2072
/*
2073
 * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
2073
 * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
2074
 *
2074
 *
2075
 * After taking care of some formalities to be sure that this call is eligible for CC,
2075
 * After taking care of some formalities to be sure that this call is eligible for CC,
2076
 * we first try to see if we can make use of native CC. We grab the information from
2076
 * we first try to see if we can make use of native CC. We grab the information from
2077
 * the passed-in sip_request (which is always a response to an INVITE). If we can
2077
 * the passed-in sip_request (which is always a response to an INVITE). If we can
2078
 * use native CC monitoring for the call, then so be it.
2078
 * use native CC monitoring for the call, then so be it.
2079
 *
2079
 *
2080
 * If native cc monitoring is not possible or not supported, then we will instead attempt
2080
 * If native cc monitoring is not possible or not supported, then we will instead attempt
2081
 * to use generic monitoring. Falling back to generic from a failed attempt at using native
2081
 * to use generic monitoring. Falling back to generic from a failed attempt at using native
2082
 * monitoring will only work if the monitor policy of the endpoint is "always"
2082
 * monitoring will only work if the monitor policy of the endpoint is "always"
2083
 *
2083
 *
2084
 * \param pvt The current dialog. Contains CC parameters for the endpoint
2084
 * \param pvt The current dialog. Contains CC parameters for the endpoint
2085
 * \param req The response to the INVITE we want to inspect
2085
 * \param req The response to the INVITE we want to inspect
2086
 * \param service The service to use if generic monitoring is to be used. For native
2086
 * \param service The service to use if generic monitoring is to be used. For native
2087
 * monitoring, we get the service from the SIP response itself
2087
 * monitoring, we get the service from the SIP response itself
2088
 */
2088
 */
2089
static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
2089
static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
2090
{
2090
{
2091
	enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
2091
	enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
2092
	int core_id;
2092
	int core_id;
2093
	char interface_name[AST_CHANNEL_NAME];
2093
	char interface_name[AST_CHANNEL_NAME];
2094

    
   
2094

   
2095
	if (monitor_policy == AST_CC_MONITOR_NEVER) {
2095
	if (monitor_policy == AST_CC_MONITOR_NEVER) {
2096
		/* Don't bother, just return */
2096
		/* Don't bother, just return */
2097
		return;
2097
		return;
2098
	}
2098
	}
2099

    
   
2099

   
2100
	if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
2100
	if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
2101
		/* For some reason, CC is invalid, so don't try it! */
2101
		/* For some reason, CC is invalid, so don't try it! */
2102
		return;
2102
		return;
2103
	}
2103
	}
2104

    
   
2104

   
2105
	ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2105
	ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2106

    
   
2106

   
2107
	if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
2107
	if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
2108
		char subscribe_uri[SIPBUFSIZE];
2108
		char subscribe_uri[SIPBUFSIZE];
2109
		char device_name[AST_CHANNEL_NAME];
2109
		char device_name[AST_CHANNEL_NAME];
2110
		enum ast_cc_service_type offered_service;
2110
		enum ast_cc_service_type offered_service;
2111
		struct sip_monitor_instance *monitor_instance;
2111
		struct sip_monitor_instance *monitor_instance;
2112
		if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
2112
		if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
2113
			/* If CC isn't being offered to us, or for some reason the CC offer is
2113
			/* If CC isn't being offered to us, or for some reason the CC offer is
2114
			 * not formatted correctly, then it may still be possible to use generic
2114
			 * not formatted correctly, then it may still be possible to use generic
2115
			 * call completion since the monitor policy may be "always"
2115
			 * call completion since the monitor policy may be "always"
2116
			 */
2116
			 */
2117
			goto generic;
2117
			goto generic;
2118
		}
2118
		}
2119
		ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2119
		ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2120
		if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
2120
		if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
2121
			/* Same deal. We can try using generic still */
2121
			/* Same deal. We can try using generic still */
2122
			goto generic;
2122
			goto generic;
2123
		}
2123
		}
2124
		/* We bump the refcount of chan_sip because once we queue this frame, the CC core
2124
		/* We bump the refcount of chan_sip because once we queue this frame, the CC core
2125
		 * will have a reference to callbacks in this module. We decrement the module
2125
		 * will have a reference to callbacks in this module. We decrement the module
2126
		 * refcount once the monitor destructor is called
2126
		 * refcount once the monitor destructor is called
2127
		 */
2127
		 */
2128
		ast_module_ref(ast_module_info->self);
2128
		ast_module_ref(ast_module_info->self);
2129
		ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
2129
		ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
2130
		ao2_ref(monitor_instance, -1);
2130
		ao2_ref(monitor_instance, -1);
2131
		return;
2131
		return;
2132
	}
2132
	}
2133

    
   
2133

   
2134
generic:
2134
generic:
2135
	if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2135
	if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2136
		ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2136
		ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2137
	}
2137
	}
2138
}
2138
}
2139

    
   
2139

   
2140
/*! \brief Working TLS connection configuration */
2140
/*! \brief Working TLS connection configuration */
2141
static struct ast_tls_config sip_tls_cfg;
2141
static struct ast_tls_config sip_tls_cfg;
2142

    
   
2142

   
2143
/*! \brief Default TLS connection configuration */
2143
/*! \brief Default TLS connection configuration */
2144
static struct ast_tls_config default_tls_cfg;
2144
static struct ast_tls_config default_tls_cfg;
2145

    
   
2145

   
2146
/*! \brief The TCP server definition */
2146
/*! \brief The TCP server definition */
2147
static struct ast_tcptls_session_args sip_tcp_desc = {
2147
static struct ast_tcptls_session_args sip_tcp_desc = {
2148
	.accept_fd = -1,
2148
	.accept_fd = -1,
2149
	.master = AST_PTHREADT_NULL,
2149
	.master = AST_PTHREADT_NULL,
2150
	.tls_cfg = NULL,
2150
	.tls_cfg = NULL,
2151
	.poll_timeout = -1,
2151
	.poll_timeout = -1,
2152
	.name = "SIP TCP server",
2152
	.name = "SIP TCP server",
2153
	.accept_fn = ast_tcptls_server_root,
2153
	.accept_fn = ast_tcptls_server_root,
2154
	.worker_fn = sip_tcp_worker_fn,
2154
	.worker_fn = sip_tcp_worker_fn,
2155
};
2155
};
2156

    
   
2156

   
2157
/*! \brief The TCP/TLS server definition */
2157
/*! \brief The TCP/TLS server definition */
2158
static struct ast_tcptls_session_args sip_tls_desc = {
2158
static struct ast_tcptls_session_args sip_tls_desc = {
2159
	.accept_fd = -1,
2159
	.accept_fd = -1,
2160
	.master = AST_PTHREADT_NULL,
2160
	.master = AST_PTHREADT_NULL,
2161
	.tls_cfg = &sip_tls_cfg,
2161
	.tls_cfg = &sip_tls_cfg,
2162
	.poll_timeout = -1,
2162
	.poll_timeout = -1,
2163
	.name = "SIP TLS server",
2163
	.name = "SIP TLS server",
2164
	.accept_fn = ast_tcptls_server_root,
2164
	.accept_fn = ast_tcptls_server_root,
2165
	.worker_fn = sip_tcp_worker_fn,
2165
	.worker_fn = sip_tcp_worker_fn,
2166
};
2166
};
2167

    
   
2167

   
2168
/*! \brief Append to SIP dialog history
2168
/*! \brief Append to SIP dialog history
2169
	\return Always returns 0 */
2169
	\return Always returns 0 */
2170
#define append_history(p, event, fmt , args... )	append_history_full(p, "%-15s " fmt, event, ## args)
2170
#define append_history(p, event, fmt , args... )	append_history_full(p, "%-15s " fmt, event, ## args)
2171

    
   
2171

   
2172
struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
2172
struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
2173
{
2173
{
2174
	if (p)
2174
	if (p)
2175
#ifdef REF_DEBUG
2175
#ifdef REF_DEBUG
2176
		__ao2_ref_debug(p, 1, tag, file, line, func);
2176
		__ao2_ref_debug(p, 1, tag, file, line, func);
2177
#else
2177
#else
2178
		ao2_ref(p, 1);
2178
		ao2_ref(p, 1);
2179
#endif
2179
#endif
2180
	else
2180
	else
2181
		ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2181
		ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2182
	return p;
2182
	return p;
2183
}
2183
}
2184

    
   
2184

   
2185
struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
2185
struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
2186
{
2186
{
2187
	if (p)
2187
	if (p)
2188
#ifdef REF_DEBUG
2188
#ifdef REF_DEBUG
2189
		__ao2_ref_debug(p, -1, tag, file, line, func);
2189
		__ao2_ref_debug(p, -1, tag, file, line, func);
2190
#else
2190
#else
2191
		ao2_ref(p, -1);
2191
		ao2_ref(p, -1);
2192
#endif
2192
#endif
2193
	return NULL;
2193
	return NULL;
2194
}
2194
}
2195

    
   
2195

   
2196
/*! \brief map from an integer value to a string.
2196
/*! \brief map from an integer value to a string.
2197
 * If no match is found, return errorstring
2197
 * If no match is found, return errorstring
2198
 */
2198
 */
2199
static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2199
static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2200
{
2200
{
2201
	const struct _map_x_s *cur;
2201
	const struct _map_x_s *cur;
2202

    
   
2202

   
2203
	for (cur = table; cur->s; cur++)
2203
	for (cur = table; cur->s; cur++)
2204
		if (cur->x == x)
2204
		if (cur->x == x)
2205
			return cur->s;
2205
			return cur->s;
2206
	return errorstring;
2206
	return errorstring;
2207
}
2207
}
2208

    
   
2208

   
2209
/*! \brief map from a string to an integer value, case insensitive.
2209
/*! \brief map from a string to an integer value, case insensitive.
2210
 * If no match is found, return errorvalue.
2210
 * If no match is found, return errorvalue.
2211
 */
2211
 */
2212
static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2212
static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2213
{
2213
{
2214
	const struct _map_x_s *cur;
2214
	const struct _map_x_s *cur;
2215

    
   
2215

   
2216
	for (cur = table; cur->s; cur++)
2216
	for (cur = table; cur->s; cur++)
2217
		if (!strcasecmp(cur->s, s))
2217
		if (!strcasecmp(cur->s, s))
2218
			return cur->x;
2218
			return cur->x;
2219
	return errorvalue;
2219
	return errorvalue;
2220
}
2220
}
2221

    
   
2221

   
2222
static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
2222
static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
2223
{
2223
{
2224
	enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2224
	enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2225
	int i;
2225
	int i;
2226

    
   
2226

   
2227
	for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
2227
	for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
2228
		if (!strcasecmp(text, sip_reason_table[i].text)) {
2228
		if (!strcasecmp(text, sip_reason_table[i].text)) {
2229
			ast = sip_reason_table[i].code;
2229
			ast = sip_reason_table[i].code;
2230
			break;
2230
			break;
2231
		}
2231
		}
2232
	}
2232
	}
2233

    
   
2233

   
2234
	return ast;
2234
	return ast;
2235
}
2235
}
2236

    
   
2236

   
2237
static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
2237
static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
2238
{
2238
{
2239
	if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2239
	if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2240
		return sip_reason_table[code].text;
2240
		return sip_reason_table[code].text;
2241
	}
2241
	}
2242

    
   
2242

   
2243
	return "unknown";
2243
	return "unknown";
2244
}
2244
}
2245

    
   
2245

   
2246
/*!
2246
/*!
2247
 * \brief generic function for determining if a correct transport is being
2247
 * \brief generic function for determining if a correct transport is being
2248
 * used to contact a peer
2248
 * used to contact a peer
2249
 *
2249
 *
2250
 * this is done as a macro so that the "tmpl" var can be passed either a
2250
 * this is done as a macro so that the "tmpl" var can be passed either a
2251
 * sip_request or a sip_peer
2251
 * sip_request or a sip_peer
2252
 */
2252
 */
2253
#define check_request_transport(peer, tmpl) ({ \
2253
#define check_request_transport(peer, tmpl) ({ \
2254
	int ret = 0; \
2254
	int ret = 0; \
2255
	if (peer->socket.type == tmpl->socket.type) \
2255
	if (peer->socket.type == tmpl->socket.type) \
2256
		; \
2256
		; \
2257
	else if (!(peer->transports & tmpl->socket.type)) {\
2257
	else if (!(peer->transports & tmpl->socket.type)) {\
2258
		ast_log(LOG_ERROR, \
2258
		ast_log(LOG_ERROR, \
2259
			"'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
2259
			"'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
2260
			get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
2260
			get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
2261
			); \
2261
			); \
2262
		ret = 1; \
2262
		ret = 1; \
2263
	} else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
2263
	} else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
2264
		ast_log(LOG_WARNING, \
2264
		ast_log(LOG_WARNING, \
2265
			"peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
2265
			"peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
2266
			peer->name, get_transport(tmpl->socket.type) \
2266
			peer->name, get_transport(tmpl->socket.type) \
2267
		); \
2267
		); \
2268
	} else { \
2268
	} else { \
2269
		ast_debug(1, \
2269
		ast_debug(1, \
2270
			"peer '%s' has contacted us over %s even though we prefer %s.\n", \
2270
			"peer '%s' has contacted us over %s even though we prefer %s.\n", \
2271
			peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
2271
			peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
2272
		); \
2272
		); \
2273
	}\
2273
	}\
2274
	(ret); \
2274
	(ret); \
2275
})
2275
})
2276

    
   
2276

   
2277
/*! \brief
2277
/*! \brief
2278
 * duplicate a list of channel variables, \return the copy.
2278
 * duplicate a list of channel variables, \return the copy.
2279
 */
2279
 */
2280
static struct ast_variable *copy_vars(struct ast_variable *src)
2280
static struct ast_variable *copy_vars(struct ast_variable *src)
2281
{
2281
{
2282
	struct ast_variable *res = NULL, *tmp, *v = NULL;
2282
	struct ast_variable *res = NULL, *tmp, *v = NULL;
2283

    
   
2283

   
2284
	for (v = src ; v ; v = v->next) {
2284
	for (v = src ; v ; v = v->next) {
2285
		if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2285
		if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2286
			tmp->next = res;
2286
			tmp->next = res;
2287
			res = tmp;
2287
			res = tmp;
2288
		}
2288
		}
2289
	}
2289
	}
2290
	return res;
2290
	return res;
2291
}
2291
}
2292

    
   
2292

   
2293
static void tcptls_packet_destructor(void *obj)
2293
static void tcptls_packet_destructor(void *obj)
2294
{
2294
{
2295
	struct tcptls_packet *packet = obj;
2295
	struct tcptls_packet *packet = obj;
2296

    
   
2296

   
2297
	ast_free(packet->data);
2297
	ast_free(packet->data);
2298
}
2298
}
2299

    
   
2299

   
2300
static void sip_tcptls_client_args_destructor(void *obj)
2300
static void sip_tcptls_client_args_destructor(void *obj)
2301
{
2301
{
2302
	struct ast_tcptls_session_args *args = obj;
2302
	struct ast_tcptls_session_args *args = obj;
2303
	if (args->tls_cfg) {
2303
	if (args->tls_cfg) {
2304
		ast_free(args->tls_cfg->certfile);
2304
		ast_free(args->tls_cfg->certfile);
2305
		ast_free(args->tls_cfg->pvtfile);
2305
		ast_free(args->tls_cfg->pvtfile);
2306
		ast_free(args->tls_cfg->cipher);
2306
		ast_free(args->tls_cfg->cipher);
2307
		ast_free(args->tls_cfg->cafile);
2307
		ast_free(args->tls_cfg->cafile);
2308
		ast_free(args->tls_cfg->capath);
2308
		ast_free(args->tls_cfg->capath);
2309
	}
2309
	}
2310
	ast_free(args->tls_cfg);
2310
	ast_free(args->tls_cfg);
2311
	ast_free((char *) args->name);
2311
	ast_free((char *) args->name);
2312
}
2312
}
2313

    
   
2313

   
2314
static void sip_threadinfo_destructor(void *obj)
2314
static void sip_threadinfo_destructor(void *obj)
2315
{
2315
{
2316
	struct sip_threadinfo *th = obj;
2316
	struct sip_threadinfo *th = obj;
2317
	struct tcptls_packet *packet;
2317
	struct tcptls_packet *packet;
2318
	if (th->alert_pipe[1] > -1) {
2318
	if (th->alert_pipe[1] > -1) {
2319
		close(th->alert_pipe[0]);
2319
		close(th->alert_pipe[0]);
2320
	}
2320
	}
2321
	if (th->alert_pipe[1] > -1) {
2321
	if (th->alert_pipe[1] > -1) {
2322
		close(th->alert_pipe[1]);
2322
		close(th->alert_pipe[1]);
2323
	}
2323
	}
2324
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2324
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2325

    
   
2325

   
2326
	while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2326
	while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2327
		ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
2327
		ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
2328
	}
2328
	}
2329

    
   
2329

   
2330
	if (th->tcptls_session) {
2330
	if (th->tcptls_session) {
2331
		ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
2331
		ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
2332
	}
2332
	}
2333
}
2333
}
2334

    
   
2334

   
2335
/*! \brief creates a sip_threadinfo object and links it into the threadt table. */
2335
/*! \brief creates a sip_threadinfo object and links it into the threadt table. */
2336
static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
2336
static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
2337
{
2337
{
2338
	struct sip_threadinfo *th;
2338
	struct sip_threadinfo *th;
2339

    
   
2339

   
2340
	if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
2340
	if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
2341
		return NULL;
2341
		return NULL;
2342
	}
2342
	}
2343

    
   
2343

   
2344
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2344
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2345

    
   
2345

   
2346
	if (pipe(th->alert_pipe) == -1) {
2346
	if (pipe(th->alert_pipe) == -1) {
2347
		ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
2347
		ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
2348
		ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
2348
		ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
2349
		return NULL;
2349
		return NULL;
2350
	}
2350
	}
2351
	ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
2351
	ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
2352
	th->tcptls_session = tcptls_session;
2352
	th->tcptls_session = tcptls_session;
2353
	th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
2353
	th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
2354
	ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2354
	ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2355
	ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
2355
	ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
2356
	return th;
2356
	return th;
2357
}
2357
}
2358

    
   
2358

   
2359
/*! \brief used to indicate to a tcptls thread that data is ready to be written */
2359
/*! \brief used to indicate to a tcptls thread that data is ready to be written */
2360
static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
2360
static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
2361
{
2361
{
2362
	int res = len;
2362
	int res = len;
2363
	struct sip_threadinfo *th = NULL;
2363
	struct sip_threadinfo *th = NULL;
2364
	struct tcptls_packet *packet = NULL;
2364
	struct tcptls_packet *packet = NULL;
2365
	struct sip_threadinfo tmp = {
2365
	struct sip_threadinfo tmp = {
2366
		.tcptls_session = tcptls_session,
2366
		.tcptls_session = tcptls_session,
2367
	};
2367
	};
2368
	enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2368
	enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2369

    
   
2369

   
2370
	if (!tcptls_session) {
2370
	if (!tcptls_session) {
2371
		return XMIT_ERROR;
2371
		return XMIT_ERROR;
2372
	}
2372
	}
2373

    
   
2373

   
2374
	ast_mutex_lock(&tcptls_session->lock);
2374
	ast_mutex_lock(&tcptls_session->lock);
2375

    
   
2375

   
2376
	if ((tcptls_session->fd == -1) ||
2376
	if ((tcptls_session->fd == -1) ||
2377
		!(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
2377
		!(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
2378
		!(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2378
		!(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2379
		!(packet->data = ast_str_create(len))) {
2379
		!(packet->data = ast_str_create(len))) {
2380
		goto tcptls_write_setup_error;
2380
		goto tcptls_write_setup_error;
2381
	}
2381
	}
2382

    
   
2382

   
2383
	/* goto tcptls_write_error should _NOT_ be used beyond this point */
2383
	/* goto tcptls_write_error should _NOT_ be used beyond this point */
2384
	ast_str_set(&packet->data, 0, "%s", (char *) buf);
2384
	ast_str_set(&packet->data, 0, "%s", (char *) buf);
2385
	packet->len = len;
2385
	packet->len = len;
2386

    
   
2386

   
2387
	/* alert tcptls thread handler that there is a packet to be sent.
2387
	/* alert tcptls thread handler that there is a packet to be sent.
2388
	 * must lock the thread info object to guarantee control of the
2388
	 * must lock the thread info object to guarantee control of the
2389
	 * packet queue */
2389
	 * packet queue */
2390
	ao2_lock(th);
2390
	ao2_lock(th);
2391
	if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2391
	if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2392
		ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
2392
		ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
2393
		ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
2393
		ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
2394
		packet = NULL;
2394
		packet = NULL;
2395
		res = XMIT_ERROR;
2395
		res = XMIT_ERROR;
2396
	} else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
2396
	} else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
2397
		AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2397
		AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2398
	}
2398
	}
2399
	ao2_unlock(th);
2399
	ao2_unlock(th);
2400

    
   
2400

   
2401
	ast_mutex_unlock(&tcptls_session->lock);
2401
	ast_mutex_unlock(&tcptls_session->lock);
2402
	ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
2402
	ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
2403
	return res;
2403
	return res;
2404

    
   
2404

   
2405
tcptls_write_setup_error:
2405
tcptls_write_setup_error:
2406
	if (th) {
2406
	if (th) {
2407
		ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
2407
		ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
2408
	}
2408
	}
2409
	if (packet) {
2409
	if (packet) {
2410
		ao2_t_ref(packet, -1, "could not allocate packet's data");
2410
		ao2_t_ref(packet, -1, "could not allocate packet's data");
2411
	}
2411
	}
2412
	ast_mutex_unlock(&tcptls_session->lock);
2412
	ast_mutex_unlock(&tcptls_session->lock);
2413

    
   
2413

   
2414
	return XMIT_ERROR;
2414
	return XMIT_ERROR;
2415
}
2415
}
2416

    
   
2416

   
2417
/*! \brief SIP TCP connection handler */
2417
/*! \brief SIP TCP connection handler */
2418
static void *sip_tcp_worker_fn(void *data)
2418
static void *sip_tcp_worker_fn(void *data)
2419
{
2419
{
2420
	struct ast_tcptls_session_instance *tcptls_session = data;
2420
	struct ast_tcptls_session_instance *tcptls_session = data;
2421

    
   
2421

   
2422
	return _sip_tcp_helper_thread(NULL, tcptls_session);
2422
	return _sip_tcp_helper_thread(NULL, tcptls_session);
2423
}
2423
}
2424

    
   
2424

   
2425
/*! \brief SIP TCP thread management function
2425
/*! \brief SIP TCP thread management function
2426
	This function reads from the socket, parses the packet into a request
2426
	This function reads from the socket, parses the packet into a request
2427
*/
2427
*/
2428
static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
2428
static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
2429
{
2429
{
2430
	int res, cl;
2430
	int res, cl;
2431
	struct sip_request req = { 0, } , reqcpy = { 0, };
2431
	struct sip_request req = { 0, } , reqcpy = { 0, };
2432
	struct sip_threadinfo *me = NULL;
2432
	struct sip_threadinfo *me = NULL;
2433
	char buf[1024] = "";
2433
	char buf[1024] = "";
2434
	struct pollfd fds[2] = { { 0 }, { 0 }, };
2434
	struct pollfd fds[2] = { { 0 }, { 0 }, };
2435
	struct ast_tcptls_session_args *ca = NULL;
2435
	struct ast_tcptls_session_args *ca = NULL;
2436

    
   
2436

   
2437
	/* If this is a server session, then the connection has already been setup,
2437
	/* If this is a server session, then the connection has already been setup,
2438
	 * simply create the threadinfo object so we can access this thread for writing.
2438
	 * simply create the threadinfo object so we can access this thread for writing.
2439
	 * 
2439
	 * 
2440
	 * if this is a client connection more work must be done.
2440
	 * if this is a client connection more work must be done.
2441
	 * 1. We own the parent session args for a client connection.  This pointer needs
2441
	 * 1. We own the parent session args for a client connection.  This pointer needs
2442
	 *    to be held on to so we can decrement it's ref count on thread destruction.
2442
	 *    to be held on to so we can decrement it's ref count on thread destruction.
2443
	 * 2. The threadinfo object was created before this thread was launched, however
2443
	 * 2. The threadinfo object was created before this thread was launched, however
2444
	 *    it must be found within the threadt table.
2444
	 *    it must be found within the threadt table.
2445
	 * 3. Last, the tcptls_session must be started.
2445
	 * 3. Last, the tcptls_session must be started.
2446
	 */
2446
	 */
2447
	if (!tcptls_session->client) {
2447
	if (!tcptls_session->client) {
2448
		if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
2448
		if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
2449
			goto cleanup;
2449
			goto cleanup;
2450
		}
2450
		}
2451
		ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
2451
		ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
2452
	} else {
2452
	} else {
2453
		struct sip_threadinfo tmp = {
2453
		struct sip_threadinfo tmp = {
2454
			.tcptls_session = tcptls_session,
2454
			.tcptls_session = tcptls_session,
2455
		};
2455
		};
2456

    
   
2456

   
2457
		if ((!(ca = tcptls_session->parent)) ||
2457
		if ((!(ca = tcptls_session->parent)) ||
2458
			(!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
2458
			(!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
2459
			(!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
2459
			(!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
2460
			goto cleanup;
2460
			goto cleanup;
2461
		}
2461
		}
2462
	}
2462
	}
2463

    
   
2463

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

    
   
2466

   
2467
	/* set up pollfd to watch for reads on both the socket and the alert_pipe */
2467
	/* set up pollfd to watch for reads on both the socket and the alert_pipe */
2468
	fds[0].fd = tcptls_session->fd;
2468
	fds[0].fd = tcptls_session->fd;
2469
	fds[1].fd = me->alert_pipe[0];
2469
	fds[1].fd = me->alert_pipe[0];
2470
	fds[0].events = fds[1].events = POLLIN | POLLPRI;
2470
	fds[0].events = fds[1].events = POLLIN | POLLPRI;
2471

    
   
2471

   
2472
	if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
2472
	if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
2473
		goto cleanup;
2473
		goto cleanup;
2474
	}
2474
	}
2475
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
2475
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
2476
		goto cleanup;
2476
		goto cleanup;
2477
	}
2477
	}
2478

    
   
2478

   
2479
	for (;;) {
2479
	for (;;) {
2480
		struct ast_str *str_save;
2480
		struct ast_str *str_save;
2481

    
   
2481

   
2482
		res = ast_poll(fds, 2, -1); /* polls for both socket and alert_pipe */
2482
		res = ast_poll(fds, 2, -1); /* polls for both socket and alert_pipe */
2483
		if (res < 0) {
2483
		if (res < 0) {
2484
			ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
2484
			ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
2485
			goto cleanup;
2485
			goto cleanup;
2486
		}
2486
		}
2487

    
   
2487

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

    
   
2491

   
2492
			fds[0].revents = 0;
2492
			fds[0].revents = 0;
2493

    
   
2493

   
2494
			/* clear request structure */
2494
			/* clear request structure */
2495
			str_save = req.data;
2495
			str_save = req.data;
2496
			memset(&req, 0, sizeof(req));
2496
			memset(&req, 0, sizeof(req));
2497
			req.data = str_save;
2497
			req.data = str_save;
2498
			ast_str_reset(req.data);
2498
			ast_str_reset(req.data);
2499

    
   
2499

   
2500
			str_save = reqcpy.data;
2500
			str_save = reqcpy.data;
2501
			memset(&reqcpy, 0, sizeof(reqcpy));
2501
			memset(&reqcpy, 0, sizeof(reqcpy));
2502
			reqcpy.data = str_save;
2502
			reqcpy.data = str_save;
2503
			ast_str_reset(reqcpy.data);
2503
			ast_str_reset(reqcpy.data);
2504

    
   
2504

   
2505
			memset(buf, 0, sizeof(buf));
2505
			memset(buf, 0, sizeof(buf));
2506

    
   
2506

   
2507
			if (tcptls_session->ssl) {
2507
			if (tcptls_session->ssl) {
2508
				set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
2508
				set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
2509
				req.socket.port = htons(ourport_tls);
2509
				req.socket.port = htons(ourport_tls);
2510
			} else {
2510
			} else {
2511
				set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
2511
				set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
2512
				req.socket.port = htons(ourport_tcp);
2512
				req.socket.port = htons(ourport_tcp);
2513
			}
2513
			}
2514
			req.socket.fd = tcptls_session->fd;
2514
			req.socket.fd = tcptls_session->fd;
2515

    
   
2515

   
2516
			/* Read in headers one line at a time */
2516
			/* Read in headers one line at a time */
2517
			while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
2517
			while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
2518
				ast_mutex_lock(&tcptls_session->lock);
2518
				ast_mutex_lock(&tcptls_session->lock);
2519
				if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2519
				if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2520
					ast_mutex_unlock(&tcptls_session->lock);
2520
					ast_mutex_unlock(&tcptls_session->lock);
2521
					goto cleanup;
2521
					goto cleanup;
2522
				}
2522
				}
2523
				ast_mutex_unlock(&tcptls_session->lock);
2523
				ast_mutex_unlock(&tcptls_session->lock);
2524
				if (me->stop) {
2524
				if (me->stop) {
2525
					 goto cleanup;
2525
					 goto cleanup;
2526
				}
2526
				}
2527
				ast_str_append(&req.data, 0, "%s", buf);
2527
				ast_str_append(&req.data, 0, "%s", buf);
2528
				req.len = req.data->used;
2528
				req.len = req.data->used;
2529
			}
2529
			}
2530
			copy_request(&reqcpy, &req);
2530
			copy_request(&reqcpy, &req);
2531
			parse_request(&reqcpy);
2531
			parse_request(&reqcpy);
2532
			/* In order to know how much to read, we need the content-length header */
2532
			/* In order to know how much to read, we need the content-length header */
2533
			if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
2533
			if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
2534
				while (cl > 0) {
2534
				while (cl > 0) {
2535
					size_t bytes_read;
2535
					size_t bytes_read;
2536
					ast_mutex_lock(&tcptls_session->lock);
2536
					ast_mutex_lock(&tcptls_session->lock);
2537
					if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
2537
					if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
2538
						ast_mutex_unlock(&tcptls_session->lock);
2538
						ast_mutex_unlock(&tcptls_session->lock);
2539
						goto cleanup;
2539
						goto cleanup;
2540
					}
2540
					}
2541
					buf[bytes_read] = '\0';
2541
					buf[bytes_read] = '\0';
2542
					ast_mutex_unlock(&tcptls_session->lock);
2542
					ast_mutex_unlock(&tcptls_session->lock);
2543
					if (me->stop) {
2543
					if (me->stop) {
2544
						goto cleanup;
2544
						goto cleanup;
2545
					}
2545
					}
2546
					cl -= strlen(buf);
2546
					cl -= strlen(buf);
2547
					ast_str_append(&req.data, 0, "%s", buf);
2547
					ast_str_append(&req.data, 0, "%s", buf);
2548
					req.len = req.data->used;
2548
					req.len = req.data->used;
2549
				}
2549
				}
2550
			}
2550
			}
2551
			/*! \todo XXX If there's no Content-Length or if the content-length and what
2551
			/*! \todo XXX If there's no Content-Length or if the content-length and what
2552
					we receive is not the same - we should generate an error */
2552
					we receive is not the same - we should generate an error */
2553

    
   
2553

   
2554
			req.socket.tcptls_session = tcptls_session;
2554
			req.socket.tcptls_session = tcptls_session;
2555
			handle_request_do(&req, &tcptls_session->remote_address);
2555
			handle_request_do(&req, &tcptls_session->remote_address);
2556
		}
2556
		}
2557

    
   
2557

   
2558
		if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
2558
		if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
2559
			enum sip_tcptls_alert alert;
2559
			enum sip_tcptls_alert alert;
2560
			struct tcptls_packet *packet;
2560
			struct tcptls_packet *packet;
2561

    
   
2561

   
2562
			fds[1].revents = 0;
2562
			fds[1].revents = 0;
2563

    
   
2563

   
2564
			if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
2564
			if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
2565
				ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
2565
				ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
2566
				continue;
2566
				continue;
2567
			}
2567
			}
2568

    
   
2568

   
2569
			switch (alert) {
2569
			switch (alert) {
2570
			case TCPTLS_ALERT_STOP:
2570
			case TCPTLS_ALERT_STOP:
2571
				goto cleanup;
2571
				goto cleanup;
2572
			case TCPTLS_ALERT_DATA:
2572
			case TCPTLS_ALERT_DATA:
2573
				ao2_lock(me);
2573
				ao2_lock(me);
2574
				if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
2574
				if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
2575
					ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
2575
					ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
2576
				} else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
2576
				} else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
2577
					ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
2577
					ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
2578
				}
2578
				}
2579

    
   
2579

   
2580
				if (packet) {
2580
				if (packet) {
2581
					ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
2581
					ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
2582
				}
2582
				}
2583
				ao2_unlock(me);
2583
				ao2_unlock(me);
2584
				break;
2584
				break;
2585
			default:
2585
			default:
2586
				ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
2586
				ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
2587
			}
2587
			}
2588
		}
2588
		}
2589
	}
2589
	}
2590

    
   
2590

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

    
   
2592

   
2593
cleanup:
2593
cleanup:
2594
	if (me) {
2594
	if (me) {
2595
		ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
2595
		ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
2596
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2596
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2597
	}
2597
	}
2598
	deinit_req(&reqcpy);
2598
	deinit_req(&reqcpy);
2599
	deinit_req(&req);
2599
	deinit_req(&req);
2600

    
   
2600

   
2601
	/* if client, we own the parent session arguments and must decrement ref */
2601
	/* if client, we own the parent session arguments and must decrement ref */
2602
	if (ca) {
2602
	if (ca) {
2603
		ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
2603
		ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
2604
	}
2604
	}
2605

    
   
2605

   
2606
	if (tcptls_session) {
2606
	if (tcptls_session) {
2607
		ast_mutex_lock(&tcptls_session->lock);
2607
		ast_mutex_lock(&tcptls_session->lock);
2608
		if (tcptls_session->f) {
2608
		if (tcptls_session->f) {
2609
			fclose(tcptls_session->f);
2609
			fclose(tcptls_session->f);
2610
			tcptls_session->f = NULL;
2610
			tcptls_session->f = NULL;
2611
		}
2611
		}
2612
		if (tcptls_session->fd != -1) {
2612
		if (tcptls_session->fd != -1) {
2613
			close(tcptls_session->fd);
2613
			close(tcptls_session->fd);
2614
			tcptls_session->fd = -1;
2614
			tcptls_session->fd = -1;
2615
		}
2615
		}
2616
		tcptls_session->parent = NULL;
2616
		tcptls_session->parent = NULL;
2617
		ast_mutex_unlock(&tcptls_session->lock);
2617
		ast_mutex_unlock(&tcptls_session->lock);
2618

    
   
2618

   
2619
		ao2_ref(tcptls_session, -1);
2619
		ao2_ref(tcptls_session, -1);
2620
		tcptls_session = NULL;
2620
		tcptls_session = NULL;
2621
	}
2621
	}
2622
	return NULL;
2622
	return NULL;
2623
}
2623
}
2624

    
   
2624

   
2625

    
   
2625

   
2626
/*!
2626
/*!
2627
 * helper functions to unreference various types of objects.
2627
 * helper functions to unreference various types of objects.
2628
 * By handling them this way, we don't have to declare the
2628
 * By handling them this way, we don't have to declare the
2629
 * destructor on each call, which removes the chance of errors.
2629
 * destructor on each call, which removes the chance of errors.
2630
 */
2630
 */
2631
static void *unref_peer(struct sip_peer *peer, char *tag)
2631
static void *unref_peer(struct sip_peer *peer, char *tag)
2632
{
2632
{
2633
	ao2_t_ref(peer, -1, tag);
2633
	ao2_t_ref(peer, -1, tag);
2634
	return NULL;
2634
	return NULL;
2635
}
2635
}
2636

    
   
2636

   
2637
static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
2637
static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
2638
{
2638
{
2639
	ao2_t_ref(peer, 1, tag);
2639
	ao2_t_ref(peer, 1, tag);
2640
	return peer;
2640
	return peer;
2641
}
2641
}
2642

    
   
2642

   
2643
/*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
2643
/*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
2644
 *
2644
 *
2645
 * This function sets pvt's outboundproxy pointer to the one referenced
2645
 * This function sets pvt's outboundproxy pointer to the one referenced
2646
 * by the proxy parameter. Because proxy may be a refcounted object, and
2646
 * by the proxy parameter. Because proxy may be a refcounted object, and
2647
 * because pvt's old outboundproxy may also be a refcounted object, we need
2647
 * because pvt's old outboundproxy may also be a refcounted object, we need
2648
 * to maintain the proper refcounts.
2648
 * to maintain the proper refcounts.
2649
 *
2649
 *
2650
 * \param pvt The sip_pvt for which we wish to set the outboundproxy
2650
 * \param pvt The sip_pvt for which we wish to set the outboundproxy
2651
 * \param proxy The sip_proxy which we will point pvt towards.
2651
 * \param proxy The sip_proxy which we will point pvt towards.
2652
 * \return Returns void
2652
 * \return Returns void
2653
 */
2653
 */
2654
static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
2654
static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
2655
{
2655
{
2656
	struct sip_proxy *old_obproxy = pvt->outboundproxy;
2656
	struct sip_proxy *old_obproxy = pvt->outboundproxy;
2657
	/* The sip_cfg.outboundproxy is statically allocated, and so
2657
	/* The sip_cfg.outboundproxy is statically allocated, and so
2658
	 * we don't ever need to adjust refcounts for it
2658
	 * we don't ever need to adjust refcounts for it
2659
	 */
2659
	 */
2660
	if (proxy && proxy != &sip_cfg.outboundproxy) {
2660
	if (proxy && proxy != &sip_cfg.outboundproxy) {
2661
		ao2_ref(proxy, +1);
2661
		ao2_ref(proxy, +1);
2662
	}
2662
	}
2663
	pvt->outboundproxy = proxy;
2663
	pvt->outboundproxy = proxy;
2664
	if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
2664
	if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
2665
		ao2_ref(old_obproxy, -1);
2665
		ao2_ref(old_obproxy, -1);
2666
	}
2666
	}
2667
}
2667
}
2668

    
   
2668

   
2669
/*!
2669
/*!
2670
 * \brief Unlink a dialog from the dialogs container, as well as any other places
2670
 * \brief Unlink a dialog from the dialogs container, as well as any other places
2671
 * that it may be currently stored.
2671
 * that it may be currently stored.
2672
 *
2672
 *
2673
 * \note A reference to the dialog must be held before calling this function, and this
2673
 * \note A reference to the dialog must be held before calling this function, and this
2674
 * function does not release that reference.
2674
 * function does not release that reference.
2675
 */
2675
 */
2676
void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
2676
void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
2677
{
2677
{
2678
	struct sip_pkt *cp;
2678
	struct sip_pkt *cp;
2679

    
   
2679

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

    
   
2681

   
2682
	ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
2682
	ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
2683

    
   
2683

   
2684
	/* Unlink us from the owner (channel) if we have one */
2684
	/* Unlink us from the owner (channel) if we have one */
2685
	if (dialog->owner) {
2685
	if (dialog->owner) {
2686
		if (lockowner)
2686
		if (lockowner)
2687
			ast_channel_lock(dialog->owner);
2687
			ast_channel_lock(dialog->owner);
2688
		ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2688
		ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2689
		dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
2689
		dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
2690
		if (lockowner) {
2690
		if (lockowner) {
2691
			ast_channel_unlock(dialog->owner);
2691
			ast_channel_unlock(dialog->owner);
2692
		}
2692
		}
2693
	}
2693
	}
2694
	if (dialog->registry) {
2694
	if (dialog->registry) {
2695
		if (dialog->registry->call == dialog) {
2695
		if (dialog->registry->call == dialog) {
2696
			dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
2696
			dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
2697
		}
2697
		}
2698
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2698
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2699
	}
2699
	}
2700
	if (dialog->stateid > -1) {
2700
	if (dialog->stateid > -1) {
2701
		ast_extension_state_del(dialog->stateid, NULL);
2701
		ast_extension_state_del(dialog->stateid, NULL);
2702
		dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
2702
		dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
2703
		dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2703
		dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2704
	}
2704
	}
2705
	/* Remove link from peer to subscription of MWI */
2705
	/* Remove link from peer to subscription of MWI */
2706
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
2706
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
2707
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2707
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2708
	}
2708
	}
2709
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
2709
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
2710
		dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
2710
		dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
2711
	}
2711
	}
2712

    
   
2712

   
2713
	/* remove all current packets in this dialog */
2713
	/* remove all current packets in this dialog */
2714
	while((cp = dialog->packets)) {
2714
	while((cp = dialog->packets)) {
2715
		dialog->packets = dialog->packets->next;
2715
		dialog->packets = dialog->packets->next;
2716
		AST_SCHED_DEL(sched, cp->retransid);
2716
		AST_SCHED_DEL(sched, cp->retransid);
2717
		dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
2717
		dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
2718
		if (cp->data) {
2718
		if (cp->data) {
2719
			ast_free(cp->data);
2719
			ast_free(cp->data);
2720
		}
2720
		}
2721
		ast_free(cp);
2721
		ast_free(cp);
2722
	}
2722
	}
2723

    
   
2723

   
2724
	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"));
2724
	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"));
2725

    
   
2725

   
2726
	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"));
2726
	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"));
2727
	
2727
	
2728
	if (dialog->autokillid > -1) {
2728
	if (dialog->autokillid > -1) {
2729
		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"));
2729
		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"));
2730
	}
2730
	}
2731

    
   
2731

   
2732
	if (dialog->request_queue_sched_id > -1) {
2732
	if (dialog->request_queue_sched_id > -1) {
2733
		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"));
2733
		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"));
2734
	}
2734
	}
2735

    
   
2735

   
2736
	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"));
2736
	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"));
2737

    
   
2737

   
2738
	if (dialog->t38id > -1) {
2738
	if (dialog->t38id > -1) {
2739
		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"));
2739
		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"));
2740
	}
2740
	}
2741

    
   
2741

   
2742
	dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
2742
	dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
2743
	return NULL;
2743
	return NULL;
2744
}
2744
}
2745

    
   
2745

   
2746
void *registry_unref(struct sip_registry *reg, char *tag)
2746
void *registry_unref(struct sip_registry *reg, char *tag)
2747
{
2747
{
2748
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
2748
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
2749
	ASTOBJ_UNREF(reg, sip_registry_destroy);
2749
	ASTOBJ_UNREF(reg, sip_registry_destroy);
2750
	return NULL;
2750
	return NULL;
2751
}
2751
}
2752

    
   
2752

   
2753
/*! \brief Add object reference to SIP registry */
2753
/*! \brief Add object reference to SIP registry */
2754
static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
2754
static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
2755
{
2755
{
2756
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
2756
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
2757
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
2757
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
2758
}
2758
}
2759

    
   
2759

   
2760
/*! \brief Interface structure with callbacks used to connect to UDPTL module*/
2760
/*! \brief Interface structure with callbacks used to connect to UDPTL module*/
2761
static struct ast_udptl_protocol sip_udptl = {
2761
static struct ast_udptl_protocol sip_udptl = {
2762
	type: "SIP",
2762
	type: "SIP",
2763
	get_udptl_info: sip_get_udptl_peer,
2763
	get_udptl_info: sip_get_udptl_peer,
2764
	set_udptl_peer: sip_set_udptl_peer,
2764
	set_udptl_peer: sip_set_udptl_peer,
2765
};
2765
};
2766

    
   
2766

   
2767
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2767
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2768
	__attribute__((format(printf, 2, 3)));
2768
	__attribute__((format(printf, 2, 3)));
2769

    
   
2769

   
2770

    
   
2770

   
2771
/*! \brief Convert transfer status to string */
2771
/*! \brief Convert transfer status to string */
2772
static const char *referstatus2str(enum referstatus rstatus)
2772
static const char *referstatus2str(enum referstatus rstatus)
2773
{
2773
{
2774
	return map_x_s(referstatusstrings, rstatus, "");
2774
	return map_x_s(referstatusstrings, rstatus, "");
2775
}
2775
}
2776

    
   
2776

   
2777
static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
2777
static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
2778
{
2778
{
2779
	if (pvt->final_destruction_scheduled) {
2779
	if (pvt->final_destruction_scheduled) {
2780
		return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
2780
		return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
2781
	}
2781
	}
2782
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
2782
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
2783
	pvt->needdestroy = 1;
2783
	pvt->needdestroy = 1;
2784
}
2784
}
2785

    
   
2785

   
2786
/*! \brief Initialize the initital request packet in the pvt structure.
2786
/*! \brief Initialize the initital request packet in the pvt structure.
2787
 	This packet is used for creating replies and future requests in
2787
 	This packet is used for creating replies and future requests in
2788
	a dialog */
2788
	a dialog */
2789
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
2789
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
2790
{
2790
{
2791
	if (p->initreq.headers) {
2791
	if (p->initreq.headers) {
2792
		ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
2792
		ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
2793
	} else {
2793
	} else {
2794
		ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
2794
		ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
2795
	}
2795
	}
2796
	/* Use this as the basis */
2796
	/* Use this as the basis */
2797
	copy_request(&p->initreq, req);
2797
	copy_request(&p->initreq, req);
2798
	parse_request(&p->initreq);
2798
	parse_request(&p->initreq);
2799
	if (req->debug) {
2799
	if (req->debug) {
2800
		ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
2800
		ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
2801
	}
2801
	}
2802
}
2802
}
2803

    
   
2803

   
2804
/*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
2804
/*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
2805
static void sip_alreadygone(struct sip_pvt *dialog)
2805
static void sip_alreadygone(struct sip_pvt *dialog)
2806
{
2806
{
2807
	ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
2807
	ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
2808
	dialog->alreadygone = 1;
2808
	dialog->alreadygone = 1;
2809
}
2809
}
2810

    
   
2810

   
2811
/*! Resolve DNS srv name or host name in a sip_proxy structure */
2811
/*! Resolve DNS srv name or host name in a sip_proxy structure */
2812
static int proxy_update(struct sip_proxy *proxy)
2812
static int proxy_update(struct sip_proxy *proxy)
2813
{
2813
{
2814
	/* if it's actually an IP address and not a name,
2814
	/* if it's actually an IP address and not a name,
2815
           there's no need for a managed lookup */
2815
           there's no need for a managed lookup */
2816
	if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
2816
	if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
2817
		/* Ok, not an IP address, then let's check if it's a domain or host */
2817
		/* Ok, not an IP address, then let's check if it's a domain or host */
2818
		/* XXX Todo - if we have proxy port, don't do SRV */
2818
		/* XXX Todo - if we have proxy port, don't do SRV */
2819
		proxy->ip.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
2819
		proxy->ip.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
2820
		if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
2820
		if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
2821
				ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2821
				ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2822
				return FALSE;
2822
				return FALSE;
2823
		}
2823
		}
2824

    
   
2824

   
2825
	}
2825
	}
2826

    
   
2826

   
2827
	ast_sockaddr_set_port(&proxy->ip, proxy->port);
2827
	ast_sockaddr_set_port(&proxy->ip, proxy->port);
2828

    
   
2828

   
2829
	proxy->last_dnsupdate = time(NULL);
2829
	proxy->last_dnsupdate = time(NULL);
2830
	return TRUE;
2830
	return TRUE;
2831
}
2831
}
2832

    
   
2832

   
2833
/*! \brief converts ascii port to int representation. If no
2833
/*! \brief converts ascii port to int representation. If no
2834
 *  pt buffer is provided or the pt has errors when being converted
2834
 *  pt buffer is provided or the pt has errors when being converted
2835
 *  to an int value, the port provided as the standard is used.
2835
 *  to an int value, the port provided as the standard is used.
2836
 */
2836
 */
2837
unsigned int port_str2int(const char *pt, unsigned int standard)
2837
unsigned int port_str2int(const char *pt, unsigned int standard)
2838
{
2838
{
2839
	int port = standard;
2839
	int port = standard;
2840
	if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
2840
	if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
2841
		port = standard;
2841
		port = standard;
2842
	}
2842
	}
2843

    
   
2843

   
2844
	return port;
2844
	return port;
2845
}
2845
}
2846

    
   
2846

   
2847
/*! \brief Get default outbound proxy or global proxy */
2847
/*! \brief Get default outbound proxy or global proxy */
2848
static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2848
static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2849
{
2849
{
2850
	if (peer && peer->outboundproxy) {
2850
	if (peer && peer->outboundproxy) {
2851
		if (sipdebug) {
2851
		if (sipdebug) {
2852
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2852
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2853
		}
2853
		}
2854
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2854
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2855
		return peer->outboundproxy;
2855
		return peer->outboundproxy;
2856
	}
2856
	}
2857
	if (sip_cfg.outboundproxy.name[0]) {
2857
	if (sip_cfg.outboundproxy.name[0]) {
2858
		if (sipdebug) {
2858
		if (sipdebug) {
2859
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2859
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2860
		}
2860
		}
2861
		append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
2861
		append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
2862
		return &sip_cfg.outboundproxy;
2862
		return &sip_cfg.outboundproxy;
2863
	}
2863
	}
2864
	if (sipdebug) {
2864
	if (sipdebug) {
2865
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2865
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2866
	}
2866
	}
2867
	return NULL;
2867
	return NULL;
2868
}
2868
}
2869

    
   
2869

   
2870
/*! \brief returns true if 'name' (with optional trailing whitespace)
2870
/*! \brief returns true if 'name' (with optional trailing whitespace)
2871
 * matches the sip method 'id'.
2871
 * matches the sip method 'id'.
2872
 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2872
 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2873
 * a case-insensitive comparison to be more tolerant.
2873
 * a case-insensitive comparison to be more tolerant.
2874
 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2874
 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2875
 */
2875
 */
2876
static int method_match(enum sipmethod id, const char *name)
2876
static int method_match(enum sipmethod id, const char *name)
2877
{
2877
{
2878
	int len = strlen(sip_methods[id].text);
2878
	int len = strlen(sip_methods[id].text);
2879
	int l_name = name ? strlen(name) : 0;
2879
	int l_name = name ? strlen(name) : 0;
2880
	/* true if the string is long enough, and ends with whitespace, and matches */
2880
	/* true if the string is long enough, and ends with whitespace, and matches */
2881
	return (l_name >= len && name[len] < 33 &&
2881
	return (l_name >= len && name[len] < 33 &&
2882
		!strncasecmp(sip_methods[id].text, name, len));
2882
		!strncasecmp(sip_methods[id].text, name, len));
2883
}
2883
}
2884

    
   
2884

   
2885
/*! \brief  find_sip_method: Find SIP method from header */
2885
/*! \brief  find_sip_method: Find SIP method from header */
2886
static int find_sip_method(const char *msg)
2886
static int find_sip_method(const char *msg)
2887
{
2887
{
2888
	int i, res = 0;
2888
	int i, res = 0;
2889
	
2889
	
2890
	if (ast_strlen_zero(msg)) {
2890
	if (ast_strlen_zero(msg)) {
2891
		return 0;
2891
		return 0;
2892
	}
2892
	}
2893
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
2893
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
2894
		if (method_match(i, msg)) {
2894
		if (method_match(i, msg)) {
2895
			res = sip_methods[i].id;
2895
			res = sip_methods[i].id;
2896
		}
2896
		}
2897
	}
2897
	}
2898
	return res;
2898
	return res;
2899
}
2899
}
2900

    
   
2900

   
2901
/*! \brief See if we pass debug IP filter */
2901
/*! \brief See if we pass debug IP filter */
2902
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
2902
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
2903
{
2903
{
2904
	/* Can't debug if sipdebug is not enabled */
2904
	/* Can't debug if sipdebug is not enabled */
2905
	if (!sipdebug) {
2905
	if (!sipdebug) {
2906
		return 0;
2906
		return 0;
2907
	}
2907
	}
2908

    
   
2908

   
2909
	/* A null debug_addr means we'll debug any address */
2909
	/* A null debug_addr means we'll debug any address */
2910
	if (ast_sockaddr_isnull(&debugaddr)) {
2910
	if (ast_sockaddr_isnull(&debugaddr)) {
2911
		return 1;
2911
		return 1;
2912
	}
2912
	}
2913

    
   
2913

   
2914
	/* If no port was specified for a debug address, just compare the
2914
	/* If no port was specified for a debug address, just compare the
2915
	 * addresses, otherwise compare the address and port
2915
	 * addresses, otherwise compare the address and port
2916
	 */
2916
	 */
2917
	if (ast_sockaddr_port(&debugaddr)) {
2917
	if (ast_sockaddr_port(&debugaddr)) {
2918
		return !ast_sockaddr_cmp(&debugaddr, addr);
2918
		return !ast_sockaddr_cmp(&debugaddr, addr);
2919
	} else {
2919
	} else {
2920
		return !ast_sockaddr_cmp_addr(&debugaddr, addr);
2920
		return !ast_sockaddr_cmp_addr(&debugaddr, addr);
2921
	}
2921
	}
2922
}
2922
}
2923

    
   
2923

   
2924
/*! \brief The real destination address for a write */
2924
/*! \brief The real destination address for a write */
2925
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
2925
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
2926
{
2926
{
2927
	if (p->outboundproxy) {
2927
	if (p->outboundproxy) {
2928
		return &p->outboundproxy->ip;
2928
		return &p->outboundproxy->ip;
2929
	}
2929
	}
2930

    
   
2930

   
2931
	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;
2931
	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;
2932
}
2932
}
2933

    
   
2933

   
2934
/*! \brief Display SIP nat mode */
2934
/*! \brief Display SIP nat mode */
2935
static const char *sip_nat_mode(const struct sip_pvt *p)
2935
static const char *sip_nat_mode(const struct sip_pvt *p)
2936
{
2936
{
2937
	return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
2937
	return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
2938
}
2938
}
2939

    
   
2939

   
2940
/*! \brief Test PVT for debugging output */
2940
/*! \brief Test PVT for debugging output */
2941
static inline int sip_debug_test_pvt(struct sip_pvt *p)
2941
static inline int sip_debug_test_pvt(struct sip_pvt *p)
2942
{
2942
{
2943
	if (!sipdebug) {
2943
	if (!sipdebug) {
2944
		return 0;
2944
		return 0;
2945
	}
2945
	}
2946
	return sip_debug_test_addr(sip_real_dst(p));
2946
	return sip_debug_test_addr(sip_real_dst(p));
2947
}
2947
}
2948

    
   
2948

   
2949
/*! \brief Return int representing a bit field of transport types found in const char *transport */
2949
/*! \brief Return int representing a bit field of transport types found in const char *transport */
2950
static int get_transport_str2enum(const char *transport)
2950
static int get_transport_str2enum(const char *transport)
2951
{
2951
{
2952
	int res = 0;
2952
	int res = 0;
2953

    
   
2953

   
2954
	if (ast_strlen_zero(transport)) {
2954
	if (ast_strlen_zero(transport)) {
2955
		return res;
2955
		return res;
2956
	}
2956
	}
2957

    
   
2957

   
2958
	if (!strcasecmp(transport, "udp")) {
2958
	if (!strcasecmp(transport, "udp")) {
2959
		res |= SIP_TRANSPORT_UDP;
2959
		res |= SIP_TRANSPORT_UDP;
2960
	}
2960
	}
2961
	if (!strcasecmp(transport, "tcp")) {
2961
	if (!strcasecmp(transport, "tcp")) {
2962
		res |= SIP_TRANSPORT_TCP;
2962
		res |= SIP_TRANSPORT_TCP;
2963
	}
2963
	}
2964
	if (!strcasecmp(transport, "tls")) {
2964
	if (!strcasecmp(transport, "tls")) {
2965
		res |= SIP_TRANSPORT_TLS;
2965
		res |= SIP_TRANSPORT_TLS;
2966
	}
2966
	}
2967

    
   
2967

   
2968
	return res;
2968
	return res;
2969
}
2969
}
2970

    
   
2970

   
2971
/*! \brief Return configuration of transports for a device */
2971
/*! \brief Return configuration of transports for a device */
2972
static inline const char *get_transport_list(unsigned int transports) {
2972
static inline const char *get_transport_list(unsigned int transports) {
2973
	switch (transports) {
2973
	switch (transports) {
2974
		case SIP_TRANSPORT_UDP:
2974
		case SIP_TRANSPORT_UDP:
2975
			return "UDP";
2975
			return "UDP";
2976
		case SIP_TRANSPORT_TCP:
2976
		case SIP_TRANSPORT_TCP:
2977
			return "TCP";
2977
			return "TCP";
2978
		case SIP_TRANSPORT_TLS:
2978
		case SIP_TRANSPORT_TLS:
2979
			return "TLS";
2979
			return "TLS";
2980
		case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
2980
		case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
2981
			return "TCP,UDP";
2981
			return "TCP,UDP";
2982
		case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
2982
		case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
2983
			return "TLS,UDP";
2983
			return "TLS,UDP";
2984
		case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
2984
		case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
2985
			return "TLS,TCP";
2985
			return "TLS,TCP";
2986
		default:
2986
		default:
2987
			return transports ?
2987
			return transports ?
2988
				"TLS,TCP,UDP" : "UNKNOWN";	
2988
				"TLS,TCP,UDP" : "UNKNOWN";	
2989
	}
2989
	}
2990
}
2990
}
2991

    
   
2991

   
2992
/*! \brief Return transport as string */
2992
/*! \brief Return transport as string */
2993
static inline const char *get_transport(enum sip_transport t)
2993
static inline const char *get_transport(enum sip_transport t)
2994
{
2994
{
2995
	switch (t) {
2995
	switch (t) {
2996
	case SIP_TRANSPORT_UDP:
2996
	case SIP_TRANSPORT_UDP:
2997
		return "UDP";
2997
		return "UDP";
2998
	case SIP_TRANSPORT_TCP:
2998
	case SIP_TRANSPORT_TCP:
2999
		return "TCP";
2999
		return "TCP";
3000
	case SIP_TRANSPORT_TLS:
3000
	case SIP_TRANSPORT_TLS:
3001
		return "TLS";
3001
		return "TLS";
3002
	}
3002
	}
3003

    
   
3003

   
3004
	return "UNKNOWN";
3004
	return "UNKNOWN";
3005
}
3005
}
3006

    
   
3006

   
3007
/*! \brief Return protocol string for srv dns query */
3007
/*! \brief Return protocol string for srv dns query */
3008
static inline const char *get_srv_protocol(enum sip_transport t)
3008
static inline const char *get_srv_protocol(enum sip_transport t)
3009
{
3009
{
3010
	switch (t) {
3010
	switch (t) {
3011
	case SIP_TRANSPORT_UDP:
3011
	case SIP_TRANSPORT_UDP:
3012
		return "udp";
3012
		return "udp";
3013
	case SIP_TRANSPORT_TLS:
3013
	case SIP_TRANSPORT_TLS:
3014
	case SIP_TRANSPORT_TCP:
3014
	case SIP_TRANSPORT_TCP:
3015
		return "tcp";
3015
		return "tcp";
3016
	}
3016
	}
3017

    
   
3017

   
3018
	return "udp";
3018
	return "udp";
3019
}
3019
}
3020

    
   
3020

   
3021
/*! \brief Return service string for srv dns query */
3021
/*! \brief Return service string for srv dns query */
3022
static inline const char *get_srv_service(enum sip_transport t)
3022
static inline const char *get_srv_service(enum sip_transport t)
3023
{
3023
{
3024
	switch (t) {
3024
	switch (t) {
3025
	case SIP_TRANSPORT_TCP:
3025
	case SIP_TRANSPORT_TCP:
3026
	case SIP_TRANSPORT_UDP:
3026
	case SIP_TRANSPORT_UDP:
3027
		return "sip";
3027
		return "sip";
3028
	case SIP_TRANSPORT_TLS:
3028
	case SIP_TRANSPORT_TLS:
3029
		return "sips";
3029
		return "sips";
3030
	}
3030
	}
3031
	return "sip";
3031
	return "sip";
3032
}
3032
}
3033

    
   
3033

   
3034
/*! \brief Return transport of dialog.
3034
/*! \brief Return transport of dialog.
3035
	\note this is based on a false assumption. We don't always use the
3035
	\note this is based on a false assumption. We don't always use the
3036
	outbound proxy for all requests in a dialog. It depends on the
3036
	outbound proxy for all requests in a dialog. It depends on the
3037
	"force" parameter. The FIRST request is always sent to the ob proxy.
3037
	"force" parameter. The FIRST request is always sent to the ob proxy.
3038
	\todo Fix this function to work correctly
3038
	\todo Fix this function to work correctly
3039
*/
3039
*/
3040
static inline const char *get_transport_pvt(struct sip_pvt *p)
3040
static inline const char *get_transport_pvt(struct sip_pvt *p)
3041
{
3041
{
3042
	if (p->outboundproxy && p->outboundproxy->transport) {
3042
	if (p->outboundproxy && p->outboundproxy->transport) {
3043
		set_socket_transport(&p->socket, p->outboundproxy->transport);
3043
		set_socket_transport(&p->socket, p->outboundproxy->transport);
3044
	}
3044
	}
3045

    
   
3045

   
3046
	return get_transport(p->socket.type);
3046
	return get_transport(p->socket.type);
3047
}
3047
}
3048

    
   
3048

   
3049
/*! \brief Transmit SIP message
3049
/*! \brief Transmit SIP message
3050
	Sends a SIP request or response on a given socket (in the pvt)
3050
	Sends a SIP request or response on a given socket (in the pvt)
3051
	Called by retrans_pkt, send_request, send_response and
3051
	Called by retrans_pkt, send_request, send_response and
3052
	__sip_reliable_xmit
3052
	__sip_reliable_xmit
3053
	\return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
3053
	\return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
3054
*/
3054
*/
3055
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
3055
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
3056
{
3056
{
3057
	int res = 0;
3057
	int res = 0;
3058
	const struct ast_sockaddr *dst = sip_real_dst(p);
3058
	const struct ast_sockaddr *dst = sip_real_dst(p);
3059

    
   
3059

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

    
   
3061

   
3062
	if (sip_prepare_socket(p) < 0) {
3062
	if (sip_prepare_socket(p) < 0) {
3063
		return XMIT_ERROR;
3063
		return XMIT_ERROR;
3064
	}
3064
	}
3065

    
   
3065

   
3066
	if (p->socket.type == SIP_TRANSPORT_UDP) {
3066
	if (p->socket.type == SIP_TRANSPORT_UDP) {
3067
		res = ast_sendto(p->socket.fd, data->str, len, 0, dst);
3067
		res = ast_sendto(p->socket.fd, data->str, len, 0, dst);
3068
	} else if (p->socket.tcptls_session) {
3068
	} else if (p->socket.tcptls_session) {
3069
		res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
3069
		res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
3070
	} else {
3070
	} else {
3071
		ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
3071
		ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
3072
		return XMIT_ERROR;
3072
		return XMIT_ERROR;
3073
	}
3073
	}
3074

    
   
3074

   
3075
	if (res == -1) {
3075
	if (res == -1) {
3076
		switch (errno) {
3076
		switch (errno) {
3077
		case EBADF: 		/* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
3077
		case EBADF: 		/* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
3078
		case EHOSTUNREACH: 	/* Host can't be reached */
3078
		case EHOSTUNREACH: 	/* Host can't be reached */
3079
		case ENETDOWN: 		/* Interface down */
3079
		case ENETDOWN: 		/* Interface down */
3080
		case ENETUNREACH:	/* Network failure */
3080
		case ENETUNREACH:	/* Network failure */
3081
		case ECONNREFUSED:      /* ICMP port unreachable */
3081
		case ECONNREFUSED:      /* ICMP port unreachable */
3082
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */
3082
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */
3083
		}
3083
		}
3084
	}
3084
	}
3085
	if (res != len) {
3085
	if (res != len) {
3086
		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));
3086
		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));
3087
	}
3087
	}
3088

    
   
3088

   
3089
	return res;
3089
	return res;
3090
}
3090
}
3091

    
   
3091

   
3092
/*! \brief Build a Via header for a request */
3092
/*! \brief Build a Via header for a request */
3093
static void build_via(struct sip_pvt *p)
3093
static void build_via(struct sip_pvt *p)
3094
{
3094
{
3095
	/* Work around buggy UNIDEN UIP200 firmware */
3095
	/* Work around buggy UNIDEN UIP200 firmware */
3096
	const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
3096
	const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
3097

    
   
3097

   
3098
	/* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
3098
	/* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
3099
	snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
3099
	snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
3100
		 get_transport_pvt(p),
3100
		 get_transport_pvt(p),
3101
		 ast_sockaddr_stringify(&p->ourip),
3101
		 ast_sockaddr_stringify(&p->ourip),
3102
		 (int) p->branch, rport);
3102
		 (int) p->branch, rport);
3103
}
3103
}
3104

    
   
3104

   
3105
/*! \brief NAT fix - decide which IP address to use for Asterisk server?
3105
/*! \brief NAT fix - decide which IP address to use for Asterisk server?
3106
 *
3106
 *
3107
 * Using the localaddr structure built up with localnet statements in sip.conf
3107
 * Using the localaddr structure built up with localnet statements in sip.conf
3108
 * apply it to their address to see if we need to substitute our
3108
 * apply it to their address to see if we need to substitute our
3109
 * externaddr or can get away with our internal bindaddr
3109
 * externaddr or can get away with our internal bindaddr
3110
 * 'us' is always overwritten.
3110
 * 'us' is always overwritten.
3111
 */
3111
 */
3112
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
3112
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
3113
{
3113
{
3114
	struct ast_sockaddr theirs;
3114
	struct ast_sockaddr theirs;
3115
	struct sockaddr_in externaddr_sin;
3115
	struct sockaddr_in externaddr_sin;
3116

    
   
3116

   
3117
	/* Set want_remap to non-zero if we want to remap 'us' to an externally
3117
	/* Set want_remap to non-zero if we want to remap 'us' to an externally
3118
	 * reachable IP address and port. This is done if:
3118
	 * reachable IP address and port. This is done if:
3119
	 * 1. we have a localaddr list (containing 'internal' addresses marked
3119
	 * 1. we have a localaddr list (containing 'internal' addresses marked
3120
	 *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
3120
	 *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
3121
	 *    and AST_SENSE_ALLOW on 'external' ones);
3121
	 *    and AST_SENSE_ALLOW on 'external' ones);
3122
	 * 2. either stunaddr or externaddr is set, so we know what to use as the
3122
	 * 2. either stunaddr or externaddr is set, so we know what to use as the
3123
	 *    externally visible address;
3123
	 *    externally visible address;
3124
	 * 3. the remote address, 'them', is external;
3124
	 * 3. the remote address, 'them', is external;
3125
	 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
3125
	 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
3126
	 *    when passed to ast_apply_ha() so it does need to be remapped.
3126
	 *    when passed to ast_apply_ha() so it does need to be remapped.
3127
	 *    This fourth condition is checked later.
3127
	 *    This fourth condition is checked later.
3128
	 */
3128
	 */
3129
	int want_remap = 0;
3129
	int want_remap = 0;
3130

    
   
3130

   
3131
	ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
3131
	ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
3132
	/* now ask the system what would it use to talk to 'them' */
3132
	/* now ask the system what would it use to talk to 'them' */
3133
	ast_ouraddrfor(them, us);
3133
	ast_ouraddrfor(them, us);
3134
	ast_sockaddr_copy(&theirs, them);
3134
	ast_sockaddr_copy(&theirs, them);
3135

    
   
3135

   
3136
	if (ast_sockaddr_is_ipv6(&theirs)) {
3136
	if (ast_sockaddr_is_ipv6(&theirs)) {
3137
		if (localaddr && !ast_sockaddr_isnull(&externaddr)) {
3137
		if (localaddr && !ast_sockaddr_isnull(&externaddr)) {
3138
			ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
3138
			ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
3139
				"but we're using IPv6, which doesn't need it. Please "
3139
				"but we're using IPv6, which doesn't need it. Please "
3140
				"remove \"localnet\" and/or \"externaddr\" settings.\n");
3140
				"remove \"localnet\" and/or \"externaddr\" settings.\n");
3141
		}
3141
		}
3142
	} else {
3142
	} else {
3143
		want_remap = localaddr &&
3143
		want_remap = localaddr &&
3144
			!(ast_sockaddr_isnull(&externaddr) && stunaddr.sin_addr.s_addr) &&
3144
			!(ast_sockaddr_isnull(&externaddr) && stunaddr.sin_addr.s_addr) &&
3145
			ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
3145
			ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
3146
	}
3146
	}
3147

    
   
3147

   
3148
	if (want_remap &&
3148
	if (want_remap &&
3149
	    (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
3149
	    (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
3150
		/* if we used externhost or stun, see if it is time to refresh the info */
3150
		/* if we used externhost or stun, see if it is time to refresh the info */
3151
		if (externexpire && time(NULL) >= externexpire) {
3151
		if (externexpire && time(NULL) >= externexpire) {
3152
			if (stunaddr.sin_addr.s_addr) {
3152
			if (stunaddr.sin_addr.s_addr) {
3153
				ast_sockaddr_to_sin(&externaddr, &externaddr_sin);
3153
				ast_sockaddr_to_sin(&externaddr, &externaddr_sin);
3154
				ast_stun_request(sipsock, &stunaddr, NULL, &externaddr_sin);
3154
				ast_stun_request(sipsock, &stunaddr, NULL, &externaddr_sin);
3155
			} else {
3155
			} else {
3156
				if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
3156
				if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
3157
					ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
3157
					ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
3158
				}
3158
				}
3159
				externexpire = time(NULL);
3159
				externexpire = time(NULL);
3160
			}
3160
			}
3161
			externexpire = time(NULL) + externrefresh;
3161
			externexpire = time(NULL) + externrefresh;
3162
		}
3162
		}
3163
		if (!ast_sockaddr_isnull(&externaddr)) {
3163
		if (!ast_sockaddr_isnull(&externaddr)) {
3164
			ast_sockaddr_copy(us, &externaddr);
3164
			ast_sockaddr_copy(us, &externaddr);
3165
			switch (p->socket.type) {
3165
			switch (p->socket.type) {
3166
			case SIP_TRANSPORT_TCP:
3166
			case SIP_TRANSPORT_TCP:
3167
				if (!externtcpport && ast_sockaddr_port(&externaddr)) {
3167
				if (!externtcpport && ast_sockaddr_port(&externaddr)) {
3168
					/* for consistency, default to the externaddr port */
3168
					/* for consistency, default to the externaddr port */
3169
					externtcpport = ast_sockaddr_port(&externaddr);
3169
					externtcpport = ast_sockaddr_port(&externaddr);
3170
				}
3170
				}
3171
				ast_sockaddr_set_port(us, externtcpport);
3171
				ast_sockaddr_set_port(us, externtcpport);
3172
				break;
3172
				break;
3173
			case SIP_TRANSPORT_TLS:
3173
			case SIP_TRANSPORT_TLS:
3174
				ast_sockaddr_set_port(us, externtlsport);
3174
				ast_sockaddr_set_port(us, externtlsport);
3175
				break;
3175
				break;
3176
			case SIP_TRANSPORT_UDP:
3176
			case SIP_TRANSPORT_UDP:
3177
				if (!ast_sockaddr_port(&externaddr)) {
3177
				if (!ast_sockaddr_port(&externaddr)) {
3178
					ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3178
					ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3179
				}
3179
				}
3180
				break;
3180
				break;
3181
			default:
3181
			default:
3182
				break;
3182
				break;
3183
			}
3183
			}
3184
		}
3184
		}
3185
		else {
3185
		else {
3186
			ast_log(LOG_WARNING, "stun failed\n");
3186
			ast_log(LOG_WARNING, "stun failed\n");
3187
		}
3187
		}
3188
		ast_debug(1, "Target address %s is not local, substituting externaddr\n",
3188
		ast_debug(1, "Target address %s is not local, substituting externaddr\n",
3189
			  ast_sockaddr_stringify(them));
3189
			  ast_sockaddr_stringify(them));
3190
	} else if (p) {
3190
	} else if (p) {
3191
		/* no remapping, but we bind to a specific address, so use it. */
3191
		/* no remapping, but we bind to a specific address, so use it. */
3192
		switch (p->socket.type) {
3192
		switch (p->socket.type) {
3193
		case SIP_TRANSPORT_TCP:
3193
		case SIP_TRANSPORT_TCP:
3194
			if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
3194
			if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
3195
				ast_sockaddr_copy(us,
3195
				ast_sockaddr_copy(us,
3196
						  &sip_tcp_desc.local_address);
3196
						  &sip_tcp_desc.local_address);
3197
			} else {
3197
			} else {
3198
				ast_sockaddr_set_port(us,
3198
				ast_sockaddr_set_port(us,
3199
						      ast_sockaddr_port(&sip_tcp_desc.local_address));
3199
						      ast_sockaddr_port(&sip_tcp_desc.local_address));
3200
			}
3200
			}
3201
			break;
3201
			break;
3202
		case SIP_TRANSPORT_TLS:
3202
		case SIP_TRANSPORT_TLS:
3203
			if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
3203
			if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
3204
				ast_sockaddr_copy(us,
3204
				ast_sockaddr_copy(us,
3205
						  &sip_tls_desc.local_address);
3205
						  &sip_tls_desc.local_address);
3206
			} else {
3206
			} else {
3207
				ast_sockaddr_set_port(us,
3207
				ast_sockaddr_set_port(us,
3208
						      ast_sockaddr_port(&sip_tls_desc.local_address));
3208
						      ast_sockaddr_port(&sip_tls_desc.local_address));
3209
			}
3209
			}
3210
			break;
3210
			break;
3211
		case SIP_TRANSPORT_UDP:
3211
		case SIP_TRANSPORT_UDP:
3212
			/* fall through on purpose */
3212
			/* fall through on purpose */
3213
		default:
3213
		default:
3214
			if (!ast_sockaddr_is_any(&bindaddr)) {
3214
			if (!ast_sockaddr_is_any(&bindaddr)) {
3215
				ast_sockaddr_copy(us, &bindaddr);
3215
				ast_sockaddr_copy(us, &bindaddr);
3216
			}
3216
			}
3217
			if (!ast_sockaddr_port(us)) {
3217
			if (!ast_sockaddr_port(us)) {
3218
				ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3218
				ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3219
			}
3219
			}
3220
		}
3220
		}
3221
	} else if (!ast_sockaddr_is_any(&bindaddr)) {
3221
	} else if (!ast_sockaddr_is_any(&bindaddr)) {
3222
		ast_sockaddr_copy(us, &bindaddr);
3222
		ast_sockaddr_copy(us, &bindaddr);
3223
	}
3223
	}
3224
	ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", get_transport(p->socket.type), ast_sockaddr_stringify(us));
3224
	ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", get_transport(p->socket.type), ast_sockaddr_stringify(us));
3225
}
3225
}
3226

    
   
3226

   
3227
/*! \brief Append to SIP dialog history with arg list  */
3227
/*! \brief Append to SIP dialog history with arg list  */
3228
static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
3228
static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
3229
{
3229
{
3230
	char buf[80], *c = buf; /* max history length */
3230
	char buf[80], *c = buf; /* max history length */
3231
	struct sip_history *hist;
3231
	struct sip_history *hist;
3232
	int l;
3232
	int l;
3233

    
   
3233

   
3234
	vsnprintf(buf, sizeof(buf), fmt, ap);
3234
	vsnprintf(buf, sizeof(buf), fmt, ap);
3235
	strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
3235
	strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
3236
	l = strlen(buf) + 1;
3236
	l = strlen(buf) + 1;
3237
	if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
3237
	if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
3238
		return;
3238
		return;
3239
	}
3239
	}
3240
	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
3240
	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
3241
		ast_free(hist);
3241
		ast_free(hist);
3242
		return;
3242
		return;
3243
	}
3243
	}
3244
	memcpy(hist->event, buf, l);
3244
	memcpy(hist->event, buf, l);
3245
	if (p->history_entries == MAX_HISTORY_ENTRIES) {
3245
	if (p->history_entries == MAX_HISTORY_ENTRIES) {
3246
		struct sip_history *oldest;
3246
		struct sip_history *oldest;
3247
		oldest = AST_LIST_REMOVE_HEAD(p->history, list);
3247
		oldest = AST_LIST_REMOVE_HEAD(p->history, list);
3248
		p->history_entries--;
3248
		p->history_entries--;
3249
		ast_free(oldest);
3249
		ast_free(oldest);
3250
	}
3250
	}
3251
	AST_LIST_INSERT_TAIL(p->history, hist, list);
3251
	AST_LIST_INSERT_TAIL(p->history, hist, list);
3252
	p->history_entries++;
3252
	p->history_entries++;
3253
}
3253
}
3254

    
   
3254

   
3255
/*! \brief Append to SIP dialog history with arg list  */
3255
/*! \brief Append to SIP dialog history with arg list  */
3256
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3256
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3257
{
3257
{
3258
	va_list ap;
3258
	va_list ap;
3259

    
   
3259

   
3260
	if (!p) {
3260
	if (!p) {
3261
		return;
3261
		return;
3262
	}
3262
	}
3263

    
   
3263

   
3264
	if (!p->do_history && !recordhistory && !dumphistory) {
3264
	if (!p->do_history && !recordhistory && !dumphistory) {
3265
		return;
3265
		return;
3266
	}
3266
	}
3267

    
   
3267

   
3268
	va_start(ap, fmt);
3268
	va_start(ap, fmt);
3269
	append_history_va(p, fmt, ap);
3269
	append_history_va(p, fmt, ap);
3270
	va_end(ap);
3270
	va_end(ap);
3271

    
   
3271

   
3272
	return;
3272
	return;
3273
}
3273
}
3274

    
   
3274

   
3275
/*! \brief Retransmit SIP message if no answer (Called from scheduler) */
3275
/*! \brief Retransmit SIP message if no answer (Called from scheduler) */
3276
static int retrans_pkt(const void *data)
3276
static int retrans_pkt(const void *data)
3277
{
3277
{
3278
	struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
3278
	struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
3279
	int reschedule = DEFAULT_RETRANS;
3279
	int reschedule = DEFAULT_RETRANS;
3280
	int xmitres = 0;
3280
	int xmitres = 0;
3281
	/* how many ms until retrans timeout is reached */
3281
	/* how many ms until retrans timeout is reached */
3282
	int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
3282
	int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
3283

    
   
3283

   
3284
	/* Do not retransmit if time out is reached. This will be negative if the time between
3284
	/* Do not retransmit if time out is reached. This will be negative if the time between
3285
	 * the first transmission and now is larger than our timeout period. This is a fail safe
3285
	 * the first transmission and now is larger than our timeout period. This is a fail safe
3286
	 * check in case the scheduler gets behind or the clock is changed. */
3286
	 * check in case the scheduler gets behind or the clock is changed. */
3287
	if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
3287
	if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
3288
		pkt->retrans_stop = 1;
3288
		pkt->retrans_stop = 1;
3289
	}
3289
	}
3290

    
   
3290

   
3291
	/* Lock channel PVT */
3291
	/* Lock channel PVT */
3292
	sip_pvt_lock(pkt->owner);
3292
	sip_pvt_lock(pkt->owner);
3293

    
   
3293

   
3294
	if (!pkt->retrans_stop) {
3294
	if (!pkt->retrans_stop) {
3295
		pkt->retrans++;
3295
		pkt->retrans++;
3296
		if (!pkt->timer_t1) {	/* Re-schedule using timer_a and timer_t1 */
3296
		if (!pkt->timer_t1) {	/* Re-schedule using timer_a and timer_t1 */
3297
			if (sipdebug) {
3297
			if (sipdebug) {
3298
				ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
3298
				ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
3299
					pkt->retransid,
3299
					pkt->retransid,
3300
					sip_methods[pkt->method].text,
3300
					sip_methods[pkt->method].text,
3301
					pkt->method);
3301
					pkt->method);
3302
			}
3302
			}
3303
		} else {
3303
		} else {
3304
			int siptimer_a;
3304
			int siptimer_a;
3305

    
   
3305

   
3306
			if (sipdebug) {
3306
			if (sipdebug) {
3307
				ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
3307
				ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
3308
					pkt->retransid,
3308
					pkt->retransid,
3309
					pkt->retrans,
3309
					pkt->retrans,
3310
					sip_methods[pkt->method].text,
3310
					sip_methods[pkt->method].text,
3311
					pkt->method);
3311
					pkt->method);
3312
			}
3312
			}
3313
			if (!pkt->timer_a) {
3313
			if (!pkt->timer_a) {
3314
				pkt->timer_a = 2 ;
3314
				pkt->timer_a = 2 ;
3315
			} else {
3315
			} else {
3316
				pkt->timer_a = 2 * pkt->timer_a;
3316
				pkt->timer_a = 2 * pkt->timer_a;
3317
			}
3317
			}
3318

    
   
3318

   
3319
			/* For non-invites, a maximum of 4 secs */
3319
			/* For non-invites, a maximum of 4 secs */
3320
			siptimer_a = pkt->timer_t1 * pkt->timer_a;	/* Double each time */
3320
			siptimer_a = pkt->timer_t1 * pkt->timer_a;	/* Double each time */
3321
			if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
3321
			if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
3322
				siptimer_a = 4000;
3322
				siptimer_a = 4000;
3323
			}
3323
			}
3324

    
   
3324

   
3325
			/* Reschedule re-transmit */
3325
			/* Reschedule re-transmit */
3326
			reschedule = siptimer_a;
3326
			reschedule = siptimer_a;
3327
			ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
3327
			ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
3328
				pkt->retrans + 1,
3328
				pkt->retrans + 1,
3329
				siptimer_a,
3329
				siptimer_a,
3330
				pkt->timer_t1,
3330
				pkt->timer_t1,
3331
				pkt->retransid);
3331
				pkt->retransid);
3332
		}
3332
		}
3333

    
   
3333

   
3334
		if (sip_debug_test_pvt(pkt->owner)) {
3334
		if (sip_debug_test_pvt(pkt->owner)) {
3335
			const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
3335
			const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
3336
			ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
3336
			ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
3337
				pkt->retrans, sip_nat_mode(pkt->owner),
3337
				pkt->retrans, sip_nat_mode(pkt->owner),
3338
				ast_sockaddr_stringify(dst),
3338
				ast_sockaddr_stringify(dst),
3339
				pkt->data->str);
3339
				pkt->data->str);
3340
		}
3340
		}
3341

    
   
3341

   
3342
		append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
3342
		append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
3343
		xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
3343
		xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
3344
		sip_pvt_unlock(pkt->owner);
3344
		sip_pvt_unlock(pkt->owner);
3345

    
   
3345

   
3346
		/* If there was no error during the network transmission, schedule the next retransmission,
3346
		/* If there was no error during the network transmission, schedule the next retransmission,
3347
		 * but if the next retransmission is going to be beyond our timeout period, mark the packet's
3347
		 * but if the next retransmission is going to be beyond our timeout period, mark the packet's
3348
		 * stop_retrans value and set the next retransmit to be the exact time of timeout.  This will
3348
		 * stop_retrans value and set the next retransmit to be the exact time of timeout.  This will
3349
		 * allow any responses to the packet to be processed before the packet is destroyed on the next
3349
		 * allow any responses to the packet to be processed before the packet is destroyed on the next
3350
		 * call to this function by the scheduler. */
3350
		 * call to this function by the scheduler. */
3351
		if (xmitres != XMIT_ERROR) {
3351
		if (xmitres != XMIT_ERROR) {
3352
			if (reschedule >= diff) {
3352
			if (reschedule >= diff) {
3353
				pkt->retrans_stop = 1;
3353
				pkt->retrans_stop = 1;
3354
				reschedule = diff;
3354
				reschedule = diff;
3355
			}
3355
			}
3356
			return  reschedule;
3356
			return  reschedule;
3357
		}
3357
		}
3358
	}
3358
	}
3359

    
   
3359

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

    
   
3362

   
3363
	pkt->retransid = -1; /* Kill this scheduler item */
3363
	pkt->retransid = -1; /* Kill this scheduler item */
3364

    
   
3364

   
3365
	if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
3365
	if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
3366
		if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
3366
		if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
3367
			ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n"
3367
			ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n"
3368
				"Packet timed out after %dms with no response\n",
3368
				"Packet timed out after %dms with no response\n",
3369
				pkt->owner->callid,
3369
				pkt->owner->callid,
3370
				pkt->seqno,
3370
				pkt->seqno,
3371
				pkt->is_fatal ? "Critical" : "Non-critical",
3371
				pkt->is_fatal ? "Critical" : "Non-critical",
3372
				pkt->is_resp ? "Response" : "Request",
3372
				pkt->is_resp ? "Response" : "Request",
3373
				(int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
3373
				(int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
3374
		}
3374
		}
3375
	} else if (pkt->method == SIP_OPTIONS && sipdebug) {
3375
	} else if (pkt->method == SIP_OPTIONS && sipdebug) {
3376
		ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
3376
		ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
3377
	}
3377
	}
3378

    
   
3378

   
3379
	if (xmitres == XMIT_ERROR) {
3379
	if (xmitres == XMIT_ERROR) {
3380
		ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
3380
		ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
3381
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3381
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3382
	} else {
3382
	} else {
3383
		append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3383
		append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3384
	}
3384
	}
3385

    
   
3385

   
3386
	if (pkt->is_fatal) {
3386
	if (pkt->is_fatal) {
3387
		while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
3387
		while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
3388
			sip_pvt_unlock(pkt->owner);	/* SIP_PVT, not channel */
3388
			sip_pvt_unlock(pkt->owner);	/* SIP_PVT, not channel */
3389
			usleep(1);
3389
			usleep(1);
3390
			sip_pvt_lock(pkt->owner);
3390
			sip_pvt_lock(pkt->owner);
3391
		}
3391
		}
3392
		if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
3392
		if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
3393
			pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
3393
			pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
3394
		}
3394
		}
3395
		if (pkt->owner->owner) {
3395
		if (pkt->owner->owner) {
3396
			ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
3396
			ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
3397

    
   
3397

   
3398
			if (pkt->is_resp &&
3398
			if (pkt->is_resp &&
3399
				(pkt->response_code >= 200) &&
3399
				(pkt->response_code >= 200) &&
3400
				(pkt->response_code < 300) &&
3400
				(pkt->response_code < 300) &&
3401
				pkt->owner->pendinginvite &&
3401
				pkt->owner->pendinginvite &&
3402
				ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
3402
				ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
3403
				/* This is a timeout of the 2XX response to a pending INVITE.  In this case terminate the INVITE
3403
				/* This is a timeout of the 2XX response to a pending INVITE.  In this case terminate the INVITE
3404
				 * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup
3404
				 * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup
3405
				 * will send the BYE as long as the dialog is not set as "alreadygone")
3405
				 * will send the BYE as long as the dialog is not set as "alreadygone")
3406
				 * RFC 3261 section 13.3.1.4.
3406
				 * RFC 3261 section 13.3.1.4.
3407
				 * "If the server retransmits the 2xx response for 64*T1 seconds without receiving
3407
				 * "If the server retransmits the 2xx response for 64*T1 seconds without receiving
3408
				 * an ACK, the dialog is confirmed, but the session SHOULD be terminated.  This is
3408
				 * an ACK, the dialog is confirmed, but the session SHOULD be terminated.  This is
3409
				 * accomplished with a BYE, as described in Section 15." */
3409
				 * accomplished with a BYE, as described in Section 15." */
3410
				pkt->owner->invitestate = INV_TERMINATED;
3410
				pkt->owner->invitestate = INV_TERMINATED;
3411
				pkt->owner->pendinginvite = 0;
3411
				pkt->owner->pendinginvite = 0;
3412
			} else {
3412
			} else {
3413
				/* there is nothing left to do, mark the dialog as gone */
3413
				/* there is nothing left to do, mark the dialog as gone */
3414
				sip_alreadygone(pkt->owner);
3414
				sip_alreadygone(pkt->owner);
3415
			}
3415
			}
3416
			ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
3416
			ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
3417
			ast_channel_unlock(pkt->owner->owner);
3417
			ast_channel_unlock(pkt->owner->owner);
3418
		} else {
3418
		} else {
3419
			/* If no channel owner, destroy now */
3419
			/* If no channel owner, destroy now */
3420

    
   
3420

   
3421
			/* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
3421
			/* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
3422
			if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
3422
			if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
3423
				pvt_set_needdestroy(pkt->owner, "no response to critical packet");
3423
				pvt_set_needdestroy(pkt->owner, "no response to critical packet");
3424
				sip_alreadygone(pkt->owner);
3424
				sip_alreadygone(pkt->owner);
3425
				append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
3425
				append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
3426
			}
3426
			}
3427
		}
3427
		}
3428
	}
3428
	}
3429

    
   
3429

   
3430
	if (pkt->method == SIP_BYE) {
3430
	if (pkt->method == SIP_BYE) {
3431
		/* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
3431
		/* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
3432
		if (pkt->owner->owner) {
3432
		if (pkt->owner->owner) {
3433
			ast_channel_unlock(pkt->owner->owner);
3433
			ast_channel_unlock(pkt->owner->owner);
3434
		}
3434
		}
3435
		append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
3435
		append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
3436
		pvt_set_needdestroy(pkt->owner, "no response to BYE");
3436
		pvt_set_needdestroy(pkt->owner, "no response to BYE");
3437
	}
3437
	}
3438

    
   
3438

   
3439
	/* Remove the packet */
3439
	/* Remove the packet */
3440
	for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
3440
	for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
3441
		if (cur == pkt) {
3441
		if (cur == pkt) {
3442
			UNLINK(cur, pkt->owner->packets, prev);
3442
			UNLINK(cur, pkt->owner->packets, prev);
3443
			sip_pvt_unlock(pkt->owner);
3443
			sip_pvt_unlock(pkt->owner);
3444
			if (pkt->owner) {
3444
			if (pkt->owner) {
3445
				pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3445
				pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3446
			}
3446
			}
3447
			if (pkt->data) {
3447
			if (pkt->data) {
3448
				ast_free(pkt->data);
3448
				ast_free(pkt->data);
3449
			}
3449
			}
3450
			pkt->data = NULL;
3450
			pkt->data = NULL;
3451
			ast_free(pkt);
3451
			ast_free(pkt);
3452
			return 0;
3452
			return 0;
3453
		}
3453
		}
3454
	}
3454
	}
3455
	/* error case */
3455
	/* error case */
3456
	ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
3456
	ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
3457
	sip_pvt_unlock(pkt->owner);
3457
	sip_pvt_unlock(pkt->owner);
3458
	return 0;
3458
	return 0;
3459
}
3459
}
3460

    
   
3460

   
3461
/*! \brief Transmit packet with retransmits
3461
/*! \brief Transmit packet with retransmits
3462
	\return 0 on success, -1 on failure to allocate packet
3462
	\return 0 on success, -1 on failure to allocate packet
3463
*/
3463
*/
3464
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)
3464
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)
3465
{
3465
{
3466
	struct sip_pkt *pkt = NULL;
3466
	struct sip_pkt *pkt = NULL;
3467
	int siptimer_a = DEFAULT_RETRANS;
3467
	int siptimer_a = DEFAULT_RETRANS;
3468
	int xmitres = 0;
3468
	int xmitres = 0;
3469
	int respid;
3469
	int respid;
3470

    
   
3470

   
3471
	if (sipmethod == SIP_INVITE) {
3471
	if (sipmethod == SIP_INVITE) {
3472
		/* Note this is a pending invite */
3472
		/* Note this is a pending invite */
3473
		p->pendinginvite = seqno;
3473
		p->pendinginvite = seqno;
3474
	}
3474
	}
3475

    
   
3475

   
3476
	/* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
3476
	/* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
3477
	/* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
3477
	/* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
3478
	/*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
3478
	/*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
3479
	if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
3479
	if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
3480
		xmitres = __sip_xmit(p, data, len);	/* Send packet */
3480
		xmitres = __sip_xmit(p, data, len);	/* Send packet */
3481
		if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
3481
		if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
3482
			append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
3482
			append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
3483
			return AST_FAILURE;
3483
			return AST_FAILURE;
3484
		} else {
3484
		} else {
3485
			return AST_SUCCESS;
3485
			return AST_SUCCESS;
3486
		}
3486
		}
3487
	}
3487
	}
3488

    
   
3488

   
3489
	if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1))) {
3489
	if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1))) {
3490
		return AST_FAILURE;
3490
		return AST_FAILURE;
3491
	}
3491
	}
3492
	/* copy data, add a terminator and save length */
3492
	/* copy data, add a terminator and save length */
3493
	if (!(pkt->data = ast_str_create(len))) {
3493
	if (!(pkt->data = ast_str_create(len))) {
3494
		ast_free(pkt);
3494
		ast_free(pkt);
3495
		return AST_FAILURE;
3495
		return AST_FAILURE;
3496
	}
3496
	}
3497
	ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
3497
	ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
3498
	pkt->packetlen = len;
3498
	pkt->packetlen = len;
3499
	/* copy other parameters from the caller */
3499
	/* copy other parameters from the caller */
3500
	pkt->method = sipmethod;
3500
	pkt->method = sipmethod;
3501
	pkt->seqno = seqno;
3501
	pkt->seqno = seqno;
3502
	pkt->is_resp = resp;
3502
	pkt->is_resp = resp;
3503
	pkt->is_fatal = fatal;
3503
	pkt->is_fatal = fatal;
3504
	pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
3504
	pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
3505
	pkt->next = p->packets;
3505
	pkt->next = p->packets;
3506
	p->packets = pkt;	/* Add it to the queue */
3506
	p->packets = pkt;	/* Add it to the queue */
3507
	if (resp) {
3507
	if (resp) {
3508
		/* Parse out the response code */
3508
		/* Parse out the response code */
3509
		if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
3509
		if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
3510
			pkt->response_code = respid;
3510
			pkt->response_code = respid;
3511
		}
3511
		}
3512
	}
3512
	}
3513
	pkt->timer_t1 = p->timer_t1;	/* Set SIP timer T1 */
3513
	pkt->timer_t1 = p->timer_t1;	/* Set SIP timer T1 */
3514
	pkt->retransid = -1;
3514
	pkt->retransid = -1;
3515
	if (pkt->timer_t1) {
3515
	if (pkt->timer_t1) {
3516
		siptimer_a = pkt->timer_t1;
3516
		siptimer_a = pkt->timer_t1;
3517
	}
3517
	}
3518

    
   
3518

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

    
   
3521

   
3522
	/* Schedule retransmission */
3522
	/* Schedule retransmission */
3523
	AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
3523
	AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
3524
	if (sipdebug) {
3524
	if (sipdebug) {
3525
		ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
3525
		ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
3526
	}
3526
	}
3527

    
   
3527

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

    
   
3529

   
3530
	if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
3530
	if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
3531
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3531
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3532
		ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
3532
		ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
3533
		AST_SCHED_DEL(sched, pkt->retransid);
3533
		AST_SCHED_DEL(sched, pkt->retransid);
3534
		p->packets = pkt->next;
3534
		p->packets = pkt->next;
3535
		pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3535
		pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3536
		ast_free(pkt->data);
3536
		ast_free(pkt->data);
3537
		ast_free(pkt);
3537
		ast_free(pkt);
3538
		return AST_FAILURE;
3538
		return AST_FAILURE;
3539
	} else {
3539
	} else {
3540
		/* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
3540
		/* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
3541
		 * only wakes up every 1000ms by default, we have to poke the thread here to make
3541
		 * only wakes up every 1000ms by default, we have to poke the thread here to make
3542
		 * sure it successfully detects this must be retransmitted in less time than
3542
		 * sure it successfully detects this must be retransmitted in less time than
3543
		 * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
3543
		 * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
3544
		if (monitor_thread != AST_PTHREADT_NULL) {
3544
		if (monitor_thread != AST_PTHREADT_NULL) {
3545
			pthread_kill(monitor_thread, SIGURG);
3545
			pthread_kill(monitor_thread, SIGURG);
3546
		}
3546
		}
3547
		return AST_SUCCESS;
3547
		return AST_SUCCESS;
3548
	}
3548
	}
3549
}
3549
}
3550

    
   
3550

   
3551
/*! \brief Kill a SIP dialog (called only by the scheduler)
3551
/*! \brief Kill a SIP dialog (called only by the scheduler)
3552
 * The scheduler has a reference to this dialog when p->autokillid != -1,
3552
 * The scheduler has a reference to this dialog when p->autokillid != -1,
3553
 * and we are called using that reference. So if the event is not
3553
 * and we are called using that reference. So if the event is not
3554
 * rescheduled, we need to call dialog_unref().
3554
 * rescheduled, we need to call dialog_unref().
3555
 */
3555
 */
3556
static int __sip_autodestruct(const void *data)
3556
static int __sip_autodestruct(const void *data)
3557
{
3557
{
3558
	struct sip_pvt *p = (struct sip_pvt *)data;
3558
	struct sip_pvt *p = (struct sip_pvt *)data;
3559

    
   
3559

   
3560
	/* If this is a subscription, tell the phone that we got a timeout */
3560
	/* If this is a subscription, tell the phone that we got a timeout */
3561
	if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
3561
	if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
3562
		transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);	/* Send last notification */
3562
		transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);	/* Send last notification */
3563
		p->subscribed = NONE;
3563
		p->subscribed = NONE;
3564
		append_history(p, "Subscribestatus", "timeout");
3564
		append_history(p, "Subscribestatus", "timeout");
3565
		ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
3565
		ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
3566
		return 10000;	/* Reschedule this destruction so that we know that it's gone */
3566
		return 10000;	/* Reschedule this destruction so that we know that it's gone */
3567
	}
3567
	}
3568

    
   
3568

   
3569
	/* If there are packets still waiting for delivery, delay the destruction */
3569
	/* If there are packets still waiting for delivery, delay the destruction */
3570
	if (p->packets) {
3570
	if (p->packets) {
3571
		if (!p->needdestroy) {
3571
		if (!p->needdestroy) {
3572
			char method_str[31];
3572
			char method_str[31];
3573
			ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
3573
			ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
3574
			append_history(p, "ReliableXmit", "timeout");
3574
			append_history(p, "ReliableXmit", "timeout");
3575
			if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
3575
			if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
3576
				if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
3576
				if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
3577
					pvt_set_needdestroy(p, "autodestruct");
3577
					pvt_set_needdestroy(p, "autodestruct");
3578
				}
3578
				}
3579
			}
3579
			}
3580
			return 10000;
3580
			return 10000;
3581
		} else {
3581
		} else {
3582
			/* They've had their chance to respond. Time to bail */
3582
			/* They've had their chance to respond. Time to bail */
3583
			__sip_pretend_ack(p);
3583
			__sip_pretend_ack(p);
3584
		}
3584
		}
3585
	}
3585
	}
3586

    
   
3586

   
3587
	if (p->relatedpeer) {
3587
	if (p->relatedpeer) {
3588
		p->relatedpeer = unref_peer(p->relatedpeer, "__sip_autodestruct: unref peer p->relatedpeer");	/* Remove link to peer. If it's realtime, make sure it's gone from memory) */
3588
		p->relatedpeer = unref_peer(p->relatedpeer, "__sip_autodestruct: unref peer p->relatedpeer");	/* Remove link to peer. If it's realtime, make sure it's gone from memory) */
3589
	}
3589
	}
3590

    
   
3590

   
3591
	/* Reset schedule ID */
3591
	/* Reset schedule ID */
3592
	p->autokillid = -1;
3592
	p->autokillid = -1;
3593

    
   
3593

   
3594
	if (p->owner) {
3594
	if (p->owner) {
3595
		ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
3595
		ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
3596
		ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
3596
		ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
3597
	} else if (p->refer && !p->alreadygone) {
3597
	} else if (p->refer && !p->alreadygone) {
3598
		ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
3598
		ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
3599
		transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3599
		transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3600
		append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
3600
		append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
3601
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3601
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3602
	} else {
3602
	} else {
3603
		append_history(p, "AutoDestroy", "%s", p->callid);
3603
		append_history(p, "AutoDestroy", "%s", p->callid);
3604
		ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
3604
		ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
3605
		dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
3605
		dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
3606
		/* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
3606
		/* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
3607
		/* sip_destroy(p); */		/* Go ahead and destroy dialog. All attempts to recover is done */
3607
		/* sip_destroy(p); */		/* Go ahead and destroy dialog. All attempts to recover is done */
3608
		/* sip_destroy also absorbs the reference */
3608
		/* sip_destroy also absorbs the reference */
3609
	}
3609
	}
3610
	dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
3610
	dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
3611
	return 0;
3611
	return 0;
3612
}
3612
}
3613

    
   
3613

   
3614
/*! \brief Schedule final destruction of SIP dialog.  This can not be canceled.
3614
/*! \brief Schedule final destruction of SIP dialog.  This can not be canceled.
3615
 *  This function is used to keep a dialog around for a period of time in order
3615
 *  This function is used to keep a dialog around for a period of time in order
3616
 *  to properly respond to any retransmits. */
3616
 *  to properly respond to any retransmits. */
3617
void sip_scheddestroy_final(struct sip_pvt *p, int ms)
3617
void sip_scheddestroy_final(struct sip_pvt *p, int ms)
3618
{
3618
{
3619
	if (p->final_destruction_scheduled) {
3619
	if (p->final_destruction_scheduled) {
3620
		return; /* already set final destruction */
3620
		return; /* already set final destruction */
3621
	}
3621
	}
3622

    
   
3622

   
3623
	sip_scheddestroy(p, ms);
3623
	sip_scheddestroy(p, ms);
3624
	if (p->autokillid != -1) {
3624
	if (p->autokillid != -1) {
3625
		p->final_destruction_scheduled = 1;
3625
		p->final_destruction_scheduled = 1;
3626
	}
3626
	}
3627
}
3627
}
3628

    
   
3628

   
3629
/*! \brief Schedule destruction of SIP dialog */
3629
/*! \brief Schedule destruction of SIP dialog */
3630
void sip_scheddestroy(struct sip_pvt *p, int ms)
3630
void sip_scheddestroy(struct sip_pvt *p, int ms)
3631
{
3631
{
3632
	if (p->final_destruction_scheduled) {
3632
	if (p->final_destruction_scheduled) {
3633
		return; /* already set final destruction */
3633
		return; /* already set final destruction */
3634
	}
3634
	}
3635

    
   
3635

   
3636
	if (ms < 0) {
3636
	if (ms < 0) {
3637
		if (p->timer_t1 == 0) {
3637
		if (p->timer_t1 == 0) {
3638
			p->timer_t1 = global_t1;	/* Set timer T1 if not set (RFC 3261) */
3638
			p->timer_t1 = global_t1;	/* Set timer T1 if not set (RFC 3261) */
3639
		}
3639
		}
3640
		if (p->timer_b == 0) {
3640
		if (p->timer_b == 0) {
3641
			p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
3641
			p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
3642
		}
3642
		}
3643
		ms = p->timer_t1 * 64;
3643
		ms = p->timer_t1 * 64;
3644
	}
3644
	}
3645
	if (sip_debug_test_pvt(p)) {
3645
	if (sip_debug_test_pvt(p)) {
3646
		ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
3646
		ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
3647
	}
3647
	}
3648
	if (sip_cancel_destroy(p)) {
3648
	if (sip_cancel_destroy(p)) {
3649
		ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
3649
		ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
3650
	}
3650
	}
3651

    
   
3651

   
3652
	if (p->do_history) {
3652
	if (p->do_history) {
3653
		append_history(p, "SchedDestroy", "%d ms", ms);
3653
		append_history(p, "SchedDestroy", "%d ms", ms);
3654
	}
3654
	}
3655
	p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
3655
	p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
3656

    
   
3656

   
3657
	if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
3657
	if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
3658
		stop_session_timer(p);
3658
		stop_session_timer(p);
3659
	}
3659
	}
3660
}
3660
}
3661

    
   
3661

   
3662
/*! \brief Cancel destruction of SIP dialog.
3662
/*! \brief Cancel destruction of SIP dialog.
3663
 * Be careful as this also absorbs the reference - if you call it
3663
 * Be careful as this also absorbs the reference - if you call it
3664
 * from within the scheduler, this might be the last reference.
3664
 * from within the scheduler, this might be the last reference.
3665
 */
3665
 */
3666
int sip_cancel_destroy(struct sip_pvt *p)
3666
int sip_cancel_destroy(struct sip_pvt *p)
3667
{
3667
{
3668
	int res = 0;
3668
	int res = 0;
3669

    
   
3669

   
3670
	if (p->final_destruction_scheduled) {
3670
	if (p->final_destruction_scheduled) {
3671
		return res;
3671
		return res;
3672
	}
3672
	}
3673

    
   
3673

   
3674
	if (p->autokillid > -1) {
3674
	if (p->autokillid > -1) {
3675
		int res3;
3675
		int res3;
3676

    
   
3676

   
3677
		if (!(res3 = ast_sched_del(sched, p->autokillid))) {
3677
		if (!(res3 = ast_sched_del(sched, p->autokillid))) {
3678
			append_history(p, "CancelDestroy", "");
3678
			append_history(p, "CancelDestroy", "");
3679
			p->autokillid = -1;
3679
			p->autokillid = -1;
3680
			dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
3680
			dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
3681
		}
3681
		}
3682
	}
3682
	}
3683
	return res;
3683
	return res;
3684
}
3684
}
3685

    
   
3685

   
3686
/*! \brief Acknowledges receipt of a packet and stops retransmission
3686
/*! \brief Acknowledges receipt of a packet and stops retransmission
3687
 * called with p locked*/
3687
 * called with p locked*/
3688
int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
3688
int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
3689
{
3689
{
3690
	struct sip_pkt *cur, *prev = NULL;
3690
	struct sip_pkt *cur, *prev = NULL;
3691
	const char *msg = "Not Found";	/* used only for debugging */
3691
	const char *msg = "Not Found";	/* used only for debugging */
3692
	int res = FALSE;
3692
	int res = FALSE;
3693

    
   
3693

   
3694
	/* If we have an outbound proxy for this dialog, then delete it now since
3694
	/* If we have an outbound proxy for this dialog, then delete it now since
3695
	  the rest of the requests in this dialog needs to follow the routing.
3695
	  the rest of the requests in this dialog needs to follow the routing.
3696
	  If obforcing is set, we will keep the outbound proxy during the whole
3696
	  If obforcing is set, we will keep the outbound proxy during the whole
3697
	  dialog, regardless of what the SIP rfc says
3697
	  dialog, regardless of what the SIP rfc says
3698
	*/
3698
	*/
3699
	if (p->outboundproxy && !p->outboundproxy->force){
3699
	if (p->outboundproxy && !p->outboundproxy->force){
3700
		ref_proxy(p, NULL);
3700
		ref_proxy(p, NULL);
3701
	}
3701
	}
3702

    
   
3702

   
3703
	for (cur = p->packets; cur; prev = cur, cur = cur->next) {
3703
	for (cur = p->packets; cur; prev = cur, cur = cur->next) {
3704
		if (cur->seqno != seqno || cur->is_resp != resp) {
3704
		if (cur->seqno != seqno || cur->is_resp != resp) {
3705
			continue;
3705
			continue;
3706
		}
3706
		}
3707
		if (cur->is_resp || cur->method == sipmethod) {
3707
		if (cur->is_resp || cur->method == sipmethod) {
3708
			res = TRUE;
3708
			res = TRUE;
3709
			msg = "Found";
3709
			msg = "Found";
3710
			if (!resp && (seqno == p->pendinginvite)) {
3710
			if (!resp && (seqno == p->pendinginvite)) {
3711
				ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
3711
				ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
3712
				p->pendinginvite = 0;
3712
				p->pendinginvite = 0;
3713
			}
3713
			}
3714
			if (cur->retransid > -1) {
3714
			if (cur->retransid > -1) {
3715
				if (sipdebug)
3715
				if (sipdebug)
3716
					ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
3716
					ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
3717
			}
3717
			}
3718
			/* This odd section is designed to thwart a
3718
			/* This odd section is designed to thwart a
3719
			 * race condition in the packet scheduler. There are
3719
			 * race condition in the packet scheduler. There are
3720
			 * two conditions under which deleting the packet from the
3720
			 * two conditions under which deleting the packet from the
3721
			 * scheduler can fail.
3721
			 * scheduler can fail.
3722
			 *
3722
			 *
3723
			 * 1. The packet has been removed from the scheduler because retransmission
3723
			 * 1. The packet has been removed from the scheduler because retransmission
3724
			 * is being attempted. The problem is that if the packet is currently attempting
3724
			 * is being attempted. The problem is that if the packet is currently attempting
3725
			 * retransmission and we are at this point in the code, then that MUST mean
3725
			 * retransmission and we are at this point in the code, then that MUST mean
3726
			 * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
3726
			 * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
3727
			 * lock temporarily to allow retransmission.
3727
			 * lock temporarily to allow retransmission.
3728
			 *
3728
			 *
3729
			 * 2. The packet has reached its maximum number of retransmissions and has
3729
			 * 2. The packet has reached its maximum number of retransmissions and has
3730
			 * been permanently removed from the packet scheduler. If this is the case, then
3730
			 * been permanently removed from the packet scheduler. If this is the case, then
3731
			 * the packet's retransid will be set to -1. The atomicity of the setting and checking
3731
			 * the packet's retransid will be set to -1. The atomicity of the setting and checking
3732
			 * of the retransid to -1 is ensured since in both cases p's lock is held.
3732
			 * of the retransid to -1 is ensured since in both cases p's lock is held.
3733
			 */
3733
			 */
3734
			while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
3734
			while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
3735
				sip_pvt_unlock(p);
3735
				sip_pvt_unlock(p);
3736
				usleep(1);
3736
				usleep(1);
3737
				sip_pvt_lock(p);
3737
				sip_pvt_lock(p);
3738
			}
3738
			}
3739
			UNLINK(cur, p->packets, prev);
3739
			UNLINK(cur, p->packets, prev);
3740
			dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
3740
			dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
3741
			if (cur->data) {
3741
			if (cur->data) {
3742
				ast_free(cur->data);
3742
				ast_free(cur->data);
3743
			}
3743
			}
3744
			ast_free(cur);
3744
			ast_free(cur);
3745
			break;
3745
			break;
3746
		}
3746
		}
3747
	}
3747
	}
3748
	ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
3748
	ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
3749
		p->callid, resp ? "Response" : "Request", seqno, msg);
3749
		p->callid, resp ? "Response" : "Request", seqno, msg);