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

    
   
18

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

    
   
94

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

    
   
163

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

    
   
168

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

    
   
170

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

    
   
177

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

    
   
185

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

    
   
188

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

    
   
206

   
207
*/
207
*/
208

    
   
208

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

    
   
210

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

    
   
212

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

    
   
217

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

    
   
278

   
279

    
   
279

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

    
   
557

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

    
   
562

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

    
   
573

   
574
static const char config[] = "sip.conf";                /*!< Main configuration file */
574
static const char config[] = "sip.conf";                /*!< Main configuration file */
575
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 */
576

    
   
576

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

    
   
592

   
593
/*! \brief Subscription types that we support. We support
593
/*! \brief Subscription types that we support. We support
594
 * - 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)
595
 * - SIMPLE presence used for device status
595
 * - SIMPLE presence used for device status
596
 * - Voicemail notification subscriptions
596
 * - Voicemail notification subscriptions
597
 */
597
 */
598
static const struct cfsubscription_types {
598
static const struct cfsubscription_types {
599
	enum subscriptiontype type;
599
	enum subscriptiontype type;
600
	const char * const event;
600
	const char * const event;
601
	const char * const mediatype;
601
	const char * const mediatype;
602
	const char * const text;
602
	const char * const text;
603
} subscription_types[] = {
603
} subscription_types[] = {
604
	{ NONE,		   "-",        "unknown",	             "unknown" },
604
	{ NONE,		   "-",        "unknown",	             "unknown" },
605
	/* RFC 4235: SIP Dialog event package */
605
	/* RFC 4235: SIP Dialog event package */
606
	{ DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
606
	{ DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
607
	{ 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 */
608
	{ PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
608
	{ PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
609
	{ 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 */
610
	{ 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 */
611
};
611
};
612

    
   
612

   
613
/*! \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
614
 *  structure and then route the messages according to the type.
614
 *  structure and then route the messages according to the type.
615
 *
615
 *
616
 *  \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
617
 */
617
 */
618
static const struct  cfsip_methods {
618
static const struct  cfsip_methods {
619
	enum sipmethod id;
619
	enum sipmethod id;
620
	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? */
621
	char * const text;
621
	char * const text;
622
	enum can_create_dialog can_create;
622
	enum can_create_dialog can_create;
623
} sip_methods[] = {
623
} sip_methods[] = {
624
	{ SIP_UNKNOWN,   RTP,    "-UNKNOWN-",CAN_CREATE_DIALOG },
624
	{ SIP_UNKNOWN,   RTP,    "-UNKNOWN-",CAN_CREATE_DIALOG },
625
	{ SIP_RESPONSE,  NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
625
	{ SIP_RESPONSE,  NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
626
	{ SIP_REGISTER,  NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
626
	{ SIP_REGISTER,  NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
627
	{ SIP_OPTIONS,   NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
627
	{ SIP_OPTIONS,   NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
628
	{ SIP_NOTIFY,    NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
628
	{ SIP_NOTIFY,    NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
629
	{ SIP_INVITE,    RTP,    "INVITE",   CAN_CREATE_DIALOG },
629
	{ SIP_INVITE,    RTP,    "INVITE",   CAN_CREATE_DIALOG },
630
	{ SIP_ACK,       NO_RTP, "ACK",      CAN_NOT_CREATE_DIALOG },
630
	{ SIP_ACK,       NO_RTP, "ACK",      CAN_NOT_CREATE_DIALOG },
631
	{ SIP_PRACK,     NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
631
	{ SIP_PRACK,     NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
632
	{ SIP_BYE,       NO_RTP, "BYE",      CAN_NOT_CREATE_DIALOG },
632
	{ SIP_BYE,       NO_RTP, "BYE",      CAN_NOT_CREATE_DIALOG },
633
	{ SIP_REFER,     NO_RTP, "REFER",    CAN_CREATE_DIALOG },
633
	{ SIP_REFER,     NO_RTP, "REFER",    CAN_CREATE_DIALOG },
634
	{ SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
634
	{ SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
635
	{ SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
635
	{ SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
636
	{ SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
636
	{ SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
637
	{ SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
637
	{ SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
638
	{ SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
638
	{ SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
639
	{ SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
639
	{ SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
640
	{ SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
640
	{ SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
641
};
641
};
642

    
   
642

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

    
   
667

   
668

    
   
668

   
669
/*! \name DefaultSettings
669
/*! \name DefaultSettings
670
	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
671
	configuring devices
671
	configuring devices
672
*/
672
*/
673
/*@{*/
673
/*@{*/
674
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 */
675
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 */
676
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 */
677
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 */
678
static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
678
static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
679
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 */
680
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 */
681
static int default_qualify;                        /*!< Default Qualify= setting */
681
static int default_qualify;                        /*!< Default Qualify= setting */
682
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 */
683
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
684
                                                    *   a bridged channel on hold */
684
                                                    *   a bridged channel on hold */
685
static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
685
static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
686
static char default_engine[256];                   /*!< Default RTP engine */
686
static char default_engine[256];                   /*!< Default RTP engine */
687
static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
687
static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
688
static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
688
static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
689
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 */
690
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 */
691
/*@}*/
691
/*@}*/
692

    
   
692

   
693
static struct sip_settings sip_cfg;		/*!< SIP configuration data.
693
static struct sip_settings sip_cfg;		/*!< SIP configuration data.
694
					\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) */
695

    
   
695

   
696
/*!< 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. */
697
#define SIP_PEDANTIC_DECODE(str)	\
697
#define SIP_PEDANTIC_DECODE(str)	\
698
	if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) {	\
698
	if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) {	\
699
		ast_uri_decode(str);	\
699
		ast_uri_decode(str);	\
700
	}	\
700
	}	\
701

    
   
701

   
702
static unsigned int chan_idx;       /*!< used in naming sip channel */
702
static unsigned int chan_idx;       /*!< used in naming sip channel */
703
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. */
704

    
   
704

   
705
static int global_relaxdtmf;        /*!< Relax DTMF */
705
static int global_relaxdtmf;        /*!< Relax DTMF */
706
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) */
707
static int global_rtptimeout;       /*!< Time out call if no RTP */
707
static int global_rtptimeout;       /*!< Time out call if no RTP */
708
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 */
709
static int global_rtpkeepalive;     /*!< Send RTP keepalives */
709
static int global_rtpkeepalive;     /*!< Send RTP keepalives */
710
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 */
711
static int global_regattempts_max;  /*!< Registration attempts before giving up */
711
static int global_regattempts_max;  /*!< Registration attempts before giving up */
712
static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
712
static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
713
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
714
                                     *   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
715
                                     *   with just a boolean flag in the device structure */
715
                                     *   with just a boolean flag in the device structure */
716
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 */
717
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 */
718
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 */
719
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 */
720
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 */
721
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 */
722
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 */
723
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 */
724
static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
724
static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
725
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 */
726
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 */
727
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 */
728
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 */
729
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. */
730
static int global_t1;           /*!< T1 time */
730
static int global_t1;           /*!< T1 time */
731
static int global_t1min;        /*!< T1 roundtrip time minimum */
731
static int global_t1min;        /*!< T1 roundtrip time minimum */
732
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 */
733
static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
733
static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
734
static int global_qualifyfreq;          /*!< Qualify frequency */
734
static int global_qualifyfreq;          /*!< Qualify frequency */
735
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 */
736
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 */
737

    
   
737

   
738
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           */
739
static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
739
static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
740
static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
740
static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
741
static int global_max_se;                     /*!< Highest threshold for session refresh interval */
741
static int global_max_se;                     /*!< Highest threshold for session refresh interval */
742

    
   
742

   
743
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 */
744
/*@}*/
744
/*@}*/
745

    
   
745

   
746
/*!
746
/*!
747
 * 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,
748
 * 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
749
 * 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
750
 * if XML parsing support was found.
750
 * if XML parsing support was found.
751
 */
751
 */
752
static int can_parse_xml;
752
static int can_parse_xml;
753

    
   
753

   
754
/*! \name Object counters @{
754
/*! \name Object counters @{
755
 *  \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()
756
 *  should be used to modify these values. */
756
 *  should be used to modify these values. */
757
static int speerobjs = 0;     /*!< Static peers */
757
static int speerobjs = 0;     /*!< Static peers */
758
static int rpeerobjs = 0;     /*!< Realtime peers */
758
static int rpeerobjs = 0;     /*!< Realtime peers */
759
static int apeerobjs = 0;     /*!< Autocreated peer objects */
759
static int apeerobjs = 0;     /*!< Autocreated peer objects */
760
static int regobjs = 0;       /*!< Registry objects */
760
static int regobjs = 0;       /*!< Registry objects */
761
/* }@ */
761
/* }@ */
762

    
   
762

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

    
   
765

   
766
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 */
767
static int network_change_event_sched_id = -1;
767
static int network_change_event_sched_id = -1;
768

    
   
768

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

    
   
770

   
771
AST_MUTEX_DEFINE_STATIC(netlock);
771
AST_MUTEX_DEFINE_STATIC(netlock);
772

    
   
772

   
773
/*! \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
774
   when it's doing something critical. */
774
   when it's doing something critical. */
775
AST_MUTEX_DEFINE_STATIC(monlock);
775
AST_MUTEX_DEFINE_STATIC(monlock);
776

    
   
776

   
777
AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
777
AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
778

    
   
778

   
779
/*! \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
780
   which are not currently in use.  */
780
   which are not currently in use.  */
781
static pthread_t monitor_thread = AST_PTHREADT_NULL;
781
static pthread_t monitor_thread = AST_PTHREADT_NULL;
782

    
   
782

   
783
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 */
784
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 */
785

    
   
785

   
786
struct sched_context *sched;     /*!< The scheduling context */
786
struct ast_sched_context *sched;     /*!< The scheduling context */
787
static struct io_context *io;           /*!< The IO context */
787
static struct io_context *io;           /*!< The IO context */
788
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 */
789
struct sip_pkt;
789
struct sip_pkt;
790
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 */
791

    
   
791

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

    
   
793

   
794
static enum sip_debug_e sipdebug;
794
static enum sip_debug_e sipdebug;
795

    
   
795

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

    
   
801

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

    
   
814

   
815
/* --- Hash tables of various objects --------*/
815
/* --- Hash tables of various objects --------*/
816
#ifdef LOW_MEMORY
816
#ifdef LOW_MEMORY
817
static const int HASH_PEER_SIZE = 17;
817
static const int HASH_PEER_SIZE = 17;
818
static const int HASH_DIALOG_SIZE = 17;
818
static const int HASH_DIALOG_SIZE = 17;
819
#else
819
#else
820
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! */
821
static const int HASH_DIALOG_SIZE = 563;
821
static const int HASH_DIALOG_SIZE = 563;
822
#endif
822
#endif
823

    
   
823

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

    
   
833

   
834
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)
835
{
835
{
836
	enum ast_cc_service_type service;
836
	enum ast_cc_service_type service;
837
	for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
837
	for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
838
		if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
838
		if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
839
			return service;
839
			return service;
840
		}
840
		}
841
	}
841
	}
842
	return AST_CC_NONE;
842
	return AST_CC_NONE;
843
}
843
}
844

    
   
844

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

    
   
852

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

    
   
854

   
855
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)
856
{
856
{
857
	struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
857
	struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
858

    
   
858

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

    
   
862

   
863
	backend->static_data = static_data;
863
	backend->static_data = static_data;
864

    
   
864

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

    
   
870

   
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
static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
872

    
   
872

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

    
   
879

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

    
   
886

   
887
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)
888
{
888
{
889
	const struct epa_backend *backend = NULL;
889
	const struct epa_backend *backend = NULL;
890

    
   
890

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

    
   
900

   
901
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)
902
{
902
{
903
	struct sip_epa_entry *epa_entry;
903
	struct sip_epa_entry *epa_entry;
904
	const struct epa_static_data *static_data;
904
	const struct epa_static_data *static_data;
905

    
   
905

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

    
   
909

   
910
	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"))) {
911
		return NULL;
911
		return NULL;
912
	}
912
	}
913

    
   
913

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

    
   
918

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

    
   
924

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

    
   
927

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

    
   
933

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

    
   
956

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

    
   
958

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

    
   
966

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

    
   
972

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

    
   
977

   
978
	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;
979
}
979
}
980

    
   
980

   
981
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) {
982
	int i;
982
	int i;
983
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
983
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
984
		if (!strcasecmp(event_package, event_state_compositors[i].name)) {
984
		if (!strcasecmp(event_package, event_state_compositors[i].name)) {
985
			return &event_state_compositors[i];
985
			return &event_state_compositors[i];
986
		}
986
		}
987
	}
987
	}
988
	return NULL;
988
	return NULL;
989
}
989
}
990

    
   
990

   
991
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) {
992
	struct sip_esc_entry *entry;
992
	struct sip_esc_entry *entry;
993
	struct sip_esc_entry finder;
993
	struct sip_esc_entry finder;
994

    
   
994

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

    
   
996

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

    
   
998

   
999
	return entry;
999
	return entry;
1000
}
1000
}
1001

    
   
1001

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

    
   
1006

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

    
   
1008

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

    
   
1013

   
1014
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)
1015
{
1015
{
1016
	int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
1016
	int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
1017
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1017
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1018

    
   
1018

   
1019
	ast_assert(esc != NULL);
1019
	ast_assert(esc != NULL);
1020
	if (is_linked) {
1020
	if (is_linked) {
1021
		ao2_unlink(esc->compositor, esc_entry);
1021
		ao2_unlink(esc->compositor, esc_entry);
1022
	}
1022
	}
1023
	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);
1024
	ao2_link(esc->compositor, esc_entry);
1024
	ao2_link(esc->compositor, esc_entry);
1025
}
1025
}
1026

    
   
1026

   
1027
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)
1028
{
1028
{
1029
	struct sip_esc_entry *esc_entry;
1029
	struct sip_esc_entry *esc_entry;
1030
	int expires_ms;
1030
	int expires_ms;
1031

    
   
1031

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

    
   
1035

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

    
   
1037

   
1038
	expires_ms = expires * 1000;
1038
	expires_ms = expires * 1000;
1039
	/* Bump refcount for scheduler */
1039
	/* Bump refcount for scheduler */
1040
	ao2_ref(esc_entry, +1);
1040
	ao2_ref(esc_entry, +1);
1041
	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);
1042

    
   
1042

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

    
   
1045

   
1046
	return esc_entry;
1046
	return esc_entry;
1047
}
1047
}
1048

    
   
1048

   
1049
static int initialize_escs(void)
1049
static int initialize_escs(void)
1050
{
1050
{
1051
	int i, res = 0;
1051
	int i, res = 0;
1052
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1052
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1053
		if (!((event_state_compositors[i].compositor) =
1053
		if (!((event_state_compositors[i].compositor) =
1054
					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))) {
1055
			res = -1;
1055
			res = -1;
1056
		}
1056
		}
1057
	}
1057
	}
1058
	return res;
1058
	return res;
1059
}
1059
}
1060

    
   
1060

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

    
   
1068

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

    
   
1075

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

    
   
1082

   
1083
/*! \brief
1083
/*! \brief
1084
 * Here we implement the container for dialogs (sip_pvt), defining
1084
 * Here we implement the container for dialogs (sip_pvt), defining
1085
 * generic wrapper functions to ease the transition from the current
1085
 * generic wrapper functions to ease the transition from the current
1086
 * implementation (a single linked list) to a different container.
1086
 * implementation (a single linked list) to a different container.
1087
 * 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
1088
 * the container and individual items, and functions to add/remove
1088
 * the container and individual items, and functions to add/remove
1089
 * references to the individual items.
1089
 * references to the individual items.
1090
 */
1090
 */
1091
static struct ao2_container *dialogs;
1091
static struct ao2_container *dialogs;
1092
#define sip_pvt_lock(x) ao2_lock(x)
1092
#define sip_pvt_lock(x) ao2_lock(x)
1093
#define sip_pvt_trylock(x) ao2_trylock(x)
1093
#define sip_pvt_trylock(x) ao2_trylock(x)
1094
#define sip_pvt_unlock(x) ao2_unlock(x)
1094
#define sip_pvt_unlock(x) ao2_unlock(x)
1095

    
   
1095

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

    
   
1098

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

    
   
1102

   
1103
/*! \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 */
1104
static struct ast_register_list {
1104
static struct ast_register_list {
1105
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1105
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1106
	int recheck;
1106
	int recheck;
1107
} regl;
1107
} regl;
1108

    
   
1108

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

    
   
1115

   
1116
/*! \brief A per-thread temporary pvt structure */
1116
/*! \brief A per-thread temporary pvt structure */
1117
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);
1118

    
   
1118

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

    
   
1122

   
1123
/* --- Sockets and networking --------------*/
1123
/* --- Sockets and networking --------------*/
1124

    
   
1124

   
1125
/*! \brief Main socket for UDP SIP communication.
1125
/*! \brief Main socket for UDP SIP communication.
1126
 *
1126
 *
1127
 * sipsock is shared between the SIP manager thread (which handles reload
1127
 * sipsock is shared between the SIP manager thread (which handles reload
1128
 * 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
1129
 * issue udp writes (using __sip_xmit()).
1129
 * issue udp writes (using __sip_xmit()).
1130
 * 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),
1131
 * 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
1132
 * 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
1133
 * 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
1134
 * 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.
1135
 * Rather, we remember that when the race may occur, communication is
1135
 * Rather, we remember that when the race may occur, communication is
1136
 * 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
1137
 * the protocol handle this above us.
1137
 * the protocol handle this above us.
1138
 */
1138
 */
1139
static int sipsock  = -1;
1139
static int sipsock  = -1;
1140

    
   
1140

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

    
   
1142

   
1143
/*! \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
1144
 *  internip is initialized picking a suitable address from one of the
1144
 *  internip is initialized picking a suitable address from one of the
1145
 * 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
1146
 * default address/port in SIP messages, and as the default address
1146
 * default address/port in SIP messages, and as the default address
1147
 * (but not port) in SDP messages.
1147
 * (but not port) in SDP messages.
1148
 */
1148
 */
1149
static struct ast_sockaddr internip;
1149
static struct ast_sockaddr internip;
1150

    
   
1150

   
1151
/*! \brief our external IP address/port for SIP sessions.
1151
/*! \brief our external IP address/port for SIP sessions.
1152
 * 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
1153
 * 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)
1154
 * ways from the config file:
1154
 * ways from the config file:
1155
 *
1155
 *
1156
 * + with "externaddr = host[:port]" we specify the address/port explicitly.
1156
 * + with "externaddr = host[:port]" we specify the address/port explicitly.
1157
 *   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;
1158
 *
1158
 *
1159
 * + with "externhost = host[:port]" we do a similar thing, but the
1159
 * + with "externhost = host[:port]" we do a similar thing, but the
1160
 *   hostname is stored in externhost, and the hostname->IP mapping
1160
 *   hostname is stored in externhost, and the hostname->IP mapping
1161
 *   is refreshed every 'externrefresh' seconds;
1161
 *   is refreshed every 'externrefresh' seconds;
1162
 *
1162
 *
1163
 * Other variables (externhost, externexpire, externrefresh) are used
1163
 * Other variables (externhost, externexpire, externrefresh) are used
1164
 * to support the above functions.
1164
 * to support the above functions.
1165
 */
1165
 */
1166
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 */
1167
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 */
1168

    
   
1168

   
1169
static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1169
static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1170
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 */
1171
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) */
1172
static uint16_t externtcpport;          /*!< external tcp port */ 
1172
static uint16_t externtcpport;          /*!< external tcp port */ 
1173
static uint16_t externtlsport;          /*!< external tls port */
1173
static uint16_t externtlsport;          /*!< external tls port */
1174

    
   
1174

   
1175
/*! \brief  List of local networks
1175
/*! \brief  List of local networks
1176
 * 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,
1177
 * 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
1178
 * 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'
1179
 * (i.e. presumably public) addresses.
1179
 * (i.e. presumably public) addresses.
1180
 */
1180
 */
1181
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 */
1182

    
   
1182

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

    
   
1186

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

    
   
1188

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

    
   
1190

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

    
   
1197

   
1198
/*---------------------------- Forward declarations of functions in chan_sip.c */
1198
/*---------------------------- Forward declarations of functions in chan_sip.c */
1199
/* 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
1200
	in coming releases. */
1200
	in coming releases. */
1201

    
   
1201

   
1202
/*--- PBX interface functions */
1202
/*--- PBX interface functions */
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 struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
1204
static int sip_devicestate(void *data);
1204
static int sip_devicestate(void *data);
1205
static int sip_sendtext(struct ast_channel *ast, const char *text);
1205
static int sip_sendtext(struct ast_channel *ast, const char *text);
1206
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);
1207
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);
1208
static int sip_hangup(struct ast_channel *ast);
1208
static int sip_hangup(struct ast_channel *ast);
1209
static int sip_answer(struct ast_channel *ast);
1209
static int sip_answer(struct ast_channel *ast);
1210
static struct ast_frame *sip_read(struct ast_channel *ast);
1210
static struct ast_frame *sip_read(struct ast_channel *ast);
1211
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);
1212
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);
1213
static int sip_transfer(struct ast_channel *ast, const char *dest);
1213
static int sip_transfer(struct ast_channel *ast, const char *dest);
1214
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);
1215
static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1215
static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1216
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);
1217
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);
1218
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);
1219
static const char *sip_get_callid(struct ast_channel *chan);
1219
static const char *sip_get_callid(struct ast_channel *chan);
1220

    
   
