Review Board 1.7.16


Support text messages outside of a call

Review Request #1042 - Created Dec. 1, 2010 and submitted

Russell Bryant
trunk
Reviewers
asterisk-dev
Asterisk
This branch contains a proposal for adding protocol independent support for processing text messages into and out of the dialplan, outside of a call.  The file doc/asterisk-messaging.txt contains more details on the proposal.  The introduction of the document is quoted here:

"    Asterisk has some limited support today for messaging.  The support that
exists primarily includes passing text messages in the context of a call.  The
SIP and IAX2 protocols have support for this, but that's it.

    There are a couple of other messaging protocols that are supported: Skype
and XMPP (Jabber).  The support of these is very minimal and not very integrated
into the architecture of Asterisk since these messages are not in the context of
a phone call.  They provide a combination of dialplan and manager interface
interfaces that are specific to each protocol.  There just is no current
architectural concept of dealing with text messages.

    The purpose of this proposal is to introduce text messaging into the
architecture of Asterisk.  For messaging support to exist in the true spirit of
Asterisk architecture, the design needs to achieve the following two goals:

    a) Protocol Independence
    b) Scriptable message routing

    The rest of this document goes through some details about how these goals
will be achieved in a way that is both architecturally compatible with Asterisk
as well as practical to implement."

----------

In addition to the documented proposal, I have made some good progress on implementation.  While the document includes some ideas for future enhancements, what is there so far should be usable.

 - core modifications to allow sending incoming messages through the dialplan
 - core modifications to allow outbound messages from the dialplan
 - modifications to res_jabber to allow inbound and outbound messages in the new architecture
 - changes to chan_sip to support inbound and outbound MESSAGE outside of a call
svn/testsuite/asterisk/team/russell/messaging:
  - This branch of the testsuite contains my tests for this branch, which include:
    - tests/sip/message_disabled
      - Ensure MESSAGE outside of a call is rejected when disabled.
    - tests/sip/message_unauth
      - When enabled, test sending a MESSAGE to Asterisk and send another back out from the dialplan.
    - tests/sip/message_auth
      - Same as the last test, but authenticate MESSAGE both inbound and outbound.
    - tests/sip/message_from_call
      - Set up a normal SIP call and send an out of call MESSAGE from the dialplan processing the call

I have also written some simple apps using the pjsua Python module from pjsip that can send and receive messages sent through Asterisk.

Lastly, I have done some manual testing of XMPP messages in and out of Asterisk using this code.
/trunk/channels/chan_sip.c
Revision 299249 New Change
1
/*
1
/*
2
 * Asterisk -- An open source telephony toolkit.
2
 * Asterisk -- An open source telephony toolkit.
3
 *
3
 *
4
 * Copyright (C) 1999 - 2006, Digium, Inc.
4
 * Copyright (C) 1999 - 2006, Digium, Inc.
5
 *
5
 *
6
 * Mark Spencer <markster@digium.com>
6
 * Mark Spencer <markster@digium.com>
7
 *
7
 *
8
 * See http://www.asterisk.org for more information about
8
 * See http://www.asterisk.org for more information about
9
 * the Asterisk project. Please do not directly contact
9
 * the Asterisk project. Please do not directly contact
10
 * any of the maintainers of this project for assistance;
10
 * any of the maintainers of this project for assistance;
11
 * the project provides a web site, mailing lists and IRC
11
 * the project provides a web site, mailing lists and IRC
12
 * channels for your use.
12
 * channels for your use.
13
 *
13
 *
14
 * This program is free software, distributed under the terms of
14
 * This program is free software, distributed under the terms of
15
 * the GNU General Public License Version 2. See the LICENSE file
15
 * the GNU General Public License Version 2. See the LICENSE file
16
 * at the top of the source tree.
16
 * at the top of the source tree.
17
 */
17
 */
18

    
   
18

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

    
   
94

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

    
   
163

   
164
/*** MODULEINFO
164
/*** MODULEINFO
165
	<use>res_crypto</use>
165
	<use>res_crypto</use>
166
	<depend>chan_local</depend>
166
	<depend>chan_local</depend>
167
 ***/
167
 ***/
168

    
   
168

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

    
   
170

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

    
   
177

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

    
   
185

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

    
   
188

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

    
   
206

   
207
*/
207
*/
208

    
   
208

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

    
   
210

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

    
   
212

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

    
   
217

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

    
   
266
#include "asterisk/message.h"
266
#include "sip/include/sip.h"
267
#include "sip/include/sip.h"
267
#include "sip/include/globals.h"
268
#include "sip/include/globals.h"
268
#include "sip/include/config_parser.h"
269
#include "sip/include/config_parser.h"
269
#include "sip/include/reqresp_parser.h"
270
#include "sip/include/reqresp_parser.h"
270
#include "sip/include/sip_utils.h"
271
#include "sip/include/sip_utils.h"
271
#include "sip/include/srtp.h"
272
#include "sip/include/srtp.h"
272
#include "sip/include/sdp_crypto.h"
273
#include "sip/include/sdp_crypto.h"
273
#include "asterisk/ccss.h"
274
#include "asterisk/ccss.h"
274
#include "asterisk/xml.h"
275
#include "asterisk/xml.h"
275
#include "sip/include/dialog.h"
276
#include "sip/include/dialog.h"
276
#include "sip/include/dialplan_functions.h"
277
#include "sip/include/dialplan_functions.h"
277

    
   
278

   
278

    
   
279

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

    
   
557

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

    
   
562

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

    
   
573

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

    
   
576

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

    
   
592

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

    
   
612

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

    
   
642

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

    
   
667

   
667

    
   
668

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

    
   
692

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

    
   
695

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

    
   
701

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

    
   
704

   
704
static int global_relaxdtmf;        /*!< Relax DTMF */
705
static int global_relaxdtmf;        /*!< Relax DTMF */
705
static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
706
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 */
707
static int global_rtptimeout;       /*!< Time out call if no RTP */
707
static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
708
static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
708
static int global_rtpkeepalive;     /*!< Send RTP keepalives */
709
static int global_rtpkeepalive;     /*!< Send RTP keepalives */
709
static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
710
static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
710
static int global_regattempts_max;  /*!< Registration attempts before giving up */
711
static int global_regattempts_max;  /*!< Registration attempts before giving up */
711
static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
712
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
713
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
714
                                     *   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 */
715
                                     *   with just a boolean flag in the device structure */
715
static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
716
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 */
717
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 */
718
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 */
719
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 */
720
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 */
721
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 */
722
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 */
723
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 */
724
static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
724
static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
725
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 */
726
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 */
727
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 */
728
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. */
729
static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
729
static int global_t1;           /*!< T1 time */
730
static int global_t1;           /*!< T1 time */
730
static int global_t1min;        /*!< T1 roundtrip time minimum */
731
static int global_t1min;        /*!< T1 roundtrip time minimum */
731
static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
732
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. */
733
static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
733
static int global_qualifyfreq;          /*!< Qualify frequency */
734
static int global_qualifyfreq;          /*!< Qualify frequency */
734
static int global_qualify_gap;          /*!< Time between our group of peer pokes */
735
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 */
736
static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
736

    
   
737

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

    
   
742

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

    
   
745

   
745
/*!
746
/*!
746
 * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
747
 * 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
748
 * 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
749
 * 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.
750
 * if XML parsing support was found.
750
 */
751
 */
751
static int can_parse_xml;
752
static int can_parse_xml;
752

    
   
753

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

    
   
762

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

    
   
765

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

    
   
768

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

    
   
770

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

    
   
772

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

    
   
776

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

    
   
778

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

    
   
782

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

    
   
785

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

    
   
791

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

    
   
793

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

    
   
795

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

    
   
801

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

    
   
814

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

    
   
823

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

    
   
833

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

    
   
844

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

    
   
852

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

    
   
854

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

    
   
858

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

    
   
862

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

    
   
864

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

    
   
870

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

    
   
872

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

    
   
879

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

    
   
886

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

    
   
890

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

    
   
900

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

    
   
905

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

    
   
909

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

    
   
913

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

    
   
918

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

    
   
924

   
924
#ifdef HAVE_LIBXML2
925
#ifdef HAVE_LIBXML2
925
static int cc_esc_publish_handler(struct sip_pvt *pvt, struct sip_request *req, struct event_state_compositor *esc, struct sip_esc_entry *esc_entry);
926
static int cc_esc_publish_handler(struct sip_pvt *pvt, struct sip_request *req, struct event_state_compositor *esc, struct sip_esc_entry *esc_entry);
926

    
   
927

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

    
   
933

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

    
   
956

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

    
   
958

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

    
   
966

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

    
   
972

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

    
   
977

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

    
   
980

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

    
   
990

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

    
   
994

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

    
   
996

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

    
   
998

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

    
   
1001

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

    
   
1006

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

    
   
1008

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

    
   
1013

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

    
   
1018

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

    
   
1026

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

    
   
1031

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

    
   
1035

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

    
   
1037

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

    
   
1042

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

    
   
1045

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

    
   
1048

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

    
   
1060

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

    
   
1068

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

    
   
1075

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

    
   
1082

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

    
   
1095

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

    
   
1098

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

    
   
1102

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

    
   
1108

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

    
   
1115

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

    
   
1118

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

    
   
1122

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

    
   
1124

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

    
   
1140

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

    
   
1142

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

    
   
1150

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

    
   
1168

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

    
   
1174

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

    
   
1182

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

    
   
1186

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

    
   
1188

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

    
   
1190

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

    
   
1197

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

    
   
1201

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

    
   
1220

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

    
   
1225

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

    
   
1263

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

    
   
1281

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

    
   
1304

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

    
   
1315

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

    
   
1320

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

    
   
1325

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

    
   
1342

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

    
   
1352

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

    
   
1402

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

    
   
1412

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

    
   
1429

   
1429
/* Realtime device support */
1430
/* Realtime device support */
1430
static void realtime_update_peer(const char *peername, struct ast_sockaddr *addr, const char *username, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms);
1431
static void realtime_update_peer(const char *peername, struct ast_sockaddr *addr, const char *username, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms);
1431
static void update_peer(struct sip_peer *p, int expire);
1432
static void update_peer(struct sip_peer *p, int expire);
1432
static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1433
static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1433
static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
1434
static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
1434
static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, int devstate_only, int which_objects);
1435
static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, int devstate_only, int which_objects);
1435
static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1436
static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1436

    
   
1437

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

    
   
1448

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

    
   
1481

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

    
   
1485

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

    
   
1518

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

    
   
1534

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

    
   
1542
static void handle_response_message(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1541
static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1543
static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1542

    
   
1544

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

    
   
1548

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

    
   
1554

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

    
   
1568

   
1567
/*------- RTP Glue functions -------- */
1569
/*------- RTP Glue functions -------- */
1568
static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_rtp_instance *vinstance, struct ast_rtp_instance *tinstance, format_t codecs, int nat_active);
1570
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);
1569

    
   
1571

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

    
   
1578

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

    
   
1608

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

    
   
1616

   
1615
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1617
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1616
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1618
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1617
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1619
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1618
static void sip_cc_agent_ack(struct ast_cc_agent *agent);
1620
static void sip_cc_agent_ack(struct ast_cc_agent *agent);
1619
static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
1621
static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
1620
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1622
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1621
static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1623
static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1622
static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1624
static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1623

    
   
1625

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

    
   
1637

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

    
   
1643

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

    
   
1646

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

    
   
1652

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

    
   
1658

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

    
   
1661

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

    
   
1667

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

    
   
1673

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

    
   
1676

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

    
   
1682

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

    
   
1687

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

    
   
1691

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

    
   
1693

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

    
   
1703

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

    
   
1708

   
1707
	agent_pvt->offer_timer_id = -1;
1709
	agent_pvt->offer_timer_id = -1;
1708

    
   
1710

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

    
   
1713

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

    
   
1718

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

    
   
1723

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

    
   
1727

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

    
   
1731

   
1730
static void sip_cc_agent_ack(struct ast_cc_agent *agent)
1732
static void sip_cc_agent_ack(struct ast_cc_agent *agent)
1731
{
1733
{
1732
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1734
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1733

    
   
1735

   
1734
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1736
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1735
	ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
1737
	ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
1736
	transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1738
	transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1737
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1739
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1738
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1740
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1739
	agent_pvt->is_available = TRUE;
1741
	agent_pvt->is_available = TRUE;
1740
}
1742
}
1741

    
   
1743

   
1742
static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
1744
static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
1743
{
1745
{
1744
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1746
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1745
	enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
1747
	enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
1746
	return ast_cc_agent_status_response(agent->core_id, state);
1748
	return ast_cc_agent_status_response(agent->core_id, state);
1747
}
1749
}
1748

    
   
1750

   
1749
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
1751
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
1750
{
1752
{
1751
	/* To start monitoring just means to wait for an incoming PUBLISH
1753
	/* To start monitoring just means to wait for an incoming PUBLISH
1752
	 * to tell us that the caller has become available again. No special
1754
	 * to tell us that the caller has become available again. No special
1753
	 * action is needed
1755
	 * action is needed
1754
	 */
1756
	 */
1755
	return 0;
1757
	return 0;
1756
}
1758
}
1757

    
   
1759

   
1758
static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1760
static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1759
{
1761
{
1760
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1762
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1761
	/* If we have received a PUBLISH beforehand stating that the caller in question
1763
	/* If we have received a PUBLISH beforehand stating that the caller in question
1762
	 * is not available, we can save ourself a bit of effort here and just report
1764
	 * is not available, we can save ourself a bit of effort here and just report
1763
	 * the caller as busy
1765
	 * the caller as busy
1764
	 */
1766
	 */
1765
	if (!agent_pvt->is_available) {
1767
	if (!agent_pvt->is_available) {
1766
		return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
1768
		return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
1767
				agent->device_name);
1769
				agent->device_name);
1768
	}
1770
	}
1769
	/* Otherwise, we transmit a NOTIFY to the caller and await either
1771
	/* Otherwise, we transmit a NOTIFY to the caller and await either
1770
	 * a PUBLISH or an INVITE
1772
	 * a PUBLISH or an INVITE
1771
	 */
1773
	 */
1772
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1774
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1773
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1775
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1774
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1776
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1775
	return 0;
1777
	return 0;
1776
}
1778
}
1777

    
   
1779

   
1778
static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
1780
static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
1779
{
1781
{
1780
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1782
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1781

    
   
1783

   
1782
	if (!agent_pvt) {
1784
	if (!agent_pvt) {
1783
		/* The agent constructor probably failed. */
1785
		/* The agent constructor probably failed. */
1784
		return;
1786
		return;
1785
	}
1787
	}
1786

    
   
1788

   
1787
	sip_cc_agent_stop_offer_timer(agent);
1789
	sip_cc_agent_stop_offer_timer(agent);
1788
	if (agent_pvt->subscribe_pvt) {
1790
	if (agent_pvt->subscribe_pvt) {
1789
		sip_pvt_lock(agent_pvt->subscribe_pvt);
1791
		sip_pvt_lock(agent_pvt->subscribe_pvt);
1790
		if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
1792
		if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
1791
			/* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
1793
			/* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
1792
			 * the subscriber know something went wrong
1794
			 * the subscriber know something went wrong
1793
			 */
1795
			 */
1794
			transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
1796
			transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
1795
		}
1797
		}
1796
		sip_pvt_unlock(agent_pvt->subscribe_pvt);
1798
		sip_pvt_unlock(agent_pvt->subscribe_pvt);
1797
		agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
1799
		agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
1798
	}
1800
	}
1799
	ast_free(agent_pvt);
1801
	ast_free(agent_pvt);
1800
}
1802
}
1801

    
   
