Review Board 1.7.16


DIALOG_INFO_XML stale (and timeout) notifiy subscriptions stop BLF's working on Grandstream GXP20xx phones.

Review Request #1813 - Created March 12, 2012 and updated

Alec Davis
1.8 and above
Reviewers
asterisk-dev
Asterisk
This issue is caused by review "handle_request_subscribe is too slow cause of iterating through all sip dialogs" https://reviewboard.asterisk.org/r/901/
commit http://svnview.digium.com/svn/asterisk?view=revision&revision=289623



Some phones (Grandstream GXP20XX series 1.2.5.3 firmware) if rebooted, loose the BLF lights due to the new subscription's "version" being less than the previous subscription's "version".
This happens the instant that asterisk timeouts the previous subscription - which has the much larger "version" sequence number.

The only way for the lights to start working again, is for the current subscription's "version" number to increment past the previous old "version" number.
That period of time could be huge, if the phone isn't rebooted for days.

The workaround has been to reboot the phone twice, within a few minutes of each reboot.
  1st time wait for the BLF's to fail (then reboot again) - which is the timeout period - a few minutes.
  2nd time the lights will work, then fail, then after a few minutes start working again.

This fix prevents the old subscription timeout from updating the phones "version" number. 

This issue doesn't affect the GXP21XX series.

Attempt to show issue byway of example below with some debug output showing call-id and version number.

astrid-test*CLI> core show hints

    -= Registered Asterisk Dial Plan Hints =-
            8601GXP0001@trusted             : Custom:q8601_a8612    State:InUse           Watchers  1
Debug output:

===Set the BLF state to InUse
- Executing [s@macro-custom-agent-inout:13] Set("SIP/GXP0001-00000005", "DEVICE_STATE(Custom:q8601_a8612)=INUSE") in new stack
...
[Mar 14 11:01:39] NOTICE[10819]: chan_sip.c:13136 state_notify_build_xml: ALEC <dialog id="8601GXP0001" call-id="3c65aed02ae1d5df@192.168.5.141"> version=5

=============
Reboot the phone, it gets a new BLF subscription.
=============
[Mar 14 11:02:30] NOTICE[10826]: chan_sip.c:13136 state_notify_build_xml: ALEC <dialog id="8601GXP0001" call-id="79956c0168125400@192.168.5.141"> version=0
===The BLF has correct state of InUse.

...
[Mar 14 11:05:00] NOTICE[10826]: chan_sip.c:13136 state_notify_build_xml: ALEC <dialog id="8601GXP0001" call-id="79956c0168125400@192.168.5.141"> version=1
===The BLF still has correct state of InUse.

...
The timeout 'last notification'
[Mar 14 11:05:09] NOTICE[10826]: chan_sip.c:13131 state_notify_build_xml: ALEC <dialog id="8601GXP0001" call-id="3c65aed02ae1d5df@192.168.5.141" direction="recipient"> version=6
[Mar 14 11:05:09] NOTICE[10826]: chan_sip.c:3868 __sip_autodestruct: ALEC TIMEOUT of SIP subscription 3c65aed02ae1d5df@192.168.5.141
===The BLF has incorrectly gone Idle.

...
[Mar 14 11:15:01] NOTICE[10826]: chan_sip.c:13136 state_notify_build_xml: ALEC <dialog id="8601GXP0001" call-id="79956c0168125400@192.168.5.141"> version=5
===The BLF is still incorrect at Idle.

    -- Registered SIP 'GXP0001' at 192.168.5.141:5066
[Mar 14 11:17:31] NOTICE[10826]: chan_sip.c:13136 state_notify_build_xml: ALEC <dialog id="8601GXP0001" call-id="79956c0168125400@192.168.5.141"> version=6
===The BLF now has correct state of InUse.
In place on a 1.8 deployment for months, our production box with ~80 GXP phones, half of which are the older GXP20XX series.

Changes between revision 1 and 2

1 2
1 2

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

    
   
18

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

    
   
94

   

    
   
95
/*! \li \ref chan_sip.c uses configuration files \ref sip.conf and \ref sip_notify.conf

    
   
96
 * \addtogroup configuration_file

    
   
97
 */

    
   
98

   

    
   
99
/*! \page sip.conf sip.conf

    
   
100
 * \verbinclude sip.conf.sample

    
   
101
 */

    
   
102

   

    
   
103
/*! \page sip_notify.conf sip_notify.conf

    
   
104
 * \verbinclude sip_notify.conf.sample

    
   
105
 */

    
   
106

   
95
/*!
107
/*!
96
 * \page sip_tcp_tls SIP TCP and TLS support
108
 * \page sip_tcp_tls SIP TCP and TLS support
97
 *
109
 *
98
 * \par tcpfixes TCP implementation changes needed
110
 * \par tcpfixes TCP implementation changes needed
99
 * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
111
 * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
100
 * \todo Save TCP/TLS sessions in registry
112
 * \todo Save TCP/TLS sessions in registry
101
 *	If someone registers a SIPS uri, this forces us to set up a TLS connection back.
113
 *	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
114
 * \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.
115
 * \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
116
 * 	The tcpbindaddr config option should only be used to open ADDITIONAL ports
105
 * 	So we should propably go back to
117
 * 	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
118
 *		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)
119
 *				if tlsenable=yes, open TLS port (provided we also have cert)
108
 *		tcpbindaddr = extra address for additional TCP connections
120
 *		tcpbindaddr = extra address for additional TCP connections
109
 *		tlsbindaddr = extra address for additional TCP/TLS connections
121
 *		tlsbindaddr = extra address for additional TCP/TLS connections
110
 *		udpbindaddr = extra address for additional UDP connections
122
 *		udpbindaddr = extra address for additional UDP connections
111
 *			These three options should take multiple IP/port pairs
123
 *			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
124
 *	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
125
 *		the XXXbindaddr options needs to be disabled until we have support for it
114
 *
126
 *
115
 * \todo re-evaluate the transport= setting in sip.conf. This is right now not well
127
 * \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,
128
 * 	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.
129
 *	even if udp is the configured first transport.
118
 *
130
 *
119
 * \todo Be prepared for one outbound and another incoming socket per pvt. This applies
131
 * \todo Be prepared for one outbound and another incoming socket per pvt. This applies
120
 *       specially to communication with other peers (proxies).
132
 *       specially to communication with other peers (proxies).
121
 * \todo We need to test TCP sessions with SIP proxies and in regards
133
 * \todo We need to test TCP sessions with SIP proxies and in regards
122
 *       to the SIP outbound specs.
134
 *       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.
135
 * \todo ;transport=tls was deprecated in RFC3261 and should not be used at all. See section 26.2.2.
124
 *
136
 *
125
 * \todo If the message is smaller than the given Content-length, the request should get a 400 Bad request
137
 * \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)
138
 *       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
139
 * \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
140
 *       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,
141
 * \todo Selection of transport for a request needs to be done after we've parsed all route headers,
130
 *	 also considering outbound proxy options.
142
 *	 also considering outbound proxy options.
131
 *		First request: Outboundproxy, routes, (reg contact or URI. If URI doesn't have port:  DNS naptr, srv, AAA)
143
 *		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
144
 *		Intermediate requests: Outboundproxy(only when forced), routes, contact/uri
133
 *	DNS naptr support is crucial. A SIP uri might lead to a TLS connection.
145
 *	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)
146
 *	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
147
 * \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,
148
 *	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
149
 *	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.
150
 *	MTU (like INIVTE with video, audio and RTT)  TCP should be preferred.
139
 *
151
 *
140
 *	When dialling unconfigured peers (with no port number)  or devices in external domains
152
 *	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,
153
 *	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.
154
 *	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,
155
 *	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
156
 *	\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
157
 *	proxy is configured, these procedures might apply for locating the proxy and determining
146
 *	the transport to use for communication with the proxy.
158
 *	the transport to use for communication with the proxy.
147
 * \par Other bugs to fix ----
159
 * \par Other bugs to fix ----
148
 * __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
160
 * __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.
161
 *	- 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)
162
 * 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
163
 *	- assumes that the contact the UA registers is using the same transport as the REGISTER request, which is
152
 *	  a bad guess.
164
 *	  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.
165
 *      - 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)
166
 * 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
167
 *	- 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
168
 *	  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
169
 *	  fail on in-secure signalling paths if there's no override in our configuration. At least, provide a
158
 *	  channel variable in the dialplan.
170
 *	  channel variable in the dialplan.
159
 * get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
171
 * 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
172
 *	- As above, if we have a SIPS: uri in the refer-to header
161
 *	- Does not check transport in refer_to uri.
173
 *	- Does not check transport in refer_to uri.
162
 */
174
 */
163

    
   
175

   
164
/*** MODULEINFO
176
/*** MODULEINFO
165
	<use type="module">res_crypto</use>
177
	<use type="module">res_crypto</use>

    
   
178
	<use type="module">res_http_websocket</use>
166
	<depend>chan_local</depend>
179
	<depend>chan_local</depend>
167
	<support_level>core</support_level>
180
	<support_level>core</support_level>
168
 ***/
181
 ***/
169

    
   
182

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

    
   
184

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

    
   
191

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

    
   
199

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

    
   
202

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

    
   
220

   
208
*/
221
*/
209

    
   
222

   
210
#include "asterisk.h"
223
#include "asterisk.h"
211

    
   
224

   
212
ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
225
ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
213

    
   
226

   
214
#include <signal.h>
227
#include <signal.h>
215
#include <sys/signal.h>
228
#include <sys/signal.h>
216
#include <regex.h>
229
#include <regex.h>
217
#include <inttypes.h>
230
#include <inttypes.h>
218

    
   
231

   
219
#include "asterisk/network.h"
232
#include "asterisk/network.h"
220
#include "asterisk/paths.h"	/* need ast_config_AST_SYSTEM_NAME */
233
#include "asterisk/paths.h"	/* need ast_config_AST_SYSTEM_NAME */
221
/*
234
/*
222
   Uncomment the define below,  if you are having refcount related memory leaks.
235
   Uncomment the define below,  if you are having refcount related memory leaks.
223
   With this uncommented, this module will generate a file, /tmp/refs, which contains
236
   With this uncommented, this module will generate a file, /tmp/refs, which contains
224
   a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
237
   a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
225
   be modified to ao2_t_* calls, and include a tag describing what is happening with
238
   be modified to ao2_t_* calls, and include a tag describing what is happening with
226
   enough detail, to make pairing up a reference count increment with its corresponding decrement.
239
   enough detail, to make pairing up a reference count increment with its corresponding decrement.
227
   The refcounter program in utils/ can be invaluable in highlighting objects that are not
240
   The refcounter program in utils/ can be invaluable in highlighting objects that are not
228
   balanced, along with the complete history for that object.
241
   balanced, along with the complete history for that object.
229
   In normal operation, the macros defined will throw away the tags, so they do not
242
   In normal operation, the macros defined will throw away the tags, so they do not
230
   affect the speed of the program at all. They can be considered to be documentation.
243
   affect the speed of the program at all. They can be considered to be documentation.
231
*/
244
*/
232
/* #define  REF_DEBUG 1 */
245
/* #define  REF_DEBUG 1 */

    
   
246

   
233
#include "asterisk/lock.h"
247
#include "asterisk/lock.h"
234
#include "asterisk/config.h"
248
#include "asterisk/config.h"
235
#include "asterisk/module.h"
249
#include "asterisk/module.h"
236
#include "asterisk/pbx.h"
250
#include "asterisk/pbx.h"
237
#include "asterisk/sched.h"
251
#include "asterisk/sched.h"
238
#include "asterisk/io.h"
252
#include "asterisk/io.h"
239
#include "asterisk/rtp_engine.h"
253
#include "asterisk/rtp_engine.h"
240
#include "asterisk/udptl.h"
254
#include "asterisk/udptl.h"
241
#include "asterisk/acl.h"
255
#include "asterisk/acl.h"
242
#include "asterisk/manager.h"
256
#include "asterisk/manager.h"
243
#include "asterisk/callerid.h"
257
#include "asterisk/callerid.h"
244
#include "asterisk/cli.h"
258
#include "asterisk/cli.h"
245
#include "asterisk/musiconhold.h"
259
#include "asterisk/musiconhold.h"
246
#include "asterisk/dsp.h"
260
#include "asterisk/dsp.h"
247
#include "asterisk/features.h"
261
#include "asterisk/features.h"
248
#include "asterisk/srv.h"
262
#include "asterisk/srv.h"
249
#include "asterisk/astdb.h"
263
#include "asterisk/astdb.h"
250
#include "asterisk/causes.h"
264
#include "asterisk/causes.h"
251
#include "asterisk/utils.h"
265
#include "asterisk/utils.h"
252
#include "asterisk/file.h"
266
#include "asterisk/file.h"
253
#include "asterisk/astobj2.h"
267
#include "asterisk/astobj2.h"
254
#include "asterisk/dnsmgr.h"
268
#include "asterisk/dnsmgr.h"
255
#include "asterisk/devicestate.h"
269
#include "asterisk/devicestate.h"
256
#include "asterisk/monitor.h"
270
#include "asterisk/monitor.h"
257
#include "asterisk/netsock2.h"
271
#include "asterisk/netsock2.h"
258
#include "asterisk/localtime.h"
272
#include "asterisk/localtime.h"
259
#include "asterisk/abstract_jb.h"
273
#include "asterisk/abstract_jb.h"
260
#include "asterisk/threadstorage.h"
274
#include "asterisk/threadstorage.h"
261
#include "asterisk/translate.h"
275
#include "asterisk/translate.h"
262
#include "asterisk/ast_version.h"
276
#include "asterisk/ast_version.h"
263
#include "asterisk/event.h"
277
#include "asterisk/event.h"
264
#include "asterisk/cel.h"
278
#include "asterisk/cel.h"
265
#include "asterisk/data.h"
279
#include "asterisk/data.h"
266
#include "asterisk/aoc.h"
280
#include "asterisk/aoc.h"
267
#include "asterisk/message.h"
281
#include "asterisk/message.h"
268
#include "sip/include/sip.h"
282
#include "sip/include/sip.h"
269
#include "sip/include/globals.h"
283
#include "sip/include/globals.h"
270
#include "sip/include/config_parser.h"
284
#include "sip/include/config_parser.h"
271
#include "sip/include/reqresp_parser.h"
285
#include "sip/include/reqresp_parser.h"
272
#include "sip/include/sip_utils.h"
286
#include "sip/include/sip_utils.h"
273
#include "sip/include/srtp.h"
287
#include "sip/include/srtp.h"
274
#include "sip/include/sdp_crypto.h"
288
#include "sip/include/sdp_crypto.h"
275
#include "asterisk/ccss.h"
289
#include "asterisk/ccss.h"
276
#include "asterisk/xml.h"
290
#include "asterisk/xml.h"
277
#include "sip/include/dialog.h"
291
#include "sip/include/dialog.h"
278
#include "sip/include/dialplan_functions.h"
292
#include "sip/include/dialplan_functions.h"
279
#include "sip/include/security_events.h"
293
#include "sip/include/security_events.h"

    
   
294
#include "asterisk/sip_api.h"
280

    
   
295

   
281

    
   

   
282
/*** DOCUMENTATION
296
/*** DOCUMENTATION
283
	<application name="SIPDtmfMode" language="en_US">
297
	<application name="SIPDtmfMode" language="en_US">
284
		<synopsis>
298
		<synopsis>
285
			Change the dtmfmode for a SIP call.
299
			Change the dtmfmode for a SIP call.
286
		</synopsis>
300
		</synopsis>
287
		<syntax>
301
		<syntax>
288
			<parameter name="mode" required="true">
302
			<parameter name="mode" required="true">
289
				<enumlist>
303
				<enumlist>
290
					<enum name="inband" />
304
					<enum name="inband" />
291
					<enum name="info" />
305
					<enum name="info" />
292
					<enum name="rfc2833" />
306
					<enum name="rfc2833" />
293
				</enumlist>
307
				</enumlist>
294
			</parameter>
308
			</parameter>
295
		</syntax>
309
		</syntax>
296
		<description>
310
		<description>
297
			<para>Changes the dtmfmode for a SIP call.</para>
311
			<para>Changes the dtmfmode for a SIP call.</para>
298
		</description>
312
		</description>
299
	</application>
313
	</application>
300
	<application name="SIPAddHeader" language="en_US">
314
	<application name="SIPAddHeader" language="en_US">
301
		<synopsis>
315
		<synopsis>
302
			Add a SIP header to the outbound call.
316
			Add a SIP header to the outbound call.
303
		</synopsis>
317
		</synopsis>
304
		<syntax argsep=":">
318
		<syntax argsep=":">
305
			<parameter name="Header" required="true" />
319
			<parameter name="Header" required="true" />
306
			<parameter name="Content" required="true" />
320
			<parameter name="Content" required="true" />
307
		</syntax>
321
		</syntax>
308
		<description>
322
		<description>
309
			<para>Adds a header to a SIP call placed with DIAL.</para>
323
			<para>Adds a header to a SIP call placed with DIAL.</para>
310
			<para>Remember to use the X-header if you are adding non-standard SIP
324
			<para>Remember to use the X-header if you are adding non-standard SIP
311
			headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
325
			headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
312
			Adding the wrong headers may jeopardize the SIP dialog.</para>
326
			Adding the wrong headers may jeopardize the SIP dialog.</para>
313
			<para>Always returns <literal>0</literal>.</para>
327
			<para>Always returns <literal>0</literal>.</para>
314
		</description>
328
		</description>
315
	</application>
329
	</application>
316
	<application name="SIPRemoveHeader" language="en_US">
330
	<application name="SIPRemoveHeader" language="en_US">
317
		<synopsis>
331
		<synopsis>
318
			Remove SIP headers previously added with SIPAddHeader
332
			Remove SIP headers previously added with SIPAddHeader
319
		</synopsis>
333
		</synopsis>
320
		<syntax>
334
		<syntax>
321
			<parameter name="Header" required="false" />
335
			<parameter name="Header" required="false" />
322
		</syntax>
336
		</syntax>
323
		<description>
337
		<description>
324
			<para>SIPRemoveHeader() allows you to remove headers which were previously
338
			<para>SIPRemoveHeader() allows you to remove headers which were previously
325
			added with SIPAddHeader(). If no parameter is supplied, all previously added
339
			added with SIPAddHeader(). If no parameter is supplied, all previously added
326
			headers will be removed. If a parameter is supplied, only the matching headers
340
			headers will be removed. If a parameter is supplied, only the matching headers
327
			will be removed.</para>
341
			will be removed.</para>
328
			<para>For example you have added these 2 headers:</para>
342
			<para>For example you have added these 2 headers:</para>
329
			<para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
343
			<para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
330
			<para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
344
			<para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
331
			<para></para>
345
			<para></para>
332
			<para>// remove all headers</para>
346
			<para>// remove all headers</para>
333
			<para>SIPRemoveHeader();</para>
347
			<para>SIPRemoveHeader();</para>
334
			<para>// remove all P- headers</para>
348
			<para>// remove all P- headers</para>
335
			<para>SIPRemoveHeader(P-);</para>
349
			<para>SIPRemoveHeader(P-);</para>
336
			<para>// remove only the PAI header (note the : at the end)</para>
350
			<para>// remove only the PAI header (note the : at the end)</para>
337
			<para>SIPRemoveHeader(P-Asserted-Identity:);</para>
351
			<para>SIPRemoveHeader(P-Asserted-Identity:);</para>
338
			<para></para>
352
			<para></para>
339
			<para>Always returns <literal>0</literal>.</para>
353
			<para>Always returns <literal>0</literal>.</para>
340
		</description>
354
		</description>
341
	</application>
355
	</application>

    
   
356
	<application name="SIPSendCustomINFO" language="en_US">

    
   
357
		<synopsis>

    
   
358
			Send a custom INFO frame on specified channels.

    
   
359
		</synopsis>

    
   
360
		<syntax>

    
   
361
			<parameter name="Data" required="true" />

    
   
362
			<parameter name="UserAgent" required="false" />

    
   
363
		</syntax>

    
   
364
		<description>

    
   
365
			<para>SIPSendCustomINFO() allows you to send a custom INFO message on all

    
   
366
			active SIP channels or on channels with the specified User Agent. This

    
   
367
			application is only available if TEST_FRAMEWORK is defined.</para>

    
   
368
		</description>

    
   
369
	</application>
342
	<function name="SIP_HEADER" language="en_US">
370
	<function name="SIP_HEADER" language="en_US">
343
		<synopsis>
371
		<synopsis>
344
			Gets the specified SIP header from an incoming INVITE message.
372
			Gets the specified SIP header from an incoming INVITE message.
345
		</synopsis>
373
		</synopsis>
346
		<syntax>
374
		<syntax>
347
			<parameter name="name" required="true" />
375
			<parameter name="name" required="true" />
348
			<parameter name="number">
376
			<parameter name="number">
349
				<para>If not specified, defaults to <literal>1</literal>.</para>
377
				<para>If not specified, defaults to <literal>1</literal>.</para>
350
			</parameter>
378
			</parameter>
351
		</syntax>
379
		</syntax>
352
		<description>
380
		<description>
353
			<para>Since there are several headers (such as Via) which can occur multiple
381
			<para>Since there are several headers (such as Via) which can occur multiple
354
			times, SIP_HEADER takes an optional second argument to specify which header with
382
			times, SIP_HEADER takes an optional second argument to specify which header with
355
			that name to retrieve. Headers start at offset <literal>1</literal>.</para>
383
			that name to retrieve. Headers start at offset <literal>1</literal>.</para>
356
			<para>Please observe that contents of the SDP (an attachment to the 
384
			<para>Please observe that contents of the SDP (an attachment to the 
357
			SIP request) can't be accessed with this function.</para>
385
			SIP request) can't be accessed with this function.</para>
358
		</description>
386
		</description>
359
	</function>
387
	</function>
360
	<function name="SIPPEER" language="en_US">
388
	<function name="SIPPEER" language="en_US">
361
		<synopsis>
389
		<synopsis>
362
			Gets SIP peer information.
390
			Gets SIP peer information.
363
		</synopsis>
391
		</synopsis>
364
		<syntax>
392
		<syntax>
365
			<parameter name="peername" required="true" />
393
			<parameter name="peername" required="true" />
366
			<parameter name="item">
394
			<parameter name="item">
367
				<enumlist>
395
				<enumlist>
368
					<enum name="ip">
396
					<enum name="ip">
369
						<para>(default) The IP address.</para>
397
						<para>(default) The IP address.</para>
370
					</enum>
398
					</enum>
371
					<enum name="port">
399
					<enum name="port">
372
						<para>The port number.</para>
400
						<para>The port number.</para>
373
					</enum>
401
					</enum>
374
					<enum name="mailbox">
402
					<enum name="mailbox">
375
						<para>The configured mailbox.</para>
403
						<para>The configured mailbox.</para>
376
					</enum>
404
					</enum>
377
					<enum name="context">
405
					<enum name="context">
378
						<para>The configured context.</para>
406
						<para>The configured context.</para>
379
					</enum>
407
					</enum>
380
					<enum name="expire">
408
					<enum name="expire">
381
						<para>The epoch time of the next expire.</para>
409
						<para>The epoch time of the next expire.</para>
382
					</enum>
410
					</enum>
383
					<enum name="dynamic">
411
					<enum name="dynamic">
384
						<para>Is it dynamic? (yes/no).</para>
412
						<para>Is it dynamic? (yes/no).</para>
385
					</enum>
413
					</enum>
386
					<enum name="callerid_name">
414
					<enum name="callerid_name">
387
						<para>The configured Caller ID name.</para>
415
						<para>The configured Caller ID name.</para>
388
					</enum>
416
					</enum>
389
					<enum name="callerid_num">
417
					<enum name="callerid_num">
390
						<para>The configured Caller ID number.</para>
418
						<para>The configured Caller ID number.</para>
391
					</enum>
419
					</enum>
392
					<enum name="callgroup">
420
					<enum name="callgroup">
393
						<para>The configured Callgroup.</para>
421
						<para>The configured Callgroup.</para>
394
					</enum>
422
					</enum>
395
					<enum name="pickupgroup">
423
					<enum name="pickupgroup">
396
						<para>The configured Pickupgroup.</para>
424
						<para>The configured Pickupgroup.</para>
397
					</enum>
425
					</enum>

    
   
426
					<enum name="namedcallgroup">

    
   
427
						<para>The configured Named Callgroup.</para>

    
   
428
					</enum>

    
   
429
					<enum name="namedpickupgroup">

    
   
430
						<para>The configured Named Pickupgroup.</para>

    
   
431
					</enum>
398
					<enum name="codecs">
432
					<enum name="codecs">
399
						<para>The configured codecs.</para>
433
						<para>The configured codecs.</para>
400
					</enum>
434
					</enum>
401
					<enum name="status">
435
					<enum name="status">
402
						<para>Status (if qualify=yes).</para>
436
						<para>Status (if qualify=yes).</para>
403
					</enum>
437
					</enum>
404
					<enum name="regexten">
438
					<enum name="regexten">
405
						<para>Extension activated at registration.</para>
439
						<para>Extension activated at registration.</para>
406
					</enum>
440
					</enum>
407
					<enum name="limit">
441
					<enum name="limit">
408
						<para>Call limit (call-limit).</para>
442
						<para>Call limit (call-limit).</para>
409
					</enum>
443
					</enum>
410
					<enum name="busylevel">
444
					<enum name="busylevel">
411
						<para>Configured call level for signalling busy.</para>
445
						<para>Configured call level for signalling busy.</para>
412
					</enum>
446
					</enum>
413
					<enum name="curcalls">
447
					<enum name="curcalls">
414
						<para>Current amount of calls. Only available if call-limit is set.</para>
448
						<para>Current amount of calls. Only available if call-limit is set.</para>
415
					</enum>
449
					</enum>
416
					<enum name="language">
450
					<enum name="language">
417
						<para>Default language for peer.</para>
451
						<para>Default language for peer.</para>
418
					</enum>
452
					</enum>
419
					<enum name="accountcode">
453
					<enum name="accountcode">
420
						<para>Account code for this peer.</para>
454
						<para>Account code for this peer.</para>
421
					</enum>
455
					</enum>
422
					<enum name="useragent">
456
					<enum name="useragent">
423
						<para>Current user agent header used by peer.</para>
457
						<para>Current user agent header used by peer.</para>
424
					</enum>
458
					</enum>
425
					<enum name="maxforwards">
459
					<enum name="maxforwards">
426
						<para>The value used for SIP loop prevention in outbound requests</para>
460
						<para>The value used for SIP loop prevention in outbound requests</para>
427
					</enum>
461
					</enum>
428
					<enum name="chanvar[name]">
462
					<enum name="chanvar[name]">
429
						<para>A channel variable configured with setvar for this peer.</para>
463
						<para>A channel variable configured with setvar for this peer.</para>
430
					</enum>
464
					</enum>
431
					<enum name="codec[x]">
465
					<enum name="codec[x]">
432
						<para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
466
						<para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
433
					</enum>
467
					</enum>
434
				</enumlist>
468
				</enumlist>
435
			</parameter>
469
			</parameter>
436
		</syntax>
470
		</syntax>
437
		<description></description>
471
		<description></description>
438
	</function>
472
	</function>
439
	<function name="SIPCHANINFO" language="en_US">
473
	<function name="SIPCHANINFO" language="en_US">
440
		<synopsis>
474
		<synopsis>
441
			Gets the specified SIP parameter from the current channel.
475
			Gets the specified SIP parameter from the current channel.
442
		</synopsis>
476
		</synopsis>
443
		<syntax>
477
		<syntax>
444
			<parameter name="item" required="true">
478
			<parameter name="item" required="true">
445
				<enumlist>
479
				<enumlist>
446
					<enum name="peerip">
480
					<enum name="peerip">
447
						<para>The IP address of the peer.</para>
481
						<para>The IP address of the peer.</para>
448
					</enum>
482
					</enum>
449
					<enum name="recvip">
483
					<enum name="recvip">
450
						<para>The source IP address of the peer.</para>
484
						<para>The source IP address of the peer.</para>
451
					</enum>
485
					</enum>
452
					<enum name="from">
486
					<enum name="from">
453
						<para>The SIP URI from the <literal>From:</literal> header.</para>
487
						<para>The SIP URI from the <literal>From:</literal> header.</para>
454
					</enum>
488
					</enum>
455
					<enum name="uri">
489
					<enum name="uri">
456
						<para>The SIP URI from the <literal>Contact:</literal> header.</para>
490
						<para>The SIP URI from the <literal>Contact:</literal> header.</para>
457
					</enum>
491
					</enum>
458
					<enum name="useragent">
492
					<enum name="useragent">
459
						<para>The Useragent header used by the peer.</para>
493
						<para>The Useragent header used by the peer.</para>
460
					</enum>
494
					</enum>
461
					<enum name="peername">
495
					<enum name="peername">
462
						<para>The name of the peer.</para>
496
						<para>The name of the peer.</para>
463
					</enum>
497
					</enum>
464
					<enum name="t38passthrough">
498
					<enum name="t38passthrough">
465
						<para><literal>1</literal> if T38 is offered or enabled in this channel,
499
						<para><literal>1</literal> if T38 is offered or enabled in this channel,
466
						otherwise <literal>0</literal>.</para>
500
						otherwise <literal>0</literal>.</para>
467
					</enum>
501
					</enum>
468
				</enumlist>
502
				</enumlist>
469
			</parameter>
503
			</parameter>
470
		</syntax>
504
		</syntax>
471
		<description></description>
505
		<description></description>
472
	</function>
506
	</function>
473
	<function name="CHECKSIPDOMAIN" language="en_US">
507
	<function name="CHECKSIPDOMAIN" language="en_US">
474
		<synopsis>
508
		<synopsis>
475
			Checks if domain is a local domain.
509
			Checks if domain is a local domain.
476
		</synopsis>
510
		</synopsis>
477
		<syntax>
511
		<syntax>
478
			<parameter name="domain" required="true" />
512
			<parameter name="domain" required="true" />
479
		</syntax>
513
		</syntax>
480
		<description>
514
		<description>
481
			<para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
515
			<para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
482
			as a local SIP domain that this Asterisk server is configured to handle.
516
			as a local SIP domain that this Asterisk server is configured to handle.
483
			Returns the domain name if it is locally handled, otherwise an empty string.
517
			Returns the domain name if it is locally handled, otherwise an empty string.
484
			Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
518
			Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
485
		</description>
519
		</description>
486
	</function>
520
	</function>
487
	<manager name="SIPpeers" language="en_US">
521
	<manager name="SIPpeers" language="en_US">
488
		<synopsis>
522
		<synopsis>
489
			List SIP peers (text format).
523
			List SIP peers (text format).
490
		</synopsis>
524
		</synopsis>
491
		<syntax>
525
		<syntax>
492
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
526
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
493
		</syntax>
527
		</syntax>
494
		<description>
528
		<description>
495
			<para>Lists SIP peers in text format with details on current status.
529
			<para>Lists SIP peers in text format with details on current status.
496
			<literal>Peerlist</literal> will follow as separate events, followed by a final event called
530
			<literal>Peerlist</literal> will follow as separate events, followed by a final event called
497
			<literal>PeerlistComplete</literal>.</para>
531
			<literal>PeerlistComplete</literal>.</para>
498
		</description>
532
		</description>
499
	</manager>
533
	</manager>
500
	<manager name="SIPshowpeer" language="en_US">
534
	<manager name="SIPshowpeer" language="en_US">
501
		<synopsis>
535
		<synopsis>
502
			show SIP peer (text format).
536
			show SIP peer (text format).
503
		</synopsis>
537
		</synopsis>
504
		<syntax>
538
		<syntax>
505
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
539
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
506
			<parameter name="Peer" required="true">
540
			<parameter name="Peer" required="true">
507
				<para>The peer name you want to check.</para>
541
				<para>The peer name you want to check.</para>
508
			</parameter>
542
			</parameter>
509
		</syntax>
543
		</syntax>
510
		<description>
544
		<description>
511
			<para>Show one SIP peer with details on current status.</para>
545
			<para>Show one SIP peer with details on current status.</para>
512
		</description>
546
		</description>
513
	</manager>
547
	</manager>
514
	<manager name="SIPqualifypeer" language="en_US">
548
	<manager name="SIPqualifypeer" language="en_US">
515
		<synopsis>
549
		<synopsis>
516
			Qualify SIP peers.
550
			Qualify SIP peers.
517
		</synopsis>
551
		</synopsis>
518
		<syntax>
552
		<syntax>
519
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
553
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
520
			<parameter name="Peer" required="true">
554
			<parameter name="Peer" required="true">
521
				<para>The peer name you want to qualify.</para>
555
				<para>The peer name you want to qualify.</para>
522
			</parameter>
556
			</parameter>
523
		</syntax>
557
		</syntax>
524
		<description>
558
		<description>
525
			<para>Qualify a SIP peer.</para>
559
			<para>Qualify a SIP peer.</para>
526
		</description>
560
		</description>

    
   
561
		<see-also>

    
   
562
			<ref type="managerEvent">SIPqualifypeerdone</ref>

    
   
563
		</see-also>
527
	</manager>
564
	</manager>
528
	<manager name="SIPshowregistry" language="en_US">
565
	<manager name="SIPshowregistry" language="en_US">
529
		<synopsis>
566
		<synopsis>
530
			Show SIP registrations (text format).
567
			Show SIP registrations (text format).
531
		</synopsis>
568
		</synopsis>
532
		<syntax>
569
		<syntax>
533
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
570
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
534
		</syntax>
571
		</syntax>
535
		<description>
572
		<description>
536
			<para>Lists all registration requests and status. Registrations will follow as separate
573
			<para>Lists all registration requests and status. Registrations will follow as separate
537
			events followed by a final event called <literal>RegistrationsComplete</literal>.</para>
574
			events followed by a final event called <literal>RegistrationsComplete</literal>.</para>
538
		</description>
575
		</description>
539
	</manager>
576
	</manager>
540
	<manager name="SIPnotify" language="en_US">
577
	<manager name="SIPnotify" language="en_US">
541
		<synopsis>
578
		<synopsis>
542
			Send a SIP notify.
579
			Send a SIP notify.
543
		</synopsis>
580
		</synopsis>
544
		<syntax>
581
		<syntax>
545
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
582
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
546
			<parameter name="Channel" required="true">
583
			<parameter name="Channel" required="true">
547
				<para>Peer to receive the notify.</para>
584
				<para>Peer to receive the notify.</para>
548
			</parameter>
585
			</parameter>
549
			<parameter name="Variable" required="true">
586
			<parameter name="Variable" required="true">
550
				<para>At least one variable pair must be specified.
587
				<para>At least one variable pair must be specified.
551
				<replaceable>name</replaceable>=<replaceable>value</replaceable></para>
588
				<replaceable>name</replaceable>=<replaceable>value</replaceable></para>
552
			</parameter>
589
			</parameter>
553
		</syntax>
590
		</syntax>
554
		<description>
591
		<description>
555
			<para>Sends a SIP Notify event.</para>
592
			<para>Sends a SIP Notify event.</para>
556
			<para>All parameters for this event must be specified in the body of this request
593
			<para>All parameters for this event must be specified in the body of this request
557
			via multiple <literal>Variable: name=value</literal> sequences.</para>
594
			via multiple <literal>Variable: name=value</literal> sequences.</para>
558
		</description>
595
		</description>
559
	</manager>
596
	</manager>

    
   
597
	<manager name="SIPpeerstatus" language="en_US">

    
   
598
		<synopsis>

    
   
599
			Show the status of one or all of the sip peers.

    
   
600
		</synopsis>

    
   
601
		<syntax>

    
   
602
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />

    
   
603
			<parameter name="Peer" required="false">

    
   
604
				<para>The peer name you want to check.</para>

    
   
605
			</parameter>

    
   
606
		</syntax>

    
   
607
		<description>

    
   
608
			<para>Retrieves the status of one or all of the sip peers.  If no peer name is specified, status

    
   
609
			for all of the sip peers will be retrieved.</para>

    
   
610
		</description>

    
   
611
	</manager>

    
   
612
	<info name="SIPMessageFromInfo" language="en_US" tech="SIP">

    
   
613
		<para>The <literal>from</literal> parameter can be a configured peer name

    
   
614
		or in the form of "display-name" &lt;URI&gt;.</para>

    
   
615
	</info>

    
   
616
	<info name="SIPMessageToInfo" language="en_US" tech="SIP">

    
   
617
		<para>Specifying a prefix of <literal>sip:</literal> will send the

    
   
618
		message as a SIP MESSAGE request.</para>

    
   
619
	</info>
560
 ***/