1220

   
1221
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);
1222
static int sip_standard_port(enum sip_transport type, int port);
1222
static int sip_standard_port(enum sip_transport type, int port);
1223
static int sip_prepare_socket(struct sip_pvt *p);
1223
static int sip_prepare_socket(struct sip_pvt *p);
1224
static int get_address_family_filter(const struct ast_sockaddr *addr);
1224
static int get_address_family_filter(const struct ast_sockaddr *addr);
1225

    
   
1225

   
1226
/*--- Transmitting responses and requests */
1226
/*--- Transmitting responses and requests */
1227
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);
1228
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);
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 int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
1230
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);
1231
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);
1232
static int retrans_pkt(const void *data);
1232
static int retrans_pkt(const void *data);
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_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);
1234
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);
1235
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);
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_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
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_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp, int rpid);
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_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
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_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);
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_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1241
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);
1242
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);
1243
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);
1244
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);
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_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, 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_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
1247
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);
1248
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);
1249
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);
1250
static int transmit_info_with_vidupdate(struct sip_pvt *p);
1250
static int transmit_info_with_vidupdate(struct sip_pvt *p);
1251
static int transmit_message_with_text(struct sip_pvt *p, const char *text, int init);
1251
static int transmit_message_with_text(struct sip_pvt *p, const char *text, int init, int auth);
1252
static int transmit_refer(struct sip_pvt *p, const char *dest);
1252
static int transmit_refer(struct sip_pvt *p, const char *dest);
1253
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);
1254
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);
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_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
1256
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);
1257
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);
1258
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);
1259
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);
1260
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);
1261
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);
1262
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);
1263

    
   
1263

   
1264
/* Misc dialog routines */
1264
/* Misc dialog routines */
1265
static int __sip_autodestruct(const void *data);
1265
static int __sip_autodestruct(const void *data);
1266
static void *registry_unref(struct sip_registry *reg, char *tag);
1266
static void *registry_unref(struct sip_registry *reg, char *tag);
1267
static int update_call_counter(struct sip_pvt *fup, int event);
1267
static int update_call_counter(struct sip_pvt *fup, int event);
1268
static int auto_congest(const void *arg);
1268
static int auto_congest(const void *arg);
1269
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);
1270
static void free_old_route(struct sip_route *route);
1270
static void free_old_route(struct sip_route *route);
1271
static void list_route(struct sip_route *route);
1271
static void list_route(struct sip_route *route);
1272
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);
1273
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,
1274
					      struct sip_request *req, const char *uri);
1274
					      struct sip_request *req, const char *uri);
1275
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);
1276
static void check_pendings(struct sip_pvt *p);
1276
static void check_pendings(struct sip_pvt *p);
1277
static void *sip_park_thread(void *stuff);
1277
static void *sip_park_thread(void *stuff);
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_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno, char *parkexten);
1279
static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1279
static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1280
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);
1281

    
   
1281

   
1282
/*--- Codec handling / SDP */
1282
/*--- Codec handling / SDP */
1283
static void try_suggested_sip_codec(struct sip_pvt *p);
1283
static void try_suggested_sip_codec(struct sip_pvt *p);
1284
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);
1285
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);
1286
static int find_sdp(struct sip_request *req);
1286
static int find_sdp(struct sip_request *req);
1287
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);
1288
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);
1289
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);
1290
static int process_sdp_a_sendonly(const char *a, int *sendonly);
1290
static int process_sdp_a_sendonly(const char *a, int *sendonly);
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_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, 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_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, 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_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);
1294
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);
1295
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,
1296
			     struct ast_str **m_buf, struct ast_str **a_buf,
1296
			     struct ast_str **m_buf, struct ast_str **a_buf,
1297
			     int debug, int *min_packet_size);
1297
			     int debug, int *min_packet_size);
1298
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,
1299
				struct ast_str **m_buf, struct ast_str **a_buf,
1299
				struct ast_str **m_buf, struct ast_str **a_buf,
1300
				int debug);
1300
				int debug);
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 enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1302
static void do_setnat(struct sip_pvt *p);
1302
static void do_setnat(struct sip_pvt *p);
1303
static void stop_media_flows(struct sip_pvt *p);
1303
static void stop_media_flows(struct sip_pvt *p);
1304

    
   
1304

   
1305
/*--- Authentication stuff */
1305
/*--- Authentication stuff */
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 reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1307
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);
1308
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,
1309
					 const char *secret, const char *md5secret, int sipmethod,
1309
					 const char *secret, const char *md5secret, int sipmethod,
1310
					 const char *uri, enum xmittype reliable, int ignore);
1310
					 const char *uri, enum xmittype reliable, int ignore);
1311
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,
1312
					      int sipmethod, const char *uri, enum xmittype reliable,
1312
					      int sipmethod, const char *uri, enum xmittype reliable,
1313
					      struct ast_sockaddr *addr, struct sip_peer **authpeer);
1313
					      struct ast_sockaddr *addr, struct sip_peer **authpeer);
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
static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
1315

    
   
1315

   
1316
/*--- Domain handling */
1316
/*--- Domain handling */
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 check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1318
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);
1319
static void clear_sip_domains(void);
1319
static void clear_sip_domains(void);
1320

    
   
1320

   
1321
/*--- SIP realm authentication */
1321
/*--- SIP realm authentication */
1322
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);
1323
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) */
1324
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);
1325

    
   
1325

   
1326
/*--- Misc functions */
1326
/*--- Misc functions */
1327
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);
1328
static int sip_do_reload(enum channelreloadreason reason);
1328
static int sip_do_reload(enum channelreloadreason reason);
1329
static int reload_config(enum channelreloadreason reason);
1329
static int reload_config(enum channelreloadreason reason);
1330
static int expire_register(const void *data);
1330
static int expire_register(const void *data);
1331
static void *do_monitor(void *data);
1331
static void *do_monitor(void *data);
1332
static int restart_monitor(void);
1332
static int restart_monitor(void);
1333
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);
1334
static struct ast_variable *copy_vars(struct ast_variable *src);
1334
static struct ast_variable *copy_vars(struct ast_variable *src);
1335
static int dialog_find_multiple(void *obj, void *arg, int flags);
1335
static int dialog_find_multiple(void *obj, void *arg, int flags);
1336
/* 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 */
1337
static int sip_refer_allocate(struct sip_pvt *p);
1337
static int sip_refer_allocate(struct sip_pvt *p);
1338
static int sip_notify_allocate(struct sip_pvt *p);
1338
static int sip_notify_allocate(struct sip_pvt *p);
1339
static void ast_quiet_chan(struct ast_channel *chan);
1339
static void ast_quiet_chan(struct ast_channel *chan);
1340
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);
1341
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);
1342

    
   
1342

   
1343
/*--- Device monitoring and Device/extension state/event handling */
1343
/*--- Device monitoring and Device/extension state/event handling */
1344
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);
1345
static int sip_devicestate(void *data);
1345
static int sip_devicestate(void *data);
1346
static int sip_poke_noanswer(const void *data);
1346
static int sip_poke_noanswer(const void *data);
1347
static int sip_poke_peer(struct sip_peer *peer, int force);
1347
static int sip_poke_peer(struct sip_peer *peer, int force);
1348
static void sip_poke_all_peers(void);
1348
static void sip_poke_all_peers(void);
1349
static void sip_peer_hold(struct sip_pvt *p, int hold);
1349
static void sip_peer_hold(struct sip_pvt *p, int hold);
1350
static void mwi_event_cb(const struct ast_event *, void *);
1350
static void mwi_event_cb(const struct ast_event *, void *);
1351
static void network_change_event_cb(const struct ast_event *, void *);
1351
static void network_change_event_cb(const struct ast_event *, void *);
1352

    
   