1803

   
1802
struct ao2_container *sip_monitor_instances;
1804
struct ao2_container *sip_monitor_instances;
1803

    
   
1805

   
1804
static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
1806
static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
1805
{
1807
{
1806
	const struct sip_monitor_instance *monitor_instance = obj;
1808
	const struct sip_monitor_instance *monitor_instance = obj;
1807
	return monitor_instance->core_id;
1809
	return monitor_instance->core_id;
1808
}
1810
}
1809

    
   
1811

   
1810
static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
1812
static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
1811
{
1813
{
1812
	struct sip_monitor_instance *monitor_instance1 = obj;
1814
	struct sip_monitor_instance *monitor_instance1 = obj;
1813
	struct sip_monitor_instance *monitor_instance2 = arg;
1815
	struct sip_monitor_instance *monitor_instance2 = arg;
1814

    
   
1816

   
1815
	return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
1817
	return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
1816
}
1818
}
1817

    
   
1819

   
1818
static void sip_monitor_instance_destructor(void *data)
1820
static void sip_monitor_instance_destructor(void *data)
1819
{
1821
{
1820
	struct sip_monitor_instance *monitor_instance = data;
1822
	struct sip_monitor_instance *monitor_instance = data;
1821
	if (monitor_instance->subscription_pvt) {
1823
	if (monitor_instance->subscription_pvt) {
1822
		sip_pvt_lock(monitor_instance->subscription_pvt);
1824
		sip_pvt_lock(monitor_instance->subscription_pvt);
1823
		monitor_instance->subscription_pvt->expiry = 0;
1825
		monitor_instance->subscription_pvt->expiry = 0;
1824
		transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
1826
		transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
1825
		sip_pvt_unlock(monitor_instance->subscription_pvt);
1827
		sip_pvt_unlock(monitor_instance->subscription_pvt);
1826
		dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
1828
		dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
1827
	}
1829
	}
1828
	if (monitor_instance->suspension_entry) {
1830
	if (monitor_instance->suspension_entry) {
1829
		monitor_instance->suspension_entry->body[0] = '\0';
1831
		monitor_instance->suspension_entry->body[0] = '\0';
1830
		transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
1832
		transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
1831
		ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
1833
		ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
1832
	}
1834
	}
1833
	ast_string_field_free_memory(monitor_instance);
1835
	ast_string_field_free_memory(monitor_instance);
1834
}
1836
}
1835

    
   
1837

   
1836
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)
1838
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)
1837
{
1839
{
1838
	struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
1840
	struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
1839

    
   
1841

   
1840
	if (!monitor_instance) {
1842
	if (!monitor_instance) {
1841
		return NULL;
1843
		return NULL;
1842
	}
1844
	}
1843

    
   
1845

   
1844
	if (ast_string_field_init(monitor_instance, 256)) {
1846
	if (ast_string_field_init(monitor_instance, 256)) {
1845
		ao2_ref(monitor_instance, -1);
1847
		ao2_ref(monitor_instance, -1);
1846
		return NULL;
1848
		return NULL;
1847
	}
1849
	}
1848

    
   
1850

   
1849
	ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
1851
	ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
1850
	ast_string_field_set(monitor_instance, peername, peername);
1852
	ast_string_field_set(monitor_instance, peername, peername);
1851
	ast_string_field_set(monitor_instance, device_name, device_name);
1853
	ast_string_field_set(monitor_instance, device_name, device_name);
1852
	monitor_instance->core_id = core_id;
1854
	monitor_instance->core_id = core_id;
1853
	ao2_link(sip_monitor_instances, monitor_instance);
1855
	ao2_link(sip_monitor_instances, monitor_instance);
1854
	return monitor_instance;
1856
	return monitor_instance;
1855
}
1857
}
1856

    
   
1858

   
1857
static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
1859
static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
1858
{
1860
{
1859
	struct sip_monitor_instance *monitor_instance = obj;
1861
	struct sip_monitor_instance *monitor_instance = obj;
1860
	return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
1862
	return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
1861
}
1863
}
1862

    
   
1864

   
1863
static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
1865
static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
1864
{
1866
{
1865
	struct sip_monitor_instance *monitor_instance = obj;
1867
	struct sip_monitor_instance *monitor_instance = obj;
1866
	return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
1868
	return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
1867
}
1869
}
1868

    
   
1870

   
1869
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
1871
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
1870
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
1872
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
1871
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
1873
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
1872
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
1874
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
1873
static void sip_cc_monitor_destructor(void *private_data);
1875
static void sip_cc_monitor_destructor(void *private_data);
1874

    
   
1876

   
1875
static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
1877
static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
1876
	.type = "SIP",
1878
	.type = "SIP",
1877
	.request_cc = sip_cc_monitor_request_cc,
1879
	.request_cc = sip_cc_monitor_request_cc,
1878
	.suspend = sip_cc_monitor_suspend,
1880
	.suspend = sip_cc_monitor_suspend,
1879
	.unsuspend = sip_cc_monitor_unsuspend,
1881
	.unsuspend = sip_cc_monitor_unsuspend,
1880
	.cancel_available_timer = sip_cc_monitor_cancel_available_timer,
1882
	.cancel_available_timer = sip_cc_monitor_cancel_available_timer,
1881
	.destructor = sip_cc_monitor_destructor,
1883
	.destructor = sip_cc_monitor_destructor,
1882
};
1884
};
1883

    
   
1885

   
1884
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
1886
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
1885
{
1887
{
1886
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1888
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1887
	enum ast_cc_service_type service = monitor->service_offered;
1889
	enum ast_cc_service_type service = monitor->service_offered;
1888
	int when;
1890
	int when;
1889

    
   
1891

   
1890
	if (!monitor_instance) {
1892
	if (!monitor_instance) {
1891
		return -1;
1893
		return -1;
1892
	}
1894
	}
1893

    
   
1895

   
1894
	if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
1896
	if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
1895
		return -1;
1897
		return -1;
1896
	}
1898
	}
1897

    
   
1899

   
1898
	when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
1900
	when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
1899
		ast_get_ccnr_available_timer(monitor->interface->config_params);
1901
		ast_get_ccnr_available_timer(monitor->interface->config_params);
1900

    
   
1902

   
1901
	sip_pvt_lock(monitor_instance->subscription_pvt);
1903
	sip_pvt_lock(monitor_instance->subscription_pvt);
1902
	create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
1904
	create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
1903
	ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
1905
	ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
1904
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1906
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1905
	monitor_instance->subscription_pvt->expiry = when;
1907
	monitor_instance->subscription_pvt->expiry = when;
1906

    
   
1908

   
1907
	transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
1909
	transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
1908
	sip_pvt_unlock(monitor_instance->subscription_pvt);
1910
	sip_pvt_unlock(monitor_instance->subscription_pvt);
1909

    
   
1911

   
1910
	ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
1912
	ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
1911
	*available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
1913
	*available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
1912
	return 0;
1914
	return 0;
1913
}
1915
}
1914

    
   
1916

   
1915
static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
1917
static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
1916
{
1918
{
1917
	struct ast_str *body = ast_str_alloca(size);
1919
	struct ast_str *body = ast_str_alloca(size);
1918
	char tuple_id[32];
1920
	char tuple_id[32];
1919

    
   
1921

   
1920
	generate_random_string(tuple_id, sizeof(tuple_id));
1922
	generate_random_string(tuple_id, sizeof(tuple_id));
1921

    
   
1923

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

    
   
1942

   
1941
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
1943
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
1942
{
1944
{
1943
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1945
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1944
	enum sip_publish_type publish_type;
1946
	enum sip_publish_type publish_type;
1945
	struct cc_epa_entry *cc_entry;
1947
	struct cc_epa_entry *cc_entry;
1946

    
   
1948

   
1947
	if (!monitor_instance) {
1949
	if (!monitor_instance) {
1948
		return -1;
1950
		return -1;
1949
	}
1951
	}
1950

    
   
1952

   
1951
	if (!monitor_instance->suspension_entry) {
1953
	if (!monitor_instance->suspension_entry) {
1952
		/* We haven't yet allocated the suspension entry, so let's give it a shot */
1954
		/* We haven't yet allocated the suspension entry, so let's give it a shot */
1953
		if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
1955
		if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
1954
			ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
1956
			ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
1955
			ao2_ref(monitor_instance, -1);
1957
			ao2_ref(monitor_instance, -1);
1956
			return -1;
1958
			return -1;
1957
		}
1959
		}
1958
		if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
1960
		if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
1959
			ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
1961
			ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
1960
			ao2_ref(monitor_instance, -1);
1962
			ao2_ref(monitor_instance, -1);
1961
			return -1;
1963
			return -1;
1962
		}
1964
		}
1963
		cc_entry->core_id = monitor->core_id;
1965
		cc_entry->core_id = monitor->core_id;
1964
		monitor_instance->suspension_entry->instance_data = cc_entry;
1966
		monitor_instance->suspension_entry->instance_data = cc_entry;
1965
		publish_type = SIP_PUBLISH_INITIAL;
1967
		publish_type = SIP_PUBLISH_INITIAL;
1966
	} else {
1968
	} else {
1967
		publish_type = SIP_PUBLISH_MODIFY;
1969
		publish_type = SIP_PUBLISH_MODIFY;
1968
		cc_entry = monitor_instance->suspension_entry->instance_data;
1970
		cc_entry = monitor_instance->suspension_entry->instance_data;
1969
	}
1971
	}
1970

    
   
1972

   
1971
	cc_entry->current_state = CC_CLOSED;
1973
	cc_entry->current_state = CC_CLOSED;
1972

    
   
1974

   
1973
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
1975
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
1974
		/* If we have no set notify_uri, then what this means is that we have
1976
		/* If we have no set notify_uri, then what this means is that we have
1975
		 * not received a NOTIFY from this destination stating that he is
1977
		 * not received a NOTIFY from this destination stating that he is
1976
		 * currently available.
1978
		 * currently available.
1977
		 *
1979
		 *
1978
		 * This situation can arise when the core calls the suspend callbacks
1980
		 * This situation can arise when the core calls the suspend callbacks
1979
		 * of multiple destinations. If one of the other destinations aside
1981
		 * of multiple destinations. If one of the other destinations aside
1980
		 * from this one notified Asterisk that he is available, then there
1982
		 * from this one notified Asterisk that he is available, then there
1981
		 * is no reason to take any suspension action on this device. Rather,
1983
		 * is no reason to take any suspension action on this device. Rather,
1982
		 * we should return now and if we receive a NOTIFY while monitoring
1984
		 * we should return now and if we receive a NOTIFY while monitoring
1983
		 * is still "suspended" then we can immediately respond with the
1985
		 * is still "suspended" then we can immediately respond with the
1984
		 * proper PUBLISH to let this endpoint know what is going on.
1986
		 * proper PUBLISH to let this endpoint know what is going on.
1985
		 */
1987
		 */
1986
		return 0;
1988
		return 0;
1987
	}
1989
	}
1988
	construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
1990
	construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
1989
	return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
1991
	return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
1990
}
1992
}
1991

    
   
1993

   
1992
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
1994
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
1993
{
1995
{
1994
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1996
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1995
	struct cc_epa_entry *cc_entry;
1997
	struct cc_epa_entry *cc_entry;
1996

    
   
1998

   
1997
	if (!monitor_instance) {
1999
	if (!monitor_instance) {
1998
		return -1;
2000
		return -1;
1999
	}
2001
	}
2000

    
   
2002

   
2001
	ast_assert(monitor_instance->suspension_entry != NULL);
2003
	ast_assert(monitor_instance->suspension_entry != NULL);
2002

    
   
2004

   
2003
	cc_entry = monitor_instance->suspension_entry->instance_data;
2005
	cc_entry = monitor_instance->suspension_entry->instance_data;
2004
	cc_entry->current_state = CC_OPEN;
2006
	cc_entry->current_state = CC_OPEN;
2005
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
2007
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
2006
		/* This means we are being asked to unsuspend a call leg we never
2008
		/* This means we are being asked to unsuspend a call leg we never
2007
		 * sent a PUBLISH on. As such, there is no reason to send another
2009
		 * sent a PUBLISH on. As such, there is no reason to send another
2008
		 * PUBLISH at this point either. We can just return instead.
2010
		 * PUBLISH at this point either. We can just return instead.
2009
		 */
2011
		 */
2010
		return 0;
2012
		return 0;
2011
	}
2013
	}
2012
	construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2014
	construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2013
	return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
2015
	return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
2014
}
2016
}
2015

    
   
2017

   
2016
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
2018
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
2017
{
2019
{
2018
	if (*sched_id != -1) {
2020
	if (*sched_id != -1) {
2019
		AST_SCHED_DEL(sched, *sched_id);
2021
		AST_SCHED_DEL(sched, *sched_id);
2020
		ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
2022
		ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
2021
	}
2023
	}
2022
	return 0;
2024
	return 0;
2023
}
2025
}
2024

    
   
2026

   
2025
static void sip_cc_monitor_destructor(void *private_data)
2027
static void sip_cc_monitor_destructor(void *private_data)
2026
{
2028
{
2027
	struct sip_monitor_instance *monitor_instance = private_data;
2029
	struct sip_monitor_instance *monitor_instance = private_data;
2028
	ao2_unlink(sip_monitor_instances, monitor_instance);
2030
	ao2_unlink(sip_monitor_instances, monitor_instance);
2029
	ast_module_unref(ast_module_info->self);
2031
	ast_module_unref(ast_module_info->self);
2030
}
2032
}
2031

    
   
2033

   
2032
static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
2034
static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
2033
{
2035
{
2034
	char *call_info = ast_strdupa(get_header(req, "Call-Info"));
2036
	char *call_info = ast_strdupa(get_header(req, "Call-Info"));
2035
	char *uri;
2037
	char *uri;
2036
	char *purpose;
2038
	char *purpose;
2037
	char *service_str;
2039
	char *service_str;
2038
	static const char cc_purpose[] = "purpose=call-completion";
2040
	static const char cc_purpose[] = "purpose=call-completion";
2039
	static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2041
	static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2040

    
   
2042

   
2041
	if (ast_strlen_zero(call_info)) {
2043
	if (ast_strlen_zero(call_info)) {
2042
		/* No Call-Info present. Definitely no CC offer */
2044
		/* No Call-Info present. Definitely no CC offer */
2043
		return -1;
2045
		return -1;
2044
	}
2046
	}
2045

    
   
2047

   
2046
	uri = strsep(&call_info, ";");
2048
	uri = strsep(&call_info, ";");
2047

    
   
2049

   
2048
	while ((purpose = strsep(&call_info, ";"))) {
2050
	while ((purpose = strsep(&call_info, ";"))) {
2049
		if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
2051
		if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
2050
			break;
2052
			break;
2051
		}
2053
		}
2052
	}
2054
	}
2053
	if (!purpose) {
2055
	if (!purpose) {
2054
		/* We didn't find the appropriate purpose= parameter. Oh well */
2056
		/* We didn't find the appropriate purpose= parameter. Oh well */
2055
		return -1;
2057
		return -1;
2056
	}
2058
	}
2057

    
   
2059

   
2058
	/* Okay, call-completion has been offered. Let's figure out what type of service this is */
2060
	/* Okay, call-completion has been offered. Let's figure out what type of service this is */
2059
	while ((service_str = strsep(&call_info, ";"))) {
2061
	while ((service_str = strsep(&call_info, ";"))) {
2060
		if (!strncmp(service_str, "m=", 2)) {
2062
		if (!strncmp(service_str, "m=", 2)) {
2061
			break;
2063
			break;
2062
		}
2064
		}
2063
	}
2065
	}