620
 ***/
561

    
   
621

   
562
static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
622
static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
563
static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
623
static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
564
static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
624
static int default_expiry = DEFAULT_DEFAULT_EXPIRY;

    
   
625
static int min_subexpiry = DEFAULT_MIN_EXPIRY;     /*!< Minimum accepted subscription time */

    
   
626
static int max_subexpiry = DEFAULT_MAX_EXPIRY;     /*!< Maximum accepted subscription time */
565
static int mwi_expiry = DEFAULT_MWI_EXPIRY;
627
static int mwi_expiry = DEFAULT_MWI_EXPIRY;
566

    
   
628

   
567
static int unauth_sessions = 0;
629
static int unauth_sessions = 0;
568
static int authlimit = DEFAULT_AUTHLIMIT;
630
static int authlimit = DEFAULT_AUTHLIMIT;
569
static int authtimeout = DEFAULT_AUTHTIMEOUT;
631
static int authtimeout = DEFAULT_AUTHTIMEOUT;
570

    
   
632

   
571
/*! \brief Global jitterbuffer configuration - by default, jb is disabled
633
/*! \brief Global jitterbuffer configuration - by default, jb is disabled
572
 *  \note Values shown here match the defaults shown in sip.conf.sample */
634
 *  \note Values shown here match the defaults shown in sip.conf.sample */
573
static struct ast_jb_conf default_jbconf =
635
static struct ast_jb_conf default_jbconf =
574
{
636
{
575
	.flags = 0,
637
	.flags = 0,
576
	.max_size = 200,
638
	.max_size = 200,
577
	.resync_threshold = 1000,
639
	.resync_threshold = 1000,
578
	.impl = "fixed",
640
	.impl = "fixed",
579
	.target_extra = 40,
641
	.target_extra = 40,
580
};
642
};
581
static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
643
static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
582

    
   
644

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

    
   
647

   
586
/*! \brief Readable descriptions of device states.
648
/*! \brief Readable descriptions of device states.
587
 *  \note Should be aligned to above table as index */
649
 *  \note Should be aligned to above table as index */
588
static const struct invstate2stringtable {
650
static const struct invstate2stringtable {
589
	const enum invitestates state;
651
	const enum invitestates state;
590
	const char *desc;
652
	const char *desc;
591
} invitestate2string[] = {
653
} invitestate2string[] = {
592
	{INV_NONE,              "None"  },
654
	{INV_NONE,              "None"  },
593
	{INV_CALLING,           "Calling (Trying)"},
655
	{INV_CALLING,           "Calling (Trying)"},
594
	{INV_PROCEEDING,        "Proceeding "},
656
	{INV_PROCEEDING,        "Proceeding "},
595
	{INV_EARLY_MEDIA,       "Early media"},
657
	{INV_EARLY_MEDIA,       "Early media"},
596
	{INV_COMPLETED,         "Completed (done)"},
658
	{INV_COMPLETED,         "Completed (done)"},
597
	{INV_CONFIRMED,         "Confirmed (up)"},
659
	{INV_CONFIRMED,         "Confirmed (up)"},
598
	{INV_TERMINATED,        "Done"},
660
	{INV_TERMINATED,        "Done"},
599
	{INV_CANCELLED,         "Cancelled"}
661
	{INV_CANCELLED,         "Cancelled"}
600
};
662
};
601

    
   
663

   
602
/*! \brief Subscription types that we support. We support
664
/*! \brief Subscription types that we support. We support
603
 * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
665
 * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
604
 * - SIMPLE presence used for device status
666
 * - SIMPLE presence used for device status
605
 * - Voicemail notification subscriptions
667
 * - Voicemail notification subscriptions
606
 */
668
 */