1352

   
1353
/*--- Applications, functions, CLI and manager command helpers */
1353
/*--- Applications, functions, CLI and manager command helpers */
1354
static const char *sip_nat_mode(const struct sip_pvt *p);
1354
static const char *sip_nat_mode(const struct sip_pvt *p);
1355
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);
1356
static char *transfermode2str(enum transfermodes mode) attribute_const;
1356
static char *transfermode2str(enum transfermodes mode) attribute_const;
1357
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);
1358
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);
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(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1360
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);
1361
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);
1362
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);
1363
static const char *dtmfmode2str(int mode) attribute_const;
1363
static const char *dtmfmode2str(int mode) attribute_const;
1364
static int str2dtmfmode(const char *str) attribute_unused;
1364
static int str2dtmfmode(const char *str) attribute_unused;
1365
static const char *insecure2str(int mode) attribute_const;
1365
static const char *insecure2str(int mode) attribute_const;
1366
static void cleanup_stale_contexts(char *new, char *old);
1366
static void cleanup_stale_contexts(char *new, char *old);
1367
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);
1368
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);
1369
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);
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(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1371
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);
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(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1373
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);
1374
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);
1375
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);
1376
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);
1377
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);
1378
static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1378
static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1379
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1379
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1380
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);
1381
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);
1382
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);
1383
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);
1384
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);
1385
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);
1386
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);
1387
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);
1388
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);
1389
static char *sip_do_debug_ip(int fd, const char *arg);
1389
static char *sip_do_debug_ip(int fd, const char *arg);
1390
static char *sip_do_debug_peer(int fd, const char *arg);
1390
static char *sip_do_debug_peer(int fd, const char *arg);
1391
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);
1392
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);
1393
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);
1394
static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1394
static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1395
static int sip_addheader(struct ast_channel *chan, const char *data);
1395
static int sip_addheader(struct ast_channel *chan, const char *data);
1396
static int sip_do_reload(enum channelreloadreason reason);
1396
static int sip_do_reload(enum channelreloadreason reason);
1397
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);
1398
static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
1398
static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
1399
				      const char *name, int flag, int family);
1399
				      const char *name, int flag, int family);
1400
static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
1400
static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
1401
				      const char *name, int flag);
1401
				      const char *name, int flag);
1402

    
   
1402

   
1403
/*--- Debugging
1403
/*--- Debugging
1404
	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
1405
	a SIP dialog
1405
	a SIP dialog
1406
*/
1406
*/
1407
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 */
1408
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);
1409
static inline int sip_debug_test_pvt(struct sip_pvt *p);
1409
static inline int sip_debug_test_pvt(struct sip_pvt *p);
1410
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, ...);
1411
static void sip_dump_history(struct sip_pvt *dialog);
1411
static void sip_dump_history(struct sip_pvt *dialog);
1412

    
   
1412

   
1413
/*--- Device object handling */
1413
/*--- Device object handling */
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 struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1415
static int update_call_counter(struct sip_pvt *fup, int event);
1415
static int update_call_counter(struct sip_pvt *fup, int event);
1416
static void sip_destroy_peer(struct sip_peer *peer);
1416
static void sip_destroy_peer(struct sip_peer *peer);
1417
static void sip_destroy_peer_fn(void *peer);
1417
static void sip_destroy_peer_fn(void *peer);
1418
static void set_peer_defaults(struct sip_peer *peer);
1418
static void set_peer_defaults(struct sip_peer *peer);
1419
static struct sip_peer *temp_peer(const char *name);
1419
static struct sip_peer *temp_peer(const char *name);
1420
static void register_peer_exten(struct sip_peer *peer, int onoff);
1420
static void register_peer_exten(struct sip_peer *peer, int onoff);
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 struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int forcenamematch, int devstate_only, int transport);
1422
static int sip_poke_peer_s(const void *data);
1422
static int sip_poke_peer_s(const void *data);
1423
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);
1424
static void reg_source_db(struct sip_peer *peer);
1424
static void reg_source_db(struct sip_peer *peer);
1425
static void destroy_association(struct sip_peer *peer);
1425
static void destroy_association(struct sip_peer *peer);
1426
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);
1427
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);
1428
static void set_socket_transport(struct sip_socket *socket, int transport);
1428
static void set_socket_transport(struct sip_socket *socket, int transport);
1429

    
   
1429

   
1430
/* Realtime device support */
1430
/* Realtime device support */
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 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);
1432
static void update_peer(struct sip_peer *p, int expire);
1432
static void update_peer(struct sip_peer *p, int expire);
1433
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);
1434
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);
1435
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);
1436
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);
1437

    
   
1437

   
1438
/*--- Internal UA client handling (outbound registrations) */
1438
/*--- Internal UA client handling (outbound registrations) */
1439
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);
1440
static void sip_registry_destroy(struct sip_registry *reg);
1440
static void sip_registry_destroy(struct sip_registry *reg);
1441
static int sip_register(const char *value, int lineno);
1441
static int sip_register(const char *value, int lineno);
1442
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1442
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1443
static int sip_reregister(const void *data);
1443
static int sip_reregister(const void *data);
1444
static int __sip_do_register(struct sip_registry *r);
1444
static int __sip_do_register(struct sip_registry *r);
1445
static int sip_reg_timeout(const void *data);
1445
static int sip_reg_timeout(const void *data);
1446
static void sip_send_all_registers(void);
1446
static void sip_send_all_registers(void);
1447
static int sip_reinvite_retry(const void *data);
1447
static int sip_reinvite_retry(const void *data);
1448

    
   
1448

   
1449
/*--- Parsing SIP requests and responses */
1449
/*--- Parsing SIP requests and responses */
1450
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 */
1451
static int determine_firstline_parts(struct sip_request *req);
1451
static int determine_firstline_parts(struct sip_request *req);
1452
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1452
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1453
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);
1454
static int find_sip_method(const char *msg);
1454
static int find_sip_method(const char *msg);
1455
static unsigned int parse_allowed_methods(struct sip_request *req);
1455
static unsigned int parse_allowed_methods(struct sip_request *req);
1456
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);
1457
static int parse_request(struct sip_request *req);
1457
static int parse_request(struct sip_request *req);
1458
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);
1459
static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1459
static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1460
static int method_match(enum sipmethod id, const char *name);
1460
static int method_match(enum sipmethod id, const char *name);
1461
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);
1462
static const char *find_alias(const char *name, const char *_default);
1462
static const char *find_alias(const char *name, const char *_default);
1463
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);
1464
static int lws2sws(char *msgbuf, int len);
1464
static int lws2sws(char *msgbuf, int len);
1465
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);
1466
static char *remove_uri_parameters(char *uri);
1466
static char *remove_uri_parameters(char *uri);
1467
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);
1468
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);
1469
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);
1470
static int set_address_from_contact(struct sip_pvt *pvt);
1470
static int set_address_from_contact(struct sip_pvt *pvt);
1471
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);
1472
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);
1473
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);
1474
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);
1475
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);
1476
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);
1477
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);
1478
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);
1479
static int get_domain(const char *str, char *domain, int len);
1479
static int get_domain(const char *str, char *domain, int len);
1480
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);
1481

    
   
1481

   
1482
/*-- TCP connection handling ---*/
1482
/*-- TCP connection handling ---*/
1483
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);
1484
static void *sip_tcp_worker_fn(void *);
1484
static void *sip_tcp_worker_fn(void *);
1485

    
   
1485

   
1486
/*--- Constructing requests and responses */
1486
/*--- Constructing requests and responses */
1487
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);
1488
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);
1489
static void deinit_req(struct sip_request *req);
1489
static void deinit_req(struct sip_request *req);
1490
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);
1491
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);
1492
static int init_resp(struct sip_request *resp, const char *msg);
1492
static int init_resp(struct sip_request *resp, const char *msg);
1493
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);
1494
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);
1495
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);
1496
static void build_via(struct sip_pvt *p);
1496
static void build_via(struct sip_pvt *p);
1497
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);
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 int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address);
1499
static char *generate_random_string(char *buf, size_t size);
1499
static char *generate_random_string(char *buf, size_t size);
1500
static void build_callid_pvt(struct sip_pvt *pvt);
1500
static void build_callid_pvt(struct sip_pvt *pvt);
1501
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);
1502
static void make_our_tag(char *tagbuf, size_t len);
1502
static void make_our_tag(char *tagbuf, size_t len);
1503
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);
1504
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);
1505
static int add_content(struct sip_request *req, const char *line);
1505
static int add_content(struct sip_request *req, const char *line);
1506
static int finalize_content(struct sip_request *req);
1506
static int finalize_content(struct sip_request *req);
1507
static int add_text(struct sip_request *req, const char *text);
1507
static int add_text(struct sip_request *req, const char *text);
1508
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);
1509
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);
1510
static int add_vidupdate(struct sip_request *req);
1510
static int add_vidupdate(struct sip_request *req);
1511
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);
1512
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);
1513
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);
1514
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);
1515
static void set_destination(struct sip_pvt *p, char *uri);
1515
static void set_destination(struct sip_pvt *p, char *uri);
1516
static void append_date(struct sip_request *req);
1516
static void append_date(struct sip_request *req);
1517
static void build_contact(struct sip_pvt *p);
1517
static void build_contact(struct sip_pvt *p);
1518

    
   
1518

   
1519
/*------Request handling functions */
1519
/*------Request handling functions */
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_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
1521
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);
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_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *recount, const char *e, 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_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1524
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);
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_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
1526
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);
1527
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);
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 int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
1529
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);
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_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
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_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *nounlock);
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 handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
1533
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);
1534

    
   
1534

   
1535
/*------Response handling functions */
1535
/*------Response handling functions */
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_publish(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_invite(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_notify(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_refer(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 void handle_response_subscribe(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);
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);
1542
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);
1543

    
   
1544

   
1544
/*------ SRTP Support -------- */
1545
/*------ SRTP Support -------- */
1545
static int setup_srtp(struct sip_srtp **srtp);
1546
static int setup_srtp(struct sip_srtp **srtp);
1546
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);
1547

    
   
1548

   
1548
/*------ T38 Support --------- */
1549
/*------ T38 Support --------- */
1549
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);
1550
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);
1551
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);
1552
static void change_t38_state(struct sip_pvt *p, int state);
1553
static void change_t38_state(struct sip_pvt *p, int state);
1553

    
   
1554

   
1554
/*------ Session-Timers functions --------- */
1555
/*------ Session-Timers functions --------- */
1555
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);
1556
static int  proc_session_timer(const void *vp);
1557
static int  proc_session_timer(const void *vp);
1557
static void stop_session_timer(struct sip_pvt *p);
1558
static void stop_session_timer(struct sip_pvt *p);
1558
static void start_session_timer(struct sip_pvt *p);
1559
static void start_session_timer(struct sip_pvt *p);
1559
static void restart_session_timer(struct sip_pvt *p);
1560
static void restart_session_timer(struct sip_pvt *p);
1560
static const char *strefresher2str(enum st_refresher r);
1561
static const char *strefresher2str(enum st_refresher r);
1561
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);
1562
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);
1563
static int st_get_se(struct sip_pvt *, int max);
1564
static int st_get_se(struct sip_pvt *, int max);
1564
static enum st_refresher st_get_refresher(struct sip_pvt *);
1565
static enum st_refresher st_get_refresher(struct sip_pvt *);
1565
static enum st_mode st_get_mode(struct sip_pvt *);
1566
static enum st_mode st_get_mode(struct sip_pvt *);
1566
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);
1567

    
   
1568

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

    
   
1571

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

    
   
1578

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

    
   
1608

   
1608
/*! \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
1609
 * 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
1610
 * DTMF BEGIN frames.
1611
 * DTMF BEGIN frames.
1611
 * The struct is initialized just before registering the channel driver,
1612
 * The struct is initialized just before registering the channel driver,
1612
 * and is for use with channels using SIP INFO DTMF.
1613
 * and is for use with channels using SIP INFO DTMF.
1613
 */
1614
 */
1614
struct ast_channel_tech sip_tech_info;
1615
struct ast_channel_tech sip_tech_info;
1615

    
   
1616

   
1616
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);
1617
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);
1618
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);
1619
static void sip_cc_agent_ack(struct ast_cc_agent *agent);
1620
static void sip_cc_agent_ack(struct ast_cc_agent *agent);
1620
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);
1621
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);
1622
static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1623
static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1623
static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1624
static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1624

    
   
1625

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

    
   
1637

   
1637
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)
1638
{
1639
{
1639
	struct ast_cc_agent *agent = obj;
1640
	struct ast_cc_agent *agent = obj;
1640
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1641
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1641
	const char *uri = arg;
1642
	const char *uri = arg;
1642

    
   
1643

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

    
   
1646

   
1646
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)
1647
{
1648
{
1648
	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");
1649
	return agent;
1650
	return agent;
1650
}
1651
}
1651

    
   
1652

   
1652
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)
1653
{
1654
{
1654
	struct ast_cc_agent *agent = obj;
1655
	struct ast_cc_agent *agent = obj;
1655
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1656
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1656
	const char *uri = arg;
1657
	const char *uri = arg;
1657

    
   
1658

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

    
   
1661

   
1661
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)
1662
{
1663
{
1663
	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");
1664
	return agent;
1665
	return agent;
1665
}
1666
}
1666

    
   
1667

   
1667
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)
1668
{
1669
{
1669
	struct ast_cc_agent *agent = obj;
1670
	struct ast_cc_agent *agent = obj;
1670
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1671
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1671
	struct sip_pvt *call_pvt = arg;
1672
	struct sip_pvt *call_pvt = arg;
1672

    
   
1673

   
1673
	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;
1674
}
1675
}
1675

    
   
1676

   
1676
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)
1677
{
1678
{
1678
	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");
1679
	return agent;
1680
	return agent;
1680
}
1681
}
1681

    
   
1682

   
1682
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)
1683
{
1684
{
1684
	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));
1685
	struct sip_pvt *call_pvt = chan->tech_pvt;
1686
	struct sip_pvt *call_pvt = chan->tech_pvt;
1686

    
   
1687

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

    
   
1691

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

    
   
1693

   
1693
	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));
1694
	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));
1695
	agent_pvt->offer_timer_id = -1;
1696
	agent_pvt->offer_timer_id = -1;
1696
	agent->private_data = agent_pvt;
1697
	agent->private_data = agent_pvt;
1697
	sip_pvt_lock(call_pvt);
1698
	sip_pvt_lock(call_pvt);
1698
	ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1699
	ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1699
	sip_pvt_unlock(call_pvt);
1700
	sip_pvt_unlock(call_pvt);
1700
	return 0;
1701
	return 0;
1701
}
1702
}
1702

    
   
1703

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

    
   
1708

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

    
   
1710

   
1710
	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);
1711
}
1712
}
1712

    
   
1713

   
1713
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)
1714
{
1715
{
1715
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1716
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1716
	int when;
1717
	int when;
1717

    
   
1718

   
1718
	when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1719
	when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1719
	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);
1720
	return 0;
1721
	return 0;
1721
}
1722
}
1722

    
   
1723

   
1723
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)
1724
{
1725
{
1725
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1726
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1726

    
   
1727

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

    
   
1731

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

    
   
1735

   
1735
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1736
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1736
	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);
1737
	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);
1738
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1739
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1739
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1740
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1740
	agent_pvt->is_available = TRUE;
1741
	agent_pvt->is_available = TRUE;
1741
}
1742
}
1742

    
   
1743

   
1743
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)
1744
{
1745
{
1745
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1746
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1746
	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;
1747
	return ast_cc_agent_status_response(agent->core_id, state);
1748
	return ast_cc_agent_status_response(agent->core_id, state);
1748
}
1749
}
1749

    
   
1750

   
1750
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)
1751
{
1752
{
1752
	/* To start monitoring just means to wait for an incoming PUBLISH
1753
	/* To start monitoring just means to wait for an incoming PUBLISH
1753
	 * 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
1754
	 * action is needed
1755
	 * action is needed
1755
	 */
1756
	 */
1756
	return 0;
1757
	return 0;
1757
}
1758
}
1758

    
   