2064
	if (!service_str) {
2066
	if (!service_str) {
2065
		/* So they didn't offer a particular service, We'll just go with CCBS since it really
2067
		/* So they didn't offer a particular service, We'll just go with CCBS since it really
2066
		 * doesn't matter anyway
2068
		 * doesn't matter anyway
2067
		 */
2069
		 */
2068
		service_str = "BS";
2070
		service_str = "BS";
2069
	} else {
2071
	} else {
2070
		/* We already determined that there is an "m=" so no need to check
2072
		/* We already determined that there is an "m=" so no need to check
2071
		 * the result of this strsep
2073
		 * the result of this strsep
2072
		 */
2074
		 */
2073
		strsep(&service_str, "=");
2075
		strsep(&service_str, "=");
2074
	}
2076
	}
2075

    
   
2077

   
2076
	if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2078
	if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2077
		/* Invalid service offered */
2079
		/* Invalid service offered */
2078
		return -1;
2080
		return -1;
2079
	}
2081
	}
2080

    
   
2082

   
2081
	ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2083
	ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2082

    
   
2084

   
2083
	return 0;
2085
	return 0;
2084
}
2086
}
2085

    
   
2087

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

    
   
2110

   
2109
	if (monitor_policy == AST_CC_MONITOR_NEVER) {
2111
	if (monitor_policy == AST_CC_MONITOR_NEVER) {
2110
		/* Don't bother, just return */
2112
		/* Don't bother, just return */
2111
		return;
2113
		return;
2112
	}
2114
	}
2113

    
   
2115

   
2114
	if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
2116
	if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
2115
		/* For some reason, CC is invalid, so don't try it! */
2117
		/* For some reason, CC is invalid, so don't try it! */
2116
		return;
2118
		return;
2117
	}
2119
	}
2118

    
   
2120

   
2119
	ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2121
	ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2120

    
   
2122

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

    
   
2149

   
2148
generic:
2150
generic:
2149
	if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2151
	if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2150
		ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2152
		ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2151
	}
2153
	}
2152
}
2154
}
2153

    
   
2155

   
2154
/*! \brief Working TLS connection configuration */
2156
/*! \brief Working TLS connection configuration */
2155
static struct ast_tls_config sip_tls_cfg;
2157
static struct ast_tls_config sip_tls_cfg;
2156

    
   
2158

   
2157
/*! \brief Default TLS connection configuration */
2159
/*! \brief Default TLS connection configuration */
2158
static struct ast_tls_config default_tls_cfg;
2160
static struct ast_tls_config default_tls_cfg;
2159

    
   
2161

   
2160
/*! \brief The TCP server definition */
2162
/*! \brief The TCP server definition */
2161
static struct ast_tcptls_session_args sip_tcp_desc = {
2163
static struct ast_tcptls_session_args sip_tcp_desc = {
2162
	.accept_fd = -1,
2164
	.accept_fd = -1,
2163
	.master = AST_PTHREADT_NULL,
2165
	.master = AST_PTHREADT_NULL,
2164
	.tls_cfg = NULL,
2166
	.tls_cfg = NULL,
2165
	.poll_timeout = -1,
2167
	.poll_timeout = -1,
2166
	.name = "SIP TCP server",
2168
	.name = "SIP TCP server",
2167
	.accept_fn = ast_tcptls_server_root,
2169
	.accept_fn = ast_tcptls_server_root,
2168
	.worker_fn = sip_tcp_worker_fn,
2170
	.worker_fn = sip_tcp_worker_fn,
2169
};
2171
};
2170

    
   
2172

   
2171
/*! \brief The TCP/TLS server definition */
2173
/*! \brief The TCP/TLS server definition */
2172
static struct ast_tcptls_session_args sip_tls_desc = {
2174
static struct ast_tcptls_session_args sip_tls_desc = {
2173
	.accept_fd = -1,
2175
	.accept_fd = -1,
2174
	.master = AST_PTHREADT_NULL,
2176
	.master = AST_PTHREADT_NULL,
2175
	.tls_cfg = &sip_tls_cfg,
2177
	.tls_cfg = &sip_tls_cfg,
2176
	.poll_timeout = -1,
2178
	.poll_timeout = -1,
2177
	.name = "SIP TLS server",
2179
	.name = "SIP TLS server",
2178
	.accept_fn = ast_tcptls_server_root,
2180
	.accept_fn = ast_tcptls_server_root,
2179
	.worker_fn = sip_tcp_worker_fn,
2181
	.worker_fn = sip_tcp_worker_fn,
2180
};
2182
};
2181

    
   
2183

   
2182
/*! \brief Append to SIP dialog history
2184
/*! \brief Append to SIP dialog history
2183
	\return Always returns 0 */
2185
	\return Always returns 0 */
2184
#define append_history(p, event, fmt , args... )	append_history_full(p, "%-15s " fmt, event, ## args)
2186
#define append_history(p, event, fmt , args... )	append_history_full(p, "%-15s " fmt, event, ## args)
2185

    
   
2187

   
2186
struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
2188
struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
2187
{
2189
{
2188
	if (p)
2190
	if (p)
2189
#ifdef REF_DEBUG
2191
#ifdef REF_DEBUG
2190
		__ao2_ref_debug(p, 1, tag, file, line, func);
2192
		__ao2_ref_debug(p, 1, tag, file, line, func);
2191
#else
2193
#else
2192
		ao2_ref(p, 1);
2194
		ao2_ref(p, 1);
2193
#endif
2195
#endif
2194
	else
2196
	else
2195
		ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2197
		ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2196
	return p;
2198
	return p;
2197
}
2199
}
2198

    
   
2200

   
2199
struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
2201
struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
2200
{
2202
{
2201
	if (p)
2203
	if (p)
2202
#ifdef REF_DEBUG
2204
#ifdef REF_DEBUG
2203
		__ao2_ref_debug(p, -1, tag, file, line, func);
2205
		__ao2_ref_debug(p, -1, tag, file, line, func);
2204
#else
2206
#else
2205
		ao2_ref(p, -1);
2207
		ao2_ref(p, -1);
2206
#endif
2208
#endif
2207
	return NULL;
2209
	return NULL;
2208
}
2210
}
2209

    
   
2211

   
2210
/*! \brief map from an integer value to a string.
2212
/*! \brief map from an integer value to a string.
2211
 * If no match is found, return errorstring
2213
 * If no match is found, return errorstring
2212
 */
2214
 */
2213
static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2215
static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2214
{
2216
{
2215
	const struct _map_x_s *cur;
2217
	const struct _map_x_s *cur;
2216

    
   
2218

   
2217
	for (cur = table; cur->s; cur++) {
2219
	for (cur = table; cur->s; cur++) {
2218
		if (cur->x == x) {
2220
		if (cur->x == x) {
2219
			return cur->s;
2221
			return cur->s;
2220
		}
2222
		}
2221
	}
2223
	}
2222
	return errorstring;
2224
	return errorstring;
2223
}
2225
}
2224

    
   
2226

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

    
   
2233

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

    
   
2241

   
2240
static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
2242
static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
2241
{
2243
{
2242
	enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2244
	enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2243
	int i;
2245
	int i;
2244

    
   
2246

   
2245
	for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
2247
	for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
2246
		if (!strcasecmp(text, sip_reason_table[i].text)) {
2248
		if (!strcasecmp(text, sip_reason_table[i].text)) {
2247
			ast = sip_reason_table[i].code;
2249
			ast = sip_reason_table[i].code;
2248
			break;
2250
			break;
2249
		}
2251
		}
2250
	}
2252
	}
2251

    
   
2253

   
2252
	return ast;
2254
	return ast;
2253
}
2255
}
2254

    
   
2256

   
2255
static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
2257
static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
2256
{
2258
{
2257
	if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2259
	if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2258
		return sip_reason_table[code].text;
2260
		return sip_reason_table[code].text;
2259
	}
2261
	}
2260

    
   
2262

   
2261
	return "unknown";
2263
	return "unknown";
2262
}
2264
}
2263

    
   
2265

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

    
   
2296

   
2295
/*! \brief
2297
/*! \brief
2296
 * duplicate a list of channel variables, \return the copy.
2298
 * duplicate a list of channel variables, \return the copy.
2297
 */
2299
 */
2298
static struct ast_variable *copy_vars(struct ast_variable *src)
2300
static struct ast_variable *copy_vars(struct ast_variable *src)
2299
{
2301
{
2300
	struct ast_variable *res = NULL, *tmp, *v = NULL;
2302
	struct ast_variable *res = NULL, *tmp, *v = NULL;
2301

    
   
2303

   
2302
	for (v = src ; v ; v = v->next) {
2304
	for (v = src ; v ; v = v->next) {
2303
		if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2305
		if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2304
			tmp->next = res;
2306
			tmp->next = res;
2305
			res = tmp;
2307
			res = tmp;
2306
		}
2308
		}
2307
	}
2309
	}
2308
	return res;
2310
	return res;
2309
}
2311
}
2310

    
   
2312

   
2311
static void tcptls_packet_destructor(void *obj)
2313
static void tcptls_packet_destructor(void *obj)
2312
{
2314
{
2313
	struct tcptls_packet *packet = obj;
2315
	struct tcptls_packet *packet = obj;
2314

    
   
2316

   
2315
	ast_free(packet->data);
2317
	ast_free(packet->data);
2316
}
2318
}
2317

    
   
2319

   
2318
static void sip_tcptls_client_args_destructor(void *obj)
2320
static void sip_tcptls_client_args_destructor(void *obj)
2319
{
2321
{
2320
	struct ast_tcptls_session_args *args = obj;
2322
	struct ast_tcptls_session_args *args = obj;
2321
	if (args->tls_cfg) {
2323
	if (args->tls_cfg) {
2322
		ast_free(args->tls_cfg->certfile);
2324
		ast_free(args->tls_cfg->certfile);
2323
		ast_free(args->tls_cfg->pvtfile);
2325
		ast_free(args->tls_cfg->pvtfile);
2324
		ast_free(args->tls_cfg->cipher);
2326
		ast_free(args->tls_cfg->cipher);
2325
		ast_free(args->tls_cfg->cafile);
2327
		ast_free(args->tls_cfg->cafile);
2326
		ast_free(args->tls_cfg->capath);
2328
		ast_free(args->tls_cfg->capath);
2327
	}
2329
	}
2328
	ast_free(args->tls_cfg);
2330
	ast_free(args->tls_cfg);
2329
	ast_free((char *) args->name);
2331
	ast_free((char *) args->name);
2330
}
2332
}
2331

    
   
2333

   
2332
static void sip_threadinfo_destructor(void *obj)
2334
static void sip_threadinfo_destructor(void *obj)
2333
{
2335
{
2334
	struct sip_threadinfo *th = obj;
2336
	struct sip_threadinfo *th = obj;
2335
	struct tcptls_packet *packet;
2337
	struct tcptls_packet *packet;
2336

    
   
2338

   
2337
	if (th->alert_pipe[1] > -1) {
2339
	if (th->alert_pipe[1] > -1) {
2338
		close(th->alert_pipe[0]);
2340
		close(th->alert_pipe[0]);
2339
	}
2341
	}
2340
	if (th->alert_pipe[1] > -1) {
2342
	if (th->alert_pipe[1] > -1) {
2341
		close(th->alert_pipe[1]);
2343
		close(th->alert_pipe[1]);
2342
	}
2344
	}
2343
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2345
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2344

    
   
2346

   
2345
	while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2347
	while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2346
		ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
2348
		ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
2347
	}
2349
	}
2348

    
   
2350

   
2349
	if (th->tcptls_session) {
2351
	if (th->tcptls_session) {
2350
		ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
2352
		ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
2351
	}
2353
	}
2352
}
2354
}
2353

    
   
2355

   
2354
/*! \brief creates a sip_threadinfo object and links it into the threadt table. */
2356
/*! \brief creates a sip_threadinfo object and links it into the threadt table. */
2355
static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
2357
static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
2356
{
2358
{
2357
	struct sip_threadinfo *th;
2359
	struct sip_threadinfo *th;
2358

    
   
2360

   
2359
	if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
2361
	if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
2360
		return NULL;
2362
		return NULL;
2361
	}
2363
	}
2362

    
   
2364

   
2363
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2365
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2364

    
   
2366

   
2365
	if (pipe(th->alert_pipe) == -1) {
2367
	if (pipe(th->alert_pipe) == -1) {
2366
		ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
2368
		ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
2367
		ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
2369
		ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
2368
		return NULL;
2370
		return NULL;
2369
	}
2371
	}
2370
	ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
2372
	ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
2371
	th->tcptls_session = tcptls_session;
2373
	th->tcptls_session = tcptls_session;
2372
	th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
2374
	th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
2373
	ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2375
	ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2374
	ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
2376
	ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
2375
	return th;
2377
	return th;
2376
}
2378
}
2377

    
   
2379

   
2378
/*! \brief used to indicate to a tcptls thread that data is ready to be written */
2380
/*! \brief used to indicate to a tcptls thread that data is ready to be written */
2379
static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
2381
static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
2380
{
2382
{
2381
	int res = len;
2383
	int res = len;
2382
	struct sip_threadinfo *th = NULL;
2384
	struct sip_threadinfo *th = NULL;
2383
	struct tcptls_packet *packet = NULL;
2385
	struct tcptls_packet *packet = NULL;
2384
	struct sip_threadinfo tmp = {
2386
	struct sip_threadinfo tmp = {
2385
		.tcptls_session = tcptls_session,
2387
		.tcptls_session = tcptls_session,
2386
	};
2388
	};
2387
	enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2389
	enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2388

    
   
2390

   
2389
	if (!tcptls_session) {
2391
	if (!tcptls_session) {
2390
		return XMIT_ERROR;
2392
		return XMIT_ERROR;
2391
	}
2393
	}
2392

    
   
2394

   
2393
	ast_mutex_lock(&tcptls_session->lock);
2395
	ast_mutex_lock(&tcptls_session->lock);
2394

    
   
2396

   
2395
	if ((tcptls_session->fd == -1) ||
2397
	if ((tcptls_session->fd == -1) ||
2396
		!(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
2398
		!(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
2397
		!(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2399
		!(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2398
		!(packet->data = ast_str_create(len))) {
2400
		!(packet->data = ast_str_create(len))) {
2399
		goto tcptls_write_setup_error;
2401
		goto tcptls_write_setup_error;
2400
	}
2402
	}
2401

    
   
2403

   
2402
	/* goto tcptls_write_error should _NOT_ be used beyond this point */
2404
	/* goto tcptls_write_error should _NOT_ be used beyond this point */
2403
	ast_str_set(&packet->data, 0, "%s", (char *) buf);
2405
	ast_str_set(&packet->data, 0, "%s", (char *) buf);
2404
	packet->len = len;
2406
	packet->len = len;
2405

    
   
2407

   
2406
	/* alert tcptls thread handler that there is a packet to be sent.
2408
	/* alert tcptls thread handler that there is a packet to be sent.
2407
	 * must lock the thread info object to guarantee control of the
2409
	 * must lock the thread info object to guarantee control of the
2408
	 * packet queue */
2410
	 * packet queue */
2409
	ao2_lock(th);
2411
	ao2_lock(th);
2410
	if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2412
	if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2411
		ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
2413
		ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
2412
		ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
2414
		ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
2413
		packet = NULL;
2415
		packet = NULL;
2414
		res = XMIT_ERROR;
2416
		res = XMIT_ERROR;
2415
	} else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
2417
	} else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
2416
		AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2418
		AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2417
	}
2419
	}
2418
	ao2_unlock(th);
2420
	ao2_unlock(th);
2419

    
   
2421

   
2420
	ast_mutex_unlock(&tcptls_session->lock);
2422
	ast_mutex_unlock(&tcptls_session->lock);
2421
	ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
2423
	ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
2422
	return res;
2424
	return res;
2423

    
   
2425

   
2424
tcptls_write_setup_error:
2426
tcptls_write_setup_error:
2425
	if (th) {
2427
	if (th) {
2426
		ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
2428
		ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
2427
	}
2429
	}
2428
	if (packet) {
2430
	if (packet) {
2429
		ao2_t_ref(packet, -1, "could not allocate packet's data");
2431
		ao2_t_ref(packet, -1, "could not allocate packet's data");
2430
	}
2432
	}
2431
	ast_mutex_unlock(&tcptls_session->lock);
2433
	ast_mutex_unlock(&tcptls_session->lock);
2432

    
   
2434

   
2433
	return XMIT_ERROR;
2435
	return XMIT_ERROR;
2434
}
2436
}
2435

    
   