607
static const struct cfsubscription_types {
669
static const struct cfsubscription_types {
608
	enum subscriptiontype type;
670
	enum subscriptiontype type;
609
	const char * const event;
671
	const char * const event;
610
	const char * const mediatype;
672
	const char * const mediatype;
611
	const char * const text;
673
	const char * const text;
612
} subscription_types[] = {
674
} subscription_types[] = {
613
	{ NONE,		   "-",        "unknown",	             "unknown" },
675
	{ NONE,		   "-",        "unknown",	             "unknown" },
614
	/* RFC 4235: SIP Dialog event package */
676
	/* RFC 4235: SIP Dialog event package */
615
	{ DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
677
	{ DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
616
	{ CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
678
	{ CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
617
	{ PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
679
	{ PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
618
	{ XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
680
	{ XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
619
	{ MWI_NOTIFICATION,	"message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
681
	{ MWI_NOTIFICATION,	"message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
620
};
682
};
621

    
   
683

   
622
/*! \brief The core structure to setup dialogs. We parse incoming messages by using
684
/*! \brief The core structure to setup dialogs. We parse incoming messages by using
623
 *  structure and then route the messages according to the type.
685
 *  structure and then route the messages according to the type.
624
 *
686
 *
625
 *  \note Note that sip_methods[i].id == i must hold or the code breaks
687
 *  \note Note that sip_methods[i].id == i must hold or the code breaks
626
 */
688
 */
627
static const struct  cfsip_methods {
689
static const struct  cfsip_methods {
628
	enum sipmethod id;
690
	enum sipmethod id;
629
	int need_rtp;		/*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
691
	int need_rtp;		/*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
630
	char * const text;
692
	char * const text;
631
	enum can_create_dialog can_create;
693
	enum can_create_dialog can_create;
632
} sip_methods[] = {
694
} sip_methods[] = {
633
	{ SIP_UNKNOWN,   RTP,    "-UNKNOWN-",CAN_CREATE_DIALOG },
695
	{ SIP_UNKNOWN,   RTP,    "-UNKNOWN-",CAN_CREATE_DIALOG },
634
	{ SIP_RESPONSE,  NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
696
	{ SIP_RESPONSE,  NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
635
	{ SIP_REGISTER,  NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
697
	{ SIP_REGISTER,  NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
636
	{ SIP_OPTIONS,   NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
698
	{ SIP_OPTIONS,   NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
637
	{ SIP_NOTIFY,    NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
699
	{ SIP_NOTIFY,    NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
638
	{ SIP_INVITE,    RTP,    "INVITE",   CAN_CREATE_DIALOG },
700
	{ SIP_INVITE,    RTP,    "INVITE",   CAN_CREATE_DIALOG },
639
	{ SIP_ACK,       NO_RTP, "ACK",      CAN_NOT_CREATE_DIALOG },
701
	{ SIP_ACK,       NO_RTP, "ACK",      CAN_NOT_CREATE_DIALOG },
640
	{ SIP_PRACK,     NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
702
	{ SIP_PRACK,     NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
641
	{ SIP_BYE,       NO_RTP, "BYE",      CAN_NOT_CREATE_DIALOG },
703
	{ SIP_BYE,       NO_RTP, "BYE",      CAN_NOT_CREATE_DIALOG },
642
	{ SIP_REFER,     NO_RTP, "REFER",    CAN_CREATE_DIALOG },
704
	{ SIP_REFER,     NO_RTP, "REFER",    CAN_CREATE_DIALOG },
643
	{ SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
705
	{ SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
644
	{ SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
706
	{ SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
645
	{ SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
707
	{ SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
646
	{ SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
708
	{ SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
647
	{ SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
709
	{ SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
648
	{ SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
710
	{ SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
649
	{ SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
711
	{ SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
650
};
712
};
651

    
   
713

   
652
/*! \brief Diversion header reasons
714
/*! \brief Diversion header reasons
653
 *
715
 *
654
 * The core defines a bunch of constants used to define
716
 * The core defines a bunch of constants used to define
655
 * redirecting reasons. This provides a translation table
717
 * redirecting reasons. This provides a translation table
656
 * between those and the strings which may be present in
718
 * between those and the strings which may be present in
657
 * a SIP Diversion header
719
 * a SIP Diversion header
658
 */
720
 */
659
static const struct sip_reasons {
721
static const struct sip_reasons {
660
	enum AST_REDIRECTING_REASON code;
722
	enum AST_REDIRECTING_REASON code;
661
	char * const text;
723
	char * const text;
662
} sip_reason_table[] = {
724
} sip_reason_table[] = {
663
	{ AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
725
	{ AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
664
	{ AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
726
	{ AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
665
	{ AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
727
	{ AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
666
	{ AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
728
	{ AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
667
	{ AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
729
	{ AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
668
	{ AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
730
	{ AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
669
	{ AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
731
	{ AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
670
	{ AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
732
	{ AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
671
	{ AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
733
	{ AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
672
	{ AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
734
	{ AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
673
	{ AST_REDIRECTING_REASON_AWAY, "away" },
735
	{ AST_REDIRECTING_REASON_AWAY, "away" },
674
	{ AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
736
	{ AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"},

    
   
737
	{ AST_REDIRECTING_REASON_SEND_TO_VM, "send_to_vm"},
675
};
738
};
676

    
   
739

   
677

    
   
740

   
678
/*! \name DefaultSettings
741
/*! \name DefaultSettings
679
	Default setttings are used as a channel setting and as a default when
742
	Default setttings are used as a channel setting and as a default when
680
	configuring devices
743
	configuring devices
681
*/
744
*/
682
/*@{*/

   
683
static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
745
static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
684
static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
746
static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
685
static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
747
static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
686
static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
748
static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
687
static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
749
static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
688
static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
750
static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
689
static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
751
static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
690
static int default_qualify;                        /*!< Default Qualify= setting */
752
static int default_qualify;                        /*!< Default Qualify= setting */

    
   
753
static int default_keepalive;                      /*!< Default keepalive= setting */
691
static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
754
static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
692
static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
755
static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
693
                                                    *   a bridged channel on hold */
756
                                                    *   a bridged channel on hold */
694
static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
757
static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
695
static char default_engine[256];                   /*!< Default RTP engine */
758
static char default_engine[256];                   /*!< Default RTP engine */
696
static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
759
static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
697
static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
760
static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
698
static char default_zone[MAX_TONEZONE_COUNTRY];        /*!< Default tone zone for channels created from the SIP driver */
761
static char default_zone[MAX_TONEZONE_COUNTRY];        /*!< Default tone zone for channels created from the SIP driver */
699
static unsigned int default_transports;            /*!< Default Transports (enum sip_transport) that are acceptable */
762
static unsigned int default_transports;            /*!< Default Transports (enum sip_transport) that are acceptable */
700
static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
763
static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
701
/*@}*/

   
702

    
   
764

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

    
   
767

   
706
/*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
768
/*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
707
#define SIP_PEDANTIC_DECODE(str)	\
769
#define SIP_PEDANTIC_DECODE(str)	\
708
	if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) {	\
770
	if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) {	\
709
		ast_uri_decode(str, ast_uri_sip_user);	\
771
		ast_uri_decode(str, ast_uri_sip_user);	\
710
	}	\
772
	}	\
711

    
   
773

   
712
static unsigned int chan_idx;       /*!< used in naming sip channel */
774
static unsigned int chan_idx;       /*!< used in naming sip channel */
713
static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
775
static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
714

    
   
776

   
715
static int global_relaxdtmf;        /*!< Relax DTMF */
777
static int global_relaxdtmf;        /*!< Relax DTMF */
716
static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
778
static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
717
static int global_rtptimeout;       /*!< Time out call if no RTP */
779
static int global_rtptimeout;       /*!< Time out call if no RTP */
718
static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
780
static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
719
static int global_rtpkeepalive;     /*!< Send RTP keepalives */
781
static int global_rtpkeepalive;     /*!< Send RTP keepalives */
720
static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
782
static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
721
static int global_regattempts_max;  /*!< Registration attempts before giving up */
783
static int global_regattempts_max;  /*!< Registration attempts before giving up */
722
static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
784
static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
723
static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
785
static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
724
                                     *   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
786
                                     *   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
725
                                     *   with just a boolean flag in the device structure */
787
                                     *   with just a boolean flag in the device structure */
726
static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
788
static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
727
static unsigned int global_tos_audio;    /*!< IP type of service for audio RTP packets */
789
static unsigned int global_tos_audio;    /*!< IP type of service for audio RTP packets */
728
static unsigned int global_tos_video;    /*!< IP type of service for video RTP packets */
790
static unsigned int global_tos_video;    /*!< IP type of service for video RTP packets */
729
static unsigned int global_tos_text;     /*!< IP type of service for text RTP packets */
791
static unsigned int global_tos_text;     /*!< IP type of service for text RTP packets */
730
static unsigned int global_cos_sip;      /*!< 802.1p class of service for SIP packets */
792
static unsigned int global_cos_sip;      /*!< 802.1p class of service for SIP packets */
731
static unsigned int global_cos_audio;    /*!< 802.1p class of service for audio RTP packets */
793
static unsigned int global_cos_audio;    /*!< 802.1p class of service for audio RTP packets */
732
static unsigned int global_cos_video;    /*!< 802.1p class of service for video RTP packets */
794
static unsigned int global_cos_video;    /*!< 802.1p class of service for video RTP packets */
733
static unsigned int global_cos_text;     /*!< 802.1p class of service for text RTP packets */
795
static unsigned int global_cos_text;     /*!< 802.1p class of service for text RTP packets */
734
static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
796
static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
735
static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
797
static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
736
static char global_useragent[AST_MAX_EXTENSION];    /*!< Useragent for the SIP channel */
798
static char global_useragent[AST_MAX_EXTENSION];    /*!< Useragent for the SIP channel */
737
static char global_sdpsession[AST_MAX_EXTENSION];   /*!< SDP session name for the SIP channel */
799
static char global_sdpsession[AST_MAX_EXTENSION];   /*!< SDP session name for the SIP channel */
738
static char global_sdpowner[AST_MAX_EXTENSION];     /*!< SDP owner name for the SIP channel */
800
static char global_sdpowner[AST_MAX_EXTENSION];     /*!< SDP owner name for the SIP channel */
739
static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
801
static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
740
static int global_t1;           /*!< T1 time */
802
static int global_t1;           /*!< T1 time */
741
static int global_t1min;        /*!< T1 roundtrip time minimum */
803
static int global_t1min;        /*!< T1 roundtrip time minimum */
742
static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
804
static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
743
static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
805
static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
744
static int global_qualifyfreq;          /*!< Qualify frequency */
806
static int global_qualifyfreq;          /*!< Qualify frequency */
745
static int global_qualify_gap;          /*!< Time between our group of peer pokes */
807
static int global_qualify_gap;          /*!< Time between our group of peer pokes */
746
static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
808
static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
747

    
   
809

   
748
static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
810
static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
749
static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
811
static enum st_refresher_param global_st_refresher; /*!< Session-Timer refresher                        */
750
static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
812
static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
751
static int global_max_se;                     /*!< Highest threshold for session refresh interval */
813
static int global_max_se;                     /*!< Highest threshold for session refresh interval */
752

    
   
814

   
753
static int global_store_sip_cause;    /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
815
static int global_store_sip_cause;    /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
754

    
   
816

   
755
static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
817
static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */

    
   
818
static unsigned char global_refer_addheaders; /*!< Add extra headers to outgoing REFER */
756
/*@}*/
819
/*@}*/
757

    
   
820

   
758
/*!
821
/*!
759
 * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
822
 * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
760
 * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
823
 * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
761
 * event package. This variable is set at module load time and may be checked at runtime to determine
824
 * event package. This variable is set at module load time and may be checked at runtime to determine
762
 * if XML parsing support was found.
825
 * if XML parsing support was found.
763
 */
826
 */
764
static int can_parse_xml;
827
static int can_parse_xml;
765

    
   
828

   
766
/*! \name Object counters @{
829
/*! \name Object counters @{
767
 *  \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
830
 *
768
 *  should be used to modify these values. */
831
 * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()

    
   
832
 * should be used to modify these values.

    
   
833
 */
769
static int speerobjs = 0;     /*!< Static peers */
834
static int speerobjs = 0;     /*!< Static peers */
770
static int rpeerobjs = 0;     /*!< Realtime peers */
835
static int rpeerobjs = 0;     /*!< Realtime peers */
771
static int apeerobjs = 0;     /*!< Autocreated peer objects */
836
static int apeerobjs = 0;     /*!< Autocreated peer objects */
772
static int regobjs = 0;       /*!< Registry objects */
837
static int regobjs = 0;       /*!< Registry objects */
773
/* }@ */
838
/*! @} */
774

    
   
839

   
775
static struct ast_flags global_flags[3] = {{0}};  /*!< global SIP_ flags */
840
static struct ast_flags global_flags[3] = {{0}};  /*!< global SIP_ flags */
776
static int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
841
static int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
777

    
   
842

   
778
static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
843
static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */

    
   
844
static struct ast_event_sub *acl_change_event_subscription; /*!< subscription id for named ACL system change events */
779
static int network_change_event_sched_id = -1;
845
static int network_change_event_sched_id = -1;
780

    
   
846

   
781
static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
847
static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
782

    
   
848

   
783
AST_MUTEX_DEFINE_STATIC(netlock);
849
AST_MUTEX_DEFINE_STATIC(netlock);
784

    
   
850

   
785
/*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
851
/*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
786
   when it's doing something critical. */
852
   when it's doing something critical. */
787
AST_MUTEX_DEFINE_STATIC(monlock);
853
AST_MUTEX_DEFINE_STATIC(monlock);
788

    
   
854

   
789
AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
855
AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
790

    
   
856

   
791
/*! \brief This is the thread for the monitor which checks for input on the channels
857
/*! \brief This is the thread for the monitor which checks for input on the channels
792
   which are not currently in use.  */
858
   which are not currently in use.  */
793
static pthread_t monitor_thread = AST_PTHREADT_NULL;
859
static pthread_t monitor_thread = AST_PTHREADT_NULL;
794

    
   
860

   
795
static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
861
static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
796
static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
862
static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
797

    
   
863

   
798
struct ast_sched_context *sched;     /*!< The scheduling context */
864
struct ast_sched_context *sched;     /*!< The scheduling context */
799
static struct io_context *io;           /*!< The IO context */
865
static struct io_context *io;           /*!< The IO context */
800
static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
866
static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
801
struct sip_pkt;
867
struct sip_pkt;
802
static AST_LIST_HEAD_STATIC(domain_list, domain);    /*!< The SIP domain list */
868
static AST_LIST_HEAD_STATIC(domain_list, domain);    /*!< The SIP domain list */
803

    
   
869

   
804
AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
870
AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
805

    
   
871

   
806
static enum sip_debug_e sipdebug;
872
static enum sip_debug_e sipdebug;
807

    
   
873

   
808
/*! \brief extra debugging for 'text' related events.
874
/*! \brief extra debugging for 'text' related events.
809
 *  At the moment this is set together with sip_debug_console.
875
 *  At the moment this is set together with sip_debug_console.
810
 *  \note It should either go away or be implemented properly.
876
 *  \note It should either go away or be implemented properly.
811
 */
877
 */
812
static int sipdebug_text;
878
static int sipdebug_text;
813

    
   
879

   
814
static const struct _map_x_s referstatusstrings[] = {
880
static const struct _map_x_s referstatusstrings[] = {
815
	{ REFER_IDLE,      "<none>" },
881
	{ REFER_IDLE,      "<none>" },
816
	{ REFER_SENT,      "Request sent" },
882
	{ REFER_SENT,      "Request sent" },
817
	{ REFER_RECEIVED,  "Request received" },
883
	{ REFER_RECEIVED,  "Request received" },
818
	{ REFER_CONFIRMED, "Confirmed" },
884
	{ REFER_CONFIRMED, "Confirmed" },
819
	{ REFER_ACCEPTED,  "Accepted" },
885
	{ REFER_ACCEPTED,  "Accepted" },
820
	{ REFER_RINGING,   "Target ringing" },
886
	{ REFER_RINGING,   "Target ringing" },
821
	{ REFER_200OK,     "Done" },
887
	{ REFER_200OK,     "Done" },
822
	{ REFER_FAILED,    "Failed" },
888
	{ REFER_FAILED,    "Failed" },
823
	{ REFER_NOAUTH,    "Failed - auth failure" },
889
	{ REFER_NOAUTH,    "Failed - auth failure" },
824
	{ -1,               NULL} /* terminator */
890
	{ -1,               NULL} /* terminator */
825
};
891
};
826

    
   
892

   
827
/* --- Hash tables of various objects --------*/
893
/* --- Hash tables of various objects --------*/
828
#ifdef LOW_MEMORY
894
#ifdef LOW_MEMORY
829
static const int HASH_PEER_SIZE = 17;
895
static const int HASH_PEER_SIZE = 17;
830
static const int HASH_DIALOG_SIZE = 17;
896
static const int HASH_DIALOG_SIZE = 17;
831
#else
897
#else
832
static const int HASH_PEER_SIZE = 563;	/*!< Size of peer hash table, prime number preferred! */
898
static const int HASH_PEER_SIZE = 563;	/*!< Size of peer hash table, prime number preferred! */
833
static const int HASH_DIALOG_SIZE = 563;
899
static const int HASH_DIALOG_SIZE = 563;
834
#endif
900
#endif
835

    
   
901

   
836
static const struct {
902
static const struct {
837
	enum ast_cc_service_type service;
903
	enum ast_cc_service_type service;
838
	const char *service_string;
904
	const char *service_string;
839
} sip_cc_service_map [] = {
905
} sip_cc_service_map [] = {
840
	[AST_CC_NONE] = { AST_CC_NONE, "" },
906
	[AST_CC_NONE] = { AST_CC_NONE, "" },
841
	[AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
907
	[AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
842
	[AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
908
	[AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
843
	[AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
909
	[AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
844
};
910
};
845

    
   
911

   
846
static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
912
static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
847
{
913
{
848
	enum ast_cc_service_type service;
914
	enum ast_cc_service_type service;
849
	for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
915
	for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
850
		if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
916
		if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
851
			return service;
917
			return service;
852
		}
918
		}
853
	}
919
	}
854
	return AST_CC_NONE;
920
	return AST_CC_NONE;
855
}
921
}
856

    
   
922

   
857
static const struct {
923
static const struct {
858
	enum sip_cc_notify_state state;
924
	enum sip_cc_notify_state state;
859
	const char *state_string;
925
	const char *state_string;
860
} sip_cc_notify_state_map [] = {
926
} sip_cc_notify_state_map [] = {
861
	[CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
927
	[CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
862
	[CC_READY] = {CC_READY, "cc-state: ready"},
928
	[CC_READY] = {CC_READY, "cc-state: ready"},
863
};
929
};
864

    
   
930

   
865
AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
931
AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
866

    
   
932

   
867
static int sip_epa_register(const struct epa_static_data *static_data)
933
static int sip_epa_register(const struct epa_static_data *static_data)
868
{
934
{
869
	struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
935
	struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
870

    
   
936

   
871
	if (!backend) {
937
	if (!backend) {
872
		return -1;
938
		return -1;
873
	}
939
	}
874

    
   
940

   
875
	backend->static_data = static_data;
941
	backend->static_data = static_data;
876

    
   
942

   
877
	AST_LIST_LOCK(&epa_static_data_list);
943
	AST_LIST_LOCK(&epa_static_data_list);
878
	AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
944
	AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
879
	AST_LIST_UNLOCK(&epa_static_data_list);
945
	AST_LIST_UNLOCK(&epa_static_data_list);
880
	return 0;
946
	return 0;
881
}
947
}
882

    
   
948

   
883
static void sip_epa_unregister_all(void)
949
static void sip_epa_unregister_all(void)
884
{
950
{
885
	struct epa_backend *backend;
951
	struct epa_backend *backend;
886

    
   
952

   
887
	AST_LIST_LOCK(&epa_static_data_list);
953
	AST_LIST_LOCK(&epa_static_data_list);
888
	while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
954
	while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
889
		ast_free(backend);
955
		ast_free(backend);
890
	}
956
	}
891
	AST_LIST_UNLOCK(&epa_static_data_list);
957
	AST_LIST_UNLOCK(&epa_static_data_list);
892
}
958
}
893

    
   
959

   
894
static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
960
static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
895

    
   
961

   
896
static void cc_epa_destructor(void *data)
962
static void cc_epa_destructor(void *data)
897
{
963
{
898
	struct sip_epa_entry *epa_entry = data;
964
	struct sip_epa_entry *epa_entry = data;
899
	struct cc_epa_entry *cc_entry = epa_entry->instance_data;
965
	struct cc_epa_entry *cc_entry = epa_entry->instance_data;
900
	ast_free(cc_entry);
966
	ast_free(cc_entry);
901
}
967
}
902

    
   
968

   
903
static const struct epa_static_data cc_epa_static_data  = {
969
static const struct epa_static_data cc_epa_static_data  = {
904
	.event = CALL_COMPLETION,
970
	.event = CALL_COMPLETION,
905
	.name = "call-completion",
971
	.name = "call-completion",
906
	.handle_error = cc_handle_publish_error,
972
	.handle_error = cc_handle_publish_error,
907
	.destructor = cc_epa_destructor,
973
	.destructor = cc_epa_destructor,
908
};
974
};
909

    
   
975

   
910
static const struct epa_static_data *find_static_data(const char * const event_package)
976
static const struct epa_static_data *find_static_data(const char * const event_package)
911
{
977
{
912
	const struct epa_backend *backend = NULL;
978
	const struct epa_backend *backend = NULL;
913

    
   
979

   
914
	AST_LIST_LOCK(&epa_static_data_list);
980
	AST_LIST_LOCK(&epa_static_data_list);
915
	AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
981
	AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
916
		if (!strcmp(backend->static_data->name, event_package)) {
982
		if (!strcmp(backend->static_data->name, event_package)) {
917
			break;
983
			break;
918
		}
984
		}
919
	}
985
	}
920
	AST_LIST_UNLOCK(&epa_static_data_list);
986
	AST_LIST_UNLOCK(&epa_static_data_list);
921
	return backend ? backend->static_data : NULL;
987
	return backend ? backend->static_data : NULL;
922
}
988
}
923

    
   
989

   
924
static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
990
static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
925
{
991
{
926
	struct sip_epa_entry *epa_entry;
992
	struct sip_epa_entry *epa_entry;
927
	const struct epa_static_data *static_data;
993
	const struct epa_static_data *static_data;
928

    
   
994

   
929
	if (!(static_data = find_static_data(event_package))) {
995
	if (!(static_data = find_static_data(event_package))) {
930
		return NULL;
996
		return NULL;
931
	}
997
	}
932

    
   
998

   
933
	if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
999
	if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
934
		return NULL;
1000
		return NULL;
935
	}
1001
	}
936

    
   
1002

   
937
	epa_entry->static_data = static_data;
1003
	epa_entry->static_data = static_data;
938
	ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
1004
	ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
939
	return epa_entry;
1005
	return epa_entry;
940
}
1006
}
941

    
   
1007

   
942
/*!
1008
/*!
943
 * Used to create new entity IDs by ESCs.
1009
 * Used to create new entity IDs by ESCs.
944
 */
1010
 */
945
static int esc_etag_counter;
1011
static int esc_etag_counter;
946
static const int DEFAULT_PUBLISH_EXPIRES = 3600;
1012
static const int DEFAULT_PUBLISH_EXPIRES = 3600;
947

    
   
1013

   
948
#ifdef HAVE_LIBXML2
1014
#ifdef HAVE_LIBXML2
949
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);
1015
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);
950

    
   
1016

   
951
static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
1017
static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
952
	.initial_handler = cc_esc_publish_handler,
1018
	.initial_handler = cc_esc_publish_handler,
953
	.modify_handler = cc_esc_publish_handler,
1019
	.modify_handler = cc_esc_publish_handler,
954
};
1020
};
955
#endif
1021
#endif
956

    
   
1022

   
957
/*!
1023
/*!
958
 * \brief The Event State Compositors
1024
 * \brief The Event State Compositors
959
 *
1025
 *
960
 * An Event State Compositor is an entity which
1026
 * An Event State Compositor is an entity which
961
 * accepts PUBLISH requests and acts appropriately
1027
 * accepts PUBLISH requests and acts appropriately
962
 * based on these requests.
1028
 * based on these requests.
963
 *
1029
 *
964
 * The actual event_state_compositor structure is simply
1030
 * The actual event_state_compositor structure is simply
965
 * an ao2_container of sip_esc_entrys. When an incoming
1031
 * an ao2_container of sip_esc_entrys. When an incoming
966
 * PUBLISH is received, we can match the appropriate sip_esc_entry
1032
 * PUBLISH is received, we can match the appropriate sip_esc_entry
967
 * using the entity ID of the incoming PUBLISH.
1033
 * using the entity ID of the incoming PUBLISH.
968
 */
1034
 */
969
static struct event_state_compositor {
1035
static struct event_state_compositor {
970
	enum subscriptiontype event;
1036
	enum subscriptiontype event;
971
	const char * name;
1037
	const char * name;
972
	const struct sip_esc_publish_callbacks *callbacks;
1038
	const struct sip_esc_publish_callbacks *callbacks;
973
	struct ao2_container *compositor;
1039
	struct ao2_container *compositor;
974
} event_state_compositors [] = {
1040
} event_state_compositors [] = {
975
#ifdef HAVE_LIBXML2
1041
#ifdef HAVE_LIBXML2
976
	{CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
1042
	{CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
977
#endif
1043
#endif
978
};
1044
};
979

    
   
1045

   
980
static const int ESC_MAX_BUCKETS = 37;
1046
static const int ESC_MAX_BUCKETS = 37;
981

    
   
1047

   
982
static void esc_entry_destructor(void *obj)
1048
static void esc_entry_destructor(void *obj)
983
{
1049
{
984
	struct sip_esc_entry *esc_entry = obj;
1050
	struct sip_esc_entry *esc_entry = obj;
985
	if (esc_entry->sched_id > -1) {
1051
	if (esc_entry->sched_id > -1) {
986
		AST_SCHED_DEL(sched, esc_entry->sched_id);
1052
		AST_SCHED_DEL(sched, esc_entry->sched_id);
987
	}
1053
	}
988
}
1054
}
989

    
   
1055

   
990
static int esc_hash_fn(const void *obj, const int flags)
1056
static int esc_hash_fn(const void *obj, const int flags)
991
{
1057
{
992
	const struct sip_esc_entry *entry = obj;
1058
	const struct sip_esc_entry *entry = obj;
993
	return ast_str_hash(entry->entity_tag);
1059
	return ast_str_hash(entry->entity_tag);
994
}
1060
}
995

    
   
1061

   
996
static int esc_cmp_fn(void *obj, void *arg, int flags)
1062
static int esc_cmp_fn(void *obj, void *arg, int flags)
997
{
1063
{
998
	struct sip_esc_entry *entry1 = obj;
1064
	struct sip_esc_entry *entry1 = obj;
999
	struct sip_esc_entry *entry2 = arg;
1065
	struct sip_esc_entry *entry2 = arg;
1000

    
   
1066

   
1001
	return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
1067
	return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
1002
}
1068
}
1003

    
   
1069

   
1004
static struct event_state_compositor *get_esc(const char * const event_package) {
1070
static struct event_state_compositor *get_esc(const char * const event_package) {
1005
	int i;
1071
	int i;
1006
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1072
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1007
		if (!strcasecmp(event_package, event_state_compositors[i].name)) {
1073
		if (!strcasecmp(event_package, event_state_compositors[i].name)) {
1008
			return &event_state_compositors[i];
1074
			return &event_state_compositors[i];
1009
		}
1075
		}
1010
	}
1076
	}
1011
	return NULL;
1077
	return NULL;
1012
}
1078
}
1013

    
   
1079

   
1014
static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
1080
static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
1015
	struct sip_esc_entry *entry;
1081
	struct sip_esc_entry *entry;
1016
	struct sip_esc_entry finder;
1082
	struct sip_esc_entry finder;
1017

    
   
1083

   
1018
	ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
1084
	ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
1019

    
   
1085

   
1020
	entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
1086
	entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
1021

    
   
1087

   
1022
	return entry;
1088
	return entry;
1023
}
1089
}
1024

    
   
1090

   
1025
static int publish_expire(const void *data)
1091
static int publish_expire(const void *data)
1026
{
1092
{
1027
	struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
1093
	struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
1028
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1094
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1029

    
   
1095

   
1030
	ast_assert(esc != NULL);
1096
	ast_assert(esc != NULL);
1031

    
   
1097

   
1032
	ao2_unlink(esc->compositor, esc_entry);
1098
	ao2_unlink(esc->compositor, esc_entry);
1033
	ao2_ref(esc_entry, -1);
1099
	ao2_ref(esc_entry, -1);
1034
	return 0;
1100
	return 0;
1035
}
1101
}
1036

    
   
1102

   
1037
static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
1103
static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
1038
{
1104
{
1039
	int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
1105
	int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
1040
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1106
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1041

    
   
1107

   
1042
	ast_assert(esc != NULL);
1108
	ast_assert(esc != NULL);
1043
	if (is_linked) {
1109
	if (is_linked) {
1044
		ao2_unlink(esc->compositor, esc_entry);
1110
		ao2_unlink(esc->compositor, esc_entry);
1045
	}
1111
	}
1046
	snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
1112
	snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
1047
	ao2_link(esc->compositor, esc_entry);
1113
	ao2_link(esc->compositor, esc_entry);
1048
}
1114
}
1049

    
   
1115

   
1050
static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
1116
static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
1051
{
1117
{
1052
	struct sip_esc_entry *esc_entry;
1118
	struct sip_esc_entry *esc_entry;
1053
	int expires_ms;
1119
	int expires_ms;
1054

    
   
1120

   
1055
	if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
1121
	if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
1056
		return NULL;
1122
		return NULL;
1057
	}
1123
	}
1058

    
   
1124

   
1059
	esc_entry->event = esc->name;
1125
	esc_entry->event = esc->name;
1060

    
   
1126

   
1061
	expires_ms = expires * 1000;
1127
	expires_ms = expires * 1000;
1062
	/* Bump refcount for scheduler */
1128
	/* Bump refcount for scheduler */
1063
	ao2_ref(esc_entry, +1);
1129
	ao2_ref(esc_entry, +1);
1064
	esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
1130
	esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
1065

    
   
1131

   
1066
	/* Note: This links the esc_entry into the ESC properly */
1132
	/* Note: This links the esc_entry into the ESC properly */
1067
	create_new_sip_etag(esc_entry, 0);
1133
	create_new_sip_etag(esc_entry, 0);
1068

    
   
1134

   
1069
	return esc_entry;
1135
	return esc_entry;
1070
}
1136
}
1071

    
   
1137

   
1072
static int initialize_escs(void)
1138
static int initialize_escs(void)
1073
{
1139
{
1074
	int i, res = 0;
1140
	int i, res = 0;
1075
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1141
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1076
		if (!((event_state_compositors[i].compositor) =
1142
		if (!((event_state_compositors[i].compositor) =
1077
					ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
1143
					ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
1078
			res = -1;
1144
			res = -1;
1079
		}
1145
		}
1080
	}
1146
	}
1081
	return res;
1147
	return res;
1082
}
1148
}
1083

    
   
1149

   
1084
static void destroy_escs(void)
1150
static void destroy_escs(void)
1085
{
1151
{
1086
	int i;
1152
	int i;
1087
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1153
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1088
		ao2_ref(event_state_compositors[i].compositor, -1);
1154
		ao2_ref(event_state_compositors[i].compositor, -1);
1089
	}
1155
	}
1090
}
1156
}
1091

    
   
1157

   

    
   
1158
struct state_notify_data {

    
   
1159
	int state;

    
   
1160
	struct ao2_container *device_state_info;

    
   
1161
	int presence_state;

    
   
1162
	const char *presence_subtype;

    
   
1163
	const char *presence_message;

    
   
1164
};

    
   
1165

   
1092
/*!
1166
/*!
1093
 * \details
1167
 * \details
1094
 * Here we implement the container for dialogs which are in the
1168
 * Here we implement the container for dialogs which are in the
1095
 * dialog_needdestroy state to iterate only through the dialogs
1169
 * dialog_needdestroy state to iterate only through the dialogs
1096
 * unlink them instead of iterate through all dialogs
1170
 * unlink them instead of iterate through all dialogs
1097
 */
1171
 */
1098
struct ao2_container *dialogs_needdestroy;
1172
struct ao2_container *dialogs_needdestroy;
1099

    
   
1173

   
1100
/*!
1174
/*!
1101
 * \details
1175
 * \details
1102
 * Here we implement the container for dialogs which have rtp
1176
 * Here we implement the container for dialogs which have rtp
1103
 * traffic and rtptimeout, rtpholdtimeout or rtpkeepalive
1177
 * traffic and rtptimeout, rtpholdtimeout or rtpkeepalive
1104
 * set. We use this container instead the whole dialog list.
1178
 * set. We use this container instead the whole dialog list.
1105
 */
1179
 */
1106
struct ao2_container *dialogs_rtpcheck;
1180
struct ao2_container *dialogs_rtpcheck;
1107

    
   
1181

   
1108
/*!
1182
/*!
1109
 * \details
1183
 * \details
1110
 * Here we implement the container for dialogs (sip_pvt), defining
1184
 * Here we implement the container for dialogs (sip_pvt), defining
1111
 * generic wrapper functions to ease the transition from the current
1185
 * generic wrapper functions to ease the transition from the current
1112
 * implementation (a single linked list) to a different container.
1186
 * implementation (a single linked list) to a different container.
1113
 * In addition to a reference to the container, we need functions to lock/unlock
1187
 * In addition to a reference to the container, we need functions to lock/unlock
1114
 * the container and individual items, and functions to add/remove
1188
 * the container and individual items, and functions to add/remove
1115
 * references to the individual items.
1189
 * references to the individual items.
1116
 */
1190
 */
1117
static struct ao2_container *dialogs;
1191
static struct ao2_container *dialogs;
1118
#define sip_pvt_lock(x) ao2_lock(x)
1192
#define sip_pvt_lock(x) ao2_lock(x)
1119
#define sip_pvt_trylock(x) ao2_trylock(x)
1193
#define sip_pvt_trylock(x) ao2_trylock(x)
1120
#define sip_pvt_unlock(x) ao2_unlock(x)
1194
#define sip_pvt_unlock(x) ao2_unlock(x)
1121

    
   
1195

   
1122
/*! \brief  The table of TCP threads */
1196
/*! \brief  The table of TCP threads */
1123
static struct ao2_container *threadt;
1197
static struct ao2_container *threadt;
1124

    
   
1198

   
1125
/*! \brief  The peer list: Users, Peers and Friends */
1199
/*! \brief  The peer list: Users, Peers and Friends */
1126
static struct ao2_container *peers;
1200
static struct ao2_container *peers;
1127
static struct ao2_container *peers_by_ip;
1201
static struct ao2_container *peers_by_ip;
1128

    
   
1202

   
1129
/*! \brief  The register list: Other SIP proxies we register with and receive calls from */
1203
/*! \brief  The register list: Other SIP proxies we register with and receive calls from */
1130
static struct ast_register_list {
1204
static struct ast_register_list {
1131
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1205
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1132
	int recheck;
1206
	int recheck;
1133
} regl;
1207
} regl;
1134

    
   
1208

   
1135
/*! \brief  The MWI subscription list */
1209
/*! \brief  The MWI subscription list */
1136
static struct ast_subscription_mwi_list {
1210
static struct ast_subscription_mwi_list {
1137
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
1211
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
1138
} submwil;
1212
} submwil;
1139
static int temp_pvt_init(void *);
1213
static int temp_pvt_init(void *);
1140
static void temp_pvt_cleanup(void *);
1214
static void temp_pvt_cleanup(void *);
1141

    
   
1215

   
1142
/*! \brief A per-thread temporary pvt structure */
1216
/*! \brief A per-thread temporary pvt structure */
1143
AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1217
AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1144

    
   
1218

   

    
   
1219
/*! \brief A per-thread buffer for transport to string conversion */

    
   
1220
AST_THREADSTORAGE(sip_transport_str_buf);

    
   
1221

   

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

    
   
1223
#define SIP_TRANSPORT_STR_BUFSIZE 128

    
   
1224

   
1145
/*! \brief Authentication container for realm authentication */
1225
/*! \brief Authentication container for realm authentication */
1146
static struct sip_auth_container *authl = NULL;
1226
static struct sip_auth_container *authl = NULL;
1147
/*! \brief Global authentication container protection while adjusting the references. */
1227
/*! \brief Global authentication container protection while adjusting the references. */
1148
AST_MUTEX_DEFINE_STATIC(authl_lock);
1228
AST_MUTEX_DEFINE_STATIC(authl_lock);
1149

    
   
1229

   
1150
/* --- Sockets and networking --------------*/
1230
/* --- Sockets and networking --------------*/
1151

    
   
1231

   
1152
/*! \brief Main socket for UDP SIP communication.
1232
/*! \brief Main socket for UDP SIP communication.
1153
 *
1233
 *
1154
 * sipsock is shared between the SIP manager thread (which handles reload
1234
 * sipsock is shared between the SIP manager thread (which handles reload
1155
 * requests), the udp io handler (sipsock_read()) and the user routines that
1235
 * requests), the udp io handler (sipsock_read()) and the user routines that
1156
 * issue udp writes (using __sip_xmit()).
1236
 * issue udp writes (using __sip_xmit()).
1157
 * The socket is -1 only when opening fails (this is a permanent condition),
1237
 * The socket is -1 only when opening fails (this is a permanent condition),
1158
 * or when we are handling a reload() that changes its address (this is
1238
 * or when we are handling a reload() that changes its address (this is
1159
 * a transient situation during which we might have a harmless race, see
1239
 * a transient situation during which we might have a harmless race, see
1160
 * below). Because the conditions for the race to be possible are extremely
1240
 * below). Because the conditions for the race to be possible are extremely
1161
 * rare, we don't want to pay the cost of locking on every I/O.
1241
 * rare, we don't want to pay the cost of locking on every I/O.
1162
 * Rather, we remember that when the race may occur, communication is
1242
 * Rather, we remember that when the race may occur, communication is
1163
 * bound to fail anyways, so we just live with this event and let
1243
 * bound to fail anyways, so we just live with this event and let
1164
 * the protocol handle this above us.
1244
 * the protocol handle this above us.
1165
 */
1245
 */
1166
static int sipsock  = -1;
1246
static int sipsock  = -1;
1167

    
   
1247

   
1168
struct ast_sockaddr bindaddr;	/*!< UDP: The address we bind to */
1248
struct ast_sockaddr bindaddr;	/*!< UDP: The address we bind to */
1169

    
   
1249

   
1170
/*! \brief our (internal) default address/port to put in SIP/SDP messages
1250
/*! \brief our (internal) default address/port to put in SIP/SDP messages
1171
 *  internip is initialized picking a suitable address from one of the
1251
 *  internip is initialized picking a suitable address from one of the
1172
 * interfaces, and the same port number we bind to. It is used as the
1252
 * interfaces, and the same port number we bind to. It is used as the
1173
 * default address/port in SIP messages, and as the default address
1253
 * default address/port in SIP messages, and as the default address
1174
 * (but not port) in SDP messages.
1254
 * (but not port) in SDP messages.
1175
 */
1255
 */
1176
static struct ast_sockaddr internip;
1256
static struct ast_sockaddr internip;
1177

    
   
1257

   
1178
/*! \brief our external IP address/port for SIP sessions.
1258
/*! \brief our external IP address/port for SIP sessions.
1179
 * externaddr.sin_addr is only set when we know we might be behind
1259
 * externaddr.sin_addr is only set when we know we might be behind
1180
 * a NAT, and this is done using a variety of (mutually exclusive)
1260
 * a NAT, and this is done using a variety of (mutually exclusive)
1181
 * ways from the config file:
1261
 * ways from the config file:
1182
 *
1262
 *
1183
 * + with "externaddr = host[:port]" we specify the address/port explicitly.
1263
 * + with "externaddr = host[:port]" we specify the address/port explicitly.
1184
 *   The address is looked up only once when (re)loading the config file;
1264
 *   The address is looked up only once when (re)loading the config file;
1185
 *
1265
 *
1186
 * + with "externhost = host[:port]" we do a similar thing, but the
1266
 * + with "externhost = host[:port]" we do a similar thing, but the
1187
 *   hostname is stored in externhost, and the hostname->IP mapping
1267
 *   hostname is stored in externhost, and the hostname->IP mapping
1188
 *   is refreshed every 'externrefresh' seconds;
1268
 *   is refreshed every 'externrefresh' seconds;
1189
 *
1269
 *
1190
 * Other variables (externhost, externexpire, externrefresh) are used
1270
 * Other variables (externhost, externexpire, externrefresh) are used
1191
 * to support the above functions.
1271
 * to support the above functions.
1192
 */
1272
 */
1193
static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
1273
static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
1194
static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
1274
static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
1195

    
   
1275

   
1196
static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1276
static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1197
static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1277
static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1198
static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
1278
static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
1199
static uint16_t externtcpport;          /*!< external tcp port */
1279
static uint16_t externtcpport;          /*!< external tcp port */
1200
static uint16_t externtlsport;          /*!< external tls port */
1280
static uint16_t externtlsport;          /*!< external tls port */
1201

    
   
1281

   
1202
/*! \brief  List of local networks
1282
/*! \brief  List of local networks
1203
 * We store "localnet" addresses from the config file into an access list,
1283
 * We store "localnet" addresses from the config file into an access list,
1204
 * marked as 'DENY', so the call to ast_apply_ha() will return
1284
 * marked as 'DENY', so the call to ast_apply_ha() will return
1205
 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1285
 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1206
 * (i.e. presumably public) addresses.
1286
 * (i.e. presumably public) addresses.
1207
 */
1287
 */
1208
static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
1288
static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
1209

    
   
1289

   
1210
static int ourport_tcp;             /*!< The port used for TCP connections */
1290
static int ourport_tcp;             /*!< The port used for TCP connections */
1211
static int ourport_tls;             /*!< The port used for TCP/TLS connections */
1291
static int ourport_tls;             /*!< The port used for TCP/TLS connections */
1212
static struct ast_sockaddr debugaddr;
1292
static struct ast_sockaddr debugaddr;
1213

    
   
1293

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

    
   
1295

   
1216
/*! some list management macros. */
1296
/*! some list management macros. */
1217

    
   
1297

   
1218
#define UNLINK(element, head, prev) do {	\
1298
#define UNLINK(element, head, prev) do {	\
1219
	if (prev)				\
1299
	if (prev)				\
1220
		(prev)->next = (element)->next;	\
1300
		(prev)->next = (element)->next;	\
1221
	else					\
1301
	else					\
1222
		(head) = (element)->next;	\
1302
		(head) = (element)->next;	\
1223
	} while (0)
1303
	} while (0)
1224

    
   
1304

   
1225
/*---------------------------- Forward declarations of functions in chan_sip.c */
1305
/*---------------------------- Forward declarations of functions in chan_sip.c */
1226
/* Note: This is added to help splitting up chan_sip.c into several files
1306
/* Note: This is added to help splitting up chan_sip.c into several files
1227
	in coming releases. */
1307
	in coming releases. */
1228

    
   
1308

   
1229
/*--- PBX interface functions */
1309
/*--- PBX interface functions */
1230
static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *dest, int *cause);
1310
static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *dest, int *cause);
1231
static int sip_devicestate(const char *data);
1311
static int sip_devicestate(const char *data);
1232
static int sip_sendtext(struct ast_channel *ast, const char *text);
1312
static int sip_sendtext(struct ast_channel *ast, const char *text);
1233
static int sip_call(struct ast_channel *ast, const char *dest, int timeout);
1313
static int sip_call(struct ast_channel *ast, const char *dest, int timeout);
1234
static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1314
static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1235
static int sip_hangup(struct ast_channel *ast);
1315
static int sip_hangup(struct ast_channel *ast);
1236
static int sip_answer(struct ast_channel *ast);
1316
static int sip_answer(struct ast_channel *ast);
1237
static struct ast_frame *sip_read(struct ast_channel *ast);
1317
static struct ast_frame *sip_read(struct ast_channel *ast);
1238
static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1318
static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1239
static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1319
static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1240
static int sip_transfer(struct ast_channel *ast, const char *dest);
1320
static int sip_transfer(struct ast_channel *ast, const char *dest);
1241
static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1321
static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1242
static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1322
static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1243
static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1323
static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1244
static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1324
static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1245
static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1325
static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1246
static const char *sip_get_callid(struct ast_channel *chan);
1326
static const char *sip_get_callid(struct ast_channel *chan);
1247

    
   
1327

   
1248
static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
1328
static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
1249
static int sip_standard_port(enum sip_transport type, int port);
1329
static int sip_standard_port(enum sip_transport type, int port);
1250
static int sip_prepare_socket(struct sip_pvt *p);
1330
static int sip_prepare_socket(struct sip_pvt *p);
1251
static int get_address_family_filter(const struct ast_sockaddr *addr);
1331
static int get_address_family_filter(unsigned int transport);
1252

    
   
1332

   
1253
/*--- Transmitting responses and requests */
1333
/*--- Transmitting responses and requests */
1254
static int sipsock_read(int *id, int fd, short events, void *ignore);
1334
static int sipsock_read(int *id, int fd, short events, void *ignore);
1255
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
1335
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
1256
static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
1336
static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
1257
static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1337
static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1258
static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1338
static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1259
static int retrans_pkt(const void *data);
1339
static int retrans_pkt(const void *data);
1260
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);
1340
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);
1261
static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1341
static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1262
static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1342
static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1263
static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1343
static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1264
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);
1344
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);
1265
static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1345
static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1266
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);
1346
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);
1267
static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1347
static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1268
static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1348
static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1269
static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
1349
static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
1270
static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
1350
static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
1271
static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
1351
static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
1272
static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
1352
static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
1273
static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
1353
static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
1274
static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1354
static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1275
static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
1355
static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
1276
static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1356
static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1277
static int transmit_info_with_vidupdate(struct sip_pvt *p);
1357
static int transmit_info_with_vidupdate(struct sip_pvt *p);
1278
static int transmit_message(struct sip_pvt *p, int init, int auth);
1358
static int transmit_message(struct sip_pvt *p, int init, int auth);
1279
static int transmit_refer(struct sip_pvt *p, const char *dest);
1359
static int transmit_refer(struct sip_pvt *p, const char *dest);
1280
static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1360
static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1281
static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1361
static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1282
static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
1362
static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
1283
static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1363
static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1284
static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
1364
static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
1285
static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
1365
static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
1286
static void copy_request(struct sip_request *dst, const struct sip_request *src);
1366
static void copy_request(struct sip_request *dst, const struct sip_request *src);
1287
static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1367
static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1288
static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1368
static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1289
static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
1369
static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
1290

    
   
1370

   
1291
/* Misc dialog routines */
1371
/* Misc dialog routines */
1292
static int __sip_autodestruct(const void *data);
1372
static int __sip_autodestruct(const void *data);
1293
static void *registry_unref(struct sip_registry *reg, char *tag);
1373
static void *registry_unref(struct sip_registry *reg, char *tag);
1294
static int update_call_counter(struct sip_pvt *fup, int event);
1374
static int update_call_counter(struct sip_pvt *fup, int event);
1295
static int auto_congest(const void *arg);
1375
static int auto_congest(const void *arg);
1296
static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
1376
static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
1297
static void free_old_route(struct sip_route *route);
1377
static void free_old_route(struct sip_route *route);
1298
static void list_route(struct sip_route *route);
1378
static void list_route(struct sip_route *route);
1299
static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
1379
static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
1300
static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
1380
static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
1301
					      struct sip_request *req, const char *uri);
1381
					      struct sip_request *req, const char *uri);
1302
static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1382
static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1303
static void check_pendings(struct sip_pvt *p);
1383
static void check_pendings(struct sip_pvt *p);
1304
static void *sip_park_thread(void *stuff);
1384
static void *sip_park_thread(void *stuff);
1305
static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, uint32_t seqno, const char *park_exten, const char *park_context);
1385
static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, uint32_t seqno, const char *park_exten, const char *park_context);
1306

    
   
1386

   
1307
static void *sip_pickup_thread(void *stuff);
1387
static void *sip_pickup_thread(void *stuff);
1308
static int sip_pickup(struct ast_channel *chan);
1388
static int sip_pickup(struct ast_channel *chan);
1309

    
   
1389

   
1310
static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1390
static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1311
static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1391
static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1312

    
   
1392

   
1313
/*--- Codec handling / SDP */
1393
/*--- Codec handling / SDP */
1314
static void try_suggested_sip_codec(struct sip_pvt *p);
1394
static void try_suggested_sip_codec(struct sip_pvt *p);
1315
static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1395
static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1316
static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1396
static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1317
static int find_sdp(struct sip_request *req);
1397
static int find_sdp(struct sip_request *req);
1318
static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1398
static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1319
static int process_sdp_o(const char *o, struct sip_pvt *p);
1399
static int process_sdp_o(const char *o, struct sip_pvt *p);
1320
static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
1400
static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
1321
static int process_sdp_a_sendonly(const char *a, int *sendonly);
1401
static int process_sdp_a_sendonly(const char *a, int *sendonly);

    
   
1402
static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);

    
   
1403
static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
1322
static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1404
static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1323
static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1405
static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1324
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);
1406
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);
1325
static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1407
static int process_sdp_a_image(const char *a, struct sip_pvt *p);

    
   
1408
static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);

    
   
1409
static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);

    
   
1410
static void start_ice(struct ast_rtp_instance *instance);
1326
static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
1411
static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
1327
			     struct ast_str **m_buf, struct ast_str **a_buf,
1412
			     struct ast_str **m_buf, struct ast_str **a_buf,
1328
			     int debug, int *min_packet_size);
1413
			     int debug, int *min_packet_size);
1329
static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1414
static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1330
				struct ast_str **m_buf, struct ast_str **a_buf,
1415
				struct ast_str **m_buf, struct ast_str **a_buf,
1331
				int debug);