1759

   
1759
static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1760
static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1760
{
1761
{
1761
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1762
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1762
	/* 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
1763
	 * 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
1764
	 * the caller as busy
1765
	 * the caller as busy
1765
	 */
1766
	 */
1766
	if (!agent_pvt->is_available) {
1767
	if (!agent_pvt->is_available) {
1767
		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",
1768
				agent->device_name);
1769
				agent->device_name);
1769
	}
1770
	}
1770
	/* Otherwise, we transmit a NOTIFY to the caller and await either
1771
	/* Otherwise, we transmit a NOTIFY to the caller and await either
1771
	 * a PUBLISH or an INVITE
1772
	 * a PUBLISH or an INVITE
1772
	 */
1773
	 */
1773
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1774
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1774
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1775
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1775
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1776
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1776
	return 0;
1777
	return 0;
1777
}
1778
}
1778

    
   
1779

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

    
   
1783

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

    
   
1788

   
1788
	sip_cc_agent_stop_offer_timer(agent);
1789
	sip_cc_agent_stop_offer_timer(agent);
1789
	if (agent_pvt->subscribe_pvt) {
1790
	if (agent_pvt->subscribe_pvt) {
1790
		sip_pvt_lock(agent_pvt->subscribe_pvt);
1791
		sip_pvt_lock(agent_pvt->subscribe_pvt);
1791
		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)) {
1792
			/* 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
1793
			 * the subscriber know something went wrong
1794
			 * the subscriber know something went wrong
1794
			 */
1795
			 */
1795
			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);
1796
		}
1797
		}
1797
		sip_pvt_unlock(agent_pvt->subscribe_pvt);
1798
		sip_pvt_unlock(agent_pvt->subscribe_pvt);
1798
		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");
1799
	}
1800
	}
1800
	ast_free(agent_pvt);
1801
	ast_free(agent_pvt);
1801
}
1802
}
1802

    
   
1803

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

    
   
1805

   
1805
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)
1806
{
1807
{
1807
	const struct sip_monitor_instance *monitor_instance = obj;
1808
	const struct sip_monitor_instance *monitor_instance = obj;
1808
	return monitor_instance->core_id;
1809
	return monitor_instance->core_id;
1809
}
1810
}
1810

    
   
1811

   
1811
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)
1812
{
1813
{
1813
	struct sip_monitor_instance *monitor_instance1 = obj;
1814
	struct sip_monitor_instance *monitor_instance1 = obj;
1814
	struct sip_monitor_instance *monitor_instance2 = arg;
1815
	struct sip_monitor_instance *monitor_instance2 = arg;
1815

    
   
1816

   
1816
	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;
1817
}
1818
}
1818

    
   
1819

   
1819
static void sip_monitor_instance_destructor(void *data)
1820
static void sip_monitor_instance_destructor(void *data)
1820
{
1821
{
1821
	struct sip_monitor_instance *monitor_instance = data;
1822
	struct sip_monitor_instance *monitor_instance = data;
1822
	if (monitor_instance->subscription_pvt) {
1823
	if (monitor_instance->subscription_pvt) {
1823
		sip_pvt_lock(monitor_instance->subscription_pvt);
1824
		sip_pvt_lock(monitor_instance->subscription_pvt);
1824
		monitor_instance->subscription_pvt->expiry = 0;
1825
		monitor_instance->subscription_pvt->expiry = 0;
1825
		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);
1826
		sip_pvt_unlock(monitor_instance->subscription_pvt);
1827
		sip_pvt_unlock(monitor_instance->subscription_pvt);
1827
		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");
1828
	}
1829
	}
1829
	if (monitor_instance->suspension_entry) {
1830
	if (monitor_instance->suspension_entry) {
1830
		monitor_instance->suspension_entry->body[0] = '\0';
1831
		monitor_instance->suspension_entry->body[0] = '\0';
1831
		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);
1832
		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");
1833
	}
1834
	}
1834
	ast_string_field_free_memory(monitor_instance);
1835
	ast_string_field_free_memory(monitor_instance);
1835
}
1836
}
1836

    
   
1837

   
1837
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)
1838
{
1839
{
1839
	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);
1840

    
   
1841

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

    
   
1845

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

    
   
1850

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

    
   
1858

   
1858
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)
1859
{
1860
{
1860
	struct sip_monitor_instance *monitor_instance = obj;
1861
	struct sip_monitor_instance *monitor_instance = obj;
1861
	return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
1862
	return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
1862
}
1863
}
1863

    
   
1864

   
1864
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)
1865
{
1866
{
1866
	struct sip_monitor_instance *monitor_instance = obj;
1867
	struct sip_monitor_instance *monitor_instance = obj;
1867
	return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
1868
	return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
1868
}
1869
}
1869

    
   
1870

   
1870
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);
1871
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
1872
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
1872
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
1873
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
1873
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);
1874
static void sip_cc_monitor_destructor(void *private_data);
1875
static void sip_cc_monitor_destructor(void *private_data);
1875

    
   
1876

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

    
   
1885

   
1885
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)
1886
{
1887
{
1887
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1888
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1888
	enum ast_cc_service_type service = monitor->service_offered;
1889
	enum ast_cc_service_type service = monitor->service_offered;
1889
	int when;
1890
	int when;
1890

    
   
1891

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

    
   
1895

   
1895
	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))) {
1896
		return -1;
1897
		return -1;
1897
	}
1898
	}
1898

    
   
1899

   
1899
	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) :
1900
		ast_get_ccnr_available_timer(monitor->interface->config_params);
1901
		ast_get_ccnr_available_timer(monitor->interface->config_params);
1901

    
   
1902

   
1902
	sip_pvt_lock(monitor_instance->subscription_pvt);
1903
	sip_pvt_lock(monitor_instance->subscription_pvt);
1903
	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);
1904
	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);
1905
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1906
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1906
	monitor_instance->subscription_pvt->expiry = when;
1907
	monitor_instance->subscription_pvt->expiry = when;
1907

    
   
1908

   
1908
	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);
1909
	sip_pvt_unlock(monitor_instance->subscription_pvt);
1910
	sip_pvt_unlock(monitor_instance->subscription_pvt);
1910

    
   
1911

   
1911
	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");
1912
	*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);
1913
	return 0;
1914
	return 0;
1914
}
1915
}
1915

    
   
1916

   
1916
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)
1917
{
1918
{
1918
	struct ast_str *body = ast_str_alloca(size);
1919
	struct ast_str *body = ast_str_alloca(size);
1919
	char tuple_id[32];
1920
	char tuple_id[32];
1920

    
   
1921

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

    
   
1923

   
1923
	/* 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
1924
	 * 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.
1925
	 */
1926
	 */
1926
	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");
1927
	/* 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
1928
	 * 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
1929
	 * 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
1930
	 * 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
1931
	 * should be revisited as support is expanded.
1932
	 * should be revisited as support is expanded.
1932
	 */
1933
	 */
1933
	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);
1934
	ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
1935
	ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
1935
	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");
1936
	ast_str_append(&body, 0, "</tuple>\n");
1937
	ast_str_append(&body, 0, "</tuple>\n");
1937
	ast_str_append(&body, 0, "</presence>\n");
1938
	ast_str_append(&body, 0, "</presence>\n");
1938
	ast_copy_string(pidf_body, ast_str_buffer(body), size);
1939
	ast_copy_string(pidf_body, ast_str_buffer(body), size);
1939
	return 0;
1940
	return 0;
1940
}
1941
}
1941

    
   
1942

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

    
   
1948

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

    
   
1952

   
1952
	if (!monitor_instance->suspension_entry) {
1953
	if (!monitor_instance->suspension_entry) {
1953
		/* 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 */
1954
		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))) {
1955
			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");
1956
			ao2_ref(monitor_instance, -1);
1957
			ao2_ref(monitor_instance, -1);
1957
			return -1;
1958
			return -1;
1958
		}
1959
		}
1959
		if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
1960
		if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
1960
			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");
1961
			ao2_ref(monitor_instance, -1);
1962
			ao2_ref(monitor_instance, -1);
1962
			return -1;
1963
			return -1;
1963
		}
1964
		}
1964
		cc_entry->core_id = monitor->core_id;
1965
		cc_entry->core_id = monitor->core_id;
1965
		monitor_instance->suspension_entry->instance_data = cc_entry;
1966
		monitor_instance->suspension_entry->instance_data = cc_entry;
1966
		publish_type = SIP_PUBLISH_INITIAL;
1967
		publish_type = SIP_PUBLISH_INITIAL;
1967
	} else {
1968
	} else {
1968
		publish_type = SIP_PUBLISH_MODIFY;
1969
		publish_type = SIP_PUBLISH_MODIFY;
1969
		cc_entry = monitor_instance->suspension_entry->instance_data;
1970
		cc_entry = monitor_instance->suspension_entry->instance_data;
1970
	}
1971
	}
1971

    
   
1972

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

    
   
1974

   
1974
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
1975
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
1975
		/* 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
1976
		 * not received a NOTIFY from this destination stating that he is
1977
		 * not received a NOTIFY from this destination stating that he is
1977
		 * currently available.
1978
		 * currently available.
1978
		 *
1979
		 *
1979
		 * This situation can arise when the core calls the suspend callbacks
1980
		 * This situation can arise when the core calls the suspend callbacks
1980
		 * of multiple destinations. If one of the other destinations aside
1981
		 * of multiple destinations. If one of the other destinations aside
1981
		 * from this one notified Asterisk that he is available, then there
1982
		 * from this one notified Asterisk that he is available, then there
1982
		 * 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,
1983
		 * 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
1984
		 * is still "suspended" then we can immediately respond with the
1985
		 * is still "suspended" then we can immediately respond with the
1985
		 * proper PUBLISH to let this endpoint know what is going on.
1986
		 * proper PUBLISH to let this endpoint know what is going on.
1986
		 */
1987
		 */
1987
		return 0;
1988
		return 0;
1988
	}
1989
	}
1989
	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);
1990
	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);
1991
}
1992
}
1992

    
   
1993

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

    
   
1998

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

    
   
2002

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

    
   
2004

   
2004
	cc_entry = monitor_instance->suspension_entry->instance_data;
2005
	cc_entry = monitor_instance->suspension_entry->instance_data;
2005
	cc_entry->current_state = CC_OPEN;
2006
	cc_entry->current_state = CC_OPEN;
2006
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
2007
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
2007
		/* 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
2008
		 * 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
2009
		 * PUBLISH at this point either. We can just return instead.
2010
		 * PUBLISH at this point either. We can just return instead.
2010
		 */
2011
		 */
2011
		return 0;
2012
		return 0;
2012
	}
2013
	}
2013
	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);
2014
	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);
2015
}
2016
}
2016

    
   
2017

   
2017
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)
2018
{
2019
{
2019
	if (*sched_id != -1) {
2020
	if (*sched_id != -1) {
2020
		AST_SCHED_DEL(sched, *sched_id);
2021
		AST_SCHED_DEL(sched, *sched_id);
2021
		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");
2022
	}
2023
	}
2023
	return 0;
2024
	return 0;
2024
}
2025
}
2025

    
   
2026

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

    
   
2033

   
2033
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)
2034
{
2035
{
2035
	char *call_info = ast_strdupa(get_header(req, "Call-Info"));
2036
	char *call_info = ast_strdupa(get_header(req, "Call-Info"));
2036
	char *uri;
2037
	char *uri;
2037
	char *purpose;
2038
	char *purpose;
2038
	char *service_str;
2039
	char *service_str;
2039
	static const char cc_purpose[] = "purpose=call-completion";
2040
	static const char cc_purpose[] = "purpose=call-completion";
2040
	static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2041
	static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2041

    
   
2042

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

    
   
2047

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

    
   
2049

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

    
   
2059

   
2059
	/* 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 */
2060
	while ((service_str = strsep(&call_info, ";"))) {
2061
	while ((service_str = strsep(&call_info, ";"))) {
2061
		if (!strncmp(service_str, "m=", 2)) {
2062
		if (!strncmp(service_str, "m=", 2)) {
2062
			break;
2063
			break;
2063
		}
2064
		}
2064
	}
2065
	}
2065
	if (!service_str) {
2066
	if (!service_str) {
2066
		/* 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
2067
		 * doesn't matter anyway
2068
		 * doesn't matter anyway
2068
		 */
2069
		 */
2069
		service_str = "BS";
2070
		service_str = "BS";
2070
	} else {
2071
	} else {
2071
		/* 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
2072
		 * the result of this strsep
2073
		 * the result of this strsep
2073
		 */
2074
		 */
2074
		strsep(&service_str, "=");
2075
		strsep(&service_str, "=");
2075
	}
2076
	}
2076

    
   
2077

   
2077
	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) {
2078
		/* Invalid service offered */
2079
		/* Invalid service offered */
2079
		return -1;
2080
		return -1;
2080
	}
2081
	}
2081

    
   
2082

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

    
   
2084

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

    
   
2087

   
2087
/*
2088
/*
2088
 * \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
2089
 *
2090
 *
2090
 * 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,
2091
 * 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
2092
 * 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
2093
 * use native CC monitoring for the call, then so be it.
2094
 * use native CC monitoring for the call, then so be it.
2094
 *
2095
 *
2095
 * 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
2096
 * 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
2097
 * 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"
2098
 *
2099
 *
2099
 * \param pvt The current dialog. Contains CC parameters for the endpoint
2100
 * \param pvt The current dialog. Contains CC parameters for the endpoint
2100
 * \param req The response to the INVITE we want to inspect
2101
 * \param req The response to the INVITE we want to inspect
2101
 * \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
2102
 * monitoring, we get the service from the SIP response itself
2103
 * monitoring, we get the service from the SIP response itself
2103
 */
2104
 */
2104
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)
2105
{
2106
{
2106
	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);
2107
	int core_id;
2108
	int core_id;
2108
	char interface_name[AST_CHANNEL_NAME];
2109
	char interface_name[AST_CHANNEL_NAME];
2109

    
   
2110

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

    
   
2115

   
2115
	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) {
2116
		/* For some reason, CC is invalid, so don't try it! */
2117
		/* For some reason, CC is invalid, so don't try it! */
2117
		return;
2118
		return;
2118
	}
2119
	}
2119

    
   
2120

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

    
   
2122

   
2122
	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) {
2123
		char subscribe_uri[SIPBUFSIZE];
2124
		char subscribe_uri[SIPBUFSIZE];
2124
		char device_name[AST_CHANNEL_NAME];
2125
		char device_name[AST_CHANNEL_NAME];
2125
		enum ast_cc_service_type offered_service;
2126
		enum ast_cc_service_type offered_service;
2126
		struct sip_monitor_instance *monitor_instance;
2127
		struct sip_monitor_instance *monitor_instance;
2127
		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)) {
2128
			/* 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
2129
			 * 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
2130
			 * call completion since the monitor policy may be "always"
2131
			 * call completion since the monitor policy may be "always"
2131
			 */
2132
			 */
2132
			goto generic;
2133
			goto generic;
2133
		}