2437

   
2436
/*! \brief SIP TCP connection handler */
2438
/*! \brief SIP TCP connection handler */
2437
static void *sip_tcp_worker_fn(void *data)
2439
static void *sip_tcp_worker_fn(void *data)
2438
{
2440
{
2439
	struct ast_tcptls_session_instance *tcptls_session = data;
2441
	struct ast_tcptls_session_instance *tcptls_session = data;
2440

    
   
2442

   
2441
	return _sip_tcp_helper_thread(NULL, tcptls_session);
2443
	return _sip_tcp_helper_thread(NULL, tcptls_session);
2442
}
2444
}
2443

    
   
2445

   
2444
/*! \brief SIP TCP thread management function
2446
/*! \brief SIP TCP thread management function
2445
	This function reads from the socket, parses the packet into a request
2447
	This function reads from the socket, parses the packet into a request
2446
*/
2448
*/
2447
static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
2449
static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
2448
{
2450
{
2449
	int res, cl;
2451
	int res, cl;
2450
	struct sip_request req = { 0, } , reqcpy = { 0, };
2452
	struct sip_request req = { 0, } , reqcpy = { 0, };
2451
	struct sip_threadinfo *me = NULL;
2453
	struct sip_threadinfo *me = NULL;
2452
	char buf[1024] = "";
2454
	char buf[1024] = "";
2453
	struct pollfd fds[2] = { { 0 }, { 0 }, };
2455
	struct pollfd fds[2] = { { 0 }, { 0 }, };
2454
	struct ast_tcptls_session_args *ca = NULL;
2456
	struct ast_tcptls_session_args *ca = NULL;
2455

    
   
2457

   
2456
	/* If this is a server session, then the connection has already been setup,
2458
	/* If this is a server session, then the connection has already been setup,
2457
	 * simply create the threadinfo object so we can access this thread for writing.
2459
	 * simply create the threadinfo object so we can access this thread for writing.
2458
	 * 
2460
	 * 
2459
	 * if this is a client connection more work must be done.
2461
	 * if this is a client connection more work must be done.
2460
	 * 1. We own the parent session args for a client connection.  This pointer needs
2462
	 * 1. We own the parent session args for a client connection.  This pointer needs
2461
	 *    to be held on to so we can decrement it's ref count on thread destruction.
2463
	 *    to be held on to so we can decrement it's ref count on thread destruction.
2462
	 * 2. The threadinfo object was created before this thread was launched, however
2464
	 * 2. The threadinfo object was created before this thread was launched, however
2463
	 *    it must be found within the threadt table.
2465
	 *    it must be found within the threadt table.
2464
	 * 3. Last, the tcptls_session must be started.
2466
	 * 3. Last, the tcptls_session must be started.
2465
	 */
2467
	 */
2466
	if (!tcptls_session->client) {
2468
	if (!tcptls_session->client) {
2467
		if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
2469
		if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
2468
			goto cleanup;
2470
			goto cleanup;
2469
		}
2471
		}
2470
		ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
2472
		ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
2471
	} else {
2473
	} else {
2472
		struct sip_threadinfo tmp = {
2474
		struct sip_threadinfo tmp = {
2473
			.tcptls_session = tcptls_session,
2475
			.tcptls_session = tcptls_session,
2474
		};
2476
		};
2475

    
   
2477

   
2476
		if ((!(ca = tcptls_session->parent)) ||
2478
		if ((!(ca = tcptls_session->parent)) ||
2477
			(!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
2479
			(!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
2478
			(!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
2480
			(!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
2479
			goto cleanup;
2481
			goto cleanup;
2480
		}
2482
		}
2481
	}
2483
	}
2482

    
   
2484

   
2483
	me->threadid = pthread_self();
2485
	me->threadid = pthread_self();
2484
	ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
2486
	ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
2485

    
   
2487

   
2486
	/* set up pollfd to watch for reads on both the socket and the alert_pipe */
2488
	/* set up pollfd to watch for reads on both the socket and the alert_pipe */
2487
	fds[0].fd = tcptls_session->fd;
2489
	fds[0].fd = tcptls_session->fd;
2488
	fds[1].fd = me->alert_pipe[0];
2490
	fds[1].fd = me->alert_pipe[0];
2489
	fds[0].events = fds[1].events = POLLIN | POLLPRI;
2491
	fds[0].events = fds[1].events = POLLIN | POLLPRI;
2490

    
   
2492

   
2491
	if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
2493
	if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
2492
		goto cleanup;
2494
		goto cleanup;
2493
	}
2495
	}
2494
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
2496
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
2495
		goto cleanup;
2497
		goto cleanup;
2496
	}
2498
	}
2497

    
   
2499

   
2498
	for (;;) {
2500
	for (;;) {
2499
		struct ast_str *str_save;
2501
		struct ast_str *str_save;
2500

    
   
2502

   
2501
		res = ast_poll(fds, 2, -1); /* polls for both socket and alert_pipe */
2503
		res = ast_poll(fds, 2, -1); /* polls for both socket and alert_pipe */
2502
		if (res < 0) {
2504
		if (res < 0) {
2503
			ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
2505
			ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
2504
			goto cleanup;
2506
			goto cleanup;
2505
		}
2507
		}
2506

    
   
2508

   
2507
		/* handle the socket event, check for both reads from the socket fd,
2509
		/* handle the socket event, check for both reads from the socket fd,
2508
		 * and writes from alert_pipe fd */
2510
		 * and writes from alert_pipe fd */
2509
		if (fds[0].revents) { /* there is data on the socket to be read */
2511
		if (fds[0].revents) { /* there is data on the socket to be read */
2510

    
   
2512

   
2511
			fds[0].revents = 0;
2513
			fds[0].revents = 0;
2512

    
   
2514

   
2513
			/* clear request structure */
2515
			/* clear request structure */
2514
			str_save = req.data;
2516
			str_save = req.data;
2515
			memset(&req, 0, sizeof(req));
2517
			memset(&req, 0, sizeof(req));
2516
			req.data = str_save;
2518
			req.data = str_save;
2517
			ast_str_reset(req.data);
2519
			ast_str_reset(req.data);
2518

    
   
2520

   
2519
			str_save = reqcpy.data;
2521
			str_save = reqcpy.data;
2520
			memset(&reqcpy, 0, sizeof(reqcpy));
2522
			memset(&reqcpy, 0, sizeof(reqcpy));
2521
			reqcpy.data = str_save;
2523
			reqcpy.data = str_save;
2522
			ast_str_reset(reqcpy.data);
2524
			ast_str_reset(reqcpy.data);
2523

    
   
2525

   
2524
			memset(buf, 0, sizeof(buf));
2526
			memset(buf, 0, sizeof(buf));
2525

    
   
2527

   
2526
			if (tcptls_session->ssl) {
2528
			if (tcptls_session->ssl) {
2527
				set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
2529
				set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
2528
				req.socket.port = htons(ourport_tls);
2530
				req.socket.port = htons(ourport_tls);
2529
			} else {
2531
			} else {
2530
				set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
2532
				set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
2531
				req.socket.port = htons(ourport_tcp);
2533
				req.socket.port = htons(ourport_tcp);
2532
			}
2534
			}
2533
			req.socket.fd = tcptls_session->fd;
2535
			req.socket.fd = tcptls_session->fd;
2534

    
   
2536

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

    
   
2574

   
2573
			req.socket.tcptls_session = tcptls_session;
2575
			req.socket.tcptls_session = tcptls_session;
2574
			handle_request_do(&req, &tcptls_session->remote_address);
2576
			handle_request_do(&req, &tcptls_session->remote_address);
2575
		}
2577
		}
2576

    
   
2578

   
2577
		if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
2579
		if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
2578
			enum sip_tcptls_alert alert;
2580
			enum sip_tcptls_alert alert;
2579
			struct tcptls_packet *packet;
2581
			struct tcptls_packet *packet;
2580

    
   
2582

   
2581
			fds[1].revents = 0;
2583
			fds[1].revents = 0;
2582

    
   
2584

   
2583
			if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
2585
			if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
2584
				ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
2586
				ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
2585
				continue;
2587
				continue;
2586
			}
2588
			}
2587

    
   
2589

   
2588
			switch (alert) {
2590
			switch (alert) {
2589
			case TCPTLS_ALERT_STOP:
2591
			case TCPTLS_ALERT_STOP:
2590
				goto cleanup;
2592
				goto cleanup;
2591
			case TCPTLS_ALERT_DATA:
2593
			case TCPTLS_ALERT_DATA:
2592
				ao2_lock(me);
2594
				ao2_lock(me);
2593
				if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
2595
				if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
2594
					ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
2596
					ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
2595
				} else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
2597
				} else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
2596
					ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
2598
					ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
2597
				}
2599
				}
2598

    
   
2600

   
2599
				if (packet) {
2601
				if (packet) {
2600
					ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
2602
					ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
2601
				}
2603
				}
2602
				ao2_unlock(me);
2604
				ao2_unlock(me);
2603
				break;
2605
				break;
2604
			default:
2606
			default:
2605
				ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
2607
				ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
2606
			}
2608
			}
2607
		}
2609
		}
2608
	}
2610
	}
2609

    
   
2611

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

    
   
2613

   
2612
cleanup:
2614
cleanup:
2613
	if (me) {
2615
	if (me) {
2614
		ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
2616
		ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
2615
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2617
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2616
	}
2618
	}
2617
	deinit_req(&reqcpy);
2619
	deinit_req(&reqcpy);
2618
	deinit_req(&req);
2620
	deinit_req(&req);
2619

    
   
2621

   
2620
	/* if client, we own the parent session arguments and must decrement ref */
2622
	/* if client, we own the parent session arguments and must decrement ref */
2621
	if (ca) {
2623
	if (ca) {
2622
		ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
2624
		ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
2623
	}
2625
	}
2624

    
   
2626

   
2625
	if (tcptls_session) {
2627
	if (tcptls_session) {
2626
		ast_mutex_lock(&tcptls_session->lock);
2628
		ast_mutex_lock(&tcptls_session->lock);
2627
		if (tcptls_session->f) {
2629
		if (tcptls_session->f) {
2628
			fclose(tcptls_session->f);
2630
			fclose(tcptls_session->f);
2629
			tcptls_session->f = NULL;
2631
			tcptls_session->f = NULL;
2630
		}
2632
		}
2631
		if (tcptls_session->fd != -1) {
2633
		if (tcptls_session->fd != -1) {
2632
			close(tcptls_session->fd);
2634
			close(tcptls_session->fd);
2633
			tcptls_session->fd = -1;
2635
			tcptls_session->fd = -1;
2634
		}
2636
		}
2635
		tcptls_session->parent = NULL;
2637
		tcptls_session->parent = NULL;
2636
		ast_mutex_unlock(&tcptls_session->lock);
2638
		ast_mutex_unlock(&tcptls_session->lock);
2637

    
   
2639

   
2638
		ao2_ref(tcptls_session, -1);
2640
		ao2_ref(tcptls_session, -1);
2639
		tcptls_session = NULL;
2641
		tcptls_session = NULL;
2640
	}
2642
	}
2641
	return NULL;
2643
	return NULL;
2642
}
2644
}
2643

    
   
2645

   
2644
/* this func is used with ao2_callback to unlink/delete all marked
2646
/* this func is used with ao2_callback to unlink/delete all marked
2645
   peers */
2647
   peers */
2646
static int peer_is_marked(void *peerobj, void *arg, int flags)
2648
static int peer_is_marked(void *peerobj, void *arg, int flags)
2647
{
2649
{
2648
	struct sip_peer *peer = peerobj;
2650
	struct sip_peer *peer = peerobj;
2649
	if (peer->the_mark && peer->pokeexpire != -1) {
2651
	if (peer->the_mark && peer->pokeexpire != -1) {
2650
		AST_SCHED_DEL(sched, peer->pokeexpire);
2652
		AST_SCHED_DEL(sched, peer->pokeexpire);
2651
	}
2653
	}
2652
	return peer->the_mark ? CMP_MATCH : 0;
2654
	return peer->the_mark ? CMP_MATCH : 0;
2653
}
2655
}
2654

    
   
2656

   
2655

    
   
2657

   
2656
/* \brief Unlink all marked peers from ao2 containers */
2658
/* \brief Unlink all marked peers from ao2 containers */
2657
static void unlink_marked_peers_from_tables(void)
2659
static void unlink_marked_peers_from_tables(void)
2658
{
2660
{
2659
	ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
2661
	ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
2660
						"initiating callback to remove marked peers");
2662
						"initiating callback to remove marked peers");
2661
	ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
2663
	ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
2662
						"initiating callback to remove marked peers");
2664
						"initiating callback to remove marked peers");
2663
}
2665
}
2664

    
   
2666

   
2665
/* \brief Unlink single peer from all ao2 containers */
2667
/* \brief Unlink single peer from all ao2 containers */
2666
static void unlink_peer_from_tables(struct sip_peer *peer)
2668
static void unlink_peer_from_tables(struct sip_peer *peer)
2667
{
2669
{
2668
	ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
2670
	ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
2669
	if (!ast_sockaddr_isnull(&peer->addr)) {
2671
	if (!ast_sockaddr_isnull(&peer->addr)) {
2670
		ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
2672
		ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
2671
	}
2673
	}
2672
}
2674
}
2673

    
   
2675

   
2674
/*!
2676
/*!
2675
 * helper functions to unreference various types of objects.
2677
 * helper functions to unreference various types of objects.
2676
 * By handling them this way, we don't have to declare the
2678
 * By handling them this way, we don't have to declare the
2677
 * destructor on each call, which removes the chance of errors.
2679
 * destructor on each call, which removes the chance of errors.
2678
 */
2680
 */
2679
static void *unref_peer(struct sip_peer *peer, char *tag)
2681
static void *unref_peer(struct sip_peer *peer, char *tag)
2680
{
2682
{
2681
	ao2_t_ref(peer, -1, tag);
2683
	ao2_t_ref(peer, -1, tag);
2682
	return NULL;
2684
	return NULL;
2683
}
2685
}
2684

    
   
2686

   
2685
static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
2687
static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
2686
{
2688
{
2687
	ao2_t_ref(peer, 1, tag);
2689
	ao2_t_ref(peer, 1, tag);
2688
	return peer;
2690
	return peer;
2689
}
2691
}
2690

    
   
2692

   
2691
/*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
2693
/*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
2692
 *
2694
 *
2693
 * This function sets pvt's outboundproxy pointer to the one referenced
2695
 * This function sets pvt's outboundproxy pointer to the one referenced
2694
 * by the proxy parameter. Because proxy may be a refcounted object, and
2696
 * by the proxy parameter. Because proxy may be a refcounted object, and
2695
 * because pvt's old outboundproxy may also be a refcounted object, we need
2697
 * because pvt's old outboundproxy may also be a refcounted object, we need
2696
 * to maintain the proper refcounts.
2698
 * to maintain the proper refcounts.
2697
 *
2699
 *
2698
 * \param pvt The sip_pvt for which we wish to set the outboundproxy
2700
 * \param pvt The sip_pvt for which we wish to set the outboundproxy
2699
 * \param proxy The sip_proxy which we will point pvt towards.
2701
 * \param proxy The sip_proxy which we will point pvt towards.
2700
 * \return Returns void
2702
 * \return Returns void
2701
 */