1416
				int debug);
1332
static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1417
static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1333
static void do_setnat(struct sip_pvt *p);
1418
static void do_setnat(struct sip_pvt *p);
1334
static void stop_media_flows(struct sip_pvt *p);
1419
static void stop_media_flows(struct sip_pvt *p);
1335

    
   
1420

   
1336
/*--- Authentication stuff */
1421
/*--- Authentication stuff */
1337
static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1422
static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1338
static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1423
static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1339
static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1424
static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1340
					 const char *secret, const char *md5secret, int sipmethod,
1425
					 const char *secret, const char *md5secret, int sipmethod,
1341
					 const char *uri, enum xmittype reliable, int ignore);
1426
					 const char *uri, enum xmittype reliable);
1342
static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1427
static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1343
					      int sipmethod, const char *uri, enum xmittype reliable,
1428
					      int sipmethod, const char *uri, enum xmittype reliable,
1344
					      struct ast_sockaddr *addr, struct sip_peer **authpeer);
1429
					      struct ast_sockaddr *addr, struct sip_peer **authpeer);
1345
static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
1430
static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
1346

    
   
1431

   
1347
/*--- Domain handling */
1432
/*--- Domain handling */
1348
static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1433
static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1349
static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1434
static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1350
static void clear_sip_domains(void);
1435
static void clear_sip_domains(void);
1351

    
   
1436

   
1352
/*--- SIP realm authentication */
1437
/*--- SIP realm authentication */
1353
static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
1438
static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
1354
static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
1439
static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
1355

    
   
1440

   
1356
/*--- Misc functions */
1441
/*--- Misc functions */
1357
static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1442
static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1358
static int reload_config(enum channelreloadreason reason);
1443
static int reload_config(enum channelreloadreason reason);
1359
static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt);
1444
static void add_diversion(struct sip_request *req, struct sip_pvt *pvt);
1360
static int expire_register(const void *data);
1445
static int expire_register(const void *data);
1361
static void *do_monitor(void *data);
1446
static void *do_monitor(void *data);
1362
static int restart_monitor(void);
1447
static int restart_monitor(void);
1363
static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1448
static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1364
static struct ast_variable *copy_vars(struct ast_variable *src);
1449
static struct ast_variable *copy_vars(struct ast_variable *src);
1365
static int dialog_find_multiple(void *obj, void *arg, int flags);
1450
static int dialog_find_multiple(void *obj, void *arg, int flags);
1366
static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
1451
static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
1367
/* static int sip_addrcmp(char *name, struct sockaddr_in *sin);	Support for peer matching */
1452
/* static int sip_addrcmp(char *name, struct sockaddr_in *sin);	Support for peer matching */
1368
static int sip_refer_allocate(struct sip_pvt *p);
1453
static int sip_refer_alloc(struct sip_pvt *p);
1369
static int sip_notify_allocate(struct sip_pvt *p);
1454
static int sip_notify_alloc(struct sip_pvt *p);
1370
static void ast_quiet_chan(struct ast_channel *chan);
1455
static void ast_quiet_chan(struct ast_channel *chan);
1371
static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1456
static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1372
static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1457
static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1373

    
   
1458

   
1374
/*--- Device monitoring and Device/extension state/event handling */
1459
/*--- Device monitoring and Device/extension state/event handling */
1375
static int cb_extensionstate(const char *context, const char *exten, enum ast_extension_states state, void *data);
1460
static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force);

    
   
1461
static int cb_extensionstate(char *context, char *exten, struct ast_state_cb_info *info, void *data);
1376
static int sip_poke_noanswer(const void *data);
1462
static int sip_poke_noanswer(const void *data);
1377
static int sip_poke_peer(struct sip_peer *peer, int force);
1463
static int sip_poke_peer(struct sip_peer *peer, int force);
1378
static void sip_poke_all_peers(void);
1464
static void sip_poke_all_peers(void);
1379
static void sip_peer_hold(struct sip_pvt *p, int hold);
1465
static void sip_peer_hold(struct sip_pvt *p, int hold);
1380
static void mwi_event_cb(const struct ast_event *, void *);
1466
static void mwi_event_cb(const struct ast_event *, void *);
1381
static void network_change_event_cb(const struct ast_event *, void *);
1467
static void network_change_event_cb(const struct ast_event *, void *);

    
   
1468
static void acl_change_event_cb(const struct ast_event *event, void *userdata);

    
   
1469
static void sip_keepalive_all_peers(void);
1382

    
   
1470

   
1383
/*--- Applications, functions, CLI and manager command helpers */
1471
/*--- Applications, functions, CLI and manager command helpers */
1384
static const char *sip_nat_mode(const struct sip_pvt *p);
1472
static const char *sip_nat_mode(const struct sip_pvt *p);
1385
static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1473
static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1386
static char *transfermode2str(enum transfermodes mode) attribute_const;
1474
static char *transfermode2str(enum transfermodes mode) attribute_const;
1387
static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1475
static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1388
static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1476
static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1389
static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1477
static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1390
static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1478
static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1391
static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1479
static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1392
static void  print_group(int fd, ast_group_t group, int crlf);
1480
static void  print_group(int fd, ast_group_t group, int crlf);

    
   
1481
static void  print_named_groups(int fd, struct ast_namedgroups *groups, int crlf);
1393
static const char *dtmfmode2str(int mode) attribute_const;
1482
static const char *dtmfmode2str(int mode) attribute_const;
1394
static int str2dtmfmode(const char *str) attribute_unused;
1483
static int str2dtmfmode(const char *str) attribute_unused;
1395
static const char *insecure2str(int mode) attribute_const;
1484
static const char *insecure2str(int mode) attribute_const;
1396
static const char *allowoverlap2str(int mode) attribute_const;
1485
static const char *allowoverlap2str(int mode) attribute_const;
1397
static void cleanup_stale_contexts(char *new, char *old);
1486
static void cleanup_stale_contexts(char *new, char *old);
1398
static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1487
static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1399
static const char *domain_mode_to_text(const enum domain_mode mode);
1488
static const char *domain_mode_to_text(const enum domain_mode mode);
1400
static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1489
static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1401
static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1490
static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1402
static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1491
static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1403
static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1492
static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1404
static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1493
static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1405
static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1494
static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1406
static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1495
static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1407
static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1496
static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1408
static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1497
static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1409
static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1498
static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1410
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1499
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1411
static char *complete_sip_peer(const char *word, int state, int flags2);
1500
static char *complete_sip_peer(const char *word, int state, int flags2);
1412
static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1501
static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1413
static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1502
static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1414
static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1503
static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1415
static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1504
static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1416
static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1505
static char *complete_sip_notify(const char *line, const char *word, int pos, int state);
1417
static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1506
static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1418
static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1507
static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1419
static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1508
static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1420
static char *sip_do_debug_ip(int fd, const char *arg);
1509
static char *sip_do_debug_ip(int fd, const char *arg);
1421
static char *sip_do_debug_peer(int fd, const char *arg);
1510
static char *sip_do_debug_peer(int fd, const char *arg);
1422
static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1511
static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1423
static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1512
static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1424
static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1513
static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1425
static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1514
static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1426
static int sip_addheader(struct ast_channel *chan, const char *data);
1515
static int sip_addheader(struct ast_channel *chan, const char *data);
1427
static int sip_do_reload(enum channelreloadreason reason);
1516
static int sip_do_reload(enum channelreloadreason reason);
1428
static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1517
static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1429
static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
1518
static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
1430
				      const char *name, int flag, int family);
1519
				      const char *name, int flag, int family);
1431
static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
1520
static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
1432
				      const char *name, int flag);
1521
				      const char *name, int flag);

    
   
1522
static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,

    
   
1523
						const char *name, int flag, unsigned int transport);
1433

    
   
1524

   
1434
/*--- Debugging
1525
/*--- Debugging
1435
	Functions for enabling debug per IP or fully, or enabling history logging for
1526
	Functions for enabling debug per IP or fully, or enabling history logging for
1436
	a SIP dialog
1527
	a SIP dialog
1437
*/
1528
*/
1438
static void sip_dump_history(struct sip_pvt *dialog);	/* Dump history to debuglog at end of dialog, before destroying data */
1529
static void sip_dump_history(struct sip_pvt *dialog);	/* Dump history to debuglog at end of dialog, before destroying data */
1439
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
1530
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
1440
static inline int sip_debug_test_pvt(struct sip_pvt *p);
1531
static inline int sip_debug_test_pvt(struct sip_pvt *p);
1441
static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1532
static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1442
static void sip_dump_history(struct sip_pvt *dialog);
1533
static void sip_dump_history(struct sip_pvt *dialog);
1443

    
   
1534

   
1444
/*--- Device object handling */
1535
/*--- Device object handling */
1445
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1536
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1446
static int update_call_counter(struct sip_pvt *fup, int event);
1537
static int update_call_counter(struct sip_pvt *fup, int event);
1447
static void sip_destroy_peer(struct sip_peer *peer);
1538
static void sip_destroy_peer(struct sip_peer *peer);
1448
static void sip_destroy_peer_fn(void *peer);
1539
static void sip_destroy_peer_fn(void *peer);
1449
static void set_peer_defaults(struct sip_peer *peer);
1540
static void set_peer_defaults(struct sip_peer *peer);
1450
static struct sip_peer *temp_peer(const char *name);
1541
static struct sip_peer *temp_peer(const char *name);
1451
static void register_peer_exten(struct sip_peer *peer, int onoff);
1542
static void register_peer_exten(struct sip_peer *peer, int onoff);
1452
static int sip_poke_peer_s(const void *data);
1543
static int sip_poke_peer_s(const void *data);
1453
static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1544
static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1454
static void reg_source_db(struct sip_peer *peer);
1545
static void reg_source_db(struct sip_peer *peer);
1455
static void destroy_association(struct sip_peer *peer);
1546
static void destroy_association(struct sip_peer *peer);
1456
static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1547
static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1457
static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1548
static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1458
static void set_socket_transport(struct sip_socket *socket, int transport);
1549
static void set_socket_transport(struct sip_socket *socket, int transport);
1459
static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags);
1550
static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags);
1460

    
   
1551

   
1461
/* Realtime device support */
1552
/* Realtime device support */
1462
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);
1553
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);
1463
static void update_peer(struct sip_peer *p, int expire);
1554
static void update_peer(struct sip_peer *p, int expire);
1464
static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1555
static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1465
static const char *get_name_from_variable(const struct ast_variable *var);
1556
static const char *get_name_from_variable(const struct ast_variable *var);
1466
static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, char *callbackexten, int devstate_only, int which_objects);
1557
static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, char *callbackexten, int devstate_only, int which_objects);
1467
static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1558
static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1468

    
   
1559

   
1469
/*--- Internal UA client handling (outbound registrations) */
1560
/*--- Internal UA client handling (outbound registrations) */
1470
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
1561
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
1471
static void sip_registry_destroy(struct sip_registry *reg);
1562
static void sip_registry_destroy(struct sip_registry *reg);
1472
static int sip_register(const char *value, int lineno);
1563
static int sip_register(const char *value, int lineno);
1473
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1564
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1474
static int sip_reregister(const void *data);
1565
static int sip_reregister(const void *data);
1475
static int __sip_do_register(struct sip_registry *r);
1566
static int __sip_do_register(struct sip_registry *r);
1476
static int sip_reg_timeout(const void *data);
1567
static int sip_reg_timeout(const void *data);
1477
static void sip_send_all_registers(void);
1568
static void sip_send_all_registers(void);
1478
static int sip_reinvite_retry(const void *data);
1569
static int sip_reinvite_retry(const void *data);
1479

    
   
1570

   
1480
/*--- Parsing SIP requests and responses */
1571
/*--- Parsing SIP requests and responses */
1481
static void append_date(struct sip_request *req);	/* Append date to SIP packet */

   
1482
static int determine_firstline_parts(struct sip_request *req);
1572
static int determine_firstline_parts(struct sip_request *req);
1483
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1573
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1484
static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1574
static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1485
static int find_sip_method(const char *msg);
1575
static int find_sip_method(const char *msg);
1486
static unsigned int parse_allowed_methods(struct sip_request *req);
1576
static unsigned int parse_allowed_methods(struct sip_request *req);
1487
static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1577
static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1488
static int parse_request(struct sip_request *req);
1578
static int parse_request(struct sip_request *req);
1489
static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1579
static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1490
static int method_match(enum sipmethod id, const char *name);
1580
static int method_match(enum sipmethod id, const char *name);
1491
static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1581
static void parse_copy(struct sip_request *dst, const struct sip_request *src);

    
   
1582
static void parse_oli(struct sip_request *req, struct ast_channel *chan);
1492
static const char *find_alias(const char *name, const char *_default);
1583
static const char *find_alias(const char *name, const char *_default);
1493
static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1584
static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1494
static void lws2sws(struct ast_str *msgbuf);
1585
static void lws2sws(struct ast_str *msgbuf);
1495
static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1586
static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1496
static char *remove_uri_parameters(char *uri);
1587
static char *remove_uri_parameters(char *uri);
1497
static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1588
static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1498
static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1589
static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1499
static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1590
static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1500
static int set_address_from_contact(struct sip_pvt *pvt);
1591
static int set_address_from_contact(struct sip_pvt *pvt);
1501
static void check_via(struct sip_pvt *p, struct sip_request *req);
1592
static void check_via(struct sip_pvt *p, struct sip_request *req);
1502
static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1593
static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1503
static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
1594
static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason, char **reason_str);
1504
static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1595
static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1505
static int get_msg_text(char *buf, int len, struct sip_request *req);
1596
static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout);
1506
static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);

   
1507
static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1597
static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1508
static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1598
static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1509
static int get_domain(const char *str, char *domain, int len);
1599
static int get_domain(const char *str, char *domain, int len);
1510
static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1600
static void get_realm(struct sip_pvt *p, const struct sip_request *req);

    
   
1601
static char *get_content(struct sip_request *req);
1511

    
   
1602

   
1512
/*-- TCP connection handling ---*/
1603
/*-- TCP connection handling ---*/
1513
static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
1604
static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
1514
static void *sip_tcp_worker_fn(void *);
1605
static void *sip_tcp_worker_fn(void *);
1515

    
   
1606

   
1516
/*--- Constructing requests and responses */
1607
/*--- Constructing requests and responses */
1517
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1608
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1518
static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1609
static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1519
static void deinit_req(struct sip_request *req);
1610
static void deinit_req(struct sip_request *req);
1520
static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
1611
static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
1521
static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1612
static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1522
static int init_resp(struct sip_request *resp, const char *msg);
1613
static int init_resp(struct sip_request *resp, const char *msg);
1523
static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1614
static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1524
static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1615
static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1525
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
1616
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
1526
static void build_via(struct sip_pvt *p);
1617
static void build_via(struct sip_pvt *p);
1527
static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1618
static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1528
static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address);
1619
static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog);
1529
static char *generate_random_string(char *buf, size_t size);
1620
static char *generate_random_string(char *buf, size_t size);
1530
static void build_callid_pvt(struct sip_pvt *pvt);
1621
static void build_callid_pvt(struct sip_pvt *pvt);
1531
static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
1622
static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
1532
static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
1623
static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
1533
static void make_our_tag(char *tagbuf, size_t len);
1624
static void make_our_tag(struct sip_pvt *pvt);
1534
static int add_header(struct sip_request *req, const char *var, const char *value);
1625
static int add_header(struct sip_request *req, const char *var, const char *value);
1535
static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
1626
static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
1536
static int add_content(struct sip_request *req, const char *line);
1627
static int add_content(struct sip_request *req, const char *line);
1537
static int finalize_content(struct sip_request *req);
1628
static int finalize_content(struct sip_request *req);
1538
static void destroy_msg_headers(struct sip_pvt *pvt);
1629
static void destroy_msg_headers(struct sip_pvt *pvt);
1539
static int add_text(struct sip_request *req, struct sip_pvt *p);
1630
static int add_text(struct sip_request *req, struct sip_pvt *p);
1540
static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1631
static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1541
static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1632
static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1542
static int add_vidupdate(struct sip_request *req);
1633
static int add_vidupdate(struct sip_request *req);
1543
static void add_route(struct sip_request *req, struct sip_route *route);
1634
static void add_route(struct sip_request *req, struct sip_route *route);
1544
static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1635
static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1545
static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1636
static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1546
static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1637
static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1547
static void set_destination(struct sip_pvt *p, char *uri);
1638
static void set_destination(struct sip_pvt *p, char *uri);
1548
static void append_date(struct sip_request *req);
1639
static void add_date(struct sip_request *req);

    
   
1640
static void add_expires(struct sip_request *req, int expires);
1549
static void build_contact(struct sip_pvt *p);
1641
static void build_contact(struct sip_pvt *p);
1550

    
   
1642

   
1551
/*------Request handling functions */
1643
/*------Request handling functions */
1552
static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
1644
static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
1553
static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1645
static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1554
static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *recount, const char *e, int *nounlock);
1646
static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, int *recount, const char *e, int *nounlock);
1555
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock);
1647
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, uint32_t seqno, int *nounlock);
1556
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1648
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1557
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
1649
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
1558
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1650
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1559
static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1651
static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1560
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1652
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1561
static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1653
static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1562
static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1654
static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1563
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock);
1655
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, int *nounlock);
1564
static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1656
static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1565
static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock);
1657
static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock);
1566

    
   
1658

   
1567
/*------Response handling functions */
1659
/*------Response handling functions */
1568
static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1660
static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1569
static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1661
static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1570
static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1662
static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1571
static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1663
static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1572
static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1664
static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1573
static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1665
static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1574
static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1666
static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1575

    
   
1667

   
1576
/*------ SRTP Support -------- */
1668
/*------ SRTP Support -------- */
1577
static int setup_srtp(struct sip_srtp **srtp);
1669
static int setup_srtp(struct sip_srtp **srtp);
1578
static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
1670
static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
1579

    
   
1671

   
1580
/*------ T38 Support --------- */
1672
/*------ T38 Support --------- */
1581
static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1673
static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1582
static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1674
static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1583
static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1675
static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1584
static void change_t38_state(struct sip_pvt *p, int state);
1676
static void change_t38_state(struct sip_pvt *p, int state);
1585

    
   
1677

   
1586
/*------ Session-Timers functions --------- */
1678
/*------ Session-Timers functions --------- */
1587
static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1679
static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1588
static int  proc_session_timer(const void *vp);
1680
static int  proc_session_timer(const void *vp);
1589
static void stop_session_timer(struct sip_pvt *p);
1681
static void stop_session_timer(struct sip_pvt *p);
1590
static void start_session_timer(struct sip_pvt *p);
1682
static void start_session_timer(struct sip_pvt *p);
1591
static void restart_session_timer(struct sip_pvt *p);
1683
static void restart_session_timer(struct sip_pvt *p);
1592
static const char *strefresher2str(enum st_refresher r);
1684
static const char *strefresherparam2str(enum st_refresher r);
1593
static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
1685
static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref);
1594
static int parse_minse(const char *p_hdrval, int *const p_interval);
1686
static int parse_minse(const char *p_hdrval, int *const p_interval);
1595
static int st_get_se(struct sip_pvt *, int max);
1687
static int st_get_se(struct sip_pvt *, int max);
1596
static enum st_refresher st_get_refresher(struct sip_pvt *);
1688
static enum st_refresher st_get_refresher(struct sip_pvt *);
1597
static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
1689
static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
1598
static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1690
static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1599

    
   
1691

   
1600
/*------- RTP Glue functions -------- */
1692
/*------- RTP Glue functions -------- */
1601
static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_rtp_instance *vinstance, struct ast_rtp_instance *tinstance, const struct ast_format_cap *cap, int nat_active);
1693
static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_rtp_instance *vinstance, struct ast_rtp_instance *tinstance, const struct ast_format_cap *cap, int nat_active);
1602

    
   
1694

   
1603
/*!--- SIP MWI Subscription support */
1695
/*!--- SIP MWI Subscription support */
1604
static int sip_subscribe_mwi(const char *value, int lineno);
1696
static int sip_subscribe_mwi(const char *value, int lineno);
1605
static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
1697
static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
1606
static void sip_send_all_mwi_subscriptions(void);
1698
static void sip_send_all_mwi_subscriptions(void);
1607
static int sip_subscribe_mwi_do(const void *data);
1699
static int sip_subscribe_mwi_do(const void *data);
1608
static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1700
static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1609

    
   
1701

   
1610
/*! \brief Definition of this channel for PBX channel registration */
1702
/*! \brief Definition of this channel for PBX channel registration */
1611
struct ast_channel_tech sip_tech = {
1703
struct ast_channel_tech sip_tech = {
1612
	.type = "SIP",
1704
	.type = "SIP",
1613
	.description = "Session Initiation Protocol (SIP)",
1705
	.description = "Session Initiation Protocol (SIP)",
1614
	.properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1706
	.properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1615
	.requester = sip_request_call,			/* called with chan unlocked */
1707
	.requester = sip_request_call,			/* called with chan unlocked */
1616
	.devicestate = sip_devicestate,			/* called with chan unlocked (not chan-specific) */
1708
	.devicestate = sip_devicestate,			/* called with chan unlocked (not chan-specific) */
1617
	.call = sip_call,			/* called with chan locked */
1709
	.call = sip_call,			/* called with chan locked */
1618
	.send_html = sip_sendhtml,
1710
	.send_html = sip_sendhtml,
1619
	.hangup = sip_hangup,			/* called with chan locked */
1711
	.hangup = sip_hangup,			/* called with chan locked */
1620
	.answer = sip_answer,			/* called with chan locked */
1712
	.answer = sip_answer,			/* called with chan locked */
1621
	.read = sip_read,			/* called with chan locked */
1713
	.read = sip_read,			/* called with chan locked */
1622
	.write = sip_write,			/* called with chan locked */
1714
	.write = sip_write,			/* called with chan locked */
1623
	.write_video = sip_write,		/* called with chan locked */
1715
	.write_video = sip_write,		/* called with chan locked */
1624
	.write_text = sip_write,
1716
	.write_text = sip_write,
1625
	.indicate = sip_indicate,		/* called with chan locked */
1717
	.indicate = sip_indicate,		/* called with chan locked */
1626
	.transfer = sip_transfer,		/* called with chan locked */
1718
	.transfer = sip_transfer,		/* called with chan locked */
1627
	.fixup = sip_fixup,			/* called with chan locked */
1719
	.fixup = sip_fixup,			/* called with chan locked */
1628
	.send_digit_begin = sip_senddigit_begin,	/* called with chan unlocked */
1720
	.send_digit_begin = sip_senddigit_begin,	/* called with chan unlocked */
1629
	.send_digit_end = sip_senddigit_end,
1721
	.send_digit_end = sip_senddigit_end,
1630
	.bridge = ast_rtp_instance_bridge,			/* XXX chan unlocked ? */
1722
	.bridge = ast_rtp_instance_bridge,			/* XXX chan unlocked ? */
1631
	.early_bridge = ast_rtp_instance_early_bridge,
1723
	.early_bridge = ast_rtp_instance_early_bridge,
1632
	.send_text = sip_sendtext,		/* called with chan locked */
1724
	.send_text = sip_sendtext,		/* called with chan locked */
1633
	.func_channel_read = sip_acf_channel_read,
1725
	.func_channel_read = sip_acf_channel_read,
1634
	.setoption = sip_setoption,
1726
	.setoption = sip_setoption,
1635
	.queryoption = sip_queryoption,
1727
	.queryoption = sip_queryoption,
1636
	.get_pvt_uniqueid = sip_get_callid,
1728
	.get_pvt_uniqueid = sip_get_callid,
1637
};
1729
};
1638

    
   
1730

   
1639
/*! \brief This version of the sip channel tech has no send_digit_begin
1731
/*! \brief This version of the sip channel tech has no send_digit_begin
1640
 * callback so that the core knows that the channel does not want
1732
 * callback so that the core knows that the channel does not want
1641
 * DTMF BEGIN frames.
1733
 * DTMF BEGIN frames.
1642
 * The struct is initialized just before registering the channel driver,
1734
 * The struct is initialized just before registering the channel driver,
1643
 * and is for use with channels using SIP INFO DTMF.
1735
 * and is for use with channels using SIP INFO DTMF.
1644
 */
1736
 */
1645
struct ast_channel_tech sip_tech_info;
1737
struct ast_channel_tech sip_tech_info;
1646

    
   
1738

   
1647
/*------- CC Support -------- */
1739
/*------- CC Support -------- */
1648
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1740
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1649
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1741
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1650
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1742
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1651
static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
1743
static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
1652
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);
1653
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1745
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1654
static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1746
static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1655
static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1747
static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1656

    
   
1748

   
1657
static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
1749
static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
1658
	.type = "SIP",
1750
	.type = "SIP",
1659
	.init = sip_cc_agent_init,
1751
	.init = sip_cc_agent_init,
1660
	.start_offer_timer = sip_cc_agent_start_offer_timer,
1752
	.start_offer_timer = sip_cc_agent_start_offer_timer,
1661
	.stop_offer_timer = sip_cc_agent_stop_offer_timer,
1753
	.stop_offer_timer = sip_cc_agent_stop_offer_timer,
1662
	.respond = sip_cc_agent_respond,
1754
	.respond = sip_cc_agent_respond,
1663
	.status_request = sip_cc_agent_status_request,
1755
	.status_request = sip_cc_agent_status_request,
1664
	.start_monitoring = sip_cc_agent_start_monitoring,
1756
	.start_monitoring = sip_cc_agent_start_monitoring,
1665
	.callee_available = sip_cc_agent_recall,
1757
	.callee_available = sip_cc_agent_recall,
1666
	.destructor = sip_cc_agent_destructor,
1758
	.destructor = sip_cc_agent_destructor,
1667
};
1759
};
1668

    
   
1760

   
1669
static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
1761
static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
1670
{
1762
{
1671
	struct ast_cc_agent *agent = obj;
1763
	struct ast_cc_agent *agent = obj;
1672
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1764
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1673
	const char *uri = arg;
1765
	const char *uri = arg;
1674

    
   
1766

   
1675
	return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1767
	return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1676
}
1768
}
1677

    
   
1769

   
1678
static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
1770
static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
1679
{
1771
{
1680
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
1772
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
1681
	return agent;
1773
	return agent;
1682
}
1774
}
1683

    
   
1775

   
1684
static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
1776
static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
1685
{
1777
{
1686
	struct ast_cc_agent *agent = obj;
1778
	struct ast_cc_agent *agent = obj;
1687
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1779
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1688
	const char *uri = arg;
1780
	const char *uri = arg;
1689

    
   
1781

   
1690
	return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1782
	return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1691
}
1783
}
1692

    
   
1784

   
1693
static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
1785
static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
1694
{
1786
{
1695
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
1787
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
1696
	return agent;
1788
	return agent;
1697
}
1789
}
1698

    
   
1790

   
1699
static int find_by_callid_helper(void *obj, void *arg, int flags)
1791
static int find_by_callid_helper(void *obj, void *arg, int flags)
1700
{
1792
{
1701
	struct ast_cc_agent *agent = obj;
1793
	struct ast_cc_agent *agent = obj;
1702
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1794
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1703
	struct sip_pvt *call_pvt = arg;
1795
	struct sip_pvt *call_pvt = arg;
1704

    
   
1796

   
1705
	return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
1797
	return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
1706
}
1798
}
1707

    
   
1799

   
1708
static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
1800
static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
1709
{
1801
{
1710
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
1802
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
1711
	return agent;
1803
	return agent;
1712
}
1804
}
1713

    
   
1805

   
1714
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
1806
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
1715
{
1807
{
1716
	struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
1808
	struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
1717
	struct sip_pvt *call_pvt = ast_channel_tech_pvt(chan);
1809
	struct sip_pvt *call_pvt = ast_channel_tech_pvt(chan);
1718

    
   
1810

   
1719
	if (!agent_pvt) {
1811
	if (!agent_pvt) {
1720
		return -1;
1812
		return -1;
1721
	}
1813
	}
1722

    
   
1814

   
1723
	ast_assert(!strcmp(ast_channel_tech(chan)->type, "SIP"));
1815
	ast_assert(!strcmp(ast_channel_tech(chan)->type, "SIP"));
1724

    
   
1816

   
1725
	ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
1817
	ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
1726
	ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
1818
	ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
1727
	agent_pvt->offer_timer_id = -1;
1819
	agent_pvt->offer_timer_id = -1;
1728
	agent->private_data = agent_pvt;
1820
	agent->private_data = agent_pvt;
1729
	sip_pvt_lock(call_pvt);
1821
	sip_pvt_lock(call_pvt);
1730
	ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1822
	ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1731
	sip_pvt_unlock(call_pvt);
1823
	sip_pvt_unlock(call_pvt);
1732
	return 0;
1824
	return 0;
1733
}
1825
}
1734

    
   