2134
		}
2134
		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));
2135
		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))) {
2136
			/* Same deal. We can try using generic still */
2137
			/* Same deal. We can try using generic still */
2137
			goto generic;
2138
			goto generic;
2138
		}
2139
		}
2139
		/* 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
2140
		 * 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
2141
		 * refcount once the monitor destructor is called
2142
		 * refcount once the monitor destructor is called
2142
		 */
2143
		 */
2143
		ast_module_ref(ast_module_info->self);
2144
		ast_module_ref(ast_module_info->self);
2144
		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);
2145
		ao2_ref(monitor_instance, -1);
2146
		ao2_ref(monitor_instance, -1);
2146
		return;
2147
		return;
2147
	}
2148
	}
2148

    
   
2149

   
2149
generic:
2150
generic:
2150
	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) {
2151
		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);
2152
	}
2153
	}
2153
}
2154
}
2154

    
   
2155

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

    
   
2158

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

    
   
2161

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

    
   
2172

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

    
   
2183

   
2183
/*! \brief Append to SIP dialog history
2184
/*! \brief Append to SIP dialog history
2184
	\return Always returns 0 */
2185
	\return Always returns 0 */
2185
#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)
2186

    
   
2187

   
2187
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)
2188
{
2189
{
2189
	if (p)
2190
	if (p)
2190
#ifdef REF_DEBUG
2191
#ifdef REF_DEBUG
2191
		__ao2_ref_debug(p, 1, tag, file, line, func);
2192
		__ao2_ref_debug(p, 1, tag, file, line, func);
2192
#else
2193
#else
2193
		ao2_ref(p, 1);
2194
		ao2_ref(p, 1);
2194
#endif
2195
#endif
2195
	else
2196
	else
2196
		ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2197
		ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2197
	return p;
2198
	return p;
2198
}
2199
}
2199

    
   
2200

   
2200
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)
2201
{
2202
{
2202
	if (p)
2203
	if (p)
2203
#ifdef REF_DEBUG
2204
#ifdef REF_DEBUG
2204
		__ao2_ref_debug(p, -1, tag, file, line, func);
2205
		__ao2_ref_debug(p, -1, tag, file, line, func);
2205
#else
2206
#else
2206
		ao2_ref(p, -1);
2207
		ao2_ref(p, -1);
2207
#endif
2208
#endif
2208
	return NULL;
2209
	return NULL;
2209
}
2210
}
2210

    
   
2211

   
2211
/*! \brief map from an integer value to a string.
2212
/*! \brief map from an integer value to a string.
2212
 * If no match is found, return errorstring
2213
 * If no match is found, return errorstring
2213
 */
2214
 */
2214
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)
2215
{
2216
{
2216
	const struct _map_x_s *cur;
2217
	const struct _map_x_s *cur;
2217

    
   
2218

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

    
   
2226

   
2226
/*! \brief map from a string to an integer value, case insensitive.
2227
/*! \brief map from a string to an integer value, case insensitive.
2227
 * If no match is found, return errorvalue.
2228
 * If no match is found, return errorvalue.
2228
 */
2229
 */
2229
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)
2230
{
2231
{
2231
	const struct _map_x_s *cur;
2232
	const struct _map_x_s *cur;
2232

    
   
2233

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

    
   
2241

   
2241
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)
2242
{
2243
{
2243
	enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2244
	enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2244
	int i;
2245
	int i;
2245

    
   
2246

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

    
   
2253

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

    
   
2256

   
2256
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)
2257
{
2258
{
2258
	if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2259
	if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2259
		return sip_reason_table[code].text;
2260
		return sip_reason_table[code].text;
2260
	}
2261
	}
2261

    
   
2262

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

    
   
2265

   
2265
/*!
2266
/*!
2266
 * \brief generic function for determining if a correct transport is being
2267
 * \brief generic function for determining if a correct transport is being
2267
 * used to contact a peer
2268
 * used to contact a peer
2268
 *
2269
 *
2269
 * 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
2270
 * sip_request or a sip_peer
2271
 * sip_request or a sip_peer
2271
 */
2272
 */
2272
#define check_request_transport(peer, tmpl) ({ \
2273
#define check_request_transport(peer, tmpl) ({ \
2273
	int ret = 0; \
2274
	int ret = 0; \
2274
	if (peer->socket.type == tmpl->socket.type) \
2275
	if (peer->socket.type == tmpl->socket.type) \
2275
		; \
2276
		; \
2276
	else if (!(peer->transports & tmpl->socket.type)) {\
2277
	else if (!(peer->transports & tmpl->socket.type)) {\
2277
		ast_log(LOG_ERROR, \
2278
		ast_log(LOG_ERROR, \
2278
			"'%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", \
2279
			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) \
2280
			); \
2281
			); \
2281
		ret = 1; \
2282
		ret = 1; \
2282
	} else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
2283
	} else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
2283
		ast_log(LOG_WARNING, \
2284
		ast_log(LOG_WARNING, \
2284
			"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", \
2285
			peer->name, get_transport(tmpl->socket.type) \
2286
			peer->name, get_transport(tmpl->socket.type) \
2286
		); \
2287
		); \
2287
	} else { \
2288
	} else { \
2288
		ast_debug(1, \
2289
		ast_debug(1, \
2289
			"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", \
2290
			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) \
2291
		); \
2292
		); \
2292
	}\
2293
	}\
2293
	(ret); \
2294
	(ret); \
2294
})
2295
})
2295

    
   
2296

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

    
   
2303

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

    
   
2312

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

    
   
2316

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

    
   
2319

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

    
   
2333

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

    
   
2338

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

    
   
2346

   
2346
	while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2347
	while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2347
		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");
2348
	}
2349
	}
2349

    
   
2350

   
2350
	if (th->tcptls_session) {
2351
	if (th->tcptls_session) {
2351
		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");
2352
	}
2353
	}
2353
}
2354
}
2354

    
   
2355

   
2355
/*! \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. */
2356
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)
2357
{
2358
{
2358
	struct sip_threadinfo *th;
2359
	struct sip_threadinfo *th;
2359

    
   
2360

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

    
   
2364

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

    
   
2366

   
2366
	if (pipe(th->alert_pipe) == -1) {
2367
	if (pipe(th->alert_pipe) == -1) {
2367
		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");
2368
		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));
2369
		return NULL;
2370
		return NULL;
2370
	}
2371
	}
2371
	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");
2372
	th->tcptls_session = tcptls_session;
2373
	th->tcptls_session = tcptls_session;
2373
	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);
2374
	ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2375
	ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2375
	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");
2376
	return th;
2377
	return th;
2377
}
2378
}
2378

    
   
2379

   
2379
/*! \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 */
2380
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)
2381
{
2382
{
2382
	int res = len;
2383
	int res = len;
2383
	struct sip_threadinfo *th = NULL;
2384
	struct sip_threadinfo *th = NULL;
2384
	struct tcptls_packet *packet = NULL;
2385
	struct tcptls_packet *packet = NULL;
2385
	struct sip_threadinfo tmp = {
2386
	struct sip_threadinfo tmp = {
2386
		.tcptls_session = tcptls_session,
2387
		.tcptls_session = tcptls_session,
2387
	};
2388
	};
2388
	enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2389
	enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2389

    
   
2390

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

    
   
2394

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

    
   
2396

   
2396
	if ((tcptls_session->fd == -1) ||
2397
	if ((tcptls_session->fd == -1) ||
2397
		!(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")) ||
2398
		!(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2399
		!(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2399
		!(packet->data = ast_str_create(len))) {
2400
		!(packet->data = ast_str_create(len))) {
2400
		goto tcptls_write_setup_error;
2401
		goto tcptls_write_setup_error;
2401
	}
2402
	}
2402

    
   
2403

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

    
   
2407

   
2407
	/* 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.
2408
	 * must lock the thread info object to guarantee control of the
2409
	 * must lock the thread info object to guarantee control of the
2409
	 * packet queue */
2410
	 * packet queue */
2410
	ao2_lock(th);
2411
	ao2_lock(th);
2411
	if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2412
	if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2412
		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));
2413
		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");
2414
		packet = NULL;
2415
		packet = NULL;
2415
		res = XMIT_ERROR;
2416
		res = XMIT_ERROR;
2416
	} 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 */
2417
		AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2418
		AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2418
	}
2419
	}
2419
	ao2_unlock(th);
2420
	ao2_unlock(th);
2420

    
   
2421

   
2421
	ast_mutex_unlock(&tcptls_session->lock);
2422
	ast_mutex_unlock(&tcptls_session->lock);
2422
	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");
2423
	return res;
2424
	return res;
2424

    
   
2425

   
2425
tcptls_write_setup_error:
2426
tcptls_write_setup_error:
2426
	if (th) {
2427
	if (th) {
2427
		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");
2428
	}
2429
	}
2429
	if (packet) {
2430
	if (packet) {
2430
		ao2_t_ref(packet, -1, "could not allocate packet's data");
2431
		ao2_t_ref(packet, -1, "could not allocate packet's data");
2431
	}
2432
	}
2432
	ast_mutex_unlock(&tcptls_session->lock);
2433
	ast_mutex_unlock(&tcptls_session->lock);
2433

    
   
2434

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

    
   
2437

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

    
   
2442

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

    
   
2445

   
2445
/*! \brief SIP TCP thread management function
2446
/*! \brief SIP TCP thread management function
2446
	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
2447
*/
2448
*/
2448
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)
2449
{
2450
{
2450
	int res, cl;
2451
	int res, cl;
2451
	struct sip_request req = { 0, } , reqcpy = { 0, };
2452
	struct sip_request req = { 0, } , reqcpy = { 0, };
2452
	struct sip_threadinfo *me = NULL;
2453
	struct sip_threadinfo *me = NULL;
2453
	char buf[1024] = "";
2454
	char buf[1024] = "";
2454
	struct pollfd fds[2] = { { 0 }, { 0 }, };
2455
	struct pollfd fds[2] = { { 0 }, { 0 }, };
2455
	struct ast_tcptls_session_args *ca = NULL;
2456
	struct ast_tcptls_session_args *ca = NULL;
2456

    
   
2457

   
2457
	/* 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,
2458
	 * 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.
2459
	 * 
2460
	 * 
2460
	 * if this is a client connection more work must be done.
2461
	 * if this is a client connection more work must be done.
2461
	 * 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
2462
	 *    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.
2463
	 * 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
2464
	 *    it must be found within the threadt table.
2465
	 *    it must be found within the threadt table.
2465
	 * 3. Last, the tcptls_session must be started.
2466
	 * 3. Last, the tcptls_session must be started.
2466
	 */
2467
	 */
2467
	if (!tcptls_session->client) {
2468
	if (!tcptls_session->client) {
2468
		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))) {
2469
			goto cleanup;
2470
			goto cleanup;
2470
		}
2471
		}
2471
		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");
2472
	} else {
2473
	} else {
2473
		struct sip_threadinfo tmp = {
2474
		struct sip_threadinfo tmp = {
2474
			.tcptls_session = tcptls_session,
2475
			.tcptls_session = tcptls_session,
2475
		};
2476
		};
2476

    
   
2477

   
2477
		if ((!(ca = tcptls_session->parent)) ||
2478
		if ((!(ca = tcptls_session->parent)) ||
2478
			(!(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"))) ||
2479
			(!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
2480
			(!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
2480
			goto cleanup;
2481
			goto cleanup;
2481
		}
2482
		}
2482
	}
2483
	}
2483

    
   
2484

   
2484
	me->threadid = pthread_self();
2485
	me->threadid = pthread_self();
2485
	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");
2486

    
   
2487

   
2487
	/* 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 */
2488
	fds[0].fd = tcptls_session->fd;
2489
	fds[0].fd = tcptls_session->fd;
2489
	fds[1].fd = me->alert_pipe[0];
2490
	fds[1].fd = me->alert_pipe[0];
2490
	fds[0].events = fds[1].events = POLLIN | POLLPRI;
2491
	fds[0].events = fds[1].events = POLLIN | POLLPRI;
2491

    
   
2492

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

    
   
2499

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

    
   
2502

   
2502
		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 */
2503
		if (res < 0) {
2504
		if (res < 0) {
2504
			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);
2505
			goto cleanup;
2506
			goto cleanup;
2506
		}
2507
		}
2507

    
   
2508

   
2508
		/* 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,
2509
		 * and writes from alert_pipe fd */
2510
		 * and writes from alert_pipe fd */
2510
		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 */
2511

    
   
2512

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

    
   
2514

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

    
   
2520

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

    
   
2525

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

    
   
2527

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

    
   
2536

   
2536
			/* Read in headers one line at a time */
2537
			/* Read in headers one line at a time */
2537
			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)) {
2538
				ast_mutex_lock(&tcptls_session->lock);
2539
				ast_mutex_lock(&tcptls_session->lock);
2539
				if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2540
				if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2540
					ast_mutex_unlock(&tcptls_session->lock);
2541
					ast_mutex_unlock(&tcptls_session->lock);
2541
					goto cleanup;
2542
					goto cleanup;
2542
				}
2543
				}
2543
				ast_mutex_unlock(&tcptls_session->lock);
2544
				ast_mutex_unlock(&tcptls_session->lock);
2544
				if (me->stop) {
2545
				if (me->stop) {
2545
					 goto cleanup;
2546
					 goto cleanup;
2546
				}
2547
				}
2547
				ast_str_append(&req.data, 0, "%s", buf);
2548
				ast_str_append(&req.data, 0, "%s", buf);
2548
				req.len = req.data->used;
2549
				req.len = req.data->used;
2549
			}
2550
			}
2550
			copy_request(&reqcpy, &req);
2551
			copy_request(&reqcpy, &req);
2551
			parse_request(&reqcpy);
2552
			parse_request(&reqcpy);
2552
			/* 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 */
2553
			if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
2554
			if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
2554
				while (cl > 0) {
2555
				while (cl > 0) {
2555
					size_t bytes_read;
2556
					size_t bytes_read;
2556
					ast_mutex_lock(&tcptls_session->lock);
2557
					ast_mutex_lock(&tcptls_session->lock);
2557
					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))) {
2558
						ast_mutex_unlock(&tcptls_session->lock);
2559
						ast_mutex_unlock(&tcptls_session->lock);
2559
						goto cleanup;
2560
						goto cleanup;
2560
					}
2561
					}
2561
					buf[bytes_read] = '\0';
2562
					buf[bytes_read] = '\0';
2562
					ast_mutex_unlock(&tcptls_session->lock);
2563
					ast_mutex_unlock(&tcptls_session->lock);
2563
					if (me->stop) {
2564
					if (me->stop) {
2564
						goto cleanup;
2565
						goto cleanup;
2565
					}
2566
					}
2566
					cl -= strlen(buf);
2567
					cl -= strlen(buf);
2567
					ast_str_append(&req.data, 0, "%s", buf);
2568
					ast_str_append(&req.data, 0, "%s", buf);
2568
					req.len = req.data->used;
2569
					req.len = req.data->used;
2569
				}
2570
				}
2570
			}
2571
			}