2703
 */
2702
static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
2704
static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
2703
{
2705
{
2704
	struct sip_proxy *old_obproxy = pvt->outboundproxy;
2706
	struct sip_proxy *old_obproxy = pvt->outboundproxy;
2705
	/* The sip_cfg.outboundproxy is statically allocated, and so
2707
	/* The sip_cfg.outboundproxy is statically allocated, and so
2706
	 * we don't ever need to adjust refcounts for it
2708
	 * we don't ever need to adjust refcounts for it
2707
	 */
2709
	 */
2708
	if (proxy && proxy != &sip_cfg.outboundproxy) {
2710
	if (proxy && proxy != &sip_cfg.outboundproxy) {
2709
		ao2_ref(proxy, +1);
2711
		ao2_ref(proxy, +1);
2710
	}
2712
	}
2711
	pvt->outboundproxy = proxy;
2713
	pvt->outboundproxy = proxy;
2712
	if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
2714
	if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
2713
		ao2_ref(old_obproxy, -1);
2715
		ao2_ref(old_obproxy, -1);
2714
	}
2716
	}
2715
}
2717
}
2716

    
   
2718

   
2717
 /*!
2719
 /*!
2718
 * \brief Unlink a dialog from the dialogs_checkrtp container
2720
 * \brief Unlink a dialog from the dialogs_checkrtp container
2719
 */
2721
 */
2720
static void *dialog_unlink_rtpcheck(struct sip_pvt *dialog)
2722
static void *dialog_unlink_rtpcheck(struct sip_pvt *dialog)
2721
{
2723
{
2722
	ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
2724
	ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
2723
	return NULL;
2725
	return NULL;
2724
}
2726
}
2725

    
   
2727

   
2726
/*!
2728
/*!
2727
 * \brief Unlink a dialog from the dialogs container, as well as any other places
2729
 * \brief Unlink a dialog from the dialogs container, as well as any other places
2728
 * that it may be currently stored.
2730
 * that it may be currently stored.
2729
 *
2731
 *
2730
 * \note A reference to the dialog must be held before calling this function, and this
2732
 * \note A reference to the dialog must be held before calling this function, and this
2731
 * function does not release that reference.
2733
 * function does not release that reference.
2732
 */
2734
 */
2733
void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
2735
void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
2734
{
2736
{
2735
	struct sip_pkt *cp;
2737
	struct sip_pkt *cp;
2736

    
   
2738

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

    
   
2740

   
2739
	ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
2741
	ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
2740
	ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
2742
	ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
2741
	ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
2743
	ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
2742

    
   
2744

   
2743
	/* Unlink us from the owner (channel) if we have one */
2745
	/* Unlink us from the owner (channel) if we have one */
2744
	if (dialog->owner) {
2746
	if (dialog->owner) {
2745
		if (lockowner) {
2747
		if (lockowner) {
2746
			ast_channel_lock(dialog->owner);
2748
			ast_channel_lock(dialog->owner);
2747
		}
2749
		}
2748
		ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2750
		ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2749
		dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
2751
		dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
2750
		if (lockowner) {
2752
		if (lockowner) {
2751
			ast_channel_unlock(dialog->owner);
2753
			ast_channel_unlock(dialog->owner);
2752
		}
2754
		}
2753
	}
2755
	}
2754
	if (dialog->registry) {
2756
	if (dialog->registry) {
2755
		if (dialog->registry->call == dialog) {
2757
		if (dialog->registry->call == dialog) {
2756
			dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
2758
			dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
2757
		}
2759
		}
2758
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2760
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2759
	}
2761
	}
2760
	if (dialog->stateid > -1) {
2762
	if (dialog->stateid > -1) {
2761
		ast_extension_state_del(dialog->stateid, NULL);
2763
		ast_extension_state_del(dialog->stateid, NULL);
2762
		dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
2764
		dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
2763
		dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2765
		dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2764
	}
2766
	}
2765
	/* Remove link from peer to subscription of MWI */
2767
	/* Remove link from peer to subscription of MWI */
2766
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
2768
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
2767
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2769
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2768
	}
2770
	}
2769
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
2771
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
2770
		dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
2772
		dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
2771
	}
2773
	}
2772

    
   
2774

   
2773
	/* remove all current packets in this dialog */
2775
	/* remove all current packets in this dialog */
2774
	while((cp = dialog->packets)) {
2776
	while((cp = dialog->packets)) {
2775
		dialog->packets = dialog->packets->next;
2777
		dialog->packets = dialog->packets->next;
2776
		AST_SCHED_DEL(sched, cp->retransid);
2778
		AST_SCHED_DEL(sched, cp->retransid);
2777
		dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
2779
		dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
2778
		if (cp->data) {
2780
		if (cp->data) {
2779
			ast_free(cp->data);
2781
			ast_free(cp->data);
2780
		}
2782
		}
2781
		ast_free(cp);
2783
		ast_free(cp);
2782
	}
2784
	}
2783

    
   
2785

   
2784
	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"));
2786
	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"));
2785

    
   
2787

   
2786
	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"));
2788
	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"));
2787
	
2789
	
2788
	if (dialog->autokillid > -1) {
2790
	if (dialog->autokillid > -1) {
2789
		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"));
2791
		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"));
2790
	}
2792
	}
2791

    
   
2793

   
2792
	if (dialog->request_queue_sched_id > -1) {
2794
	if (dialog->request_queue_sched_id > -1) {
2793
		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"));
2795
		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"));
2794
	}
2796
	}
2795

    
   
2797

   
2796
	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"));
2798
	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"));
2797

    
   
2799

   
2798
	if (dialog->t38id > -1) {
2800
	if (dialog->t38id > -1) {
2799
		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"));
2801
		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"));
2800
	}
2802
	}
2801

    
   
2803

   
2802
	dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
2804
	dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
2803
	return NULL;
2805
	return NULL;
2804
}
2806
}
2805

    
   
2807

   
2806
void *registry_unref(struct sip_registry *reg, char *tag)
2808
void *registry_unref(struct sip_registry *reg, char *tag)
2807
{
2809
{
2808
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
2810
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
2809
	ASTOBJ_UNREF(reg, sip_registry_destroy);
2811
	ASTOBJ_UNREF(reg, sip_registry_destroy);
2810
	return NULL;
2812
	return NULL;
2811
}
2813
}
2812

    
   
2814

   
2813
/*! \brief Add object reference to SIP registry */
2815
/*! \brief Add object reference to SIP registry */
2814
static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
2816
static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
2815
{
2817
{
2816
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
2818
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
2817
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
2819
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
2818
}
2820
}
2819

    
   
2821

   
2820
/*! \brief Interface structure with callbacks used to connect to UDPTL module*/
2822
/*! \brief Interface structure with callbacks used to connect to UDPTL module*/
2821
static struct ast_udptl_protocol sip_udptl = {
2823
static struct ast_udptl_protocol sip_udptl = {
2822
	type: "SIP",
2824
	type: "SIP",
2823
	get_udptl_info: sip_get_udptl_peer,
2825
	get_udptl_info: sip_get_udptl_peer,
2824
	set_udptl_peer: sip_set_udptl_peer,
2826
	set_udptl_peer: sip_set_udptl_peer,
2825
};
2827
};
2826

    
   
2828

   
2827
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2829
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2828
	__attribute__((format(printf, 2, 3)));
2830
	__attribute__((format(printf, 2, 3)));
2829

    
   
2831

   
2830

    
   
2832

   
2831
/*! \brief Convert transfer status to string */
2833
/*! \brief Convert transfer status to string */
2832
static const char *referstatus2str(enum referstatus rstatus)
2834
static const char *referstatus2str(enum referstatus rstatus)
2833
{
2835
{
2834
	return map_x_s(referstatusstrings, rstatus, "");
2836
	return map_x_s(referstatusstrings, rstatus, "");
2835
}
2837
}
2836

    
   
2838

   
2837
static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
2839
static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
2838
{
2840
{
2839
	if (pvt->final_destruction_scheduled) {
2841
	if (pvt->final_destruction_scheduled) {
2840
		return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
2842
		return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
2841
	}
2843
	}
2842
	if(pvt->needdestroy != 1) {
2844
	if(pvt->needdestroy != 1) {
2843
		ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
2845
		ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
2844
	}
2846
	}
2845
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
2847
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
2846
	pvt->needdestroy = 1;
2848
	pvt->needdestroy = 1;
2847
}
2849
}
2848

    
   
2850

   
2849
/*! \brief Initialize the initital request packet in the pvt structure.
2851
/*! \brief Initialize the initital request packet in the pvt structure.
2850
 	This packet is used for creating replies and future requests in
2852
 	This packet is used for creating replies and future requests in
2851
	a dialog */
2853
	a dialog */
2852
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
2854
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
2853
{
2855
{
2854
	if (p->initreq.headers) {
2856
	if (p->initreq.headers) {
2855
		ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
2857
		ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
2856
	} else {
2858
	} else {
2857
		ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
2859
		ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
2858
	}
2860
	}
2859
	/* Use this as the basis */
2861
	/* Use this as the basis */
2860
	copy_request(&p->initreq, req);
2862
	copy_request(&p->initreq, req);
2861
	parse_request(&p->initreq);
2863
	parse_request(&p->initreq);
2862
	if (req->debug) {
2864
	if (req->debug) {
2863
		ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
2865
		ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
2864
	}
2866
	}
2865
}
2867
}
2866

    
   
2868

   
2867
/*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
2869
/*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
2868
static void sip_alreadygone(struct sip_pvt *dialog)
2870
static void sip_alreadygone(struct sip_pvt *dialog)
2869
{
2871
{
2870
	ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
2872
	ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
2871
	dialog->alreadygone = 1;
2873
	dialog->alreadygone = 1;
2872
}
2874
}
2873

    
   
2875

   
2874
/*! Resolve DNS srv name or host name in a sip_proxy structure */
2876
/*! Resolve DNS srv name or host name in a sip_proxy structure */
2875
static int proxy_update(struct sip_proxy *proxy)
2877
static int proxy_update(struct sip_proxy *proxy)
2876
{
2878
{
2877
	/* if it's actually an IP address and not a name,
2879
	/* if it's actually an IP address and not a name,
2878
           there's no need for a managed lookup */
2880
           there's no need for a managed lookup */
2879
	if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
2881
	if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
2880
		/* Ok, not an IP address, then let's check if it's a domain or host */
2882
		/* Ok, not an IP address, then let's check if it's a domain or host */
2881
		/* XXX Todo - if we have proxy port, don't do SRV */
2883
		/* XXX Todo - if we have proxy port, don't do SRV */
2882
		proxy->ip.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
2884
		proxy->ip.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
2883
		if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
2885
		if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
2884
				ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2886
				ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2885
				return FALSE;
2887
				return FALSE;
2886
		}
2888
		}
2887

    
   
2889

   
2888
	}
2890
	}
2889

    
   
2891

   
2890
	ast_sockaddr_set_port(&proxy->ip, proxy->port);
2892
	ast_sockaddr_set_port(&proxy->ip, proxy->port);
2891

    
   
2893

   
2892
	proxy->last_dnsupdate = time(NULL);
2894
	proxy->last_dnsupdate = time(NULL);
2893
	return TRUE;
2895
	return TRUE;
2894
}
2896
}
2895

    
   
2897

   
2896
/*! \brief converts ascii port to int representation. If no
2898
/*! \brief converts ascii port to int representation. If no
2897
 *  pt buffer is provided or the pt has errors when being converted
2899
 *  pt buffer is provided or the pt has errors when being converted
2898
 *  to an int value, the port provided as the standard is used.
2900
 *  to an int value, the port provided as the standard is used.
2899
 */
2901
 */
2900
unsigned int port_str2int(const char *pt, unsigned int standard)
2902
unsigned int port_str2int(const char *pt, unsigned int standard)
2901
{
2903
{
2902
	int port = standard;
2904
	int port = standard;
2903
	if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
2905
	if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
2904
		port = standard;
2906
		port = standard;
2905
	}
2907
	}
2906

    
   
2908

   
2907
	return port;
2909
	return port;
2908
}
2910
}
2909

    
   
2911

   
2910
/*! \brief Get default outbound proxy or global proxy */
2912
/*! \brief Get default outbound proxy or global proxy */
2911
static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2913
static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2912
{
2914
{
2913
	if (peer && peer->outboundproxy) {
2915
	if (peer && peer->outboundproxy) {
2914
		if (sipdebug) {
2916
		if (sipdebug) {
2915
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2917
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2916
		}
2918
		}
2917
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2919
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2918
		return peer->outboundproxy;
2920
		return peer->outboundproxy;
2919
	}
2921
	}
2920
	if (sip_cfg.outboundproxy.name[0]) {
2922
	if (sip_cfg.outboundproxy.name[0]) {
2921
		if (sipdebug) {
2923
		if (sipdebug) {
2922
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2924
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2923
		}
2925
		}
2924
		append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
2926
		append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
2925
		return &sip_cfg.outboundproxy;
2927
		return &sip_cfg.outboundproxy;
2926
	}
2928
	}
2927
	if (sipdebug) {
2929
	if (sipdebug) {
2928
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2930
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2929
	}
2931
	}
2930
	return NULL;
2932
	return NULL;
2931
}
2933
}
2932

    
   
2934

   
2933
/*! \brief returns true if 'name' (with optional trailing whitespace)
2935
/*! \brief returns true if 'name' (with optional trailing whitespace)
2934
 * matches the sip method 'id'.
2936
 * matches the sip method 'id'.
2935
 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2937
 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2936
 * a case-insensitive comparison to be more tolerant.
2938
 * a case-insensitive comparison to be more tolerant.
2937
 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2939
 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2938
 */
2940
 */
2939
static int method_match(enum sipmethod id, const char *name)
2941
static int method_match(enum sipmethod id, const char *name)
2940
{
2942
{
2941
	int len = strlen(sip_methods[id].text);
2943
	int len = strlen(sip_methods[id].text);
2942
	int l_name = name ? strlen(name) : 0;
2944
	int l_name = name ? strlen(name) : 0;
2943
	/* true if the string is long enough, and ends with whitespace, and matches */
2945
	/* true if the string is long enough, and ends with whitespace, and matches */
2944
	return (l_name >= len && name[len] < 33 &&
2946
	return (l_name >= len && name[len] < 33 &&
2945
		!strncasecmp(sip_methods[id].text, name, len));
2947
		!strncasecmp(sip_methods[id].text, name, len));
2946
}
2948
}
2947

    
   
2949

   
2948
/*! \brief  find_sip_method: Find SIP method from header */
2950
/*! \brief  find_sip_method: Find SIP method from header */
2949
static int find_sip_method(const char *msg)
2951
static int find_sip_method(const char *msg)
2950
{
2952
{
2951
	int i, res = 0;
2953
	int i, res = 0;
2952
	
2954
	
2953
	if (ast_strlen_zero(msg)) {
2955
	if (ast_strlen_zero(msg)) {
2954
		return 0;
2956
		return 0;
2955
	}
2957
	}
2956
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
2958
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
2957
		if (method_match(i, msg)) {
2959
		if (method_match(i, msg)) {
2958
			res = sip_methods[i].id;
2960
			res = sip_methods[i].id;
2959
		}
2961
		}
2960
	}
2962
	}
2961
	return res;
2963
	return res;
2962
}
2964
}
2963

    
   