1826

   
1735
static int sip_offer_timer_expire(const void *data)
1827
static int sip_offer_timer_expire(const void *data)
1736
{
1828
{
1737
	struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
1829
	struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
1738
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1830
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1739

    
   
1831

   
1740
	agent_pvt->offer_timer_id = -1;
1832
	agent_pvt->offer_timer_id = -1;
1741

    
   
1833

   
1742
	return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
1834
	return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
1743
}
1835
}
1744

    
   
1836

   
1745
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
1837
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
1746
{
1838
{
1747
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1839
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1748
	int when;
1840
	int when;
1749

    
   
1841

   
1750
	when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1842
	when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1751
	agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
1843
	agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
1752
	return 0;
1844
	return 0;
1753
}
1845
}
1754

    
   
1846

   
1755
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
1847
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
1756
{
1848
{
1757
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1849
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1758

    
   
1850

   
1759
	AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1851
	AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1760
	return 0;
1852
	return 0;
1761
}
1853
}
1762

    
   
1854

   
1763
static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
1855
static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
1764
{
1856
{
1765
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1857
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1766

    
   
1858

   
1767
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1859
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1768
	ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
1860
	ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
1769
	if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
1861
	if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
1770
		/* The second half of this if statement may be a bit hard to grasp,
1862
		/* The second half of this if statement may be a bit hard to grasp,
1771
		 * so here's an explanation. When a subscription comes into
1863
		 * so here's an explanation. When a subscription comes into
1772
		 * chan_sip, as long as it is not malformed, it will be passed
1864
		 * chan_sip, as long as it is not malformed, it will be passed
1773
		 * to the CC core. If the core senses an out-of-order state transition,
1865
		 * to the CC core. If the core senses an out-of-order state transition,
1774
		 * then the core will call this callback with the "reason" set to a
1866
		 * then the core will call this callback with the "reason" set to a
1775
		 * failure condition.
1867
		 * failure condition.
1776
		 * However, an out-of-order state transition will occur during a resubscription
1868
		 * However, an out-of-order state transition will occur during a resubscription
1777
		 * for CC. In such a case, we can see that we have already generated a notify_uri
1869
		 * for CC. In such a case, we can see that we have already generated a notify_uri
1778
		 * and so we can detect that this isn't a *real* failure. Rather, it is just
1870
		 * and so we can detect that this isn't a *real* failure. Rather, it is just
1779
		 * something the core doesn't recognize as a legitimate SIP state transition.
1871
		 * something the core doesn't recognize as a legitimate SIP state transition.
1780
		 * Thus we respond with happiness and flowers.
1872
		 * Thus we respond with happiness and flowers.
1781
		 */
1873
		 */
1782
		transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1874
		transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1783
		transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1875
		transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1784
	} else {
1876
	} else {
1785
		transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
1877
		transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
1786
	}
1878
	}
1787
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1879
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1788
	agent_pvt->is_available = TRUE;
1880
	agent_pvt->is_available = TRUE;
1789
}
1881
}
1790

    
   
1882

   
1791
static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
1883
static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
1792
{
1884
{
1793
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1885
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1794
	enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
1886
	enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
1795
	return ast_cc_agent_status_response(agent->core_id, state);
1887
	return ast_cc_agent_status_response(agent->core_id, state);
1796
}
1888
}
1797

    
   
1889

   
1798
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
1890
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
1799
{
1891
{
1800
	/* To start monitoring just means to wait for an incoming PUBLISH
1892
	/* To start monitoring just means to wait for an incoming PUBLISH
1801
	 * to tell us that the caller has become available again. No special
1893
	 * to tell us that the caller has become available again. No special
1802
	 * action is needed
1894
	 * action is needed
1803
	 */
1895
	 */
1804
	return 0;
1896
	return 0;
1805
}
1897
}
1806

    
   
1898

   
1807
static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1899
static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1808
{
1900
{
1809
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1901
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1810
	/* If we have received a PUBLISH beforehand stating that the caller in question
1902
	/* If we have received a PUBLISH beforehand stating that the caller in question
1811
	 * is not available, we can save ourself a bit of effort here and just report
1903
	 * is not available, we can save ourself a bit of effort here and just report
1812
	 * the caller as busy
1904
	 * the caller as busy
1813
	 */
1905
	 */
1814
	if (!agent_pvt->is_available) {
1906
	if (!agent_pvt->is_available) {
1815
		return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
1907
		return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
1816
				agent->device_name);
1908
				agent->device_name);
1817
	}
1909
	}
1818
	/* Otherwise, we transmit a NOTIFY to the caller and await either
1910
	/* Otherwise, we transmit a NOTIFY to the caller and await either
1819
	 * a PUBLISH or an INVITE
1911
	 * a PUBLISH or an INVITE
1820
	 */
1912
	 */
1821
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1913
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1822
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1914
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1823
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1915
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1824
	return 0;
1916
	return 0;
1825
}
1917
}
1826

    
   
1918

   
1827
static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
1919
static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
1828
{
1920
{
1829
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1921
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1830

    
   
1922

   
1831
	if (!agent_pvt) {
1923
	if (!agent_pvt) {
1832
		/* The agent constructor probably failed. */
1924
		/* The agent constructor probably failed. */
1833
		return;
1925
		return;
1834
	}
1926
	}
1835

    
   
1927

   
1836
	sip_cc_agent_stop_offer_timer(agent);
1928
	sip_cc_agent_stop_offer_timer(agent);
1837
	if (agent_pvt->subscribe_pvt) {
1929
	if (agent_pvt->subscribe_pvt) {
1838
		sip_pvt_lock(agent_pvt->subscribe_pvt);
1930
		sip_pvt_lock(agent_pvt->subscribe_pvt);
1839
		if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
1931
		if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
1840
			/* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
1932
			/* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
1841
			 * the subscriber know something went wrong
1933
			 * the subscriber know something went wrong
1842
			 */
1934
			 */
1843
			transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
1935
			transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
1844
		}
1936
		}
1845
		sip_pvt_unlock(agent_pvt->subscribe_pvt);
1937
		sip_pvt_unlock(agent_pvt->subscribe_pvt);
1846
		agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
1938
		agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
1847
	}
1939
	}
1848
	ast_free(agent_pvt);
1940
	ast_free(agent_pvt);
1849
}
1941
}
1850

    
   
1942

   
1851
struct ao2_container *sip_monitor_instances;
1943
struct ao2_container *sip_monitor_instances;
1852

    
   
1944

   
1853
static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
1945
static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
1854
{
1946
{
1855
	const struct sip_monitor_instance *monitor_instance = obj;
1947
	const struct sip_monitor_instance *monitor_instance = obj;
1856
	return monitor_instance->core_id;
1948
	return monitor_instance->core_id;
1857
}
1949
}
1858

    
   
1950

   
1859
static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
1951
static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
1860
{
1952
{
1861
	struct sip_monitor_instance *monitor_instance1 = obj;
1953
	struct sip_monitor_instance *monitor_instance1 = obj;
1862
	struct sip_monitor_instance *monitor_instance2 = arg;
1954
	struct sip_monitor_instance *monitor_instance2 = arg;
1863

    
   
1955

   
1864
	return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
1956
	return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
1865
}
1957
}
1866

    
   
1958

   
1867
static void sip_monitor_instance_destructor(void *data)
1959
static void sip_monitor_instance_destructor(void *data)
1868
{
1960
{
1869
	struct sip_monitor_instance *monitor_instance = data;
1961
	struct sip_monitor_instance *monitor_instance = data;
1870
	if (monitor_instance->subscription_pvt) {
1962
	if (monitor_instance->subscription_pvt) {
1871
		sip_pvt_lock(monitor_instance->subscription_pvt);
1963
		sip_pvt_lock(monitor_instance->subscription_pvt);
1872
		monitor_instance->subscription_pvt->expiry = 0;
1964
		monitor_instance->subscription_pvt->expiry = 0;
1873
		transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
1965
		transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
1874
		sip_pvt_unlock(monitor_instance->subscription_pvt);
1966
		sip_pvt_unlock(monitor_instance->subscription_pvt);
1875
		dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
1967
		dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
1876
	}
1968
	}
1877
	if (monitor_instance->suspension_entry) {
1969
	if (monitor_instance->suspension_entry) {
1878
		monitor_instance->suspension_entry->body[0] = '\0';
1970
		monitor_instance->suspension_entry->body[0] = '\0';
1879
		transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
1971
		transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
1880
		ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
1972
		ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
1881
	}
1973
	}
1882
	ast_string_field_free_memory(monitor_instance);
1974
	ast_string_field_free_memory(monitor_instance);
1883
}
1975
}
1884

    
   
1976

   
1885
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)
1977
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)
1886
{
1978
{
1887
	struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
1979
	struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
1888

    
   
1980

   
1889
	if (!monitor_instance) {
1981
	if (!monitor_instance) {
1890
		return NULL;
1982
		return NULL;
1891
	}
1983
	}
1892

    
   
1984

   
1893
	if (ast_string_field_init(monitor_instance, 256)) {
1985
	if (ast_string_field_init(monitor_instance, 256)) {
1894
		ao2_ref(monitor_instance, -1);
1986
		ao2_ref(monitor_instance, -1);
1895
		return NULL;
1987
		return NULL;
1896
	}
1988
	}
1897

    
   
1989

   
1898
	ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
1990
	ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
1899
	ast_string_field_set(monitor_instance, peername, peername);
1991
	ast_string_field_set(monitor_instance, peername, peername);
1900
	ast_string_field_set(monitor_instance, device_name, device_name);
1992
	ast_string_field_set(monitor_instance, device_name, device_name);
1901
	monitor_instance->core_id = core_id;
1993
	monitor_instance->core_id = core_id;
1902
	ao2_link(sip_monitor_instances, monitor_instance);
1994
	ao2_link(sip_monitor_instances, monitor_instance);
1903
	return monitor_instance;
1995
	return monitor_instance;
1904
}
1996
}
1905

    
   
1997

   
1906
static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
1998
static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
1907
{
1999
{
1908
	struct sip_monitor_instance *monitor_instance = obj;
2000
	struct sip_monitor_instance *monitor_instance = obj;
1909
	return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
2001
	return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
1910
}
2002
}
1911

    
   
2003

   
1912
static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
2004
static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
1913
{
2005
{
1914
	struct sip_monitor_instance *monitor_instance = obj;
2006
	struct sip_monitor_instance *monitor_instance = obj;
1915
	return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
2007
	return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
1916
}
2008
}
1917

    
   
2009

   
1918
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
2010
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
1919
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
2011
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
1920
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
2012
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
1921
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
2013
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
1922
static void sip_cc_monitor_destructor(void *private_data);
2014
static void sip_cc_monitor_destructor(void *private_data);
1923

    
   
2015

   
1924
static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
2016
static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
1925
	.type = "SIP",
2017
	.type = "SIP",
1926
	.request_cc = sip_cc_monitor_request_cc,
2018
	.request_cc = sip_cc_monitor_request_cc,
1927
	.suspend = sip_cc_monitor_suspend,
2019
	.suspend = sip_cc_monitor_suspend,
1928
	.unsuspend = sip_cc_monitor_unsuspend,
2020
	.unsuspend = sip_cc_monitor_unsuspend,
1929
	.cancel_available_timer = sip_cc_monitor_cancel_available_timer,
2021
	.cancel_available_timer = sip_cc_monitor_cancel_available_timer,
1930
	.destructor = sip_cc_monitor_destructor,
2022
	.destructor = sip_cc_monitor_destructor,
1931
};
2023
};
1932

    
   
2024

   
1933
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
2025
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
1934
{
2026
{
1935
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
2027
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1936
	enum ast_cc_service_type service = monitor->service_offered;
2028
	enum ast_cc_service_type service = monitor->service_offered;
1937
	int when;
2029
	int when;
1938

    
   
2030

   
1939
	if (!monitor_instance) {
2031
	if (!monitor_instance) {
1940
		return -1;
2032
		return -1;
1941
	}
2033
	}
1942

    
   
2034

   
1943
	if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
2035
	if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, NULL))) {
1944
		return -1;
2036
		return -1;
1945
	}
2037
	}
1946

    
   
2038

   
1947
	when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
2039
	when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
1948
		ast_get_ccnr_available_timer(monitor->interface->config_params);
2040
		ast_get_ccnr_available_timer(monitor->interface->config_params);
1949

    
   
2041

   
1950
	sip_pvt_lock(monitor_instance->subscription_pvt);
2042
	sip_pvt_lock(monitor_instance->subscription_pvt);
1951
	ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
2043
	ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
1952
	create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
2044
	create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1);
1953
	ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
2045
	ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
1954
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
2046
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1955
	monitor_instance->subscription_pvt->expiry = when;
2047
	monitor_instance->subscription_pvt->expiry = when;
1956

    
   
2048

   
1957
	transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
2049
	transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
1958
	sip_pvt_unlock(monitor_instance->subscription_pvt);
2050
	sip_pvt_unlock(monitor_instance->subscription_pvt);
1959

    
   
2051

   
1960
	ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
2052
	ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
1961
	*available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
2053
	*available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
1962
	return 0;
2054
	return 0;
1963
}
2055
}
1964

    
   
2056

   
1965
static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
2057
static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
1966
{
2058
{
1967
	struct ast_str *body = ast_str_alloca(size);
2059
	struct ast_str *body = ast_str_alloca(size);
1968
	char tuple_id[32];
2060
	char tuple_id[32];
1969

    
   
2061

   
1970
	generate_random_string(tuple_id, sizeof(tuple_id));
2062
	generate_random_string(tuple_id, sizeof(tuple_id));
1971

    
   
2063

   
1972
	/* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
2064
	/* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
1973
	 * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
2065
	 * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
1974
	 */
2066
	 */
1975
	ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2067
	ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1976
	/* XXX The entity attribute is currently set to the peer name associated with the
2068
	/* XXX The entity attribute is currently set to the peer name associated with the
1977
	 * dialog. This is because we currently only call this function for call-completion
2069
	 * dialog. This is because we currently only call this function for call-completion
1978
	 * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
2070
	 * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
1979
	 * event packages, it may be crucial to have a proper URI as the presentity so this
2071
	 * event packages, it may be crucial to have a proper URI as the presentity so this
1980
	 * should be revisited as support is expanded.
2072
	 * should be revisited as support is expanded.
1981
	 */
2073
	 */
1982
	ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
2074
	ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
1983
	ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
2075
	ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
1984
	ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
2076
	ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
1985
	ast_str_append(&body, 0, "</tuple>\n");
2077
	ast_str_append(&body, 0, "</tuple>\n");
1986
	ast_str_append(&body, 0, "</presence>\n");
2078
	ast_str_append(&body, 0, "</presence>\n");
1987
	ast_copy_string(pidf_body, ast_str_buffer(body), size);
2079
	ast_copy_string(pidf_body, ast_str_buffer(body), size);
1988
	return 0;
2080
	return 0;
1989
}
2081
}
1990

    
   
2082

   
1991
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
2083
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
1992
{
2084
{
1993
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
2085
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1994
	enum sip_publish_type publish_type;
2086
	enum sip_publish_type publish_type;
1995
	struct cc_epa_entry *cc_entry;
2087
	struct cc_epa_entry *cc_entry;
1996

    
   
2088

   
1997
	if (!monitor_instance) {
2089
	if (!monitor_instance) {
1998
		return -1;
2090
		return -1;
1999
	}
2091
	}
2000

    
   
2092

   
2001
	if (!monitor_instance->suspension_entry) {
2093
	if (!monitor_instance->suspension_entry) {
2002
		/* We haven't yet allocated the suspension entry, so let's give it a shot */
2094
		/* We haven't yet allocated the suspension entry, so let's give it a shot */
2003
		if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
2095
		if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
2004
			ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
2096
			ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
2005
			ao2_ref(monitor_instance, -1);
2097
			ao2_ref(monitor_instance, -1);
2006
			return -1;
2098
			return -1;
2007
		}
2099
		}
2008
		if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
2100
		if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
2009
			ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
2101
			ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
2010
			ao2_ref(monitor_instance, -1);
2102
			ao2_ref(monitor_instance, -1);
2011
			return -1;
2103
			return -1;
2012
		}
2104
		}
2013
		cc_entry->core_id = monitor->core_id;
2105
		cc_entry->core_id = monitor->core_id;
2014
		monitor_instance->suspension_entry->instance_data = cc_entry;
2106
		monitor_instance->suspension_entry->instance_data = cc_entry;
2015
		publish_type = SIP_PUBLISH_INITIAL;
2107
		publish_type = SIP_PUBLISH_INITIAL;
2016
	} else {
2108
	} else {
2017
		publish_type = SIP_PUBLISH_MODIFY;
2109
		publish_type = SIP_PUBLISH_MODIFY;
2018
		cc_entry = monitor_instance->suspension_entry->instance_data;
2110
		cc_entry = monitor_instance->suspension_entry->instance_data;
2019
	}
2111
	}
2020

    
   
2112

   
2021
	cc_entry->current_state = CC_CLOSED;
2113
	cc_entry->current_state = CC_CLOSED;
2022

    
   
2114

   
2023
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
2115
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
2024
		/* If we have no set notify_uri, then what this means is that we have
2116
		/* If we have no set notify_uri, then what this means is that we have
2025
		 * not received a NOTIFY from this destination stating that he is
2117
		 * not received a NOTIFY from this destination stating that he is
2026
		 * currently available.
2118
		 * currently available.
2027
		 *
2119
		 *
2028
		 * This situation can arise when the core calls the suspend callbacks
2120
		 * This situation can arise when the core calls the suspend callbacks
2029
		 * of multiple destinations. If one of the other destinations aside
2121
		 * of multiple destinations. If one of the other destinations aside
2030
		 * from this one notified Asterisk that he is available, then there
2122
		 * from this one notified Asterisk that he is available, then there
2031
		 * is no reason to take any suspension action on this device. Rather,
2123
		 * is no reason to take any suspension action on this device. Rather,
2032
		 * we should return now and if we receive a NOTIFY while monitoring
2124
		 * we should return now and if we receive a NOTIFY while monitoring
2033
		 * is still "suspended" then we can immediately respond with the
2125
		 * is still "suspended" then we can immediately respond with the
2034
		 * proper PUBLISH to let this endpoint know what is going on.
2126
		 * proper PUBLISH to let this endpoint know what is going on.
2035
		 */
2127
		 */
2036
		return 0;
2128
		return 0;
2037
	}
2129
	}
2038
	construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2130
	construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2039
	return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
2131
	return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
2040
}
2132
}
2041

    
   
2133

   
2042
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
2134
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
2043
{
2135
{
2044
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
2136
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
2045
	struct cc_epa_entry *cc_entry;
2137
	struct cc_epa_entry *cc_entry;
2046

    
   
2138

   
2047
	if (!monitor_instance) {
2139
	if (!monitor_instance) {
2048
		return -1;
2140
		return -1;
2049
	}
2141
	}
2050

    
   
2142

   
2051
	ast_assert(monitor_instance->suspension_entry != NULL);
2143
	ast_assert(monitor_instance->suspension_entry != NULL);
2052

    
   
2144

   
2053
	cc_entry = monitor_instance->suspension_entry->instance_data;
2145
	cc_entry = monitor_instance->suspension_entry->instance_data;
2054
	cc_entry->current_state = CC_OPEN;
2146
	cc_entry->current_state = CC_OPEN;
2055
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
2147
	if (ast_strlen_zero(monitor_instance->notify_uri)) {
2056
		/* This means we are being asked to unsuspend a call leg we never
2148
		/* This means we are being asked to unsuspend a call leg we never
2057
		 * sent a PUBLISH on. As such, there is no reason to send another
2149
		 * sent a PUBLISH on. As such, there is no reason to send another
2058
		 * PUBLISH at this point either. We can just return instead.
2150
		 * PUBLISH at this point either. We can just return instead.
2059
		 */
2151
		 */
2060
		return 0;
2152
		return 0;
2061
	}
2153
	}
2062
	construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2154
	construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2063
	return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
2155
	return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
2064
}
2156
}
2065

    
   
2157

   
2066
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
2158
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
2067
{
2159
{
2068
	if (*sched_id != -1) {
2160
	if (*sched_id != -1) {
2069
		AST_SCHED_DEL(sched, *sched_id);
2161
		AST_SCHED_DEL(sched, *sched_id);
2070
		ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
2162
		ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
2071
	}
2163
	}
2072
	return 0;
2164
	return 0;
2073
}
2165
}
2074

    
   
2166

   
2075
static void sip_cc_monitor_destructor(void *private_data)
2167
static void sip_cc_monitor_destructor(void *private_data)
2076
{
2168
{
2077
	struct sip_monitor_instance *monitor_instance = private_data;
2169
	struct sip_monitor_instance *monitor_instance = private_data;
2078
	ao2_unlink(sip_monitor_instances, monitor_instance);
2170
	ao2_unlink(sip_monitor_instances, monitor_instance);
2079
	ast_module_unref(ast_module_info->self);
2171
	ast_module_unref(ast_module_info->self);
2080
}
2172
}
2081

    
   
2173

   
2082
static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
2174
static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
2083
{
2175
{
2084
	char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
2176
	char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
2085
	char *uri;
2177
	char *uri;
2086
	char *purpose;
2178
	char *purpose;
2087
	char *service_str;
2179
	char *service_str;
2088
	static const char cc_purpose[] = "purpose=call-completion";
2180
	static const char cc_purpose[] = "purpose=call-completion";
2089
	static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2181
	static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2090

    
   
2182

   
2091
	if (ast_strlen_zero(call_info)) {
2183
	if (ast_strlen_zero(call_info)) {
2092
		/* No Call-Info present. Definitely no CC offer */
2184
		/* No Call-Info present. Definitely no CC offer */
2093
		return -1;
2185
		return -1;
2094
	}
2186
	}
2095

    
   
2187

   
2096
	uri = strsep(&call_info, ";");
2188
	uri = strsep(&call_info, ";");
2097

    
   
2189

   
2098
	while ((purpose = strsep(&call_info, ";"))) {
2190
	while ((purpose = strsep(&call_info, ";"))) {
2099
		if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
2191
		if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
2100
			break;
2192
			break;
2101
		}
2193
		}
2102
	}
2194
	}
2103
	if (!purpose) {
2195
	if (!purpose) {
2104
		/* We didn't find the appropriate purpose= parameter. Oh well */
2196
		/* We didn't find the appropriate purpose= parameter. Oh well */
2105
		return -1;
2197
		return -1;
2106
	}
2198
	}
2107

    
   
2199

   
2108
	/* Okay, call-completion has been offered. Let's figure out what type of service this is */
2200
	/* Okay, call-completion has been offered. Let's figure out what type of service this is */
2109
	while ((service_str = strsep(&call_info, ";"))) {
2201
	while ((service_str = strsep(&call_info, ";"))) {
2110
		if (!strncmp(service_str, "m=", 2)) {
2202
		if (!strncmp(service_str, "m=", 2)) {
2111
			break;
2203
			break;
2112
		}
2204
		}
2113
	}
2205
	}
2114
	if (!service_str) {
2206
	if (!service_str) {
2115
		/* So they didn't offer a particular service, We'll just go with CCBS since it really
2207
		/* So they didn't offer a particular service, We'll just go with CCBS since it really
2116
		 * doesn't matter anyway
2208
		 * doesn't matter anyway
2117
		 */
2209
		 */
2118
		service_str = "BS";
2210
		service_str = "BS";
2119
	} else {
2211
	} else {
2120
		/* We already determined that there is an "m=" so no need to check
2212
		/* We already determined that there is an "m=" so no need to check
2121
		 * the result of this strsep
2213
		 * the result of this strsep
2122
		 */
2214
		 */
2123
		strsep(&service_str, "=");
2215
		strsep(&service_str, "=");
2124
	}
2216
	}
2125

    
   
2217

   
2126
	if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2218
	if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2127
		/* Invalid service offered */
2219
		/* Invalid service offered */
2128
		return -1;
2220
		return -1;
2129
	}
2221
	}
2130

    
   
2222

   
2131
	ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2223
	ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2132

    
   
2224

   
2133
	return 0;
2225
	return 0;
2134
}
2226
}
2135

    
   
2227

   
2136
/*
2228
/*
2137
 * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
2229
 * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
2138
 *
2230
 *
2139
 * After taking care of some formalities to be sure that this call is eligible for CC,
2231
 * After taking care of some formalities to be sure that this call is eligible for CC,
2140
 * we first try to see if we can make use of native CC. We grab the information from
2232
 * we first try to see if we can make use of native CC. We grab the information from
2141
 * the passed-in sip_request (which is always a response to an INVITE). If we can
2233
 * the passed-in sip_request (which is always a response to an INVITE). If we can
2142
 * use native CC monitoring for the call, then so be it.
2234
 * use native CC monitoring for the call, then so be it.
2143
 *
2235
 *
2144
 * If native cc monitoring is not possible or not supported, then we will instead attempt
2236
 * If native cc monitoring is not possible or not supported, then we will instead attempt
2145
 * to use generic monitoring. Falling back to generic from a failed attempt at using native
2237
 * to use generic monitoring. Falling back to generic from a failed attempt at using native
2146
 * monitoring will only work if the monitor policy of the endpoint is "always"
2238
 * monitoring will only work if the monitor policy of the endpoint is "always"
2147
 *
2239
 *
2148
 * \param pvt The current dialog. Contains CC parameters for the endpoint
2240
 * \param pvt The current dialog. Contains CC parameters for the endpoint
2149
 * \param req The response to the INVITE we want to inspect
2241
 * \param req The response to the INVITE we want to inspect
2150
 * \param service The service to use if generic monitoring is to be used. For native
2242
 * \param service The service to use if generic monitoring is to be used. For native
2151
 * monitoring, we get the service from the SIP response itself
2243
 * monitoring, we get the service from the SIP response itself
2152
 */
2244
 */
2153
static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
2245
static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
2154
{
2246
{
2155
	enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
2247
	enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
2156
	int core_id;
2248
	int core_id;
2157
	char interface_name[AST_CHANNEL_NAME];
2249
	char interface_name[AST_CHANNEL_NAME];
2158

    
   
2250

   
2159
	if (monitor_policy == AST_CC_MONITOR_NEVER) {
2251
	if (monitor_policy == AST_CC_MONITOR_NEVER) {
2160
		/* Don't bother, just return */
2252
		/* Don't bother, just return */
2161
		return;
2253
		return;
2162
	}
2254
	}
2163

    
   
2255

   
2164
	if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
2256
	if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
2165
		/* For some reason, CC is invalid, so don't try it! */
2257
		/* For some reason, CC is invalid, so don't try it! */
2166
		return;
2258
		return;
2167
	}
2259
	}
2168

    
   
2260

   
2169
	ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2261
	ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2170

    
   
2262

   
2171
	if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
2263
	if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
2172
		char subscribe_uri[SIPBUFSIZE];
2264
		char subscribe_uri[SIPBUFSIZE];
2173
		char device_name[AST_CHANNEL_NAME];
2265
		char device_name[AST_CHANNEL_NAME];
2174
		enum ast_cc_service_type offered_service;
2266
		enum ast_cc_service_type offered_service;
2175
		struct sip_monitor_instance *monitor_instance;
2267
		struct sip_monitor_instance *monitor_instance;
2176
		if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
2268
		if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
2177
			/* If CC isn't being offered to us, or for some reason the CC offer is
2269
			/* If CC isn't being offered to us, or for some reason the CC offer is
2178
			 * not formatted correctly, then it may still be possible to use generic
2270
			 * not formatted correctly, then it may still be possible to use generic
2179
			 * call completion since the monitor policy may be "always"
2271
			 * call completion since the monitor policy may be "always"
2180
			 */
2272
			 */
2181
			goto generic;
2273
			goto generic;
2182
		}
2274
		}
2183
		ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2275
		ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2184
		if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
2276
		if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
2185
			/* Same deal. We can try using generic still */
2277
			/* Same deal. We can try using generic still */
2186
			goto generic;
2278
			goto generic;
2187
		}
2279
		}
2188
		/* We bump the refcount of chan_sip because once we queue this frame, the CC core
2280
		/* We bump the refcount of chan_sip because once we queue this frame, the CC core
2189
		 * will have a reference to callbacks in this module. We decrement the module
2281
		 * will have a reference to callbacks in this module. We decrement the module
2190
		 * refcount once the monitor destructor is called
2282
		 * refcount once the monitor destructor is called
2191
		 */
2283
		 */
2192
		ast_module_ref(ast_module_info->self);
2284
		ast_module_ref(ast_module_info->self);
2193
		ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
2285
		ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
2194
		ao2_ref(monitor_instance, -1);
2286
		ao2_ref(monitor_instance, -1);
2195
		return;
2287
		return;
2196
	}
2288
	}
2197

    
   
2289

   
2198
generic:
2290
generic:
2199
	if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2291
	if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2200
		ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2292
		ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2201
	}
2293
	}
2202
}
2294
}
2203

    
   
2295

   
2204
/*! \brief Working TLS connection configuration */
2296
/*! \brief Working TLS connection configuration */
2205
static struct ast_tls_config sip_tls_cfg;
2297
static struct ast_tls_config sip_tls_cfg;
2206

    
   
2298

   
2207
/*! \brief Default TLS connection configuration */
2299
/*! \brief Default TLS connection configuration */
2208
static struct ast_tls_config default_tls_cfg;
2300
static struct ast_tls_config default_tls_cfg;
2209

    
   