2571
			/*! \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
2572
					we receive is not the same - we should generate an error */
2573
					we receive is not the same - we should generate an error */
2573

    
   
2574

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

    
   
2578

   
2578
		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 */
2579
			enum sip_tcptls_alert alert;
2580
			enum sip_tcptls_alert alert;
2580
			struct tcptls_packet *packet;
2581
			struct tcptls_packet *packet;
2581

    
   
2582

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

    
   
2584

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

    
   
2589

   
2589
			switch (alert) {
2590
			switch (alert) {
2590
			case TCPTLS_ALERT_STOP:
2591
			case TCPTLS_ALERT_STOP:
2591
				goto cleanup;
2592
				goto cleanup;
2592
			case TCPTLS_ALERT_DATA:
2593
			case TCPTLS_ALERT_DATA:
2593
				ao2_lock(me);
2594
				ao2_lock(me);
2594
				if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
2595
				if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
2595
					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");
2596
				} 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) {
2597
					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");
2598
				}
2599
				}
2599

    
   
2600

   
2600
				if (packet) {
2601
				if (packet) {
2601
					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");
2602
				}
2603
				}
2603
				ao2_unlock(me);
2604
				ao2_unlock(me);
2604
				break;
2605
				break;
2605
			default:
2606
			default:
2606
				ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
2607
				ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
2607
			}
2608
			}
2608
		}
2609
		}
2609
	}
2610
	}
2610

    
   
2611

   
2611
	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");
2612

    
   
2613

   
2613
cleanup:
2614
cleanup:
2614
	if (me) {
2615
	if (me) {
2615
		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");
2616
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2617
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2617
	}
2618
	}
2618
	deinit_req(&reqcpy);
2619
	deinit_req(&reqcpy);
2619
	deinit_req(&req);
2620
	deinit_req(&req);
2620

    
   
2621

   
2621
	/* 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 */
2622
	if (ca) {
2623
	if (ca) {
2623
		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");
2624
	}
2625
	}
2625

    
   
2626

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

    
   
2639

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

    
   
2645

   
2645
/* 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
2646
   peers */
2647
   peers */
2647
static int peer_is_marked(void *peerobj, void *arg, int flags)
2648
static int peer_is_marked(void *peerobj, void *arg, int flags)
2648
{
2649
{
2649
	struct sip_peer *peer = peerobj;
2650
	struct sip_peer *peer = peerobj;
2650
	if (peer->the_mark && peer->pokeexpire != -1) {
2651
	if (peer->the_mark && peer->pokeexpire != -1) {
2651
		AST_SCHED_DEL(sched, peer->pokeexpire);
2652
		AST_SCHED_DEL(sched, peer->pokeexpire);
2652
	}
2653
	}
2653
	return peer->the_mark ? CMP_MATCH : 0;
2654
	return peer->the_mark ? CMP_MATCH : 0;
2654
}
2655
}
2655

    
   
2656

   
2656

    
   
2657

   
2657
/* \brief Unlink all marked peers from ao2 containers */
2658
/* \brief Unlink all marked peers from ao2 containers */
2658
static void unlink_marked_peers_from_tables(void)
2659
static void unlink_marked_peers_from_tables(void)
2659
{
2660
{
2660
	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,
2661
						"initiating callback to remove marked peers");
2662
						"initiating callback to remove marked peers");
2662
	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,
2663
						"initiating callback to remove marked peers");
2664
						"initiating callback to remove marked peers");
2664
}
2665
}
2665

    
   
2666

   
2666
/* \brief Unlink single peer from all ao2 containers */
2667
/* \brief Unlink single peer from all ao2 containers */
2667
static void unlink_peer_from_tables(struct sip_peer *peer)
2668
static void unlink_peer_from_tables(struct sip_peer *peer)
2668
{
2669
{
2669
	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");
2670
	if (!ast_sockaddr_isnull(&peer->addr)) {
2671
	if (!ast_sockaddr_isnull(&peer->addr)) {
2671
		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");
2672
	}
2673
	}
2673
}
2674
}
2674

    
   
2675

   
2675
/*!
2676
/*!
2676
 * helper functions to unreference various types of objects.
2677
 * helper functions to unreference various types of objects.
2677
 * 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
2678
 * destructor on each call, which removes the chance of errors.
2679
 * destructor on each call, which removes the chance of errors.
2679
 */
2680
 */
2680
static void *unref_peer(struct sip_peer *peer, char *tag)
2681
static void *unref_peer(struct sip_peer *peer, char *tag)
2681
{
2682
{
2682
	ao2_t_ref(peer, -1, tag);
2683
	ao2_t_ref(peer, -1, tag);
2683
	return NULL;
2684
	return NULL;
2684
}
2685
}
2685

    
   
2686

   
2686
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)
2687
{
2688
{
2688
	ao2_t_ref(peer, 1, tag);
2689
	ao2_t_ref(peer, 1, tag);
2689
	return peer;
2690
	return peer;
2690
}
2691
}
2691

    
   
2692

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

    
   
2718

   
2718
 /*!
2719
 /*!
2719
 * \brief Unlink a dialog from the dialogs_checkrtp container
2720
 * \brief Unlink a dialog from the dialogs_checkrtp container
2720
 */
2721
 */
2721
static void *dialog_unlink_rtpcheck(struct sip_pvt *dialog)
2722
static void *dialog_unlink_rtpcheck(struct sip_pvt *dialog)
2722
{
2723
{
2723
	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");
2724
	return NULL;
2725
	return NULL;
2725
}
2726
}
2726

    
   
2727

   
2727
/*!
2728
/*!
2728
 * \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
2729
 * that it may be currently stored.
2730
 * that it may be currently stored.
2730
 *
2731
 *
2731
 * \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
2732
 * function does not release that reference.
2733
 * function does not release that reference.
2733
 */
2734
 */
2734
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)
2735
{
2736
{
2736
	struct sip_pkt *cp;
2737
	struct sip_pkt *cp;
2737

    
   
2738

   
2738
	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");
2739

    
   
2740

   
2740
	ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
2741
	ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
2741
	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");
2742
	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");
2743

    
   
2744

   
2744
	/* Unlink us from the owner (channel) if we have one */
2745
	/* Unlink us from the owner (channel) if we have one */
2745
	if (dialog->owner) {
2746
	if (dialog->owner) {
2746
		if (lockowner) {
2747
		if (lockowner) {
2747
			ast_channel_lock(dialog->owner);
2748
			ast_channel_lock(dialog->owner);
2748
		}
2749
		}
2749
		ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2750
		ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2750
		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");
2751
		if (lockowner) {
2752
		if (lockowner) {
2752
			ast_channel_unlock(dialog->owner);
2753
			ast_channel_unlock(dialog->owner);
2753
		}
2754
		}
2754
	}
2755
	}
2755
	if (dialog->registry) {
2756
	if (dialog->registry) {
2756
		if (dialog->registry->call == dialog) {
2757
		if (dialog->registry->call == dialog) {
2757
			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");
2758
		}
2759
		}
2759
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2760
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2760
	}
2761
	}
2761
	if (dialog->stateid > -1) {
2762
	if (dialog->stateid > -1) {
2762
		ast_extension_state_del(dialog->stateid, NULL);
2763
		ast_extension_state_del(dialog->stateid, NULL);
2763
		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.");
2764
		dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2765
		dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2765
	}
2766
	}
2766
	/* Remove link from peer to subscription of MWI */
2767
	/* Remove link from peer to subscription of MWI */
2767
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
2768
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
2768
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2769
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2769
	}
2770
	}
2770
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
2771
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
2771
		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");
2772
	}
2773
	}
2773

    
   
2774

   
2774
	/* remove all current packets in this dialog */
2775
	/* remove all current packets in this dialog */
2775
	while((cp = dialog->packets)) {
2776
	while((cp = dialog->packets)) {
2776
		dialog->packets = dialog->packets->next;
2777
		dialog->packets = dialog->packets->next;
2777
		AST_SCHED_DEL(sched, cp->retransid);
2778
		AST_SCHED_DEL(sched, cp->retransid);
2778
		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");
2779
		if (cp->data) {
2780
		if (cp->data) {
2780
			ast_free(cp->data);
2781
			ast_free(cp->data);
2781
		}
2782
		}
2782
		ast_free(cp);
2783
		ast_free(cp);
2783
	}
2784
	}
2784

    
   
2785

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

    
   
2787

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

    
   
2793

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

    
   
2797

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

    
   
2799

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

    
   
2803

   
2803
	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");
2804
	return NULL;
2805
	return NULL;
2805
}
2806
}
2806

    
   
2807

   
2807
void *registry_unref(struct sip_registry *reg, char *tag)
2808
void *registry_unref(struct sip_registry *reg, char *tag)
2808
{
2809
{
2809
	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);
2810
	ASTOBJ_UNREF(reg, sip_registry_destroy);
2811
	ASTOBJ_UNREF(reg, sip_registry_destroy);
2811
	return NULL;
2812
	return NULL;
2812
}
2813
}
2813

    
   
2814

   
2814
/*! \brief Add object reference to SIP registry */
2815
/*! \brief Add object reference to SIP registry */
2815
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)
2816
{
2817
{
2817
	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);
2818
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
2819
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
2819
}
2820
}
2820

    
   
2821

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

    
   
2828

   
2828
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, ...)
2829
	__attribute__((format(printf, 2, 3)));
2830
	__attribute__((format(printf, 2, 3)));
2830

    
   
2831

   
2831

    
   
2832

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

    
   
2838

   
2838
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)
2839
{
2840
{
2840
	if (pvt->final_destruction_scheduled) {
2841
	if (pvt->final_destruction_scheduled) {
2841
		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. */
2842
	}
2843
	}
2843
	if(pvt->needdestroy != 1) {
2844
	if(pvt->needdestroy != 1) {
2844
		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");
2845
	}
2846
	}
2846
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
2847
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
2847
	pvt->needdestroy = 1;
2848
	pvt->needdestroy = 1;
2848
}
2849
}
2849

    
   
2850

   
2850
/*! \brief Initialize the initital request packet in the pvt structure.
2851
/*! \brief Initialize the initital request packet in the pvt structure.
2851
 	This packet is used for creating replies and future requests in
2852
 	This packet is used for creating replies and future requests in
2852
	a dialog */
2853
	a dialog */
2853
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)
2854
{
2855
{
2855
	if (p->initreq.headers) {
2856
	if (p->initreq.headers) {
2856
		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);
2857
	} else {
2858
	} else {
2858
		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);
2859
	}
2860
	}
2860
	/* Use this as the basis */
2861
	/* Use this as the basis */
2861
	copy_request(&p->initreq, req);
2862
	copy_request(&p->initreq, req);
2862
	parse_request(&p->initreq);
2863
	parse_request(&p->initreq);
2863
	if (req->debug) {
2864
	if (req->debug) {
2864
		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);
2865
	}
2866
	}
2866
}
2867
}
2867

    
   
2868

   
2868
/*! \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 */
2869
static void sip_alreadygone(struct sip_pvt *dialog)
2870
static void sip_alreadygone(struct sip_pvt *dialog)
2870
{
2871
{
2871
	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);
2872
	dialog->alreadygone = 1;
2873
	dialog->alreadygone = 1;
2873
}
2874
}
2874

    
   
2875

   
2875
/*! 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 */
2876
static int proxy_update(struct sip_proxy *proxy)
2877
static int proxy_update(struct sip_proxy *proxy)
2877
{
2878
{
2878
	/* if it's actually an IP address and not a name,
2879
	/* if it's actually an IP address and not a name,
2879
           there's no need for a managed lookup */
2880
           there's no need for a managed lookup */
2880
	if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
2881
	if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
2881
		/* 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 */
2882
		/* XXX Todo - if we have proxy port, don't do SRV */
2883
		/* XXX Todo - if we have proxy port, don't do SRV */
2883
		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 */
2884
		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) {
2885
				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);
2886
				return FALSE;
2887
				return FALSE;
2887
		}
2888
		}
2888

    
   
2889

   
2889
	}
2890
	}
2890

    
   
2891

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

    
   
2893

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

    
   
2897

   
2897
/*! \brief converts ascii port to int representation. If no
2898
/*! \brief converts ascii port to int representation. If no
2898
 *  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
2899
 *  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.
2900
 */
2901
 */
2901
unsigned int port_str2int(const char *pt, unsigned int standard)
2902
unsigned int port_str2int(const char *pt, unsigned int standard)
2902
{
2903
{
2903
	int port = standard;
2904
	int port = standard;
2904
	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)) {
2905
		port = standard;
2906
		port = standard;
2906
	}
2907
	}
2907

    
   
2908

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

    
   
2911

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

    
   
2934

   
2934
/*! \brief returns true if 'name' (with optional trailing whitespace)
2935
/*! \brief returns true if 'name' (with optional trailing whitespace)
2935
 * matches the sip method 'id'.
2936
 * matches the sip method 'id'.
2936
 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2937
 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2937
 * a case-insensitive comparison to be more tolerant.
2938
 * a case-insensitive comparison to be more tolerant.
2938
 * 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
2939
 */
2940
 */
2940
static int method_match(enum sipmethod id, const char *name)
2941
static int method_match(enum sipmethod id, const char *name)
2941
{
2942
{
2942
	int len = strlen(sip_methods[id].text);
2943
	int len = strlen(sip_methods[id].text);
2943
	int l_name = name ? strlen(name) : 0;
2944
	int l_name = name ? strlen(name) : 0;
2944
	/* 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 */
2945
	return (l_name >= len && name[len] < 33 &&
2946
	return (l_name >= len && name[len] < 33 &&
2946
		!strncasecmp(sip_methods[id].text, name, len));
2947
		!strncasecmp(sip_methods[id].text, name, len));
2947
}
2948
}
2948

    
   
2949

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

    
   
2965

   
2965
/*! \brief See if we pass debug IP filter */
2966
/*! \brief See if we pass debug IP filter */
2966
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)
2967
{
2968
{
2968
	/* Can't debug if sipdebug is not enabled */
2969
	/* Can't debug if sipdebug is not enabled */
2969
	if (!sipdebug) {
2970
	if (!sipdebug) {
2970
		return 0;
2971
		return 0;
2971
	}
2972
	}
2972

    
   
2973

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

    
   
2978

   
2978
	/* 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
2979
	 * addresses, otherwise compare the address and port
2980
	 * addresses, otherwise compare the address and port
2980
	 */
2981
	 */
2981
	if (ast_sockaddr_port(&debugaddr)) {
2982
	if (ast_sockaddr_port(&debugaddr)) {
2982
		return !ast_sockaddr_cmp(&debugaddr, addr);
2983
		return !ast_sockaddr_cmp(&debugaddr, addr);
2983
	} else {
2984
	} else {
2984
		return !ast_sockaddr_cmp_addr(&debugaddr, addr);
2985
		return !ast_sockaddr_cmp_addr(&debugaddr, addr);
2985
	}
2986
	}
2986
}
2987
}
2987

    
   