2965

   
2964
/*! \brief See if we pass debug IP filter */
2966
/*! \brief See if we pass debug IP filter */
2965
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
2967
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
2966
{
2968
{
2967
	/* Can't debug if sipdebug is not enabled */
2969
	/* Can't debug if sipdebug is not enabled */
2968
	if (!sipdebug) {
2970
	if (!sipdebug) {
2969
		return 0;
2971
		return 0;
2970
	}
2972
	}
2971

    
   
2973

   
2972
	/* A null debug_addr means we'll debug any address */
2974
	/* A null debug_addr means we'll debug any address */
2973
	if (ast_sockaddr_isnull(&debugaddr)) {
2975
	if (ast_sockaddr_isnull(&debugaddr)) {
2974
		return 1;
2976
		return 1;
2975
	}
2977
	}
2976

    
   
2978

   
2977
	/* If no port was specified for a debug address, just compare the
2979
	/* If no port was specified for a debug address, just compare the
2978
	 * addresses, otherwise compare the address and port
2980
	 * addresses, otherwise compare the address and port
2979
	 */
2981
	 */
2980
	if (ast_sockaddr_port(&debugaddr)) {
2982
	if (ast_sockaddr_port(&debugaddr)) {
2981
		return !ast_sockaddr_cmp(&debugaddr, addr);
2983
		return !ast_sockaddr_cmp(&debugaddr, addr);
2982
	} else {
2984
	} else {
2983
		return !ast_sockaddr_cmp_addr(&debugaddr, addr);
2985
		return !ast_sockaddr_cmp_addr(&debugaddr, addr);
2984
	}
2986
	}
2985
}
2987
}
2986

    
   
2988

   
2987
/*! \brief The real destination address for a write */
2989
/*! \brief The real destination address for a write */
2988
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
2990
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
2989
{
2991
{
2990
	if (p->outboundproxy) {
2992
	if (p->outboundproxy) {
2991
		return &p->outboundproxy->ip;
2993
		return &p->outboundproxy->ip;
2992
	}
2994
	}
2993

    
   
2995

   
2994
	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;
2996
	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;
2995
}
2997
}
2996

    
   
2998

   
2997
/*! \brief Display SIP nat mode */
2999
/*! \brief Display SIP nat mode */
2998
static const char *sip_nat_mode(const struct sip_pvt *p)
3000
static const char *sip_nat_mode(const struct sip_pvt *p)
2999
{
3001
{
3000
	return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
3002
	return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
3001
}
3003
}
3002

    
   
3004

   
3003
/*! \brief Test PVT for debugging output */
3005
/*! \brief Test PVT for debugging output */
3004
static inline int sip_debug_test_pvt(struct sip_pvt *p)
3006
static inline int sip_debug_test_pvt(struct sip_pvt *p)
3005
{
3007
{
3006
	if (!sipdebug) {
3008
	if (!sipdebug) {
3007
		return 0;
3009
		return 0;
3008
	}
3010
	}
3009
	return sip_debug_test_addr(sip_real_dst(p));
3011
	return sip_debug_test_addr(sip_real_dst(p));
3010
}
3012
}
3011

    
   
3013

   
3012
/*! \brief Return int representing a bit field of transport types found in const char *transport */
3014
/*! \brief Return int representing a bit field of transport types found in const char *transport */
3013
static int get_transport_str2enum(const char *transport)
3015
static int get_transport_str2enum(const char *transport)
3014
{
3016
{
3015
	int res = 0;
3017
	int res = 0;
3016

    
   
3018

   
3017
	if (ast_strlen_zero(transport)) {
3019
	if (ast_strlen_zero(transport)) {
3018
		return res;
3020
		return res;
3019
	}
3021
	}
3020

    
   
3022

   
3021
	if (!strcasecmp(transport, "udp")) {
3023
	if (!strcasecmp(transport, "udp")) {
3022
		res |= SIP_TRANSPORT_UDP;
3024
		res |= SIP_TRANSPORT_UDP;
3023
	}
3025
	}
3024
	if (!strcasecmp(transport, "tcp")) {
3026
	if (!strcasecmp(transport, "tcp")) {
3025
		res |= SIP_TRANSPORT_TCP;
3027
		res |= SIP_TRANSPORT_TCP;
3026
	}
3028
	}
3027
	if (!strcasecmp(transport, "tls")) {
3029
	if (!strcasecmp(transport, "tls")) {
3028
		res |= SIP_TRANSPORT_TLS;
3030
		res |= SIP_TRANSPORT_TLS;
3029
	}
3031
	}
3030

    
   
3032

   
3031
	return res;
3033
	return res;
3032
}
3034
}
3033

    
   
3035

   
3034
/*! \brief Return configuration of transports for a device */
3036
/*! \brief Return configuration of transports for a device */
3035
static inline const char *get_transport_list(unsigned int transports) {
3037
static inline const char *get_transport_list(unsigned int transports) {
3036
	switch (transports) {
3038
	switch (transports) {
3037
		case SIP_TRANSPORT_UDP:
3039
		case SIP_TRANSPORT_UDP:
3038
			return "UDP";
3040
			return "UDP";
3039
		case SIP_TRANSPORT_TCP:
3041
		case SIP_TRANSPORT_TCP:
3040
			return "TCP";
3042
			return "TCP";
3041
		case SIP_TRANSPORT_TLS:
3043
		case SIP_TRANSPORT_TLS:
3042
			return "TLS";
3044
			return "TLS";
3043
		case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
3045
		case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
3044
			return "TCP,UDP";
3046
			return "TCP,UDP";
3045
		case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
3047
		case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
3046
			return "TLS,UDP";
3048
			return "TLS,UDP";
3047
		case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
3049
		case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
3048
			return "TLS,TCP";
3050
			return "TLS,TCP";
3049
		default:
3051
		default:
3050
			return transports ?
3052
			return transports ?
3051
				"TLS,TCP,UDP" : "UNKNOWN";	
3053
				"TLS,TCP,UDP" : "UNKNOWN";	
3052
	}
3054
	}
3053
}
3055
}
3054

    
   
3056

   
3055
/*! \brief Return transport as string */
3057
/*! \brief Return transport as string */
3056
static inline const char *get_transport(enum sip_transport t)
3058
static inline const char *get_transport(enum sip_transport t)
3057
{
3059
{
3058
	switch (t) {
3060
	switch (t) {
3059
	case SIP_TRANSPORT_UDP:
3061
	case SIP_TRANSPORT_UDP:
3060
		return "UDP";
3062
		return "UDP";
3061
	case SIP_TRANSPORT_TCP:
3063
	case SIP_TRANSPORT_TCP:
3062
		return "TCP";
3064
		return "TCP";
3063
	case SIP_TRANSPORT_TLS:
3065
	case SIP_TRANSPORT_TLS:
3064
		return "TLS";
3066
		return "TLS";
3065
	}
3067
	}
3066

    
   
3068

   
3067
	return "UNKNOWN";
3069
	return "UNKNOWN";
3068
}
3070
}
3069

    
   
3071

   
3070
/*! \brief Return protocol string for srv dns query */
3072
/*! \brief Return protocol string for srv dns query */
3071
static inline const char *get_srv_protocol(enum sip_transport t)
3073
static inline const char *get_srv_protocol(enum sip_transport t)
3072
{
3074
{
3073
	switch (t) {
3075
	switch (t) {
3074
	case SIP_TRANSPORT_UDP:
3076
	case SIP_TRANSPORT_UDP:
3075
		return "udp";
3077
		return "udp";
3076
	case SIP_TRANSPORT_TLS:
3078
	case SIP_TRANSPORT_TLS:
3077
	case SIP_TRANSPORT_TCP:
3079
	case SIP_TRANSPORT_TCP:
3078
		return "tcp";
3080
		return "tcp";
3079
	}
3081
	}
3080

    
   
3082

   
3081
	return "udp";
3083
	return "udp";
3082
}
3084
}
3083

    
   
3085

   
3084
/*! \brief Return service string for srv dns query */
3086
/*! \brief Return service string for srv dns query */
3085
static inline const char *get_srv_service(enum sip_transport t)
3087
static inline const char *get_srv_service(enum sip_transport t)
3086
{
3088
{
3087
	switch (t) {
3089
	switch (t) {
3088
	case SIP_TRANSPORT_TCP:
3090
	case SIP_TRANSPORT_TCP:
3089
	case SIP_TRANSPORT_UDP:
3091
	case SIP_TRANSPORT_UDP:
3090
		return "sip";
3092
		return "sip";
3091
	case SIP_TRANSPORT_TLS:
3093
	case SIP_TRANSPORT_TLS:
3092
		return "sips";
3094
		return "sips";
3093
	}
3095
	}
3094
	return "sip";
3096
	return "sip";
3095
}
3097
}
3096

    
   
3098

   
3097
/*! \brief Return transport of dialog.
3099
/*! \brief Return transport of dialog.
3098
	\note this is based on a false assumption. We don't always use the
3100
	\note this is based on a false assumption. We don't always use the
3099
	outbound proxy for all requests in a dialog. It depends on the
3101
	outbound proxy for all requests in a dialog. It depends on the
3100
	"force" parameter. The FIRST request is always sent to the ob proxy.
3102
	"force" parameter. The FIRST request is always sent to the ob proxy.
3101
	\todo Fix this function to work correctly
3103
	\todo Fix this function to work correctly
3102
*/
3104
*/
3103
static inline const char *get_transport_pvt(struct sip_pvt *p)
3105
static inline const char *get_transport_pvt(struct sip_pvt *p)
3104
{
3106
{
3105
	if (p->outboundproxy && p->outboundproxy->transport) {
3107
	if (p->outboundproxy && p->outboundproxy->transport) {
3106
		set_socket_transport(&p->socket, p->outboundproxy->transport);
3108
		set_socket_transport(&p->socket, p->outboundproxy->transport);
3107
	}
3109
	}
3108

    
   
3110

   
3109
	return get_transport(p->socket.type);
3111
	return get_transport(p->socket.type);
3110
}
3112
}
3111

    
   
3113

   
3112
/*! \brief Transmit SIP message
3114
/*! \brief Transmit SIP message
3113
	Sends a SIP request or response on a given socket (in the pvt)
3115
	Sends a SIP request or response on a given socket (in the pvt)
3114
	Called by retrans_pkt, send_request, send_response and
3116
	Called by retrans_pkt, send_request, send_response and
3115
	__sip_reliable_xmit
3117
	__sip_reliable_xmit
3116
	\return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
3118
	\return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
3117
*/
3119
*/
3118
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
3120
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
3119
{
3121
{
3120
	int res = 0;
3122
	int res = 0;
3121
	const struct ast_sockaddr *dst = sip_real_dst(p);
3123
	const struct ast_sockaddr *dst = sip_real_dst(p);
3122

    
   
3124

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

    
   
3126

   
3125
	if (sip_prepare_socket(p) < 0) {
3127
	if (sip_prepare_socket(p) < 0) {
3126
		return XMIT_ERROR;
3128
		return XMIT_ERROR;
3127
	}
3129
	}
3128

    
   
3130

   
3129
	if (p->socket.type == SIP_TRANSPORT_UDP) {
3131
	if (p->socket.type == SIP_TRANSPORT_UDP) {
3130
		res = ast_sendto(p->socket.fd, data->str, len, 0, dst);
3132
		res = ast_sendto(p->socket.fd, data->str, len, 0, dst);
3131
	} else if (p->socket.tcptls_session) {
3133
	} else if (p->socket.tcptls_session) {
3132
		res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
3134
		res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
3133
	} else {
3135
	} else {
3134
		ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
3136
		ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
3135
		return XMIT_ERROR;
3137
		return XMIT_ERROR;
3136
	}
3138
	}
3137

    
   
3139

   
3138
	if (res == -1) {
3140
	if (res == -1) {
3139
		switch (errno) {
3141
		switch (errno) {
3140
		case EBADF: 		/* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
3142
		case EBADF: 		/* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
3141
		case EHOSTUNREACH: 	/* Host can't be reached */
3143
		case EHOSTUNREACH: 	/* Host can't be reached */
3142
		case ENETDOWN: 		/* Interface down */
3144
		case ENETDOWN: 		/* Interface down */
3143
		case ENETUNREACH:	/* Network failure */
3145
		case ENETUNREACH:	/* Network failure */
3144
		case ECONNREFUSED:      /* ICMP port unreachable */
3146
		case ECONNREFUSED:      /* ICMP port unreachable */
3145
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */
3147
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */
3146
		}
3148
		}
3147
	}
3149
	}
3148
	if (res != len) {
3150
	if (res != len) {
3149
		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));
3151
		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));
3150
	}
3152
	}
3151

    
   
3153

   
3152
	return res;
3154
	return res;
3153
}
3155
}
3154

    
   
3156

   
3155
/*! \brief Build a Via header for a request */
3157
/*! \brief Build a Via header for a request */
3156
static void build_via(struct sip_pvt *p)
3158
static void build_via(struct sip_pvt *p)
3157
{
3159
{
3158
	/* Work around buggy UNIDEN UIP200 firmware */
3160
	/* Work around buggy UNIDEN UIP200 firmware */
3159
	const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
3161
	const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
3160

    
   
3162

   
3161
	/* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
3163
	/* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
3162
	snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
3164
	snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
3163
		 get_transport_pvt(p),
3165
		 get_transport_pvt(p),
3164
		 ast_sockaddr_stringify(&p->ourip),
3166
		 ast_sockaddr_stringify(&p->ourip),
3165
		 (int) p->branch, rport);
3167
		 (int) p->branch, rport);
3166
}
3168
}
3167

    
   
3169

   
3168
/*! \brief NAT fix - decide which IP address to use for Asterisk server?
3170
/*! \brief NAT fix - decide which IP address to use for Asterisk server?
3169
 *
3171
 *
3170
 * Using the localaddr structure built up with localnet statements in sip.conf
3172
 * Using the localaddr structure built up with localnet statements in sip.conf
3171
 * apply it to their address to see if we need to substitute our
3173
 * apply it to their address to see if we need to substitute our
3172
 * externaddr or can get away with our internal bindaddr
3174
 * externaddr or can get away with our internal bindaddr
3173
 * 'us' is always overwritten.
3175
 * 'us' is always overwritten.
3174
 */
3176
 */
3175
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
3177
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
3176
{
3178
{
3177
	struct ast_sockaddr theirs;
3179
	struct ast_sockaddr theirs;
3178

    
   
3180

   
3179
	/* Set want_remap to non-zero if we want to remap 'us' to an externally
3181
	/* Set want_remap to non-zero if we want to remap 'us' to an externally
3180
	 * reachable IP address and port. This is done if:
3182
	 * reachable IP address and port. This is done if:
3181
	 * 1. we have a localaddr list (containing 'internal' addresses marked
3183
	 * 1. we have a localaddr list (containing 'internal' addresses marked
3182
	 *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
3184
	 *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
3183
	 *    and AST_SENSE_ALLOW on 'external' ones);
3185
	 *    and AST_SENSE_ALLOW on 'external' ones);
3184
	 * 2. externaddr is set, so we know what to use as the
3186
	 * 2. externaddr is set, so we know what to use as the
3185
	 *    externally visible address;
3187
	 *    externally visible address;
3186
	 * 3. the remote address, 'them', is external;
3188
	 * 3. the remote address, 'them', is external;
3187
	 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
3189
	 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
3188
	 *    when passed to ast_apply_ha() so it does need to be remapped.
3190
	 *    when passed to ast_apply_ha() so it does need to be remapped.
3189
	 *    This fourth condition is checked later.
3191
	 *    This fourth condition is checked later.
3190
	 */
3192
	 */
3191
	int want_remap = 0;
3193
	int want_remap = 0;
3192

    
   
3194

   
3193
	ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
3195
	ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
3194
	/* now ask the system what would it use to talk to 'them' */
3196
	/* now ask the system what would it use to talk to 'them' */
3195
	ast_ouraddrfor(them, us);
3197
	ast_ouraddrfor(them, us);
3196
	ast_sockaddr_copy(&theirs, them);
3198
	ast_sockaddr_copy(&theirs, them);
3197

    
   
3199

   
3198
	if (ast_sockaddr_is_ipv6(&theirs)) {
3200
	if (ast_sockaddr_is_ipv6(&theirs)) {
3199
		if (localaddr && !ast_sockaddr_isnull(&externaddr)) {
3201
		if (localaddr && !ast_sockaddr_isnull(&externaddr)) {
3200
			ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
3202
			ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
3201
				"but we're using IPv6, which doesn't need it. Please "
3203
				"but we're using IPv6, which doesn't need it. Please "
3202
				"remove \"localnet\" and/or \"externaddr\" settings.\n");
3204
				"remove \"localnet\" and/or \"externaddr\" settings.\n");
3203
		}
3205
		}
3204
	} else {
3206
	} else {
3205
		want_remap = localaddr &&
3207
		want_remap = localaddr &&
3206
			!ast_sockaddr_isnull(&externaddr) &&
3208
			!ast_sockaddr_isnull(&externaddr) &&
3207
			ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
3209
			ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
3208
	}
3210
	}
3209

    
   
3211

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

    
   
3281

   
3280
/*! \brief Append to SIP dialog history with arg list  */
3282
/*! \brief Append to SIP dialog history with arg list  */
3281
static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
3283
static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
3282
{
3284
{
3283
	char buf[80], *c = buf; /* max history length */
3285
	char buf[80], *c = buf; /* max history length */
3284
	struct sip_history *hist;
3286
	struct sip_history *hist;
3285
	int l;
3287
	int l;
3286

    
   
3288

   
3287
	vsnprintf(buf, sizeof(buf), fmt, ap);
3289
	vsnprintf(buf, sizeof(buf), fmt, ap);
3288
	strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
3290
	strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
3289
	l = strlen(buf) + 1;
3291
	l = strlen(buf) + 1;
3290
	if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
3292
	if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
3291
		return;
3293
		return;
3292
	}
3294
	}
3293
	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
3295
	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
3294
		ast_free(hist);
3296
		ast_free(hist);
3295
		return;
3297
		return;
3296
	}
3298
	}