2301

   
2210
/*! \brief The TCP server definition */
2302
/*! \brief The TCP server definition */
2211
static struct ast_tcptls_session_args sip_tcp_desc = {
2303
static struct ast_tcptls_session_args sip_tcp_desc = {
2212
	.accept_fd = -1,
2304
	.accept_fd = -1,
2213
	.master = AST_PTHREADT_NULL,
2305
	.master = AST_PTHREADT_NULL,
2214
	.tls_cfg = NULL,
2306
	.tls_cfg = NULL,
2215
	.poll_timeout = -1,
2307
	.poll_timeout = -1,
2216
	.name = "SIP TCP server",
2308
	.name = "SIP TCP server",
2217
	.accept_fn = ast_tcptls_server_root,
2309
	.accept_fn = ast_tcptls_server_root,
2218
	.worker_fn = sip_tcp_worker_fn,
2310
	.worker_fn = sip_tcp_worker_fn,
2219
};
2311
};
2220

    
   
2312

   
2221
/*! \brief The TCP/TLS server definition */
2313
/*! \brief The TCP/TLS server definition */
2222
static struct ast_tcptls_session_args sip_tls_desc = {
2314
static struct ast_tcptls_session_args sip_tls_desc = {
2223
	.accept_fd = -1,
2315
	.accept_fd = -1,
2224
	.master = AST_PTHREADT_NULL,
2316
	.master = AST_PTHREADT_NULL,
2225
	.tls_cfg = &sip_tls_cfg,
2317
	.tls_cfg = &sip_tls_cfg,
2226
	.poll_timeout = -1,
2318
	.poll_timeout = -1,
2227
	.name = "SIP TLS server",
2319
	.name = "SIP TLS server",
2228
	.accept_fn = ast_tcptls_server_root,
2320
	.accept_fn = ast_tcptls_server_root,
2229
	.worker_fn = sip_tcp_worker_fn,
2321
	.worker_fn = sip_tcp_worker_fn,
2230
};
2322
};
2231

    
   
2323

   
2232
/*! \brief Append to SIP dialog history
2324
/*! \brief Append to SIP dialog history
2233
	\return Always returns 0 */
2325
	\return Always returns 0 */
2234
#define append_history(p, event, fmt , args... )	append_history_full(p, "%-15s " fmt, event, ## args)
2326
#define append_history(p, event, fmt , args... )	append_history_full(p, "%-15s " fmt, event, ## args)
2235

    
   
2327

   
2236
struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
2328
struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
2237
{
2329
{
2238
	if (p)
2330
	if (p)
2239
#ifdef REF_DEBUG
2331
#ifdef REF_DEBUG
2240
		__ao2_ref_debug(p, 1, tag, file, line, func);
2332
		__ao2_ref_debug(p, 1, tag, file, line, func);
2241
#else
2333
#else
2242
		ao2_ref(p, 1);
2334
		ao2_ref(p, 1);
2243
#endif
2335
#endif
2244
	else
2336
	else
2245
		ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2337
		ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2246
	return p;
2338
	return p;
2247
}
2339
}
2248

    
   
2340

   
2249
struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
2341
struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
2250
{
2342
{
2251
	if (p)
2343
	if (p)
2252
#ifdef REF_DEBUG
2344
#ifdef REF_DEBUG
2253
		__ao2_ref_debug(p, -1, tag, file, line, func);
2345
		__ao2_ref_debug(p, -1, tag, file, line, func);
2254
#else
2346
#else
2255
		ao2_ref(p, -1);
2347
		ao2_ref(p, -1);
2256
#endif
2348
#endif
2257
	return NULL;
2349
	return NULL;
2258
}
2350
}
2259

    
   
2351

   
2260
/*! \brief map from an integer value to a string.
2352
/*! \brief map from an integer value to a string.
2261
 * If no match is found, return errorstring
2353
 * If no match is found, return errorstring
2262
 */
2354
 */
2263
static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2355
static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2264
{
2356
{
2265
	const struct _map_x_s *cur;
2357
	const struct _map_x_s *cur;
2266

    
   
2358

   
2267
	for (cur = table; cur->s; cur++) {
2359
	for (cur = table; cur->s; cur++) {
2268
		if (cur->x == x) {
2360
		if (cur->x == x) {
2269
			return cur->s;
2361
			return cur->s;
2270
		}
2362
		}
2271
	}
2363
	}
2272
	return errorstring;
2364
	return errorstring;
2273
}
2365
}
2274

    
   
2366

   
2275
/*! \brief map from a string to an integer value, case insensitive.
2367
/*! \brief map from a string to an integer value, case insensitive.
2276
 * If no match is found, return errorvalue.
2368
 * If no match is found, return errorvalue.
2277
 */
2369
 */
2278
static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2370
static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2279
{
2371
{
2280
	const struct _map_x_s *cur;
2372
	const struct _map_x_s *cur;
2281

    
   
2373

   
2282
	for (cur = table; cur->s; cur++) {
2374
	for (cur = table; cur->s; cur++) {
2283
		if (!strcasecmp(cur->s, s)) {
2375
		if (!strcasecmp(cur->s, s)) {
2284
			return cur->x;
2376
			return cur->x;
2285
		}
2377
		}
2286
	}
2378
	}
2287
	return errorvalue;
2379
	return errorvalue;
2288
}
2380
}
2289

    
   
2381

   
2290
static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
2382
static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
2291
{
2383
{
2292
	enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2384
	enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2293
	int i;
2385
	int i;
2294

    
   
2386

   
2295
	for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
2387
	for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
2296
		if (!strcasecmp(text, sip_reason_table[i].text)) {
2388
		if (!strcasecmp(text, sip_reason_table[i].text)) {
2297
			ast = sip_reason_table[i].code;
2389
			ast = sip_reason_table[i].code;
2298
			break;
2390
			break;
2299
		}
2391
		}
2300
	}
2392
	}
2301

    
   
2393

   
2302
	return ast;
2394
	return ast;
2303
}
2395
}
2304

    
   
2396

   
2305
static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
2397
static const char *sip_reason_code_to_str(struct ast_party_redirecting_reason *reason, int *table_lookup)
2306
{
2398
{

    
   
2399
	int code = reason->code;

    
   
2400

   

    
   
2401
	/* If there's a specific string set, then we just

    
   
2402
	 * use it.

    
   
2403
	 */

    
   
2404
	if (!ast_strlen_zero(reason->str)) {

    
   
2405
		/* If we care about whether this can be found in

    
   
2406
		 * the table, then we need to check about that.

    
   
2407
		 */

    
   
2408
		if (table_lookup) {

    
   
2409
			/* If the string is literally "unknown" then don't bother with the lookup

    
   
2410
			 * because it can lead to a false negative.

    
   
2411
			 */

    
   
2412
			if (!strcasecmp(reason->str, "unknown") ||

    
   
2413
					sip_reason_str_to_code(reason->str) != AST_REDIRECTING_REASON_UNKNOWN) {

    
   
2414
				*table_lookup = TRUE;

    
   
2415
			} else {

    
   
2416
				*table_lookup = FALSE;

    
   
2417
			}

    
   
2418
		}

    
   
2419
		return reason->str;

    
   
2420
	}

    
   
2421

   

    
   
2422
	if (table_lookup) {

    
   
2423
		*table_lookup = TRUE;

    
   
2424
	}

    
   
2425

   
2307
	if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2426
	if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2308
		return sip_reason_table[code].text;
2427
		return sip_reason_table[code].text;
2309
	}
2428
	}
2310

    
   
2429

   
2311
	return "unknown";
2430
	return "unknown";
2312
}
2431
}
2313

    
   
2432

   
2314
/*!
2433
/*!
2315
 * \brief generic function for determining if a correct transport is being
2434
 * \brief generic function for determining if a correct transport is being
2316
 * used to contact a peer
2435
 * used to contact a peer
2317
 *
2436
 *
2318
 * this is done as a macro so that the "tmpl" var can be passed either a
2437
 * this is done as a macro so that the "tmpl" var can be passed either a
2319
 * sip_request or a sip_peer
2438
 * sip_request or a sip_peer
2320
 */
2439
 */
2321
#define check_request_transport(peer, tmpl) ({ \
2440
#define check_request_transport(peer, tmpl) ({ \
2322
	int ret = 0; \
2441
	int ret = 0; \
2323
	if (peer->socket.type == tmpl->socket.type) \
2442
	if (peer->socket.type == tmpl->socket.type) \
2324
		; \
2443
		; \
2325
	else if (!(peer->transports & tmpl->socket.type)) {\
2444
	else if (!(peer->transports & tmpl->socket.type)) {\
2326
		ast_log(LOG_ERROR, \
2445
		ast_log(LOG_ERROR, \
2327
			"'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
2446
			"'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
2328
			sip_get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
2447
			sip_get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
2329
			); \
2448
			); \
2330
		ret = 1; \
2449
		ret = 1; \
2331
	} else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
2450
	} else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
2332
		ast_log(LOG_WARNING, \
2451
		ast_log(LOG_WARNING, \
2333
			"peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
2452
			"peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
2334
			peer->name, sip_get_transport(tmpl->socket.type) \
2453
			peer->name, sip_get_transport(tmpl->socket.type) \
2335
		); \
2454
		); \
2336
	} else { \
2455
	} else { \
2337
		ast_debug(1, \
2456
		ast_debug(1, \
2338
			"peer '%s' has contacted us over %s even though we prefer %s.\n", \
2457
			"peer '%s' has contacted us over %s even though we prefer %s.\n", \
2339
			peer->name, sip_get_transport(tmpl->socket.type), sip_get_transport(peer->socket.type) \
2458
			peer->name, sip_get_transport(tmpl->socket.type), sip_get_transport(peer->socket.type) \
2340
		); \
2459
		); \
2341
	}\
2460
	}\
2342
	(ret); \
2461
	(ret); \
2343
})
2462
})
2344

    
   
2463

   
2345
/*! \brief
2464
/*! \brief
2346
 * duplicate a list of channel variables, \return the copy.
2465
 * duplicate a list of channel variables, \return the copy.
2347
 */
2466
 */
2348
static struct ast_variable *copy_vars(struct ast_variable *src)
2467
static struct ast_variable *copy_vars(struct ast_variable *src)
2349
{
2468
{
2350
	struct ast_variable *res = NULL, *tmp, *v = NULL;
2469
	struct ast_variable *res = NULL, *tmp, *v = NULL;
2351

    
   
2470

   
2352
	for (v = src ; v ; v = v->next) {
2471
	for (v = src ; v ; v = v->next) {
2353
		if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2472
		if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2354
			tmp->next = res;
2473
			tmp->next = res;
2355
			res = tmp;
2474
			res = tmp;
2356
		}
2475
		}
2357
	}
2476
	}
2358
	return res;
2477
	return res;
2359
}
2478
}
2360

    
   
2479

   
2361
static void tcptls_packet_destructor(void *obj)
2480
static void tcptls_packet_destructor(void *obj)
2362
{
2481
{
2363
	struct tcptls_packet *packet = obj;
2482
	struct tcptls_packet *packet = obj;
2364

    
   
2483

   
2365
	ast_free(packet->data);
2484
	ast_free(packet->data);
2366
}
2485
}
2367

    
   
2486

   
2368
static void sip_tcptls_client_args_destructor(void *obj)
2487
static void sip_tcptls_client_args_destructor(void *obj)
2369
{
2488
{
2370
	struct ast_tcptls_session_args *args = obj;
2489
	struct ast_tcptls_session_args *args = obj;
2371
	if (args->tls_cfg) {
2490
	if (args->tls_cfg) {
2372
		ast_free(args->tls_cfg->certfile);
2491
		ast_free(args->tls_cfg->certfile);
2373
		ast_free(args->tls_cfg->pvtfile);
2492
		ast_free(args->tls_cfg->pvtfile);
2374
		ast_free(args->tls_cfg->cipher);
2493
		ast_free(args->tls_cfg->cipher);
2375
		ast_free(args->tls_cfg->cafile);
2494
		ast_free(args->tls_cfg->cafile);
2376
		ast_free(args->tls_cfg->capath);
2495
		ast_free(args->tls_cfg->capath);

    
   
2496

   

    
   
2497
		ast_ssl_teardown(args->tls_cfg);
2377
	}
2498
	}
2378
	ast_free(args->tls_cfg);
2499
	ast_free(args->tls_cfg);
2379
	ast_free((char *) args->name);
2500
	ast_free((char *) args->name);
2380
}
2501
}
2381

    
   
2502

   
2382
static void sip_threadinfo_destructor(void *obj)
2503
static void sip_threadinfo_destructor(void *obj)
2383
{
2504
{
2384
	struct sip_threadinfo *th = obj;
2505
	struct sip_threadinfo *th = obj;
2385
	struct tcptls_packet *packet;
2506
	struct tcptls_packet *packet;
2386

    
   
2507

   
2387
	if (th->alert_pipe[1] > -1) {
2508
	if (th->alert_pipe[1] > -1) {
2388
		close(th->alert_pipe[0]);
2509
		close(th->alert_pipe[0]);
2389
	}
2510
	}
2390
	if (th->alert_pipe[1] > -1) {
2511
	if (th->alert_pipe[1] > -1) {
2391
		close(th->alert_pipe[1]);
2512
		close(th->alert_pipe[1]);
2392
	}
2513
	}
2393
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2514
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2394

    
   
2515

   
2395
	while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2516
	while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2396
		ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
2517
		ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
2397
	}
2518
	}
2398

    
   
2519

   
2399
	if (th->tcptls_session) {
2520
	if (th->tcptls_session) {
2400
		ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
2521
		ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
2401
	}
2522
	}
2402
}
2523
}
2403

    
   
2524

   
2404
/*! \brief creates a sip_threadinfo object and links it into the threadt table. */
2525
/*! \brief creates a sip_threadinfo object and links it into the threadt table. */
2405
static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
2526
static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
2406
{
2527
{
2407
	struct sip_threadinfo *th;
2528
	struct sip_threadinfo *th;
2408

    
   
2529

   
2409
	if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
2530
	if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
2410
		return NULL;
2531
		return NULL;
2411
	}
2532
	}
2412

    
   
2533

   
2413
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2534
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2414

    
   
2535

   
2415
	if (pipe(th->alert_pipe) == -1) {
2536
	if (pipe(th->alert_pipe) == -1) {
2416
		ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
2537
		ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
2417
		ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
2538
		ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
2418
		return NULL;
2539
		return NULL;
2419
	}
2540
	}
2420
	ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
2541
	ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
2421
	th->tcptls_session = tcptls_session;
2542
	th->tcptls_session = tcptls_session;
2422
	th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
2543
	th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
2423
	ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2544
	ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2424
	ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
2545
	ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
2425
	return th;
2546
	return th;
2426
}
2547
}
2427

    
   
2548

   
2428
/*! \brief used to indicate to a tcptls thread that data is ready to be written */
2549
/*! \brief used to indicate to a tcptls thread that data is ready to be written */
2429
static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
2550
static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
2430
{
2551
{
2431
	int res = len;
2552
	int res = len;
2432
	struct sip_threadinfo *th = NULL;
2553
	struct sip_threadinfo *th = NULL;
2433
	struct tcptls_packet *packet = NULL;
2554
	struct tcptls_packet *packet = NULL;
2434
	struct sip_threadinfo tmp = {
2555
	struct sip_threadinfo tmp = {
2435
		.tcptls_session = tcptls_session,
2556
		.tcptls_session = tcptls_session,
2436
	};
2557
	};
2437
	enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2558
	enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2438

    
   
2559

   
2439
	if (!tcptls_session) {
2560
	if (!tcptls_session) {
2440
		return XMIT_ERROR;
2561
		return XMIT_ERROR;
2441
	}
2562
	}
2442

    
   
2563

   
2443
	ao2_lock(tcptls_session);
2564
	ao2_lock(tcptls_session);
2444

    
   
2565

   
2445
	if ((tcptls_session->fd == -1) ||
2566
	if ((tcptls_session->fd == -1) ||
2446
		!(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
2567
		!(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
2447
		!(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2568
		!(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2448
		!(packet->data = ast_str_create(len))) {
2569
		!(packet->data = ast_str_create(len))) {
2449
		goto tcptls_write_setup_error;
2570
		goto tcptls_write_setup_error;
2450
	}
2571
	}
2451

    
   
2572

   
2452
	/* goto tcptls_write_error should _NOT_ be used beyond this point */
2573
	/* goto tcptls_write_error should _NOT_ be used beyond this point */
2453
	ast_str_set(&packet->data, 0, "%s", (char *) buf);
2574
	ast_str_set(&packet->data, 0, "%s", (char *) buf);
2454
	packet->len = len;
2575
	packet->len = len;
2455

    
   
2576

   
2456
	/* alert tcptls thread handler that there is a packet to be sent.
2577
	/* alert tcptls thread handler that there is a packet to be sent.
2457
	 * must lock the thread info object to guarantee control of the
2578
	 * must lock the thread info object to guarantee control of the
2458
	 * packet queue */
2579
	 * packet queue */
2459
	ao2_lock(th);
2580
	ao2_lock(th);
2460
	if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2581
	if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2461
		ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
2582
		ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
2462
		ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
2583
		ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
2463
		packet = NULL;
2584
		packet = NULL;
2464
		res = XMIT_ERROR;
2585
		res = XMIT_ERROR;
2465
	} else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
2586
	} else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
2466
		AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2587
		AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2467
	}
2588
	}
2468
	ao2_unlock(th);
2589
	ao2_unlock(th);
2469

    
   
2590

   
2470
	ao2_unlock(tcptls_session);
2591
	ao2_unlock(tcptls_session);
2471
	ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
2592
	ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
2472
	return res;
2593
	return res;
2473

    
   
2594

   
2474
tcptls_write_setup_error:
2595
tcptls_write_setup_error:
2475
	if (th) {
2596
	if (th) {
2476
		ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
2597
		ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
2477
	}
2598
	}
2478
	if (packet) {
2599
	if (packet) {
2479
		ao2_t_ref(packet, -1, "could not allocate packet's data");
2600
		ao2_t_ref(packet, -1, "could not allocate packet's data");
2480
	}
2601
	}
2481
	ao2_unlock(tcptls_session);
2602
	ao2_unlock(tcptls_session);
2482

    
   
2603

   
2483
	return XMIT_ERROR;
2604
	return XMIT_ERROR;
2484
}
2605
}
2485

    
   
2606

   
2486
/*! \brief SIP TCP connection handler */
2607
/*! \brief SIP TCP connection handler */
2487
static void *sip_tcp_worker_fn(void *data)
2608
static void *sip_tcp_worker_fn(void *data)
2488
{
2609
{
2489
	struct ast_tcptls_session_instance *tcptls_session = data;
2610
	struct ast_tcptls_session_instance *tcptls_session = data;
2490

    
   
2611

   
2491
	return _sip_tcp_helper_thread(tcptls_session);
2612
	return _sip_tcp_helper_thread(tcptls_session);
2492
}
2613
}
2493

    
   
2614

   
2494
/*! \brief Check if the authtimeout has expired.
2615
/*! \brief SIP WebSocket connection handler */
2495
 * \param start the time when the session started
2616
static void sip_websocket_callback(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
2496
 *

   
2497
 * \retval 0 the timeout has expired

   
2498
 * \retval -1 error

   
2499
 * \return the number of milliseconds until the timeout will expire

   
2500
 */

   
2501
static int sip_check_authtimeout(time_t start)

   
2502
{
2617
{
2503
	int timeout;
2618
	int res;
2504
	time_t now;

   
2505
	if(time(&now) == -1) {

   
2506
		ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));

   
2507
		return -1;

   
2508
	}

   
2509

    
   

   
2510
	timeout = (authtimeout - (now - start)) * 1000;

   
2511
	if (timeout < 0) {

   
2512
		/* we have timed out */

   
2513
		return 0;

   
2514
	}

   
2515

    
   

   
2516
	return timeout;

   
2517
}

   
2518

    
   

   
2519
/*! \brief SIP TCP thread management function

   
2520
	This function reads from the socket, parses the packet into a request

   
2521
*/

   
2522
static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)

   
2523
{

   
2524
	int res, cl, timeout = -1, authenticated = 0, flags, after_poll = 0, need_poll = 1;

   
2525
	time_t start;
Moved to 3041

   
2526
	struct sip_request req = { 0, } , reqcpy = { 0, };
Moved to 3042

   
2527
	struct sip_threadinfo *me = NULL;
Moved to 3043

   
2528
	char buf[1024] = "";
Moved to 3044

   
2529
	struct pollfd fds[2] = { { 0 }, { 0 }, };
Moved to 3045

   
2530
	struct ast_tcptls_session_args *ca = NULL;
Moved to 3046

   
2531

    
   

   
2532
	/* If this is a server session, then the connection has already been

   
2533
	 * setup. Check if the authlimit has been reached and if not create the

   
2534
	 * threadinfo object so we can access this thread for writing.

   
2535
	 *

   
2536
	 * if this is a client connection more work must be done.

   
2537
	 * 1. We own the parent session args for a client connection.  This pointer needs

   
2538
	 *    to be held on to so we can decrement it's ref count on thread destruction.

   
2539
	 * 2. The threadinfo object was created before this thread was launched, however

   
2540
	 *    it must be found within the threadt table.

   
2541
	 * 3. Last, the tcptls_session must be started.

   
2542
	 */

   
2543
	if (!tcptls_session->client) {

   
2544
		if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {

   
2545
			/* unauth_sessions is decremented in the cleanup code */

   
2546
			goto cleanup;

   
2547
		}

   
2548

    
   

   
2549
		if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {

   
2550
			ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));

   
2551
			goto cleanup;

   
2552
		}

   
2553

    
   

   
2554
		flags |= O_NONBLOCK;

   
2555
		if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {

   
2556
			ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));

   
2557
			goto cleanup;

   
2558
		}

   
2559

    
   

   
2560
		if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {

   
2561
			goto cleanup;

   
2562
		}

   
2563
		ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");

   
2564
	} else {

   
2565
		struct sip_threadinfo tmp = {

   
2566
			.tcptls_session = tcptls_session,

   
2567
		};

   
2568

    
   

   
2569
		if ((!(ca = tcptls_session->parent)) ||

   
2570
			(!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||

   
2571
			(!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {

   
2572
			goto cleanup;

   
2573
		}

   
2574
	}

   
2575

    
   

   
2576
	flags = 1;

   
2577
	if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {

   
2578
		ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));

   
2579
		goto cleanup;

   
2580
	}

   
2581

    
   

   
2582
	me->threadid = pthread_self();
Moved to 3098

   
2583
	ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
Moved to 3099

   
2584

    
   

   
2585
	/* set up pollfd to watch for reads on both the socket and the alert_pipe */
Moved to 3101

   
2586
	fds[0].fd = tcptls_session->fd;
Moved to 3102

   
2587
	fds[1].fd = me->alert_pipe[0];
Moved to 3103

   
2588
	fds[0].events = fds[1].events = POLLIN | POLLPRI;
Moved to 3104

   
2589

    
   

   
2590
	if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {

   
2591
		goto cleanup;

   
2592
	}

   
2593
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {

   
2594
		goto cleanup;

   
2595
	}

   
2596

    
   

   
2597
	if(time(&start) == -1) {

   
2598
		ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));

   
2599
		goto cleanup;

   
2600
	}

   
2601

    
   

   
2602
	for (;;) {
Moved to 3118

   
2603
		struct ast_str *str_save;
Moved to 3119

   
2604

    
   

   
2605
		if (!tcptls_session->client && req.authenticated && !authenticated) {

   
2606
			authenticated = 1;

   
2607
			ast_atomic_fetchadd_int(&unauth_sessions, -1);

   
2608
		}

   
2609

    
   

   
2610
		/* calculate the timeout for unauthenticated server sessions */

   
2611
		if (!tcptls_session->client && !authenticated ) {

   
2612
			if ((timeout = sip_check_authtimeout(start)) < 0) {

   
2613
				goto cleanup;

   
2614
			}

   
2615

    
   
2619

   
2616
			if (timeout == 0) {
2620
	if (ast_websocket_set_nonblock(session)) {
2617
				ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
2621
		goto end;
2618
				goto cleanup;

   
2619
			}

   
2620
		} else {

   
2621
			timeout = -1;

   
2622
		}
2622
	}
2623

    
   
2623

   
2624
		res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
2624
	while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {
2625
		if (res < 0) {
2625
		char *payload;
2626
			ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
2626
		uint64_t payload_len;
2627
			goto cleanup;
2627
		enum ast_websocket_opcode opcode;
2628
		} else if (res == 0) {
2628
		int fragmented;
2629
			/* timeout */

   
2630
			ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");

   
2631
			goto cleanup;

   
2632
		}

   
2633

    
   

   
2634
		/* handle the socket event, check for both reads from the socket fd,

   
2635
		 * and writes from alert_pipe fd */

   
2636
		if (fds[0].revents) { /* there is data on the socket to be read */

   
2637
			after_poll = 1;

   
2638

    
   

   
2639
			fds[0].revents = 0;

   
2640

    
   

   
2641
			/* clear request structure */
Moved to 3159

   
2642
			str_save = req.data;
Moved to 3160

   
2643
			memset(&req, 0, sizeof(req));
Moved to 3161

   
2644
			req.data = str_save;
Moved to 3162

   
2645
			ast_str_reset(req.data);
Moved to 3163

   
2646

    
   

   
2647
			str_save = reqcpy.data;
Moved to 3165

   
2648
			memset(&reqcpy, 0, sizeof(reqcpy));
Moved to 3166

   
2649
			reqcpy.data = str_save;
Moved to 3167

   
2650
			ast_str_reset(reqcpy.data);
Moved to 3168

   
2651

    
   

   
2652
			memset(buf, 0, sizeof(buf));

   
2653

    
   
2629

   
2654
			if (tcptls_session->ssl) {
2630
		if (ast_websocket_read(session, &payload, &payload_len, &opcode, &fragmented)) {
2655
				set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
2631
			/* We err on the side of caution and terminate the session if any error occurs */
2656
				req.socket.port = htons(ourport_tls);
2632
			break;
2657
			} else {

   
2658
				set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);

   
2659
				req.socket.port = htons(ourport_tcp);

   
2660
			}
2633
		}
2661
			req.socket.fd = tcptls_session->fd;

   
2662

    
   
2634

   
2663
			/* Read in headers one line at a time */
2635
		if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
2664
			while (ast_str_strlen(req.data) < 4 || strncmp(REQ_OFFSET_TO_STR(&req, data->used - 4), "\r\n\r\n", 4)) {
2636
			struct sip_request req = { 0, };
2665
				if (!tcptls_session->client && !authenticated ) {

   
2666
					if ((timeout = sip_check_authtimeout(start)) < 0) {

   
2667
						goto cleanup;

   
2668
					}

   
2669

    
   
2637

   
2670
					if (timeout == 0) {
2638
			if (!(req.data = ast_str_create(payload_len))) {
2671
						ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
2639
				goto end;
2672
						goto cleanup;
2640
			}
2673
					}
2641

   
2674
				} else {
2642
			if (ast_str_set(&req.data, -1, "%s", payload) == AST_DYNSTR_BUILD_FAILED) {
2675
					timeout = -1;
2643
				deinit_req(&req);

    
   
2644
				goto end;

    
   
2645
			}

    
   
2646

   

    
   
2647
			req.socket.fd = ast_websocket_fd(session);

    
   
2648
			set_socket_transport(&req.socket, ast_websocket_is_secure(session) ? SIP_TRANSPORT_WSS : SIP_TRANSPORT_WS);

    
   
2649
			req.socket.ws_session = session;

    
   
2650

   

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

    
   
2652
			deinit_req(&req);

    
   
2653

   

    
   
2654
		} else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {

    
   
2655
			break;

    
   
2656
		}

    
   
2657
	}

    
   
2658

   

    
   
2659
end:

    
   
2660
	ast_websocket_unref(session);

    
   
2661
}

    
   
2662

   

    
   
2663
/*! \brief Check if the authtimeout has expired.

    
   
2664
 * \param start the time when the session started
Moved from 2496

    
   
2665
 *
Moved from 2497

    
   
2666
 * \retval 0 the timeout has expired
Moved from 2498

    
   
2667
 * \retval -1 error
Moved from 2499

    
   
2668
 * \return the number of milliseconds until the timeout will expire
Moved from 2500

    
   
2669
 */
Moved from 2501

    
   
2670
static int sip_check_authtimeout(time_t start)

    
   
2671
{

    
   
2672
	int timeout;
Moved from 2504

    
   
2673
	time_t now;
Moved from 2505

    
   
2674
	if(time(&now) == -1) {
Moved from 2506

    
   
2675
		ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
Moved from 2507

    
   
2676
		return -1;
Moved from 2508

    
   
2677
	}

    
   
2678

   
Moved from 2510

    
   
2679
	timeout = (authtimeout - (now - start)) * 1000;
Moved from 2511

    
   
2680
	if (timeout < 0) {
Moved from 2512

    
   
2681
		/* we have timed out */
Moved from 2513

    
   
2682
		return 0;
Moved from 2514

    
   
2683
	}

    
   
2684

   
Moved from 2516

    
   
2685
	return timeout;
Moved from 2517

    
   
2686
}

    
   
2687

   

    
   
2688
/*!

    
   
2689
 * \brief Read a SIP request or response from a TLS connection

    
   
2690
 *

    
   
2691
 * Because TLS operations are hidden from view via a FILE handle, the

    
   
2692
 * logic for reading data is a bit complex, and we have to make periodic

    
   
2693
 * checks to be sure we aren't taking too long to perform the necessary

    
   
2694
 * action.

    
   
2695
 *

    
   
2696
 * \todo XXX This should be altered in the future not to use a FILE pointer

    
   
2697
 *

    
   
2698
 * \param req The request structure to fill in

    
   
2699
 * \param tcptls_session The TLS connection on which the data is being received

    
   
2700
 * \param authenticated A flag indicating whether authentication has occurred yet.

    
   
2701
 *        This is only relevant in a server role.

    
   
2702
 * \param start The time at which we started attempting to read data. Used in

    
   
2703
 *        determining if there has been a timeout.

    
   
2704
 * \param me Thread info. Used as a means of determining if the session needs to be stoppped.

    
   
2705
 * \retval -1 Failed to read data

    
   
2706
 * \retval 0 Succeeded in reading data

    
   
2707
 */

    
   
2708
static int sip_tls_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session, int authenticated, time_t start, struct sip_threadinfo *me)

    
   