2988

   
2988
/*! \brief The real destination address for a write */
2989
/*! \brief The real destination address for a write */
2989
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)
2990
{
2991
{
2991
	if (p->outboundproxy) {
2992
	if (p->outboundproxy) {
2992
		return &p->outboundproxy->ip;
2993
		return &p->outboundproxy->ip;
2993
	}
2994
	}
2994

    
   
2995

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

    
   
2998

   
2998
/*! \brief Display SIP nat mode */
2999
/*! \brief Display SIP nat mode */
2999
static const char *sip_nat_mode(const struct sip_pvt *p)
3000
static const char *sip_nat_mode(const struct sip_pvt *p)
3000
{
3001
{
3001
	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";
3002
}
3003
}
3003

    
   
3004

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

    
   
3013

   
3013
/*! \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 */
3014
static int get_transport_str2enum(const char *transport)
3015
static int get_transport_str2enum(const char *transport)
3015
{
3016
{
3016
	int res = 0;
3017
	int res = 0;
3017

    
   
3018

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

    
   
3022

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

    
   
3032

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

    
   
3035

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

    
   
3056

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

    
   
3068

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

    
   
3071

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

    
   
3082

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

    
   
3085

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

    
   
3098

   
3098
/*! \brief Return transport of dialog.
3099
/*! \brief Return transport of dialog.
3099
	\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
3100
	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
3101
	"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.
3102
	\todo Fix this function to work correctly
3103
	\todo Fix this function to work correctly
3103
*/
3104
*/
3104
static inline const char *get_transport_pvt(struct sip_pvt *p)
3105
static inline const char *get_transport_pvt(struct sip_pvt *p)
3105
{
3106
{
3106
	if (p->outboundproxy && p->outboundproxy->transport) {
3107
	if (p->outboundproxy && p->outboundproxy->transport) {
3107
		set_socket_transport(&p->socket, p->outboundproxy->transport);
3108
		set_socket_transport(&p->socket, p->outboundproxy->transport);
3108
	}
3109
	}
3109

    
   
3110

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

    
   
3113

   
3113
/*! \brief Transmit SIP message
3114
/*! \brief Transmit SIP message
3114
	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)
3115
	Called by retrans_pkt, send_request, send_response and
3116
	Called by retrans_pkt, send_request, send_response and
3116
	__sip_reliable_xmit
3117
	__sip_reliable_xmit
3117
	\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.
3118
*/
3119
*/
3119
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)
3120
{
3121
{
3121
	int res = 0;
3122
	int res = 0;
3122
	const struct ast_sockaddr *dst = sip_real_dst(p);
3123
	const struct ast_sockaddr *dst = sip_real_dst(p);
3123

    
   
3124

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

    
   
3126

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

    
   
3130

   
3130
	if (p->socket.type == SIP_TRANSPORT_UDP) {
3131
	if (p->socket.type == SIP_TRANSPORT_UDP) {
3131
		res = ast_sendto(p->socket.fd, data->str, len, 0, dst);
3132
		res = ast_sendto(p->socket.fd, data->str, len, 0, dst);
3132
	} else if (p->socket.tcptls_session) {
3133
	} else if (p->socket.tcptls_session) {
3133
		res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
3134
		res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
3134
	} else {
3135
	} else {
3135
		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");
3136
		return XMIT_ERROR;
3137
		return XMIT_ERROR;
3137
	}
3138
	}
3138

    
   
3139

   
3139
	if (res == -1) {
3140
	if (res == -1) {
3140
		switch (errno) {
3141
		switch (errno) {
3141
		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 */
3142
		case EHOSTUNREACH: 	/* Host can't be reached */
3143
		case EHOSTUNREACH: 	/* Host can't be reached */
3143
		case ENETDOWN: 		/* Interface down */
3144
		case ENETDOWN: 		/* Interface down */
3144
		case ENETUNREACH:	/* Network failure */
3145
		case ENETUNREACH:	/* Network failure */
3145
		case ECONNREFUSED:      /* ICMP port unreachable */
3146
		case ECONNREFUSED:      /* ICMP port unreachable */
3146
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */
3147
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */
3147
		}
3148
		}
3148
	}
3149
	}
3149
	if (res != len) {
3150
	if (res != len) {
3150
		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));
3151
	}
3152
	}
3152

    
   
3153

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

    
   
3156

   
3156
/*! \brief Build a Via header for a request */
3157
/*! \brief Build a Via header for a request */
3157
static void build_via(struct sip_pvt *p)
3158
static void build_via(struct sip_pvt *p)
3158
{
3159
{
3159
	/* Work around buggy UNIDEN UIP200 firmware */
3160
	/* Work around buggy UNIDEN UIP200 firmware */
3160
	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" : "";
3161

    
   
3162

   
3162
	/* 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 */
3163
	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",
3164
		 get_transport_pvt(p),
3165
		 get_transport_pvt(p),
3165
		 ast_sockaddr_stringify(&p->ourip),
3166
		 ast_sockaddr_stringify(&p->ourip),
3166
		 (int) p->branch, rport);
3167
		 (int) p->branch, rport);
3167
}
3168
}
3168

    
   
3169

   
3169
/*! \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?
3170
 *
3171
 *
3171
 * 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
3172
 * 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
3173
 * externaddr or can get away with our internal bindaddr
3174
 * externaddr or can get away with our internal bindaddr
3174
 * 'us' is always overwritten.
3175
 * 'us' is always overwritten.
3175
 */
3176
 */
3176
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)
3177
{
3178
{
3178
	struct ast_sockaddr theirs;
3179
	struct ast_sockaddr theirs;
3179

    
   
3180

   
3180
	/* 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
3181
	 * reachable IP address and port. This is done if:
3182
	 * reachable IP address and port. This is done if:
3182
	 * 1. we have a localaddr list (containing 'internal' addresses marked
3183
	 * 1. we have a localaddr list (containing 'internal' addresses marked
3183
	 *    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,
3184
	 *    and AST_SENSE_ALLOW on 'external' ones);
3185
	 *    and AST_SENSE_ALLOW on 'external' ones);
3185
	 * 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
3186
	 *    externally visible address;
3187
	 *    externally visible address;
3187
	 * 3. the remote address, 'them', is external;
3188
	 * 3. the remote address, 'them', is external;
3188
	 * 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
3189
	 *    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.
3190
	 *    This fourth condition is checked later.
3191
	 *    This fourth condition is checked later.
3191
	 */
3192
	 */
3192
	int want_remap = 0;
3193
	int want_remap = 0;
3193

    
   
3194

   
3194
	ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
3195
	ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
3195
	/* 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' */
3196
	ast_ouraddrfor(them, us);
3197
	ast_ouraddrfor(them, us);
3197
	ast_sockaddr_copy(&theirs, them);
3198
	ast_sockaddr_copy(&theirs, them);
3198

    
   
3199

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

    
   
3211

   
3211
	if (want_remap &&
3212
	if (want_remap &&
3212
	    (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
3213
	    (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
3213
		/* 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 */
3214
		if (externexpire && time(NULL) >= externexpire) {
3215
		if (externexpire && time(NULL) >= externexpire) {
3215
			if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
3216
			if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
3216
				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);
3217
			}
3218
			}
3218
			externexpire = time(NULL) + externrefresh;
3219
			externexpire = time(NULL) + externrefresh;
3219
		}
3220
		}
3220
		if (!ast_sockaddr_isnull(&externaddr)) {
3221
		if (!ast_sockaddr_isnull(&externaddr)) {
3221
			ast_sockaddr_copy(us, &externaddr);
3222
			ast_sockaddr_copy(us, &externaddr);
3222
			switch (p->socket.type) {
3223
			switch (p->socket.type) {
3223
			case SIP_TRANSPORT_TCP:
3224
			case SIP_TRANSPORT_TCP:
3224
				if (!externtcpport && ast_sockaddr_port(&externaddr)) {
3225
				if (!externtcpport && ast_sockaddr_port(&externaddr)) {
3225
					/* for consistency, default to the externaddr port */
3226
					/* for consistency, default to the externaddr port */
3226
					externtcpport = ast_sockaddr_port(&externaddr);
3227
					externtcpport = ast_sockaddr_port(&externaddr);
3227
				}
3228
				}
3228
				ast_sockaddr_set_port(us, externtcpport);
3229
				ast_sockaddr_set_port(us, externtcpport);
3229
				break;
3230
				break;
3230
			case SIP_TRANSPORT_TLS:
3231
			case SIP_TRANSPORT_TLS:
3231
				ast_sockaddr_set_port(us, externtlsport);
3232
				ast_sockaddr_set_port(us, externtlsport);
3232
				break;
3233
				break;
3233
			case SIP_TRANSPORT_UDP:
3234
			case SIP_TRANSPORT_UDP:
3234
				if (!ast_sockaddr_port(&externaddr)) {
3235
				if (!ast_sockaddr_port(&externaddr)) {
3235
					ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3236
					ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3236
				}
3237
				}
3237
				break;
3238
				break;
3238
			default:
3239
			default:
3239
				break;
3240
				break;
3240
			}
3241
			}
3241
		}
3242
		}
3242
		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",
3243
			  ast_sockaddr_stringify(them));
3244
			  ast_sockaddr_stringify(them));
3244
	} else if (p) {
3245
	} else if (p) {
3245
		/* 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. */
3246
		switch (p->socket.type) {
3247
		switch (p->socket.type) {
3247
		case SIP_TRANSPORT_TCP:
3248
		case SIP_TRANSPORT_TCP:
3248
			if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
3249
			if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
3249
				ast_sockaddr_copy(us,
3250
				ast_sockaddr_copy(us,
3250
						  &sip_tcp_desc.local_address);
3251
						  &sip_tcp_desc.local_address);
3251
			} else {
3252
			} else {
3252
				ast_sockaddr_set_port(us,
3253
				ast_sockaddr_set_port(us,
3253
						      ast_sockaddr_port(&sip_tcp_desc.local_address));
3254
						      ast_sockaddr_port(&sip_tcp_desc.local_address));
3254
			}
3255
			}
3255
			break;
3256
			break;
3256
		case SIP_TRANSPORT_TLS:
3257
		case SIP_TRANSPORT_TLS:
3257
			if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
3258
			if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
3258
				ast_sockaddr_copy(us,
3259
				ast_sockaddr_copy(us,
3259
						  &sip_tls_desc.local_address);
3260
						  &sip_tls_desc.local_address);
3260
			} else {
3261
			} else {
3261
				ast_sockaddr_set_port(us,
3262
				ast_sockaddr_set_port(us,
3262
						      ast_sockaddr_port(&sip_tls_desc.local_address));
3263
						      ast_sockaddr_port(&sip_tls_desc.local_address));
3263
			}
3264
			}
3264
			break;
3265
			break;
3265
		case SIP_TRANSPORT_UDP:
3266
		case SIP_TRANSPORT_UDP:
3266
			/* fall through on purpose */
3267
			/* fall through on purpose */
3267
		default:
3268
		default:
3268
			if (!ast_sockaddr_is_any(&bindaddr)) {
3269
			if (!ast_sockaddr_is_any(&bindaddr)) {
3269
				ast_sockaddr_copy(us, &bindaddr);
3270
				ast_sockaddr_copy(us, &bindaddr);
3270
			}
3271
			}
3271
			if (!ast_sockaddr_port(us)) {
3272
			if (!ast_sockaddr_port(us)) {
3272
				ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3273
				ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3273
			}
3274
			}
3274
		}
3275
		}
3275
	} else if (!ast_sockaddr_is_any(&bindaddr)) {
3276
	} else if (!ast_sockaddr_is_any(&bindaddr)) {
3276
		ast_sockaddr_copy(us, &bindaddr);
3277
		ast_sockaddr_copy(us, &bindaddr);
3277
	}
3278
	}
3278
	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));
3279
}
3280
}
3280

    
   
3281

   
3281
/*! \brief Append to SIP dialog history with arg list  */
3282
/*! \brief Append to SIP dialog history with arg list  */
3282
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)
3283
{
3284
{
3284
	char buf[80], *c = buf; /* max history length */
3285
	char buf[80], *c = buf; /* max history length */
3285
	struct sip_history *hist;
3286
	struct sip_history *hist;
3286
	int l;
3287
	int l;
3287

    
   
3288

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

    
   
3309

   
3309
/*! \brief Append to SIP dialog history with arg list  */
3310
/*! \brief Append to SIP dialog history with arg list  */
3310
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, ...)
3311
{
3312
{
3312
	va_list ap;
3313
	va_list ap;
3313

    
   
3314

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

    
   
3318

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

    
   
3322

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

    
   
3326

   
3326
	return;
3327
	return;
3327
}
3328
}
3328

    
   
3329

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

    
   
3338

   
3338
	/* 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
3339
	 * 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
3340
	 * 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. */
3341
	if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
3342
	if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
3342
		pkt->retrans_stop = 1;
3343
		pkt->retrans_stop = 1;
3343
	}
3344
	}
3344

    
   
3345

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

    
   
3348

   
3348
	if (!pkt->retrans_stop) {
3349
	if (!pkt->retrans_stop) {
3349
		pkt->retrans++;
3350
		pkt->retrans++;
3350
		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 */
3351
			if (sipdebug) {
3352
			if (sipdebug) {
3352
				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",
3353
					pkt->retransid,
3354
					pkt->retransid,
3354
					sip_methods[pkt->method].text,
3355
					sip_methods[pkt->method].text,
3355
					pkt->method);
3356
					pkt->method);
3356
			}
3357
			}
3357
		} else {
3358
		} else {
3358
			int siptimer_a;
3359
			int siptimer_a;
3359

    
   
3360

   
3360
			if (sipdebug) {
3361
			if (sipdebug) {
3361
				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",
3362
					pkt->retransid,
3363
					pkt->retransid,
3363
					pkt->retrans,
3364
					pkt->retrans,
3364
					sip_methods[pkt->method].text,
3365
					sip_methods[pkt->method].text,
3365
					pkt->method);
3366
					pkt->method);
3366
			}
3367
			}
3367
			if (!pkt->timer_a) {
3368
			if (!pkt->timer_a) {
3368
				pkt->timer_a = 2 ;
3369
				pkt->timer_a = 2 ;
3369
			} else {
3370
			} else {
3370
				pkt->timer_a = 2 * pkt->timer_a;
3371
				pkt->timer_a = 2 * pkt->timer_a;
3371
			}
3372
			}
3372

    
   
3373

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

    
   
3379

   
3379
			/* Reschedule re-transmit */
3380
			/* Reschedule re-transmit */
3380
			reschedule = siptimer_a;
3381
			reschedule = siptimer_a;
3381
			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",
3382
				pkt->retrans + 1,
3383
				pkt->retrans + 1,
3383
				siptimer_a,
3384
				siptimer_a,
3384
				pkt->timer_t1,
3385
				pkt->timer_t1,
3385
				pkt->retransid);
3386
				pkt->retransid);
3386
		}
3387
		}
3387

    
   
3388

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

    
   
3396

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

    
   
3399

   
3399
		/* 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,
3400
		 * 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
3401
		 * 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
3402
		 * 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
3403
		 * call to this function by the scheduler. */
3404
		 * call to this function by the scheduler. */