3297
	memcpy(hist->event, buf, l);
3299
	memcpy(hist->event, buf, l);
3298
	if (p->history_entries == MAX_HISTORY_ENTRIES) {
3300
	if (p->history_entries == MAX_HISTORY_ENTRIES) {
3299
		struct sip_history *oldest;
3301
		struct sip_history *oldest;
3300
		oldest = AST_LIST_REMOVE_HEAD(p->history, list);
3302
		oldest = AST_LIST_REMOVE_HEAD(p->history, list);
3301
		p->history_entries--;
3303
		p->history_entries--;
3302
		ast_free(oldest);
3304
		ast_free(oldest);
3303
	}
3305
	}
3304
	AST_LIST_INSERT_TAIL(p->history, hist, list);
3306
	AST_LIST_INSERT_TAIL(p->history, hist, list);
3305
	p->history_entries++;
3307
	p->history_entries++;
3306
}
3308
}
3307

    
   
3309

   
3308
/*! \brief Append to SIP dialog history with arg list  */
3310
/*! \brief Append to SIP dialog history with arg list  */
3309
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3311
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3310
{
3312
{
3311
	va_list ap;
3313
	va_list ap;
3312

    
   
3314

   
3313
	if (!p) {
3315
	if (!p) {
3314
		return;
3316
		return;
3315
	}
3317
	}
3316

    
   
3318

   
3317
	if (!p->do_history && !recordhistory && !dumphistory) {
3319
	if (!p->do_history && !recordhistory && !dumphistory) {
3318
		return;
3320
		return;
3319
	}
3321
	}
3320

    
   
3322

   
3321
	va_start(ap, fmt);
3323
	va_start(ap, fmt);
3322
	append_history_va(p, fmt, ap);
3324
	append_history_va(p, fmt, ap);
3323
	va_end(ap);
3325
	va_end(ap);
3324

    
   
3326

   
3325
	return;
3327
	return;
3326
}
3328
}
3327

    
   
3329

   
3328
/*! \brief Retransmit SIP message if no answer (Called from scheduler) */
3330
/*! \brief Retransmit SIP message if no answer (Called from scheduler) */
3329
static int retrans_pkt(const void *data)
3331
static int retrans_pkt(const void *data)
3330
{
3332
{
3331
	struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
3333
	struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
3332
	int reschedule = DEFAULT_RETRANS;
3334
	int reschedule = DEFAULT_RETRANS;
3333
	int xmitres = 0;
3335
	int xmitres = 0;
3334
	/* how many ms until retrans timeout is reached */
3336
	/* how many ms until retrans timeout is reached */
3335
	int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
3337
	int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
3336

    
   
3338

   
3337
	/* Do not retransmit if time out is reached. This will be negative if the time between
3339
	/* Do not retransmit if time out is reached. This will be negative if the time between
3338
	 * the first transmission and now is larger than our timeout period. This is a fail safe
3340
	 * the first transmission and now is larger than our timeout period. This is a fail safe
3339
	 * check in case the scheduler gets behind or the clock is changed. */
3341
	 * check in case the scheduler gets behind or the clock is changed. */
3340
	if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
3342
	if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
3341
		pkt->retrans_stop = 1;
3343
		pkt->retrans_stop = 1;
3342
	}
3344
	}
3343

    
   
3345

   
3344
	/* Lock channel PVT */
3346
	/* Lock channel PVT */
3345
	sip_pvt_lock(pkt->owner);
3347
	sip_pvt_lock(pkt->owner);
3346

    
   
3348

   
3347
	if (!pkt->retrans_stop) {
3349
	if (!pkt->retrans_stop) {
3348
		pkt->retrans++;
3350
		pkt->retrans++;
3349
		if (!pkt->timer_t1) {	/* Re-schedule using timer_a and timer_t1 */
3351
		if (!pkt->timer_t1) {	/* Re-schedule using timer_a and timer_t1 */
3350
			if (sipdebug) {
3352
			if (sipdebug) {
3351
				ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
3353
				ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
3352
					pkt->retransid,
3354
					pkt->retransid,
3353
					sip_methods[pkt->method].text,
3355
					sip_methods[pkt->method].text,
3354
					pkt->method);
3356
					pkt->method);
3355
			}
3357
			}
3356
		} else {
3358
		} else {
3357
			int siptimer_a;
3359
			int siptimer_a;
3358

    
   
3360

   
3359
			if (sipdebug) {
3361
			if (sipdebug) {
3360
				ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
3362
				ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
3361
					pkt->retransid,
3363
					pkt->retransid,
3362
					pkt->retrans,
3364
					pkt->retrans,
3363
					sip_methods[pkt->method].text,
3365
					sip_methods[pkt->method].text,
3364
					pkt->method);
3366
					pkt->method);
3365
			}
3367
			}
3366
			if (!pkt->timer_a) {
3368
			if (!pkt->timer_a) {
3367
				pkt->timer_a = 2 ;
3369
				pkt->timer_a = 2 ;
3368
			} else {
3370
			} else {
3369
				pkt->timer_a = 2 * pkt->timer_a;
3371
				pkt->timer_a = 2 * pkt->timer_a;
3370
			}
3372
			}
3371

    
   
3373

   
3372
			/* For non-invites, a maximum of 4 secs */
3374
			/* For non-invites, a maximum of 4 secs */
3373
			siptimer_a = pkt->timer_t1 * pkt->timer_a;	/* Double each time */
3375
			siptimer_a = pkt->timer_t1 * pkt->timer_a;	/* Double each time */
3374
			if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
3376
			if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
3375
				siptimer_a = 4000;
3377
				siptimer_a = 4000;
3376
			}
3378
			}
3377

    
   
3379

   
3378
			/* Reschedule re-transmit */
3380
			/* Reschedule re-transmit */
3379
			reschedule = siptimer_a;
3381
			reschedule = siptimer_a;
3380
			ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
3382
			ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
3381
				pkt->retrans + 1,
3383
				pkt->retrans + 1,
3382
				siptimer_a,
3384
				siptimer_a,
3383
				pkt->timer_t1,
3385
				pkt->timer_t1,
3384
				pkt->retransid);
3386
				pkt->retransid);
3385
		}
3387
		}
3386

    
   
3388

   
3387
		if (sip_debug_test_pvt(pkt->owner)) {
3389
		if (sip_debug_test_pvt(pkt->owner)) {
3388
			const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
3390
			const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
3389
			ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
3391
			ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
3390
				pkt->retrans, sip_nat_mode(pkt->owner),
3392
				pkt->retrans, sip_nat_mode(pkt->owner),
3391
				ast_sockaddr_stringify(dst),
3393
				ast_sockaddr_stringify(dst),
3392
				pkt->data->str);
3394
				pkt->data->str);
3393
		}
3395
		}
3394

    
   
3396

   
3395
		append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
3397
		append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
3396
		xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
3398
		xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
3397

    
   
3399

   
3398
		/* If there was no error during the network transmission, schedule the next retransmission,
3400
		/* If there was no error during the network transmission, schedule the next retransmission,
3399
		 * but if the next retransmission is going to be beyond our timeout period, mark the packet's
3401
		 * but if the next retransmission is going to be beyond our timeout period, mark the packet's
3400
		 * stop_retrans value and set the next retransmit to be the exact time of timeout.  This will
3402
		 * stop_retrans value and set the next retransmit to be the exact time of timeout.  This will
3401
		 * allow any responses to the packet to be processed before the packet is destroyed on the next
3403
		 * allow any responses to the packet to be processed before the packet is destroyed on the next
3402
		 * call to this function by the scheduler. */
3404
		 * call to this function by the scheduler. */
3403
		if (xmitres != XMIT_ERROR) {
3405
		if (xmitres != XMIT_ERROR) {
3404
			if (reschedule >= diff) {
3406
			if (reschedule >= diff) {
3405
				pkt->retrans_stop = 1;
3407
				pkt->retrans_stop = 1;
3406
				reschedule = diff;
3408
				reschedule = diff;
3407
			}
3409
			}
3408
			sip_pvt_unlock(pkt->owner);
3410
			sip_pvt_unlock(pkt->owner);
3409
			return  reschedule;
3411
			return  reschedule;
3410
		}
3412
		}
3411
	}
3413
	}
3412

    
   
3414

   
3413
	/* At this point, either the packet's retransmission timed out, or there was a
3415
	/* At this point, either the packet's retransmission timed out, or there was a
3414
	 * transmission error, either way destroy the scheduler item and this packet. */
3416
	 * transmission error, either way destroy the scheduler item and this packet. */
3415

    
   
3417

   
3416
	pkt->retransid = -1; /* Kill this scheduler item */
3418
	pkt->retransid = -1; /* Kill this scheduler item */
3417

    
   
3419

   
3418
	if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
3420
	if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
3419
		if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
3421
		if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
3420
			ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n"
3422
			ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n"
3421
				"Packet timed out after %dms with no response\n",
3423
				"Packet timed out after %dms with no response\n",
3422
				pkt->owner->callid,
3424
				pkt->owner->callid,
3423
				pkt->seqno,
3425
				pkt->seqno,
3424
				pkt->is_fatal ? "Critical" : "Non-critical",
3426
				pkt->is_fatal ? "Critical" : "Non-critical",
3425
				pkt->is_resp ? "Response" : "Request",
3427
				pkt->is_resp ? "Response" : "Request",
3426
				(int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
3428
				(int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
3427
		}
3429
		}
3428
	} else if (pkt->method == SIP_OPTIONS && sipdebug) {
3430
	} else if (pkt->method == SIP_OPTIONS && sipdebug) {
3429
		ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
3431
		ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
3430
	}
3432
	}
3431

    
   
3433

   
3432
	if (xmitres == XMIT_ERROR) {
3434
	if (xmitres == XMIT_ERROR) {
3433
		ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
3435
		ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
3434
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3436
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3435
	} else {
3437
	} else {
3436
		append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3438
		append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3437
	}
3439
	}
3438

    
   
3440

   
3439
	if (pkt->is_fatal) {
3441
	if (pkt->is_fatal) {
3440
		while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
3442
		while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
3441
			sip_pvt_unlock(pkt->owner);	/* SIP_PVT, not channel */
3443
			sip_pvt_unlock(pkt->owner);	/* SIP_PVT, not channel */
3442
			usleep(1);
3444
			usleep(1);
3443
			sip_pvt_lock(pkt->owner);
3445
			sip_pvt_lock(pkt->owner);
3444
		}
3446
		}
3445
		if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
3447
		if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
3446
			pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
3448
			pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
3447
		}
3449
		}
3448
		if (pkt->owner->owner) {
3450
		if (pkt->owner->owner) {
3449
			ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
3451
			ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
3450

    
   
3452

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

    
   
3475

   
3474
			/* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
3476
			/* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
3475
			if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
3477
			if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
3476
				pvt_set_needdestroy(pkt->owner, "no response to critical packet");
3478
				pvt_set_needdestroy(pkt->owner, "no response to critical packet");
3477
				sip_alreadygone(pkt->owner);
3479
				sip_alreadygone(pkt->owner);
3478
				append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
3480
				append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
3479
			}
3481
			}
3480
		}
3482
		}
3481
	}
3483
	}
3482

    
   
3484

   
3483
	if (pkt->method == SIP_BYE) {
3485
	if (pkt->method == SIP_BYE) {
3484
		/* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
3486
		/* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
3485
		if (pkt->owner->owner) {
3487
		if (pkt->owner->owner) {
3486
			ast_channel_unlock(pkt->owner->owner);
3488
			ast_channel_unlock(pkt->owner->owner);
3487
		}
3489
		}
3488
		append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
3490
		append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
3489
		pvt_set_needdestroy(pkt->owner, "no response to BYE");
3491
		pvt_set_needdestroy(pkt->owner, "no response to BYE");
3490
	}
3492
	}
3491

    
   
3493

   
3492
	/* Remove the packet */
3494
	/* Remove the packet */
3493
	for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
3495
	for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
3494
		if (cur == pkt) {
3496
		if (cur == pkt) {
3495
			UNLINK(cur, pkt->owner->packets, prev);
3497
			UNLINK(cur, pkt->owner->packets, prev);
3496
			sip_pvt_unlock(pkt->owner);
3498
			sip_pvt_unlock(pkt->owner);
3497
			if (pkt->owner) {
3499
			if (pkt->owner) {
3498
				pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3500
				pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3499
			}
3501
			}
3500
			if (pkt->data) {
3502
			if (pkt->data) {
3501
				ast_free(pkt->data);
3503
				ast_free(pkt->data);
3502
			}
3504
			}
3503
			pkt->data = NULL;
3505
			pkt->data = NULL;
3504
			ast_free(pkt);
3506
			ast_free(pkt);
3505
			return 0;
3507
			return 0;
3506
		}
3508
		}
3507
	}
3509
	}
3508
	/* error case */
3510
	/* error case */
3509
	ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
3511
	ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
3510
	sip_pvt_unlock(pkt->owner);
3512
	sip_pvt_unlock(pkt->owner);
3511
	return 0;
3513
	return 0;
3512
}
3514
}
3513

    
   