2709
{

    
   
2710
	int res, content_length, after_poll = 1, need_poll = 1;

    
   
2711
	struct sip_request reqcpy = { 0, };

    
   
2712
	char buf[1024] = "";

    
   
2713
	int timeout = -1;

    
   
2714

   

    
   
2715
	/* Read in headers one line at a time */

    
   
2716
	while (ast_str_strlen(req->data) < 4 || strncmp(REQ_OFFSET_TO_STR(req, data->used - 4), "\r\n\r\n", 4)) {

    
   
2717
		if (!tcptls_session->client && !authenticated) {

    
   
2718
			if ((timeout = sip_check_authtimeout(start)) < 0) {

    
   
2719
				ast_debug(2, "SIP SSL server failed to determine authentication timeout\n");
Moved from 2507

    
   
2720
				return -1;
Moved from 2508

    
   
2721
			}

    
   
2722

   

    
   
2723
			if (timeout == 0) {

    
   
2724
				ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");

    
   
2725
				return -1;

    
   
2726
			}

    
   
2727
		} else {

    
   
2728
			timeout = -1;
2676
				}
2729
		}
2677

    
   
2730

   
2678
				/* special polling behavior is required for TLS
2731
		/* special polling behavior is required for TLS
2679
				 * sockets because of the buffering done in the
2732
		 * sockets because of the buffering done in the
2680
				 * TLS layer */
2733
		 * TLS layer */
2681
				if (!tcptls_session->ssl || need_poll) {
2734
		if (need_poll) {
2682
					need_poll = 0;
2735
			need_poll = 0;
2683
					after_poll = 1;
2736
			after_poll = 1;
2684
					res = ast_wait_for_input(tcptls_session->fd, timeout);
2737
			res = ast_wait_for_input(tcptls_session->fd, timeout);
2685
					if (res < 0) {
2738
			if (res < 0) {
2686
						ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
2739
				ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
2687
						goto cleanup;
2740
				return -1;
2688
					} else if (res == 0) {
2741
			} else if (res == 0) {
2689
						/* timeout */
2742
				/* timeout */
2690
						ast_debug(2, "SIP TCP server timed out\n");
2743
				ast_debug(2, "SIP TCP server timed out\n");
2691
						goto cleanup;
2744
				return -1;
2692
					}
2745
			}
2693
				}
2746
		}
2694

    
   
2747

   
2695
				ao2_lock(tcptls_session);
2748
		ao2_lock(tcptls_session);
2696
				if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2749
		if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2697
					ao2_unlock(tcptls_session);
2750
			ao2_unlock(tcptls_session);
2698
					if (after_poll) {
2751
			if (after_poll) {
2699
						goto cleanup;
2752
				return -1;
2700
					} else {
2753
			} else {
2701
						need_poll = 1;
2754
				need_poll = 1;
2702
						continue;
2755
				continue;
2703
					}
2756
			}
2704
				}
2757
		}
2705
				ao2_unlock(tcptls_session);
2758
		ao2_unlock(tcptls_session);
2706
				after_poll = 0;
2759
		after_poll = 0;
2707
				if (me->stop) {
2760
		if (me->stop) {
2708
					 goto cleanup;
2761
			return -1;
2709
				}
2762
		}
2710
				ast_str_append(&req.data, 0, "%s", buf);
2763
		ast_str_append(&req->data, 0, "%s", buf);
2711
			}
2764
	}
2712
			copy_request(&reqcpy, &req);
2765
	copy_request(&reqcpy, req);
2713
			parse_request(&reqcpy);
2766
	parse_request(&reqcpy);
2714
			/* In order to know how much to read, we need the content-length header */
2767
	/* In order to know how much to read, we need the content-length header */
2715
			if (sscanf(sip_get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
2768
	if (sscanf(sip_get_header(&reqcpy, "Content-Length"), "%30d", &content_length)) {
2716
				while (cl > 0) {
2769
		while (content_length > 0) {
2717
					size_t bytes_read;
2770
			size_t bytes_read;
2718
					if (!tcptls_session->client && !authenticated ) {
2771
			if (!tcptls_session->client && !authenticated) {
2719
						if ((timeout = sip_check_authtimeout(start)) < 0) {
2772
				if ((timeout = sip_check_authtimeout(start)) < 0) {
2720
							goto cleanup;
2773
					return -1;
2721
						}
2774
				}
2722

    
   
2775

   
2723
						if (timeout == 0) {
2776
				if (timeout == 0) {
2724
							ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
2777
					ast_debug(2, "SIP SSL server timed out\n");
2725
							goto cleanup;
2778
					return -1;
2726
						}
2779
				}
2727
					} else {
2780
			} else {
2728
						timeout = -1;
2781
				timeout = -1;
2729
					}
2782
			}
2730

    
   
2783

   
2731
					if (!tcptls_session->ssl || need_poll) {
2784
			if (need_poll) {
2732
						need_poll = 0;
2785
				need_poll = 0;
2733
						after_poll = 1;
2786
				after_poll = 1;
2734
						res = ast_wait_for_input(tcptls_session->fd, timeout);
2787
				res = ast_wait_for_input(tcptls_session->fd, timeout);
2735
						if (res < 0) {
2788
				if (res < 0) {
2736
							ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
2789
					ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
2737
							goto cleanup;
2790
					return -1;
2738
						} else if (res == 0) {
2791
				} else if (res == 0) {
2739
							/* timeout */
2792
					/* timeout */
2740
							ast_debug(2, "SIP TCP server timed out\n");
2793
					ast_debug(2, "SIP TCP server timed out\n");
2741
							goto cleanup;
2794
					return -1;
2742
						}
2795
				}
2743
					}
2796
			}
2744

    
   
2797

   
2745
					ao2_lock(tcptls_session);
2798
			ao2_lock(tcptls_session);
2746
					if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
2799
			if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, content_length), tcptls_session->f))) {
2747
						ao2_unlock(tcptls_session);
2800
				ao2_unlock(tcptls_session);
2748
						if (after_poll) {
2801
				if (after_poll) {
2749
							goto cleanup;
2802
					return -1;
2750
						} else {
2803
				} else {
2751
							need_poll = 1;
2804
					need_poll = 1;
2752
							continue;
2805
					continue;
2753
						}
2806
				}
2754
					}
2807
			}
2755
					buf[bytes_read] = '\0';
2808
			buf[bytes_read] = '\0';
2756
					ao2_unlock(tcptls_session);
2809
			ao2_unlock(tcptls_session);
2757
					after_poll = 0;
2810
			after_poll = 0;
2758
					if (me->stop) {
2811
			if (me->stop) {
2759
						goto cleanup;
2812
				return -1;
2760
					}
2813
			}
2761
					cl -= strlen(buf);
2814
			content_length -= strlen(buf);
2762
					ast_str_append(&req.data, 0, "%s", buf);
2815
			ast_str_append(&req->data, 0, "%s", buf);
2763
				}
2816
		}
2764
			}
2817
	}
2765
			/*! \todo XXX If there's no Content-Length or if the content-length and what
2818
	/*! \todo XXX If there's no Content-Length or if the content-length and what
2766
					we receive is not the same - we should generate an error */
2819
					we receive is not the same - we should generate an error */
Moved from 2513

    
   
2820
	return 0;
Moved from 2514

    
   
2821
}

    
   
2822

   

    
   
2823
/*!

    
   
2824
 * \brief Indication of a TCP message's integrity

    
   
2825
 */

    
   
2826
enum message_integrity {

    
   
2827
	/*!

    
   
2828
	 * The message has an error in it with

    
   
2829
	 * regards to its Content-Length header

    
   
2830
	 */

    
   
2831
	MESSAGE_INVALID,

    
   
2832
	/*!

    
   
2833
	 * The message is incomplete

    
   
2834
	 */

    
   
2835
	MESSAGE_FRAGMENT,

    
   
2836
	/*!

    
   
2837
	 * The data contains a complete message

    
   
2838
	 * plus a fragment of another.

    
   
2839
	 */

    
   
2840
	MESSAGE_FRAGMENT_COMPLETE,

    
   
2841
	/*!

    
   
2842
	 * The message is complete

    
   
2843
	 */

    
   
2844
	MESSAGE_COMPLETE,

    
   
2845
};

    
   
2846

   

    
   
2847
/*!

    
   
2848
 * \brief

    
   
2849
 * Get the content length from an unparsed SIP message

    
   
2850
 *

    
   
2851
 * \param message The unparsed SIP message headers

    
   
2852
 * \return The value of the Content-Length header or -1 if message is invalid

    
   
2853
 */

    
   
2854
static int read_raw_content_length(const char *message)

    
   
2855
{

    
   
2856
	char *content_length_str;

    
   
2857
	int content_length = -1;

    
   
2858

   

    
   
2859
	struct ast_str *msg_copy;

    
   
2860
	char *msg;

    
   
2861

   

    
   
2862
	/* Using a ast_str because lws2sws takes one of those */

    
   
2863
	if (!(msg_copy = ast_str_create(strlen(message) + 1))) {
Moved from 2507

    
   
2864
		return -1;
Moved from 2508

    
   
2865
	}

    
   
2866
	ast_str_set(&msg_copy, 0, "%s", message);

    
   
2867

   

    
   
2868
	if (sip_cfg.pedanticsipchecking) {

    
   
2869
		lws2sws(msg_copy);

    
   
2870
	}

    
   
2871

   

    
   
2872
	msg = ast_str_buffer(msg_copy);

    
   
2873

   

    
   
2874
	/* Let's find a Content-Length header */

    
   
2875
	if ((content_length_str = strcasestr(msg, "\nContent-Length:"))) {

    
   
2876
		content_length_str += sizeof("\nContent-Length:") - 1;

    
   
2877
	} else if ((content_length_str = strcasestr(msg, "\nl:"))) {

    
   
2878
		content_length_str += sizeof("\nl:") - 1;

    
   
2879
	} else {

    
   
2880
		/* RFC 3261 18.3

    
   
2881
		 * "In the case of stream-oriented transports such as TCP, the Content-

    
   
2882
		 *  Length header field indicates the size of the body.  The Content-

    
   
2883
		 *  Length header field MUST be used with stream oriented transports."

    
   
2884
		 */

    
   
2885
		goto done;

    
   
2886
	}

    
   
2887

   

    
   
2888
	/* Double-check that this is a complete header */

    
   
2889
	if (!strchr(content_length_str, '\n')) {

    
   
2890
		goto done;

    
   
2891
	}

    
   
2892

   

    
   
2893
	if (sscanf(content_length_str, "%30d", &content_length) != 1) {

    
   
2894
		content_length = -1;

    
   
2895
	}

    
   
2896

   

    
   
2897
done:

    
   
2898
	ast_free(msg_copy);

    
   
2899
	return content_length;

    
   
2900
}

    
   
2901

   

    
   
2902
/*!

    
   
2903
 * \brief Check that a message received over TCP is a full message

    
   
2904
 *

    
   
2905
 * This will take the information read in and then determine if

    
   
2906
 * 1) The message is a full SIP request

    
   
2907
 * 2) The message is a partial SIP request

    
   
2908
 * 3) The message contains a full SIP request along with another partial request

    
   
2909
 * \param data The unparsed incoming SIP message.

    
   
2910
 * \param request The resulting request with extra fragments removed.

    
   
2911
 * \param overflow If the message contains more than a full request, this is the remainder of the message

    
   
2912
 * \return The resulting integrity of the message

    
   
2913
 */

    
   
2914
static enum message_integrity check_message_integrity(struct ast_str **request, struct ast_str **overflow)

    
   
2915
{

    
   
2916
	char *message = ast_str_buffer(*request);

    
   
2917
	char *body;

    
   
2918
	int content_length;

    
   
2919
	int message_len = ast_str_strlen(*request);

    
   
2920
	int body_len;

    
   
2921

   

    
   
2922
	/* Important pieces to search for in a SIP request are \r\n\r\n. This

    
   
2923
	 * marks either

    
   
2924
	 * 1) The division between the headers and body

    
   
2925
	 * 2) The end of the SIP request

    
   
2926
	 */

    
   
2927
	body = strstr(message, "\r\n\r\n");

    
   
2928
	if (!body) {

    
   
2929
		/* This is clearly a partial message since we haven't reached an end

    
   
2930
		 * yet.

    
   
2931
		 */

    
   
2932
		return MESSAGE_FRAGMENT;

    
   
2933
	}

    
   
2934
	body += sizeof("\r\n\r\n") - 1;

    
   
2935
	body_len = message_len - (body - message);

    
   
2936

   

    
   
2937
	body[-1] = '\0';

    
   
2938
	content_length = read_raw_content_length(message);

    
   
2939
	body[-1] = '\n';

    
   
2940

   

    
   
2941
	if (content_length < 0) {

    
   
2942
		return MESSAGE_INVALID;

    
   
2943
	} else if (content_length == 0) {

    
   
2944
		/* We've definitely received an entire message. We need

    
   
2945
		 * to check if there's also a fragment of another message

    
   
2946
		 * in addition.

    
   
2947
		 */

    
   
2948
		if (body_len == 0) {

    
   
2949
			return MESSAGE_COMPLETE;

    
   
2950
		} else {

    
   
2951
			ast_str_append(overflow, 0, "%s", body);

    
   
2952
			ast_str_truncate(*request, message_len - body_len);

    
   
2953
			return MESSAGE_FRAGMENT_COMPLETE;

    
   
2954
		}

    
   
2955
	}

    
   
2956
	/* Positive content length. Let's see what sort of

    
   
2957
	 * message body we're dealing with.

    
   
2958
	 */

    
   
2959
	if (body_len < content_length) {

    
   
2960
		/* We don't have the full message body yet */

    
   
2961
		return MESSAGE_FRAGMENT;

    
   
2962
	} else if (body_len > content_length) {

    
   
2963
		/* We have the full message plus a fragment of a further

    
   
2964
		 * message

    
   
2965
		 */

    
   
2966
		ast_str_append(overflow, 0, "%s", body + content_length);

    
   
2967
		ast_str_truncate(*request, message_len - (body_len - content_length));

    
   
2968
		return MESSAGE_FRAGMENT_COMPLETE;

    
   
2969
	} else {

    
   
2970
		/* Yay! Full message with no extra content */

    
   
2971
		return MESSAGE_COMPLETE;

    
   
2972
	}

    
   
2973
}

    
   
2974

   

    
   
2975
/*!

    
   
2976
 * \brief Read SIP request or response from a TCP connection

    
   
2977
 *

    
   
2978
 * \param req The request structure to be filled in

    
   
2979
 * \param tcptls_session The TCP connection from which to read

    
   
2980
 * \retval -1 Failed to read data

    
   
2981
 * \retval 0 Successfully read data

    
   
2982
 */

    
   
2983
static int sip_tcp_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session,

    
   
2984
		int authenticated, time_t start)

    
   
2985
{

    
   
2986
	enum message_integrity message_integrity = MESSAGE_FRAGMENT;

    
   
2987

   

    
   
2988
	while (message_integrity == MESSAGE_FRAGMENT) {

    
   
2989
		if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {

    
   
2990
			char readbuf[4097];

    
   
2991
			int timeout;

    
   
2992
			int res;

    
   
2993
			if (!tcptls_session->client && !authenticated) {

    
   
2994
				if ((timeout = sip_check_authtimeout(start)) < 0) {

    
   
2995
					return -1;

    
   
2996
				}

    
   
2997

   

    
   
2998
				if (timeout == 0) {

    
   
2999
					ast_debug(2, "SIP TCP server timed out\n");
Moved from 2507

    
   
3000
					return -1;
Moved from 2508

    
   
3001
				}

    
   
3002
			} else {

    
   
3003
				timeout = -1;

    
   
3004
			}

    
   
3005
			res = ast_wait_for_input(tcptls_session->fd, timeout);

    
   
3006
			if (res < 0) {

    
   
3007
				ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);

    
   
3008
				return -1;

    
   
3009
			} else if (res == 0) {

    
   
3010
				ast_debug(2, "SIP TCP server timed out\n");
Moved from 2507

    
   
3011
				return -1;
Moved from 2508

    
   
3012
			}

    
   
3013

   

    
   
3014
			res = recv(tcptls_session->fd, readbuf, sizeof(readbuf) - 1, 0);

    
   
3015
			if (res < 0) {

    
   
3016
				ast_debug(2, "SIP TCP server error when receiving data\n");

    
   
3017
				return -1;

    
   
3018
			} else if (res == 0) {

    
   
3019
				ast_debug(2, "SIP TCP server has shut down\n");
Moved from 2507

    
   
3020
				return -1;
Moved from 2508

    
   
3021
			}

    
   
3022
			readbuf[res] = '\0';

    
   
3023
			ast_str_append(&req->data, 0, "%s", readbuf);

    
   
3024
		} else {

    
   
3025
			ast_str_append(&req->data, 0, "%s", ast_str_buffer(tcptls_session->overflow_buf));

    
   
3026
			ast_str_reset(tcptls_session->overflow_buf);

    
   
3027
		}

    
   
3028

   

    
   
3029
		message_integrity = check_message_integrity(&req->data, &tcptls_session->overflow_buf);

    
   
3030
	}

    
   
3031

   
Moved from 2513

    
   
3032
	return 0;
Moved from 2514

    
   
3033
}

    
   
3034

   
Moved from 2519

    
   
3035
/*! \brief SIP TCP thread management function
Moved from 2520

    
   
3036
	This function reads from the socket, parses the packet into a request
Moved from 2521

    
   
3037
*/
Moved from 2522

    
   
3038
static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
Moved from 2523

    
   
3039
{

    
   
3040
	int res, timeout = -1, authenticated = 0, flags;
Moved from 2525

    
   
3041
	time_t start;
Moved from 2526

    
   
3042
	struct sip_request req = { 0, } , reqcpy = { 0, };
Moved from 2527

    
   
3043
	struct sip_threadinfo *me = NULL;
Moved from 2528

    
   
3044
	char buf[1024] = "";
Moved from 2529

    
   
3045
	struct pollfd fds[2] = { { 0 }, { 0 }, };
Moved from 2530

    
   
3046
	struct ast_tcptls_session_args *ca = NULL;

    
   
3047

   
Moved from 2532

    
   
3048
	/* If this is a server session, then the connection has already been
Moved from 2533

    
   
3049
	 * setup. Check if the authlimit has been reached and if not create the
Moved from 2534

    
   
3050
	 * threadinfo object so we can access this thread for writing.
Moved from 2535

    
   
3051
	 *
Moved from 2536

    
   
3052
	 * if this is a client connection more work must be done.
Moved from 2537

    
   
3053
	 * 1. We own the parent session args for a client connection.  This pointer needs
Moved from 2538

    
   
3054
	 *    to be held on to so we can decrement it's ref count on thread destruction.
Moved from 2539

    
   
3055
	 * 2. The threadinfo object was created before this thread was launched, however
Moved from 2540

    
   
3056
	 *    it must be found within the threadt table.
Moved from 2541

    
   
3057
	 * 3. Last, the tcptls_session must be started.
Moved from 2542

    
   
3058
	 */
Moved from 2543

    
   
3059
	if (!tcptls_session->client) {
Moved from 2544

    
   
3060
		if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
Moved from 2545

    
   
3061
			/* unauth_sessions is decremented in the cleanup code */
Moved from 2546

    
   
3062
			goto cleanup;
Moved from 2547

    
   
3063
		}

    
   
3064

   
Moved from 2549

    
   
3065
		if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
Moved from 2550

    
   
3066
			ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
Moved from 2551

    
   
3067
			goto cleanup;
Moved from 2552

    
   
3068
		}

    
   
3069

   
Moved from 2554

    
   
3070
		flags |= O_NONBLOCK;
Moved from 2555

    
   
3071
		if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
Moved from 2556

    
   
3072
			ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
Moved from 2557

    
   
3073
			goto cleanup;
Moved from 2558

    
   
3074
		}

    
   
3075

   
Moved from 2560

    
   
3076
		if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
Moved from 2561

    
   
3077
			goto cleanup;
Moved from 2562

    
   
3078
		}
Moved from 2563

    
   
3079
		ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
Moved from 2564

    
   
3080
	} else {
Moved from 2565

    
   
3081
		struct sip_threadinfo tmp = {
Moved from 2566

    
   
3082
			.tcptls_session = tcptls_session,
Moved from 2567

    
   
3083
		};

    
   
3084

   
Moved from 2569

    
   
3085
		if ((!(ca = tcptls_session->parent)) ||
Moved from 2570

    
   
3086
			(!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
Moved from 2571

    
   
3087
			(!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
Moved from 2572

    
   
3088
			goto cleanup;
Moved from 2573

    
   
3089
		}
Moved from 2574

    
   
3090
	}

    
   
3091

   
Moved from 2576

    
   
3092
	flags = 1;
Moved from 2577

    
   
3093
	if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
Moved from 2578

    
   
3094
		ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
Moved from 2579

    
   
3095
		goto cleanup;
Moved from 2580

    
   
3096
	}

    
   
3097

   
Moved from 2582

    
   
3098
	me->threadid = pthread_self();
Moved from 2583

    
   
3099
	ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");

    
   
3100

   
Moved from 2585

    
   
3101
	/* set up pollfd to watch for reads on both the socket and the alert_pipe */
Moved from 2586

    
   
3102
	fds[0].fd = tcptls_session->fd;
Moved from 2587

    
   
3103
	fds[1].fd = me->alert_pipe[0];
Moved from 2588

    
   
3104
	fds[0].events = fds[1].events = POLLIN | POLLPRI;

    
   
3105

   
Moved from 2590

    
   
3106
	if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
Moved from 2591

    
   
3107
		goto cleanup;
Moved from 2592

    
   
3108
	}
Moved from 2593

    
   
3109
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
Moved from 2594

    
   
3110
		goto cleanup;
Moved from 2595

    
   
3111
	}

    
   
3112

   
Moved from 2597

    
   
3113
	if(time(&start) == -1) {
Moved from 2598

    
   
3114
		ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
Moved from 2599

    
   
3115
		goto cleanup;
Moved from 2600

    
   
3116
	}

    
   
3117

   
Moved from 2602

    
   
3118
	for (;;) {
Moved from 2603

    
   
3119
		struct ast_str *str_save;

    
   
3120

   
Moved from 2605

    
   
3121
		if (!tcptls_session->client && req.authenticated && !authenticated) {
Moved from 2606

    
   
3122
			authenticated = 1;
Moved from 2607

    
   
3123
			ast_atomic_fetchadd_int(&unauth_sessions, -1);
Moved from 2608

    
   
3124
		}

    
   
3125

   
Moved from 2610

    
   
3126
		/* calculate the timeout for unauthenticated server sessions */
Moved from 2611

    
   
3127
		if (!tcptls_session->client && !authenticated ) {
Moved from 2612

    
   
3128
			if ((timeout = sip_check_authtimeout(start)) < 0) {
Moved from 2613

    
   
3129
				goto cleanup;
Moved from 2614

    
   
3130
			}

    
   
3131

   

    
   
3132
			if (timeout == 0) {
Moved from 2630

    
   
3133
				ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
Moved from 2631

    
   
3134
				goto cleanup;
Moved from 2632

    
   
3135
			}

    
   
3136
		} else {

    
   
3137
			timeout = -1;

    
   
3138
		}

    
   
3139

   

    
   
3140
		if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {

    
   
3141
			res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */

    
   
3142
			if (res < 0) {

    
   
3143
				ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);

    
   
3144
				goto cleanup;

    
   
3145
			} else if (res == 0) {
Moved from 2629

    
   
3146
				/* timeout */
Moved from 2630

    
   
3147
				ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
Moved from 2631

    
   
3148
				goto cleanup;
Moved from 2632

    
   
3149
			}

    
   
3150
		}

    
   
3151

   

    
   
3152
		/* 

    
   
3153
		 * handle the socket event, check for both reads from the socket fd or TCP overflow buffer,

    
   
3154
		 * and writes from alert_pipe fd.

    
   
3155
		 */

    
   
3156
		if (fds[0].revents || (ast_str_strlen(tcptls_session->overflow_buf) > 0)) { /* there is data on the socket to be read */

    
   
3157
			fds[0].revents = 0;

    
   
3158

   
Moved from 2641

    
   
3159
			/* clear request structure */
Moved from 2642

    
   
3160
			str_save = req.data;
Moved from 2643

    
   
3161
			memset(&req, 0, sizeof(req));
Moved from 2644

    
   
3162
			req.data = str_save;
Moved from 2645

    
   
3163
			ast_str_reset(req.data);

    
   
3164

   
Moved from 2647

    
   
3165
			str_save = reqcpy.data;
Moved from 2648

    
   
3166
			memset(&reqcpy, 0, sizeof(reqcpy));
Moved from 2649

    
   
3167
			reqcpy.data = str_save;
Moved from 2650

    
   
3168
			ast_str_reset(reqcpy.data);

    
   
3169

   

    
   
3170
			memset(buf, 0, sizeof(buf));

    
   
3171

   

    
   
3172
			if (tcptls_session->ssl) {

    
   
3173
				set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);

    
   
3174
				req.socket.port = htons(ourport_tls);

    
   
3175
			} else {

    
   
3176
				set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);

    
   
3177
				req.socket.port = htons(ourport_tcp);

    
   
3178
			}

    
   
3179
			req.socket.fd = tcptls_session->fd;

    
   
3180
			if (tcptls_session->ssl) {

    
   
3181
				res = sip_tls_read(&req, tcptls_session, authenticated, start, me);

    
   
3182
			} else {

    
   
3183
				res = sip_tcp_read(&req, tcptls_session, authenticated, start);

    
   
3184
			}

    
   
3185

   

    
   
3186
			if (res < 0) {
Moved from 2546

    
   
3187
				goto cleanup;
Moved from 2547

    
   
3188
			}
2767

    
   
3189

   
2768
			req.socket.tcptls_session = tcptls_session;
3190
			req.socket.tcptls_session = tcptls_session;

    
   
3191
			req.socket.ws_session = NULL;
2769
			handle_request_do(&req, &tcptls_session->remote_address);
3192
			handle_request_do(&req, &tcptls_session->remote_address);
2770
		}
3193
		}
2771

    
   
3194

   
2772
		if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
3195
		if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
2773
			enum sip_tcptls_alert alert;
3196
			enum sip_tcptls_alert alert;
2774
			struct tcptls_packet *packet;
3197
			struct tcptls_packet *packet;
2775

    
   
3198

   
2776
			fds[1].revents = 0;
3199
			fds[1].revents = 0;
2777

    
   
3200

   
2778
			if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
3201
			if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
2779
				ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
3202
				ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
2780
				continue;
3203
				continue;
2781
			}
3204
			}
2782

    
   
3205

   
2783
			switch (alert) {
3206
			switch (alert) {
2784
			case TCPTLS_ALERT_STOP:
3207
			case TCPTLS_ALERT_STOP:
2785
				goto cleanup;
3208
				goto cleanup;
2786
			case TCPTLS_ALERT_DATA:
3209
			case TCPTLS_ALERT_DATA:
2787
				ao2_lock(me);
3210
				ao2_lock(me);
2788
				if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
3211
				if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
2789
					ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
3212
					ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
2790
				}
3213
				}
2791
				ao2_unlock(me);
3214
				ao2_unlock(me);
2792

    
   
3215

   
2793
				if (packet) {
3216
				if (packet) {
2794
					if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
3217
					if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
2795
						ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
3218
						ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
2796
					}
3219
					}
2797
					ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
3220
					ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
2798
				}
3221
				}
2799
				break;
3222
				break;
2800
			default:
3223
			default:
2801
				ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
3224
				ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
2802
			}
3225
			}
2803
		}
3226
		}
2804
	}
3227
	}
2805

    
   
3228

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

    
   
3230

   
2808
cleanup:
3231
cleanup:
2809
	if (tcptls_session && !tcptls_session->client && !authenticated) {
3232
	if (tcptls_session && !tcptls_session->client && !authenticated) {
2810
		ast_atomic_fetchadd_int(&unauth_sessions, -1);
3233
		ast_atomic_fetchadd_int(&unauth_sessions, -1);
2811
	}
3234
	}
2812

    
   
3235

   
2813
	if (me) {
3236
	if (me) {
2814
		ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
3237
		ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
2815
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
3238
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2816
	}
3239
	}
2817
	deinit_req(&reqcpy);
3240
	deinit_req(&reqcpy);
2818
	deinit_req(&req);
3241
	deinit_req(&req);
2819

    
   
3242

   
2820
	/* if client, we own the parent session arguments and must decrement ref */
3243
	/* if client, we own the parent session arguments and must decrement ref */
2821
	if (ca) {
3244
	if (ca) {
2822
		ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
3245
		ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
2823
	}
3246
	}
2824

    
   
3247

   
2825
	if (tcptls_session) {
3248
	if (tcptls_session) {
2826
		ao2_lock(tcptls_session);
3249
		ao2_lock(tcptls_session);
2827
		ast_tcptls_close_session_file(tcptls_session);
3250
		ast_tcptls_close_session_file(tcptls_session);
2828
		tcptls_session->parent = NULL;
3251
		tcptls_session->parent = NULL;
2829
		ao2_unlock(tcptls_session);
3252
		ao2_unlock(tcptls_session);
2830

    
   
3253

   
2831
		ao2_ref(tcptls_session, -1);
3254
		ao2_ref(tcptls_session, -1);
2832
		tcptls_session = NULL;
3255
		tcptls_session = NULL;
2833
	}
3256
	}
2834
	return NULL;
3257
	return NULL;
2835
}
3258
}
2836

    
   