3404
		if (xmitres != XMIT_ERROR) {
3405
		if (xmitres != XMIT_ERROR) {
3405
			if (reschedule >= diff) {
3406
			if (reschedule >= diff) {
3406
				pkt->retrans_stop = 1;
3407
				pkt->retrans_stop = 1;
3407
				reschedule = diff;
3408
				reschedule = diff;
3408
			}
3409
			}
3409
			sip_pvt_unlock(pkt->owner);
3410
			sip_pvt_unlock(pkt->owner);
3410
			return  reschedule;
3411
			return  reschedule;
3411
		}
3412
		}
3412
	}
3413
	}
3413

    
   
3414

   
3414
	/* 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
3415
	 * transmission error, either way destroy the scheduler item and this packet. */
3416
	 * transmission error, either way destroy the scheduler item and this packet. */
3416

    
   
3417

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

    
   
3419

   
3419
	if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
3420
	if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
3420
		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 */
3421
			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"
3422
				"Packet timed out after %dms with no response\n",
3423
				"Packet timed out after %dms with no response\n",
3423
				pkt->owner->callid,
3424
				pkt->owner->callid,
3424
				pkt->seqno,
3425
				pkt->seqno,
3425
				pkt->is_fatal ? "Critical" : "Non-critical",
3426
				pkt->is_fatal ? "Critical" : "Non-critical",
3426
				pkt->is_resp ? "Response" : "Request",
3427
				pkt->is_resp ? "Response" : "Request",
3427
				(int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
3428
				(int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
3428
		}
3429
		}
3429
	} else if (pkt->method == SIP_OPTIONS && sipdebug) {
3430
	} else if (pkt->method == SIP_OPTIONS && sipdebug) {
3430
		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);
3431
	}
3432
	}
3432

    
   
3433

   
3433
	if (xmitres == XMIT_ERROR) {
3434
	if (xmitres == XMIT_ERROR) {
3434
		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);
3435
		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)");
3436
	} else {
3437
	} else {
3437
		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)");
3438
	}
3439
	}
3439

    
   
3440

   
3440
	if (pkt->is_fatal) {
3441
	if (pkt->is_fatal) {
3441
		while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
3442
		while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
3442
			sip_pvt_unlock(pkt->owner);	/* SIP_PVT, not channel */
3443
			sip_pvt_unlock(pkt->owner);	/* SIP_PVT, not channel */
3443
			usleep(1);
3444
			usleep(1);
3444
			sip_pvt_lock(pkt->owner);
3445
			sip_pvt_lock(pkt->owner);
3445
		}
3446
		}
3446
		if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
3447
		if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
3447
			pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
3448
			pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
3448
		}
3449
		}
3449
		if (pkt->owner->owner) {
3450
		if (pkt->owner->owner) {
3450
			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);
3451

    
   
3452

   
3452
			if (pkt->is_resp &&
3453
			if (pkt->is_resp &&
3453
				(pkt->response_code >= 200) &&
3454
				(pkt->response_code >= 200) &&
3454
				(pkt->response_code < 300) &&
3455
				(pkt->response_code < 300) &&
3455
				pkt->owner->pendinginvite &&
3456
				pkt->owner->pendinginvite &&
3456
				ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
3457
				ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
3457
				/* 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
3458
				 * 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
3459
				 * 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")
3460
				 * RFC 3261 section 13.3.1.4.
3461
				 * RFC 3261 section 13.3.1.4.
3461
				 * "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
3462
				 * 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
3463
				 * accomplished with a BYE, as described in Section 15." */
3464
				 * accomplished with a BYE, as described in Section 15." */
3464
				pkt->owner->invitestate = INV_TERMINATED;
3465
				pkt->owner->invitestate = INV_TERMINATED;
3465
				pkt->owner->pendinginvite = 0;
3466
				pkt->owner->pendinginvite = 0;
3466
			} else {
3467
			} else {
3467
				/* there is nothing left to do, mark the dialog as gone */
3468
				/* there is nothing left to do, mark the dialog as gone */
3468
				sip_alreadygone(pkt->owner);
3469
				sip_alreadygone(pkt->owner);
3469
			}
3470
			}
3470
			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);
3471
			ast_channel_unlock(pkt->owner->owner);
3472
			ast_channel_unlock(pkt->owner->owner);
3472
		} else {
3473
		} else {
3473
			/* If no channel owner, destroy now */
3474
			/* If no channel owner, destroy now */
3474

    
   
3475

   
3475
			/* 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 */
3476
			if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
3477
			if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
3477
				pvt_set_needdestroy(pkt->owner, "no response to critical packet");
3478
				pvt_set_needdestroy(pkt->owner, "no response to critical packet");
3478
				sip_alreadygone(pkt->owner);
3479
				sip_alreadygone(pkt->owner);
3479
				append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
3480
				append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
3480
			}
3481
			}
3481
		}
3482
		}
3482
	}
3483
	}
3483

    
   
3484

   
3484
	if (pkt->method == SIP_BYE) {
3485
	if (pkt->method == SIP_BYE) {
3485
		/* 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. */
3486
		if (pkt->owner->owner) {
3487
		if (pkt->owner->owner) {
3487
			ast_channel_unlock(pkt->owner->owner);
3488
			ast_channel_unlock(pkt->owner->owner);
3488
		}
3489
		}
3489
		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.");
3490
		pvt_set_needdestroy(pkt->owner, "no response to BYE");
3491
		pvt_set_needdestroy(pkt->owner, "no response to BYE");
3491
	}
3492
	}
3492

    
   
3493

   
3493
	/* Remove the packet */
3494
	/* Remove the packet */
3494
	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) {
3495
		if (cur == pkt) {
3496
		if (cur == pkt) {
3496
			UNLINK(cur, pkt->owner->packets, prev);
3497
			UNLINK(cur, pkt->owner->packets, prev);
3497
			sip_pvt_unlock(pkt->owner);
3498
			sip_pvt_unlock(pkt->owner);
3498
			if (pkt->owner) {
3499
			if (pkt->owner) {
3499
				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");
3500
			}
3501
			}
3501
			if (pkt->data) {
3502
			if (pkt->data) {
3502
				ast_free(pkt->data);
3503
				ast_free(pkt->data);
3503
			}
3504
			}
3504
			pkt->data = NULL;
3505
			pkt->data = NULL;
3505
			ast_free(pkt);
3506
			ast_free(pkt);
3506
			return 0;
3507
			return 0;
3507
		}
3508
		}
3508
	}
3509
	}
3509
	/* error case */
3510
	/* error case */
3510
	ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
3511
	ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
3511
	sip_pvt_unlock(pkt->owner);
3512
	sip_pvt_unlock(pkt->owner);
3512
	return 0;
3513
	return 0;
3513
}
3514
}
3514

    
   
3515

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

    
   
3525

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

    
   
3530

   
3530
	/* 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 */
3531
	/* 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 */
3532
	/*! \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 */
3533
	if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
3534
	if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
3534
		xmitres = __sip_xmit(p, data, len);	/* Send packet */
3535
		xmitres = __sip_xmit(p, data, len);	/* Send packet */
3535
		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 */
3536
			append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
3537
			append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
3537
			return AST_FAILURE;
3538
			return AST_FAILURE;
3538
		} else {
3539
		} else {
3539
			return AST_SUCCESS;
3540
			return AST_SUCCESS;
3540
		}
3541
		}
3541
	}
3542
	}
3542

    
   
3543

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

    
   
3573

   
3573
	pkt->time_sent = ast_tvnow(); /* time packet was sent */
3574
	pkt->time_sent = ast_tvnow(); /* time packet was sent */
3574
	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 */
3575

    
   
3576

   
3576
	/* Schedule retransmission */
3577
	/* Schedule retransmission */
3577
	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);
3578
	if (sipdebug) {
3579
	if (sipdebug) {
3579
		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);
3580
	}
3581
	}
3581

    
   
3582

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

    
   
3584

   
3584
	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 */
3585
		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)");
3586
		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");
3587
		AST_SCHED_DEL(sched, pkt->retransid);
3588
		AST_SCHED_DEL(sched, pkt->retransid);
3588
		p->packets = pkt->next;
3589
		p->packets = pkt->next;
3589
		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");
3590
		ast_free(pkt->data);
3591
		ast_free(pkt->data);
3591
		ast_free(pkt);
3592
		ast_free(pkt);
3592
		return AST_FAILURE;
3593
		return AST_FAILURE;
3593
	} else {
3594
	} else {
3594
		/* 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
3595
		 * 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
3596
		 * 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
3597
		 * 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. */
3598
		if (monitor_thread != AST_PTHREADT_NULL) {
3599
		if (monitor_thread != AST_PTHREADT_NULL) {
3599
			pthread_kill(monitor_thread, SIGURG);
3600
			pthread_kill(monitor_thread, SIGURG);
3600
		}
3601
		}
3601
		return AST_SUCCESS;
3602
		return AST_SUCCESS;
3602
	}
3603
	}
3603
}
3604
}
3604

    
   
3605

   
3605
/*! \brief Kill a SIP dialog (called only by the scheduler)
3606
/*! \brief Kill a SIP dialog (called only by the scheduler)
3606
 * 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,
3607
 * 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
3608
 * rescheduled, we need to call dialog_unref().
3609
 * rescheduled, we need to call dialog_unref().
3609
 */
3610
 */
3610
static int __sip_autodestruct(const void *data)
3611
static int __sip_autodestruct(const void *data)
3611
{
3612
{
3612
	struct sip_pvt *p = (struct sip_pvt *)data;
3613
	struct sip_pvt *p = (struct sip_pvt *)data;
3613

    
   
3614

   
3614
	/* 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 */
3615
	if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
3616
	if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
3616
		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 */
3617
		p->subscribed = NONE;
3618
		p->subscribed = NONE;
3618
		append_history(p, "Subscribestatus", "timeout");
3619
		append_history(p, "Subscribestatus", "timeout");
3619
		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>");
3620
		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 */
3621
	}
3622
	}
3622

    
   
3623

   
3623
	/* If there are packets still waiting for delivery, delay the destruction */
3624
	/* If there are packets still waiting for delivery, delay the destruction */
3624
	if (p->packets) {
3625
	if (p->packets) {
3625
		if (!p->needdestroy) {
3626
		if (!p->needdestroy) {
3626
			char method_str[31];
3627
			char method_str[31];
3627
			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>");
3628
			append_history(p, "ReliableXmit", "timeout");
3629
			append_history(p, "ReliableXmit", "timeout");
3629
			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) {
3630
				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)) {
3631
					pvt_set_needdestroy(p, "autodestruct");
3632
					pvt_set_needdestroy(p, "autodestruct");
3632
				}
3633
				}
3633
			}
3634
			}
3634
			return 10000;
3635
			return 10000;
3635
		} else {
3636
		} else {
3636
			/* They've had their chance to respond. Time to bail */
3637
			/* They've had their chance to respond. Time to bail */
3637
			__sip_pretend_ack(p);
3638
			__sip_pretend_ack(p);
3638
		}
3639
		}
3639
	}
3640
	}
3640

    
   
3641

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

    
   
3644

   
3644

    
   
3645

   
3645
	/*
3646
	/*
3646
	 * 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.
3647
	 */
3648
	 */
3648
	sip_pvt_lock(p);
3649
	sip_pvt_lock(p);
3649
	while (p->owner && ast_channel_trylock(p->owner)) {
3650
	while (p->owner && ast_channel_trylock(p->owner)) {
3650
		sip_pvt_unlock(p);
3651
		sip_pvt_unlock(p);
3651
		sched_yield();
3652
		sched_yield();
3652
		sip_pvt_lock(p);
3653
		sip_pvt_lock(p);
3653
	}
3654
	}
3654

    
   
3655

   
3655
	if (p->owner) {
3656
	if (p->owner) {
3656
		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);
3657
		ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
3658
		ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
3658
		ast_channel_unlock(p->owner);
3659
		ast_channel_unlock(p->owner);
3659
	} else if (p->refer && !p->alreadygone) {
3660
	} else if (p->refer && !p->alreadygone) {
3660
		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);
3661
		transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3662
		transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3662
		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);
3663
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3664
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3664
	} else {
3665
	} else {
3665
		append_history(p, "AutoDestroy", "%s", p->callid);
3666
		append_history(p, "AutoDestroy", "%s", p->callid);
3666
		ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
3667
		ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
3667
		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 */
3668
		/* 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. */
3669
		/* 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 */
3670
		/* sip_destroy also absorbs the reference */
3671
		/* sip_destroy also absorbs the reference */
3671
	}
3672
	}
3672

    
   
3673

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

    
   
3675

   
3675
	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.");
3676

    
   
3677

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

    
   
3680

   
3680
/*! \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.
3681
 *  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
3682
 *  to properly respond to any retransmits. */
3683
 *  to properly respond to any retransmits. */
3683
void sip_scheddestroy_final(struct sip_pvt *p, int ms)
3684
void sip_scheddestroy_final(struct sip_pvt *p, int ms)
3684
{
3685
{
3685
	if (p->final_destruction_scheduled) {
3686
	if (p->final_destruction_scheduled) {
3686
		return; /* already set final destruction */
3687
		return; /* already set final destruction */
3687
	}
3688
	}
3688

    
   
3689

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

    
   
3695

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

    
   
3702

   
3702
	if (ms < 0) {
3703
	if (ms < 0) {
3703
		if (p->timer_t1 == 0) {
3704
		if (p->timer_t1 == 0) {
3704
			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) */
3705
		}
3706
		}
3706
		if (p->timer_b == 0) {
3707
		if (p->timer_b == 0) {
3707
			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) */
3708
		}
3709
		}
3709
		ms = p->timer_t1 * 64;
3710
		ms = p->timer_t1 * 64;
3710
	}
3711
	}
3711
	if (sip_debug_test_pvt(p)) {
3712
	if (sip_debug_test_pvt(p)) {
3712
		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);
3713
	}
3714
	}
3714
	if (sip_cancel_destroy(p)) {
3715
	if (sip_cancel_destroy(p)) {
3715
		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");
3716
	}
3717
	}
3717

    
   
3718

   
3718
	if (p->do_history) {
3719
	if (p->do_history) {
3719
		append_history(p, "SchedDestroy", "%d ms", ms);
3720
		append_history(p, "SchedDestroy", "%d ms", ms);
3720
	}
3721
	}
3721
	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"));
3722

    
   
3723

   
3723
	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) {
3724
		stop_session_timer(p);
3725
		stop_session_timer(p);
3725
	}
3726
	}
3726
}
3727
}
3727

    
   
3728

   
3728
/*! \brief Cancel destruction of SIP dialog.
3729
/*! \brief Cancel destruction of SIP dialog.
3729
 * 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
3730
 * from within the scheduler, this might be the last reference.
3731
 * from within the scheduler, this might be the last reference.
3731
 */
3732
 */
3732
int sip_cancel_destroy(struct sip_pvt *p)
3733
int sip_cancel_destroy(struct sip_pvt *p)
3733
{
3734
{
3734
	int res = 0;
3735
	int res = 0;
3735

    
   
3736

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

    
   
3740

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

    
   
3743

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