3515

   
3514
/*! \brief Transmit packet with retransmits
3516
/*! \brief Transmit packet with retransmits
3515
	\return 0 on success, -1 on failure to allocate packet
3517
	\return 0 on success, -1 on failure to allocate packet
3516
*/
3518
*/
3517
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)
3519
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)
3518
{
3520
{
3519
	struct sip_pkt *pkt = NULL;
3521
	struct sip_pkt *pkt = NULL;
3520
	int siptimer_a = DEFAULT_RETRANS;
3522
	int siptimer_a = DEFAULT_RETRANS;
3521
	int xmitres = 0;
3523
	int xmitres = 0;
3522
	int respid;
3524
	int respid;
3523

    
   
3525

   
3524
	if (sipmethod == SIP_INVITE) {
3526
	if (sipmethod == SIP_INVITE) {
3525
		/* Note this is a pending invite */
3527
		/* Note this is a pending invite */
3526
		p->pendinginvite = seqno;
3528
		p->pendinginvite = seqno;
3527
	}
3529
	}
3528

    
   
3530

   
3529
	/* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
3531
	/* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
3530
	/* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
3532
	/* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
3531
	/*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
3533
	/*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
3532
	if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
3534
	if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
3533
		xmitres = __sip_xmit(p, data, len);	/* Send packet */
3535
		xmitres = __sip_xmit(p, data, len);	/* Send packet */
3534
		if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
3536
		if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
3535
			append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
3537
			append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
3536
			return AST_FAILURE;
3538
			return AST_FAILURE;
3537
		} else {
3539
		} else {
3538
			return AST_SUCCESS;
3540
			return AST_SUCCESS;
3539
		}
3541
		}
3540
	}
3542
	}
3541

    
   
3543

   
3542
	if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1))) {
3544
	if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1))) {
3543
		return AST_FAILURE;
3545
		return AST_FAILURE;
3544
	}
3546
	}
3545
	/* copy data, add a terminator and save length */
3547
	/* copy data, add a terminator and save length */
3546
	if (!(pkt->data = ast_str_create(len))) {
3548
	if (!(pkt->data = ast_str_create(len))) {
3547
		ast_free(pkt);
3549
		ast_free(pkt);
3548
		return AST_FAILURE;
3550
		return AST_FAILURE;
3549
	}
3551
	}
3550
	ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
3552
	ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
3551
	pkt->packetlen = len;
3553
	pkt->packetlen = len;
3552
	/* copy other parameters from the caller */
3554
	/* copy other parameters from the caller */
3553
	pkt->method = sipmethod;
3555
	pkt->method = sipmethod;
3554
	pkt->seqno = seqno;
3556
	pkt->seqno = seqno;
3555
	pkt->is_resp = resp;
3557
	pkt->is_resp = resp;
3556
	pkt->is_fatal = fatal;
3558
	pkt->is_fatal = fatal;
3557
	pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
3559
	pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
3558
	pkt->next = p->packets;
3560
	pkt->next = p->packets;
3559
	p->packets = pkt;	/* Add it to the queue */
3561
	p->packets = pkt;	/* Add it to the queue */
3560
	if (resp) {
3562
	if (resp) {
3561
		/* Parse out the response code */
3563
		/* Parse out the response code */
3562
		if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
3564
		if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
3563
			pkt->response_code = respid;
3565
			pkt->response_code = respid;
3564
		}
3566
		}
3565
	}
3567
	}
3566
	pkt->timer_t1 = p->timer_t1;	/* Set SIP timer T1 */
3568
	pkt->timer_t1 = p->timer_t1;	/* Set SIP timer T1 */
3567
	pkt->retransid = -1;
3569
	pkt->retransid = -1;
3568
	if (pkt->timer_t1) {
3570
	if (pkt->timer_t1) {
3569
		siptimer_a = pkt->timer_t1;
3571
		siptimer_a = pkt->timer_t1;
3570
	}
3572
	}
3571

    
   
3573

   
3572
	pkt->time_sent = ast_tvnow(); /* time packet was sent */
3574
	pkt->time_sent = ast_tvnow(); /* time packet was sent */
3573
	pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
3575
	pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
3574

    
   
3576

   
3575
	/* Schedule retransmission */
3577
	/* Schedule retransmission */
3576
	AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
3578
	AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
3577
	if (sipdebug) {
3579
	if (sipdebug) {
3578
		ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
3580
		ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
3579
	}
3581
	}
3580

    
   
3582

   
3581
	xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);	/* Send packet */
3583
	xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);	/* Send packet */
3582

    
   
3584

   
3583
	if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
3585
	if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
3584
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3586
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3585
		ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
3587
		ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
3586
		AST_SCHED_DEL(sched, pkt->retransid);
3588
		AST_SCHED_DEL(sched, pkt->retransid);
3587
		p->packets = pkt->next;
3589
		p->packets = pkt->next;
3588
		pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3590
		pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3589
		ast_free(pkt->data);
3591
		ast_free(pkt->data);
3590
		ast_free(pkt);
3592
		ast_free(pkt);
3591
		return AST_FAILURE;
3593
		return AST_FAILURE;
3592
	} else {
3594
	} else {
3593
		/* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
3595
		/* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
3594
		 * only wakes up every 1000ms by default, we have to poke the thread here to make
3596
		 * only wakes up every 1000ms by default, we have to poke the thread here to make
3595
		 * sure it successfully detects this must be retransmitted in less time than
3597
		 * sure it successfully detects this must be retransmitted in less time than
3596
		 * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
3598
		 * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
3597
		if (monitor_thread != AST_PTHREADT_NULL) {
3599
		if (monitor_thread != AST_PTHREADT_NULL) {
3598
			pthread_kill(monitor_thread, SIGURG);
3600
			pthread_kill(monitor_thread, SIGURG);
3599
		}
3601
		}
3600
		return AST_SUCCESS;
3602
		return AST_SUCCESS;
3601
	}
3603
	}
3602
}
3604
}
3603

    
   
3605

   
3604
/*! \brief Kill a SIP dialog (called only by the scheduler)
3606
/*! \brief Kill a SIP dialog (called only by the scheduler)
3605
 * The scheduler has a reference to this dialog when p->autokillid != -1,
3607
 * The scheduler has a reference to this dialog when p->autokillid != -1,
3606
 * and we are called using that reference. So if the event is not
3608
 * and we are called using that reference. So if the event is not
3607
 * rescheduled, we need to call dialog_unref().
3609
 * rescheduled, we need to call dialog_unref().
3608
 */
3610
 */
3609
static int __sip_autodestruct(const void *data)
3611
static int __sip_autodestruct(const void *data)
3610
{
3612
{
3611
	struct sip_pvt *p = (struct sip_pvt *)data;
3613
	struct sip_pvt *p = (struct sip_pvt *)data;
3612

    
   
3614

   
3613
	/* If this is a subscription, tell the phone that we got a timeout */
3615
	/* If this is a subscription, tell the phone that we got a timeout */
3614
	if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
3616
	if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
3615
		transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);	/* Send last notification */
3617
		transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);	/* Send last notification */
3616
		p->subscribed = NONE;
3618
		p->subscribed = NONE;
3617
		append_history(p, "Subscribestatus", "timeout");
3619
		append_history(p, "Subscribestatus", "timeout");
3618
		ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
3620
		ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
3619
		return 10000;	/* Reschedule this destruction so that we know that it's gone */
3621
		return 10000;	/* Reschedule this destruction so that we know that it's gone */
3620
	}
3622
	}
3621

    
   
3623

   
3622
	/* If there are packets still waiting for delivery, delay the destruction */
3624
	/* If there are packets still waiting for delivery, delay the destruction */
3623
	if (p->packets) {
3625
	if (p->packets) {
3624
		if (!p->needdestroy) {
3626
		if (!p->needdestroy) {
3625
			char method_str[31];
3627
			char method_str[31];
3626
			ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
3628
			ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
3627
			append_history(p, "ReliableXmit", "timeout");
3629
			append_history(p, "ReliableXmit", "timeout");
3628
			if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
3630
			if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
3629
				if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
3631
				if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
3630
					pvt_set_needdestroy(p, "autodestruct");
3632
					pvt_set_needdestroy(p, "autodestruct");
3631
				}
3633
				}
3632
			}
3634
			}
3633
			return 10000;
3635
			return 10000;
3634
		} else {
3636
		} else {
3635
			/* They've had their chance to respond. Time to bail */
3637
			/* They've had their chance to respond. Time to bail */
3636
			__sip_pretend_ack(p);
3638
			__sip_pretend_ack(p);
3637
		}
3639
		}
3638
	}
3640
	}
3639

    
   
3641

   
3640
	/* Reset schedule ID */
3642
	/* Reset schedule ID */
3641
	p->autokillid = -1;
3643
	p->autokillid = -1;
3642

    
   
3644

   
3643

    
   
3645

   
3644
	/*
3646
	/*
3645
	 * Lock both the pvt and the channel safely so that we can queue up a frame.
3647
	 * Lock both the pvt and the channel safely so that we can queue up a frame.
3646
	 */
3648
	 */
3647
	sip_pvt_lock(p);
3649
	sip_pvt_lock(p);
3648
	while (p->owner && ast_channel_trylock(p->owner)) {
3650
	while (p->owner && ast_channel_trylock(p->owner)) {
3649
		sip_pvt_unlock(p);
3651
		sip_pvt_unlock(p);
3650
		sched_yield();
3652
		sched_yield();
3651
		sip_pvt_lock(p);
3653
		sip_pvt_lock(p);
3652
	}
3654
	}
3653

    
   
3655

   
3654
	if (p->owner) {
3656
	if (p->owner) {
3655
		ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
3657
		ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
3656
		ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
3658
		ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
3657
		ast_channel_unlock(p->owner);
3659
		ast_channel_unlock(p->owner);
3658
	} else if (p->refer && !p->alreadygone) {
3660
	} else if (p->refer && !p->alreadygone) {
3659
		ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
3661
		ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
3660
		transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3662
		transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3661
		append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
3663
		append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
3662
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3664
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3663
	} else {
3665
	} else {
3664
		append_history(p, "AutoDestroy", "%s", p->callid);
3666
		append_history(p, "AutoDestroy", "%s", p->callid);
3665
		ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
3667
		ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
3666
		dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
3668
		dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
3667
		/* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
3669
		/* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
3668
		/* sip_destroy(p); */		/* Go ahead and destroy dialog. All attempts to recover is done */
3670
		/* sip_destroy(p); */		/* Go ahead and destroy dialog. All attempts to recover is done */
3669
		/* sip_destroy also absorbs the reference */
3671
		/* sip_destroy also absorbs the reference */
3670
	}
3672
	}
3671

    
   
3673

   
3672
	sip_pvt_unlock(p);
3674
	sip_pvt_unlock(p);
3673

    
   
3675

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

    
   
3677

   
3676
	return 0;
3678
	return 0;
3677
}
3679
}
3678

    
   
3680

   
3679
/*! \brief Schedule final destruction of SIP dialog.  This can not be canceled.
3681
/*! \brief Schedule final destruction of SIP dialog.  This can not be canceled.
3680
 *  This function is used to keep a dialog around for a period of time in order
3682
 *  This function is used to keep a dialog around for a period of time in order
3681
 *  to properly respond to any retransmits. */
3683
 *  to properly respond to any retransmits. */
3682
void sip_scheddestroy_final(struct sip_pvt *p, int ms)
3684
void sip_scheddestroy_final(struct sip_pvt *p, int ms)
3683
{
3685
{
3684
	if (p->final_destruction_scheduled) {
3686
	if (p->final_destruction_scheduled) {
3685
		return; /* already set final destruction */
3687
		return; /* already set final destruction */
3686
	}
3688
	}
3687

    
   
3689

   
3688
	sip_scheddestroy(p, ms);
3690
	sip_scheddestroy(p, ms);
3689
	if (p->autokillid != -1) {
3691
	if (p->autokillid != -1) {
3690
		p->final_destruction_scheduled = 1;
3692
		p->final_destruction_scheduled = 1;
3691
	}
3693
	}
3692
}
3694
}
3693

    
   
3695

   
3694
/*! \brief Schedule destruction of SIP dialog */
3696
/*! \brief Schedule destruction of SIP dialog */
3695
void sip_scheddestroy(struct sip_pvt *p, int ms)
3697
void sip_scheddestroy(struct sip_pvt *p, int ms)
3696
{
3698
{
3697
	if (p->final_destruction_scheduled) {
3699
	if (p->final_destruction_scheduled) {
3698
		return; /* already set final destruction */
3700
		return; /* already set final destruction */
3699
	}
3701
	}
3700

    
   
3702

   
3701
	if (ms < 0) {
3703
	if (ms < 0) {
3702
		if (p->timer_t1 == 0) {
3704
		if (p->timer_t1 == 0) {
3703
			p->timer_t1 = global_t1;	/* Set timer T1 if not set (RFC 3261) */
3705
			p->timer_t1 = global_t1;	/* Set timer T1 if not set (RFC 3261) */
3704
		}
3706
		}
3705
		if (p->timer_b == 0) {
3707
		if (p->timer_b == 0) {
3706
			p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
3708
			p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
3707
		}
3709
		}
3708
		ms = p->timer_t1 * 64;
3710
		ms = p->timer_t1 * 64;
3709
	}
3711
	}
3710
	if (sip_debug_test_pvt(p)) {
3712
	if (sip_debug_test_pvt(p)) {
3711
		ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
3713
		ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
3712
	}
3714
	}
3713
	if (sip_cancel_destroy(p)) {
3715
	if (sip_cancel_destroy(p)) {
3714
		ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
3716
		ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
3715
	}
3717
	}
3716

    
   
3718

   
3717
	if (p->do_history) {
3719
	if (p->do_history) {
3718
		append_history(p, "SchedDestroy", "%d ms", ms);
3720
		append_history(p, "SchedDestroy", "%d ms", ms);
3719
	}
3721
	}
3720
	p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
3722
	p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
3721

    
   
3723

   
3722
	if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
3724
	if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
3723
		stop_session_timer(p);
3725
		stop_session_timer(p);
3724
	}
3726
	}
3725
}
3727
}
3726

    
   
3728

   
3727
/*! \brief Cancel destruction of SIP dialog.
3729
/*! \brief Cancel destruction of SIP dialog.
3728
 * Be careful as this also absorbs the reference - if you call it
3730
 * Be careful as this also absorbs the reference - if you call it
3729
 * from within the scheduler, this might be the last reference.
3731
 * from within the scheduler, this might be the last reference.
3730
 */
3732
 */
3731
int sip_cancel_destroy(struct sip_pvt *p)
3733
int sip_cancel_destroy(struct sip_pvt *p)
3732
{
3734
{
3733
	int res = 0;
3735
	int res = 0;
3734

    
   
3736

   
3735
	if (p->final_destruction_scheduled) {
3737
	if (p->final_destruction_scheduled) {
3736
		return res;
3738
		return res;
3737
	}
3739
	}
3738

    
   
3740

   
3739
	if (p->autokillid > -1) {
3741
	if (p->autokillid > -1) {
3740
		int res3;
3742
		int res3;
3741

    
   
3743

   
3742
		if (!(res3 = ast_sched_del(sched, p->autokillid))) {
3744
		if (!(res3 = ast_sched_del(sched, p->autokillid))) {
3743
			append_history(p, "CancelDestroy", "");
3745
			append_history(p, "CancelDestroy", "");
3744
			p->autokillid = -1;
3746
			p->autokillid = -1;
3745
			dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
3747
			dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
3746
		}
3748
		}
3747
	}
3749
	}
3748
	return res;
3750
	return res;
3749
}
3751
}
3750

    
   
3752

   
3751
/*! \brief Acknowledges receipt of a packet and stops retransmission
3753
/*! \brief Acknowledges receipt of a packet and stops retransmission
3752
 * called with p locked*/
3754
 * called with p locked*/
3753
int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
3755
int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)