3259

   
2837
#ifdef REF_DEBUG
3260
#ifdef REF_DEBUG
2838
#define sip_ref_peer(arg1,arg2) _ref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
3261
#define sip_ref_peer(arg1,arg2) _ref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
2839
#define sip_unref_peer(arg1,arg2) _unref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
3262
#define sip_unref_peer(arg1,arg2) _unref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
2840
static struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
3263
static struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
2841
{
3264
{
2842
	if (peer)
3265
	if (peer)
2843
		__ao2_ref_debug(peer, 1, tag, file, line, func);
3266
		__ao2_ref_debug(peer, 1, tag, file, line, func);
2844
	else
3267
	else
2845
		ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
3268
		ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
2846
	return peer;
3269
	return peer;
2847
}
3270
}
2848

    
   
3271

   
2849
static struct sip_peer *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
3272
static struct sip_peer *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
2850
{
3273
{
2851
	if (peer)
3274
	if (peer)
2852
		__ao2_ref_debug(peer, -1, tag, file, line, func);
3275
		__ao2_ref_debug(peer, -1, tag, file, line, func);
2853
	return NULL;
3276
	return NULL;
2854
}
3277
}
2855
#else
3278
#else
2856
/*!
3279
/*!
2857
 * helper functions to unreference various types of objects.
3280
 * helper functions to unreference various types of objects.
2858
 * By handling them this way, we don't have to declare the
3281
 * By handling them this way, we don't have to declare the
2859
 * destructor on each call, which removes the chance of errors.
3282
 * destructor on each call, which removes the chance of errors.
2860
 */
3283
 */
2861
void *sip_unref_peer(struct sip_peer *peer, char *tag)
3284
void *sip_unref_peer(struct sip_peer *peer, char *tag)
2862
{
3285
{
2863
	ao2_t_ref(peer, -1, tag);
3286
	ao2_t_ref(peer, -1, tag);
2864
	return NULL;
3287
	return NULL;
2865
}
3288
}
2866

    
   
3289

   
2867
struct sip_peer *sip_ref_peer(struct sip_peer *peer, char *tag)
3290
struct sip_peer *sip_ref_peer(struct sip_peer *peer, char *tag)
2868
{
3291
{
2869
	ao2_t_ref(peer, 1, tag);
3292
	ao2_t_ref(peer, 1, tag);
2870
	return peer;
3293
	return peer;
2871
}
3294
}
2872
#endif /* REF_DEBUG */
3295
#endif /* REF_DEBUG */
2873

    
   
3296

   
2874
static void peer_sched_cleanup(struct sip_peer *peer)
3297
static void peer_sched_cleanup(struct sip_peer *peer)
2875
{
3298
{
2876
	if (peer->pokeexpire != -1) {
3299
	if (peer->pokeexpire != -1) {
2877
		AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
3300
		AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
2878
				sip_unref_peer(peer, "removing poke peer ref"));
3301
				sip_unref_peer(peer, "removing poke peer ref"));
2879
	}
3302
	}
2880
	if (peer->expire != -1) {
3303
	if (peer->expire != -1) {
2881
		AST_SCHED_DEL_UNREF(sched, peer->expire,
3304
		AST_SCHED_DEL_UNREF(sched, peer->expire,
2882
				sip_unref_peer(peer, "remove register expire ref"));
3305
				sip_unref_peer(peer, "remove register expire ref"));

    
   
3306
	}

    
   
3307
	if (peer->keepalivesend != -1) {

    
   
3308
		AST_SCHED_DEL_UNREF(sched, peer->keepalivesend,

    
   
3309
				    sip_unref_peer(peer, "remove keepalive peer ref"));
2883
	}
3310
	}
2884
}
3311
}
2885

    
   
3312

   
2886
typedef enum {
3313
typedef enum {
2887
	SIP_PEERS_MARKED,
3314
	SIP_PEERS_MARKED,
2888
	SIP_PEERS_ALL,
3315
	SIP_PEERS_ALL,
2889
} peer_unlink_flag_t;
3316
} peer_unlink_flag_t;
2890

    
   
3317

   
2891
/* this func is used with ao2_callback to unlink/delete all marked or linked
3318
/* this func is used with ao2_callback to unlink/delete all marked or linked
2892
   peers, depending on arg */
3319
   peers, depending on arg */
2893
static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
3320
static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
2894
{
3321
{
2895
	struct sip_peer *peer = peerobj;
3322
	struct sip_peer *peer = peerobj;
2896
	peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
3323
	peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
2897

    
   
3324

   
2898
	if (which == SIP_PEERS_ALL || peer->the_mark) {
3325
	if (which == SIP_PEERS_ALL || peer->the_mark) {
2899
		peer_sched_cleanup(peer);
3326
		peer_sched_cleanup(peer);
2900
		if (peer->dnsmgr) {
3327
		if (peer->dnsmgr) {
2901
			ast_dnsmgr_release(peer->dnsmgr);
3328
			ast_dnsmgr_release(peer->dnsmgr);
2902
			peer->dnsmgr = NULL;
3329
			peer->dnsmgr = NULL;
2903
			sip_unref_peer(peer, "Release peer from dnsmgr");
3330
			sip_unref_peer(peer, "Release peer from dnsmgr");
2904
		}
3331
		}
2905
		return CMP_MATCH;
3332
		return CMP_MATCH;
2906
	}
3333
	}
2907
	return 0;
3334
	return 0;
2908
}
3335
}
2909

    
   
3336

   
2910
static void unlink_peers_from_tables(peer_unlink_flag_t flag)
3337
static void unlink_peers_from_tables(peer_unlink_flag_t flag)
2911
{
3338
{
2912
	ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
3339
	ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
2913
		match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
3340
		match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
2914
	ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
3341
	ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
2915
		match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
3342
		match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
2916
}
3343
}
2917

    
   
3344

   
2918
/* \brief Unlink all marked peers from ao2 containers */
3345
/* \brief Unlink all marked peers from ao2 containers */
2919
static void unlink_marked_peers_from_tables(void)
3346
static void unlink_marked_peers_from_tables(void)
2920
{
3347
{
2921
	unlink_peers_from_tables(SIP_PEERS_MARKED);
3348
	unlink_peers_from_tables(SIP_PEERS_MARKED);
2922
}
3349
}
2923

    
   
3350

   
2924
static void unlink_all_peers_from_tables(void)
3351
static void unlink_all_peers_from_tables(void)
2925
{
3352
{
2926
	unlink_peers_from_tables(SIP_PEERS_ALL);
3353
	unlink_peers_from_tables(SIP_PEERS_ALL);
2927
}
3354
}
2928

    
   
3355

   
2929
/* \brief Unlink single peer from all ao2 containers */
3356
/* \brief Unlink single peer from all ao2 containers */
2930
static void unlink_peer_from_tables(struct sip_peer *peer)
3357
static void unlink_peer_from_tables(struct sip_peer *peer)
2931
{
3358
{
2932
	ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
3359
	ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
2933
	if (!ast_sockaddr_isnull(&peer->addr)) {
3360
	if (!ast_sockaddr_isnull(&peer->addr)) {
2934
		ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
3361
		ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
2935
	}
3362
	}
2936
}
3363
}
2937

    
   
3364

   
2938
/*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
3365
/*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
2939
 *
3366
 *
2940
 * This function sets pvt's outboundproxy pointer to the one referenced
3367
 * This function sets pvt's outboundproxy pointer to the one referenced
2941
 * by the proxy parameter. Because proxy may be a refcounted object, and
3368
 * by the proxy parameter. Because proxy may be a refcounted object, and
2942
 * because pvt's old outboundproxy may also be a refcounted object, we need
3369
 * because pvt's old outboundproxy may also be a refcounted object, we need
2943
 * to maintain the proper refcounts.
3370
 * to maintain the proper refcounts.
2944
 *
3371
 *
2945
 * \param pvt The sip_pvt for which we wish to set the outboundproxy
3372
 * \param pvt The sip_pvt for which we wish to set the outboundproxy
2946
 * \param proxy The sip_proxy which we will point pvt towards.
3373
 * \param proxy The sip_proxy which we will point pvt towards.
2947
 * \return Returns void
3374
 * \return Returns void
2948
 */
3375
 */
2949
static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
3376
static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
2950
{
3377
{
2951
	struct sip_proxy *old_obproxy = pvt->outboundproxy;
3378
	struct sip_proxy *old_obproxy = pvt->outboundproxy;
2952
	/* The sip_cfg.outboundproxy is statically allocated, and so
3379
	/* The sip_cfg.outboundproxy is statically allocated, and so
2953
	 * we don't ever need to adjust refcounts for it
3380
	 * we don't ever need to adjust refcounts for it
2954
	 */
3381
	 */
2955
	if (proxy && proxy != &sip_cfg.outboundproxy) {
3382
	if (proxy && proxy != &sip_cfg.outboundproxy) {
2956
		ao2_ref(proxy, +1);
3383
		ao2_ref(proxy, +1);
2957
	}
3384
	}
2958
	pvt->outboundproxy = proxy;
3385
	pvt->outboundproxy = proxy;
2959
	if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
3386
	if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
2960
		ao2_ref(old_obproxy, -1);
3387
		ao2_ref(old_obproxy, -1);
2961
	}
3388
	}
2962
}
3389
}
2963

    
   
3390

   
2964
/*!
3391
/*!
2965
 * \brief Unlink a dialog from the dialogs container, as well as any other places
3392
 * \brief Unlink a dialog from the dialogs container, as well as any other places
2966
 * that it may be currently stored.
3393
 * that it may be currently stored.
2967
 *
3394
 *
2968
 * \note A reference to the dialog must be held before calling this function, and this
3395
 * \note A reference to the dialog must be held before calling this function, and this
2969
 * function does not release that reference.
3396
 * function does not release that reference.
2970
 */
3397
 */
2971
void dialog_unlink_all(struct sip_pvt *dialog)
3398
void dialog_unlink_all(struct sip_pvt *dialog)
2972
{
3399
{
2973
	struct sip_pkt *cp;
3400
	struct sip_pkt *cp;
2974
	struct ast_channel *owner;
3401
	struct ast_channel *owner;
2975

    
   
3402

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

    
   
3404

   
2978
	ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
3405
	ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
2979
	ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
3406
	ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
2980
	ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
3407
	ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
2981

    
   
3408

   
2982
	/* Unlink us from the owner (channel) if we have one */
3409
	/* Unlink us from the owner (channel) if we have one */
2983
	owner = sip_pvt_lock_full(dialog);
3410
	owner = sip_pvt_lock_full(dialog);
2984
	if (owner) {
3411
	if (owner) {
2985
		ast_debug(1, "Detaching from channel %s\n", ast_channel_name(owner));
3412
		ast_debug(1, "Detaching from channel %s\n", ast_channel_name(owner));
2986
		ast_channel_tech_pvt_set(owner, dialog_unref(ast_channel_tech_pvt(owner), "resetting channel dialog ptr in unlink_all"));
3413
		ast_channel_tech_pvt_set(owner, dialog_unref(ast_channel_tech_pvt(owner), "resetting channel dialog ptr in unlink_all"));
2987
		ast_channel_unlock(owner);
3414
		ast_channel_unlock(owner);
2988
		ast_channel_unref(owner);
3415
		ast_channel_unref(owner);
2989
		dialog->owner = NULL;
3416
		dialog->owner = NULL;
2990
	}
3417
	}
2991
	sip_pvt_unlock(dialog);
3418
	sip_pvt_unlock(dialog);
2992

    
   
3419

   
2993
	if (dialog->registry) {
3420
	if (dialog->registry) {
2994
		if (dialog->registry->call == dialog) {
3421
		if (dialog->registry->call == dialog) {
2995
			dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
3422
			dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
2996
		}
3423
		}
2997
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
3424
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2998
	}
3425
	}
2999
	if (dialog->stateid != -1) {
3426
	if (dialog->stateid != -1) {
3000
		ast_extension_state_del(dialog->stateid, cb_extensionstate);
3427
		ast_extension_state_del(dialog->stateid, cb_extensionstate);
3001
		dialog->stateid = -1;
3428
		dialog->stateid = -1;
3002
	}
3429
	}
3003
	/* Remove link from peer to subscription of MWI */
3430
	/* Remove link from peer to subscription of MWI */
3004
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
3431
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
3005
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
3432
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
3006
	}
3433
	}
3007
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
3434
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
3008
		dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
3435
		dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
3009
	}
3436
	}
3010

    
   
3437

   
3011
	/* remove all current packets in this dialog */
3438
	/* remove all current packets in this dialog */
3012
	while((cp = dialog->packets)) {
3439
	while((cp = dialog->packets)) {
3013
		dialog->packets = dialog->packets->next;
3440
		dialog->packets = dialog->packets->next;
3014
		AST_SCHED_DEL(sched, cp->retransid);
3441
		AST_SCHED_DEL(sched, cp->retransid);
3015
		dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
3442
		dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
3016
		if (cp->data) {
3443
		if (cp->data) {
3017
			ast_free(cp->data);
3444
			ast_free(cp->data);
3018
		}
3445
		}
3019
		ast_free(cp);
3446
		ast_free(cp);
3020
	}
3447
	}
3021

    
   
3448

   
3022
	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"));
3449
	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"));
3023

    
   
3450

   
3024
	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"));
3451
	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"));
3025
	
3452
	
3026
	if (dialog->autokillid > -1) {
3453
	if (dialog->autokillid > -1) {
3027
		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"));
3454
		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"));
3028
	}
3455
	}
3029

    
   
3456

   
3030
	if (dialog->request_queue_sched_id > -1) {
3457
	if (dialog->request_queue_sched_id > -1) {
3031
		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"));
3458
		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"));
3032
	}
3459
	}
3033

    
   
3460

   
3034
	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"));
3461
	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"));
3035

    
   
3462

   
3036
	if (dialog->t38id > -1) {
3463
	if (dialog->t38id > -1) {
3037
		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"));
3464
		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"));
3038
	}
3465
	}
3039

    
   
3466

   
3040
	if (dialog->stimer) {
3467
	if (dialog->stimer) {
3041
		stop_session_timer(dialog);
3468
		stop_session_timer(dialog);
3042
	}
3469
	}
3043

    
   
3470

   
3044
	dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
3471
	dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
3045
}
3472
}
3046

    
   
3473

   
3047
void *registry_unref(struct sip_registry *reg, char *tag)
3474
void *registry_unref(struct sip_registry *reg, char *tag)
3048
{
3475
{
3049
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
3476
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
3050
	ASTOBJ_UNREF(reg, sip_registry_destroy);
3477
	ASTOBJ_UNREF(reg, sip_registry_destroy);
3051
	return NULL;
3478
	return NULL;
3052
}
3479
}
3053

    
   
3480

   
3054
/*! \brief Add object reference to SIP registry */
3481
/*! \brief Add object reference to SIP registry */
3055
static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
3482
static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
3056
{
3483
{
3057
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
3484
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
3058
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
3485
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
3059
}
3486
}
3060

    
   
3487

   
3061
/*! \brief Interface structure with callbacks used to connect to UDPTL module*/
3488
/*! \brief Interface structure with callbacks used to connect to UDPTL module*/
3062
static struct ast_udptl_protocol sip_udptl = {
3489
static struct ast_udptl_protocol sip_udptl = {
3063
	type: "SIP",
3490
	.type = "SIP",
3064
	get_udptl_info: sip_get_udptl_peer,
3491
	.get_udptl_info = sip_get_udptl_peer,
3065
	set_udptl_peer: sip_set_udptl_peer,
3492
	.set_udptl_peer = sip_set_udptl_peer,
3066
};
3493
};
3067

    
   
3494

   
3068
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3495
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3069
	__attribute__((format(printf, 2, 3)));
3496
	__attribute__((format(printf, 2, 3)));
3070

    
   
3497

   
3071

    
   
3498

   
3072
/*! \brief Convert transfer status to string */
3499
/*! \brief Convert transfer status to string */
3073
static const char *referstatus2str(enum referstatus rstatus)
3500
static const char *referstatus2str(enum referstatus rstatus)
3074
{
3501
{
3075
	return map_x_s(referstatusstrings, rstatus, "");
3502
	return map_x_s(referstatusstrings, rstatus, "");
3076
}
3503
}
3077

    
   
3504

   
3078
static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
3505
static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
3079
{
3506
{
3080
	if (pvt->final_destruction_scheduled) {
3507
	if (pvt->final_destruction_scheduled) {
3081
		return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
3508
		return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
3082
	}
3509
	}
3083
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
3510
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
3084
	if (!pvt->needdestroy) {
3511
	if (!pvt->needdestroy) {
3085
		pvt->needdestroy = 1;
3512
		pvt->needdestroy = 1;
3086
		ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
3513
		ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
3087
	}
3514
	}
3088
}
3515
}
3089

    
   
3516

   
3090
/*! \brief Initialize the initital request packet in the pvt structure.
3517
/*! \brief Initialize the initital request packet in the pvt structure.
3091
	This packet is used for creating replies and future requests in
3518
	This packet is used for creating replies and future requests in
3092
	a dialog */
3519
	a dialog */
3093
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
3520
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
3094
{
3521
{
3095
	if (p->initreq.headers) {
3522
	if (p->initreq.headers) {
3096
		ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
3523
		ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
3097
	} else {
3524
	} else {
3098
		ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
3525
		ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
3099
	}
3526
	}
3100
	/* Use this as the basis */
3527
	/* Use this as the basis */
3101
	copy_request(&p->initreq, req);
3528
	copy_request(&p->initreq, req);
3102
	parse_request(&p->initreq);
3529
	parse_request(&p->initreq);
3103
	if (req->debug) {
3530
	if (req->debug) {
3104
		ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
3531
		ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
3105
	}
3532
	}
3106
}
3533
}
3107

    
   
3534

   
3108
/*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
3535
/*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
3109
static void sip_alreadygone(struct sip_pvt *dialog)
3536
static void sip_alreadygone(struct sip_pvt *dialog)
3110
{
3537
{
3111
	ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
3538
	ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
3112
	dialog->alreadygone = 1;
3539
	dialog->alreadygone = 1;
3113
}
3540
}
3114

    
   
3541

   
3115
/*! Resolve DNS srv name or host name in a sip_proxy structure */
3542
/*! Resolve DNS srv name or host name in a sip_proxy structure */
3116
static int proxy_update(struct sip_proxy *proxy)
3543
static int proxy_update(struct sip_proxy *proxy)
3117
{
3544
{
3118
	/* if it's actually an IP address and not a name,
3545
	/* if it's actually an IP address and not a name,
3119
           there's no need for a managed lookup */
3546
           there's no need for a managed lookup */
3120
	if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
3547
	if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
3121
		/* Ok, not an IP address, then let's check if it's a domain or host */
3548
		/* Ok, not an IP address, then let's check if it's a domain or host */
3122
		/* XXX Todo - if we have proxy port, don't do SRV */
3549
		/* XXX Todo - if we have proxy port, don't do SRV */
3123
		proxy->ip.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
3550
		proxy->ip.ss.ss_family = get_address_family_filter(SIP_TRANSPORT_UDP); /* Filter address family */
3124
		if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
3551
		if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
3125
				ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
3552
				ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
3126
				return FALSE;
3553
				return FALSE;
3127
		}
3554
		}
3128

    
   
3555

   
3129
	}
3556
	}
3130

    
   
3557

   
3131
	ast_sockaddr_set_port(&proxy->ip, proxy->port);
3558
	ast_sockaddr_set_port(&proxy->ip, proxy->port);
3132

    
   
3559

   
3133
	proxy->last_dnsupdate = time(NULL);
3560
	proxy->last_dnsupdate = time(NULL);
3134
	return TRUE;
3561
	return TRUE;

    
   
3562
}

    
   
3563

   

    
   
3564
/*! \brief Parse proxy string and return an ao2_alloc'd proxy. If dest is

    
   
3565
 *         non-NULL, no allocation is performed and dest is used instead.

    
   
3566
 *         On error NULL is returned. */

    
   
3567
static struct sip_proxy *proxy_from_config(const char *proxy, int sipconf_lineno, struct sip_proxy *dest)

    
   
3568
{

    
   
3569
	char *mutable_proxy, *sep, *name;

    
   
3570
	int allocated = 0;

    
   
3571

   

    
   
3572
	if (!dest) {

    
   
3573
		dest = ao2_alloc(sizeof(struct sip_proxy), NULL);

    
   
3574
		if (!dest) {

    
   
3575
			ast_log(LOG_WARNING, "Unable to allocate config storage for proxy\n");

    
   
3576
			return NULL;

    
   
3577
		}

    
   
3578
		allocated = 1;

    
   
3579
	}

    
   
3580

   

    
   
3581
	/* Format is: [transport://]name[:port][,force] */

    
   
3582
	mutable_proxy = ast_skip_blanks(ast_strdupa(proxy));

    
   
3583
	sep = strchr(mutable_proxy, ',');

    
   
3584
	if (sep) {

    
   
3585
		*sep++ = '\0';

    
   
3586
		dest->force = !strncasecmp(ast_skip_blanks(sep), "force", 5);

    
   
3587
	} else {

    
   
3588
		dest->force = FALSE;

    
   
3589
	}

    
   
3590

   

    
   
3591
	sip_parse_host(mutable_proxy, sipconf_lineno, &name, &dest->port, &dest->transport);

    
   
3592

   

    
   
3593
	/* Check that there is a name at all */

    
   
3594
	if (ast_strlen_zero(name)) {

    
   
3595
		if (allocated) {

    
   
3596
			ao2_ref(dest, -1);

    
   
3597
		} else {

    
   
3598
			dest->name[0] = '\0';

    
   
3599
		}

    
   
3600
		return NULL;

    
   
3601
	}

    
   
3602
	ast_copy_string(dest->name, name, sizeof(dest->name));

    
   
3603

   

    
   
3604
	/* Resolve host immediately */

    
   
3605
	proxy_update(dest);

    
   
3606

   

    
   
3607
	return dest;
3135
}
3608
}
3136

    
   
3609

   
3137
/*! \brief converts ascii port to int representation. If no
3610
/*! \brief converts ascii port to int representation. If no
3138
 *  pt buffer is provided or the pt has errors when being converted
3611
 *  pt buffer is provided or the pt has errors when being converted
3139
 *  to an int value, the port provided as the standard is used.
3612
 *  to an int value, the port provided as the standard is used.
3140
 */
3613
 */
3141
unsigned int port_str2int(const char *pt, unsigned int standard)
3614
unsigned int port_str2int(const char *pt, unsigned int standard)
3142
{
3615
{
3143
	int port = standard;
3616
	int port = standard;
3144
	if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
3617
	if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
3145
		port = standard;
3618
		port = standard;
3146
	}
3619
	}
3147

    
   
3620

   
3148
	return port;
3621
	return port;
3149
}
3622
}
3150

    
   
3623

   
3151
/*! \brief Get default outbound proxy or global proxy */
3624
/*! \brief Get default outbound proxy or global proxy */
3152
static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
3625
static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
3153
{
3626
{

    
   
3627
	if (dialog && dialog->options && dialog->options->outboundproxy) {

    
   
3628
		if (sipdebug) {

    
   
3629
			ast_debug(1, "OBPROXY: Applying dialplan set OBproxy to this call\n");

    
   
3630
		}

    
   
3631
		append_history(dialog, "OBproxy", "Using dialplan obproxy %s", dialog->options->outboundproxy->name);

    
   
3632
		return dialog->options->outboundproxy;

    
   
3633
	}
3154
	if (peer && peer->outboundproxy) {
3634
	if (peer && peer->outboundproxy) {
3155
		if (sipdebug) {
3635
		if (sipdebug) {
3156
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
3636
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
3157
		}
3637
		}
3158
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
3638
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
3159
		return peer->outboundproxy;
3639
		return peer->outboundproxy;
3160
	}
3640
	}
3161
	if (sip_cfg.outboundproxy.name[0]) {
3641
	if (sip_cfg.outboundproxy.name[0]) {
3162
		if (sipdebug) {
3642
		if (sipdebug) {
3163
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
3643
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
3164
		}
3644
		}
3165
		append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
3645
		append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
3166
		return &sip_cfg.outboundproxy;
3646
		return &sip_cfg.outboundproxy;
3167
	}
3647
	}
3168
	if (sipdebug) {
3648
	if (sipdebug) {
3169
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
3649
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
3170
	}
3650
	}
3171
	return NULL;
3651
	return NULL;
3172
}
3652
}
3173

    
   
3653

   
3174
/*! \brief returns true if 'name' (with optional trailing whitespace)
3654
/*! \brief returns true if 'name' (with optional trailing whitespace)
3175
 * matches the sip method 'id'.
3655
 * matches the sip method 'id'.
3176
 * Strictly speaking, SIP methods are case SENSITIVE, but we do
3656
 * Strictly speaking, SIP methods are case SENSITIVE, but we do
3177
 * a case-insensitive comparison to be more tolerant.
3657
 * a case-insensitive comparison to be more tolerant.
3178
 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
3658
 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
3179
 */
3659
 */
3180
static int method_match(enum sipmethod id, const char *name)
3660
static int method_match(enum sipmethod id, const char *name)
3181
{
3661
{
3182
	int len = strlen(sip_methods[id].text);
3662
	int len = strlen(sip_methods[id].text);
3183
	int l_name = name ? strlen(name) : 0;
3663
	int l_name = name ? strlen(name) : 0;
3184
	/* true if the string is long enough, and ends with whitespace, and matches */
3664
	/* true if the string is long enough, and ends with whitespace, and matches */
3185
	return (l_name >= len && name[len] < 33 &&
3665
	return (l_name >= len && name && name[len] < 33 &&
3186
		!strncasecmp(sip_methods[id].text, name, len));
3666
		!strncasecmp(sip_methods[id].text, name, len));
3187
}
3667
}
3188

    
   
3668

   
3189
/*! \brief  find_sip_method: Find SIP method from header */
3669
/*! \brief  find_sip_method: Find SIP method from header */
3190
static int find_sip_method(const char *msg)
3670
static int find_sip_method(const char *msg)
3191
{
3671
{
3192
	int i, res = 0;
3672
	int i, res = 0;
3193
	
3673
	
3194
	if (ast_strlen_zero(msg)) {
3674
	if (ast_strlen_zero(msg)) {
3195
		return 0;
3675
		return 0;
3196
	}
3676
	}
3197
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
3677
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
3198
		if (method_match(i, msg)) {
3678
		if (method_match(i, msg)) {
3199
			res = sip_methods[i].id;
3679
			res = sip_methods[i].id;
3200
		}
3680
		}
3201
	}
3681
	}
3202
	return res;
3682
	return res;
3203
}
3683
}
3204

    
   
3684

   
3205
/*! \brief See if we pass debug IP filter */
3685
/*! \brief See if we pass debug IP filter */
3206
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
3686
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
3207
{
3687
{
3208
	/* Can't debug if sipdebug is not enabled */
3688
	/* Can't debug if sipdebug is not enabled */
3209
	if (!sipdebug) {
3689
	if (!sipdebug) {
3210
		return 0;
3690
		return 0;
3211
	}
3691
	}
3212

    
   
3692

   
3213
	/* A null debug_addr means we'll debug any address */
3693
	/* A null debug_addr means we'll debug any address */
3214
	if (ast_sockaddr_isnull(&debugaddr)) {
3694
	if (ast_sockaddr_isnull(&debugaddr)) {
3215
		return 1;
3695
		return 1;
3216
	}
3696
	}
3217

    
   
3697

   
3218
	/* If no port was specified for a debug address, just compare the
3698
	/* If no port was specified for a debug address, just compare the
3219
	 * addresses, otherwise compare the address and port
3699
	 * addresses, otherwise compare the address and port
3220
	 */
3700
	 */
3221
	if (ast_sockaddr_port(&debugaddr)) {
3701
	if (ast_sockaddr_port(&debugaddr)) {
3222
		return !ast_sockaddr_cmp(&debugaddr, addr);
3702
		return !ast_sockaddr_cmp(&debugaddr, addr);
3223
	} else {
3703
	} else {
3224
		return !ast_sockaddr_cmp_addr(&debugaddr, addr);
3704
		return !ast_sockaddr_cmp_addr(&debugaddr, addr);
3225
	}
3705
	}
3226
}
3706
}
3227

    
   
3707

   
3228
/*! \brief The real destination address for a write */
3708
/*! \brief The real destination address for a write */
3229
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
3709
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
3230
{
3710
{
3231
	if (p->outboundproxy) {
3711
	if (p->outboundproxy) {
3232
		return &p->outboundproxy->ip;
3712
		return &p->outboundproxy->ip;
3233
	}
3713
	}
3234

    
   
3714

   
3235
	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;
3715
	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;
3236
}
3716
}
3237

    
   
3717

   
3238
/*! \brief Display SIP nat mode */
3718
/*! \brief Display SIP nat mode */
3239
static const char *sip_nat_mode(const struct sip_pvt *p)
3719
static const char *sip_nat_mode(const struct sip_pvt *p)
3240
{
3720
{
3241
	return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
3721
	return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
3242
}
3722
}
3243

    
   
3723

   
3244
/*! \brief Test PVT for debugging output */
3724
/*! \brief Test PVT for debugging output */
3245
static inline int sip_debug_test_pvt(struct sip_pvt *p)
3725
static inline int sip_debug_test_pvt(struct sip_pvt *p)
3246
{
3726
{
3247
	if (!sipdebug) {
3727
	if (!sipdebug) {
3248
		return 0;
3728
		return 0;
3249
	}
3729
	}
3250
	return sip_debug_test_addr(sip_real_dst(p));
3730
	return sip_debug_test_addr(sip_real_dst(p));
3251
}
3731
}
3252

    
   
3732

   
3253
/*! \brief Return int representing a bit field of transport types found in const char *transport */
3733
/*! \brief Return int representing a bit field of transport types found in const char *transport */
3254
static int get_transport_str2enum(const char *transport)
3734
static int get_transport_str2enum(const char *transport)
3255
{</